@morshoto/framekit 0.1.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.
- package/README.md +67 -0
- package/bin/framekit.mjs +26 -0
- package/dist-package/adapters/final-cut/typescript/src/analyzers.js +116 -0
- package/dist-package/adapters/final-cut/typescript/src/assets.js +112 -0
- package/dist-package/adapters/final-cut/typescript/src/connection.js +379 -0
- package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +282 -0
- package/dist-package/adapters/final-cut/typescript/src/export.js +382 -0
- package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +503 -0
- package/dist-package/adapters/final-cut/typescript/src/index.js +11 -0
- package/dist-package/adapters/final-cut/typescript/src/live.js +415 -0
- package/dist-package/adapters/final-cut/typescript/src/native-operation.js +18 -0
- package/dist-package/adapters/final-cut/typescript/src/native.js +3134 -0
- package/dist-package/adapters/final-cut/typescript/src/publisher.js +102 -0
- package/dist-package/adapters/final-cut/typescript/src/session.js +171 -0
- package/dist-package/apps/cli/src/main.js +130 -0
- package/dist-package/apps/mcp-server/src/main.js +146 -0
- package/dist-package/apps/mcp-server/src/server.js +617 -0
- package/dist-package/packages/runtime/src/capabilities.js +24 -0
- package/dist-package/packages/runtime/src/context/context-engine.js +142 -0
- package/dist-package/packages/runtime/src/diff/diff.js +145 -0
- package/dist-package/packages/runtime/src/domain/types.js +1 -0
- package/dist-package/packages/runtime/src/editing/intent.js +83 -0
- package/dist-package/packages/runtime/src/index.js +8 -0
- package/dist-package/packages/runtime/src/runtime.js +890 -0
- package/dist-package/packages/runtime/src/snapshot-digest.js +24 -0
- package/dist-package/packages/runtime/src/speech/filler-removal.js +87 -0
- package/dist-package/packages/runtime/src/verification/verification.js +113 -0
- package/dist-package/packages/testkit/src/fixture-analyzers.js +39 -0
- package/dist-package/packages/testkit/src/in-memory-editor.js +520 -0
- package/dist-package/packages/testkit/src/index.js +2 -0
- package/package.json +64 -0
|
@@ -0,0 +1,3134 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { execFile as execFileCallback } from "node:child_process";
|
|
3
|
+
import { access, constants, stat } from "node:fs/promises";
|
|
4
|
+
import { basename, dirname, extname, resolve } from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
const execFile = promisify(execFileCallback);
|
|
7
|
+
class NativeFinalCutPreflightError extends Error {
|
|
8
|
+
code;
|
|
9
|
+
context;
|
|
10
|
+
constructor(code, message, context) {
|
|
11
|
+
super(`${code}: ${message}`);
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.context = context;
|
|
14
|
+
this.name = "NativeFinalCutPreflightError";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export class FinalCutNativeAutomationAdapter {
|
|
18
|
+
enabled;
|
|
19
|
+
executor;
|
|
20
|
+
canDriveNativeMouse;
|
|
21
|
+
liveState;
|
|
22
|
+
nativeOperationLease;
|
|
23
|
+
suspendLiveConnection;
|
|
24
|
+
resumeLiveConnection;
|
|
25
|
+
now;
|
|
26
|
+
sleep;
|
|
27
|
+
nativePreflightTimeoutMs;
|
|
28
|
+
mediaImportTimeoutMs;
|
|
29
|
+
mediaImportDiscoveryTimeoutMs;
|
|
30
|
+
mediaImportPollMs;
|
|
31
|
+
nativeUiDepth = 0;
|
|
32
|
+
operations = new Map();
|
|
33
|
+
latestOperationId;
|
|
34
|
+
mediaHandles = new Map();
|
|
35
|
+
selectedMediaHandle;
|
|
36
|
+
stableMediaHandles = new Map();
|
|
37
|
+
occurrenceHandles = new Map();
|
|
38
|
+
ambiguousMediaHandles = new Set();
|
|
39
|
+
bladePreviews = new Map();
|
|
40
|
+
rangePreviews = new Map();
|
|
41
|
+
mediaInsertionPreviews = new Map();
|
|
42
|
+
titlePreviews = new Map();
|
|
43
|
+
constructor(options = {}) {
|
|
44
|
+
this.enabled = options.enabled ?? process.env.FRAMEKIT_FINAL_CUT_NATIVE_WRITES === "1";
|
|
45
|
+
this.executor = options.executor ?? runAppleScript;
|
|
46
|
+
this.canDriveNativeMouse = options.executor === undefined;
|
|
47
|
+
this.liveState = options.liveState;
|
|
48
|
+
this.nativeOperationLease = options.nativeOperationLease;
|
|
49
|
+
this.suspendLiveConnection = options.suspendLiveConnection;
|
|
50
|
+
this.resumeLiveConnection = options.resumeLiveConnection;
|
|
51
|
+
this.now = options.now ?? Date.now;
|
|
52
|
+
this.sleep = options.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
|
|
53
|
+
this.nativePreflightTimeoutMs = options.nativePreflightTimeoutMs ?? 10_000;
|
|
54
|
+
this.mediaImportTimeoutMs = options.mediaImportTimeoutMs ?? 30_000;
|
|
55
|
+
this.mediaImportDiscoveryTimeoutMs = options.mediaImportDiscoveryTimeoutMs ?? 30_000;
|
|
56
|
+
this.mediaImportPollMs = options.mediaImportPollMs ?? 100;
|
|
57
|
+
}
|
|
58
|
+
capabilities() {
|
|
59
|
+
return {
|
|
60
|
+
selectionEdit: this.enabled,
|
|
61
|
+
undo: this.enabled,
|
|
62
|
+
mediaLibrarySearch: this.enabled,
|
|
63
|
+
mediaImport: this.enabled,
|
|
64
|
+
mediaSelection: this.enabled,
|
|
65
|
+
mediaAppendSelected: this.enabled,
|
|
66
|
+
timelineOccurrenceLocate: this.enabled,
|
|
67
|
+
bladeAtPlayhead: this.enabled,
|
|
68
|
+
deleteRange: this.enabled,
|
|
69
|
+
trimToDuration: this.enabled,
|
|
70
|
+
mediaAppend: this.enabled,
|
|
71
|
+
mediaInsert: this.enabled,
|
|
72
|
+
titlePlacement: this.enabled,
|
|
73
|
+
timelineFocus: this.enabled,
|
|
74
|
+
requiresAccessibility: true,
|
|
75
|
+
requiresFinalCutFrontmost: true,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
async inspect() {
|
|
79
|
+
return this.withNativeUi(() => this.inspectNative());
|
|
80
|
+
}
|
|
81
|
+
async focusTimeline() {
|
|
82
|
+
return this.withNativeUi(() => this.focusTimelineNative());
|
|
83
|
+
}
|
|
84
|
+
async inspectNative() {
|
|
85
|
+
if (!this.enabled) {
|
|
86
|
+
return unavailableContext("CAPABILITY_UNAVAILABLE", "Final Cut native writes are disabled; set FRAMEKIT_FINAL_CUT_NATIVE_WRITES=1");
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
return await this.attachLiveState(await this.ensureTimelineReady());
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
return unavailableContext(nativeErrorCode(error), nativeErrorMessage(error), preflightContext(error));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
async focusTimelineNative() {
|
|
96
|
+
if (!this.enabled) {
|
|
97
|
+
return unavailableContext("CAPABILITY_UNAVAILABLE", "Final Cut native writes are disabled; set FRAMEKIT_FINAL_CUT_NATIVE_WRITES=1");
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
return await this.attachLiveState(await this.ensureTimelineReady());
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
return unavailableContext(nativeErrorCode(error), nativeErrorMessage(error), preflightContext(error));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
async inspectRawNative(deadline) {
|
|
107
|
+
try {
|
|
108
|
+
return await this.attachLiveState(parseContext(await this.executeNativeScript(inspectScript(), deadline)));
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
return unavailableContext(nativeErrorCode(error), nativeErrorMessage(error));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async attachLiveState(context) {
|
|
115
|
+
if (!this.liveState)
|
|
116
|
+
return context;
|
|
117
|
+
try {
|
|
118
|
+
const live = await this.liveState();
|
|
119
|
+
context.project = live.project?.name;
|
|
120
|
+
context.sequence = live.sequence?.name;
|
|
121
|
+
context.playheadTime = live.playheadTime
|
|
122
|
+
? `${live.playheadTime.value}/${live.playheadTime.timescale}`
|
|
123
|
+
: undefined;
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
// Native UI inspection remains useful when the optional live socket is down.
|
|
127
|
+
}
|
|
128
|
+
return context;
|
|
129
|
+
}
|
|
130
|
+
async readLiveState() {
|
|
131
|
+
if (!this.liveState)
|
|
132
|
+
return undefined;
|
|
133
|
+
try {
|
|
134
|
+
return await this.liveState();
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
rememberOperation(operationId, record) {
|
|
141
|
+
this.operations.set(operationId, record);
|
|
142
|
+
this.latestOperationId = operationId;
|
|
143
|
+
}
|
|
144
|
+
async edit(operation) {
|
|
145
|
+
return this.withNativeUi(() => this.editNative(operation));
|
|
146
|
+
}
|
|
147
|
+
async editNative(operation) {
|
|
148
|
+
this.assertEnabled();
|
|
149
|
+
const before = await this.requireTimelineTarget(operation);
|
|
150
|
+
const beforeLive = await this.readLiveState();
|
|
151
|
+
const operationId = `native-op-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
152
|
+
const command = commandName(operation);
|
|
153
|
+
const requiresPlayhead = operation.type === "trim-selected-clip-to-playhead" || operation.type === "add-marker-at-playhead";
|
|
154
|
+
try {
|
|
155
|
+
await this.executeNativeCommand(editScript(operation), (recovered) => this.assertRetryContext(before, recovered, requiresPlayhead));
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
|
|
159
|
+
}
|
|
160
|
+
const after = await this.requireTimelineContext();
|
|
161
|
+
const afterLive = await this.readLiveState();
|
|
162
|
+
const verification = verifyNativeEdit(operation, before, after);
|
|
163
|
+
if (!verification.verified) {
|
|
164
|
+
throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}`);
|
|
165
|
+
}
|
|
166
|
+
this.rememberOperation(operationId, { kind: "selection", before, after, beforeLive, afterLive, undoCommand: after.undoCommand });
|
|
167
|
+
return { operationId, operation, command, before, after, verification, undoAvailable: after.undoAvailable, ...(after.undoCommand ? { undoCommand: after.undoCommand } : {}) };
|
|
168
|
+
}
|
|
169
|
+
async undo(operationId) {
|
|
170
|
+
return this.withNativeUi(() => this.undoNative(operationId));
|
|
171
|
+
}
|
|
172
|
+
async undoNative(operationId) {
|
|
173
|
+
this.assertEnabled();
|
|
174
|
+
const operation = this.operations.get(operationId);
|
|
175
|
+
if (!operation)
|
|
176
|
+
throw new Error(`FINAL_CUT_NATIVE_UNDO_UNAVAILABLE: unknown operation ${operationId}`);
|
|
177
|
+
if (this.latestOperationId !== operationId)
|
|
178
|
+
throw new Error("FINAL_CUT_NATIVE_UNDO_STALE: operation is no longer the latest native edit");
|
|
179
|
+
const before = await this.requireTimelineContext();
|
|
180
|
+
const currentLive = await this.readLiveState();
|
|
181
|
+
if (operation.afterLive && currentLive && operation.afterLive.revision.id !== currentLive.revision.id) {
|
|
182
|
+
throw new Error("FINAL_CUT_NATIVE_UNDO_STALE: Final Cut timeline changed after the native edit");
|
|
183
|
+
}
|
|
184
|
+
if (!before.undoAvailable || !before.undoCommand)
|
|
185
|
+
throw new Error("FINAL_CUT_NATIVE_UNDO_UNAVAILABLE: Final Cut has no available Undo command");
|
|
186
|
+
if (!operation.undoCommand || before.undoCommand !== operation.undoCommand) {
|
|
187
|
+
throw new Error("FINAL_CUT_NATIVE_UNDO_COMMAND_CHANGED: Final Cut's current Undo command does not match the native edit");
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
await this.executeNativeCommand(undoScript(operation.undoCommand), (recovered) => {
|
|
191
|
+
this.assertRetryContext(before, recovered);
|
|
192
|
+
if (!recovered.undoAvailable || recovered.undoCommand !== operation.undoCommand) {
|
|
193
|
+
throw new Error("FINAL_CUT_NATIVE_UNDO_COMMAND_CHANGED: Final Cut's current Undo command does not match the native edit");
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
|
|
199
|
+
}
|
|
200
|
+
const after = await this.requireTimelineContext();
|
|
201
|
+
const afterLive = await this.waitForUndo(operation);
|
|
202
|
+
const verification = verifyNativeUndo(operation, after, afterLive);
|
|
203
|
+
if (!verification.verified)
|
|
204
|
+
throw new Error(`FINAL_CUT_NATIVE_UNDO_VERIFICATION_FAILED: ${verification.detail}`);
|
|
205
|
+
this.operations.delete(operationId);
|
|
206
|
+
this.latestOperationId = undefined;
|
|
207
|
+
return { operationId, undone: true, context: after, verification };
|
|
208
|
+
}
|
|
209
|
+
async importMedia(sourcePath) {
|
|
210
|
+
return this.withNativeUi(() => this.importMediaNative(sourcePath));
|
|
211
|
+
}
|
|
212
|
+
async importMediaNative(sourcePath) {
|
|
213
|
+
this.assertEnabled();
|
|
214
|
+
const normalizedPath = resolve(sourcePath.trim());
|
|
215
|
+
const name = basename(normalizedPath);
|
|
216
|
+
if (!name)
|
|
217
|
+
throw new Error("INVALID_OPERATION: local media path cannot be empty");
|
|
218
|
+
try {
|
|
219
|
+
const details = await stat(normalizedPath);
|
|
220
|
+
await access(normalizedPath, constants.R_OK);
|
|
221
|
+
if (!details.isFile())
|
|
222
|
+
throw new Error("path is not a file");
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
throw new Error(`FINAL_CUT_NATIVE_MEDIA_PATH_UNAVAILABLE: ${normalizedPath} is not a readable local media file (${String(error)})`);
|
|
226
|
+
}
|
|
227
|
+
const beforeDiscoveryDeadline = this.now() + this.mediaImportDiscoveryTimeoutMs;
|
|
228
|
+
await this.ensureBrowserReady(beforeDiscoveryDeadline, "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT");
|
|
229
|
+
const beforeMatches = await this.searchMediaNative(name, beforeDiscoveryDeadline, "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT");
|
|
230
|
+
const beforeIdentities = new Set(beforeMatches
|
|
231
|
+
.filter((match) => match.name.toLowerCase() === name.toLowerCase())
|
|
232
|
+
.map((match) => browserMediaIdentity(match))
|
|
233
|
+
.filter((identity) => Boolean(identity)));
|
|
234
|
+
const hasIndistinguishablePreExistingMatch = beforeMatches.some((match) => match.name.toLowerCase() === name.toLowerCase() && !browserMediaIdentity(match));
|
|
235
|
+
if (hasIndistinguishablePreExistingMatch) {
|
|
236
|
+
throw new Error(`FINAL_CUT_NATIVE_MEDIA_IMPORT_IDENTITY_UNAVAILABLE: Final Cut did not expose an immutable Browser source identity for pre-existing ${name}`);
|
|
237
|
+
}
|
|
238
|
+
try {
|
|
239
|
+
await this.executeNativeScript(importMediaScript(dirname(normalizedPath), name), this.now() + this.mediaImportTimeoutMs);
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
|
|
243
|
+
}
|
|
244
|
+
const discoveryDeadline = this.now() + this.mediaImportDiscoveryTimeoutMs;
|
|
245
|
+
let sawPreExistingMatch = false;
|
|
246
|
+
while (this.now() <= discoveryDeadline) {
|
|
247
|
+
let matches;
|
|
248
|
+
try {
|
|
249
|
+
matches = await this.searchMediaNative(name, discoveryDeadline, "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT");
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
if (nativeErrorCode(error) === "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT") {
|
|
253
|
+
throw new Error(`FINAL_CUT_NATIVE_MEDIA_ID_UNAVAILABLE: Final Cut imported ${name}, but Browser Accessibility did not expose a stable media identity before the ${this.mediaImportDiscoveryTimeoutMs}ms discovery deadline`);
|
|
254
|
+
}
|
|
255
|
+
throw error;
|
|
256
|
+
}
|
|
257
|
+
const exactMatches = matches.filter((match) => match.name.toLowerCase() === name.toLowerCase());
|
|
258
|
+
if (exactMatches.some((match) => !browserMediaIdentity(match))) {
|
|
259
|
+
throw new Error(`FINAL_CUT_NATIVE_MEDIA_IMPORT_IDENTITY_UNAVAILABLE: Final Cut did not expose an immutable Browser source identity for ${name}`);
|
|
260
|
+
}
|
|
261
|
+
const newMatches = exactMatches.filter((match) => {
|
|
262
|
+
const identity = browserMediaIdentity(match);
|
|
263
|
+
if (!identity)
|
|
264
|
+
return false;
|
|
265
|
+
if (beforeIdentities.has(identity)) {
|
|
266
|
+
sawPreExistingMatch = true;
|
|
267
|
+
return false;
|
|
268
|
+
}
|
|
269
|
+
return true;
|
|
270
|
+
});
|
|
271
|
+
if (newMatches.length > 1) {
|
|
272
|
+
throw new Error(`FINAL_CUT_NATIVE_MEDIA_IMPORT_AMBIGUOUS: Final Cut exposed multiple newly appearing Browser results for ${name}`);
|
|
273
|
+
}
|
|
274
|
+
const match = newMatches[0];
|
|
275
|
+
if (match) {
|
|
276
|
+
const identity = browserMediaIdentity(match);
|
|
277
|
+
if (!identity)
|
|
278
|
+
throw new Error(`FINAL_CUT_NATIVE_MEDIA_IMPORT_IDENTITY_UNAVAILABLE: Final Cut did not expose an immutable Browser source identity for ${name}`);
|
|
279
|
+
const mediaHandle = this.stableMediaHandle(identity);
|
|
280
|
+
const stableMatch = { ...match, handle: mediaHandle };
|
|
281
|
+
this.stableMediaHandles.set(identity, mediaHandle);
|
|
282
|
+
this.mediaHandles.set(mediaHandle, stableMatch);
|
|
283
|
+
return {
|
|
284
|
+
mediaHandle,
|
|
285
|
+
sourcePath: normalizedPath,
|
|
286
|
+
name,
|
|
287
|
+
kind: mediaKind(normalizedPath),
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
if (this.now() >= discoveryDeadline)
|
|
291
|
+
break;
|
|
292
|
+
await this.sleep(Math.min(this.mediaImportPollMs, discoveryDeadline - this.now()));
|
|
293
|
+
}
|
|
294
|
+
if (sawPreExistingMatch) {
|
|
295
|
+
throw new Error(`FINAL_CUT_NATIVE_MEDIA_IMPORT_PRE_EXISTING: Final Cut exposed only pre-existing Browser results for ${name}`);
|
|
296
|
+
}
|
|
297
|
+
const diagnostics = await this.readBrowserMediaDiagnostics(name);
|
|
298
|
+
throw new Error(`FINAL_CUT_NATIVE_MEDIA_ID_UNAVAILABLE: Final Cut imported ${name}, but Browser Accessibility did not expose a stable media identity${diagnostics ? `; diagnostics=${diagnostics}` : ""}`);
|
|
299
|
+
}
|
|
300
|
+
async searchMedia(query) {
|
|
301
|
+
return this.withNativeUi(() => this.searchMediaNative(query));
|
|
302
|
+
}
|
|
303
|
+
async searchMediaNative(query, deadline, timeoutCode = "FINAL_CUT_NATIVE_MEDIA_IMPORT_TIMEOUT") {
|
|
304
|
+
this.assertEnabled();
|
|
305
|
+
if (!query.trim())
|
|
306
|
+
throw new Error("INVALID_OPERATION: media search query cannot be empty");
|
|
307
|
+
const context = await this.ensureBrowserReady(deadline, timeoutCode);
|
|
308
|
+
if (!context.frontmost)
|
|
309
|
+
throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's Browser must be frontmost");
|
|
310
|
+
try {
|
|
311
|
+
const rawMatches = parseMediaMatches(await this.executeNativeScript(searchMediaScript(query), deadline, timeoutCode));
|
|
312
|
+
const normalizedQuery = query.toLocaleLowerCase();
|
|
313
|
+
if (rawMatches.some((match) => !browserMediaIdentity(match) && match.name.toLocaleLowerCase().includes(normalizedQuery))) {
|
|
314
|
+
const diagnostics = await this.readBrowserMediaDiagnostics(query);
|
|
315
|
+
throw new Error(`FINAL_CUT_NATIVE_MEDIA_ID_UNAVAILABLE: matching Browser media has no AXIdentifier${diagnostics ? `; diagnostics=${diagnostics}` : ""}`);
|
|
316
|
+
}
|
|
317
|
+
const seenSourceIdentities = new Set();
|
|
318
|
+
const matches = rawMatches
|
|
319
|
+
.filter((match) => {
|
|
320
|
+
const identity = browserMediaIdentity(match);
|
|
321
|
+
if (!identity || seenSourceIdentities.has(identity))
|
|
322
|
+
return false;
|
|
323
|
+
seenSourceIdentities.add(identity);
|
|
324
|
+
return true;
|
|
325
|
+
})
|
|
326
|
+
.map((match) => {
|
|
327
|
+
const identity = browserMediaIdentity(match);
|
|
328
|
+
if (!identity)
|
|
329
|
+
return match;
|
|
330
|
+
const stableHandle = this.stableMediaHandles.get(identity) ?? this.stableMediaHandle(identity);
|
|
331
|
+
this.stableMediaHandles.set(identity, stableHandle);
|
|
332
|
+
return { ...match, handle: stableHandle };
|
|
333
|
+
});
|
|
334
|
+
const stableHandles = new Set(this.stableMediaHandles.values());
|
|
335
|
+
for (const handle of this.mediaHandles.keys()) {
|
|
336
|
+
if (!stableHandles.has(handle))
|
|
337
|
+
this.mediaHandles.delete(handle);
|
|
338
|
+
}
|
|
339
|
+
this.selectedMediaHandle = undefined;
|
|
340
|
+
for (const match of matches)
|
|
341
|
+
this.mediaHandles.set(match.handle, match);
|
|
342
|
+
return matches;
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
if (deadline !== undefined && nativeErrorCode(error) === timeoutCode)
|
|
346
|
+
throw error;
|
|
347
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
async readBrowserMediaDiagnostics(query) {
|
|
351
|
+
try {
|
|
352
|
+
const output = await this.executeNativeScript(browserMediaDiagnosticScript(query), this.now() + 2_000, "FINAL_CUT_NATIVE_MEDIA_DIAGNOSTIC_TIMEOUT");
|
|
353
|
+
return output.trim().slice(0, 8_000);
|
|
354
|
+
}
|
|
355
|
+
catch {
|
|
356
|
+
return "";
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
async previewAppendSelectedMedia() {
|
|
360
|
+
return this.withNativeUi(() => this.previewSelectedMediaInsertionNative());
|
|
361
|
+
}
|
|
362
|
+
async previewSelectedMediaInsertionNative() {
|
|
363
|
+
this.assertEnabled();
|
|
364
|
+
const media = await this.readSelectedMediaNative();
|
|
365
|
+
const mediaHandle = this.stableMediaHandle(media.sourceIdentity);
|
|
366
|
+
const stableMedia = { ...media, handle: mediaHandle };
|
|
367
|
+
this.stableMediaHandles.set(media.sourceIdentity, mediaHandle);
|
|
368
|
+
this.mediaHandles.set(mediaHandle, stableMedia);
|
|
369
|
+
this.selectedMediaHandle = mediaHandle;
|
|
370
|
+
return this.previewMediaInsertionNative("append", mediaHandle, "selected");
|
|
371
|
+
}
|
|
372
|
+
async readSelectedMediaNative() {
|
|
373
|
+
const context = await this.ensureBrowserReady();
|
|
374
|
+
if (!context.frontmost)
|
|
375
|
+
throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's Browser must be frontmost");
|
|
376
|
+
try {
|
|
377
|
+
const matches = parseMediaMatches(await this.executor(selectedBrowserMediaScript()));
|
|
378
|
+
if (matches.length === 0)
|
|
379
|
+
throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_UNAVAILABLE: no selected Browser media was exposed by Accessibility");
|
|
380
|
+
if (matches.length > 1)
|
|
381
|
+
throw new Error("FINAL_CUT_NATIVE_AMBIGUOUS_TARGET: multiple selected Browser media items were exposed");
|
|
382
|
+
const media = matches[0];
|
|
383
|
+
if (!media.sourceIdentity) {
|
|
384
|
+
const diagnostics = await this.readBrowserMediaDiagnostics(media.name);
|
|
385
|
+
throw new Error(`FINAL_CUT_NATIVE_MEDIA_ID_UNAVAILABLE: selected Browser media has no AXIdentifier${diagnostics ? `; diagnostics=${diagnostics}` : ""}`);
|
|
386
|
+
}
|
|
387
|
+
return media;
|
|
388
|
+
}
|
|
389
|
+
catch (error) {
|
|
390
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
async selectMedia(handle) {
|
|
394
|
+
return this.withNativeUi(() => this.selectMediaNative(handle));
|
|
395
|
+
}
|
|
396
|
+
async selectMediaNative(handle) {
|
|
397
|
+
this.assertEnabled();
|
|
398
|
+
const match = this.mediaHandles.get(handle);
|
|
399
|
+
if (!match)
|
|
400
|
+
throw new Error(`FINAL_CUT_NATIVE_MEDIA_HANDLE_STALE: unknown media handle ${handle}`);
|
|
401
|
+
const before = await this.ensureBrowserReady();
|
|
402
|
+
if (!before.frontmost)
|
|
403
|
+
throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's Browser must be frontmost");
|
|
404
|
+
try {
|
|
405
|
+
await this.executor(selectMediaScript(match));
|
|
406
|
+
}
|
|
407
|
+
catch (error) {
|
|
408
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
|
|
409
|
+
}
|
|
410
|
+
const after = await this.requireAvailableContext();
|
|
411
|
+
this.selectedMediaHandle = handle;
|
|
412
|
+
return {
|
|
413
|
+
...after,
|
|
414
|
+
target: { kind: "browser-media", name: match.name, ...(match.role ? { role: match.role } : {}) },
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
async locateOccurrence(mediaHandle) {
|
|
418
|
+
return this.withNativeUi(() => this.locateOccurrenceNative(mediaHandle));
|
|
419
|
+
}
|
|
420
|
+
async targetMedia(query) {
|
|
421
|
+
return this.withNativeUi(() => this.targetMediaNative(query));
|
|
422
|
+
}
|
|
423
|
+
async targetMediaNative(query) {
|
|
424
|
+
this.assertEnabled();
|
|
425
|
+
const matches = await this.searchMediaNative(query);
|
|
426
|
+
if (matches.length === 0)
|
|
427
|
+
throw new Error("FINAL_CUT_NATIVE_MEDIA_NOT_FOUND: no Browser media matched the query");
|
|
428
|
+
if (matches.length > 1)
|
|
429
|
+
throw new Error("FINAL_CUT_NATIVE_AMBIGUOUS_TARGET: media query matched multiple Browser items");
|
|
430
|
+
const media = matches[0];
|
|
431
|
+
await this.selectMediaNative(media.handle);
|
|
432
|
+
const located = await this.locateOccurrenceNative(media.handle, true);
|
|
433
|
+
if (located.status === "none") {
|
|
434
|
+
throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_NOT_FOUND: selected Browser media has no timeline occurrence");
|
|
435
|
+
}
|
|
436
|
+
if (located.status === "ambiguous") {
|
|
437
|
+
throw new Error("FINAL_CUT_NATIVE_AMBIGUOUS_TARGET: media has multiple timeline occurrences");
|
|
438
|
+
}
|
|
439
|
+
if (located.occurrences[0]?.timelineOffset === undefined) {
|
|
440
|
+
throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_POSITION_UNAVAILABLE: unique timeline occurrence has no selectable position");
|
|
441
|
+
}
|
|
442
|
+
const live = await this.readLiveState();
|
|
443
|
+
if (!live?.playheadTime) {
|
|
444
|
+
throw new Error("FINAL_CUT_NATIVE_PLAYHEAD_UNAVAILABLE: deterministic targeting requires live playhead state");
|
|
445
|
+
}
|
|
446
|
+
return {
|
|
447
|
+
query,
|
|
448
|
+
status: "unique",
|
|
449
|
+
media,
|
|
450
|
+
occurrence: located.occurrences[0],
|
|
451
|
+
selected: true,
|
|
452
|
+
playheadTime: `${live.playheadTime.value}/${live.playheadTime.timescale}`,
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
async locateOccurrenceNative(mediaHandle, scanAll = false) {
|
|
456
|
+
this.assertEnabled();
|
|
457
|
+
const match = this.mediaHandles.get(mediaHandle);
|
|
458
|
+
if (!match)
|
|
459
|
+
throw new Error(`FINAL_CUT_NATIVE_MEDIA_HANDLE_STALE: unknown media handle ${mediaHandle}`);
|
|
460
|
+
if (!match.sourceIdentity)
|
|
461
|
+
throw new Error("FINAL_CUT_NATIVE_MEDIA_ID_UNAVAILABLE: Browser result has no shared source-media identifier");
|
|
462
|
+
const context = await this.requireTimelineContext();
|
|
463
|
+
if (!context.frontmost)
|
|
464
|
+
throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
|
|
465
|
+
try {
|
|
466
|
+
const occurrences = parseOccurrences(await this.executor(locateOccurrenceScript(match, scanAll)), mediaHandle);
|
|
467
|
+
if (occurrences.length === 1 && this.canDriveNativeMouse) {
|
|
468
|
+
const timelineOffset = occurrences[0]?.timelineOffset;
|
|
469
|
+
if (timelineOffset === undefined) {
|
|
470
|
+
throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_POSITION_UNAVAILABLE: unique timeline occurrence has no selectable position");
|
|
471
|
+
}
|
|
472
|
+
await selectTimelineOccurrence(this.executor, timelineOffset);
|
|
473
|
+
}
|
|
474
|
+
const live = this.liveState ? await this.liveState().catch(() => undefined) : undefined;
|
|
475
|
+
for (const occurrence of occurrences) {
|
|
476
|
+
occurrence.sequence = live?.sequence?.name;
|
|
477
|
+
occurrence.sequenceId = live?.sequence?.id;
|
|
478
|
+
occurrence.revision = live?.revision.id;
|
|
479
|
+
occurrence.uiContext = context.frontWindow;
|
|
480
|
+
}
|
|
481
|
+
this.occurrenceHandles.clear();
|
|
482
|
+
this.ambiguousMediaHandles.clear();
|
|
483
|
+
for (const occurrence of occurrences)
|
|
484
|
+
this.occurrenceHandles.set(occurrence.handle, occurrence);
|
|
485
|
+
if (occurrences.length !== 1)
|
|
486
|
+
this.ambiguousMediaHandles.add(mediaHandle);
|
|
487
|
+
return {
|
|
488
|
+
status: occurrences.length === 0 ? "none" : occurrences.length === 1 ? "unique" : "ambiguous",
|
|
489
|
+
occurrences,
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
catch (error) {
|
|
493
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
async previewBlade(occurrenceHandle) {
|
|
497
|
+
return this.withNativeUi(() => this.previewBladeNative(occurrenceHandle));
|
|
498
|
+
}
|
|
499
|
+
async previewBladeNative(occurrenceHandle) {
|
|
500
|
+
this.assertEnabled();
|
|
501
|
+
const occurrence = this.occurrenceHandles.get(occurrenceHandle);
|
|
502
|
+
if (!occurrence)
|
|
503
|
+
throw new Error(`FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: unknown occurrence handle ${occurrenceHandle}`);
|
|
504
|
+
if (this.ambiguousMediaHandles.has(occurrence.mediaHandle)) {
|
|
505
|
+
throw new Error("FINAL_CUT_NATIVE_AMBIGUOUS_OCCURRENCE: automatic Blade requires exactly one timeline occurrence");
|
|
506
|
+
}
|
|
507
|
+
const context = await this.requireTimelineContext();
|
|
508
|
+
if (!context.frontmost)
|
|
509
|
+
throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
|
|
510
|
+
if (context.target.kind !== "selected-clip")
|
|
511
|
+
throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: select exactly one timeline occurrence");
|
|
512
|
+
if (context.target.name && context.target.name !== occurrence.name) {
|
|
513
|
+
throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: selected timeline occurrence changed");
|
|
514
|
+
}
|
|
515
|
+
await this.validateOccurrenceBinding(occurrence);
|
|
516
|
+
if (!context.bladeAvailable)
|
|
517
|
+
throw new Error("FINAL_CUT_NATIVE_PLAYHEAD_OUTSIDE_OCCURRENCE: Final Cut has disabled Blade for the current selection/playhead");
|
|
518
|
+
const expiresAtMs = this.now() + 30_000;
|
|
519
|
+
const previewToken = opaqueHandle("blade-preview");
|
|
520
|
+
this.bladePreviews.set(previewToken, { occurrence, expiresAt: expiresAtMs });
|
|
521
|
+
return {
|
|
522
|
+
previewToken,
|
|
523
|
+
occurrence,
|
|
524
|
+
...(context.playheadTime ? { playheadTime: context.playheadTime } : {}),
|
|
525
|
+
command: "Blade at playhead",
|
|
526
|
+
expiresAt: new Date(expiresAtMs).toISOString(),
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
async executeBlade(previewToken) {
|
|
530
|
+
return this.withNativeUi(() => this.executeBladeNative(previewToken));
|
|
531
|
+
}
|
|
532
|
+
async executeBladeNative(previewToken) {
|
|
533
|
+
this.assertEnabled();
|
|
534
|
+
const preview = this.bladePreviews.get(previewToken);
|
|
535
|
+
if (!preview)
|
|
536
|
+
throw new Error(`FINAL_CUT_NATIVE_PREVIEW_STALE: unknown Blade preview ${previewToken}`);
|
|
537
|
+
this.bladePreviews.delete(previewToken);
|
|
538
|
+
if (this.now() > preview.expiresAt)
|
|
539
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: Blade preview has expired");
|
|
540
|
+
const before = await this.requireTimelineContext();
|
|
541
|
+
if (!before.frontmost)
|
|
542
|
+
throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
|
|
543
|
+
if (before.target.kind !== "selected-clip")
|
|
544
|
+
throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: select exactly one timeline occurrence");
|
|
545
|
+
if (before.target.name && before.target.name !== preview.occurrence.name) {
|
|
546
|
+
throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: selected timeline occurrence changed");
|
|
547
|
+
}
|
|
548
|
+
await this.validateOccurrenceBinding(preview.occurrence);
|
|
549
|
+
if (!before.bladeAvailable)
|
|
550
|
+
throw new Error("FINAL_CUT_NATIVE_PLAYHEAD_OUTSIDE_OCCURRENCE: Final Cut has disabled Blade for the current selection/playhead");
|
|
551
|
+
try {
|
|
552
|
+
await this.executeNativeCommand(bladeScript(), async (recovered) => {
|
|
553
|
+
this.assertRetryContext(before, recovered, true);
|
|
554
|
+
await this.validateOccurrenceBinding(preview.occurrence);
|
|
555
|
+
if (!recovered.bladeAvailable)
|
|
556
|
+
throw new Error("FINAL_CUT_NATIVE_PLAYHEAD_OUTSIDE_OCCURRENCE: Final Cut has disabled Blade for the current selection/playhead");
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
catch (error) {
|
|
560
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
|
|
561
|
+
}
|
|
562
|
+
const after = await this.requireTimelineContext();
|
|
563
|
+
if (!after.frontmost)
|
|
564
|
+
throw new Error("FINAL_CUT_NATIVE_VERIFICATION_FAILED: Final Cut changed focus during Blade");
|
|
565
|
+
const resultingSegments = parseOccurrences(await this.executor(locateOccurrenceScript({ handle: preview.occurrence.mediaHandle, name: preview.occurrence.name }, true)), preview.occurrence.mediaHandle);
|
|
566
|
+
if (resultingSegments.length < 2) {
|
|
567
|
+
throw new Error("FINAL_CUT_NATIVE_VERIFICATION_FAILED: Final Cut did not expose two resulting timeline segments after Blade");
|
|
568
|
+
}
|
|
569
|
+
const operationId = opaqueHandle("native-blade");
|
|
570
|
+
const afterLive = await this.readLiveState();
|
|
571
|
+
this.rememberOperation(operationId, { kind: "blade", before, after, beforeLive: undefined, afterLive, undoCommand: after.undoCommand });
|
|
572
|
+
return {
|
|
573
|
+
operationId,
|
|
574
|
+
previewToken,
|
|
575
|
+
occurrence: preview.occurrence,
|
|
576
|
+
resultingSegments,
|
|
577
|
+
before,
|
|
578
|
+
after,
|
|
579
|
+
verification: { verified: true, detail: "Final Cut accepted the Blade command while the target remained frontmost" },
|
|
580
|
+
undoAvailable: after.undoAvailable,
|
|
581
|
+
...(after.undoCommand ? { undoCommand: after.undoCommand } : {}),
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
async previewDeleteRange(range) {
|
|
585
|
+
return this.withNativeUi(() => this.previewRangeNative("delete-range", range));
|
|
586
|
+
}
|
|
587
|
+
async executeDeleteRange(previewToken) {
|
|
588
|
+
return this.withNativeUi(() => this.executeRangeNative(previewToken));
|
|
589
|
+
}
|
|
590
|
+
async previewTrimToDuration(duration) {
|
|
591
|
+
return this.withNativeUi(async () => {
|
|
592
|
+
this.assertEnabled();
|
|
593
|
+
const live = await this.requireLiveState();
|
|
594
|
+
const context = await this.requireTimelineContext();
|
|
595
|
+
if (!context.frontmost)
|
|
596
|
+
throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline window must be frontmost");
|
|
597
|
+
const sequenceStart = live.sequenceTimeRange?.start ?? live.sequence?.startTime;
|
|
598
|
+
const currentDuration = live.sequenceTimeRange?.duration ?? live.sequence?.duration;
|
|
599
|
+
if (!sequenceStart || !currentDuration)
|
|
600
|
+
throw new Error("CAPABILITY_UNAVAILABLE: Final Cut sequence duration is unavailable");
|
|
601
|
+
if (compareRational(duration, zeroRational()) <= 0)
|
|
602
|
+
throw new Error("INVALID_OPERATION: target duration must be positive");
|
|
603
|
+
if (compareRational(duration, currentDuration) >= 0) {
|
|
604
|
+
const token = this.createRangePreview("trim-to-duration", { start: sequenceStart, end: sequenceStart }, currentDuration, currentDuration, live);
|
|
605
|
+
return { ...token, command: "Trim sequence to duration" };
|
|
606
|
+
}
|
|
607
|
+
const range = { start: addRational(sequenceStart, duration), end: addRational(sequenceStart, currentDuration) };
|
|
608
|
+
return this.createRangePreview("trim-to-duration", range, currentDuration, duration, live, duration);
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
async executeTrimToDuration(previewToken) {
|
|
612
|
+
return this.withNativeUi(() => this.executeRangeNative(previewToken, "trim-to-duration"));
|
|
613
|
+
}
|
|
614
|
+
async previewAppendMedia(mediaHandle) {
|
|
615
|
+
return this.withNativeUi(() => this.previewMediaInsertionNative("append", mediaHandle));
|
|
616
|
+
}
|
|
617
|
+
async executeAppendMedia(previewToken) {
|
|
618
|
+
return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "append", "handle"));
|
|
619
|
+
}
|
|
620
|
+
async executeAppendSelectedMedia(previewToken) {
|
|
621
|
+
return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "append", "selected"));
|
|
622
|
+
}
|
|
623
|
+
async previewInsertMedia(mediaHandle) {
|
|
624
|
+
return this.withNativeUi(() => this.previewMediaInsertionNative("insert", mediaHandle));
|
|
625
|
+
}
|
|
626
|
+
async executeInsertMedia(previewToken) {
|
|
627
|
+
return this.withNativeUi(() => this.executeMediaInsertionNative(previewToken, "insert"));
|
|
628
|
+
}
|
|
629
|
+
async previewTitleAdd(request) {
|
|
630
|
+
return this.withNativeUi(() => this.previewTitleAddNative(request));
|
|
631
|
+
}
|
|
632
|
+
async executeTitleAdd(previewToken) {
|
|
633
|
+
return this.withNativeUi(() => this.executeTitleAddNative(previewToken));
|
|
634
|
+
}
|
|
635
|
+
async previewTitleAddNative(request) {
|
|
636
|
+
this.assertEnabled();
|
|
637
|
+
assertNativeTitleAsset(request.asset);
|
|
638
|
+
if (!request.text.trim())
|
|
639
|
+
throw new Error("INVALID_OPERATION: native title text cannot be empty");
|
|
640
|
+
const context = await this.requireTimelineContext();
|
|
641
|
+
if (!context.frontmost)
|
|
642
|
+
throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
|
|
643
|
+
const live = await this.requireLiveState();
|
|
644
|
+
const sequenceStart = live.sequenceTimeRange?.start ?? live.sequence?.startTime;
|
|
645
|
+
const sequenceDuration = live.sequenceTimeRange?.duration ?? live.sequence?.duration;
|
|
646
|
+
const frameDuration = live.sequence?.frameDuration;
|
|
647
|
+
if (!sequenceStart || !sequenceDuration || !frameDuration)
|
|
648
|
+
throw new Error("CAPABILITY_UNAVAILABLE: Final Cut sequence timing is unavailable");
|
|
649
|
+
if (compareRational(frameDuration, zeroRational()) <= 0)
|
|
650
|
+
throw new Error("CAPABILITY_UNAVAILABLE: Final Cut sequence frame duration is invalid");
|
|
651
|
+
if (compareRational(request.duration, zeroRational()) <= 0) {
|
|
652
|
+
throw new Error("INVALID_OPERATION: native title duration must be positive");
|
|
653
|
+
}
|
|
654
|
+
if (compareRational(request.duration, frameDuration) < 0 || !isFrameAligned(request.duration, zeroRational(), frameDuration)) {
|
|
655
|
+
throw new Error("INVALID_OPERATION: native title duration must cover a whole number of sequence frames");
|
|
656
|
+
}
|
|
657
|
+
const start = request.start ?? live.playheadTime;
|
|
658
|
+
if (!start)
|
|
659
|
+
throw new Error("CAPABILITY_UNAVAILABLE: Final Cut playhead is unavailable for native title placement");
|
|
660
|
+
if (!isFrameAligned(start, sequenceStart, frameDuration)) {
|
|
661
|
+
throw new Error("INVALID_OPERATION: native title start must align to the sequence frame duration");
|
|
662
|
+
}
|
|
663
|
+
const sequenceEnd = addRational(sequenceStart, sequenceDuration);
|
|
664
|
+
const end = addRational(start, request.duration);
|
|
665
|
+
if (compareRational(start, sequenceStart) < 0 || compareRational(end, sequenceEnd) > 0) {
|
|
666
|
+
throw new Error("FINAL_CUT_NATIVE_TITLE_RANGE_OUT_OF_BOUNDS: title placement must be inside the active sequence");
|
|
667
|
+
}
|
|
668
|
+
const expiresAt = this.now() + 30_000;
|
|
669
|
+
const previewToken = opaqueHandle("title-preview");
|
|
670
|
+
const target = request.start ? "selected-range" : "playhead";
|
|
671
|
+
this.titlePreviews.set(previewToken, {
|
|
672
|
+
asset: structuredClone(request.asset),
|
|
673
|
+
text: request.text,
|
|
674
|
+
target,
|
|
675
|
+
start: structuredClone(start),
|
|
676
|
+
end: structuredClone(end),
|
|
677
|
+
duration: structuredClone(request.duration),
|
|
678
|
+
sequenceId: live.sequence?.id,
|
|
679
|
+
revision: live.revision.id,
|
|
680
|
+
expiresAt,
|
|
681
|
+
});
|
|
682
|
+
return {
|
|
683
|
+
previewToken,
|
|
684
|
+
asset: publicTitleAsset(request.asset),
|
|
685
|
+
text: request.text,
|
|
686
|
+
target,
|
|
687
|
+
start: structuredClone(start),
|
|
688
|
+
end: structuredClone(end),
|
|
689
|
+
duration: structuredClone(request.duration),
|
|
690
|
+
...(live.sequence?.id ? { sequenceId: live.sequence.id } : {}),
|
|
691
|
+
revision: live.revision.id,
|
|
692
|
+
command: "Add native title",
|
|
693
|
+
expiresAt: new Date(expiresAt).toISOString(),
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
async executeTitleAddNative(previewToken) {
|
|
697
|
+
this.assertEnabled();
|
|
698
|
+
const preview = this.titlePreviews.get(previewToken);
|
|
699
|
+
if (!preview)
|
|
700
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: unknown native title preview");
|
|
701
|
+
this.titlePreviews.delete(previewToken);
|
|
702
|
+
if (this.now() > preview.expiresAt)
|
|
703
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: native title preview has expired");
|
|
704
|
+
const before = await this.requireTimelineContext();
|
|
705
|
+
const beforeLive = await this.requireLiveState();
|
|
706
|
+
this.validateTitleBinding(preview, beforeLive);
|
|
707
|
+
const startTimecode = this.toTimecode(preview.start, beforeLive);
|
|
708
|
+
const endTimecode = this.toTimecode(preview.end, beforeLive);
|
|
709
|
+
try {
|
|
710
|
+
await this.executeNativeSequence(async () => {
|
|
711
|
+
await this.executor(titleAssetSelectionScript(preview.asset.name));
|
|
712
|
+
await this.focusTimelineForMediaInsertion();
|
|
713
|
+
await this.executor(setPlayheadScript(startTimecode));
|
|
714
|
+
await this.waitForPlayhead(preview.start, beforeLive.sequence?.id);
|
|
715
|
+
await this.executor(markRangeStartScript());
|
|
716
|
+
await this.executor(setPlayheadScript(endTimecode));
|
|
717
|
+
await this.waitForPlayhead(preview.end, beforeLive.sequence?.id);
|
|
718
|
+
await this.executor(markRangeEndAndConnectTitleScript());
|
|
719
|
+
await this.executor(titleTextEditScript(preview.text));
|
|
720
|
+
}, async (recovered) => {
|
|
721
|
+
const targetChanged = before.target.kind !== recovered.target.kind
|
|
722
|
+
|| before.target.name !== recovered.target.name
|
|
723
|
+
|| before.target.role !== recovered.target.role;
|
|
724
|
+
if (targetChanged)
|
|
725
|
+
throw new Error("FINAL_CUT_NATIVE_RETRY_TARGET_CHANGED: Final Cut selection changed during focus recovery");
|
|
726
|
+
this.validateTitleBinding(preview, await this.requireLiveState());
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
catch (error) {
|
|
730
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
|
|
731
|
+
}
|
|
732
|
+
const after = await this.requireTimelineContext();
|
|
733
|
+
const afterLive = await this.waitForRevision(beforeLive.revision.id);
|
|
734
|
+
const verification = verifyNativeTitle(preview, beforeLive, after, afterLive);
|
|
735
|
+
const operationId = opaqueHandle("native-title");
|
|
736
|
+
const operation = {
|
|
737
|
+
kind: "title-placement",
|
|
738
|
+
before,
|
|
739
|
+
after,
|
|
740
|
+
beforeLive,
|
|
741
|
+
afterLive,
|
|
742
|
+
undoCommand: after.undoCommand,
|
|
743
|
+
};
|
|
744
|
+
if (!verification.verified) {
|
|
745
|
+
if (afterLive.revision.id !== beforeLive.revision.id && after.undoAvailable && after.undoCommand) {
|
|
746
|
+
this.rememberOperation(operationId, operation);
|
|
747
|
+
try {
|
|
748
|
+
await this.undo(operationId);
|
|
749
|
+
}
|
|
750
|
+
catch (rollbackError) {
|
|
751
|
+
throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}; operationId=${operationId}; native rollback failed: ${String(rollbackError)}`);
|
|
752
|
+
}
|
|
753
|
+
throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}; title placement was rolled back`);
|
|
754
|
+
}
|
|
755
|
+
throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}`);
|
|
756
|
+
}
|
|
757
|
+
this.rememberOperation(operationId, operation);
|
|
758
|
+
return {
|
|
759
|
+
operationId,
|
|
760
|
+
previewToken,
|
|
761
|
+
asset: publicTitleAsset(preview.asset),
|
|
762
|
+
text: preview.text,
|
|
763
|
+
target: preview.target,
|
|
764
|
+
start: structuredClone(preview.start),
|
|
765
|
+
end: structuredClone(preview.end),
|
|
766
|
+
duration: structuredClone(preview.duration),
|
|
767
|
+
before,
|
|
768
|
+
after,
|
|
769
|
+
beforeRevision: beforeLive.revision,
|
|
770
|
+
afterRevision: afterLive.revision,
|
|
771
|
+
verification,
|
|
772
|
+
undoAvailable: after.undoAvailable,
|
|
773
|
+
...(after.undoCommand ? { undoCommand: after.undoCommand } : {}),
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
async previewMediaInsertionNative(operation, mediaHandle, selectionMode = "handle") {
|
|
777
|
+
this.assertEnabled();
|
|
778
|
+
const media = this.mediaHandles.get(mediaHandle);
|
|
779
|
+
if (!media)
|
|
780
|
+
throw new Error(`FINAL_CUT_NATIVE_MEDIA_HANDLE_STALE: unknown media handle ${mediaHandle}`);
|
|
781
|
+
if (this.selectedMediaHandle !== mediaHandle) {
|
|
782
|
+
throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_REQUIRED: select one Browser media result before insertion");
|
|
783
|
+
}
|
|
784
|
+
const context = await this.requireTimelineContext();
|
|
785
|
+
if (!context.frontmost)
|
|
786
|
+
throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
|
|
787
|
+
const live = await this.requireLiveState();
|
|
788
|
+
const sequenceStart = live.sequenceTimeRange?.start ?? live.sequence?.startTime;
|
|
789
|
+
const beforeDuration = live.sequenceTimeRange?.duration ?? live.sequence?.duration;
|
|
790
|
+
if (!sequenceStart || !beforeDuration)
|
|
791
|
+
throw new Error("CAPABILITY_UNAVAILABLE: Final Cut sequence duration is unavailable");
|
|
792
|
+
const insertionTime = operation === "append"
|
|
793
|
+
? addRational(sequenceStart, beforeDuration)
|
|
794
|
+
: live.playheadTime;
|
|
795
|
+
if (!insertionTime)
|
|
796
|
+
throw new Error("CAPABILITY_UNAVAILABLE: Final Cut playhead is unavailable for media insertion");
|
|
797
|
+
const expiresAt = this.now() + 30_000;
|
|
798
|
+
const previewToken = opaqueHandle(`${operation}-media-preview`);
|
|
799
|
+
this.mediaInsertionPreviews.set(previewToken, {
|
|
800
|
+
operation,
|
|
801
|
+
mediaHandle,
|
|
802
|
+
selectionMode,
|
|
803
|
+
beforeDuration,
|
|
804
|
+
insertionTime,
|
|
805
|
+
sequenceId: live.sequence?.id,
|
|
806
|
+
revision: live.revision.id,
|
|
807
|
+
expiresAt,
|
|
808
|
+
});
|
|
809
|
+
return {
|
|
810
|
+
previewToken,
|
|
811
|
+
operation,
|
|
812
|
+
media,
|
|
813
|
+
beforeDuration,
|
|
814
|
+
insertionTime,
|
|
815
|
+
...(live.sequence?.id ? { sequenceId: live.sequence.id } : {}),
|
|
816
|
+
revision: live.revision.id,
|
|
817
|
+
command: operation === "append" ? "Append selected media" : "Insert selected media at playhead",
|
|
818
|
+
expiresAt: new Date(expiresAt).toISOString(),
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
async executeMediaInsertionNative(previewToken, expectedOperation, expectedSelectionMode) {
|
|
822
|
+
this.assertEnabled();
|
|
823
|
+
const preview = this.mediaInsertionPreviews.get(previewToken);
|
|
824
|
+
if (!preview)
|
|
825
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: unknown media insertion preview");
|
|
826
|
+
this.mediaInsertionPreviews.delete(previewToken);
|
|
827
|
+
if (this.now() > preview.expiresAt)
|
|
828
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: media insertion preview has expired");
|
|
829
|
+
if (expectedOperation && preview.operation !== expectedOperation)
|
|
830
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: preview operation does not match execute operation");
|
|
831
|
+
if (expectedSelectionMode && preview.selectionMode !== expectedSelectionMode)
|
|
832
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: preview selection mode does not match execute operation");
|
|
833
|
+
const media = this.mediaHandles.get(preview.mediaHandle);
|
|
834
|
+
if (!media)
|
|
835
|
+
throw new Error(`FINAL_CUT_NATIVE_MEDIA_HANDLE_STALE: unknown media handle ${preview.mediaHandle}`);
|
|
836
|
+
if (preview.selectionMode === "handle" && this.selectedMediaHandle !== preview.mediaHandle) {
|
|
837
|
+
throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_REQUIRED: selected Browser media changed before insertion");
|
|
838
|
+
}
|
|
839
|
+
const before = await this.requireTimelineContext();
|
|
840
|
+
const beforeLive = await this.requireLiveState();
|
|
841
|
+
this.validateMediaInsertionBinding(preview, beforeLive);
|
|
842
|
+
if (preview.selectionMode === "selected")
|
|
843
|
+
await this.validateSelectedMediaBinding(media);
|
|
844
|
+
try {
|
|
845
|
+
// Re-select by the stable Browser identity immediately before the edit. The
|
|
846
|
+
// cached handle only proves what this process selected, not what Final Cut
|
|
847
|
+
// currently has selected after another UI interaction.
|
|
848
|
+
if (preview.selectionMode === "handle")
|
|
849
|
+
await this.selectMediaNative(preview.mediaHandle);
|
|
850
|
+
await this.focusTimelineForMediaInsertion();
|
|
851
|
+
await this.executeNativeCommand(mediaInsertionScript(preview.operation), async (recovered) => {
|
|
852
|
+
this.assertRetryContext(before, recovered, preview.operation === "insert");
|
|
853
|
+
if (preview.selectionMode === "handle")
|
|
854
|
+
await this.selectMediaNative(preview.mediaHandle);
|
|
855
|
+
const refocused = await this.prepareNativeRetry();
|
|
856
|
+
this.assertRetryContext(before, refocused, preview.operation === "insert");
|
|
857
|
+
await this.focusTimelineForMediaInsertion();
|
|
858
|
+
this.validateMediaInsertionBinding(preview, await this.requireLiveState());
|
|
859
|
+
if (preview.selectionMode === "selected")
|
|
860
|
+
await this.validateSelectedMediaBinding(media);
|
|
861
|
+
});
|
|
862
|
+
}
|
|
863
|
+
catch (error) {
|
|
864
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
|
|
865
|
+
}
|
|
866
|
+
const operationId = opaqueHandle(`native-${preview.operation}-media`);
|
|
867
|
+
let after;
|
|
868
|
+
let afterLive;
|
|
869
|
+
try {
|
|
870
|
+
after = await this.requireTimelineContext();
|
|
871
|
+
afterLive = await this.waitForMediaInsertion(preview.beforeDuration, beforeLive.revision.id);
|
|
872
|
+
}
|
|
873
|
+
catch (error) {
|
|
874
|
+
const observedContext = after ?? await this.inspectRawNative();
|
|
875
|
+
const observedLive = afterLive ?? await this.readLiveState();
|
|
876
|
+
if (observedLive && mediaInsertionMutationObserved(beforeLive, observedLive) && observedContext.undoCommand) {
|
|
877
|
+
this.rememberOperation(operationId, {
|
|
878
|
+
kind: "media-insertion",
|
|
879
|
+
before,
|
|
880
|
+
after: observedContext,
|
|
881
|
+
beforeLive,
|
|
882
|
+
afterLive: observedLive,
|
|
883
|
+
beforeDuration: preview.beforeDuration,
|
|
884
|
+
undoCommand: observedContext.undoCommand,
|
|
885
|
+
});
|
|
886
|
+
try {
|
|
887
|
+
await this.undo(operationId);
|
|
888
|
+
}
|
|
889
|
+
catch (rollbackError) {
|
|
890
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}; operationId=${operationId}; native rollback failed: ${String(rollbackError)}`);
|
|
891
|
+
}
|
|
892
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}; insertion was rolled back`);
|
|
893
|
+
}
|
|
894
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}; post-command state was not safely recoverable, so no Undo handle was retained`);
|
|
895
|
+
}
|
|
896
|
+
const afterDuration = afterLive.sequenceTimeRange?.duration ?? afterLive.sequence?.duration;
|
|
897
|
+
const verification = mediaInsertionVerificationDetail(afterDuration, preview.beforeDuration, afterLive.revision.id, beforeLive.revision.id);
|
|
898
|
+
const operation = {
|
|
899
|
+
kind: "media-insertion",
|
|
900
|
+
before,
|
|
901
|
+
after,
|
|
902
|
+
beforeLive,
|
|
903
|
+
afterLive,
|
|
904
|
+
beforeDuration: preview.beforeDuration,
|
|
905
|
+
undoCommand: after.undoCommand,
|
|
906
|
+
};
|
|
907
|
+
if (!verification.verified) {
|
|
908
|
+
if (mediaInsertionMutationObserved(beforeLive, afterLive) && after.undoAvailable && after.undoCommand) {
|
|
909
|
+
this.rememberOperation(operationId, operation);
|
|
910
|
+
try {
|
|
911
|
+
await this.undo(operationId);
|
|
912
|
+
}
|
|
913
|
+
catch (rollbackError) {
|
|
914
|
+
throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}; operationId=${operationId}; native rollback failed: ${String(rollbackError)}`);
|
|
915
|
+
}
|
|
916
|
+
throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}; insertion was rolled back`);
|
|
917
|
+
}
|
|
918
|
+
throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}`);
|
|
919
|
+
}
|
|
920
|
+
this.rememberOperation(operationId, operation);
|
|
921
|
+
return {
|
|
922
|
+
operationId,
|
|
923
|
+
previewToken,
|
|
924
|
+
operation: preview.operation,
|
|
925
|
+
media,
|
|
926
|
+
before,
|
|
927
|
+
after,
|
|
928
|
+
beforeDuration: preview.beforeDuration,
|
|
929
|
+
afterDuration: afterDuration,
|
|
930
|
+
beforeRevision: beforeLive.revision,
|
|
931
|
+
afterRevision: afterLive.revision,
|
|
932
|
+
verification,
|
|
933
|
+
undoAvailable: after.undoAvailable,
|
|
934
|
+
...(after.undoCommand ? { undoCommand: after.undoCommand } : {}),
|
|
935
|
+
};
|
|
936
|
+
}
|
|
937
|
+
async focusTimelineForMediaInsertion() {
|
|
938
|
+
if (!this.canDriveNativeMouse)
|
|
939
|
+
return;
|
|
940
|
+
const coordinates = (await this.executor(timelineInsertionCoordinatesScript())).split("|").map(Number);
|
|
941
|
+
const [originX, originY, width, height] = coordinates;
|
|
942
|
+
if (![originX, originY, width, height].every(Number.isFinite)) {
|
|
943
|
+
throw new Error("FINAL_CUT_NATIVE_AUTOMATION_FAILED: could not resolve Final Cut timeline coordinates");
|
|
944
|
+
}
|
|
945
|
+
const x = Math.round(originX + width * 0.5);
|
|
946
|
+
const y = Math.round(originY + height * 0.82);
|
|
947
|
+
try {
|
|
948
|
+
await execFile("swift", ["-e", nativeMouseFocusSource(x, y)]);
|
|
949
|
+
}
|
|
950
|
+
catch (error) {
|
|
951
|
+
throw new Error(`FINAL_CUT_NATIVE_AUTOMATION_FAILED: native timeline focus failed: ${String(error)}`);
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
async validateSelectedMediaBinding(media) {
|
|
955
|
+
const selected = await this.readSelectedMediaNative();
|
|
956
|
+
if (selected.sourceIdentity !== media.sourceIdentity) {
|
|
957
|
+
throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_CHANGED: selected Browser media changed before insertion");
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
async previewRangeNative(operation, range) {
|
|
961
|
+
this.assertEnabled();
|
|
962
|
+
const context = await this.requireTimelineContext();
|
|
963
|
+
if (!context.frontmost)
|
|
964
|
+
throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline window must be frontmost");
|
|
965
|
+
const live = await this.requireLiveState();
|
|
966
|
+
const sequenceStart = live.sequenceTimeRange?.start ?? live.sequence?.startTime;
|
|
967
|
+
const currentDuration = live.sequenceTimeRange?.duration ?? live.sequence?.duration;
|
|
968
|
+
if (!sequenceStart || !currentDuration)
|
|
969
|
+
throw new Error("CAPABILITY_UNAVAILABLE: Final Cut sequence duration is unavailable");
|
|
970
|
+
const duration = subtractRational(range.end, range.start);
|
|
971
|
+
if (compareRational(duration, zeroRational()) <= 0)
|
|
972
|
+
throw new Error("INVALID_OPERATION: delete range must have start before end");
|
|
973
|
+
if (compareRational(range.start, sequenceStart) < 0 || compareRational(range.end, addRational(sequenceStart, currentDuration)) > 0) {
|
|
974
|
+
throw new Error("FINAL_CUT_NATIVE_RANGE_OUT_OF_BOUNDS: delete range must be inside the active sequence");
|
|
975
|
+
}
|
|
976
|
+
const expectedAfterDuration = subtractRational(currentDuration, duration);
|
|
977
|
+
return this.createRangePreview(operation, range, currentDuration, expectedAfterDuration, live);
|
|
978
|
+
}
|
|
979
|
+
createRangePreview(operation, range, beforeDuration, expectedAfterDuration, live, targetDuration) {
|
|
980
|
+
const expiresAt = this.now() + 30_000;
|
|
981
|
+
const previewToken = opaqueHandle(`${operation}-preview`);
|
|
982
|
+
this.rangePreviews.set(previewToken, {
|
|
983
|
+
operation,
|
|
984
|
+
range,
|
|
985
|
+
beforeDuration,
|
|
986
|
+
expectedAfterDuration,
|
|
987
|
+
sequenceId: live.sequence?.id,
|
|
988
|
+
revision: live.revision.id,
|
|
989
|
+
expiresAt,
|
|
990
|
+
});
|
|
991
|
+
return {
|
|
992
|
+
previewToken,
|
|
993
|
+
operation,
|
|
994
|
+
range,
|
|
995
|
+
beforeDuration,
|
|
996
|
+
expectedAfterDuration: targetDuration ?? expectedAfterDuration,
|
|
997
|
+
...(live.sequence?.id ? { sequenceId: live.sequence.id } : {}),
|
|
998
|
+
revision: live.revision.id,
|
|
999
|
+
command: operation === "delete-range" ? "Delete primary storyline range" : "Trim sequence to duration",
|
|
1000
|
+
expiresAt: new Date(expiresAt).toISOString(),
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
async executeRangeNative(previewToken, expectedOperation) {
|
|
1004
|
+
this.assertEnabled();
|
|
1005
|
+
const preview = this.rangePreviews.get(previewToken);
|
|
1006
|
+
if (!preview)
|
|
1007
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: unknown range preview");
|
|
1008
|
+
this.rangePreviews.delete(previewToken);
|
|
1009
|
+
if (this.now() > preview.expiresAt)
|
|
1010
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: range preview has expired");
|
|
1011
|
+
if (expectedOperation && preview.operation !== expectedOperation)
|
|
1012
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: preview operation does not match execute operation");
|
|
1013
|
+
const before = await this.requireTimelineContext();
|
|
1014
|
+
const beforeLive = await this.requireLiveState();
|
|
1015
|
+
this.validateRangeBinding(preview, beforeLive);
|
|
1016
|
+
const rangeDuration = subtractRational(preview.range.end, preview.range.start);
|
|
1017
|
+
if (compareRational(rangeDuration, zeroRational()) === 0) {
|
|
1018
|
+
return {
|
|
1019
|
+
operationId: opaqueHandle("native-noop"),
|
|
1020
|
+
previewToken,
|
|
1021
|
+
operation: preview.operation,
|
|
1022
|
+
range: preview.range,
|
|
1023
|
+
before,
|
|
1024
|
+
after: before,
|
|
1025
|
+
beforeDuration: preview.beforeDuration,
|
|
1026
|
+
afterDuration: preview.beforeDuration,
|
|
1027
|
+
expectedAfterDuration: preview.expectedAfterDuration,
|
|
1028
|
+
verification: { verified: true, detail: "Requested duration is already at or below the active sequence duration" },
|
|
1029
|
+
undoAvailable: false,
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
try {
|
|
1033
|
+
await this.positionAndDeleteRange(preview.range, beforeLive, async () => {
|
|
1034
|
+
this.validateRangeBinding(preview, await this.requireLiveState());
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
catch (error) {
|
|
1038
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
|
|
1039
|
+
}
|
|
1040
|
+
const after = await this.requireTimelineContext();
|
|
1041
|
+
const afterLive = await this.waitForDuration(preview.expectedAfterDuration, beforeLive.revision.id);
|
|
1042
|
+
const detail = durationVerificationDetail(afterLive.sequenceTimeRange?.duration ?? afterLive.sequence?.duration, preview.expectedAfterDuration, afterLive.sequence?.frameDuration ?? beforeLive.sequence?.frameDuration);
|
|
1043
|
+
if (!detail.verified)
|
|
1044
|
+
throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${detail.detail}`);
|
|
1045
|
+
const operationId = opaqueHandle(`native-${preview.operation}`);
|
|
1046
|
+
this.rememberOperation(operationId, {
|
|
1047
|
+
kind: "range",
|
|
1048
|
+
before,
|
|
1049
|
+
after,
|
|
1050
|
+
beforeLive,
|
|
1051
|
+
afterLive,
|
|
1052
|
+
beforeDuration: preview.beforeDuration,
|
|
1053
|
+
undoCommand: after.undoCommand,
|
|
1054
|
+
});
|
|
1055
|
+
return {
|
|
1056
|
+
operationId,
|
|
1057
|
+
previewToken,
|
|
1058
|
+
operation: preview.operation,
|
|
1059
|
+
range: preview.range,
|
|
1060
|
+
before,
|
|
1061
|
+
after,
|
|
1062
|
+
beforeDuration: preview.beforeDuration,
|
|
1063
|
+
afterDuration: afterLive.sequenceTimeRange?.duration ?? afterLive.sequence?.duration ?? preview.expectedAfterDuration,
|
|
1064
|
+
expectedAfterDuration: preview.expectedAfterDuration,
|
|
1065
|
+
verification: { verified: true, detail: detail.detail },
|
|
1066
|
+
undoAvailable: after.undoAvailable,
|
|
1067
|
+
...(after.undoCommand ? { undoCommand: after.undoCommand } : {}),
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
validateRangeBinding(preview, live) {
|
|
1071
|
+
if (preview.sequenceId && live.sequence?.id !== preview.sequenceId)
|
|
1072
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: active sequence changed");
|
|
1073
|
+
if (preview.revision && live.revision.id !== preview.revision)
|
|
1074
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: playhead or timeline revision changed");
|
|
1075
|
+
const currentDuration = live.sequenceTimeRange?.duration ?? live.sequence?.duration;
|
|
1076
|
+
if (!currentDuration || compareRational(currentDuration, preview.beforeDuration) !== 0)
|
|
1077
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: sequence duration changed");
|
|
1078
|
+
}
|
|
1079
|
+
async requireLiveState() {
|
|
1080
|
+
if (!this.liveState)
|
|
1081
|
+
throw new Error("CAPABILITY_UNAVAILABLE: live Final Cut state is required for range operations");
|
|
1082
|
+
return this.liveState();
|
|
1083
|
+
}
|
|
1084
|
+
validateMediaInsertionBinding(preview, live) {
|
|
1085
|
+
if (preview.sequenceId && live.sequence?.id !== preview.sequenceId)
|
|
1086
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: active sequence changed");
|
|
1087
|
+
if (live.revision.id !== preview.revision)
|
|
1088
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: playhead or timeline revision changed");
|
|
1089
|
+
const currentDuration = live.sequenceTimeRange?.duration ?? live.sequence?.duration;
|
|
1090
|
+
if (!currentDuration || compareRational(currentDuration, preview.beforeDuration) !== 0) {
|
|
1091
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: sequence duration changed");
|
|
1092
|
+
}
|
|
1093
|
+
if (preview.operation === "insert" && (!live.playheadTime || compareRational(live.playheadTime, preview.insertionTime) !== 0)) {
|
|
1094
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: playhead changed");
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
validateTitleBinding(preview, live) {
|
|
1098
|
+
if (preview.sequenceId && live.sequence?.id !== preview.sequenceId)
|
|
1099
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: active sequence changed");
|
|
1100
|
+
if (live.revision.id !== preview.revision)
|
|
1101
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: playhead or timeline revision changed");
|
|
1102
|
+
if (preview.target === "playhead" && (!live.playheadTime || compareRational(live.playheadTime, preview.start) !== 0)) {
|
|
1103
|
+
throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: playhead changed");
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
async waitForMediaInsertion(expectedBeforeDuration, previousRevision) {
|
|
1107
|
+
const deadline = this.now() + 5_000;
|
|
1108
|
+
let latest = await this.requireLiveState();
|
|
1109
|
+
while (this.now() < deadline) {
|
|
1110
|
+
const duration = latest.sequenceTimeRange?.duration ?? latest.sequence?.duration;
|
|
1111
|
+
if (duration && compareRational(duration, expectedBeforeDuration) > 0 && latest.revision.id !== previousRevision)
|
|
1112
|
+
return latest;
|
|
1113
|
+
await this.sleep(100);
|
|
1114
|
+
latest = await this.requireLiveState();
|
|
1115
|
+
}
|
|
1116
|
+
return latest;
|
|
1117
|
+
}
|
|
1118
|
+
async waitForRevision(previousRevision) {
|
|
1119
|
+
const deadline = this.now() + 5_000;
|
|
1120
|
+
let latest = await this.requireLiveState();
|
|
1121
|
+
while (this.now() < deadline) {
|
|
1122
|
+
if (latest.revision.id !== previousRevision)
|
|
1123
|
+
return latest;
|
|
1124
|
+
await this.sleep(100);
|
|
1125
|
+
latest = await this.requireLiveState();
|
|
1126
|
+
}
|
|
1127
|
+
return latest;
|
|
1128
|
+
}
|
|
1129
|
+
async waitForDuration(expected, previousRevision) {
|
|
1130
|
+
const deadline = this.now() + 5_000;
|
|
1131
|
+
let latest = await this.requireLiveState();
|
|
1132
|
+
while (this.now() < deadline) {
|
|
1133
|
+
const duration = latest.sequenceTimeRange?.duration ?? latest.sequence?.duration;
|
|
1134
|
+
if (duration && durationVerificationDetail(duration, expected, latest.sequence?.frameDuration).verified && latest.revision.id !== previousRevision)
|
|
1135
|
+
return latest;
|
|
1136
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
1137
|
+
latest = await this.requireLiveState();
|
|
1138
|
+
}
|
|
1139
|
+
return latest;
|
|
1140
|
+
}
|
|
1141
|
+
async waitForUndo(operation) {
|
|
1142
|
+
if (!operation.afterLive || !this.liveState)
|
|
1143
|
+
return undefined;
|
|
1144
|
+
const deadline = this.now() + 5_000;
|
|
1145
|
+
let latest = await this.requireLiveState();
|
|
1146
|
+
while (this.now() < deadline) {
|
|
1147
|
+
const duration = latest.sequenceTimeRange?.duration ?? latest.sequence?.duration;
|
|
1148
|
+
const durationRestored = operation.beforeDuration
|
|
1149
|
+
? Boolean(duration && compareRational(duration, operation.beforeDuration) === 0)
|
|
1150
|
+
: true;
|
|
1151
|
+
if (latest.revision.id !== operation.afterLive.revision.id && durationRestored)
|
|
1152
|
+
return latest;
|
|
1153
|
+
await this.sleep(100);
|
|
1154
|
+
latest = await this.requireLiveState();
|
|
1155
|
+
}
|
|
1156
|
+
return latest;
|
|
1157
|
+
}
|
|
1158
|
+
async positionAndDeleteRange(range, beforeLive, validateRetry) {
|
|
1159
|
+
const startTimecode = this.toTimecode(range.start, beforeLive);
|
|
1160
|
+
const endTimecode = this.toTimecode(range.end, beforeLive);
|
|
1161
|
+
const executeRange = async () => {
|
|
1162
|
+
await this.executor(setPlayheadScript(startTimecode));
|
|
1163
|
+
await this.waitForPlayhead(range.start, beforeLive.sequence?.id);
|
|
1164
|
+
await this.executor(markRangeStartScript());
|
|
1165
|
+
await this.executor(setPlayheadScript(endTimecode));
|
|
1166
|
+
await this.waitForPlayhead(range.end, beforeLive.sequence?.id);
|
|
1167
|
+
await this.executor(markRangeEndAndDeleteScript());
|
|
1168
|
+
};
|
|
1169
|
+
await this.executeNativeSequence(executeRange, validateRetry);
|
|
1170
|
+
}
|
|
1171
|
+
async executeNativeCommand(script, validateRetry) {
|
|
1172
|
+
try {
|
|
1173
|
+
await this.executor(script);
|
|
1174
|
+
}
|
|
1175
|
+
catch (error) {
|
|
1176
|
+
if (!isRecoverableNativeFocusRace(error))
|
|
1177
|
+
throw error;
|
|
1178
|
+
await validateRetry?.(await this.prepareNativeRetry());
|
|
1179
|
+
await this.executor(script);
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
async executeNativeSequence(execute, validateRetry) {
|
|
1183
|
+
try {
|
|
1184
|
+
await execute();
|
|
1185
|
+
}
|
|
1186
|
+
catch (error) {
|
|
1187
|
+
if (!isRecoverableNativeFocusRace(error))
|
|
1188
|
+
throw error;
|
|
1189
|
+
await validateRetry(await this.prepareNativeRetry());
|
|
1190
|
+
await execute();
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
async prepareNativeRetry() {
|
|
1194
|
+
return this.attachLiveState(await this.ensureTimelineReady());
|
|
1195
|
+
}
|
|
1196
|
+
assertRetryContext(expected, recovered, requirePlayhead = false) {
|
|
1197
|
+
const targetChanged = expected.target.kind !== recovered.target.kind
|
|
1198
|
+
|| expected.target.name !== recovered.target.name
|
|
1199
|
+
|| expected.target.role !== recovered.target.role;
|
|
1200
|
+
const occurrenceChanged = expected.target.kind === "selected-clip" && recovered.target.kind === "selected-clip"
|
|
1201
|
+
&& (!expected.target.identity || !recovered.target.identity || expected.target.identity !== recovered.target.identity);
|
|
1202
|
+
const playheadChanged = requirePlayhead
|
|
1203
|
+
? !expected.playheadTime || !recovered.playheadTime || expected.playheadTime !== recovered.playheadTime
|
|
1204
|
+
: expected.playheadTime !== recovered.playheadTime;
|
|
1205
|
+
if (targetChanged || occurrenceChanged || playheadChanged) {
|
|
1206
|
+
throw new Error("FINAL_CUT_NATIVE_RETRY_TARGET_CHANGED: Final Cut selection or playhead changed during focus recovery");
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
async waitForPlayhead(expected, sequenceId) {
|
|
1210
|
+
const deadline = this.now() + 5_000;
|
|
1211
|
+
let latest = await this.requireLiveState();
|
|
1212
|
+
while (this.now() < deadline) {
|
|
1213
|
+
if ((!sequenceId || latest.sequence?.id === sequenceId) && latest.playheadTime && compareRational(latest.playheadTime, expected) === 0)
|
|
1214
|
+
return latest;
|
|
1215
|
+
await this.sleep(100);
|
|
1216
|
+
latest = await this.requireLiveState();
|
|
1217
|
+
}
|
|
1218
|
+
throw new Error("FINAL_CUT_NATIVE_PLAYHEAD_VERIFICATION_FAILED: Final Cut did not move to the requested frame");
|
|
1219
|
+
}
|
|
1220
|
+
toTimecode(time, live) {
|
|
1221
|
+
const sequence = live.sequence;
|
|
1222
|
+
if (!sequence)
|
|
1223
|
+
throw new Error("CAPABILITY_UNAVAILABLE: Final Cut sequence frame rate is unavailable");
|
|
1224
|
+
const relative = subtractRational(time, sequence.startTime);
|
|
1225
|
+
const frames = divideRationalFloor(relative, sequence.frameDuration);
|
|
1226
|
+
const nominalFps = Math.max(1, Math.round(Number(sequence.frameDuration.timescale) / Number(sequence.frameDuration.value)));
|
|
1227
|
+
return formatTimecode(frames, nominalFps);
|
|
1228
|
+
}
|
|
1229
|
+
assertEnabled() {
|
|
1230
|
+
if (!this.enabled)
|
|
1231
|
+
throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native writes are disabled");
|
|
1232
|
+
}
|
|
1233
|
+
async withNativeUi(operation) {
|
|
1234
|
+
const outermost = this.nativeUiDepth === 0;
|
|
1235
|
+
if (outermost && this.enabled) {
|
|
1236
|
+
if (this.nativeOperationLease)
|
|
1237
|
+
this.nativeOperationLease.acquire();
|
|
1238
|
+
else
|
|
1239
|
+
this.suspendLiveConnection?.();
|
|
1240
|
+
}
|
|
1241
|
+
this.nativeUiDepth += 1;
|
|
1242
|
+
try {
|
|
1243
|
+
return await operation();
|
|
1244
|
+
}
|
|
1245
|
+
finally {
|
|
1246
|
+
this.nativeUiDepth -= 1;
|
|
1247
|
+
if (outermost && this.enabled) {
|
|
1248
|
+
if (this.nativeOperationLease)
|
|
1249
|
+
this.nativeOperationLease.release();
|
|
1250
|
+
else
|
|
1251
|
+
this.resumeLiveConnection?.();
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
async validateOccurrenceBinding(occurrence) {
|
|
1256
|
+
if (!this.liveState || !occurrence.revision)
|
|
1257
|
+
return;
|
|
1258
|
+
const live = await this.liveState().catch(() => undefined);
|
|
1259
|
+
if (!live)
|
|
1260
|
+
return;
|
|
1261
|
+
if (occurrence.sequenceId && live.sequence?.id !== occurrence.sequenceId) {
|
|
1262
|
+
throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: active sequence changed");
|
|
1263
|
+
}
|
|
1264
|
+
if (live.revision.id !== occurrence.revision) {
|
|
1265
|
+
throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: playhead or timeline revision changed");
|
|
1266
|
+
}
|
|
1267
|
+
if (occurrence.start && occurrence.duration && live.playheadTime) {
|
|
1268
|
+
const start = parseRationalNumber(occurrence.start);
|
|
1269
|
+
const duration = parseRationalNumber(occurrence.duration);
|
|
1270
|
+
const playhead = Number(live.playheadTime.value) / Number(live.playheadTime.timescale);
|
|
1271
|
+
if (start !== undefined && duration !== undefined && (playhead < start || playhead >= start + duration)) {
|
|
1272
|
+
throw new Error("FINAL_CUT_NATIVE_PLAYHEAD_OUTSIDE_OCCURRENCE: playhead is outside the target occurrence");
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
async requireTimelineTarget(operation) {
|
|
1277
|
+
const context = await this.requireTimelineContext();
|
|
1278
|
+
if (requiresClip(operation) && context.target.kind !== "selected-clip") {
|
|
1279
|
+
throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: select exactly one clip in Final Cut Pro");
|
|
1280
|
+
}
|
|
1281
|
+
if (!requiresClip(operation) && context.target.kind === "none") {
|
|
1282
|
+
throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: position the playhead in Final Cut Pro");
|
|
1283
|
+
}
|
|
1284
|
+
return context;
|
|
1285
|
+
}
|
|
1286
|
+
async requireTimelineContext() {
|
|
1287
|
+
const context = await this.attachLiveState(await this.ensureTimelineReady());
|
|
1288
|
+
if (!context.available) {
|
|
1289
|
+
throw new Error(`${context.error?.code ?? "FINAL_CUT_NATIVE_UNAVAILABLE"}: ${context.error?.message ?? "native timeline context unavailable"}`);
|
|
1290
|
+
}
|
|
1291
|
+
return context;
|
|
1292
|
+
}
|
|
1293
|
+
async ensureTimelineReady() {
|
|
1294
|
+
const deadline = this.now() + this.nativePreflightTimeoutMs;
|
|
1295
|
+
let lastCode = "FINAL_CUT_NATIVE_NO_TIMELINE_WINDOW";
|
|
1296
|
+
let lastMessage = "Final Cut has no accessible timeline window; open a project timeline and retry";
|
|
1297
|
+
let lastContext;
|
|
1298
|
+
while (this.now() < deadline) {
|
|
1299
|
+
try {
|
|
1300
|
+
const context = parseContext(await this.executeNativeScript(timelinePreflightScript(), deadline, "FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT"));
|
|
1301
|
+
lastContext = context;
|
|
1302
|
+
if (!context.timelineWindowAvailable) {
|
|
1303
|
+
lastCode = "FINAL_CUT_NATIVE_NO_TIMELINE_WINDOW";
|
|
1304
|
+
lastMessage = "Final Cut has no accessible timeline window; open a project timeline and retry";
|
|
1305
|
+
}
|
|
1306
|
+
else if (context.overlayBlocked) {
|
|
1307
|
+
lastCode = "FINAL_CUT_NATIVE_OVERLAY_BLOCKED";
|
|
1308
|
+
lastMessage = "The Framekit window could not be minimized; close or minimize the overlay and retry";
|
|
1309
|
+
}
|
|
1310
|
+
else if (!context.frontmost) {
|
|
1311
|
+
lastCode = "FINAL_CUT_NATIVE_NOT_FRONTMOST";
|
|
1312
|
+
lastMessage = "Final Cut is running but is not the frontmost application";
|
|
1313
|
+
}
|
|
1314
|
+
else if (!context.timelineFocused) {
|
|
1315
|
+
lastCode = "FINAL_CUT_NATIVE_TIMELINE_FOCUS_REQUIRED";
|
|
1316
|
+
lastMessage = "Final Cut's timeline pane could not be focused; click the timeline and retry";
|
|
1317
|
+
}
|
|
1318
|
+
else {
|
|
1319
|
+
return context;
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
catch (error) {
|
|
1323
|
+
const code = nativeErrorCode(error);
|
|
1324
|
+
if (code === "FINAL_CUT_NATIVE_PERMISSION_REQUIRED")
|
|
1325
|
+
throw new NativeFinalCutPreflightError(code, nativeErrorMessage(error), lastContext);
|
|
1326
|
+
lastCode = code;
|
|
1327
|
+
lastMessage = nativeErrorMessage(error);
|
|
1328
|
+
}
|
|
1329
|
+
if (this.now() >= deadline)
|
|
1330
|
+
break;
|
|
1331
|
+
await this.sleep(Math.min(100, deadline - this.now()));
|
|
1332
|
+
}
|
|
1333
|
+
throw new NativeFinalCutPreflightError(lastCode, lastMessage, lastContext);
|
|
1334
|
+
}
|
|
1335
|
+
async requireAvailableContext(deadline) {
|
|
1336
|
+
const context = await this.inspectRawNative(deadline);
|
|
1337
|
+
if (!context.available)
|
|
1338
|
+
throw new Error(`${context.error?.code ?? "FINAL_CUT_NATIVE_UNAVAILABLE"}: ${context.error?.message ?? "native context unavailable"}`);
|
|
1339
|
+
return context;
|
|
1340
|
+
}
|
|
1341
|
+
async ensureBrowserReady(deadline, timeoutCode = "FINAL_CUT_NATIVE_MEDIA_IMPORT_TIMEOUT") {
|
|
1342
|
+
try {
|
|
1343
|
+
await this.executeNativeScript(browserFocusScript(), deadline, timeoutCode);
|
|
1344
|
+
}
|
|
1345
|
+
catch (error) {
|
|
1346
|
+
throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
|
|
1347
|
+
}
|
|
1348
|
+
const context = await this.requireAvailableContext(deadline);
|
|
1349
|
+
if (!context.frontmost)
|
|
1350
|
+
throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut could not be brought to the front for Browser automation");
|
|
1351
|
+
return context;
|
|
1352
|
+
}
|
|
1353
|
+
stableMediaHandle(identity) {
|
|
1354
|
+
return `media-import-${createHash("sha256").update(identity).digest("hex").slice(0, 24)}`;
|
|
1355
|
+
}
|
|
1356
|
+
async executeNativeScript(script, deadline, timeoutCode = "FINAL_CUT_NATIVE_MEDIA_IMPORT_TIMEOUT") {
|
|
1357
|
+
if (deadline === undefined)
|
|
1358
|
+
return this.executor(script);
|
|
1359
|
+
const remaining = deadline - this.now();
|
|
1360
|
+
if (remaining <= 0)
|
|
1361
|
+
throw new Error(`${timeoutCode}: native automation deadline expired`);
|
|
1362
|
+
const controller = new AbortController();
|
|
1363
|
+
let timer;
|
|
1364
|
+
const timeout = new Promise((_, reject) => {
|
|
1365
|
+
timer = setTimeout(() => {
|
|
1366
|
+
controller.abort();
|
|
1367
|
+
reject(new Error(`${timeoutCode}: native automation deadline expired`));
|
|
1368
|
+
}, remaining);
|
|
1369
|
+
});
|
|
1370
|
+
try {
|
|
1371
|
+
return await Promise.race([this.executor(script, { signal: controller.signal }), timeout]);
|
|
1372
|
+
}
|
|
1373
|
+
finally {
|
|
1374
|
+
if (timer !== undefined)
|
|
1375
|
+
clearTimeout(timer);
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
function verifyNativeUndo(operation, after, afterLive) {
|
|
1380
|
+
if (operation.afterLive && (!afterLive || afterLive.revision.id === operation.afterLive.revision.id)) {
|
|
1381
|
+
return { verified: false, detail: "Final Cut did not expose a new revision after Undo" };
|
|
1382
|
+
}
|
|
1383
|
+
if (operation.beforeDuration) {
|
|
1384
|
+
const duration = afterLive?.sequenceTimeRange?.duration ?? afterLive?.sequence?.duration;
|
|
1385
|
+
const detail = durationVerificationDetail(duration, operation.beforeDuration);
|
|
1386
|
+
if (!detail.verified)
|
|
1387
|
+
return detail;
|
|
1388
|
+
}
|
|
1389
|
+
if (operation.kind === "selection" && operation.before.target.name !== after.target.name) {
|
|
1390
|
+
return {
|
|
1391
|
+
verified: false,
|
|
1392
|
+
detail: `expected selected target ${operation.before.target.name ?? "<unnamed>"}, observed ${after.target.name ?? "<unnamed>"}`,
|
|
1393
|
+
};
|
|
1394
|
+
}
|
|
1395
|
+
return { verified: true, detail: "Final Cut restored the native edit's pre-operation state" };
|
|
1396
|
+
}
|
|
1397
|
+
function assertNativeTitleAsset(asset) {
|
|
1398
|
+
if (!asset.id.trim() || !asset.name.trim())
|
|
1399
|
+
throw new Error("TITLE_ASSET_NOT_FOUND: native title asset identity is incomplete");
|
|
1400
|
+
if (asset.kind !== "title")
|
|
1401
|
+
throw new Error(`TITLE_ASSET_INCOMPATIBLE: ${asset.id} is not a Final Cut title asset`);
|
|
1402
|
+
}
|
|
1403
|
+
function publicTitleAsset(asset) {
|
|
1404
|
+
return { id: asset.id, kind: asset.kind, name: asset.name, vendor: asset.vendor };
|
|
1405
|
+
}
|
|
1406
|
+
function verifyNativeTitle(preview, beforeLive, after, afterLive) {
|
|
1407
|
+
if (afterLive.revision.id === beforeLive.revision.id) {
|
|
1408
|
+
return { verified: false, detail: "Final Cut did not expose a new revision after native title placement" };
|
|
1409
|
+
}
|
|
1410
|
+
if (after.target.kind !== "selected-clip") {
|
|
1411
|
+
return { verified: false, detail: "Final Cut did not expose the inserted title as the selected timeline item" };
|
|
1412
|
+
}
|
|
1413
|
+
const observedName = after.target.name ?? "";
|
|
1414
|
+
if (!observedName.toLowerCase().includes(preview.asset.name.toLowerCase())
|
|
1415
|
+
&& !observedName.toLowerCase().includes(preview.text.toLowerCase())) {
|
|
1416
|
+
return { verified: false, detail: `Final Cut selected ${observedName || "an unnamed item"}, not ${preview.asset.name}` };
|
|
1417
|
+
}
|
|
1418
|
+
if (!after.undoAvailable || !after.undoCommand) {
|
|
1419
|
+
return { verified: false, detail: "Final Cut did not expose an Undo command for the native title placement" };
|
|
1420
|
+
}
|
|
1421
|
+
return {
|
|
1422
|
+
verified: true,
|
|
1423
|
+
detail: `Final Cut selected ${preview.asset.name} for ${preview.start.value}/${preview.start.timescale}-${preview.end.value}/${preview.end.timescale} (${preview.duration.value}/${preview.duration.timescale}) at revision ${afterLive.revision.id}`,
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
async function runAppleScript(script, options = {}) {
|
|
1427
|
+
try {
|
|
1428
|
+
const result = await execFile("osascript", ["-e", script], { maxBuffer: 1_000_000, signal: options.signal });
|
|
1429
|
+
return result.stdout.trim();
|
|
1430
|
+
}
|
|
1431
|
+
catch (error) {
|
|
1432
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
1433
|
+
if (detail.includes("not authorized") || detail.includes("-1743") || detail.includes("-25211")) {
|
|
1434
|
+
throw new Error(`FINAL_CUT_NATIVE_PERMISSION_REQUIRED: ${detail}`);
|
|
1435
|
+
}
|
|
1436
|
+
throw new Error(`FINAL_CUT_NATIVE_AUTOMATION_FAILED: ${detail}`);
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
function activateFinalCutWindowAppleScript() {
|
|
1440
|
+
return `
|
|
1441
|
+
set frontmost to true
|
|
1442
|
+
delay 0.1`;
|
|
1443
|
+
}
|
|
1444
|
+
function requireFrontmostAppleScript() {
|
|
1445
|
+
return `
|
|
1446
|
+
if not frontmost then error number -1719`;
|
|
1447
|
+
}
|
|
1448
|
+
function timelinePreflightScript() {
|
|
1449
|
+
return `
|
|
1450
|
+
tell application "System Events"
|
|
1451
|
+
tell process "Final Cut Pro"
|
|
1452
|
+
set frontmost to true
|
|
1453
|
+
end tell
|
|
1454
|
+
end tell
|
|
1455
|
+
delay 0.1
|
|
1456
|
+
on preflightResult(processFrontmost, frontWindowName, selectedCount, selectedName, selectedRole, focusedName, focusedRole, focusedDescription, focusedWindowName, timelineWindowAvailable, timelineFocused, focusTarget, focusAttempts, framekitWindowAvailable, framekitWindowMinimized, overlayBlocked, selectedIdentity)
|
|
1457
|
+
set undoEnabled to false
|
|
1458
|
+
set undoCommand to ""
|
|
1459
|
+
try
|
|
1460
|
+
tell application "System Events"
|
|
1461
|
+
tell process "Final Cut Pro"
|
|
1462
|
+
repeat with candidate in menu items of menu "Edit" of menu bar 1
|
|
1463
|
+
try
|
|
1464
|
+
set candidateName to name of candidate as text
|
|
1465
|
+
if candidateName starts with "Undo" and (enabled of candidate) is true then
|
|
1466
|
+
set undoEnabled to true
|
|
1467
|
+
set undoCommand to candidateName
|
|
1468
|
+
exit repeat
|
|
1469
|
+
end if
|
|
1470
|
+
end try
|
|
1471
|
+
end repeat
|
|
1472
|
+
end tell
|
|
1473
|
+
end tell
|
|
1474
|
+
end try
|
|
1475
|
+
return processFrontmost & (ASCII character 31) & frontWindowName & (ASCII character 31) & selectedCount & (ASCII character 31) & selectedName & (ASCII character 31) & selectedRole & (ASCII character 31) & undoEnabled & (ASCII character 31) & "false" & (ASCII character 31) & focusedName & (ASCII character 31) & focusedRole & (ASCII character 31) & focusedDescription & (ASCII character 31) & timelineWindowAvailable & (ASCII character 31) & timelineFocused & (ASCII character 31) & focusTarget & (ASCII character 31) & focusAttempts & (ASCII character 31) & framekitWindowAvailable & (ASCII character 31) & framekitWindowMinimized & (ASCII character 31) & focusedWindowName & (ASCII character 31) & overlayBlocked & (ASCII character 31) & undoCommand & (ASCII character 31) & selectedIdentity
|
|
1476
|
+
end preflightResult
|
|
1477
|
+
|
|
1478
|
+
on focusSnapshot()
|
|
1479
|
+
tell application "System Events"
|
|
1480
|
+
tell process "Final Cut Pro"
|
|
1481
|
+
set processState to frontmost as text
|
|
1482
|
+
set windowName to ""
|
|
1483
|
+
set elementName to ""
|
|
1484
|
+
set elementRole to ""
|
|
1485
|
+
set elementDescription to ""
|
|
1486
|
+
try
|
|
1487
|
+
set focusedWindow to value of attribute "AXFocusedWindow"
|
|
1488
|
+
set windowName to name of focusedWindow as text
|
|
1489
|
+
end try
|
|
1490
|
+
try
|
|
1491
|
+
set focusedElement to value of attribute "AXFocusedUIElement"
|
|
1492
|
+
set elementName to name of focusedElement as text
|
|
1493
|
+
set elementRole to role of focusedElement as text
|
|
1494
|
+
set elementDescription to description of focusedElement as text
|
|
1495
|
+
end try
|
|
1496
|
+
return {processState, windowName, elementName, elementRole, elementDescription}
|
|
1497
|
+
end tell
|
|
1498
|
+
end tell
|
|
1499
|
+
end focusSnapshot
|
|
1500
|
+
|
|
1501
|
+
on attemptTimelineFocus(candidatePoint)
|
|
1502
|
+
tell application "System Events"
|
|
1503
|
+
tell process "Final Cut Pro"
|
|
1504
|
+
set clickedName to ""
|
|
1505
|
+
set clickedRole to ""
|
|
1506
|
+
set clickedDescription to ""
|
|
1507
|
+
try
|
|
1508
|
+
set clickedElement to click at candidatePoint
|
|
1509
|
+
set clickedName to name of clickedElement as text
|
|
1510
|
+
set clickedRole to role of clickedElement as text
|
|
1511
|
+
set clickedDescription to description of clickedElement as text
|
|
1512
|
+
try
|
|
1513
|
+
perform action "AXPress" of clickedElement
|
|
1514
|
+
end try
|
|
1515
|
+
end try
|
|
1516
|
+
end tell
|
|
1517
|
+
end tell
|
|
1518
|
+
delay 0.1
|
|
1519
|
+
return (my focusSnapshot()) & {clickedName, clickedRole, clickedDescription}
|
|
1520
|
+
end attemptTimelineFocus
|
|
1521
|
+
|
|
1522
|
+
on timelineFocus(roleName, descriptionText, elementName)
|
|
1523
|
+
if roleName is "AXTextField" or roleName is "AXSearchField" then return false
|
|
1524
|
+
if roleName is "AXSheet" or roleName is "AXDialog" then return false
|
|
1525
|
+
if descriptionText contains "Browser" or descriptionText contains "browser" or descriptionText contains "search" or descriptionText contains "Search" or elementName contains "Browser" or elementName contains "browser" or elementName contains "search" or elementName contains "Search" then return false
|
|
1526
|
+
if roleName is "AXGroup" or roleName is "AXScrollArea" or roleName is "AXLayoutArea" or roleName is "AXCanvas" then return true
|
|
1527
|
+
if roleName is "AXImage" and (descriptionText contains "Filmstrip" or descriptionText contains "filmstrip" or descriptionText contains "Video") then return true
|
|
1528
|
+
if descriptionText contains "timeline" or descriptionText contains "Timeline" or elementName contains "timeline" or elementName contains "Timeline" then return true
|
|
1529
|
+
return false
|
|
1530
|
+
end timelineFocus
|
|
1531
|
+
|
|
1532
|
+
tell application "System Events"
|
|
1533
|
+
tell process "Final Cut Pro"
|
|
1534
|
+
try
|
|
1535
|
+
set frontmost to true
|
|
1536
|
+
delay 0.1
|
|
1537
|
+
end try
|
|
1538
|
+
set processFrontmost to frontmost as text
|
|
1539
|
+
set timelineWindowAvailable to false
|
|
1540
|
+
set frontWindowName to ""
|
|
1541
|
+
set focusAttempts to 0
|
|
1542
|
+
set framekitWindowAvailable to false
|
|
1543
|
+
set framekitWindowMinimized to false
|
|
1544
|
+
set overlayBlocked to false
|
|
1545
|
+
set focusedWindowName to ""
|
|
1546
|
+
try
|
|
1547
|
+
set frontWindow to window "Final Cut Pro"
|
|
1548
|
+
set timelineWindowAvailable to true
|
|
1549
|
+
set frontWindowName to name of frontWindow as text
|
|
1550
|
+
on error
|
|
1551
|
+
return my preflightResult(processFrontmost, frontWindowName, 0, "", "", "", "", "", "", timelineWindowAvailable, false, "none", focusAttempts, framekitWindowAvailable, framekitWindowMinimized, overlayBlocked, "")
|
|
1552
|
+
end try
|
|
1553
|
+
|
|
1554
|
+
try
|
|
1555
|
+
repeat with candidateWindow in windows
|
|
1556
|
+
try
|
|
1557
|
+
set candidateWindowName to name of candidateWindow as text
|
|
1558
|
+
if candidateWindowName contains "Framekit" then
|
|
1559
|
+
set framekitWindowAvailable to true
|
|
1560
|
+
set framekitWindow to contents of candidateWindow
|
|
1561
|
+
try
|
|
1562
|
+
set framekitWindowMinimized to (value of attribute "AXMinimized" of framekitWindow) as boolean
|
|
1563
|
+
end try
|
|
1564
|
+
if not framekitWindowMinimized then
|
|
1565
|
+
try
|
|
1566
|
+
perform action "AXMinimize" of framekitWindow
|
|
1567
|
+
on error
|
|
1568
|
+
try
|
|
1569
|
+
set value of attribute "AXMinimized" of framekitWindow to true
|
|
1570
|
+
end try
|
|
1571
|
+
end try
|
|
1572
|
+
delay 0.1
|
|
1573
|
+
try
|
|
1574
|
+
set framekitWindowMinimized to (value of attribute "AXMinimized" of framekitWindow) as boolean
|
|
1575
|
+
end try
|
|
1576
|
+
end if
|
|
1577
|
+
if not framekitWindowMinimized then set overlayBlocked to true
|
|
1578
|
+
exit repeat
|
|
1579
|
+
end if
|
|
1580
|
+
end try
|
|
1581
|
+
end repeat
|
|
1582
|
+
end try
|
|
1583
|
+
|
|
1584
|
+
if overlayBlocked then
|
|
1585
|
+
set snapshot to my focusSnapshot()
|
|
1586
|
+
set processFrontmost to item 1 of snapshot
|
|
1587
|
+
set focusedWindowName to item 2 of snapshot
|
|
1588
|
+
set focusedName to item 3 of snapshot
|
|
1589
|
+
set focusedRole to item 4 of snapshot
|
|
1590
|
+
set focusedDescription to item 5 of snapshot
|
|
1591
|
+
return my preflightResult(processFrontmost, frontWindowName, 0, "", "", focusedName, focusedRole, focusedDescription, focusedWindowName, timelineWindowAvailable, false, "unknown", focusAttempts, framekitWindowAvailable, framekitWindowMinimized, overlayBlocked, "")
|
|
1592
|
+
end if
|
|
1593
|
+
try
|
|
1594
|
+
set frontmost to true
|
|
1595
|
+
delay 0.1
|
|
1596
|
+
end try
|
|
1597
|
+
set snapshot to my focusSnapshot()
|
|
1598
|
+
set processFrontmost to item 1 of snapshot
|
|
1599
|
+
set focusedWindowName to item 2 of snapshot
|
|
1600
|
+
if processFrontmost is not "true" then
|
|
1601
|
+
return my preflightResult(processFrontmost, frontWindowName, 0, "", "", item 3 of snapshot, item 4 of snapshot, item 5 of snapshot, focusedWindowName, timelineWindowAvailable, false, "unknown", focusAttempts, framekitWindowAvailable, framekitWindowMinimized, overlayBlocked, "")
|
|
1602
|
+
end if
|
|
1603
|
+
try
|
|
1604
|
+
perform action "AXRaise" of frontWindow
|
|
1605
|
+
end try
|
|
1606
|
+
set frontmost to true
|
|
1607
|
+
delay 0.1
|
|
1608
|
+
set snapshot to my focusSnapshot()
|
|
1609
|
+
set processFrontmost to item 1 of snapshot
|
|
1610
|
+
set focusedWindowName to item 2 of snapshot
|
|
1611
|
+
if processFrontmost is not "true" then
|
|
1612
|
+
return my preflightResult(processFrontmost, frontWindowName, 0, "", "", item 3 of snapshot, item 4 of snapshot, item 5 of snapshot, focusedWindowName, timelineWindowAvailable, false, "unknown", focusAttempts, framekitWindowAvailable, framekitWindowMinimized, overlayBlocked, "")
|
|
1613
|
+
end if
|
|
1614
|
+
|
|
1615
|
+
set windowPosition to position of frontWindow
|
|
1616
|
+
set windowSize to size of frontWindow
|
|
1617
|
+
set originX to item 1 of windowPosition
|
|
1618
|
+
set originY to item 2 of windowPosition
|
|
1619
|
+
set windowWidth to item 1 of windowSize
|
|
1620
|
+
set windowHeight to item 2 of windowSize
|
|
1621
|
+
set semanticPoints to {}
|
|
1622
|
+
-- Full AX-tree traversal can block Final Cut for tens of seconds while
|
|
1623
|
+
-- the Browser or Framekit extension window is hosted. Keep semanticPoints
|
|
1624
|
+
-- available for diagnostics, but use bounded timeline fallback points.
|
|
1625
|
+
|
|
1626
|
+
set fallbackPoints to {{originX + (windowWidth * 0.50), originY + (windowHeight * 0.82)}, {originX + (windowWidth * 0.75), originY + (windowHeight * 0.82)}, {originX + (windowWidth * 0.25), originY + (windowHeight * 0.82)}, {originX + (windowWidth * 0.50), originY + (windowHeight * 0.90)}}
|
|
1627
|
+
set timelineFocused to false
|
|
1628
|
+
set focusTarget to "unknown"
|
|
1629
|
+
repeat with candidatePoint in semanticPoints
|
|
1630
|
+
set focusAttempts to focusAttempts + 1
|
|
1631
|
+
set snapshot to my attemptTimelineFocus(contents of candidatePoint)
|
|
1632
|
+
set processFrontmost to item 1 of snapshot
|
|
1633
|
+
set focusedWindowName to item 2 of snapshot
|
|
1634
|
+
set focusedName to item 3 of snapshot
|
|
1635
|
+
set focusedRole to item 4 of snapshot
|
|
1636
|
+
set focusedDescription to item 5 of snapshot
|
|
1637
|
+
set clickedName to item 6 of snapshot
|
|
1638
|
+
set clickedRole to item 7 of snapshot
|
|
1639
|
+
set clickedDescription to item 8 of snapshot
|
|
1640
|
+
if focusedWindowName contains "Framekit" then
|
|
1641
|
+
set overlayBlocked to true
|
|
1642
|
+
exit repeat
|
|
1643
|
+
else if (my timelineFocus(focusedRole, focusedDescription, focusedName) or my timelineFocus(clickedRole, clickedDescription, clickedName)) and processFrontmost is "true" then
|
|
1644
|
+
set timelineFocused to true
|
|
1645
|
+
set focusTarget to "timeline"
|
|
1646
|
+
exit repeat
|
|
1647
|
+
else if focusedRole is "AXTextField" or focusedRole is "AXSearchField" then
|
|
1648
|
+
set focusTarget to "text-field"
|
|
1649
|
+
else if focusedDescription contains "Browser" or focusedDescription contains "browser" or focusedDescription contains "search" or focusedDescription contains "Search" or focusedName contains "Browser" or focusedName contains "browser" or focusedName contains "search" or focusedName contains "Search" then
|
|
1650
|
+
set focusTarget to "browser"
|
|
1651
|
+
end if
|
|
1652
|
+
end repeat
|
|
1653
|
+
if not timelineFocused then
|
|
1654
|
+
repeat with fallbackPoint in fallbackPoints
|
|
1655
|
+
set focusAttempts to focusAttempts + 1
|
|
1656
|
+
set snapshot to my attemptTimelineFocus(contents of fallbackPoint)
|
|
1657
|
+
set processFrontmost to item 1 of snapshot
|
|
1658
|
+
set focusedWindowName to item 2 of snapshot
|
|
1659
|
+
set focusedName to item 3 of snapshot
|
|
1660
|
+
set focusedRole to item 4 of snapshot
|
|
1661
|
+
set focusedDescription to item 5 of snapshot
|
|
1662
|
+
set clickedName to item 6 of snapshot
|
|
1663
|
+
set clickedRole to item 7 of snapshot
|
|
1664
|
+
set clickedDescription to item 8 of snapshot
|
|
1665
|
+
if focusedWindowName contains "Framekit" then
|
|
1666
|
+
set overlayBlocked to true
|
|
1667
|
+
exit repeat
|
|
1668
|
+
else if (my timelineFocus(focusedRole, focusedDescription, focusedName) or my timelineFocus(clickedRole, clickedDescription, clickedName)) and processFrontmost is "true" then
|
|
1669
|
+
set timelineFocused to true
|
|
1670
|
+
set focusTarget to "timeline"
|
|
1671
|
+
exit repeat
|
|
1672
|
+
else if focusedRole is "AXTextField" or focusedRole is "AXSearchField" then
|
|
1673
|
+
set focusTarget to "text-field"
|
|
1674
|
+
else if focusedRole is "AXSheet" or focusedRole is "AXDialog" then
|
|
1675
|
+
set focusTarget to "modal"
|
|
1676
|
+
else if focusedDescription contains "Browser" or focusedDescription contains "browser" or focusedDescription contains "search" or focusedDescription contains "Search" or focusedName contains "Browser" or focusedName contains "browser" or focusedName contains "search" or focusedName contains "Search" then
|
|
1677
|
+
set focusTarget to "browser"
|
|
1678
|
+
else
|
|
1679
|
+
set focusTarget to "unknown"
|
|
1680
|
+
end if
|
|
1681
|
+
end repeat
|
|
1682
|
+
end if
|
|
1683
|
+
|
|
1684
|
+
set snapshot to my focusSnapshot()
|
|
1685
|
+
set processFrontmost to item 1 of snapshot
|
|
1686
|
+
set focusedWindowName to item 2 of snapshot
|
|
1687
|
+
set focusedName to item 3 of snapshot
|
|
1688
|
+
set focusedRole to item 4 of snapshot
|
|
1689
|
+
set focusedDescription to item 5 of snapshot
|
|
1690
|
+
if focusedWindowName contains "Framekit" then set overlayBlocked to true
|
|
1691
|
+
set selectedName to ""
|
|
1692
|
+
set selectedRole to ""
|
|
1693
|
+
set selectedIdentity to ""
|
|
1694
|
+
set selectedCount to 0
|
|
1695
|
+
-- Do not walk the full AX tree here. Final Cut can block that traversal
|
|
1696
|
+
-- while the Browser or Framekit extension window is hosted; selected
|
|
1697
|
+
-- Browser media is discovered through its dedicated bounded path.
|
|
1698
|
+
return my preflightResult(processFrontmost, frontWindowName, selectedCount, selectedName, selectedRole, focusedName, focusedRole, focusedDescription, focusedWindowName, timelineWindowAvailable, timelineFocused, focusTarget, focusAttempts, framekitWindowAvailable, framekitWindowMinimized, overlayBlocked, selectedIdentity)
|
|
1699
|
+
end tell
|
|
1700
|
+
end tell`;
|
|
1701
|
+
}
|
|
1702
|
+
function inspectScript() {
|
|
1703
|
+
return `
|
|
1704
|
+
tell application "System Events"
|
|
1705
|
+
tell process "Final Cut Pro"
|
|
1706
|
+
${activateFinalCutWindowAppleScript()}
|
|
1707
|
+
set frontWindow to window "Final Cut Pro"
|
|
1708
|
+
set frontWindowName to name of frontWindow
|
|
1709
|
+
set selectedName to ""
|
|
1710
|
+
set selectedRole to ""
|
|
1711
|
+
set selectedCount to 0
|
|
1712
|
+
try
|
|
1713
|
+
repeat with candidate in entire contents of frontWindow
|
|
1714
|
+
try
|
|
1715
|
+
if (selected of candidate) is true then
|
|
1716
|
+
set selectedCount to selectedCount + 1
|
|
1717
|
+
if selectedCount is 1 then
|
|
1718
|
+
set selectedName to name of candidate as text
|
|
1719
|
+
set selectedRole to role of candidate as text
|
|
1720
|
+
end if
|
|
1721
|
+
end if
|
|
1722
|
+
end try
|
|
1723
|
+
end repeat
|
|
1724
|
+
end try
|
|
1725
|
+
set undoEnabled to false
|
|
1726
|
+
set undoCommand to ""
|
|
1727
|
+
try
|
|
1728
|
+
repeat with candidate in menu items of menu "Edit" of menu bar 1
|
|
1729
|
+
try
|
|
1730
|
+
set candidateName to name of candidate as text
|
|
1731
|
+
if candidateName starts with "Undo" and (enabled of candidate) is true then
|
|
1732
|
+
set undoEnabled to true
|
|
1733
|
+
set undoCommand to candidateName
|
|
1734
|
+
exit repeat
|
|
1735
|
+
end if
|
|
1736
|
+
end try
|
|
1737
|
+
end repeat
|
|
1738
|
+
end try
|
|
1739
|
+
set bladeEnabled to false
|
|
1740
|
+
try
|
|
1741
|
+
set bladeEnabled to enabled of menu item "Blade" of menu "Trim" of menu bar 1
|
|
1742
|
+
end try
|
|
1743
|
+
set inspectorName to ""
|
|
1744
|
+
set inspectorRole to ""
|
|
1745
|
+
if selectedCount is 0 and bladeEnabled then
|
|
1746
|
+
set selectedCount to 1
|
|
1747
|
+
if inspectorName is not "" then
|
|
1748
|
+
set selectedName to inspectorName
|
|
1749
|
+
set selectedRole to inspectorRole
|
|
1750
|
+
end if
|
|
1751
|
+
end if
|
|
1752
|
+
set focusedName to ""
|
|
1753
|
+
set focusedRole to ""
|
|
1754
|
+
set focusedDescription to ""
|
|
1755
|
+
try
|
|
1756
|
+
set focusedElement to value of attribute "AXFocusedUIElement"
|
|
1757
|
+
set focusedName to value of focusedElement as text
|
|
1758
|
+
set focusedRole to role of focusedElement as text
|
|
1759
|
+
set focusedDescription to description of focusedElement as text
|
|
1760
|
+
end try
|
|
1761
|
+
set frontState to frontmost as text
|
|
1762
|
+
return frontState & (ASCII character 31) & frontWindowName & (ASCII character 31) & selectedCount & (ASCII character 31) & selectedName & (ASCII character 31) & selectedRole & (ASCII character 31) & undoEnabled & (ASCII character 31) & bladeEnabled & (ASCII character 31) & focusedName & (ASCII character 31) & focusedRole & (ASCII character 31) & focusedDescription & (ASCII character 31) & "" & (ASCII character 31) & "" & (ASCII character 31) & frontWindowName & (ASCII character 31) & "false" & (ASCII character 31) & undoCommand
|
|
1763
|
+
end tell
|
|
1764
|
+
end tell`;
|
|
1765
|
+
}
|
|
1766
|
+
function searchMediaScript(query) {
|
|
1767
|
+
return `
|
|
1768
|
+
${browserSearchControlFinderScript()}
|
|
1769
|
+
${browserMediaTraversalScript()}
|
|
1770
|
+
tell application "System Events"
|
|
1771
|
+
tell process "Final Cut Pro"
|
|
1772
|
+
${activateFinalCutWindowAppleScript()}
|
|
1773
|
+
${requireFrontmostAppleScript()}
|
|
1774
|
+
set mainWindow to window "Final Cut Pro"
|
|
1775
|
+
set origin to position of mainWindow
|
|
1776
|
+
${browserSearchFieldScript()}
|
|
1777
|
+
set searchQuery to ${appleScriptString(query)}
|
|
1778
|
+
set value of searchField to searchQuery
|
|
1779
|
+
delay 0.5
|
|
1780
|
+
set output to my collectBrowserMedia(browserRoot, 0, searchQuery, origin, false, {}, "root")
|
|
1781
|
+
return output
|
|
1782
|
+
end tell
|
|
1783
|
+
end tell`;
|
|
1784
|
+
}
|
|
1785
|
+
function selectedBrowserMediaScript() {
|
|
1786
|
+
return `
|
|
1787
|
+
${browserSearchControlFinderScript()}
|
|
1788
|
+
${browserMediaTraversalScript()}
|
|
1789
|
+
tell application "System Events"
|
|
1790
|
+
tell process "Final Cut Pro"
|
|
1791
|
+
${activateFinalCutWindowAppleScript()}
|
|
1792
|
+
${requireFrontmostAppleScript()}
|
|
1793
|
+
set mainWindow to window "Final Cut Pro"
|
|
1794
|
+
set origin to position of mainWindow
|
|
1795
|
+
set output to ""
|
|
1796
|
+
set selectedCandidateCount to 0
|
|
1797
|
+
set selectedIdentityCount to 0
|
|
1798
|
+
set missingSourceIdentity to false
|
|
1799
|
+
set seenSourceIdentities to {}
|
|
1800
|
+
set browserRoot to mainWindow
|
|
1801
|
+
try
|
|
1802
|
+
set browserSearchResult to my findBrowserSearchControl(mainWindow, 0)
|
|
1803
|
+
if browserSearchResult is not missing value then set browserRoot to item 2 of browserSearchResult
|
|
1804
|
+
end try
|
|
1805
|
+
try
|
|
1806
|
+
set output to my collectSelectedBrowserMedia(browserRoot, 0, origin, false, {}, "root")
|
|
1807
|
+
if output is not "" then
|
|
1808
|
+
repeat with recordItem in my splitText(output, ASCII character 30)
|
|
1809
|
+
if recordItem is not "" then
|
|
1810
|
+
set selectedCandidateCount to selectedCandidateCount + 1
|
|
1811
|
+
set recordParts to my splitText(recordItem, ASCII character 31)
|
|
1812
|
+
set candidateSourceIdentity to item 4 of recordParts
|
|
1813
|
+
if candidateSourceIdentity is "" then
|
|
1814
|
+
set missingSourceIdentity to true
|
|
1815
|
+
else if seenSourceIdentities does not contain candidateSourceIdentity then
|
|
1816
|
+
set end of seenSourceIdentities to candidateSourceIdentity
|
|
1817
|
+
set selectedIdentityCount to selectedIdentityCount + 1
|
|
1818
|
+
end if
|
|
1819
|
+
end if
|
|
1820
|
+
end repeat
|
|
1821
|
+
end if
|
|
1822
|
+
on error
|
|
1823
|
+
error "FINAL_CUT_NATIVE_MEDIA_SELECTION_UNAVAILABLE: selected Browser media was not accessible"
|
|
1824
|
+
end try
|
|
1825
|
+
if selectedIdentityCount is 0 then
|
|
1826
|
+
if selectedCandidateCount is 0 then error "FINAL_CUT_NATIVE_MEDIA_SELECTION_UNAVAILABLE: no selected Browser media was exposed by Accessibility"
|
|
1827
|
+
if missingSourceIdentity then error "FINAL_CUT_NATIVE_MEDIA_ID_UNAVAILABLE: selected Browser media has no AXIdentifier"
|
|
1828
|
+
end if
|
|
1829
|
+
if selectedIdentityCount > 1 then error "FINAL_CUT_NATIVE_AMBIGUOUS_TARGET: multiple selected Browser media items were exposed"
|
|
1830
|
+
return output
|
|
1831
|
+
end tell
|
|
1832
|
+
end tell`;
|
|
1833
|
+
}
|
|
1834
|
+
function browserFocusScript() {
|
|
1835
|
+
return `
|
|
1836
|
+
${browserSearchControlFinderScript()}
|
|
1837
|
+
tell application "System Events"
|
|
1838
|
+
tell process "Final Cut Pro"
|
|
1839
|
+
${activateFinalCutWindowAppleScript()}
|
|
1840
|
+
${requireFrontmostAppleScript()}
|
|
1841
|
+
set mainWindow to window "Final Cut Pro"
|
|
1842
|
+
${browserSearchFieldScript()}
|
|
1843
|
+
return "browser-focused"
|
|
1844
|
+
end tell
|
|
1845
|
+
end tell`;
|
|
1846
|
+
}
|
|
1847
|
+
function browserSearchFieldScript() {
|
|
1848
|
+
return `
|
|
1849
|
+
set origin to position of mainWindow
|
|
1850
|
+
set searchFieldFound to false
|
|
1851
|
+
set searchField to missing value
|
|
1852
|
+
set searchButton to missing value
|
|
1853
|
+
set browserRoot to mainWindow
|
|
1854
|
+
try
|
|
1855
|
+
set focusedCandidate to value of attribute "AXFocusedUIElement"
|
|
1856
|
+
set focusedRole to role of focusedCandidate as text
|
|
1857
|
+
set focusedDescription to ""
|
|
1858
|
+
try
|
|
1859
|
+
set focusedDescription to description of focusedCandidate as text
|
|
1860
|
+
end try
|
|
1861
|
+
if focusedRole is "AXSearchField" or (focusedRole is "AXTextField" and (focusedDescription contains "search" or focusedDescription contains "Search")) then
|
|
1862
|
+
set searchField to focusedCandidate
|
|
1863
|
+
set searchFieldFound to true
|
|
1864
|
+
end if
|
|
1865
|
+
end try
|
|
1866
|
+
if not searchFieldFound then
|
|
1867
|
+
repeat with searchOffset in {368, 400, 340, 561, 531, 501}
|
|
1868
|
+
repeat with searchY in {52, 38}
|
|
1869
|
+
try
|
|
1870
|
+
click at {(item 1 of origin) + (searchOffset as integer), (item 2 of origin) + (searchY as integer)}
|
|
1871
|
+
delay 0.15
|
|
1872
|
+
set focusedCandidate to value of attribute "AXFocusedUIElement"
|
|
1873
|
+
set focusedRole to role of focusedCandidate as text
|
|
1874
|
+
set focusedDescription to ""
|
|
1875
|
+
try
|
|
1876
|
+
set focusedDescription to description of focusedCandidate as text
|
|
1877
|
+
end try
|
|
1878
|
+
if (focusedRole is "AXSearchField" or (focusedRole is "AXTextField" and (focusedDescription contains "search" or focusedDescription contains "Search"))) then
|
|
1879
|
+
set searchField to focusedCandidate
|
|
1880
|
+
set searchFieldFound to true
|
|
1881
|
+
exit repeat
|
|
1882
|
+
end if
|
|
1883
|
+
end try
|
|
1884
|
+
end repeat
|
|
1885
|
+
if searchFieldFound then exit repeat
|
|
1886
|
+
end repeat
|
|
1887
|
+
end if
|
|
1888
|
+
try
|
|
1889
|
+
if my revealBrowser(mainWindow, 0) then delay 0.5
|
|
1890
|
+
end try
|
|
1891
|
+
try
|
|
1892
|
+
set searchControlResult to my findBrowserSearchControl(mainWindow, 0)
|
|
1893
|
+
if searchControlResult is not missing value then
|
|
1894
|
+
set searchControl to item 1 of searchControlResult
|
|
1895
|
+
set browserRoot to item 2 of searchControlResult
|
|
1896
|
+
set searchRole to role of searchControl as text
|
|
1897
|
+
if searchRole is "AXSearchField" or searchRole is "AXTextField" then
|
|
1898
|
+
set searchField to searchControl
|
|
1899
|
+
set searchFieldFound to true
|
|
1900
|
+
else if searchRole is "AXButton" then
|
|
1901
|
+
set searchButton to searchControl
|
|
1902
|
+
end if
|
|
1903
|
+
end if
|
|
1904
|
+
end try
|
|
1905
|
+
if not searchFieldFound then
|
|
1906
|
+
try
|
|
1907
|
+
set searchControlResult to my findBrowserSearchControl(mainWindow, 0)
|
|
1908
|
+
if searchControlResult is not missing value then
|
|
1909
|
+
set searchControl to item 1 of searchControlResult
|
|
1910
|
+
set browserRoot to item 2 of searchControlResult
|
|
1911
|
+
set searchRole to role of searchControl as text
|
|
1912
|
+
if searchRole is "AXSearchField" or searchRole is "AXTextField" then
|
|
1913
|
+
set searchField to searchControl
|
|
1914
|
+
set searchFieldFound to true
|
|
1915
|
+
else if searchRole is "AXButton" then
|
|
1916
|
+
set searchButton to searchControl
|
|
1917
|
+
end if
|
|
1918
|
+
end if
|
|
1919
|
+
end try
|
|
1920
|
+
end if
|
|
1921
|
+
if not searchFieldFound and searchButton is missing value then
|
|
1922
|
+
try
|
|
1923
|
+
set directSearchButton to UI element 3 of UI element 3 of UI element 1 of UI element 2 of UI element 1 of UI element 1 of UI element 1 of mainWindow
|
|
1924
|
+
set directSearchDescription to description of directSearchButton as text
|
|
1925
|
+
if directSearchDescription contains "search" or directSearchDescription contains "Search" then
|
|
1926
|
+
set searchButton to directSearchButton
|
|
1927
|
+
end if
|
|
1928
|
+
end try
|
|
1929
|
+
end if
|
|
1930
|
+
if not searchFieldFound then
|
|
1931
|
+
if searchButton is not missing value then
|
|
1932
|
+
try
|
|
1933
|
+
perform action "AXPress" of searchButton
|
|
1934
|
+
delay 0.2
|
|
1935
|
+
set focusedCandidate to value of attribute "AXFocusedUIElement"
|
|
1936
|
+
set focusedRole to role of focusedCandidate as text
|
|
1937
|
+
set focusedDescription to ""
|
|
1938
|
+
try
|
|
1939
|
+
set focusedDescription to description of focusedCandidate as text
|
|
1940
|
+
end try
|
|
1941
|
+
if (focusedRole is "AXSearchField" or (focusedRole is "AXTextField" and (focusedDescription contains "search" or focusedDescription contains "Search"))) then
|
|
1942
|
+
set searchField to focusedCandidate
|
|
1943
|
+
set searchFieldFound to true
|
|
1944
|
+
end if
|
|
1945
|
+
end try
|
|
1946
|
+
end if
|
|
1947
|
+
end if
|
|
1948
|
+
if not searchFieldFound then error "FINAL_CUT_NATIVE_SEARCH_UNAVAILABLE: Browser search field was not found through Accessibility or coordinate fallback"
|
|
1949
|
+
set searchRole to role of searchField as text
|
|
1950
|
+
if searchRole is not "AXTextField" and searchRole is not "AXSearchField" then error "FINAL_CUT_NATIVE_SEARCH_UNAVAILABLE: Browser search field was not hit"
|
|
1951
|
+
try
|
|
1952
|
+
perform action "AXPress" of searchField
|
|
1953
|
+
end try
|
|
1954
|
+
try
|
|
1955
|
+
set value of attribute "AXFocused" of searchField to true
|
|
1956
|
+
end try
|
|
1957
|
+
delay 0.2`;
|
|
1958
|
+
}
|
|
1959
|
+
function browserSearchControlFinderScript() {
|
|
1960
|
+
return `
|
|
1961
|
+
using terms from application "System Events"
|
|
1962
|
+
on findBrowserSearchControl(containerItem, depth)
|
|
1963
|
+
if depth > 12 then return missing value
|
|
1964
|
+
set candidateItems to UI elements of containerItem
|
|
1965
|
+
repeat with candidateIndex in my orderedChildIndices(containerItem)
|
|
1966
|
+
try
|
|
1967
|
+
set candidate to item (contents of candidateIndex) of candidateItems
|
|
1968
|
+
set candidateRole to role of candidate as text
|
|
1969
|
+
if candidateRole is "AXSearchField" then
|
|
1970
|
+
return {candidate, containerItem}
|
|
1971
|
+
end if
|
|
1972
|
+
if candidateRole is "AXTextField" then
|
|
1973
|
+
set candidateName to ""
|
|
1974
|
+
set candidateDescription to ""
|
|
1975
|
+
try
|
|
1976
|
+
set candidateName to name of candidate as text
|
|
1977
|
+
end try
|
|
1978
|
+
try
|
|
1979
|
+
set candidateDescription to description of candidate as text
|
|
1980
|
+
end try
|
|
1981
|
+
if candidateName contains "search" or candidateName contains "Search" or candidateDescription contains "search" or candidateDescription contains "Search" then
|
|
1982
|
+
return {candidate, containerItem}
|
|
1983
|
+
end if
|
|
1984
|
+
end if
|
|
1985
|
+
if candidateRole is "AXButton" then
|
|
1986
|
+
set candidateDescription to description of candidate as text
|
|
1987
|
+
if candidateDescription contains "search" or candidateDescription contains "Search" then
|
|
1988
|
+
return {candidate, containerItem}
|
|
1989
|
+
end if
|
|
1990
|
+
end if
|
|
1991
|
+
end try
|
|
1992
|
+
try
|
|
1993
|
+
set nestedCandidate to my findBrowserSearchControl(candidate, depth + 1)
|
|
1994
|
+
if nestedCandidate is not missing value then
|
|
1995
|
+
return nestedCandidate
|
|
1996
|
+
end if
|
|
1997
|
+
end try
|
|
1998
|
+
end repeat
|
|
1999
|
+
return missing value
|
|
2000
|
+
end findBrowserSearchControl
|
|
2001
|
+
|
|
2002
|
+
on revealBrowser(containerItem, depth)
|
|
2003
|
+
if depth > 8 then return false
|
|
2004
|
+
set candidateItems to UI elements of containerItem
|
|
2005
|
+
repeat with candidateIndex in my orderedChildIndices(containerItem)
|
|
2006
|
+
try
|
|
2007
|
+
set candidate to item (contents of candidateIndex) of candidateItems
|
|
2008
|
+
set candidateRole to role of candidate as text
|
|
2009
|
+
set candidateName to ""
|
|
2010
|
+
set candidateDescription to ""
|
|
2011
|
+
try
|
|
2012
|
+
set candidateName to name of candidate as text
|
|
2013
|
+
end try
|
|
2014
|
+
try
|
|
2015
|
+
set candidateDescription to description of candidate as text
|
|
2016
|
+
end try
|
|
2017
|
+
if candidateRole is "AXCheckBox" and (candidateName contains "Browser" or candidateDescription contains "Browser" or candidateDescription contains "browser") then
|
|
2018
|
+
set browserVisible to false
|
|
2019
|
+
try
|
|
2020
|
+
set browserVisible to (value of candidate as boolean)
|
|
2021
|
+
end try
|
|
2022
|
+
if not browserVisible then perform action "AXPress" of candidate
|
|
2023
|
+
return true
|
|
2024
|
+
end if
|
|
2025
|
+
end try
|
|
2026
|
+
try
|
|
2027
|
+
if my revealBrowser(candidate, depth + 1) then return true
|
|
2028
|
+
end try
|
|
2029
|
+
end repeat
|
|
2030
|
+
return false
|
|
2031
|
+
end revealBrowser
|
|
2032
|
+
|
|
2033
|
+
on orderedChildIndices(containerItem)
|
|
2034
|
+
set childCount to count of UI elements of containerItem
|
|
2035
|
+
set orderedIndices to {}
|
|
2036
|
+
repeat with candidateIndex from 1 to childCount
|
|
2037
|
+
set end of orderedIndices to contents of candidateIndex
|
|
2038
|
+
end repeat
|
|
2039
|
+
return orderedIndices
|
|
2040
|
+
end orderedChildIndices
|
|
2041
|
+
|
|
2042
|
+
end using terms from`;
|
|
2043
|
+
}
|
|
2044
|
+
function browserMediaTraversalScript() {
|
|
2045
|
+
return `
|
|
2046
|
+
using terms from application "System Events"
|
|
2047
|
+
on splitText(valueText, delimiter)
|
|
2048
|
+
set oldDelimiters to AppleScript's text item delimiters
|
|
2049
|
+
set AppleScript's text item delimiters to delimiter
|
|
2050
|
+
set parts to text items of valueText
|
|
2051
|
+
set AppleScript's text item delimiters to oldDelimiters
|
|
2052
|
+
return parts
|
|
2053
|
+
end splitText
|
|
2054
|
+
|
|
2055
|
+
on mediaContainer(containerItem, inheritedContext)
|
|
2056
|
+
set containerText to ""
|
|
2057
|
+
try
|
|
2058
|
+
set containerText to description of containerItem as text
|
|
2059
|
+
end try
|
|
2060
|
+
if containerText is "" then
|
|
2061
|
+
try
|
|
2062
|
+
set containerText to name of containerItem as text
|
|
2063
|
+
end try
|
|
2064
|
+
end if
|
|
2065
|
+
if containerText is "" then
|
|
2066
|
+
try
|
|
2067
|
+
set containerText to value of containerItem as text
|
|
2068
|
+
end try
|
|
2069
|
+
end if
|
|
2070
|
+
if containerText contains "Browser" or containerText contains "browser" or containerText contains "Events" or containerText contains "events" or containerText contains "Event" or containerText contains "event" then return true
|
|
2071
|
+
return inheritedContext
|
|
2072
|
+
end mediaContainer
|
|
2073
|
+
|
|
2074
|
+
on accessibilityMediaIdentity(candidate, candidateName, candidateRole, mediaContext, browserPath)
|
|
2075
|
+
if not mediaContext or candidateName is "" then return ""
|
|
2076
|
+
if candidateRole is not "AXGroup" and candidateRole is not "AXBrowserMedia" and candidateRole is not "AXRow" and candidateRole is not "AXCell" then
|
|
2077
|
+
return ""
|
|
2078
|
+
end if
|
|
2079
|
+
return "fcp-ax://browser/" & browserPath & "|" & candidateRole & "|" & candidateName
|
|
2080
|
+
end accessibilityMediaIdentity
|
|
2081
|
+
|
|
2082
|
+
on browserMediaRole(candidateRole, mediaContext, candidateSelected, candidateSourceIdentity)
|
|
2083
|
+
if candidateRole is "AXBrowserMedia" or candidateRole is "AXRow" or candidateRole is "AXCell" then return true
|
|
2084
|
+
if candidateRole is "AXButton" then return mediaContext and candidateSourceIdentity is not ""
|
|
2085
|
+
if candidateRole is "AXGroup" or candidateRole is "AXStaticText" or candidateRole is "AXImage" then return mediaContext or (candidateSelected and candidateSourceIdentity is not "")
|
|
2086
|
+
return false
|
|
2087
|
+
end browserMediaRole
|
|
2088
|
+
|
|
2089
|
+
on browserRegion(candidatePosition, origin, mediaContext)
|
|
2090
|
+
if mediaContext then return true
|
|
2091
|
+
set candidateX to item 1 of candidatePosition
|
|
2092
|
+
set candidateY to item 2 of candidatePosition
|
|
2093
|
+
set originX to item 1 of origin
|
|
2094
|
+
set originY to item 2 of origin
|
|
2095
|
+
return candidateX >= originX and candidateX < (originX + 900) and candidateY >= (originY + 60) and candidateY < (originY + 650)
|
|
2096
|
+
end browserRegion
|
|
2097
|
+
|
|
2098
|
+
on collectBrowserMedia(containerItem, depth, searchQuery, origin, inheritedContext, seenIdentities, browserPath)
|
|
2099
|
+
if depth > 12 then return ""
|
|
2100
|
+
set output to ""
|
|
2101
|
+
set mediaContext to my mediaContainer(containerItem, inheritedContext)
|
|
2102
|
+
tell application "System Events"
|
|
2103
|
+
try
|
|
2104
|
+
set candidateItems to UI elements of containerItem
|
|
2105
|
+
repeat with candidateIndex from 1 to (count of candidateItems)
|
|
2106
|
+
try
|
|
2107
|
+
set candidate to contents of item candidateIndex of candidateItems
|
|
2108
|
+
set candidatePath to browserPath & "/" & (candidateIndex as text)
|
|
2109
|
+
set candidateRole to role of candidate as text
|
|
2110
|
+
set candidateName to ""
|
|
2111
|
+
try
|
|
2112
|
+
set candidateName to value of candidate as text
|
|
2113
|
+
end try
|
|
2114
|
+
if candidateName is "missing value" then set candidateName to ""
|
|
2115
|
+
if candidateName is "" then
|
|
2116
|
+
try
|
|
2117
|
+
set candidateName to name of candidate as text
|
|
2118
|
+
end try
|
|
2119
|
+
end if
|
|
2120
|
+
if candidateName is "missing value" then set candidateName to ""
|
|
2121
|
+
if candidateName is "" then
|
|
2122
|
+
try
|
|
2123
|
+
set candidateName to description of candidate as text
|
|
2124
|
+
end try
|
|
2125
|
+
end if
|
|
2126
|
+
if candidateName is "missing value" then set candidateName to ""
|
|
2127
|
+
set candidateSelected to false
|
|
2128
|
+
try
|
|
2129
|
+
set candidateSelected to (selected of candidate) is true
|
|
2130
|
+
end try
|
|
2131
|
+
set candidateSourceIdentity to ""
|
|
2132
|
+
try
|
|
2133
|
+
set candidateSourceIdentity to value of attribute "AXIdentifier" of candidate as text
|
|
2134
|
+
end try
|
|
2135
|
+
set candidatePosition to position of candidate
|
|
2136
|
+
set candidateMediaContext to my mediaContainer(candidate, mediaContext)
|
|
2137
|
+
set isBrowserMedia to my browserMediaRole(candidateRole, candidateMediaContext, candidateSelected, candidateSourceIdentity)
|
|
2138
|
+
set inBrowserRegion to my browserRegion(candidatePosition, origin, candidateMediaContext)
|
|
2139
|
+
if candidateSourceIdentity is "" and isBrowserMedia then set candidateSourceIdentity to my accessibilityMediaIdentity(candidate, candidateName, candidateRole, candidateMediaContext, candidatePath)
|
|
2140
|
+
if candidateName is not "" and candidateSourceIdentity is not "" and isBrowserMedia and inBrowserRegion and candidateName contains searchQuery then
|
|
2141
|
+
if seenIdentities does not contain candidateSourceIdentity then
|
|
2142
|
+
set end of seenIdentities to candidateSourceIdentity
|
|
2143
|
+
set output to output & candidateName & (ASCII character 31) & candidateRole & (ASCII character 31) & candidateSourceIdentity & (ASCII character 31) & candidateSourceIdentity & (ASCII character 30)
|
|
2144
|
+
end if
|
|
2145
|
+
end if
|
|
2146
|
+
set output to output & my collectBrowserMedia(candidate, depth + 1, searchQuery, origin, candidateMediaContext, seenIdentities, candidatePath)
|
|
2147
|
+
on error
|
|
2148
|
+
-- Ignore inaccessible descendants and continue enumerating Browser results.
|
|
2149
|
+
end try
|
|
2150
|
+
end repeat
|
|
2151
|
+
on error
|
|
2152
|
+
error "FINAL_CUT_NATIVE_SEARCH_UNAVAILABLE: Browser media results were not accessible"
|
|
2153
|
+
end try
|
|
2154
|
+
end tell
|
|
2155
|
+
return output
|
|
2156
|
+
end collectBrowserMedia
|
|
2157
|
+
|
|
2158
|
+
on collectSelectedBrowserMedia(containerItem, depth, origin, inheritedContext, seenIdentities, browserPath)
|
|
2159
|
+
if depth > 12 then return ""
|
|
2160
|
+
set output to ""
|
|
2161
|
+
set mediaContext to my mediaContainer(containerItem, inheritedContext)
|
|
2162
|
+
tell application "System Events"
|
|
2163
|
+
try
|
|
2164
|
+
set candidateItems to UI elements of containerItem
|
|
2165
|
+
repeat with candidateIndex from 1 to (count of candidateItems)
|
|
2166
|
+
try
|
|
2167
|
+
set candidate to contents of item candidateIndex of candidateItems
|
|
2168
|
+
set candidatePath to browserPath & "/" & (candidateIndex as text)
|
|
2169
|
+
set candidateSelected to false
|
|
2170
|
+
try
|
|
2171
|
+
set candidateSelected to (selected of candidate) is true
|
|
2172
|
+
end try
|
|
2173
|
+
set candidateName to ""
|
|
2174
|
+
try
|
|
2175
|
+
set candidateName to value of candidate as text
|
|
2176
|
+
end try
|
|
2177
|
+
if candidateName is "missing value" then set candidateName to ""
|
|
2178
|
+
if candidateName is "" then
|
|
2179
|
+
try
|
|
2180
|
+
set candidateName to name of candidate as text
|
|
2181
|
+
end try
|
|
2182
|
+
end if
|
|
2183
|
+
if candidateName is "missing value" then set candidateName to ""
|
|
2184
|
+
if candidateName is "" then
|
|
2185
|
+
try
|
|
2186
|
+
set candidateName to description of candidate as text
|
|
2187
|
+
end try
|
|
2188
|
+
end if
|
|
2189
|
+
if candidateName is "missing value" then set candidateName to ""
|
|
2190
|
+
set candidateRole to role of candidate as text
|
|
2191
|
+
set candidatePosition to position of candidate
|
|
2192
|
+
set candidateSourceIdentity to ""
|
|
2193
|
+
try
|
|
2194
|
+
set candidateSourceIdentity to value of attribute "AXIdentifier" of candidate as text
|
|
2195
|
+
end try
|
|
2196
|
+
set candidateMediaContext to my mediaContainer(candidate, mediaContext)
|
|
2197
|
+
set isBrowserMedia to my browserMediaRole(candidateRole, candidateMediaContext, candidateSelected, candidateSourceIdentity)
|
|
2198
|
+
set inBrowserRegion to my browserRegion(candidatePosition, origin, candidateMediaContext)
|
|
2199
|
+
if candidateSourceIdentity is "" and isBrowserMedia then set candidateSourceIdentity to my accessibilityMediaIdentity(candidate, candidateName, candidateRole, candidateMediaContext, candidatePath)
|
|
2200
|
+
if candidateSelected and candidateName is not "" and isBrowserMedia and inBrowserRegion then
|
|
2201
|
+
if candidateSourceIdentity is "" or seenIdentities does not contain candidateSourceIdentity then
|
|
2202
|
+
if candidateSourceIdentity is not "" then set end of seenIdentities to candidateSourceIdentity
|
|
2203
|
+
set output to output & candidateName & (ASCII character 31) & candidateRole & (ASCII character 31) & candidateSourceIdentity & (ASCII character 31) & candidateSourceIdentity & (ASCII character 30)
|
|
2204
|
+
end if
|
|
2205
|
+
end if
|
|
2206
|
+
set output to output & my collectSelectedBrowserMedia(candidate, depth + 1, origin, candidateMediaContext, seenIdentities, candidatePath)
|
|
2207
|
+
on error
|
|
2208
|
+
-- Ignore inaccessible descendants and continue looking for the selection.
|
|
2209
|
+
end try
|
|
2210
|
+
end repeat
|
|
2211
|
+
on error
|
|
2212
|
+
error "FINAL_CUT_NATIVE_MEDIA_SELECTION_UNAVAILABLE: selected Browser media was not accessible"
|
|
2213
|
+
end try
|
|
2214
|
+
end tell
|
|
2215
|
+
return output
|
|
2216
|
+
end collectSelectedBrowserMedia
|
|
2217
|
+
|
|
2218
|
+
on pressBrowserMedia(containerItem, depth, origin, inheritedContext, targetSourceIdentity, targetIdentity, browserPath)
|
|
2219
|
+
if depth > 12 then return false
|
|
2220
|
+
set mediaContext to my mediaContainer(containerItem, inheritedContext)
|
|
2221
|
+
tell application "System Events"
|
|
2222
|
+
try
|
|
2223
|
+
set candidateItems to UI elements of containerItem
|
|
2224
|
+
repeat with candidateIndex from 1 to (count of candidateItems)
|
|
2225
|
+
try
|
|
2226
|
+
set candidate to contents of item candidateIndex of candidateItems
|
|
2227
|
+
set candidatePath to browserPath & "/" & (candidateIndex as text)
|
|
2228
|
+
set candidateRole to role of candidate as text
|
|
2229
|
+
set candidateName to ""
|
|
2230
|
+
try
|
|
2231
|
+
set candidateName to value of candidate as text
|
|
2232
|
+
end try
|
|
2233
|
+
if candidateName is "missing value" then set candidateName to ""
|
|
2234
|
+
if candidateName is "" then
|
|
2235
|
+
try
|
|
2236
|
+
set candidateName to name of candidate as text
|
|
2237
|
+
end try
|
|
2238
|
+
end if
|
|
2239
|
+
if candidateName is "missing value" then set candidateName to ""
|
|
2240
|
+
if candidateName is "" then
|
|
2241
|
+
try
|
|
2242
|
+
set candidateName to description of candidate as text
|
|
2243
|
+
end try
|
|
2244
|
+
end if
|
|
2245
|
+
if candidateName is "missing value" then set candidateName to ""
|
|
2246
|
+
set candidatePosition to position of candidate
|
|
2247
|
+
set candidateSourceIdentity to ""
|
|
2248
|
+
try
|
|
2249
|
+
set candidateSourceIdentity to value of attribute "AXIdentifier" of candidate as text
|
|
2250
|
+
end try
|
|
2251
|
+
set candidateMediaContext to my mediaContainer(candidate, mediaContext)
|
|
2252
|
+
set candidateSelected to false
|
|
2253
|
+
try
|
|
2254
|
+
set candidateSelected to (selected of candidate) is true
|
|
2255
|
+
end try
|
|
2256
|
+
if candidateSourceIdentity is "" and my browserMediaRole(candidateRole, candidateMediaContext, candidateSelected, candidateSourceIdentity) then set candidateSourceIdentity to my accessibilityMediaIdentity(candidate, candidateName, candidateRole, candidateMediaContext, candidatePath)
|
|
2257
|
+
if my browserMediaRole(candidateRole, candidateMediaContext, candidateSelected, candidateSourceIdentity) and my browserRegion(candidatePosition, origin, candidateMediaContext) then
|
|
2258
|
+
set candidateIdentity to (candidatePosition as text) & "|" & ((size of candidate) as text)
|
|
2259
|
+
if (targetSourceIdentity is not "" and candidateSourceIdentity is targetSourceIdentity) or (targetSourceIdentity is "" and candidateIdentity is targetIdentity) then
|
|
2260
|
+
if candidateRole is "AXGroup" and targetSourceIdentity starts with "fcp-ax://browser/" then
|
|
2261
|
+
set thumbnailClicked to false
|
|
2262
|
+
try
|
|
2263
|
+
set candidateChildren to UI elements of candidate
|
|
2264
|
+
repeat with thumbnailIndex from 1 to (count of candidateChildren)
|
|
2265
|
+
set thumbnailCandidate to contents of item thumbnailIndex of candidateChildren
|
|
2266
|
+
if (role of thumbnailCandidate as text) is "AXImage" then
|
|
2267
|
+
set thumbnailPosition to position of thumbnailCandidate
|
|
2268
|
+
set thumbnailSize to size of thumbnailCandidate
|
|
2269
|
+
click at {(item 1 of thumbnailPosition) + ((item 1 of thumbnailSize) / 2), (item 2 of thumbnailPosition) + ((item 2 of thumbnailSize) / 2)}
|
|
2270
|
+
set thumbnailClicked to true
|
|
2271
|
+
exit repeat
|
|
2272
|
+
end if
|
|
2273
|
+
end repeat
|
|
2274
|
+
end try
|
|
2275
|
+
if not thumbnailClicked then perform action "AXPress" of candidate
|
|
2276
|
+
else
|
|
2277
|
+
perform action "AXPress" of candidate
|
|
2278
|
+
end if
|
|
2279
|
+
return true
|
|
2280
|
+
end if
|
|
2281
|
+
end if
|
|
2282
|
+
if my pressBrowserMedia(candidate, depth + 1, origin, candidateMediaContext, targetSourceIdentity, targetIdentity, candidatePath) then return true
|
|
2283
|
+
on error
|
|
2284
|
+
-- Ignore inaccessible descendants and continue looking for the target.
|
|
2285
|
+
end try
|
|
2286
|
+
end repeat
|
|
2287
|
+
end try
|
|
2288
|
+
end tell
|
|
2289
|
+
return false
|
|
2290
|
+
end pressBrowserMedia
|
|
2291
|
+
end using terms from`;
|
|
2292
|
+
}
|
|
2293
|
+
function browserMediaDiagnosticScript(query) {
|
|
2294
|
+
return `
|
|
2295
|
+
using terms from application "System Events"
|
|
2296
|
+
on collectBrowserMediaDiagnostics(containerItem, depth, searchQuery, ancestors)
|
|
2297
|
+
if depth > 12 then return ""
|
|
2298
|
+
set output to ""
|
|
2299
|
+
set nextAncestors to ancestors
|
|
2300
|
+
try
|
|
2301
|
+
set containerDescription to description of containerItem as text
|
|
2302
|
+
if containerDescription is not "" then set nextAncestors to ancestors & containerDescription & " > "
|
|
2303
|
+
end try
|
|
2304
|
+
tell application "System Events"
|
|
2305
|
+
try
|
|
2306
|
+
repeat with candidate in UI elements of containerItem
|
|
2307
|
+
try
|
|
2308
|
+
set candidateValue to ""
|
|
2309
|
+
try
|
|
2310
|
+
set candidateValue to value of candidate as text
|
|
2311
|
+
end try
|
|
2312
|
+
set candidateName to candidateValue
|
|
2313
|
+
if candidateName is "" then
|
|
2314
|
+
try
|
|
2315
|
+
set candidateName to name of candidate as text
|
|
2316
|
+
end try
|
|
2317
|
+
end if
|
|
2318
|
+
if candidateName contains searchQuery and (length of output) < 8000 then
|
|
2319
|
+
set candidateRole to role of candidate as text
|
|
2320
|
+
set candidateDescription to ""
|
|
2321
|
+
try
|
|
2322
|
+
set candidateDescription to description of candidate as text
|
|
2323
|
+
end try
|
|
2324
|
+
set candidateSelected to "false"
|
|
2325
|
+
try
|
|
2326
|
+
set candidateSelected to (selected of candidate) as text
|
|
2327
|
+
end try
|
|
2328
|
+
set candidateSourceIdentity to ""
|
|
2329
|
+
try
|
|
2330
|
+
set candidateSourceIdentity to value of attribute "AXIdentifier" of candidate as text
|
|
2331
|
+
end try
|
|
2332
|
+
set candidateBounds to ""
|
|
2333
|
+
try
|
|
2334
|
+
set candidateBounds to ((position of candidate) as text) & "|" & ((size of candidate) as text)
|
|
2335
|
+
end try
|
|
2336
|
+
set output to output & candidateRole & (ASCII character 31) & candidateValue & (ASCII character 31) & candidateDescription & (ASCII character 31) & candidateSelected & (ASCII character 31) & candidateSourceIdentity & (ASCII character 31) & candidateBounds & (ASCII character 31) & nextAncestors & candidateDescription & (ASCII character 30)
|
|
2337
|
+
end if
|
|
2338
|
+
set output to output & my collectBrowserMediaDiagnostics(candidate, depth + 1, searchQuery, nextAncestors)
|
|
2339
|
+
on error
|
|
2340
|
+
-- Ignore inaccessible descendants and continue collecting diagnostics.
|
|
2341
|
+
end try
|
|
2342
|
+
end repeat
|
|
2343
|
+
end try
|
|
2344
|
+
end tell
|
|
2345
|
+
return output
|
|
2346
|
+
end collectBrowserMediaDiagnostics
|
|
2347
|
+
end using terms from
|
|
2348
|
+
tell application "System Events"
|
|
2349
|
+
tell process "Final Cut Pro"
|
|
2350
|
+
${activateFinalCutWindowAppleScript()}
|
|
2351
|
+
${requireFrontmostAppleScript()}
|
|
2352
|
+
set mainWindow to window "Final Cut Pro"
|
|
2353
|
+
set output to my collectBrowserMediaDiagnostics(mainWindow, 0, ${appleScriptString(query)}, "")
|
|
2354
|
+
return output
|
|
2355
|
+
end tell
|
|
2356
|
+
end tell`;
|
|
2357
|
+
}
|
|
2358
|
+
function importMediaScript(sourceDirectory, fileName) {
|
|
2359
|
+
return `
|
|
2360
|
+
tell application "System Events"
|
|
2361
|
+
tell process "Final Cut Pro"
|
|
2362
|
+
-- FRAMEKIT_IMPORT_MEDIA
|
|
2363
|
+
set frontmost to true
|
|
2364
|
+
if not (exists window "Media Import") then keystroke "i" using {command down}
|
|
2365
|
+
set mediaImportWindow to missing value
|
|
2366
|
+
repeat 40 times
|
|
2367
|
+
if exists window "Media Import" then
|
|
2368
|
+
set mediaImportWindow to window "Media Import"
|
|
2369
|
+
exit repeat
|
|
2370
|
+
end if
|
|
2371
|
+
delay 0.1
|
|
2372
|
+
end repeat
|
|
2373
|
+
if mediaImportWindow is missing value then error "FINAL_CUT_NATIVE_MEDIA_IMPORT_UI_UNAVAILABLE: Media Import window did not open"
|
|
2374
|
+
keystroke "g" using {command down, shift down}
|
|
2375
|
+
set goSheet to missing value
|
|
2376
|
+
repeat 30 times
|
|
2377
|
+
if exists sheet 1 of mediaImportWindow then
|
|
2378
|
+
set goSheet to sheet 1 of mediaImportWindow
|
|
2379
|
+
exit repeat
|
|
2380
|
+
end if
|
|
2381
|
+
delay 0.1
|
|
2382
|
+
end repeat
|
|
2383
|
+
if goSheet is missing value then error "FINAL_CUT_NATIVE_MEDIA_IMPORT_UI_UNAVAILABLE: Go to folder sheet did not open"
|
|
2384
|
+
set value of text field 1 of goSheet to ${appleScriptString(sourceDirectory)}
|
|
2385
|
+
click button "Go" of goSheet
|
|
2386
|
+
repeat 30 times
|
|
2387
|
+
if not (exists sheet 1 of mediaImportWindow) then exit repeat
|
|
2388
|
+
delay 0.1
|
|
2389
|
+
end repeat
|
|
2390
|
+
if exists sheet 1 of mediaImportWindow then error "FINAL_CUT_NATIVE_MEDIA_IMPORT_UI_UNAVAILABLE: Go to folder sheet did not close"
|
|
2391
|
+
set importWindowPosition to position of mediaImportWindow
|
|
2392
|
+
set importWindowSize to size of mediaImportWindow
|
|
2393
|
+
click at {(item 1 of importWindowPosition) + 400, (item 2 of importWindowPosition) + (item 2 of importWindowSize) - 140}
|
|
2394
|
+
keystroke ${appleScriptString(fileName)}
|
|
2395
|
+
delay 0.2
|
|
2396
|
+
set importButton to missing value
|
|
2397
|
+
repeat 40 times
|
|
2398
|
+
try
|
|
2399
|
+
if exists button "Import All" of mediaImportWindow then set importButton to button "Import All" of mediaImportWindow
|
|
2400
|
+
if importButton is missing value and exists button "Import Selected" of mediaImportWindow then set importButton to button "Import Selected" of mediaImportWindow
|
|
2401
|
+
if importButton is not missing value and enabled of importButton then exit repeat
|
|
2402
|
+
end try
|
|
2403
|
+
delay 0.1
|
|
2404
|
+
end repeat
|
|
2405
|
+
if importButton is missing value or (enabled of importButton) is false then error "FINAL_CUT_NATIVE_MEDIA_IMPORT_UI_UNAVAILABLE: no enabled import button"
|
|
2406
|
+
click importButton
|
|
2407
|
+
repeat 20 times
|
|
2408
|
+
if exists window "Processing Files" then exit repeat
|
|
2409
|
+
if not (exists window "Media Import") then exit repeat
|
|
2410
|
+
delay 0.1
|
|
2411
|
+
end repeat
|
|
2412
|
+
repeat 100 times
|
|
2413
|
+
if not (exists window "Processing Files") then exit repeat
|
|
2414
|
+
delay 0.1
|
|
2415
|
+
end repeat
|
|
2416
|
+
if exists window "Processing Files" then error "FINAL_CUT_NATIVE_MEDIA_IMPORT_UI_UNAVAILABLE: Final Cut is still processing the import"
|
|
2417
|
+
if exists window "Media Import" then
|
|
2418
|
+
repeat with candidate in buttons of mediaImportWindow
|
|
2419
|
+
try
|
|
2420
|
+
if (description of candidate as text) is "close button" then
|
|
2421
|
+
click candidate
|
|
2422
|
+
exit repeat
|
|
2423
|
+
end if
|
|
2424
|
+
end try
|
|
2425
|
+
end repeat
|
|
2426
|
+
repeat 20 times
|
|
2427
|
+
if not (exists window "Media Import") then exit repeat
|
|
2428
|
+
delay 0.1
|
|
2429
|
+
end repeat
|
|
2430
|
+
if exists window "Media Import" then error "FINAL_CUT_NATIVE_MEDIA_IMPORT_UI_UNAVAILABLE: Media Import window did not close"
|
|
2431
|
+
end if
|
|
2432
|
+
return "import-requested"
|
|
2433
|
+
end tell
|
|
2434
|
+
end tell`;
|
|
2435
|
+
}
|
|
2436
|
+
function selectMediaScript(match) {
|
|
2437
|
+
return `
|
|
2438
|
+
${browserSearchControlFinderScript()}
|
|
2439
|
+
${browserMediaTraversalScript()}
|
|
2440
|
+
tell application "System Events"
|
|
2441
|
+
tell process "Final Cut Pro"
|
|
2442
|
+
${activateFinalCutWindowAppleScript()}
|
|
2443
|
+
if not frontmost then error number -1719
|
|
2444
|
+
set mainWindow to window "Final Cut Pro"
|
|
2445
|
+
${browserSearchFieldScript()}
|
|
2446
|
+
set value of searchField to ${appleScriptString(match.name)}
|
|
2447
|
+
delay 0.5
|
|
2448
|
+
set origin to position of mainWindow
|
|
2449
|
+
set targetSourceIdentity to ${appleScriptString(match.sourceIdentity ?? "")}
|
|
2450
|
+
set targetIdentity to ${appleScriptString(match.identity ?? "")}
|
|
2451
|
+
if targetSourceIdentity is "" and targetIdentity is "" then error "FINAL_CUT_NATIVE_MEDIA_SELECTION_UNAVAILABLE: Browser result has no stable identity"
|
|
2452
|
+
if my pressBrowserMedia(browserRoot, 0, origin, false, targetSourceIdentity, targetIdentity, "root") then return "selected"
|
|
2453
|
+
error "FINAL_CUT_NATIVE_MEDIA_SELECTION_UNAVAILABLE: Browser result could not be selected"
|
|
2454
|
+
end tell
|
|
2455
|
+
end tell`;
|
|
2456
|
+
}
|
|
2457
|
+
function locateOccurrenceScript(match, scanAll) {
|
|
2458
|
+
const timelineOffsets = scanAll
|
|
2459
|
+
? [40, 160, 224, 256, 400, 640, 880, 1120, 1360, 1500].join(", ")
|
|
2460
|
+
: "800";
|
|
2461
|
+
return `
|
|
2462
|
+
tell application "System Events"
|
|
2463
|
+
tell process "Final Cut Pro"
|
|
2464
|
+
${requireFrontmostAppleScript()}
|
|
2465
|
+
set sourceIdentity to ${appleScriptString(match.sourceIdentity ?? "")}
|
|
2466
|
+
if sourceIdentity is "" then error "FINAL_CUT_NATIVE_MEDIA_ID_UNAVAILABLE: timeline lookup requires a shared source-media identifier"
|
|
2467
|
+
set mainWindow to window "Final Cut Pro"
|
|
2468
|
+
set origin to position of mainWindow
|
|
2469
|
+
set timelineSelection to click at {(item 1 of origin) + 800, (item 2 of origin) + 650}
|
|
2470
|
+
key code 115
|
|
2471
|
+
repeat 30 times
|
|
2472
|
+
key code 124
|
|
2473
|
+
end repeat
|
|
2474
|
+
set output to ""
|
|
2475
|
+
set inMatch to false
|
|
2476
|
+
set lastMatchIdentity to ""
|
|
2477
|
+
repeat with xOffset in {${timelineOffsets}}
|
|
2478
|
+
try
|
|
2479
|
+
set candidate to click at {(item 1 of origin) + xOffset, (item 2 of origin) + 650}
|
|
2480
|
+
set candidateRole to role of candidate as text
|
|
2481
|
+
set candidateName to value of candidate as text
|
|
2482
|
+
set candidateIdentity to ((position of candidate) as text) & "|" & ((size of candidate) as text)
|
|
2483
|
+
set candidateSourceIdentity to ""
|
|
2484
|
+
try
|
|
2485
|
+
set candidateSourceIdentity to value of attribute "AXIdentifier" of candidate as text
|
|
2486
|
+
end try
|
|
2487
|
+
if candidateSourceIdentity is sourceIdentity then
|
|
2488
|
+
if candidateIdentity is not lastMatchIdentity then
|
|
2489
|
+
set output to output & candidateName & (ASCII character 31) & candidateRole & (ASCII character 31) & candidateSourceIdentity & (ASCII character 31) & (xOffset as text) & (ASCII character 30)
|
|
2490
|
+
end if
|
|
2491
|
+
set lastMatchIdentity to candidateIdentity
|
|
2492
|
+
set inMatch to true
|
|
2493
|
+
else
|
|
2494
|
+
set inMatch to false
|
|
2495
|
+
end if
|
|
2496
|
+
on error
|
|
2497
|
+
set inMatch to false
|
|
2498
|
+
end try
|
|
2499
|
+
end repeat
|
|
2500
|
+
if output is not "" then
|
|
2501
|
+
click at {(item 1 of origin) + 800, (item 2 of origin) + 650}
|
|
2502
|
+
key code 115
|
|
2503
|
+
repeat 30 times
|
|
2504
|
+
key code 124
|
|
2505
|
+
end repeat
|
|
2506
|
+
end if
|
|
2507
|
+
return output
|
|
2508
|
+
end tell
|
|
2509
|
+
end tell`;
|
|
2510
|
+
}
|
|
2511
|
+
async function selectTimelineOccurrence(executor, timelineOffset) {
|
|
2512
|
+
const coordinates = (await executor(timelineSelectionCoordinatesScript())).split("|").map(Number);
|
|
2513
|
+
const [originX, originY] = coordinates;
|
|
2514
|
+
if (!Number.isFinite(originX) || !Number.isFinite(originY)) {
|
|
2515
|
+
throw new Error("FINAL_CUT_NATIVE_AUTOMATION_FAILED: could not resolve Final Cut window coordinates");
|
|
2516
|
+
}
|
|
2517
|
+
const x = Math.round(originX + timelineOffset);
|
|
2518
|
+
const y = Math.round(originY + 650);
|
|
2519
|
+
try {
|
|
2520
|
+
await execFile("swift", ["-e", nativeMouseSelectionSource(x, y)]);
|
|
2521
|
+
}
|
|
2522
|
+
catch (error) {
|
|
2523
|
+
throw new Error(`FINAL_CUT_NATIVE_AUTOMATION_FAILED: native timeline selection failed: ${String(error)}`);
|
|
2524
|
+
}
|
|
2525
|
+
}
|
|
2526
|
+
function timelineSelectionCoordinatesScript() {
|
|
2527
|
+
return `
|
|
2528
|
+
tell application "System Events"
|
|
2529
|
+
tell process "Final Cut Pro"
|
|
2530
|
+
${requireFrontmostAppleScript()}
|
|
2531
|
+
set mainWindow to window "Final Cut Pro"
|
|
2532
|
+
set origin to position of mainWindow
|
|
2533
|
+
return ((item 1 of origin) as text) & "|" & ((item 2 of origin) as text)
|
|
2534
|
+
end tell
|
|
2535
|
+
end tell`;
|
|
2536
|
+
}
|
|
2537
|
+
function timelineInsertionCoordinatesScript() {
|
|
2538
|
+
return `
|
|
2539
|
+
tell application "System Events"
|
|
2540
|
+
tell process "Final Cut Pro"
|
|
2541
|
+
${requireFrontmostAppleScript()}
|
|
2542
|
+
set mainWindow to window "Final Cut Pro"
|
|
2543
|
+
set origin to position of mainWindow
|
|
2544
|
+
set windowSize to size of mainWindow
|
|
2545
|
+
return ((item 1 of origin) as text) & "|" & ((item 2 of origin) as text) & "|" & ((item 1 of windowSize) as text) & "|" & ((item 2 of windowSize) as text)
|
|
2546
|
+
end tell
|
|
2547
|
+
end tell`;
|
|
2548
|
+
}
|
|
2549
|
+
function nativeMouseFocusSource(x, y) {
|
|
2550
|
+
return `
|
|
2551
|
+
import CoreGraphics
|
|
2552
|
+
import Foundation
|
|
2553
|
+
|
|
2554
|
+
let point = CGPoint(x: ${x}, y: ${y})
|
|
2555
|
+
func postMouse(_ type: CGEventType) {
|
|
2556
|
+
CGEvent(mouseEventSource: nil, mouseType: type, mouseCursorPosition: point, mouseButton: .left)?.post(tap: .cghidEventTap)
|
|
2557
|
+
}
|
|
2558
|
+
postMouse(.leftMouseDown)
|
|
2559
|
+
usleep(80_000)
|
|
2560
|
+
postMouse(.leftMouseUp)
|
|
2561
|
+
usleep(100_000)
|
|
2562
|
+
`;
|
|
2563
|
+
}
|
|
2564
|
+
function nativeMouseSelectionSource(x, y) {
|
|
2565
|
+
return `
|
|
2566
|
+
import CoreGraphics
|
|
2567
|
+
import Foundation
|
|
2568
|
+
|
|
2569
|
+
let point = CGPoint(x: ${x}, y: ${y})
|
|
2570
|
+
func postMouse(_ type: CGEventType) {
|
|
2571
|
+
CGEvent(mouseEventSource: nil, mouseType: type, mouseCursorPosition: point, mouseButton: .left)?.post(tap: .cghidEventTap)
|
|
2572
|
+
}
|
|
2573
|
+
func pressKey(_ key: CGKeyCode) {
|
|
2574
|
+
CGEvent(keyboardEventSource: nil, virtualKey: key, keyDown: true)?.post(tap: .cghidEventTap)
|
|
2575
|
+
usleep(30_000)
|
|
2576
|
+
CGEvent(keyboardEventSource: nil, virtualKey: key, keyDown: false)?.post(tap: .cghidEventTap)
|
|
2577
|
+
}
|
|
2578
|
+
postMouse(.leftMouseDown)
|
|
2579
|
+
usleep(80_000)
|
|
2580
|
+
postMouse(.leftMouseUp)
|
|
2581
|
+
usleep(100_000)
|
|
2582
|
+
pressKey(115)
|
|
2583
|
+
for _ in 0..<30 { pressKey(124) }
|
|
2584
|
+
`;
|
|
2585
|
+
}
|
|
2586
|
+
function bladeScript() {
|
|
2587
|
+
return `
|
|
2588
|
+
tell application "System Events"
|
|
2589
|
+
tell process "Final Cut Pro"
|
|
2590
|
+
${requireFrontmostAppleScript()}
|
|
2591
|
+
try
|
|
2592
|
+
click menu item "Blade" of menu "Trim" of menu bar 1
|
|
2593
|
+
on error
|
|
2594
|
+
keystroke "b"
|
|
2595
|
+
end try
|
|
2596
|
+
end tell
|
|
2597
|
+
end tell`;
|
|
2598
|
+
}
|
|
2599
|
+
function mediaInsertionScript(operation) {
|
|
2600
|
+
const shortcut = operation === "append" ? "e" : "w";
|
|
2601
|
+
return `
|
|
2602
|
+
tell application "System Events"
|
|
2603
|
+
tell process "Final Cut Pro"
|
|
2604
|
+
${requireFrontmostAppleScript()}
|
|
2605
|
+
set mainWindow to window "Final Cut Pro"
|
|
2606
|
+
set timelinePosition to position of mainWindow
|
|
2607
|
+
set timelineSize to size of mainWindow
|
|
2608
|
+
-- Selecting the Browser item leaves focus in the Browser search field.
|
|
2609
|
+
-- Final Cut interprets E/W there as Browser input, so explicitly return
|
|
2610
|
+
-- focus to the timeline before issuing the native insertion shortcut.
|
|
2611
|
+
click at {(item 1 of timelinePosition) + ((item 1 of timelineSize) * 0.50), (item 2 of timelinePosition) + ((item 2 of timelineSize) * 0.82)}
|
|
2612
|
+
delay 0.1
|
|
2613
|
+
keystroke "${shortcut}"
|
|
2614
|
+
-- When the first media item establishes an empty project's settings,
|
|
2615
|
+
-- Final Cut presents a modal properties sheet. Accept only that sheet;
|
|
2616
|
+
-- never send an unconditional Return to the timeline.
|
|
2617
|
+
repeat 30 times
|
|
2618
|
+
try
|
|
2619
|
+
if exists sheet 1 of mainWindow and exists button "OK" of sheet 1 of mainWindow then
|
|
2620
|
+
click button "OK" of sheet 1 of mainWindow
|
|
2621
|
+
exit repeat
|
|
2622
|
+
end if
|
|
2623
|
+
end try
|
|
2624
|
+
delay 0.1
|
|
2625
|
+
end repeat
|
|
2626
|
+
delay 0.5
|
|
2627
|
+
end tell
|
|
2628
|
+
end tell`;
|
|
2629
|
+
}
|
|
2630
|
+
function titleAssetSelectionScript(assetName) {
|
|
2631
|
+
return `
|
|
2632
|
+
tell application "System Events"
|
|
2633
|
+
tell process "Final Cut Pro"
|
|
2634
|
+
${requireFrontmostAppleScript()}
|
|
2635
|
+
set mainWindow to window "Final Cut Pro"
|
|
2636
|
+
set mainOrigin to position of mainWindow
|
|
2637
|
+
-- Final Cut 10.7 exposes the Titles tab as a custom Browser control. Its
|
|
2638
|
+
-- Control-Command-1 shortcut is not stable across releases (on some
|
|
2639
|
+
-- builds it opens Export), so use the bounded window-relative fallback.
|
|
2640
|
+
click at {(item 1 of mainOrigin) + 104, (item 2 of mainOrigin) + 53}
|
|
2641
|
+
delay 0.3
|
|
2642
|
+
set titleSearchField to missing value
|
|
2643
|
+
repeat with candidate in entire contents of front window
|
|
2644
|
+
try
|
|
2645
|
+
set candidateRole to role of candidate as text
|
|
2646
|
+
set candidateDescription to description of candidate as text
|
|
2647
|
+
if (candidateRole is "AXTextField" or candidateRole is "AXSearchField") and (candidateDescription contains "search" or candidateDescription contains "Search") then
|
|
2648
|
+
set titleSearchField to candidate
|
|
2649
|
+
exit repeat
|
|
2650
|
+
end if
|
|
2651
|
+
end try
|
|
2652
|
+
end repeat
|
|
2653
|
+
if titleSearchField is missing value then
|
|
2654
|
+
-- The Browser search field is custom UI in some Final Cut builds and is
|
|
2655
|
+
-- not present in the Accessibility tree. Focus its bounded position.
|
|
2656
|
+
click at {(item 1 of mainOrigin) + 280, (item 2 of mainOrigin) + 83}
|
|
2657
|
+
keystroke "a" using {command down}
|
|
2658
|
+
key code 51
|
|
2659
|
+
keystroke ${appleScriptString(assetName)}
|
|
2660
|
+
else
|
|
2661
|
+
set value of titleSearchField to ${appleScriptString(assetName)}
|
|
2662
|
+
try
|
|
2663
|
+
set value of attribute "AXFocused" of titleSearchField to true
|
|
2664
|
+
end try
|
|
2665
|
+
end if
|
|
2666
|
+
delay 0.6
|
|
2667
|
+
if titleSearchField is missing value then
|
|
2668
|
+
-- An exact search leaves one result in the first title-grid slot. Final
|
|
2669
|
+
-- Cut opens the category sidebar when the Titles tab is activated, so
|
|
2670
|
+
-- the result begins after that sidebar.
|
|
2671
|
+
click at {(item 1 of mainOrigin) + 240, (item 2 of mainOrigin) + 145}
|
|
2672
|
+
else
|
|
2673
|
+
set exactTitleItem to missing value
|
|
2674
|
+
set containingTitleItem to missing value
|
|
2675
|
+
set exactMatchCount to 0
|
|
2676
|
+
set containingMatchCount to 0
|
|
2677
|
+
set seenTitleIdentities to {}
|
|
2678
|
+
repeat with candidate in entire contents of front window
|
|
2679
|
+
try
|
|
2680
|
+
set candidateRole to role of candidate as text
|
|
2681
|
+
set candidateName to name of candidate as text
|
|
2682
|
+
set candidateIdentity to ""
|
|
2683
|
+
try
|
|
2684
|
+
set candidateSourceIdentity to value of attribute "AXIdentifier" of candidate as text
|
|
2685
|
+
if candidateSourceIdentity is not "" then set candidateIdentity to "source:" & candidateSourceIdentity
|
|
2686
|
+
end try
|
|
2687
|
+
if candidateIdentity is "" then
|
|
2688
|
+
set candidateIdentity to (candidateRole as text) & "|" & (candidateName as text) & "|" & ((position of candidate) as text) & "|" & ((size of candidate) as text)
|
|
2689
|
+
end if
|
|
2690
|
+
if (candidateName is ${appleScriptString(assetName)} or candidateName contains ${appleScriptString(assetName)}) and seenTitleIdentities does not contain candidateIdentity then
|
|
2691
|
+
set end of seenTitleIdentities to candidateIdentity
|
|
2692
|
+
if candidateName is ${appleScriptString(assetName)} then
|
|
2693
|
+
set exactMatchCount to exactMatchCount + 1
|
|
2694
|
+
set exactTitleItem to candidate
|
|
2695
|
+
else
|
|
2696
|
+
set containingMatchCount to containingMatchCount + 1
|
|
2697
|
+
set containingTitleItem to candidate
|
|
2698
|
+
end if
|
|
2699
|
+
end if
|
|
2700
|
+
end try
|
|
2701
|
+
end repeat
|
|
2702
|
+
set titleItem to missing value
|
|
2703
|
+
if exactMatchCount is 1 then
|
|
2704
|
+
set titleItem to exactTitleItem
|
|
2705
|
+
else if exactMatchCount is greater than 1 then
|
|
2706
|
+
error "FINAL_CUT_NATIVE_TITLE_ASSET_AMBIGUOUS: multiple exact title matches were visible in the Titles browser"
|
|
2707
|
+
else if containingMatchCount is 1 then
|
|
2708
|
+
set titleItem to containingTitleItem
|
|
2709
|
+
else if containingMatchCount is greater than 1 then
|
|
2710
|
+
error "FINAL_CUT_NATIVE_TITLE_ASSET_AMBIGUOUS: multiple title matches were visible in the Titles browser"
|
|
2711
|
+
end if
|
|
2712
|
+
if titleItem is missing value then error "FINAL_CUT_NATIVE_TITLE_ASSET_NOT_FOUND: installed title was not visible in the Titles browser"
|
|
2713
|
+
try
|
|
2714
|
+
perform action "AXPress" of titleItem
|
|
2715
|
+
on error
|
|
2716
|
+
click titleItem
|
|
2717
|
+
end try
|
|
2718
|
+
end if
|
|
2719
|
+
end tell
|
|
2720
|
+
end tell`;
|
|
2721
|
+
}
|
|
2722
|
+
function markRangeEndAndConnectTitleScript() {
|
|
2723
|
+
return `
|
|
2724
|
+
tell application "System Events"
|
|
2725
|
+
tell process "Final Cut Pro"
|
|
2726
|
+
${requireFrontmostAppleScript()}
|
|
2727
|
+
keystroke "o"
|
|
2728
|
+
delay 0.2
|
|
2729
|
+
keystroke "q"
|
|
2730
|
+
delay 0.5
|
|
2731
|
+
end tell
|
|
2732
|
+
end tell`;
|
|
2733
|
+
}
|
|
2734
|
+
function titleTextEditScript(text) {
|
|
2735
|
+
return `
|
|
2736
|
+
tell application "System Events"
|
|
2737
|
+
tell process "Final Cut Pro"
|
|
2738
|
+
set mainWindow to window "Final Cut Pro"
|
|
2739
|
+
set mainOrigin to position of mainWindow
|
|
2740
|
+
set mainSize to size of mainWindow
|
|
2741
|
+
-- Connecting a title leaves the Browser selection active on some Final
|
|
2742
|
+
-- Cut builds. Select the connected title before opening its text controls.
|
|
2743
|
+
-- The live insertion flow places the requested title at the sequence
|
|
2744
|
+
-- start, which is the bounded leftmost connected-title slot here.
|
|
2745
|
+
keystroke "a"
|
|
2746
|
+
delay 0.1
|
|
2747
|
+
set titleX to (item 1 of mainOrigin) + ((item 1 of mainSize) * 0.11)
|
|
2748
|
+
set titleY to (item 2 of mainOrigin) + ((item 2 of mainSize) * 0.74)
|
|
2749
|
+
click at {titleX, titleY}
|
|
2750
|
+
delay 0.1
|
|
2751
|
+
click at {titleX, titleY}
|
|
2752
|
+
delay 0.2
|
|
2753
|
+
keystroke "4" using {command down}
|
|
2754
|
+
delay 0.3
|
|
2755
|
+
-- The Text inspector is a custom control in Final Cut 10.7 and is not
|
|
2756
|
+
-- exposed as an Accessibility text field until this tab is selected.
|
|
2757
|
+
click at {(item 1 of mainOrigin) + (item 1 of mainSize) - 385, (item 2 of mainOrigin) + 53}
|
|
2758
|
+
delay 0.2
|
|
2759
|
+
set titleTextField to missing value
|
|
2760
|
+
repeat with candidate in text fields of front window
|
|
2761
|
+
try
|
|
2762
|
+
set candidateName to name of candidate as text
|
|
2763
|
+
set candidateDescription to description of candidate as text
|
|
2764
|
+
if candidateName contains "Title" or candidateDescription contains "Title" then
|
|
2765
|
+
set titleTextField to candidate
|
|
2766
|
+
exit repeat
|
|
2767
|
+
end if
|
|
2768
|
+
end try
|
|
2769
|
+
end repeat
|
|
2770
|
+
if titleTextField is missing value then
|
|
2771
|
+
-- Final Cut 10.7 keeps the editable title value in a custom control.
|
|
2772
|
+
-- Focus its bounded Inspector position and use normal text editing.
|
|
2773
|
+
click at {(item 1 of mainOrigin) + (item 1 of mainSize) - 215, (item 2 of mainOrigin) + 154}
|
|
2774
|
+
keystroke "a" using {command down}
|
|
2775
|
+
key code 51
|
|
2776
|
+
keystroke ${appleScriptString(text)}
|
|
2777
|
+
else
|
|
2778
|
+
set value of titleTextField to ${appleScriptString(text)}
|
|
2779
|
+
end if
|
|
2780
|
+
end tell
|
|
2781
|
+
end tell`;
|
|
2782
|
+
}
|
|
2783
|
+
function setPlayheadScript(timecode) {
|
|
2784
|
+
return `
|
|
2785
|
+
tell application "System Events"
|
|
2786
|
+
tell process "Final Cut Pro"
|
|
2787
|
+
${requireFrontmostAppleScript()}
|
|
2788
|
+
keystroke "p" using {control down}
|
|
2789
|
+
keystroke ${appleScriptString(timecode)}
|
|
2790
|
+
key code 36
|
|
2791
|
+
delay 0.2
|
|
2792
|
+
end tell
|
|
2793
|
+
end tell`;
|
|
2794
|
+
}
|
|
2795
|
+
function markRangeStartScript() {
|
|
2796
|
+
return `
|
|
2797
|
+
tell application "System Events"
|
|
2798
|
+
tell process "Final Cut Pro"
|
|
2799
|
+
${requireFrontmostAppleScript()}
|
|
2800
|
+
keystroke "i"
|
|
2801
|
+
end tell
|
|
2802
|
+
end tell`;
|
|
2803
|
+
}
|
|
2804
|
+
function markRangeEndAndDeleteScript() {
|
|
2805
|
+
return `
|
|
2806
|
+
tell application "System Events"
|
|
2807
|
+
tell process "Final Cut Pro"
|
|
2808
|
+
${requireFrontmostAppleScript()}
|
|
2809
|
+
keystroke "o"
|
|
2810
|
+
delay 0.2
|
|
2811
|
+
key code 51
|
|
2812
|
+
delay 0.5
|
|
2813
|
+
end tell
|
|
2814
|
+
end tell`;
|
|
2815
|
+
}
|
|
2816
|
+
function editScript(operation) {
|
|
2817
|
+
const action = operation.type === "rename-selected-clip"
|
|
2818
|
+
? `click menu item "Apply Custom Name" of menu "Modify" of menu bar 1\n delay 0.2\n set value of first text field of front window to ${appleScriptString(operation.name)}\n key code 36`
|
|
2819
|
+
: operation.type === "trim-selected-clip-to-playhead"
|
|
2820
|
+
? `click menu item "Trim ${operation.edge === "start" ? "Start" : "End"}" of menu "Trim" of menu bar 1`
|
|
2821
|
+
: operation.type === "set-selected-clip-gain"
|
|
2822
|
+
? `click menu item "Adjust Volume" of menu "Modify" of menu bar 1\n delay 0.2\n set value of first text field of front window to ${appleScriptString(`${operation.gainDb}`)}\n key code 36`
|
|
2823
|
+
: `click menu item "Marker" of menu "Mark" of menu bar 1`;
|
|
2824
|
+
return `
|
|
2825
|
+
tell application "System Events"
|
|
2826
|
+
tell process "Final Cut Pro"
|
|
2827
|
+
${requireFrontmostAppleScript()}
|
|
2828
|
+
${action}
|
|
2829
|
+
end tell
|
|
2830
|
+
end tell`;
|
|
2831
|
+
}
|
|
2832
|
+
function undoScript(command) {
|
|
2833
|
+
return `
|
|
2834
|
+
tell application "System Events"
|
|
2835
|
+
tell process "Final Cut Pro"
|
|
2836
|
+
${requireFrontmostAppleScript()}
|
|
2837
|
+
click menu item ${appleScriptString(command)} of menu "Edit" of menu bar 1
|
|
2838
|
+
end tell
|
|
2839
|
+
end tell`;
|
|
2840
|
+
}
|
|
2841
|
+
function parseContext(output) {
|
|
2842
|
+
const [frontState, frontWindow, selectedCountText, selectedName, selectedRole, undoState, bladeState, focusedName, focusedRole, focusedDescription, timelineWindowState, timelineFocusedState, focusTargetState, focusAttemptsState, framekitWindowState, framekitMinimizedState, focusedWindowName, overlayBlockedState, undoCommandState, targetIdentity] = output.split(String.fromCharCode(31));
|
|
2843
|
+
const selectedCount = Number(selectedCountText ?? "0");
|
|
2844
|
+
const timelineWindowAvailable = timelineWindowState === undefined ? Boolean(frontWindow) : timelineWindowState === "true";
|
|
2845
|
+
const timelineFocused = timelineFocusedState === undefined
|
|
2846
|
+
? frontState === "true" && timelineWindowAvailable
|
|
2847
|
+
: timelineFocusedState === "true";
|
|
2848
|
+
const focusTarget = focusTargetState === "timeline" || focusTargetState === "browser" || focusTargetState === "text-field" || focusTargetState === "modal" || focusTargetState === "unknown" || focusTargetState === "none"
|
|
2849
|
+
? focusTargetState
|
|
2850
|
+
: timelineFocused
|
|
2851
|
+
? "timeline"
|
|
2852
|
+
: "none";
|
|
2853
|
+
const target = selectedCount === 1
|
|
2854
|
+
? { kind: "selected-clip", ...(selectedName ? { name: selectedName } : {}), ...(selectedRole ? { role: selectedRole } : {}), ...(targetIdentity ? { identity: targetIdentity } : {}) }
|
|
2855
|
+
: selectedCount > 1
|
|
2856
|
+
? { kind: "unknown" }
|
|
2857
|
+
: (focusedRole === "AXTextField" && (focusedDescription === "text field" || focusedDescription === "Title")
|
|
2858
|
+
|| focusedRole === "AXTextArea" && focusedDescription === "text entry area") && focusedName
|
|
2859
|
+
? { kind: "selected-clip", name: focusedName, role: focusedRole }
|
|
2860
|
+
: { kind: "playhead" };
|
|
2861
|
+
return {
|
|
2862
|
+
available: true,
|
|
2863
|
+
application: "Final Cut Pro",
|
|
2864
|
+
frontmost: frontState === "true",
|
|
2865
|
+
frontWindow,
|
|
2866
|
+
timelineWindowAvailable,
|
|
2867
|
+
timelineFocused,
|
|
2868
|
+
focusTarget,
|
|
2869
|
+
...(focusedName ? { focusedName } : {}),
|
|
2870
|
+
...(focusedRole ? { focusedRole } : {}),
|
|
2871
|
+
...(focusedDescription ? { focusedDescription } : {}),
|
|
2872
|
+
...(focusedWindowName ? { focusedWindowName } : {}),
|
|
2873
|
+
...(focusAttemptsState && Number.isFinite(Number(focusAttemptsState)) ? { focusAttempts: Number(focusAttemptsState) } : {}),
|
|
2874
|
+
...(framekitWindowState !== undefined ? { framekitWindowAvailable: framekitWindowState === "true" } : {}),
|
|
2875
|
+
...(framekitMinimizedState !== undefined ? { framekitWindowMinimized: framekitMinimizedState === "true" } : {}),
|
|
2876
|
+
...(overlayBlockedState !== undefined ? { overlayBlocked: overlayBlockedState === "true" } : {}),
|
|
2877
|
+
target,
|
|
2878
|
+
bladeAvailable: bladeState === "true",
|
|
2879
|
+
undoAvailable: undoState === "true",
|
|
2880
|
+
...(undoCommandState ? { undoCommand: undoCommandState } : {}),
|
|
2881
|
+
};
|
|
2882
|
+
}
|
|
2883
|
+
function parseMediaMatches(output) {
|
|
2884
|
+
return output
|
|
2885
|
+
.split(String.fromCharCode(30))
|
|
2886
|
+
.map((record) => record.trim())
|
|
2887
|
+
.filter(Boolean)
|
|
2888
|
+
.map((record, index) => {
|
|
2889
|
+
const [name = "", role = "", identity = "", sourceIdentity = ""] = record.split(String.fromCharCode(31));
|
|
2890
|
+
return {
|
|
2891
|
+
handle: opaqueHandle("media", index),
|
|
2892
|
+
name,
|
|
2893
|
+
...(role ? { role } : {}),
|
|
2894
|
+
...(identity ? { identity } : {}),
|
|
2895
|
+
...(sourceIdentity ? { sourceIdentity } : {}),
|
|
2896
|
+
uiIndex: index,
|
|
2897
|
+
};
|
|
2898
|
+
});
|
|
2899
|
+
}
|
|
2900
|
+
function browserMediaIdentity(match) {
|
|
2901
|
+
const identity = match.sourceIdentity?.trim();
|
|
2902
|
+
return identity || undefined;
|
|
2903
|
+
}
|
|
2904
|
+
function parseOccurrences(output, mediaHandle) {
|
|
2905
|
+
return output
|
|
2906
|
+
.split(String.fromCharCode(30))
|
|
2907
|
+
.map((record) => record.trim())
|
|
2908
|
+
.filter(Boolean)
|
|
2909
|
+
.map((record, index) => {
|
|
2910
|
+
const [name = "", role = "", sourceIdentity = "", timelineOffsetOrDuration = "", legacyTimelineOffset] = record.split(String.fromCharCode(31));
|
|
2911
|
+
const legacyRecord = legacyTimelineOffset !== undefined;
|
|
2912
|
+
const identityOrStart = sourceIdentity;
|
|
2913
|
+
const timelineOffsetText = legacyRecord ? legacyTimelineOffset : timelineOffsetOrDuration;
|
|
2914
|
+
const legacyRange = legacyRecord || (!legacyRecord && isRational(identityOrStart) && isRational(timelineOffsetOrDuration));
|
|
2915
|
+
return {
|
|
2916
|
+
handle: opaqueHandle("occurrence", index),
|
|
2917
|
+
mediaHandle,
|
|
2918
|
+
name,
|
|
2919
|
+
...(role ? { role } : {}),
|
|
2920
|
+
...(sourceIdentity && !legacyRange ? { sourceIdentity } : {}),
|
|
2921
|
+
...(legacyRange ? { start: identityOrStart, duration: timelineOffsetOrDuration } : {}),
|
|
2922
|
+
...(timelineOffsetText && Number.isFinite(Number(timelineOffsetText)) ? { timelineOffset: Number(timelineOffsetText) } : {}),
|
|
2923
|
+
};
|
|
2924
|
+
});
|
|
2925
|
+
}
|
|
2926
|
+
function isRational(value) {
|
|
2927
|
+
return /^-?\d+\/\d+$/.test(value);
|
|
2928
|
+
}
|
|
2929
|
+
function opaqueHandle(kind, suffix) {
|
|
2930
|
+
return `${kind}-${Date.now().toString(36)}-${suffix ?? Math.random().toString(36).slice(2, 8)}`;
|
|
2931
|
+
}
|
|
2932
|
+
function mediaKind(sourcePath) {
|
|
2933
|
+
return new Set([".aif", ".aiff", ".flac", ".m4a", ".mp3", ".wav", ".aac", ".caf"]).has(extname(sourcePath).toLowerCase())
|
|
2934
|
+
? "audio"
|
|
2935
|
+
: "video";
|
|
2936
|
+
}
|
|
2937
|
+
function parseRationalNumber(value) {
|
|
2938
|
+
const [numerator, timescale] = value.split("/").map(Number);
|
|
2939
|
+
if (!Number.isFinite(numerator) || !Number.isFinite(timescale) || timescale <= 0)
|
|
2940
|
+
return undefined;
|
|
2941
|
+
return numerator / timescale;
|
|
2942
|
+
}
|
|
2943
|
+
function zeroRational() {
|
|
2944
|
+
return { value: "0", timescale: "1" };
|
|
2945
|
+
}
|
|
2946
|
+
function rationalParts(value) {
|
|
2947
|
+
const numerator = BigInt(value.value);
|
|
2948
|
+
const denominator = BigInt(value.timescale);
|
|
2949
|
+
if (denominator <= 0n)
|
|
2950
|
+
throw new Error("INVALID_OPERATION: rational timescale must be positive");
|
|
2951
|
+
return [numerator, denominator];
|
|
2952
|
+
}
|
|
2953
|
+
function normalizeRational(numerator, denominator) {
|
|
2954
|
+
if (denominator <= 0n)
|
|
2955
|
+
throw new Error("INVALID_OPERATION: rational timescale must be positive");
|
|
2956
|
+
const divisor = gcd(numerator < 0n ? -numerator : numerator, denominator);
|
|
2957
|
+
return { value: (numerator / divisor).toString(), timescale: (denominator / divisor).toString() };
|
|
2958
|
+
}
|
|
2959
|
+
function addRational(left, right) {
|
|
2960
|
+
const [leftValue, leftScale] = rationalParts(left);
|
|
2961
|
+
const [rightValue, rightScale] = rationalParts(right);
|
|
2962
|
+
return normalizeRational(leftValue * rightScale + rightValue * leftScale, leftScale * rightScale);
|
|
2963
|
+
}
|
|
2964
|
+
function subtractRational(left, right) {
|
|
2965
|
+
const [leftValue, leftScale] = rationalParts(left);
|
|
2966
|
+
const [rightValue, rightScale] = rationalParts(right);
|
|
2967
|
+
return normalizeRational(leftValue * rightScale - rightValue * leftScale, leftScale * rightScale);
|
|
2968
|
+
}
|
|
2969
|
+
function compareRational(left, right) {
|
|
2970
|
+
const [leftValue, leftScale] = rationalParts(left);
|
|
2971
|
+
const [rightValue, rightScale] = rationalParts(right);
|
|
2972
|
+
const difference = leftValue * rightScale - rightValue * leftScale;
|
|
2973
|
+
return difference < 0n ? -1 : difference > 0n ? 1 : 0;
|
|
2974
|
+
}
|
|
2975
|
+
function isFrameAligned(value, origin, frameDuration) {
|
|
2976
|
+
const relative = subtractRational(value, origin);
|
|
2977
|
+
const [valueNumerator, valueDenominator] = rationalParts(relative);
|
|
2978
|
+
const [frameNumerator, frameDenominator] = rationalParts(frameDuration);
|
|
2979
|
+
return (valueNumerator * frameDenominator) % (valueDenominator * frameNumerator) === 0n;
|
|
2980
|
+
}
|
|
2981
|
+
function divideRationalFloor(value, divisor) {
|
|
2982
|
+
const [valueNumerator, valueDenominator] = rationalParts(value);
|
|
2983
|
+
const [divisorNumerator, divisorDenominator] = rationalParts(divisor);
|
|
2984
|
+
if (divisorNumerator <= 0n)
|
|
2985
|
+
throw new Error("INVALID_OPERATION: frame duration must be positive");
|
|
2986
|
+
const numerator = valueNumerator * divisorDenominator;
|
|
2987
|
+
const denominator = valueDenominator * divisorNumerator;
|
|
2988
|
+
return numerator / denominator;
|
|
2989
|
+
}
|
|
2990
|
+
function formatTimecode(totalFrames, framesPerSecond) {
|
|
2991
|
+
if (totalFrames < 0n)
|
|
2992
|
+
throw new Error("INVALID_OPERATION: timecode cannot be negative");
|
|
2993
|
+
const fps = BigInt(framesPerSecond);
|
|
2994
|
+
const framesPerMinute = fps * 60n;
|
|
2995
|
+
const framesPerHour = framesPerMinute * 60n;
|
|
2996
|
+
const hours = totalFrames / framesPerHour;
|
|
2997
|
+
const minutes = (totalFrames % framesPerHour) / framesPerMinute;
|
|
2998
|
+
const seconds = (totalFrames % framesPerMinute) / fps;
|
|
2999
|
+
const frames = totalFrames % fps;
|
|
3000
|
+
return [hours, minutes, seconds, frames]
|
|
3001
|
+
.map((part) => part.toString().padStart(2, "0"))
|
|
3002
|
+
.join(":");
|
|
3003
|
+
}
|
|
3004
|
+
function gcd(left, right) {
|
|
3005
|
+
let a = left;
|
|
3006
|
+
let b = right;
|
|
3007
|
+
while (b !== 0n) {
|
|
3008
|
+
const remainder = a % b;
|
|
3009
|
+
a = b;
|
|
3010
|
+
b = remainder;
|
|
3011
|
+
}
|
|
3012
|
+
return a || 1n;
|
|
3013
|
+
}
|
|
3014
|
+
function durationVerificationDetail(actual, expected, tolerance = zeroRational()) {
|
|
3015
|
+
if (!actual)
|
|
3016
|
+
return { verified: false, detail: "Final Cut did not expose a resulting sequence duration" };
|
|
3017
|
+
const difference = subtractRational(actual, expected);
|
|
3018
|
+
const [differenceNumerator, differenceDenominator] = rationalParts(difference);
|
|
3019
|
+
const [toleranceNumerator, toleranceDenominator] = rationalParts(tolerance);
|
|
3020
|
+
if ((differenceNumerator < 0n ? -differenceNumerator : differenceNumerator) * toleranceDenominator <= toleranceNumerator * differenceDenominator) {
|
|
3021
|
+
return { verified: true, detail: `Final Cut exposed resulting duration ${actual.value}/${actual.timescale}` };
|
|
3022
|
+
}
|
|
3023
|
+
return { verified: false, detail: `expected duration ${expected.value}/${expected.timescale}, observed ${actual.value}/${actual.timescale}` };
|
|
3024
|
+
}
|
|
3025
|
+
function mediaInsertionVerificationDetail(actual, before, revision, previousRevision) {
|
|
3026
|
+
if (!actual)
|
|
3027
|
+
return { verified: false, detail: "Final Cut did not expose a resulting sequence duration" };
|
|
3028
|
+
if (compareRational(actual, before) <= 0) {
|
|
3029
|
+
return { verified: false, detail: `expected inserted media to increase duration beyond ${before.value}/${before.timescale}, observed ${actual.value}/${actual.timescale}` };
|
|
3030
|
+
}
|
|
3031
|
+
if (revision === previousRevision)
|
|
3032
|
+
return { verified: false, detail: "Final Cut did not expose a new revision after media insertion" };
|
|
3033
|
+
return { verified: true, detail: `Final Cut exposed resulting duration ${actual.value}/${actual.timescale} at revision ${revision}` };
|
|
3034
|
+
}
|
|
3035
|
+
function mediaInsertionMutationObserved(before, after) {
|
|
3036
|
+
const beforeDuration = before.sequenceTimeRange?.duration ?? before.sequence?.duration;
|
|
3037
|
+
const afterDuration = after.sequenceTimeRange?.duration ?? after.sequence?.duration;
|
|
3038
|
+
return Boolean(beforeDuration && afterDuration && compareRational(afterDuration, beforeDuration) > 0);
|
|
3039
|
+
}
|
|
3040
|
+
function unavailableContext(code, message, observed) {
|
|
3041
|
+
return {
|
|
3042
|
+
...(observed ?? {
|
|
3043
|
+
application: "Final Cut Pro",
|
|
3044
|
+
frontmost: false,
|
|
3045
|
+
timelineWindowAvailable: false,
|
|
3046
|
+
timelineFocused: false,
|
|
3047
|
+
focusTarget: "none",
|
|
3048
|
+
target: { kind: "none" },
|
|
3049
|
+
undoAvailable: false,
|
|
3050
|
+
bladeAvailable: false,
|
|
3051
|
+
}),
|
|
3052
|
+
available: false,
|
|
3053
|
+
error: { code, message },
|
|
3054
|
+
};
|
|
3055
|
+
}
|
|
3056
|
+
function preflightContext(error) {
|
|
3057
|
+
return error instanceof NativeFinalCutPreflightError ? error.context : undefined;
|
|
3058
|
+
}
|
|
3059
|
+
function verifyNativeEdit(operation, before, after) {
|
|
3060
|
+
if (operation.type === "rename-selected-clip" && after.target.name !== operation.name) {
|
|
3061
|
+
return { verified: false, level: "selection-observed", detail: "Final Cut did not expose the renamed selected clip" };
|
|
3062
|
+
}
|
|
3063
|
+
if (operation.type === "rename-selected-clip") {
|
|
3064
|
+
return { verified: true, level: "selection-observed", detail: "Selected clip name changed" };
|
|
3065
|
+
}
|
|
3066
|
+
if (!after.frontmost || before.frontWindow !== after.frontWindow) {
|
|
3067
|
+
return { verified: false, level: "native-command-accepted", detail: "Final Cut changed focus during the native edit" };
|
|
3068
|
+
}
|
|
3069
|
+
return { verified: true, level: "native-command-accepted", detail: "Final Cut accepted the native menu command" };
|
|
3070
|
+
}
|
|
3071
|
+
function requiresClip(operation) {
|
|
3072
|
+
return operation.type === "rename-selected-clip" || operation.type === "trim-selected-clip-to-playhead" || operation.type === "set-selected-clip-gain";
|
|
3073
|
+
}
|
|
3074
|
+
function commandName(operation) {
|
|
3075
|
+
if (operation.type === "rename-selected-clip")
|
|
3076
|
+
return "Modify > Apply Custom Name";
|
|
3077
|
+
if (operation.type === "trim-selected-clip-to-playhead")
|
|
3078
|
+
return `Trim > Trim ${operation.edge === "start" ? "Start" : "End"}`;
|
|
3079
|
+
if (operation.type === "set-selected-clip-gain")
|
|
3080
|
+
return "Modify > Adjust Volume";
|
|
3081
|
+
return "Mark > Marker";
|
|
3082
|
+
}
|
|
3083
|
+
function appleScriptString(value) {
|
|
3084
|
+
return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replace(/[\r\n]/g, " ")}"`;
|
|
3085
|
+
}
|
|
3086
|
+
function nativeErrorCode(error) {
|
|
3087
|
+
const message = String(error);
|
|
3088
|
+
if (message.includes("-1712") || /AppleEvent.*timed out/i.test(message))
|
|
3089
|
+
return "FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT";
|
|
3090
|
+
const explicitCodes = [...message.matchAll(/FINAL_CUT_NATIVE_[A-Z_]+/g)].map((match) => match[0]);
|
|
3091
|
+
if (explicitCodes.length > 0)
|
|
3092
|
+
return explicitCodes[explicitCodes.length - 1];
|
|
3093
|
+
if (message.includes("PERMISSION_REQUIRED") || message.includes("not authorized") || message.includes("-1743") || message.includes("-25211"))
|
|
3094
|
+
return "FINAL_CUT_NATIVE_PERMISSION_REQUIRED";
|
|
3095
|
+
if (message.includes("-600") || message.includes("isn't running") || message.includes("is not running"))
|
|
3096
|
+
return "FINAL_CUT_NATIVE_NO_TIMELINE_WINDOW";
|
|
3097
|
+
if (message.includes("-1728") || message.includes("Can’t get window") || message.includes("Can't get window"))
|
|
3098
|
+
return "FINAL_CUT_NATIVE_NO_TIMELINE_WINDOW";
|
|
3099
|
+
if (message.includes("-1719") || message.includes("window 1") || message.includes("Invalid index"))
|
|
3100
|
+
return "FINAL_CUT_NATIVE_NOT_FRONTMOST";
|
|
3101
|
+
if (message.includes("MODAL"))
|
|
3102
|
+
return "FINAL_CUT_NATIVE_MODAL_BLOCKED";
|
|
3103
|
+
return "FINAL_CUT_NATIVE_AUTOMATION_FAILED";
|
|
3104
|
+
}
|
|
3105
|
+
function nativeErrorMessage(error) {
|
|
3106
|
+
const message = String(error);
|
|
3107
|
+
if (message.includes("FINAL_CUT_NATIVE_OVERLAY_BLOCKED"))
|
|
3108
|
+
return "The Framekit window could not be minimized; close or minimize the overlay and retry";
|
|
3109
|
+
if (message.includes("FINAL_CUT_NATIVE_APPLE_EVENT_TIMEOUT") || message.includes("-1712") || /AppleEvent.*timed out/i.test(message))
|
|
3110
|
+
return "Final Cut did not respond to an AppleEvent; reopen or bring Final Cut Pro to the front and retry";
|
|
3111
|
+
if (message.includes("FINAL_CUT_NATIVE_NO_TIMELINE_WINDOW"))
|
|
3112
|
+
return "Final Cut has no accessible timeline window; open a project timeline and retry";
|
|
3113
|
+
if (message.includes("FINAL_CUT_NATIVE_TIMELINE_FOCUS_REQUIRED"))
|
|
3114
|
+
return "Final Cut's timeline pane could not be focused; click the timeline and retry";
|
|
3115
|
+
if (message.includes("FINAL_CUT_NATIVE_NOT_FRONTMOST"))
|
|
3116
|
+
return "Final Cut is running but is not the frontmost application";
|
|
3117
|
+
if (message.includes("-600") || message.includes("isn't running") || message.includes("is not running"))
|
|
3118
|
+
return "Final Cut is not running or has no accessible timeline window; open a project timeline and retry";
|
|
3119
|
+
if (message.includes("-1728") || message.includes("Can’t get window") || message.includes("Can't get window"))
|
|
3120
|
+
return "Final Cut has no accessible timeline window; open a project timeline and retry";
|
|
3121
|
+
if (message.includes("-1719") || message.includes("window 1") || message.includes("Invalid index"))
|
|
3122
|
+
return "Final Cut has no accessible timeline window; bring a project timeline to the front";
|
|
3123
|
+
if (message.includes("PERMISSION_REQUIRED") || message.includes("not authorized") || message.includes("-1743") || message.includes("-25211"))
|
|
3124
|
+
return "Grant Accessibility and Automation permission to the MCP host for Final Cut Pro";
|
|
3125
|
+
const executionError = message.split("\n").find((line) => line.includes("execution error:"));
|
|
3126
|
+
return executionError?.trim() ?? message;
|
|
3127
|
+
}
|
|
3128
|
+
function isRecoverableNativeFocusRace(error) {
|
|
3129
|
+
const code = nativeErrorCode(error);
|
|
3130
|
+
if (code === "FINAL_CUT_NATIVE_NOT_FRONTMOST" || code === "FINAL_CUT_NATIVE_TIMELINE_FOCUS_REQUIRED")
|
|
3131
|
+
return true;
|
|
3132
|
+
const message = String(error);
|
|
3133
|
+
return message.includes("execution error:") && message.includes("-1719");
|
|
3134
|
+
}
|