@morshoto/framekit 0.1.5 → 0.1.6

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.
@@ -37,9 +37,11 @@ export class FinalCutNativeAutomationAdapter {
37
37
  occurrenceHandles = new Map();
38
38
  ambiguousMediaHandles = new Set();
39
39
  bladePreviews = new Map();
40
+ maskPreviews = new Map();
40
41
  rangePreviews = new Map();
41
42
  mediaInsertionPreviews = new Map();
42
43
  titlePreviews = new Map();
44
+ pictureInPicturePreviews = new Map();
43
45
  transitionPreviews = new Map();
44
46
  constructor(options = {}) {
45
47
  this.enabled = options.enabled ?? process.env.FRAMEKIT_FINAL_CUT_NATIVE_WRITES === "1";
@@ -71,8 +73,11 @@ export class FinalCutNativeAutomationAdapter {
71
73
  mediaAppend: this.enabled,
72
74
  mediaInsert: this.enabled,
73
75
  titlePlacement: this.enabled,
76
+ titleDiscovery: this.enabled,
77
+ pictureInPicture: this.enabled,
74
78
  transitionDiscovery: this.enabled,
75
79
  transitionPlacement: this.enabled,
80
+ masking: this.enabled,
76
81
  timelineFocus: this.enabled,
77
82
  requiresAccessibility: true,
78
83
  requiresFinalCutFrontmost: true,
@@ -488,6 +493,11 @@ export class FinalCutNativeAutomationAdapter {
488
493
  }
489
494
  await selectTimelineOccurrence(this.executor, timelineOffset);
490
495
  await this.ensureOccurrenceRange(occurrences[0]);
496
+ const selectedContext = await this.inspectRawNative();
497
+ if (selectedContext.target.kind !== "selected-clip" || !selectedContext.target.identity) {
498
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_IDENTITY_UNAVAILABLE: selected timeline occurrence has no stable native identity");
499
+ }
500
+ occurrences[0].nativeIdentity = selectedContext.target.identity;
491
501
  }
492
502
  const live = this.liveState ? await this.liveState().catch(() => undefined) : liveBefore;
493
503
  for (const occurrence of occurrences) {
@@ -550,6 +560,144 @@ export class FinalCutNativeAutomationAdapter {
550
560
  async executeBlade(previewToken) {
551
561
  return this.withNativeUi(() => this.executeBladeNative(previewToken));
552
562
  }
563
+ async previewMask(request) {
564
+ return this.withNativeUi(() => this.previewMaskNative(request));
565
+ }
566
+ async executeMask(previewToken) {
567
+ return this.withNativeUi(() => this.executeMaskNative(previewToken));
568
+ }
569
+ async previewMaskNative(request) {
570
+ this.assertEnabled();
571
+ assertNativeMaskConfiguration(request.mask);
572
+ const occurrence = this.occurrenceHandles.get(request.occurrenceHandle);
573
+ if (!occurrence)
574
+ throw new Error(`FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: unknown occurrence handle ${request.occurrenceHandle}`);
575
+ if (this.ambiguousMediaHandles.has(occurrence.mediaHandle)) {
576
+ throw new Error("FINAL_CUT_NATIVE_AMBIGUOUS_OCCURRENCE: masking requires exactly one timeline occurrence");
577
+ }
578
+ const context = await this.requireTimelineContext();
579
+ if (!context.frontmost)
580
+ throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
581
+ assertNativeMaskTarget(context, occurrence);
582
+ await this.validateOccurrenceBinding(occurrence);
583
+ const live = await this.requireLiveState();
584
+ const expiresAt = this.now() + 30_000;
585
+ const previewToken = opaqueHandle("mask-preview");
586
+ const mask = structuredClone(request.mask);
587
+ this.maskPreviews.set(previewToken, {
588
+ occurrence: structuredClone(occurrence),
589
+ mask,
590
+ sequenceId: live.sequence?.id,
591
+ revision: live.revision.id,
592
+ expiresAt,
593
+ });
594
+ return {
595
+ previewToken,
596
+ occurrence: structuredClone(occurrence),
597
+ mask,
598
+ ...(live.sequence?.id ? { sequenceId: live.sequence.id } : {}),
599
+ revision: live.revision.id,
600
+ command: "Add native Draw Mask",
601
+ expiresAt: new Date(expiresAt).toISOString(),
602
+ };
603
+ }
604
+ async executeMaskNative(previewToken) {
605
+ this.assertEnabled();
606
+ const preview = this.maskPreviews.get(previewToken);
607
+ if (!preview)
608
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: unknown native mask preview");
609
+ this.maskPreviews.delete(previewToken);
610
+ if (this.now() > preview.expiresAt)
611
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: native mask preview has expired");
612
+ const before = await this.requireTimelineContext();
613
+ const beforeLive = await this.requireLiveState();
614
+ if (!before.frontmost)
615
+ throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
616
+ if (before.target.kind !== "selected-clip")
617
+ throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: select exactly one timeline occurrence");
618
+ assertNativeMaskTarget(before, preview.occurrence);
619
+ validateMaskPreviewBinding(preview, beforeLive);
620
+ await this.validateOccurrenceBinding(preview.occurrence);
621
+ let observedAfter;
622
+ let observedLive;
623
+ try {
624
+ const observedMask = parseNativeMaskReadback(await this.executor(applyMaskScript(preview.mask)));
625
+ observedAfter = await this.requireTimelineContext();
626
+ observedLive = await this.waitForRevision(beforeLive.revision.id);
627
+ const verification = verifyNativeMask(preview, observedAfter, beforeLive, observedLive, observedMask);
628
+ if (!verification.verified) {
629
+ throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}`);
630
+ }
631
+ const operationId = opaqueHandle("native-mask");
632
+ const operation = {
633
+ kind: "masking",
634
+ before,
635
+ after: observedAfter,
636
+ beforeLive,
637
+ afterLive: observedLive,
638
+ undoCommand: observedAfter.undoCommand,
639
+ };
640
+ this.rememberOperation(operationId, operation);
641
+ return {
642
+ operationId,
643
+ previewToken,
644
+ occurrence: structuredClone(preview.occurrence),
645
+ mask: structuredClone(preview.mask),
646
+ observedMask,
647
+ before,
648
+ after: observedAfter,
649
+ beforeRevision: beforeLive.revision,
650
+ afterRevision: observedLive.revision,
651
+ verification,
652
+ undoAvailable: observedAfter.undoAvailable,
653
+ ...(observedAfter.undoCommand ? { undoCommand: observedAfter.undoCommand } : {}),
654
+ };
655
+ }
656
+ catch (error) {
657
+ const rollback = await this.rollbackFailedMask(before, beforeLive, previewToken, error, observedAfter, observedLive);
658
+ const failure = `${nativeErrorCode(error)}: ${String(error)}`;
659
+ if (rollback.rolledBack)
660
+ throw new Error(`${failure}; mask placement was rolled back`);
661
+ throw new Error(`${failure}; rollback unavailable: ${rollback.detail}`);
662
+ }
663
+ }
664
+ async rollbackFailedMask(before, beforeLive, previewToken, error, after, afterLive) {
665
+ const observedAfter = after ?? await this.inspectRawNative();
666
+ const observedLive = afterLive ?? await this.readLiveState();
667
+ if (!observedAfter.available || !observedAfter.undoAvailable || !observedAfter.undoCommand) {
668
+ return {
669
+ rolledBack: false,
670
+ detail: observedAfter.error?.message ?? "Final Cut did not expose a matching Undo command",
671
+ };
672
+ }
673
+ const revisionChanged = Boolean(observedLive && observedLive.revision.id !== beforeLive.revision.id);
674
+ const undoChanged = observedAfter.undoCommand !== before.undoCommand;
675
+ if (!revisionChanged && !undoChanged) {
676
+ return { rolledBack: false, detail: "Final Cut did not expose a changed revision or Undo command after mask placement" };
677
+ }
678
+ const operationId = opaqueHandle("native-mask-failed");
679
+ this.rememberOperation(operationId, {
680
+ kind: "masking",
681
+ before,
682
+ after: observedAfter,
683
+ beforeLive,
684
+ afterLive: observedLive,
685
+ undoCommand: observedAfter.undoCommand,
686
+ });
687
+ try {
688
+ const undoResult = await this.undo(operationId);
689
+ if (!undoResult.verification.verified) {
690
+ return { rolledBack: false, detail: undoResult.verification.detail };
691
+ }
692
+ }
693
+ catch (rollbackError) {
694
+ return {
695
+ rolledBack: false,
696
+ detail: `operationId=${operationId}; native rollback failed: ${String(rollbackError)}`,
697
+ };
698
+ }
699
+ return { rolledBack: true, detail: `preview=${previewToken}; original failure=${String(error)}` };
700
+ }
553
701
  async executeBladeNative(previewToken) {
554
702
  this.assertEnabled();
555
703
  const preview = this.bladePreviews.get(previewToken);
@@ -654,6 +802,15 @@ export class FinalCutNativeAutomationAdapter {
654
802
  async executeTitleAdd(previewToken) {
655
803
  return this.withNativeUi(() => this.executeTitleAddNative(previewToken));
656
804
  }
805
+ async searchTitles(query) {
806
+ return this.withNativeUi(() => this.searchTitlesNative(query));
807
+ }
808
+ async previewPictureInPicture(request) {
809
+ return this.withNativeUi(() => this.previewPictureInPictureNative(request));
810
+ }
811
+ async executePictureInPicture(previewToken) {
812
+ return this.withNativeUi(() => this.executePictureInPictureNative(previewToken));
813
+ }
657
814
  async searchTransitions(query) {
658
815
  return this.withNativeUi(() => this.searchTransitionsNative(query));
659
816
  }
@@ -663,6 +820,37 @@ export class FinalCutNativeAutomationAdapter {
663
820
  async executeTransitionAdd(previewToken) {
664
821
  return this.withNativeUi(() => this.executeTransitionAddNative(previewToken));
665
822
  }
823
+ async searchTitlesNative(query) {
824
+ this.assertEnabled();
825
+ try {
826
+ await this.ensureTitleBrowserReady();
827
+ const normalizedQuery = query.trim();
828
+ const identity = titleIdentityFromId(normalizedQuery);
829
+ let lastError;
830
+ for (let attempt = 0; attempt < 2; attempt += 1) {
831
+ try {
832
+ return parseTitleMatches(await this.executeNativeScript(titleSearchScript(identity ?? normalizedQuery, identity !== undefined)));
833
+ }
834
+ catch (error) {
835
+ lastError = error;
836
+ if (attempt === 0)
837
+ await this.sleep(250);
838
+ }
839
+ }
840
+ throw lastError;
841
+ }
842
+ catch (error) {
843
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
844
+ }
845
+ }
846
+ async ensureTitleBrowserReady() {
847
+ const output = await this.executeNativeScript(titleBrowserPreflightScript());
848
+ const [frontmost = "false", windowAvailable = "false"] = output.split(String.fromCharCode(31));
849
+ if (frontmost !== "true")
850
+ throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut must be frontmost for title discovery");
851
+ if (windowAvailable !== "true")
852
+ throw new Error("FINAL_CUT_NATIVE_TITLE_BROWSER_UNAVAILABLE: Final Cut's Titles browser is unavailable");
853
+ }
666
854
  async searchTransitionsNative(query) {
667
855
  this.assertEnabled();
668
856
  if (!query.trim())
@@ -914,7 +1102,7 @@ export class FinalCutNativeAutomationAdapter {
914
1102
  const endTimecode = this.toTimecode(preview.end, beforeLive);
915
1103
  try {
916
1104
  await this.executeNativeSequence(async () => {
917
- await this.executor(titleAssetSelectionScript(preview.asset.name));
1105
+ await this.executor(titleAssetSelectionScript(preview.asset.name, nativeTitleIdentity(preview.asset)));
918
1106
  await this.focusTimelineForMediaInsertion();
919
1107
  await this.executor(setPlayheadScript(startTimecode));
920
1108
  await this.waitForPlayhead(preview.start, beforeLive.sequence?.id);
@@ -979,6 +1167,209 @@ export class FinalCutNativeAutomationAdapter {
979
1167
  ...(after.undoCommand ? { undoCommand: after.undoCommand } : {}),
980
1168
  };
981
1169
  }
1170
+ async previewPictureInPictureNative(request) {
1171
+ this.assertEnabled();
1172
+ const media = this.mediaHandles.get(request.mediaHandle);
1173
+ if (!media)
1174
+ throw new Error(`FINAL_CUT_NATIVE_MEDIA_HANDLE_STALE: unknown media handle ${request.mediaHandle}`);
1175
+ if (this.selectedMediaHandle !== request.mediaHandle) {
1176
+ throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_REQUIRED: select one Browser media result before picture-in-picture placement");
1177
+ }
1178
+ const anchorOccurrence = this.occurrenceHandles.get(request.anchorOccurrenceHandle);
1179
+ if (!anchorOccurrence) {
1180
+ throw new Error(`FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: unknown anchor occurrence ${request.anchorOccurrenceHandle}`);
1181
+ }
1182
+ await this.ensureOccurrenceRange(anchorOccurrence);
1183
+ const context = await this.requireTimelineContext();
1184
+ if (!context.frontmost)
1185
+ throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
1186
+ const live = await this.requireLiveState();
1187
+ const sequenceStart = live.sequenceTimeRange?.start ?? live.sequence?.startTime;
1188
+ const sequenceDuration = live.sequenceTimeRange?.duration ?? live.sequence?.duration;
1189
+ const frameDuration = live.sequence?.frameDuration;
1190
+ if (!sequenceStart || !sequenceDuration || !frameDuration) {
1191
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut sequence timing is unavailable");
1192
+ }
1193
+ const start = structuredClone(request.start);
1194
+ const duration = structuredClone(request.duration);
1195
+ const end = addRational(start, duration);
1196
+ validatePictureInPictureRequest(request, sequenceStart, sequenceDuration, frameDuration, start, end);
1197
+ validatePictureInPictureAnchor(anchorOccurrence, live);
1198
+ const expiresAt = this.now() + 30_000;
1199
+ const previewToken = opaqueHandle("picture-in-picture-preview");
1200
+ this.pictureInPicturePreviews.set(previewToken, {
1201
+ mediaHandle: request.mediaHandle,
1202
+ anchorOccurrence: structuredClone(anchorOccurrence),
1203
+ start,
1204
+ end,
1205
+ duration,
1206
+ position: structuredClone(request.position),
1207
+ scale: request.scale,
1208
+ ...(request.crop ? { crop: structuredClone(request.crop) } : {}),
1209
+ ...(request.frame ? { frame: structuredClone(request.frame) } : {}),
1210
+ sequenceId: live.sequence?.id,
1211
+ revision: live.revision.id,
1212
+ expiresAt,
1213
+ });
1214
+ return {
1215
+ previewToken,
1216
+ media: structuredClone(media),
1217
+ anchorOccurrence: structuredClone(anchorOccurrence),
1218
+ start,
1219
+ end,
1220
+ duration,
1221
+ position: structuredClone(request.position),
1222
+ scale: request.scale,
1223
+ ...(request.crop ? { crop: structuredClone(request.crop) } : {}),
1224
+ ...(request.frame ? { frame: structuredClone(request.frame) } : {}),
1225
+ ...(live.sequence?.id ? { sequenceId: live.sequence.id } : {}),
1226
+ revision: live.revision.id,
1227
+ command: "Add native picture-in-picture",
1228
+ expiresAt: new Date(expiresAt).toISOString(),
1229
+ };
1230
+ }
1231
+ async executePictureInPictureNative(previewToken) {
1232
+ this.assertEnabled();
1233
+ const preview = this.pictureInPicturePreviews.get(previewToken);
1234
+ if (!preview)
1235
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: unknown native picture-in-picture preview");
1236
+ this.pictureInPicturePreviews.delete(previewToken);
1237
+ if (this.now() > preview.expiresAt)
1238
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: native picture-in-picture preview has expired");
1239
+ const media = this.mediaHandles.get(preview.mediaHandle);
1240
+ if (!media)
1241
+ throw new Error(`FINAL_CUT_NATIVE_MEDIA_HANDLE_STALE: unknown media handle ${preview.mediaHandle}`);
1242
+ if (this.selectedMediaHandle !== preview.mediaHandle) {
1243
+ throw new Error("FINAL_CUT_NATIVE_MEDIA_SELECTION_REQUIRED: selected Browser media changed before picture-in-picture placement");
1244
+ }
1245
+ const before = await this.requireTimelineContext();
1246
+ const beforeLive = await this.requireLiveState();
1247
+ validatePictureInPicturePreviewBinding(preview, beforeLive);
1248
+ const anchorOccurrence = this.occurrenceHandles.get(preview.anchorOccurrence.handle) ?? preview.anchorOccurrence;
1249
+ validatePictureInPictureAnchor(anchorOccurrence, beforeLive);
1250
+ const startTimecode = this.toTimecode(preview.start, beforeLive);
1251
+ const endTimecode = this.toTimecode(preview.end, beforeLive);
1252
+ const operationId = opaqueHandle("native-picture-in-picture");
1253
+ try {
1254
+ await this.executeNativeSequence(async () => {
1255
+ await this.selectMediaNative(preview.mediaHandle);
1256
+ await this.focusTimelineForMediaInsertion();
1257
+ if (this.canDriveNativeMouse && anchorOccurrence.timelineOffset !== undefined) {
1258
+ await selectTimelineOccurrence(this.executor, anchorOccurrence.timelineOffset);
1259
+ }
1260
+ await this.validateSelectedPictureInPictureAnchor(anchorOccurrence);
1261
+ await this.executor(setPlayheadScript(startTimecode));
1262
+ await this.waitForPlayhead(preview.start, beforeLive.sequence?.id);
1263
+ await this.executor(markRangeStartScript());
1264
+ await this.executor(setPlayheadScript(endTimecode));
1265
+ await this.waitForPlayhead(preview.end, beforeLive.sequence?.id);
1266
+ await this.executor(markRangeEndAndConnectPictureInPictureScript());
1267
+ await this.executor(pictureInPictureTransformScript(preview));
1268
+ }, async (recovered) => {
1269
+ this.assertRetryContext(before, recovered, true);
1270
+ validatePictureInPicturePreviewBinding(preview, await this.requireLiveState());
1271
+ await this.selectMediaNative(preview.mediaHandle);
1272
+ await this.focusTimelineForMediaInsertion();
1273
+ });
1274
+ }
1275
+ catch (error) {
1276
+ const observedContext = await this.inspectRawNative();
1277
+ const observedLive = await this.readLiveState();
1278
+ if (observedLive && observedLive.revision.id !== beforeLive.revision.id && observedContext.undoCommand) {
1279
+ this.rememberOperation(operationId, {
1280
+ kind: "picture-in-picture",
1281
+ before,
1282
+ after: observedContext,
1283
+ beforeLive,
1284
+ afterLive: observedLive,
1285
+ undoCommand: observedContext.undoCommand,
1286
+ });
1287
+ try {
1288
+ await this.undo(operationId);
1289
+ }
1290
+ catch (rollbackError) {
1291
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}; operationId=${operationId}; native rollback failed: ${String(rollbackError)}`);
1292
+ }
1293
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}; picture-in-picture placement was rolled back`);
1294
+ }
1295
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
1296
+ }
1297
+ let after;
1298
+ let afterLive;
1299
+ try {
1300
+ after = await this.requireTimelineContext();
1301
+ afterLive = await this.waitForRevision(beforeLive.revision.id);
1302
+ const occurrence = await this.readPictureInPictureOccurrence(preview, anchorOccurrence);
1303
+ const observed = parsePictureInPictureReadback(await this.executor(pictureInPictureInspectorReadbackScript()));
1304
+ const verification = verifyNativePictureInPicture({ ...preview, media }, after, beforeLive, afterLive, observed, occurrence);
1305
+ const operation = {
1306
+ kind: "picture-in-picture",
1307
+ before,
1308
+ after,
1309
+ beforeLive,
1310
+ afterLive,
1311
+ undoCommand: after.undoCommand,
1312
+ };
1313
+ if (!verification.verified) {
1314
+ if (afterLive.revision.id !== beforeLive.revision.id && after.undoAvailable && after.undoCommand) {
1315
+ this.rememberOperation(operationId, operation);
1316
+ try {
1317
+ await this.undo(operationId);
1318
+ }
1319
+ catch (rollbackError) {
1320
+ throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}; operationId=${operationId}; native rollback failed: ${String(rollbackError)}`);
1321
+ }
1322
+ throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}; picture-in-picture placement was rolled back`);
1323
+ }
1324
+ throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}`);
1325
+ }
1326
+ this.rememberOperation(operationId, operation);
1327
+ return {
1328
+ operationId,
1329
+ previewToken,
1330
+ media: structuredClone(media),
1331
+ anchorOccurrence: structuredClone(anchorOccurrence),
1332
+ occurrence: structuredClone(occurrence),
1333
+ start: structuredClone(preview.start),
1334
+ end: structuredClone(preview.end),
1335
+ duration: structuredClone(preview.duration),
1336
+ position: structuredClone(preview.position),
1337
+ scale: preview.scale,
1338
+ ...(preview.crop ? { crop: structuredClone(preview.crop) } : {}),
1339
+ ...(preview.frame ? { frame: structuredClone(preview.frame) } : {}),
1340
+ observed,
1341
+ before,
1342
+ after,
1343
+ beforeRevision: beforeLive.revision,
1344
+ afterRevision: afterLive.revision,
1345
+ verification,
1346
+ undoAvailable: after.undoAvailable,
1347
+ ...(after.undoCommand ? { undoCommand: after.undoCommand } : {}),
1348
+ };
1349
+ }
1350
+ catch (error) {
1351
+ const observedContext = after ?? await this.inspectRawNative();
1352
+ const observedLive = afterLive ?? await this.readLiveState();
1353
+ if (observedLive && observedLive.revision.id !== beforeLive.revision.id && observedContext.undoCommand) {
1354
+ this.rememberOperation(operationId, {
1355
+ kind: "picture-in-picture",
1356
+ before,
1357
+ after: observedContext,
1358
+ beforeLive,
1359
+ afterLive: observedLive,
1360
+ undoCommand: observedContext.undoCommand,
1361
+ });
1362
+ try {
1363
+ await this.undo(operationId);
1364
+ }
1365
+ catch (rollbackError) {
1366
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}; operationId=${operationId}; native rollback failed: ${String(rollbackError)}`);
1367
+ }
1368
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}; picture-in-picture placement was rolled back`);
1369
+ }
1370
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
1371
+ }
1372
+ }
982
1373
  async previewMediaInsertionNative(operation, mediaHandle, selectionMode = "handle") {
983
1374
  this.assertEnabled();
984
1375
  const media = this.mediaHandles.get(mediaHandle);
@@ -1479,6 +1870,50 @@ export class FinalCutNativeAutomationAdapter {
1479
1870
  }
1480
1871
  }
1481
1872
  }
1873
+ async validateSelectedPictureInPictureAnchor(anchor) {
1874
+ if (!anchor.identity) {
1875
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_ID_UNAVAILABLE: native PIP requires a stable anchor occurrence identity");
1876
+ }
1877
+ const context = await this.requireTimelineContext();
1878
+ if (context.target.kind !== "selected-clip" || context.target.identity !== anchor.identity) {
1879
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: selected timeline occurrence does not match the requested anchor");
1880
+ }
1881
+ const reread = await this.locateOccurrenceNative(anchor.mediaHandle, true);
1882
+ if (reread.status !== "unique" || reread.occurrences[0]?.identity !== anchor.identity) {
1883
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: anchor occurrence identity became ambiguous or changed");
1884
+ }
1885
+ const observed = reread.occurrences[0];
1886
+ if (anchor.start && observed.start && parseRationalString(anchor.start, "anchor start")
1887
+ && compareRational(parseRationalString(anchor.start, "anchor start"), parseRationalString(observed.start, "observed anchor start")) !== 0) {
1888
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: anchor occurrence start changed");
1889
+ }
1890
+ if (anchor.duration && observed.duration && parseRationalString(anchor.duration, "anchor duration")
1891
+ && compareRational(parseRationalString(anchor.duration, "anchor duration"), parseRationalString(observed.duration, "observed anchor duration")) !== 0) {
1892
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: anchor occurrence duration changed");
1893
+ }
1894
+ }
1895
+ async readPictureInPictureOccurrence(preview, anchor) {
1896
+ const located = await this.locateOccurrenceNative(preview.mediaHandle, true);
1897
+ const matches = located.occurrences.filter((occurrence) => pictureInPictureOccurrenceMatchesRange(occurrence, preview));
1898
+ if (matches.length === 0) {
1899
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_OCCURRENCE_UNAVAILABLE: inserted clip range was not read back");
1900
+ }
1901
+ if (matches.length > 1) {
1902
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_OCCURRENCE_AMBIGUOUS: multiple inserted clips match the requested range");
1903
+ }
1904
+ const occurrence = matches[0];
1905
+ if (!occurrence.identity) {
1906
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_OCCURRENCE_UNAVAILABLE: inserted clip has no stable identity");
1907
+ }
1908
+ const context = await this.requireTimelineContext();
1909
+ if (context.target.kind !== "selected-clip" || context.target.identity !== occurrence.identity) {
1910
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_OCCURRENCE_STALE: selected clip does not match the inserted occurrence");
1911
+ }
1912
+ if (!anchor.identity) {
1913
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_ID_UNAVAILABLE: native PIP anchor identity is unavailable");
1914
+ }
1915
+ return occurrence;
1916
+ }
1482
1917
  async ensureOccurrenceRange(occurrence) {
1483
1918
  if (occurrence.start && occurrence.duration)
1484
1919
  return;
@@ -1673,6 +2108,10 @@ function assertNativeTitleAsset(asset) {
1673
2108
  if (asset.kind !== "title")
1674
2109
  throw new Error(`TITLE_ASSET_INCOMPATIBLE: ${asset.id} is not a Final Cut title asset`);
1675
2110
  }
2111
+ function nativeTitleIdentity(asset) {
2112
+ const idIdentity = titleIdentityFromId(asset.id);
2113
+ return idIdentity?.trim() || undefined;
2114
+ }
1676
2115
  function publicTitleAsset(asset) {
1677
2116
  return { id: asset.id, kind: asset.kind, name: asset.name, vendor: asset.vendor };
1678
2117
  }
@@ -1696,6 +2135,156 @@ function verifyNativeTitle(preview, beforeLive, after, afterLive) {
1696
2135
  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}`,
1697
2136
  };
1698
2137
  }
2138
+ function validatePictureInPictureRequest(request, sequenceStart, sequenceDuration, frameDuration, start, end) {
2139
+ if (compareRational(request.duration, zeroRational()) <= 0) {
2140
+ throw new Error("INVALID_OPERATION: native picture-in-picture duration must be positive");
2141
+ }
2142
+ if (!isFrameAligned(start, sequenceStart, frameDuration) || !isFrameAligned(request.duration, zeroRational(), frameDuration)) {
2143
+ throw new Error("INVALID_OPERATION: native picture-in-picture range must align to the sequence frame duration");
2144
+ }
2145
+ const sequenceEnd = addRational(sequenceStart, sequenceDuration);
2146
+ if (compareRational(start, sequenceStart) < 0 || compareRational(end, sequenceEnd) > 0) {
2147
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_RANGE_OUT_OF_BOUNDS: placement must be inside the active sequence");
2148
+ }
2149
+ if (!Number.isFinite(request.position.x) || !Number.isFinite(request.position.y)) {
2150
+ throw new Error("INVALID_OPERATION: native picture-in-picture position must be finite");
2151
+ }
2152
+ if (!Number.isFinite(request.scale) || request.scale <= 0) {
2153
+ throw new Error("INVALID_OPERATION: native picture-in-picture scale must be positive");
2154
+ }
2155
+ validatePictureInPictureStyle(request.crop, request.frame);
2156
+ }
2157
+ function validatePictureInPictureStyle(crop, frame) {
2158
+ if (crop) {
2159
+ const values = [crop.top, crop.right, crop.bottom, crop.left];
2160
+ if (!values.every((value) => Number.isFinite(value) && value >= 0 && value < 1)
2161
+ || crop.left + crop.right >= 1
2162
+ || crop.top + crop.bottom >= 1) {
2163
+ throw new Error("INVALID_OPERATION: native picture-in-picture crop must leave a visible rectangle");
2164
+ }
2165
+ }
2166
+ if (frame && (frame.style !== "solid" || !/^#[0-9a-f]{6}$/i.test(frame.color) || !Number.isFinite(frame.width) || frame.width < 0)) {
2167
+ throw new Error("INVALID_OPERATION: native picture-in-picture frame must be a solid six-digit hex color with nonnegative width");
2168
+ }
2169
+ }
2170
+ function validatePictureInPictureAnchor(anchor, live) {
2171
+ if (!anchor.identity) {
2172
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_ID_UNAVAILABLE: native PIP requires a stable anchor occurrence identity");
2173
+ }
2174
+ if (anchor.sequenceId && live.sequence?.id !== anchor.sequenceId) {
2175
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: active sequence changed");
2176
+ }
2177
+ if (anchor.revision && live.revision.id !== anchor.revision) {
2178
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: playhead or timeline revision changed");
2179
+ }
2180
+ if (!anchor.start || !anchor.duration) {
2181
+ throw new Error("FINAL_CUT_NATIVE_EDIT_POINT_POSITION_UNAVAILABLE: anchor occurrence has no exact timeline range");
2182
+ }
2183
+ }
2184
+ function validatePictureInPicturePreviewBinding(preview, live) {
2185
+ if (preview.sequenceId && live.sequence?.id !== preview.sequenceId) {
2186
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: active sequence changed");
2187
+ }
2188
+ if (live.revision.id !== preview.revision) {
2189
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: playhead or timeline revision changed");
2190
+ }
2191
+ validatePictureInPictureAnchor(preview.anchorOccurrence, live);
2192
+ }
2193
+ function parsePictureInPictureReadback(output) {
2194
+ const [xText, yText, scalePercentText, frameStyle = "", frameColor = "", frameWidthText = "", topText = "", rightText = "", bottomText = "", leftText = ""] = output.split(String.fromCharCode(31));
2195
+ const x = inspectorNumber(xText);
2196
+ const y = inspectorNumber(yText);
2197
+ const scalePercent = inspectorNumber(scalePercentText);
2198
+ if (![x, y, scalePercent].every(Number.isFinite) || scalePercent <= 0) {
2199
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_READBACK_UNAVAILABLE: Final Cut did not expose finite transform values");
2200
+ }
2201
+ const readback = {
2202
+ position: { x, y },
2203
+ scale: scalePercent / 100,
2204
+ };
2205
+ if (frameStyle || frameColor || frameWidthText) {
2206
+ const frameWidth = inspectorNumber(frameWidthText);
2207
+ if (!frameStyle || !frameColor || !Number.isFinite(frameWidth)) {
2208
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_READBACK_UNAVAILABLE: Final Cut returned an incomplete frame");
2209
+ }
2210
+ const frame = { style: frameStyle, color: frameColor, width: frameWidth };
2211
+ validatePictureInPictureStyle(undefined, frame);
2212
+ readback.frame = frame;
2213
+ }
2214
+ if (topText || rightText || bottomText || leftText) {
2215
+ const crop = {
2216
+ top: inspectorFraction(topText),
2217
+ right: inspectorFraction(rightText),
2218
+ bottom: inspectorFraction(bottomText),
2219
+ left: inspectorFraction(leftText),
2220
+ };
2221
+ if (![crop.top, crop.right, crop.bottom, crop.left].every(Number.isFinite)) {
2222
+ throw new Error("FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_READBACK_UNAVAILABLE: Final Cut returned an incomplete crop");
2223
+ }
2224
+ validatePictureInPictureStyle(crop, undefined);
2225
+ readback.crop = crop;
2226
+ }
2227
+ return readback;
2228
+ }
2229
+ function inspectorNumber(value) {
2230
+ const normalized = (value ?? "").trim().replace(/,/g, "").replace(/%$/, "");
2231
+ const number = Number(normalized);
2232
+ return Number.isFinite(number) ? number : Number.NaN;
2233
+ }
2234
+ function inspectorFraction(value) {
2235
+ const normalized = (value ?? "").trim();
2236
+ const number = inspectorNumber(normalized);
2237
+ return normalized.endsWith("%") ? number / 100 : number;
2238
+ }
2239
+ function verifyNativePictureInPicture(preview, after, beforeLive, afterLive, observed, occurrence) {
2240
+ if (afterLive.revision.id === beforeLive.revision.id) {
2241
+ return { verified: false, detail: "Final Cut did not expose a new revision after native picture-in-picture placement" };
2242
+ }
2243
+ if (after.target.kind !== "selected-clip") {
2244
+ return { verified: false, detail: "Final Cut did not expose the inserted picture-in-picture clip as the selected timeline item" };
2245
+ }
2246
+ if (!occurrence.identity || after.target.identity !== occurrence.identity) {
2247
+ return { verified: false, detail: "Final Cut did not expose the inserted picture-in-picture occurrence identity" };
2248
+ }
2249
+ if (!pictureInPictureOccurrenceMatchesRange(occurrence, preview)) {
2250
+ return { verified: false, detail: "Final Cut did not read back the requested picture-in-picture timeline range" };
2251
+ }
2252
+ const observedName = after.target.name ?? "";
2253
+ if (observedName && !observedName.toLowerCase().includes(preview.media.name.toLowerCase())) {
2254
+ return { verified: false, detail: `Final Cut selected ${observedName}, not ${preview.media.name}` };
2255
+ }
2256
+ if (Math.abs(observed.position.x - preview.position.x) > 0.001 || Math.abs(observed.position.y - preview.position.y) > 0.001) {
2257
+ return { verified: false, detail: `Final Cut read back position ${observed.position.x},${observed.position.y}, expected ${preview.position.x},${preview.position.y}` };
2258
+ }
2259
+ if (Math.abs(observed.scale - preview.scale) > 0.0001) {
2260
+ return { verified: false, detail: `Final Cut read back scale ${observed.scale}, expected ${preview.scale}` };
2261
+ }
2262
+ if (preview.crop && JSON.stringify(observed.crop) !== JSON.stringify(preview.crop)) {
2263
+ return { verified: false, detail: "Final Cut did not read back the requested picture-in-picture crop" };
2264
+ }
2265
+ const observedFrame = observed.frame
2266
+ ? { ...observed.frame, color: observed.frame.color.toLowerCase() }
2267
+ : undefined;
2268
+ const previewFrame = preview.frame
2269
+ ? { ...preview.frame, color: preview.frame.color.toLowerCase() }
2270
+ : undefined;
2271
+ if (preview.frame && JSON.stringify(observedFrame) !== JSON.stringify(previewFrame)) {
2272
+ return { verified: false, detail: "Final Cut did not read back the requested picture-in-picture frame" };
2273
+ }
2274
+ if (!after.undoAvailable || !after.undoCommand) {
2275
+ return { verified: false, detail: "Final Cut did not expose an Undo command for native picture-in-picture placement" };
2276
+ }
2277
+ return {
2278
+ verified: true,
2279
+ detail: `Final Cut verified ${preview.media.name} occurrence ${occurrence.identity} at ${preview.start.value}/${preview.start.timescale}-${preview.end.value}/${preview.end.timescale} on the selected anchor's connected lane with transform readback at revision ${afterLive.revision.id}`,
2280
+ };
2281
+ }
2282
+ function pictureInPictureOccurrenceMatchesRange(occurrence, preview) {
2283
+ if (!occurrence.start || !occurrence.duration)
2284
+ return false;
2285
+ return compareRational(parseRationalString(occurrence.start, "picture-in-picture occurrence start"), preview.start) === 0
2286
+ && compareRational(parseRationalString(occurrence.duration, "picture-in-picture occurrence duration"), preview.duration) === 0;
2287
+ }
1699
2288
  function assertNativeTransitionAsset(asset) {
1700
2289
  if (!asset.id.trim() || !asset.name.trim() || !asset.identity.trim()) {
1701
2290
  throw new Error("TRANSITION_ASSET_NOT_FOUND: native transition asset identity is incomplete");
@@ -1730,6 +2319,92 @@ function validateTransitionEditPoint(before, after, duration, live) {
1730
2319
  }
1731
2320
  return beforeEnd;
1732
2321
  }
2322
+ function assertNativeMaskConfiguration(mask) {
2323
+ if (!mask || mask.mode !== "rectangle") {
2324
+ throw new Error("CAPABILITY_UNAVAILABLE: native Final Cut masking supports bounded Draw Mask only");
2325
+ }
2326
+ const { x, y, width, height } = mask.bounds;
2327
+ if (![x, y, width, height].every(Number.isFinite)
2328
+ || x < 0 || y < 0 || width <= 0 || height <= 0
2329
+ || x + width > 1 || y + height > 1) {
2330
+ throw new Error("INVALID_OPERATION: native Draw Mask bounds must be normalized");
2331
+ }
2332
+ }
2333
+ function validateMaskPreviewBinding(preview, live) {
2334
+ if (preview.sequenceId && live.sequence?.id !== preview.sequenceId) {
2335
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: active sequence changed");
2336
+ }
2337
+ if (live.revision.id !== preview.revision) {
2338
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: playhead or timeline revision changed");
2339
+ }
2340
+ if (preview.occurrence.sequenceId && live.sequence?.id !== preview.occurrence.sequenceId) {
2341
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: target occurrence sequence changed");
2342
+ }
2343
+ }
2344
+ function assertNativeMaskTarget(context, occurrence) {
2345
+ if (context.target.kind !== "selected-clip") {
2346
+ throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: select exactly one timeline occurrence");
2347
+ }
2348
+ if (context.target.name && context.target.name !== occurrence.name) {
2349
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: selected timeline occurrence changed");
2350
+ }
2351
+ if (!occurrence.nativeIdentity || !context.target.identity || context.target.identity !== occurrence.nativeIdentity) {
2352
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: selected timeline occurrence changed");
2353
+ }
2354
+ }
2355
+ function parseNativeMaskReadback(output) {
2356
+ const marker = "FRAMEKIT_NATIVE_MASK_READBACK|";
2357
+ const markerIndex = output.lastIndexOf(marker);
2358
+ if (markerIndex < 0) {
2359
+ throw new Error("FINAL_CUT_NATIVE_MASK_READBACK_UNAVAILABLE: Final Cut did not return Draw Mask properties");
2360
+ }
2361
+ const [mode, xText, yText, widthText, heightText] = output
2362
+ .slice(markerIndex + marker.length)
2363
+ .split(/\r?\n/, 1)[0]
2364
+ .trim()
2365
+ .split("|");
2366
+ const values = [xText, yText, widthText, heightText].map((value) => Number(value));
2367
+ if (mode !== "rectangle" || values.some((value) => !Number.isFinite(value))) {
2368
+ throw new Error("FINAL_CUT_NATIVE_MASK_READBACK_UNAVAILABLE: Final Cut returned malformed Draw Mask properties");
2369
+ }
2370
+ const mask = {
2371
+ mode: "rectangle",
2372
+ bounds: { x: values[0], y: values[1], width: values[2], height: values[3] },
2373
+ };
2374
+ assertNativeMaskConfiguration(mask);
2375
+ return mask;
2376
+ }
2377
+ function verifyNativeMask(preview, after, beforeLive, afterLive, observedMask) {
2378
+ if (!afterLive.revision.id || afterLive.revision.id === beforeLive.revision.id) {
2379
+ return { verified: false, detail: "Final Cut did not expose a new revision after native Draw Mask placement" };
2380
+ }
2381
+ if (after.target.kind !== "selected-clip") {
2382
+ return { verified: false, detail: "Final Cut did not retain the masked occurrence as the selected timeline item" };
2383
+ }
2384
+ if (!preview.occurrence.nativeIdentity || after.target.identity !== preview.occurrence.nativeIdentity) {
2385
+ return { verified: false, detail: "Final Cut did not retain the exact masked timeline occurrence" };
2386
+ }
2387
+ if (!after.undoAvailable || !after.undoCommand) {
2388
+ return { verified: false, detail: "Final Cut did not expose an Undo command for native Draw Mask placement" };
2389
+ }
2390
+ if (!sameNativeMask(preview.mask, observedMask)) {
2391
+ return {
2392
+ verified: false,
2393
+ detail: `Final Cut read back Draw Mask ${JSON.stringify(observedMask)}, expected ${JSON.stringify(preview.mask)}`,
2394
+ };
2395
+ }
2396
+ return {
2397
+ verified: true,
2398
+ detail: `Final Cut verified Draw Mask bounds at revision ${afterLive.revision.id}`,
2399
+ };
2400
+ }
2401
+ function sameNativeMask(left, right) {
2402
+ return left.mode === right.mode
2403
+ && left.bounds.x === right.bounds.x
2404
+ && left.bounds.y === right.bounds.y
2405
+ && left.bounds.width === right.bounds.width
2406
+ && left.bounds.height === right.bounds.height;
2407
+ }
1733
2408
  function validateTransitionPreviewBinding(preview, live) {
1734
2409
  if (preview.sequenceId && live.sequence?.id !== preview.sequenceId) {
1735
2410
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: active sequence changed");
@@ -1769,6 +2444,28 @@ function verifyNativeTransition(preview, after, beforeLive, afterLive, observedD
1769
2444
  detail: `Final Cut verified ${preview.asset.name} at ${preview.editPoint.value}/${preview.editPoint.timescale} for requested and observed duration ${observedDuration.value}/${observedDuration.timescale} at revision ${afterLive.revision.id}`,
1770
2445
  };
1771
2446
  }
2447
+ function parseTitleMatches(output) {
2448
+ const matches = new Map();
2449
+ for (const record of output.split(String.fromCharCode(30)).map((value) => value.trim()).filter(Boolean)) {
2450
+ const [name = "", identity = ""] = record.split(String.fromCharCode(31));
2451
+ if (!name || !identity) {
2452
+ throw new Error("FINAL_CUT_NATIVE_TITLE_ID_UNAVAILABLE: title browser did not expose stable identities");
2453
+ }
2454
+ const match = {
2455
+ id: `final-cut:title:${identity}`,
2456
+ kind: "title",
2457
+ name,
2458
+ vendor: "Final Cut Pro",
2459
+ identity,
2460
+ };
2461
+ matches.set(match.id, match);
2462
+ }
2463
+ return [...matches.values()].sort((left, right) => `${left.name}:${left.identity}`.localeCompare(`${right.name}:${right.identity}`));
2464
+ }
2465
+ function titleIdentityFromId(value) {
2466
+ const prefix = "final-cut:title:";
2467
+ return value.startsWith(prefix) ? value.slice(prefix.length) : undefined;
2468
+ }
1772
2469
  function parseTransitionMatches(output) {
1773
2470
  return output
1774
2471
  .split(String.fromCharCode(30))
@@ -1863,6 +2560,21 @@ function requireFrontmostAppleScript() {
1863
2560
  }
1864
2561
  function timelinePreflightScript() {
1865
2562
  return `
2563
+ on findInspectorField(fieldLabel)
2564
+ tell application "System Events"
2565
+ tell process "Final Cut Pro"
2566
+ repeat with candidate in text fields of front window
2567
+ try
2568
+ set candidateDescription to description of candidate as text
2569
+ set candidateName to name of candidate as text
2570
+ if candidateDescription contains fieldLabel or candidateName contains fieldLabel then return candidate
2571
+ end try
2572
+ end repeat
2573
+ end tell
2574
+ end tell
2575
+ return missing value
2576
+ end findInspectorField
2577
+
1866
2578
  tell application "System Events"
1867
2579
  tell process "Final Cut Pro"
1868
2580
  set frontmost to true
@@ -2987,7 +3699,12 @@ function locateOccurrenceScript(match, scanAll) {
2987
3699
  end repeat
2988
3700
  if candidateStart is not "" and candidateDuration is not "" then
2989
3701
  set candidateOffset to ((item 1 of candidatePosition) + 10) - (item 1 of mainOrigin)
2990
- set output to output & targetName & (ASCII character 31) & candidateRole & (ASCII character 31) & sourceIdentity & (ASCII character 31) & (candidateOffset as text) & (ASCII character 31) & candidateStart & (ASCII character 31) & candidateDuration & (ASCII character 30)
3702
+ set candidateIdentity to ""
3703
+ try
3704
+ set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
3705
+ end try
3706
+ if candidateIdentity is "" then error "FINAL_CUT_NATIVE_OCCURRENCE_ID_UNAVAILABLE: timeline clip has no AXIdentifier"
3707
+ set output to output & targetName & (ASCII character 31) & candidateRole & (ASCII character 31) & sourceIdentity & (ASCII character 31) & (candidateOffset as text) & (ASCII character 31) & candidateStart & (ASCII character 31) & candidateDuration & (ASCII character 31) & candidateIdentity & (ASCII character 30)
2991
3708
  end if
2992
3709
  else
2993
3710
  set shouldDescend to false
@@ -3484,6 +4201,73 @@ function applyTransitionScript(duration, frameDuration) {
3484
4201
  end tell
3485
4202
  end tell`;
3486
4203
  }
4204
+ function applyMaskScript(mask) {
4205
+ const { x, y, width, height } = mask.bounds;
4206
+ const values = [x, y, width, height].map((value) => value.toString());
4207
+ return `
4208
+ tell application "System Events"
4209
+ tell process "Final Cut Pro"
4210
+ ${requireFrontmostAppleScript()}
4211
+ -- Apply native Draw Mask to the already selected timeline occurrence.
4212
+ click menu item "Show Effects" of menu "Window" of menu bar 1
4213
+ delay 0.3
4214
+ set effectSearchField to missing value
4215
+ repeat with candidate in entire contents of front window
4216
+ try
4217
+ set candidateRole to role of candidate as text
4218
+ set candidateDescription to description of candidate as text
4219
+ if (candidateRole is "AXTextField" or candidateRole is "AXSearchField") and (candidateDescription contains "search" or candidateDescription contains "Search") then
4220
+ set effectSearchField to candidate
4221
+ exit repeat
4222
+ end if
4223
+ end try
4224
+ end repeat
4225
+ if effectSearchField is missing value then error "FINAL_CUT_NATIVE_MASK_UNAVAILABLE: Final Cut did not expose the Effects search field"
4226
+ set value of effectSearchField to "Draw Mask"
4227
+ key code 36
4228
+ delay 0.3
4229
+ set drawMaskEffect to missing value
4230
+ repeat with candidate in entire contents of front window
4231
+ try
4232
+ set candidateName to name of candidate as text
4233
+ if candidateName is "Draw Mask" then
4234
+ set drawMaskEffect to candidate
4235
+ exit repeat
4236
+ end if
4237
+ end try
4238
+ end repeat
4239
+ if drawMaskEffect is missing value then error "FINAL_CUT_NATIVE_MASK_UNAVAILABLE: Final Cut did not expose the Draw Mask effect"
4240
+ perform action "AXPress" of drawMaskEffect
4241
+ delay 0.4
4242
+ -- Draw Mask's normalized inspector fields must be both writable and readable.
4243
+ set positionXField to missing value
4244
+ set positionYField to missing value
4245
+ set widthField to missing value
4246
+ set heightField to missing value
4247
+ repeat with candidate in entire contents of front window
4248
+ try
4249
+ set candidateName to name of candidate as text
4250
+ if candidateName contains "Position X" then set positionXField to candidate
4251
+ if candidateName contains "Position Y" then set positionYField to candidate
4252
+ if candidateName contains "Width" then set widthField to candidate
4253
+ if candidateName contains "Height" then set heightField to candidate
4254
+ end try
4255
+ end repeat
4256
+ if positionXField is missing value or positionYField is missing value or widthField is missing value or heightField is missing value then error "FINAL_CUT_NATIVE_MASK_READBACK_UNAVAILABLE: Draw Mask inspector fields are not accessible"
4257
+ set value of positionXField to ${appleScriptString(values[0])}
4258
+ set value of positionYField to ${appleScriptString(values[1])}
4259
+ set value of widthField to ${appleScriptString(values[2])}
4260
+ set value of heightField to ${appleScriptString(values[3])}
4261
+ key code 36
4262
+ delay 0.2
4263
+ set observedX to value of positionXField as text
4264
+ set observedY to value of positionYField as text
4265
+ set observedWidth to value of widthField as text
4266
+ set observedHeight to value of heightField as text
4267
+ return "FRAMEKIT_NATIVE_MASK_READBACK|rectangle|" & observedX & "|" & observedY & "|" & observedWidth & "|" & observedHeight
4268
+ end tell
4269
+ end tell`;
4270
+ }
3487
4271
  function occurrenceRangeEndpointScript(timelineOffset, endpoint) {
3488
4272
  const shortcut = endpoint === "start" ? "i" : "o";
3489
4273
  return `
@@ -3502,13 +4286,138 @@ function occurrenceRangeEndpointScript(timelineOffset, endpoint) {
3502
4286
  end tell
3503
4287
  end tell`;
3504
4288
  }
3505
- function titleAssetSelectionScript(assetName) {
4289
+ function titleSearchScript(query, identityQuery = false) {
4290
+ const searchQuery = identityQuery ? "" : query;
4291
+ return `
4292
+ using terms from application "System Events"
4293
+ on titlePaneVisible(candidate, mainOrigin, mainSize)
4294
+ try
4295
+ set candidatePosition to position of candidate
4296
+ set candidateSize to size of candidate
4297
+ set candidateX to item 1 of candidatePosition
4298
+ set candidateY to item 2 of candidatePosition
4299
+ set candidateRight to candidateX + (item 1 of candidateSize)
4300
+ set candidateBottom to candidateY + (item 2 of candidateSize)
4301
+ set minimumX to (item 1 of mainOrigin) + ((item 1 of mainSize) * 0.02)
4302
+ set minimumY to (item 2 of mainOrigin) + ((item 2 of mainSize) * 0.25)
4303
+ set maximumX to (item 1 of mainOrigin) + (item 1 of mainSize)
4304
+ set maximumY to (item 2 of mainOrigin) + (item 2 of mainSize)
4305
+ return candidateRight is greater than minimumX and candidateBottom is greater than minimumY and candidateX is less than maximumX and candidateY is less than maximumY
4306
+ on error
4307
+ return false
4308
+ end try
4309
+ end titlePaneVisible
4310
+
4311
+ on titleCandidateName(candidate)
4312
+ set candidateName to ""
4313
+ try
4314
+ set candidateName to name of candidate as text
4315
+ end try
4316
+ if candidateName is "missing value" then set candidateName to ""
4317
+ if candidateName is "" then
4318
+ try
4319
+ set candidateName to value of candidate as text
4320
+ end try
4321
+ end if
4322
+ if candidateName is "missing value" then set candidateName to ""
4323
+ return candidateName
4324
+ end titleCandidateName
4325
+
4326
+ on collectTitleMatches(nodes, depth, queryText, identityQuery, seenIdentities, mainOrigin, mainSize)
4327
+ if depth > 12 then return ""
4328
+ set output to ""
4329
+ repeat with candidateIndex from 1 to count of nodes
4330
+ try
4331
+ set candidate to contents of item candidateIndex of nodes
4332
+ if my titlePaneVisible(candidate, mainOrigin, mainSize) then
4333
+ set candidateName to my titleCandidateName(candidate)
4334
+ set candidateIdentity to ""
4335
+ try
4336
+ set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
4337
+ end try
4338
+ set matches to false
4339
+ if candidateName is not "" and candidateIdentity is not "" then
4340
+ if identityQuery then
4341
+ set matches to candidateIdentity is queryText
4342
+ else
4343
+ set matches to candidateName contains queryText
4344
+ end if
4345
+ end if
4346
+ if matches and seenIdentities does not contain candidateIdentity then
4347
+ set end of seenIdentities to candidateIdentity
4348
+ set output to output & candidateName & (ASCII character 31) & candidateIdentity & (ASCII character 30)
4349
+ end if
4350
+ set output to output & my collectTitleMatches(UI elements of candidate, depth + 1, queryText, identityQuery, seenIdentities, mainOrigin, mainSize)
4351
+ end if
4352
+ on error
4353
+ -- Ignore inaccessible descendants and continue the bounded scan.
4354
+ end try
4355
+ end repeat
4356
+ return output
4357
+ end collectTitleMatches
4358
+ end using terms from
4359
+ tell application "System Events"
4360
+ tell process "Final Cut Pro"
4361
+ ${requireFrontmostAppleScript()}
4362
+ set mainWindow to window "Final Cut Pro"
4363
+ set mainOrigin to position of mainWindow
4364
+ set mainSize to size of mainWindow
4365
+ click at {(item 1 of mainOrigin) + 104, (item 2 of mainOrigin) + 53}
4366
+ delay 0.3
4367
+ set titleSearchField to missing value
4368
+ repeat with candidate in entire contents of front window
4369
+ try
4370
+ set candidateRole to role of candidate as text
4371
+ set candidateDescription to description of candidate as text
4372
+ if (candidateRole is "AXTextField" or candidateRole is "AXSearchField") and (candidateDescription contains "search" or candidateDescription contains "Search") then
4373
+ set titleSearchField to candidate
4374
+ exit repeat
4375
+ end if
4376
+ end try
4377
+ end repeat
4378
+ if titleSearchField is not missing value then
4379
+ set value of titleSearchField to ${appleScriptString(searchQuery)}
4380
+ try
4381
+ set value of attribute "AXFocused" of titleSearchField to true
4382
+ end try
4383
+ else if ${searchQuery === "" ? "false" : "true"} then
4384
+ click at {(item 1 of mainOrigin) + 280, (item 2 of mainOrigin) + 83}
4385
+ keystroke "a" using {command down}
4386
+ key code 51
4387
+ keystroke ${appleScriptString(searchQuery)}
4388
+ end if
4389
+ delay 0.6
4390
+ set seenIdentities to {}
4391
+ return my collectTitleMatches(UI elements of mainWindow, 0, ${appleScriptString(identityQuery ? query : searchQuery)}, ${identityQuery ? "true" : "false"}, seenIdentities, mainOrigin, mainSize)
4392
+ end tell
4393
+ end tell`;
4394
+ }
4395
+ function titleBrowserPreflightScript() {
4396
+ return `
4397
+ on titleBrowserPreflightResult(processFrontmost, browserWindowAvailable)
4398
+ return processFrontmost & (ASCII character 31) & browserWindowAvailable
4399
+ end titleBrowserPreflightResult
4400
+
4401
+ tell application "System Events"
4402
+ tell process "Final Cut Pro"
4403
+ set processFrontmost to frontmost as text
4404
+ set browserWindowAvailable to false
4405
+ try
4406
+ set browserWindow to window "Final Cut Pro"
4407
+ set browserWindowAvailable to true
4408
+ end try
4409
+ return my titleBrowserPreflightResult(processFrontmost, browserWindowAvailable)
4410
+ end tell
4411
+ end tell`;
4412
+ }
4413
+ function titleAssetSelectionScript(assetName, assetIdentity) {
3506
4414
  return `
3507
4415
  tell application "System Events"
3508
4416
  tell process "Final Cut Pro"
3509
4417
  ${requireFrontmostAppleScript()}
3510
4418
  set mainWindow to window "Final Cut Pro"
3511
4419
  set mainOrigin to position of mainWindow
4420
+ set targetIdentity to ${appleScriptString(assetIdentity ?? "")}
3512
4421
  -- Final Cut 10.7 exposes the Titles tab as a custom Browser control. Its
3513
4422
  -- Control-Command-1 shortcut is not stable across releases (on some
3514
4423
  -- builds it opens Export), so use the bounded window-relative fallback.
@@ -3557,14 +4466,14 @@ tell application "System Events"
3557
4466
  set candidateIdentity to ""
3558
4467
  try
3559
4468
  set candidateSourceIdentity to value of attribute "AXIdentifier" of candidate as text
3560
- if candidateSourceIdentity is not "" then set candidateIdentity to "source:" & candidateSourceIdentity
4469
+ if candidateSourceIdentity is not "" then set candidateIdentity to candidateSourceIdentity
3561
4470
  end try
3562
4471
  if candidateIdentity is "" then
3563
4472
  set candidateIdentity to (candidateRole as text) & "|" & (candidateName as text) & "|" & ((position of candidate) as text) & "|" & ((size of candidate) as text)
3564
4473
  end if
3565
- if (candidateName is ${appleScriptString(assetName)} or candidateName contains ${appleScriptString(assetName)}) and seenTitleIdentities does not contain candidateIdentity then
4474
+ if ((targetIdentity is not "" and candidateIdentity is targetIdentity) or (targetIdentity is "" and (candidateName is ${appleScriptString(assetName)} or candidateName contains ${appleScriptString(assetName)}))) and seenTitleIdentities does not contain candidateIdentity then
3566
4475
  set end of seenTitleIdentities to candidateIdentity
3567
- if candidateName is ${appleScriptString(assetName)} then
4476
+ if targetIdentity is not "" or candidateName is ${appleScriptString(assetName)} then
3568
4477
  set exactMatchCount to exactMatchCount + 1
3569
4478
  set exactTitleItem to candidate
3570
4479
  else
@@ -3606,6 +4515,115 @@ tell application "System Events"
3606
4515
  end tell
3607
4516
  end tell`;
3608
4517
  }
4518
+ function markRangeEndAndConnectPictureInPictureScript() {
4519
+ return `
4520
+ tell application "System Events"
4521
+ tell process "Final Cut Pro"
4522
+ ${requireFrontmostAppleScript()}
4523
+ keystroke "o"
4524
+ delay 0.2
4525
+ -- Q connects the selected Browser video to the selected primary clip.
4526
+ keystroke "q"
4527
+ delay 0.5
4528
+ end tell
4529
+ end tell`;
4530
+ }
4531
+ function pictureInPictureTransformScript(preview) {
4532
+ const optionalFields = [
4533
+ preview.crop ? `
4534
+ set value of cropTopField to ${appleScriptString(String(preview.crop.top * 100))}
4535
+ set value of cropRightField to ${appleScriptString(String(preview.crop.right * 100))}
4536
+ set value of cropBottomField to ${appleScriptString(String(preview.crop.bottom * 100))}
4537
+ set value of cropLeftField to ${appleScriptString(String(preview.crop.left * 100))}` : "",
4538
+ preview.frame ? `
4539
+ set value of frameStyleField to ${appleScriptString(preview.frame.style)}
4540
+ set value of frameColorField to ${appleScriptString(preview.frame.color)}
4541
+ set value of frameWidthField to ${appleScriptString(String(preview.frame.width))}` : "",
4542
+ ].join("");
4543
+ const requiredFieldLookup = `
4544
+ set positionXField to my findInspectorField("Position X")
4545
+ set positionYField to my findInspectorField("Position Y")
4546
+ set scaleField to my findInspectorField("Scale")
4547
+ if positionXField is missing value or positionYField is missing value or scaleField is missing value then error "FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_TRANSFORM_UNAVAILABLE: Transform inspector fields were not visible"
4548
+ set value of positionXField to ${appleScriptString(String(preview.position.x))}
4549
+ set value of positionYField to ${appleScriptString(String(preview.position.y))}
4550
+ set value of scaleField to ${appleScriptString(String(preview.scale * 100))}`;
4551
+ const optionalLookup = `${preview.crop ? `
4552
+ set cropTopField to my findInspectorField("Crop Top")
4553
+ set cropRightField to my findInspectorField("Crop Right")
4554
+ set cropBottomField to my findInspectorField("Crop Bottom")
4555
+ set cropLeftField to my findInspectorField("Crop Left")
4556
+ if cropTopField is missing value or cropRightField is missing value or cropBottomField is missing value or cropLeftField is missing value then error "FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_CROP_UNAVAILABLE: Crop inspector fields were not visible"` : ""}${preview.frame ? `
4557
+ set frameStyleField to my findInspectorField("Frame Style")
4558
+ set frameColorField to my findInspectorField("Frame Color")
4559
+ set frameWidthField to my findInspectorField("Frame Width")
4560
+ if frameStyleField is missing value or frameColorField is missing value or frameWidthField is missing value then error "FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_FRAME_UNAVAILABLE: Frame inspector fields were not visible"` : ""}`;
4561
+ return `
4562
+ tell application "System Events"
4563
+ tell process "Final Cut Pro"
4564
+ ${requireFrontmostAppleScript()}
4565
+ set mainWindow to window "Final Cut Pro"
4566
+ set inspectorTab to missing value
4567
+ repeat with candidate in entire contents of mainWindow
4568
+ try
4569
+ set candidateDescription to description of candidate as text
4570
+ set candidateName to name of candidate as text
4571
+ if candidateDescription contains "Video Inspector" or candidateName is "Inspector" then
4572
+ set inspectorTab to candidate
4573
+ exit repeat
4574
+ end if
4575
+ end try
4576
+ end repeat
4577
+ if inspectorTab is missing value then error "FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_TRANSFORM_UNAVAILABLE: Video Inspector was not visible"
4578
+ try
4579
+ perform action "AXPress" of inspectorTab
4580
+ on error
4581
+ click inspectorTab
4582
+ end try
4583
+ delay 0.3
4584
+ ${requiredFieldLookup}
4585
+ ${optionalLookup}
4586
+ ${optionalFields}
4587
+ delay 0.2
4588
+ end tell
4589
+ end tell`;
4590
+ }
4591
+ function pictureInPictureInspectorReadbackScript() {
4592
+ return `
4593
+ on readInspectorField(fieldLabel, fallback)
4594
+ tell application "System Events"
4595
+ tell process "Final Cut Pro"
4596
+ repeat with candidate in text fields of front window
4597
+ try
4598
+ set candidateDescription to description of candidate as text
4599
+ set candidateName to name of candidate as text
4600
+ if candidateDescription contains fieldLabel or candidateName contains fieldLabel then return value of candidate as text
4601
+ end try
4602
+ end repeat
4603
+ end tell
4604
+ end tell
4605
+ return fallback
4606
+ end readInspectorField
4607
+
4608
+ -- FRAMEKIT_NATIVE_PIP_READBACK
4609
+ tell application "System Events"
4610
+ tell process "Final Cut Pro"
4611
+ ${requireFrontmostAppleScript()}
4612
+ set positionXText to my readInspectorField("Position X", "")
4613
+ set positionYText to my readInspectorField("Position Y", "")
4614
+ set scaleText to my readInspectorField("Scale", "")
4615
+ if positionXText is "" or positionYText is "" or scaleText is "" then error "FINAL_CUT_NATIVE_PICTURE_IN_PICTURE_READBACK_UNAVAILABLE: Transform inspector values were not visible"
4616
+ set frameStyleText to my readInspectorField("Frame Style", "")
4617
+ set frameColorText to my readInspectorField("Frame Color", "")
4618
+ set frameWidthText to my readInspectorField("Frame Width", "")
4619
+ set cropTopText to my readInspectorField("Crop Top", "")
4620
+ set cropRightText to my readInspectorField("Crop Right", "")
4621
+ set cropBottomText to my readInspectorField("Crop Bottom", "")
4622
+ set cropLeftText to my readInspectorField("Crop Left", "")
4623
+ return positionXText & (ASCII character 31) & positionYText & (ASCII character 31) & scaleText & (ASCII character 31) & frameStyleText & (ASCII character 31) & frameColorText & (ASCII character 31) & frameWidthText & (ASCII character 31) & cropTopText & (ASCII character 31) & cropRightText & (ASCII character 31) & cropBottomText & (ASCII character 31) & cropLeftText
4624
+ end tell
4625
+ end tell`;
4626
+ }
3609
4627
  function titleTextEditScript(text) {
3610
4628
  return `
3611
4629
  tell application "System Events"
@@ -3785,7 +4803,7 @@ function parseOccurrences(output, mediaHandle) {
3785
4803
  .filter(Boolean)
3786
4804
  .map((record, index) => {
3787
4805
  const fields = record.split(String.fromCharCode(31));
3788
- const [name = "", role = "", sourceIdentity = "", timelineOffsetOrDuration = "", legacyTimelineOffset, nativeDuration] = fields;
4806
+ const [name = "", role = "", sourceIdentity = "", timelineOffsetOrDuration = "", legacyTimelineOffset, nativeDuration, identity] = fields;
3789
4807
  const nativeRange = nativeDuration !== undefined;
3790
4808
  const legacyRecord = legacyTimelineOffset !== undefined && !nativeRange;
3791
4809
  const identityOrStart = sourceIdentity;
@@ -3795,6 +4813,7 @@ function parseOccurrences(output, mediaHandle) {
3795
4813
  handle: opaqueHandle("occurrence"),
3796
4814
  mediaHandle,
3797
4815
  name,
4816
+ ...(identity ? { identity } : {}),
3798
4817
  ...(role ? { role } : {}),
3799
4818
  ...(sourceIdentity && !legacyRange ? { sourceIdentity } : {}),
3800
4819
  ...(nativeRange ? { start: legacyTimelineOffset, duration: nativeDuration } : {}),