Repository navigation
Expand file tree
/
Copy pathtauri.ts
More file actions
701 lines (681 loc) · 26.5 KB
/
Copy pathtauri.ts
File metadata and controls
701 lines (681 loc) · 26.5 KB
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
import type { Channel, InvokeArgs } from "@tauri-apps/api/core";
import { emit } from "@tauri-apps/api/event";
import { mockIPC, mockWindows } from "@tauri-apps/api/mocks";
import {
MENU_EVENT,
SCORE_EXTENSIONS,
type AppInfo,
type CommandError,
type MenuAction,
type MenuState,
type MixerSettings,
type MonitorParams,
type Shortcut,
type CloudStem,
type CloudStemFile,
type StemSong,
type StemTempo,
type StemModelId,
type StemModelStatus,
type UmxStatus,
} from "@/lib/tauri";
/** Same shape the Rust `app_info` command returns (see src-tauri/tests/ipc.rs). */
export const APP_INFO: AppInfo = {
name: "Smart Beat",
version: "0.1.0",
tauriVersion: "2.12.0",
os: "macos",
arch: "aarch64",
};
/** Same shape the Rust `menu_shortcuts` command returns on macOS. */
export const SHORTCUTS: Shortcut[] = [
{ action: "open", menu: "File", label: "Open", keys: ["⌘", "O"], spoken: "Command+O" },
{
action: "quit",
menu: "File",
label: "Quit Smart Beat",
keys: ["⌘", "Q"],
spoken: "Command+Q",
},
{
action: "toggle-theme",
menu: "View",
label: "Toggle Dark Mode",
keys: ["⇧", "⌘", "L"],
spoken: "Shift+Command+L",
},
{
action: "shortcuts",
menu: "Help",
label: "Keyboard Shortcuts",
keys: ["⌘", "/"],
spoken: "Command+Slash",
},
];
/** A separated song, as `stems_list` returns it. */
export const STEM_SONG: StemSong = {
id: "0123456789abcdef",
name: "Neon Nights",
durationSeconds: 215,
sampleRate: 44_100,
engine: "fast",
strongDrums: false,
stems: (["drums", "bass", "vocals", "panned", "other"] as const).map((kind) => ({
kind,
bytes: 38_000_000,
})),
mono: false,
skipped: [],
pannedShare: 0.3,
bytes: 190_000_000,
createdAtMs: 1_790_000_000_000,
pinned: false,
lastOpened: null,
savedPath: null,
hasOriginal: true,
};
/** What `stems_detect_tempo` returns unless a test sets `backend.stemTempo`. */
export const STEM_TEMPO: StemTempo = {
bpm: 120,
confidence: 0.9,
firstBeatSec: 0.5,
alternatives: [60, 240],
steady: true,
sections: [],
};
/** The neural model before anything is downloaded. */
export const UMX_STATUS: UmxStatus = {
downloaded: false,
termsAccepted: false,
termsVersion: 1,
downloadBytes: 142_551_184,
licence:
"The code is MIT. The weights are listed as MIT, and were trained on MUSDB18-HQ, whose terms allow academic and educational use.",
};
/** A model of the `stem_model_*` commands before anything is downloaded. */
export const stemModelStatus = (
model: StemModelId,
override: Partial<StemModelStatus> = {},
): StemModelStatus => ({
model,
downloaded: false,
termsAccepted: false,
termsVersion: 1,
// The sizes the app pins (src-tauri/src/stems/models.rs); every model is hosted.
downloadBytes: {
scnet: 52_271_228,
"scnet-xl": 216_163_649,
htdemucs: 176_589_623,
"htdemucs-6s": 116_246_052,
}[model],
licence: `The terms of ${model}: the weights have no stated licence.`,
licenceSummary: "Weights without a stated licence.",
available: true,
...override,
});
const freshStemModels = (): Record<StemModelId, StemModelStatus> => ({
scnet: stemModelStatus("scnet"),
"scnet-xl": stemModelStatus("scnet-xl"),
htdemucs: stemModelStatus("htdemucs"),
"htdemucs-6s": stemModelStatus("htdemucs-6s"),
});
type CommandHandler = (args?: InvokeArgs) => unknown;
type MockMonitor = { params: MonitorParams; device: string | null; channel: number | null };
export interface IpcCall {
cmd: string;
args?: InvokeArgs;
/** The invoke options' headers of a raw-body call (`cloud_create` names its provider there). */
headers?: Record<string, string>;
}
/**
* State behind the mocked Rust commands: files on "disk", saved mixes, and
* what the Open dialog returns. Reset by {@link mockTauri}.
*/
export const backend = {
pluginsEnabled: false,
monitor: null as { params: MonitorParams; device: string | null; channel: number | null } | null,
files: new Map<string, Uint8Array>(),
mixes: new Map<string, MixerSettings>(),
/** Path the Open dialog picks, or `null` for Cancel. */
dialogResult: null as string | null,
/** The linked cloud folder `get_cloud_folder` returns (none by default). */
cloudFolder: null as string | null,
/** The `.sbstems` files `list_cloud_stems` returns (newest first). */
cloudStems: [] as CloudStem[],
/** The `.sbstems` files `cloud_list_stems` returns for each connected account (newest first). */
driveStems: {} as Record<string, CloudStemFile[]>,
/** The tabs `cloud_list` returns for each connected account (newest first). */
driveTabs: {} as Record<string, CloudStemFile[]>,
/** What `cloud_accounts` returns (none connected by default). */
cloudAccounts: [] as {
provider: string;
label: string;
/** Defaults to true (a build with credentials). */
configured?: boolean;
account: string | null;
/** The link levels the service makes (view only when left out). */
shareLevels?: string[];
}[],
/** The last menu state the UI sent. */
menuState: null as MenuState | null,
/** Recently opened songs, most recent first (see `src-tauri/src/recent.rs`). */
recent: [] as string[],
/** Songs the system asked to open that the page has not collected (`src-tauri/src/open_file.rs`). */
pendingOpen: [] as string[],
/** Path the Save dialog picks, or `null` for Cancel. */
saveResult: null as string | null,
/** Files written by `write_score_file`, by path. */
written: new Map<string, Uint8Array>(),
/** Headers of the last `write_score_file` (the destination, and the expected hash). */
lastWriteHeaders: undefined as Record<string, string> | undefined,
/** Settings stored inside saved `.gp` files, by path. */
projectSettings: new Map<string, MixerSettings>(),
/** Usage counter settings (see `src-tauri/src/telemetry.rs`); builds without an endpoint have none. */
usage: { enabled: true, available: false, noticeSeen: true },
/** Crash report settings (opt-in, off by default); `available` means the core has a DSN. */
crashReports: { enabled: false, available: false },
/** The separated songs `stems_list` returns (newest first). */
stemSongs: [] as StemSong[],
/** `.sbstems` paths the system opened before the page was listening (the Rust queue). */
pendingStemBundles: [] as string[],
/** What `stems_detect_tempo` returns. */
stemTempo: { ...STEM_TEMPO } as StemTempo,
/** What `umx_model_status` returns. */
umx: { ...UMX_STATUS } as UmxStatus,
/** The song `stems_open_bundle` returns. */
bundleSong: { ...STEM_SONG, id: "bbbbbbbbbbbbbbbb", name: "Opened Song" } as StemSong,
/** What `stem_model_status` returns, by model. */
stemModels: freshStemModels(),
/** The update the updater plugin finds, or `null` when this is the latest version. */
update: null as { version: string; body?: string } | null,
/** Makes `check` or the download fail with this message. */
updateError: null as { during: "check" | "install"; message: string } | null,
/** Size of the fake download, in bytes (sent as three equal chunks). */
updateBytes: 3000,
};
const MAX_RECENT = 10;
let lastOptions: { headers?: Record<string, string> } | undefined;
const fail = (kind: CommandError["kind"], message: string): never => {
throw { kind, message } satisfies CommandError;
};
/** Mirrors `read_score_file` in src-tauri/src/score_file.rs (minus the signature check). */
function readScoreFile(args?: InvokeArgs): ArrayBuffer {
const { path } = args as { path: string };
const extension = path.split(".").pop()?.toLowerCase() ?? "";
if (!(SCORE_EXTENSIONS as readonly string[]).includes(extension)) {
fail("unsupported-type", `“${path}” is not a Guitar Pro file.`);
}
const bytes = backend.files.get(path) ?? fail("not-found", `“${path}” could not be found.`);
return bytes.slice().buffer;
}
/**
* Installs Tauri IPC mocks that behave like the Rust core. Individual commands
* can be overridden (e.g. to simulate failures). Returns the recorded calls.
*/
export function mockTauri(overrides: Record<string, CommandHandler> = {}): IpcCall[] {
const calls: IpcCall[] = [];
backend.pluginsEnabled = false;
backend.monitor = null;
backend.files.clear();
backend.mixes.clear();
backend.dialogResult = null;
backend.cloudAccounts = [];
backend.cloudFolder = null;
backend.cloudStems = [];
backend.menuState = null;
backend.recent = [];
backend.pendingOpen = [];
backend.saveResult = null;
backend.written.clear();
backend.projectSettings.clear();
backend.usage = { enabled: true, available: false, noticeSeen: true };
backend.crashReports = { enabled: false, available: false };
backend.stemSongs = [];
backend.bundleSong = { ...STEM_SONG, id: "bbbbbbbbbbbbbbbb", name: "Opened Song" };
backend.pendingStemBundles = [];
backend.stemTempo = { ...STEM_TEMPO };
backend.umx = { ...UMX_STATUS };
backend.stemModels = freshStemModels();
backend.update = null;
backend.updateError = null;
backend.updateBytes = 3000;
mockWindows("main");
mockIPC(
(cmd, args) => {
calls.push({ cmd, args, headers: lastOptions?.headers });
const override = overrides[cmd];
if (override) return override(args);
switch (cmd) {
case "app_info":
return APP_INFO;
case "menu_shortcuts":
return SHORTCUTS;
case "read_score_file":
return readScoreFile(args);
case "load_mixer_settings":
return backend.mixes.get((args as { fileKey: string }).fileKey) ?? null;
case "save_mixer_settings": {
const { fileKey, settings } = args as { fileKey: string; settings: MixerSettings };
backend.mixes.set(fileKey, settings);
return null;
}
case "take_pending_open_files":
return backend.pendingOpen.splice(0);
case "load_recent_files":
return backend.recent;
case "add_recent_file": {
const { path } = args as { path: string };
backend.recent = [path, ...backend.recent.filter((p) => p !== path)].slice(0, MAX_RECENT);
return backend.recent;
}
case "remove_recent_file": {
const { path } = args as { path: string };
backend.recent = backend.recent.filter((p) => p !== path);
return backend.recent;
}
case "clear_recent_files":
backend.recent = [];
return backend.recent;
// `export_m4a` encodes the WAV it is sent as AAC; the mock keeps the WAV.
case "export_m4a":
case "write_score_file": {
// Raw body (bytes) plus the URI-encoded destination in a header.
const path = decodeURIComponent(lastOptions?.headers?.path ?? "");
backend.lastWriteHeaders = lastOptions?.headers;
backend.written.set(path, new Uint8Array(args as ArrayBuffer | Uint8Array));
return null;
}
case "export_pdf":
return null;
// Practice together (#158): no other player in unit tests.
case "practice_host":
return {
code: "ABCD-EFGH-JKMN-PQRS-TVWX",
link: "smartbeat://join/ABCD-EFGH-JKMN-PQRS-TVWX",
address: "192.168.1.5:50123",
};
case "practice_join":
case "practice_kick":
case "practice_leave":
case "practice_signal_join":
case "practice_signal_send":
case "practice_signal_kick":
case "practice_signal_leave":
return null;
case "practice_send":
return true;
case "practice_signal_available":
return false;
case "practice_signal_create":
return "ABCD-EFGH";
case "track_event":
return null;
// No folder linked and none detected; no cloud accounts or pending uploads (#187).
case "get_cloud_folder":
return backend.cloudFolder;
case "list_cloud_stems":
return backend.cloudStems;
// Mirrors the Rust command: a path in the linked folder, "not-found" without one.
case "stems_cloud_save_path": {
if (!backend.cloudFolder) return fail("not-found", "No cloud folder is linked.");
return `${backend.cloudFolder}/${(args as { name: string }).name}.sbstems`;
}
// An estimate: the original adds 25 MB to the stems.
case "stems_estimate_bundle":
return {
bytes: (args as { includeOriginal: boolean }).includeOriginal
? 80 * 1024 * 1024
: 55 * 1024 * 1024,
};
case "cloud_accounts":
return backend.cloudAccounts.map((a) => ({ configured: true, ...a }));
case "cloud_list":
return backend.driveTabs[(args as { provider: string }).provider] ?? [];
case "cloud_list_stems":
return backend.driveStems[(args as { provider: string }).provider] ?? [];
// Saving to an account: the file is named after the song, as the Rust command does.
case "stems_cloud_save": {
const { id, provider, includeOriginal } = (
args as {
request: { id: string; provider: string; includeOriginal: boolean };
}
).request;
const name = backend.stemSongs.find((song) => song.id === id)?.name ?? STEM_SONG.name;
return {
item: `${provider}:1`,
name: `${name}.sbstems`,
provider,
bytes: 24_000_000,
originalIncluded: includeOriginal,
};
}
case "stems_cloud_open": {
const { item } = (args as { request: { item: string } }).request;
const opened = { ...backend.bundleSong, savedPath: item };
backend.stemSongs = [opened, ...backend.stemSongs.filter((s) => s.id !== opened.id)];
return opened;
}
// A share link is made by the service: the mock gives one that names what was asked.
case "cloud_share": {
const { item, level } = args as { item: string; level: string };
return `https://share.example.com/${encodeURIComponent(item)}?as=${level}`;
}
case "detect_cloud_folders":
case "cloud_pending":
case "cloud_flush":
return [];
case "cloud_disconnect":
return null;
// Stem separation (#186). Tests override `stems_separate`, `stems_read` and
// `stems_render_mix` to play a part.
case "stems_list":
return backend.stemSongs;
case "stems_delete":
backend.stemSongs = backend.stemSongs.filter(
(song) => song.id !== (args as { id: string }).id,
);
return null;
case "take_pending_stem_bundles":
return backend.pendingStemBundles.splice(0);
case "stems_touch":
case "stems_pin": {
const { id, pinned } = args as { id: string; pinned?: boolean };
backend.stemSongs = backend.stemSongs.map((song) =>
song.id !== id
? song
: cmd === "stems_pin"
? { ...song, pinned: pinned ?? false }
: { ...song, lastOpened: Date.now() },
);
return null;
}
// Saving writes the file at `dest` and marks the song as saved there; opening a file
// returns the song (tests set `backend.bundleSong`) as saved at that path.
case "stems_save_bundle": {
const { id, dest, includeOriginal } = (
args as { request: { id: string; dest: string; includeOriginal: boolean } }
).request;
backend.stemSongs = backend.stemSongs.map((song) =>
song.id === id ? { ...song, savedPath: dest } : song,
);
return { path: dest, bytes: 24_000_000, originalIncluded: includeOriginal };
}
// Exporting writes nothing in tests: the answer says where the files would go.
case "stems_export_mixed": {
const { dest } = (args as { request: { dest: string } }).request;
return { paths: [dest], folder: null, clipped: false };
}
case "stems_export_batch": {
const { dir, kinds, format } = (
args as { request: { dir: string; kinds: string[]; format: string } }
).request;
const folder = `${dir}/Neon Nights stems`;
return {
paths: kinds.map((kind) => `${folder}/${kind} - Neon Nights.${format}`),
folder,
clipped: false,
};
}
// A stem loaded as a lane's audio file: one source per stem, 3:35 long.
case "stems_audio_source": {
const { id, kind } = args as { id: string; kind: string };
return {
id: `${id}${kind}`.padEnd(64, "0"),
name: `${kind} - Neon Nights.wav`,
ext: "wav",
durationMs: 215_000,
sampleRate: 44_100,
channels: 2,
peaks: [0.5, 0.25],
peaksPerSecond: 20,
};
}
case "stems_open_bundle": {
const opened = { ...backend.bundleSong, savedPath: (args as { path: string }).path };
backend.stemSongs = [opened, ...backend.stemSongs.filter((s) => s.id !== opened.id)];
return opened;
}
case "stems_detect_tempo":
return backend.stemTempo;
case "stems_cache_info":
return {
bytes: backend.stemSongs.reduce((sum, song) => sum + song.bytes, 0),
count: backend.stemSongs.length,
limitBytes: 2 * 1024 ** 3,
};
case "stems_cancel":
case "umx_model_cancel":
case "umx_model_accept_terms":
if (cmd === "umx_model_accept_terms") backend.umx.termsAccepted = true;
return null;
case "umx_model_status":
return backend.umx;
case "stem_model_cancel":
return null;
case "stem_model_accept_terms":
backend.stemModels[(args as { model: StemModelId }).model].termsAccepted = true;
return null;
case "stem_model_status":
return backend.stemModels[(args as { model: StemModelId }).model];
case "stem_model_remove":
backend.stemModels[(args as { model: StemModelId }).model].downloaded = false;
return null;
case "umx_model_remove":
backend.umx.downloaded = false;
return null;
case "get_usage_settings":
return backend.usage;
case "set_usage_settings": {
const { enabled, noticeSeen } = args as {
enabled: boolean | null;
noticeSeen: boolean | null;
};
backend.usage = {
...backend.usage,
enabled: enabled ?? backend.usage.enabled,
noticeSeen: noticeSeen ?? backend.usage.noticeSeen,
};
return backend.usage;
}
case "get_crash_report_settings":
return backend.crashReports;
case "set_crash_report_settings":
backend.crashReports = {
...backend.crashReports,
enabled: (args as { enabled: boolean }).enabled,
};
return backend.crashReports;
case "plugin:dialog|save":
return backend.saveResult;
case "update_menu_state":
backend.menuState = (args as { state: MenuState }).state;
return null;
case "plugin:dialog|open":
return backend.dialogResult;
case "plugin:window|set_theme":
case "plugin:window|set_title":
return null;
// The updater plugin: `check` finds `backend.update`, and the install reports progress
// through the channel the plugin passes in, like the Rust side.
case "plugin:updater|check": {
if (backend.updateError?.during === "check") throw backend.updateError.message;
if (!backend.update) return null;
return {
rid: 7,
currentVersion: APP_INFO.version,
version: backend.update.version,
date: "2026-11-01T00:00:00Z",
body: backend.update.body,
rawJson: {},
};
}
case "plugin:updater|download_and_install": {
const { onEvent } = args as { onEvent: Channel<unknown> };
const send = (message: unknown) => onEvent.onmessage(message);
send({ event: "Started", data: { contentLength: backend.updateBytes } });
for (let i = 0; i < 3; i++) {
send({ event: "Progress", data: { chunkLength: backend.updateBytes / 3 } });
}
if (backend.updateError?.during === "install") throw backend.updateError.message;
send({ event: "Finished" });
return null;
}
case "plugin:opener|open_url":
case "plugin:opener|reveal_item_in_dir":
case "plugin:process|restart":
case "plugin:resources|close":
return null;
// The sound library starts empty; the native engine is never started here.
case "library_list":
return [];
case "plugins_enabled":
return backend.pluginsEnabled;
case "plugins_set_enabled":
backend.pluginsEnabled = (args as { enabled: boolean }).enabled;
return null;
case "plugins_scan":
return { plugins: [], skipped: [] };
case "audio_plugin_info":
return [];
// No drum kits imported (#40); tests override these to have some.
case "kits_list":
return [];
case "kits_remove":
case "audio_set_track_kit":
return null;
case "audio_input_channels":
return 2;
// Opening a file for the lanes only decodes it: no engine is involved (a 4 s file whose
// content id follows its name).
case "audio_load_source": {
const { location } = args as {
location:
| { type: "file"; path: string }
| { type: "embedded"; entry: string }
| { type: "pool"; id: string; name: string };
};
// A file that was only loaded (a stem put on a lane) is described under its own id.
const path =
location.type === "file"
? location.path
: location.type === "embedded"
? location.entry
: location.name;
const name = path.split(/[\\/]/).pop() ?? path;
let hash = 7;
for (const c of name) hash = (hash * 31 + c.charCodeAt(0)) >>> 0;
return {
id:
location.type === "pool" ? location.id : hash.toString(16).padStart(8, "0").repeat(8),
name,
ext: name.split(".").pop()?.toLowerCase() ?? "wav",
durationMs: 4000,
sampleRate: 44100,
channels: 2,
peaks: [0.4, 0.8, 0.5, 0.9],
peaksPerSecond: 1,
};
}
// One quiet second, 1 s into every file; tests override it for other shapes.
case "audio_silent_regions":
return [{ startMs: 1000, endMs: 2000 }];
case "audio_set_monitor":
backend.monitor = (args as { monitor: MockMonitor | null }).monitor;
return backend.monitor
? {
open: backend.monitor.params.enabled,
device: backend.monitor.device ?? "System default",
channels: 2,
sampleRate: 48000,
latencyMs: 5,
clockFrames: 0,
error: null,
}
: null;
case "audio_set_monitor_chain":
return [];
case "audio_set_chain":
return [];
case "audio_set_sounds":
return (args as { sounds: unknown[] }).sounds.map(() => []);
case "read_project_settings":
return backend.projectSettings.get((args as { path: string }).path) ?? null;
case "write_project_settings": {
const { path, settings } = args as { path: string; settings: MixerSettings };
backend.projectSettings.set(path, settings);
return null;
}
case "cloud_embed_project":
// The song itself, unchanged: the real command stores the mix inside it.
return new Uint8Array(args as Uint8Array).buffer;
case "cloud_project_settings":
return null;
case "audio_set_automation":
case "audio_set_track_eq":
case "audio_set_drum_mix":
case "audio_set_backing":
case "audio_clear_backing":
return null;
case "audio_load_backing":
return {
name: "take.mp3",
durationMs: 2000,
sampleRate: 44100,
channels: 2,
peaks: Array.from({ length: 200 }, (_, i) => (i % 10) / 10),
peaksPerSecond: 100,
};
case "audio_transport":
case "audio_set_mix":
case "audio_stop":
return null;
default:
throw new Error(`Unmocked Tauri command: ${cmd}`);
}
},
{ shouldMockEvents: true },
);
// mockIPC hides the invoke options; a write's destination header is needed.
const internals = window.__TAURI_INTERNALS__ as unknown as {
invoke: (cmd: string, args?: unknown, options?: unknown) => Promise<unknown>;
};
const inner = internals.invoke;
internals.invoke = (cmd, args, options) => {
lastOptions = options as typeof lastOptions;
return inner(cmd, args, options);
};
return calls;
}
/** Simulates the Rust core forwarding a native menu click. */
export async function emitMenuAction(action: MenuAction) {
await emit(MENU_EVENT, action);
}
/** Simulates File › Open Recent: the core sends the chosen path. */
export async function emitOpenRecent(path: string) {
await emit("open-recent", path);
}
/** Simulates the system handing songs to the app: they are queued, then the page is told. */
export async function emitOpenExternalFiles(paths: string[]) {
backend.pendingOpen.push(...paths);
await emit("open-external-file");
}
/** Simulates the system opening a `.sbstems` file: the core sends its path. */
export async function emitStemBundleOpened(path: string) {
await emit("stems-bundle-opened", { path });
}
/** Simulates the OS dragging files onto the window (Tauri webview events). */
export async function emitFileDrag(
event:
| { type: "enter"; paths: string[] }
| { type: "over"; position: { x: number; y: number } }
| { type: "leave" }
| { type: "drop"; paths: string[]; position?: { x: number; y: number } },
) {
const position = (event.type !== "enter" && event.type !== "leave" && event.position) || {
x: 10,
y: 10,
};
if (event.type === "leave") await emit("tauri://drag-leave", null);
else if (event.type === "over") await emit("tauri://drag-over", { position });
else await emit(`tauri://drag-${event.type}`, { paths: event.paths, position });
}