@morshoto/framekit 0.1.0 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +42 -17
  2. package/dist-package/adapters/final-cut/typescript/src/analyzers.js +57 -0
  3. package/dist-package/adapters/final-cut/typescript/src/connection.js +5 -1
  4. package/dist-package/adapters/final-cut/typescript/src/export.js +231 -8
  5. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +55 -5
  6. package/dist-package/adapters/final-cut/typescript/src/live.js +2 -2
  7. package/dist-package/adapters/final-cut/typescript/src/native.js +1000 -100
  8. package/dist-package/adapters/final-cut/typescript/src/publisher.js +40 -5
  9. package/dist-package/adapters/final-cut/typescript/src/session.js +21 -5
  10. package/dist-package/apps/mcp-server/src/main.js +9 -1
  11. package/dist-package/apps/mcp-server/src/routing.js +172 -0
  12. package/dist-package/apps/mcp-server/src/server.js +780 -33
  13. package/dist-package/packages/runtime/src/application/duration-policy-service.js +6 -0
  14. package/dist-package/packages/runtime/src/application/media-analysis-service.js +370 -0
  15. package/dist-package/packages/runtime/src/application/project-service.js +127 -0
  16. package/dist-package/packages/runtime/src/application/runtime-options.js +1 -0
  17. package/dist-package/packages/runtime/src/application/transaction-store.js +12 -0
  18. package/dist-package/packages/runtime/src/audio/dialogue-normalization.js +64 -0
  19. package/dist-package/packages/runtime/src/audio/noise-reduction.js +46 -0
  20. package/dist-package/packages/runtime/src/capabilities.js +112 -1
  21. package/dist-package/packages/runtime/src/color-correction.js +48 -0
  22. package/dist-package/packages/runtime/src/context/context-engine.js +11 -6
  23. package/dist-package/packages/runtime/src/context/context-service.js +30 -0
  24. package/dist-package/packages/runtime/src/context/revision.js +3 -0
  25. package/dist-package/packages/runtime/src/domain/capabilities.js +1 -0
  26. package/dist-package/packages/runtime/src/domain/context.js +1 -0
  27. package/dist-package/packages/runtime/src/domain/diff.js +1 -0
  28. package/dist-package/packages/runtime/src/domain/duration.js +1 -0
  29. package/dist-package/packages/runtime/src/domain/editing.js +1 -0
  30. package/dist-package/packages/runtime/src/domain/index.js +12 -0
  31. package/dist-package/packages/runtime/src/domain/media.js +7 -0
  32. package/dist-package/packages/runtime/src/domain/ports.js +1 -0
  33. package/dist-package/packages/runtime/src/domain/primitives.js +1 -0
  34. package/dist-package/packages/runtime/src/domain/project.js +1 -0
  35. package/dist-package/packages/runtime/src/domain/rough-cut.js +69 -0
  36. package/dist-package/packages/runtime/src/domain/skills.js +33 -0
  37. package/dist-package/packages/runtime/src/domain/types.js +5 -1
  38. package/dist-package/packages/runtime/src/domain/verification.js +1 -0
  39. package/dist-package/packages/runtime/src/editing/dialogue-normalization-service.js +141 -0
  40. package/dist-package/packages/runtime/src/editing/duration-policy.js +187 -0
  41. package/dist-package/packages/runtime/src/editing/edit-service.js +413 -0
  42. package/dist-package/packages/runtime/src/editing/filler-removal-service.js +337 -0
  43. package/dist-package/packages/runtime/src/editing/music-service.js +85 -0
  44. package/dist-package/packages/runtime/src/index.js +12 -3
  45. package/dist-package/packages/runtime/src/planning/rough-cut.js +65 -0
  46. package/dist-package/packages/runtime/src/runtime.js +130 -825
  47. package/dist-package/packages/runtime/src/skills/builtin.js +339 -0
  48. package/dist-package/packages/runtime/src/skills/index.js +3 -0
  49. package/dist-package/packages/runtime/src/skills/registry.js +74 -0
  50. package/dist-package/packages/runtime/src/skills/requirements.js +170 -0
  51. package/dist-package/packages/runtime/src/skills/runtime.js +239 -0
  52. package/dist-package/packages/runtime/src/speech/filler-detector.js +132 -0
  53. package/dist-package/packages/runtime/src/speech/safe-cut-resolver.js +314 -0
  54. package/dist-package/packages/runtime/src/timeline/rational-time.js +58 -0
  55. package/dist-package/packages/runtime/src/verification/verification.js +712 -1
  56. package/dist-package/packages/testkit/src/fixture-analyzers.js +27 -0
  57. package/dist-package/packages/testkit/src/in-memory-editor.js +286 -3
  58. package/dist-package/packages/testkit/src/index.js +1 -0
  59. package/dist-package/packages/testkit/src/skill-fixtures.js +64 -0
  60. package/package.json +15 -7
  61. /package/dist-package/packages/runtime/src/{diff/diff.js → timeline/snapshot-diff.js} +0 -0
  62. /package/dist-package/packages/runtime/src/{snapshot-digest.js → timeline/snapshot-digest.js} +0 -0
@@ -40,6 +40,7 @@ export class FinalCutNativeAutomationAdapter {
40
40
  rangePreviews = new Map();
41
41
  mediaInsertionPreviews = new Map();
42
42
  titlePreviews = new Map();
43
+ transitionPreviews = new Map();
43
44
  constructor(options = {}) {
44
45
  this.enabled = options.enabled ?? process.env.FRAMEKIT_FINAL_CUT_NATIVE_WRITES === "1";
45
46
  this.executor = options.executor ?? runAppleScript;
@@ -70,6 +71,8 @@ export class FinalCutNativeAutomationAdapter {
70
71
  mediaAppend: this.enabled,
71
72
  mediaInsert: this.enabled,
72
73
  titlePlacement: this.enabled,
74
+ transitionDiscovery: this.enabled,
75
+ transitionPlacement: this.enabled,
73
76
  timelineFocus: this.enabled,
74
77
  requiresAccessibility: true,
75
78
  requiresFinalCutFrontmost: true,
@@ -463,23 +466,41 @@ export class FinalCutNativeAutomationAdapter {
463
466
  if (!context.frontmost)
464
467
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
465
468
  try {
466
- const occurrences = parseOccurrences(await this.executor(locateOccurrenceScript(match, scanAll)), mediaHandle);
469
+ const liveBefore = this.liveState ? await this.liveState().catch(() => undefined) : undefined;
470
+ let occurrenceOutput = "";
471
+ for (let attempt = 0; attempt < 2; attempt += 1) {
472
+ try {
473
+ occurrenceOutput = await this.executor(locateOccurrenceScript(match, scanAll));
474
+ break;
475
+ }
476
+ catch (error) {
477
+ if (attempt > 0)
478
+ throw error;
479
+ await this.sleep(300);
480
+ }
481
+ }
482
+ const occurrences = parseOccurrences(occurrenceOutput, mediaHandle);
483
+ normalizeOccurrenceTimes(occurrences, liveBefore?.sequence);
467
484
  if (occurrences.length === 1 && this.canDriveNativeMouse) {
468
485
  const timelineOffset = occurrences[0]?.timelineOffset;
469
486
  if (timelineOffset === undefined) {
470
487
  throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_POSITION_UNAVAILABLE: unique timeline occurrence has no selectable position");
471
488
  }
472
489
  await selectTimelineOccurrence(this.executor, timelineOffset);
490
+ await this.ensureOccurrenceRange(occurrences[0]);
473
491
  }
474
- const live = this.liveState ? await this.liveState().catch(() => undefined) : undefined;
492
+ const live = this.liveState ? await this.liveState().catch(() => undefined) : liveBefore;
475
493
  for (const occurrence of occurrences) {
476
494
  occurrence.sequence = live?.sequence?.name;
477
495
  occurrence.sequenceId = live?.sequence?.id;
478
496
  occurrence.revision = live?.revision.id;
479
497
  occurrence.uiContext = context.frontWindow;
480
498
  }
481
- this.occurrenceHandles.clear();
482
- this.ambiguousMediaHandles.clear();
499
+ for (const [handle, occurrence] of this.occurrenceHandles) {
500
+ if (occurrence.mediaHandle === mediaHandle)
501
+ this.occurrenceHandles.delete(handle);
502
+ }
503
+ this.ambiguousMediaHandles.delete(mediaHandle);
483
504
  for (const occurrence of occurrences)
484
505
  this.occurrenceHandles.set(occurrence.handle, occurrence);
485
506
  if (occurrences.length !== 1)
@@ -562,12 +583,13 @@ export class FinalCutNativeAutomationAdapter {
562
583
  const after = await this.requireTimelineContext();
563
584
  if (!after.frontmost)
564
585
  throw new Error("FINAL_CUT_NATIVE_VERIFICATION_FAILED: Final Cut changed focus during Blade");
586
+ const afterLive = await this.readLiveState();
565
587
  const resultingSegments = parseOccurrences(await this.executor(locateOccurrenceScript({ handle: preview.occurrence.mediaHandle, name: preview.occurrence.name }, true)), preview.occurrence.mediaHandle);
588
+ normalizeOccurrenceTimes(resultingSegments, afterLive?.sequence);
566
589
  if (resultingSegments.length < 2) {
567
590
  throw new Error("FINAL_CUT_NATIVE_VERIFICATION_FAILED: Final Cut did not expose two resulting timeline segments after Blade");
568
591
  }
569
592
  const operationId = opaqueHandle("native-blade");
570
- const afterLive = await this.readLiveState();
571
593
  this.rememberOperation(operationId, { kind: "blade", before, after, beforeLive: undefined, afterLive, undoCommand: after.undoCommand });
572
594
  return {
573
595
  operationId,
@@ -632,6 +654,190 @@ export class FinalCutNativeAutomationAdapter {
632
654
  async executeTitleAdd(previewToken) {
633
655
  return this.withNativeUi(() => this.executeTitleAddNative(previewToken));
634
656
  }
657
+ async searchTransitions(query) {
658
+ return this.withNativeUi(() => this.searchTransitionsNative(query));
659
+ }
660
+ async previewTransitionAdd(request) {
661
+ return this.withNativeUi(() => this.previewTransitionAddNative(request));
662
+ }
663
+ async executeTransitionAdd(previewToken) {
664
+ return this.withNativeUi(() => this.executeTransitionAddNative(previewToken));
665
+ }
666
+ async searchTransitionsNative(query) {
667
+ this.assertEnabled();
668
+ if (!query.trim())
669
+ throw new Error("INVALID_OPERATION: transition search query cannot be empty");
670
+ const context = await this.requireTimelineContext();
671
+ if (!context.frontmost)
672
+ throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut must be frontmost for transition discovery");
673
+ try {
674
+ const identity = transitionIdentityFromId(query);
675
+ let lastError;
676
+ for (let attempt = 0; attempt < 2; attempt += 1) {
677
+ try {
678
+ return parseTransitionMatches(await this.executeNativeScript(transitionSearchScript(identity ?? query, identity !== undefined)));
679
+ }
680
+ catch (error) {
681
+ lastError = error;
682
+ if (attempt === 0)
683
+ await this.sleep(250);
684
+ }
685
+ }
686
+ throw lastError;
687
+ }
688
+ catch (error) {
689
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
690
+ }
691
+ }
692
+ async previewTransitionAddNative(request) {
693
+ this.assertEnabled();
694
+ assertNativeTransitionAsset(request.asset);
695
+ const beforeOccurrence = this.occurrenceHandles.get(request.beforeOccurrenceHandle);
696
+ if (!beforeOccurrence)
697
+ throw new Error(`FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: unknown before occurrence ${request.beforeOccurrenceHandle}`);
698
+ const afterOccurrence = this.occurrenceHandles.get(request.afterOccurrenceHandle);
699
+ if (!afterOccurrence)
700
+ throw new Error(`FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: unknown after occurrence ${request.afterOccurrenceHandle}`);
701
+ await this.ensureOccurrenceRange(beforeOccurrence);
702
+ await this.ensureOccurrenceRange(afterOccurrence);
703
+ const context = await this.requireTimelineContext();
704
+ if (!context.frontmost)
705
+ throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
706
+ const live = await this.requireLiveState();
707
+ const editPoint = validateTransitionEditPoint(beforeOccurrence, afterOccurrence, request.duration, live);
708
+ const expiresAt = this.now() + 30_000;
709
+ const previewToken = opaqueHandle("transition-preview");
710
+ this.transitionPreviews.set(previewToken, {
711
+ asset: structuredClone(request.asset),
712
+ beforeOccurrence: structuredClone(beforeOccurrence),
713
+ afterOccurrence: structuredClone(afterOccurrence),
714
+ editPoint,
715
+ duration: structuredClone(request.duration),
716
+ sequenceId: live.sequence?.id,
717
+ revision: live.revision.id,
718
+ expiresAt,
719
+ });
720
+ return {
721
+ previewToken,
722
+ asset: structuredClone(request.asset),
723
+ beforeOccurrence: structuredClone(beforeOccurrence),
724
+ afterOccurrence: structuredClone(afterOccurrence),
725
+ editPoint,
726
+ duration: structuredClone(request.duration),
727
+ ...(live.sequence?.id ? { sequenceId: live.sequence.id } : {}),
728
+ revision: live.revision.id,
729
+ command: "Add native transition",
730
+ expiresAt: new Date(expiresAt).toISOString(),
731
+ };
732
+ }
733
+ async executeTransitionAddNative(previewToken) {
734
+ this.assertEnabled();
735
+ const preview = this.transitionPreviews.get(previewToken);
736
+ if (!preview)
737
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: unknown native transition preview");
738
+ this.transitionPreviews.delete(previewToken);
739
+ if (this.now() > preview.expiresAt)
740
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: native transition preview has expired");
741
+ const before = await this.requireTimelineContext();
742
+ const beforeLive = await this.requireLiveState();
743
+ validateTransitionPreviewBinding(preview, beforeLive);
744
+ const frameDuration = beforeLive.sequence?.frameDuration;
745
+ if (!frameDuration) {
746
+ throw new Error("FINAL_CUT_NATIVE_TRANSITION_DURATION_UNAVAILABLE: Final Cut sequence frame duration is unavailable");
747
+ }
748
+ if (!before.frontmost)
749
+ throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
750
+ let observedDuration;
751
+ const validatePreparationRetry = async (recovered) => {
752
+ if (!recovered.frontmost || !recovered.timelineWindowAvailable) {
753
+ throw new Error("FINAL_CUT_NATIVE_RETRY_TARGET_CHANGED: Final Cut timeline became unavailable during transition placement");
754
+ }
755
+ const recoveredLive = await this.requireLiveState();
756
+ if (preview.sequenceId && recoveredLive.sequence?.id !== preview.sequenceId) {
757
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: active sequence changed");
758
+ }
759
+ };
760
+ try {
761
+ await this.executeNativeCommand(transitionAssetSelectionScript(preview.asset.name, preview.asset.identity), validatePreparationRetry);
762
+ await this.executeNativeCommand(selectTransitionEditPointScript(this.toTimecode(preview.editPoint, beforeLive)), validatePreparationRetry);
763
+ await this.waitForPlayhead(preview.editPoint, beforeLive.sequence?.id);
764
+ // Command-T may mutate before duration editing fails. Never retry this
765
+ // script: the outer recovery path observes and rolls back that mutation.
766
+ observedDuration = parseObservedTransitionDuration(await this.executor(applyTransitionScript(preview.duration, frameDuration)), frameDuration);
767
+ if (compareRational(observedDuration, preview.duration) !== 0) {
768
+ throw new Error(`FINAL_CUT_NATIVE_TRANSITION_DURATION_UNAVAILABLE: Final Cut read back ${observedDuration.value}/${observedDuration.timescale}, expected ${preview.duration.value}/${preview.duration.timescale}`);
769
+ }
770
+ }
771
+ catch (error) {
772
+ const observedContext = await this.inspectRawNative();
773
+ const observedLive = await this.readLiveState();
774
+ if (observedLive && observedLive.revision.id !== beforeLive.revision.id && observedContext.undoCommand) {
775
+ const failedOperationId = opaqueHandle("native-transition");
776
+ this.rememberOperation(failedOperationId, {
777
+ kind: "transition-placement",
778
+ before,
779
+ after: observedContext,
780
+ beforeLive,
781
+ afterLive: observedLive,
782
+ undoCommand: observedContext.undoCommand,
783
+ });
784
+ try {
785
+ await this.undo(failedOperationId);
786
+ }
787
+ catch (rollbackError) {
788
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}; operationId=${failedOperationId}; native rollback failed: ${String(rollbackError)}`);
789
+ }
790
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}; transition placement was rolled back`);
791
+ }
792
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
793
+ }
794
+ const after = await this.requireTimelineContext();
795
+ const afterLive = await this.waitForRevision(beforeLive.revision.id);
796
+ if (!observedDuration) {
797
+ throw new Error("FINAL_CUT_NATIVE_TRANSITION_DURATION_UNAVAILABLE: Final Cut did not expose the applied transition duration");
798
+ }
799
+ const verification = verifyNativeTransition(preview, after, beforeLive, afterLive, observedDuration);
800
+ const operationId = opaqueHandle("native-transition");
801
+ const operation = {
802
+ kind: "transition-placement",
803
+ before,
804
+ after,
805
+ beforeLive,
806
+ afterLive,
807
+ undoCommand: after.undoCommand,
808
+ };
809
+ if (!verification.verified) {
810
+ if (afterLive.revision.id !== beforeLive.revision.id && after.undoAvailable && after.undoCommand) {
811
+ this.rememberOperation(operationId, operation);
812
+ try {
813
+ await this.undo(operationId);
814
+ }
815
+ catch (rollbackError) {
816
+ throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}; operationId=${operationId}; native rollback failed: ${String(rollbackError)}`);
817
+ }
818
+ throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}; transition placement was rolled back`);
819
+ }
820
+ throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}`);
821
+ }
822
+ this.rememberOperation(operationId, operation);
823
+ return {
824
+ operationId,
825
+ previewToken,
826
+ asset: structuredClone(preview.asset),
827
+ beforeOccurrence: structuredClone(preview.beforeOccurrence),
828
+ afterOccurrence: structuredClone(preview.afterOccurrence),
829
+ editPoint: structuredClone(preview.editPoint),
830
+ duration: structuredClone(preview.duration),
831
+ observedDuration: structuredClone(observedDuration),
832
+ before,
833
+ after,
834
+ beforeRevision: beforeLive.revision,
835
+ afterRevision: afterLive.revision,
836
+ verification,
837
+ undoAvailable: after.undoAvailable,
838
+ ...(after.undoCommand ? { undoCommand: after.undoCommand } : {}),
839
+ };
840
+ }
635
841
  async previewTitleAddNative(request) {
636
842
  this.assertEnabled();
637
843
  assertNativeTitleAsset(request.asset);
@@ -1273,6 +1479,68 @@ export class FinalCutNativeAutomationAdapter {
1273
1479
  }
1274
1480
  }
1275
1481
  }
1482
+ async ensureOccurrenceRange(occurrence) {
1483
+ if (occurrence.start && occurrence.duration)
1484
+ return;
1485
+ if (occurrence.timelineOffset === undefined) {
1486
+ throw new Error("FINAL_CUT_NATIVE_EDIT_POINT_POSITION_UNAVAILABLE: occurrence has no selectable timeline position");
1487
+ }
1488
+ const originalLive = await this.requireLiveState();
1489
+ if (!originalLive.playheadTime) {
1490
+ throw new Error("FINAL_CUT_NATIVE_PLAYHEAD_UNAVAILABLE: exact occurrence range discovery requires a live playhead");
1491
+ }
1492
+ let startLive;
1493
+ let endLive;
1494
+ try {
1495
+ await this.executor(occurrenceRangeEndpointScript(occurrence.timelineOffset, "start"));
1496
+ startLive = await this.waitForLivePlayheadChangeOrCurrent(originalLive, "start");
1497
+ await this.executor(occurrenceRangeEndpointScript(occurrence.timelineOffset, "end"));
1498
+ endLive = await this.waitForLivePlayheadChangeOrCurrent(startLive, "end");
1499
+ }
1500
+ finally {
1501
+ try {
1502
+ await this.executor(setPlayheadScript(this.toTimecode(originalLive.playheadTime, originalLive)));
1503
+ await this.waitForPlayhead(originalLive.playheadTime, originalLive.sequence?.id);
1504
+ }
1505
+ catch {
1506
+ // Preserve the original discovery error; the next native operation will
1507
+ // fail closed if Final Cut did not return to the original playhead.
1508
+ }
1509
+ }
1510
+ const start = startLive?.playheadTime;
1511
+ const end = endLive?.playheadTime;
1512
+ if (!start || !end || compareRational(end, start) <= 0) {
1513
+ throw new Error("FINAL_CUT_NATIVE_EDIT_POINT_POSITION_UNAVAILABLE: Final Cut did not expose positive clip-range endpoints");
1514
+ }
1515
+ const duration = subtractRational(end, start);
1516
+ if (originalLive.sequence?.frameDuration && !isFrameAligned(duration, zeroRational(), originalLive.sequence.frameDuration)) {
1517
+ throw new Error("FINAL_CUT_NATIVE_EDIT_POINT_POSITION_UNAVAILABLE: Final Cut returned a non-frame-aligned clip range");
1518
+ }
1519
+ occurrence.start = rationalText(start);
1520
+ occurrence.duration = rationalText(duration);
1521
+ }
1522
+ async waitForLivePlayheadChangeOrCurrent(previous, endpoint) {
1523
+ const deadline = this.now() + 5_000;
1524
+ let latest = await this.requireLiveState();
1525
+ let stableStartPlayhead;
1526
+ while (this.now() < deadline) {
1527
+ if (latest.playheadTime) {
1528
+ const changed = !previous.playheadTime || compareRational(latest.playheadTime, previous.playheadTime) !== 0;
1529
+ if (endpoint === "end" && changed)
1530
+ return latest;
1531
+ if (endpoint === "start") {
1532
+ if (changed)
1533
+ return latest;
1534
+ if (stableStartPlayhead && compareRational(stableStartPlayhead, latest.playheadTime) === 0)
1535
+ return latest;
1536
+ stableStartPlayhead = latest.playheadTime;
1537
+ }
1538
+ }
1539
+ await this.sleep(100);
1540
+ latest = await this.requireLiveState();
1541
+ }
1542
+ throw new Error(`FINAL_CUT_NATIVE_EDIT_POINT_POSITION_UNAVAILABLE: Final Cut did not expose the ${endpoint} endpoint playhead`);
1543
+ }
1276
1544
  async requireTimelineTarget(operation) {
1277
1545
  const context = await this.requireTimelineContext();
1278
1546
  if (requiresClip(operation) && context.target.kind !== "selected-clip") {
@@ -1288,6 +1556,11 @@ export class FinalCutNativeAutomationAdapter {
1288
1556
  if (!context.available) {
1289
1557
  throw new Error(`${context.error?.code ?? "FINAL_CUT_NATIVE_UNAVAILABLE"}: ${context.error?.message ?? "native timeline context unavailable"}`);
1290
1558
  }
1559
+ if (context.target.kind === "playhead") {
1560
+ const detailed = await this.inspectRawNative();
1561
+ if (detailed.available && detailed.frontWindow && detailed.timelineWindowAvailable)
1562
+ return detailed;
1563
+ }
1291
1564
  return context;
1292
1565
  }
1293
1566
  async ensureTimelineReady() {
@@ -1423,6 +1696,149 @@ function verifyNativeTitle(preview, beforeLive, after, afterLive) {
1423
1696
  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
1697
  };
1425
1698
  }
1699
+ function assertNativeTransitionAsset(asset) {
1700
+ if (!asset.id.trim() || !asset.name.trim() || !asset.identity.trim()) {
1701
+ throw new Error("TRANSITION_ASSET_NOT_FOUND: native transition asset identity is incomplete");
1702
+ }
1703
+ if (asset.kind !== "transition") {
1704
+ throw new Error(`TRANSITION_ASSET_INCOMPATIBLE: ${asset.id} is not a Final Cut transition asset`);
1705
+ }
1706
+ }
1707
+ function validateTransitionEditPoint(before, after, duration, live) {
1708
+ if (before.timelineOffset === undefined || after.timelineOffset === undefined) {
1709
+ throw new Error("FINAL_CUT_NATIVE_EDIT_POINT_POSITION_UNAVAILABLE: adjacent occurrences do not have selectable timeline positions");
1710
+ }
1711
+ if (before.sequenceId && after.sequenceId && before.sequenceId !== after.sequenceId) {
1712
+ throw new Error("FINAL_CUT_NATIVE_EDIT_POINT_INVALID: adjacent occurrences belong to different sequences");
1713
+ }
1714
+ if (!before.start || !before.duration || !after.start || !after.duration) {
1715
+ throw new Error("FINAL_CUT_NATIVE_EDIT_POINT_POSITION_UNAVAILABLE: adjacent occurrences do not expose exact coordinates");
1716
+ }
1717
+ const beforeEnd = addRational(parseRationalString(before.start, "before occurrence start"), parseRationalString(before.duration, "before occurrence duration"));
1718
+ const afterStart = parseRationalString(after.start, "after occurrence start");
1719
+ if (compareRational(beforeEnd, afterStart) !== 0) {
1720
+ throw new Error("FINAL_CUT_NATIVE_EDIT_POINT_INVALID: occurrences are not adjacent on the same edit point");
1721
+ }
1722
+ const exactDuration = parseRationalInput(duration, "transition duration");
1723
+ if (compareRational(exactDuration, zeroRational()) <= 0
1724
+ || compareRational(exactDuration, parseRationalString(before.duration, "before occurrence duration")) > 0
1725
+ || compareRational(exactDuration, parseRationalString(after.duration, "after occurrence duration")) > 0) {
1726
+ throw new Error("INVALID_OPERATION: transition duration must be positive and fit both adjacent occurrences");
1727
+ }
1728
+ if (live.sequence?.frameDuration && !isFrameAligned(exactDuration, zeroRational(), live.sequence.frameDuration)) {
1729
+ throw new Error("INVALID_OPERATION: transition duration must align to the sequence frame duration");
1730
+ }
1731
+ return beforeEnd;
1732
+ }
1733
+ function validateTransitionPreviewBinding(preview, live) {
1734
+ if (preview.sequenceId && live.sequence?.id !== preview.sequenceId) {
1735
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: active sequence changed");
1736
+ }
1737
+ if (live.revision.id !== preview.revision) {
1738
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: playhead or timeline revision changed");
1739
+ }
1740
+ if (preview.beforeOccurrence.sequenceId && live.sequence?.id !== preview.beforeOccurrence.sequenceId) {
1741
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: before occurrence sequence changed");
1742
+ }
1743
+ if (preview.afterOccurrence.sequenceId && live.sequence?.id !== preview.afterOccurrence.sequenceId) {
1744
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: after occurrence sequence changed");
1745
+ }
1746
+ }
1747
+ function verifyNativeTransition(preview, after, beforeLive, afterLive, observedDuration) {
1748
+ if (!afterLive.revision.id || afterLive.revision.id === beforeLive.revision.id) {
1749
+ return { verified: false, detail: "Final Cut did not expose a new revision after native transition placement" };
1750
+ }
1751
+ if (after.target.kind !== "selected-clip") {
1752
+ return { verified: false, detail: "Final Cut did not expose the inserted transition as the selected timeline item" };
1753
+ }
1754
+ const observedName = after.target.name ?? "";
1755
+ if (after.target.role !== "transition" && !observedName.toLowerCase().includes(preview.asset.name.toLowerCase())) {
1756
+ return { verified: false, detail: `Final Cut selected ${observedName || "an unnamed item"}, not ${preview.asset.name}` };
1757
+ }
1758
+ if (!after.undoAvailable || !after.undoCommand) {
1759
+ return { verified: false, detail: "Final Cut did not expose an Undo command for the native transition placement" };
1760
+ }
1761
+ if (compareRational(observedDuration, preview.duration) !== 0) {
1762
+ return {
1763
+ verified: false,
1764
+ detail: `Final Cut read back ${observedDuration.value}/${observedDuration.timescale}, expected ${preview.duration.value}/${preview.duration.timescale}`,
1765
+ };
1766
+ }
1767
+ return {
1768
+ verified: true,
1769
+ 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
+ };
1771
+ }
1772
+ function parseTransitionMatches(output) {
1773
+ return output
1774
+ .split(String.fromCharCode(30))
1775
+ .map((record) => record.trim())
1776
+ .filter(Boolean)
1777
+ .map((record) => {
1778
+ const [name = "", identity = ""] = record.split(String.fromCharCode(31));
1779
+ if (!name || !identity) {
1780
+ throw new Error("FINAL_CUT_NATIVE_TRANSITION_ID_UNAVAILABLE: transition browser did not expose stable identities");
1781
+ }
1782
+ return {
1783
+ id: `final-cut:transition:${identity}`,
1784
+ kind: "transition",
1785
+ name,
1786
+ vendor: "Final Cut Pro",
1787
+ identity,
1788
+ };
1789
+ });
1790
+ }
1791
+ function transitionIdentityFromId(value) {
1792
+ const prefix = "final-cut:transition:";
1793
+ return value.startsWith(prefix) ? value.slice(prefix.length) : undefined;
1794
+ }
1795
+ function parseObservedTransitionDuration(output, frameDuration) {
1796
+ const marker = "FRAMEKIT_NATIVE_TRANSITION_DURATION=";
1797
+ const markerIndex = output.lastIndexOf(marker);
1798
+ if (markerIndex < 0) {
1799
+ throw new Error("FINAL_CUT_NATIVE_TRANSITION_DURATION_UNAVAILABLE: Final Cut did not return a readable transition duration");
1800
+ }
1801
+ const value = output.slice(markerIndex + marker.length).trim();
1802
+ try {
1803
+ return parseRationalString(value, "observed transition duration");
1804
+ }
1805
+ catch {
1806
+ const match = value.match(/^(\d+):(\d{2}):(\d{2}):(\d{2})$/);
1807
+ if (match && frameDuration) {
1808
+ const framesPerSecond = Math.max(1, Math.round(Number(frameDuration.timescale) / Number(frameDuration.value)));
1809
+ const totalFrames = (((BigInt(match[1]) * 60n + BigInt(match[2])) * 60n + BigInt(match[3])) * BigInt(framesPerSecond)) + BigInt(match[4]);
1810
+ return normalizeRational(totalFrames * BigInt(frameDuration.value), BigInt(frameDuration.timescale));
1811
+ }
1812
+ const frameCount = value.match(/^(\d+)$/);
1813
+ if (frameCount && frameDuration) {
1814
+ return normalizeRational(BigInt(frameCount[1]) * BigInt(frameDuration.value), BigInt(frameDuration.timescale));
1815
+ }
1816
+ throw new Error(`FINAL_CUT_NATIVE_TRANSITION_DURATION_UNAVAILABLE: Final Cut returned an unsupported transition duration ${value || "<empty>"}`);
1817
+ }
1818
+ }
1819
+ function transitionDurationInput(duration, frameDuration) {
1820
+ const durationNumerator = BigInt(duration.value) * BigInt(frameDuration.timescale);
1821
+ const durationDenominator = BigInt(duration.timescale) * BigInt(frameDuration.value);
1822
+ if (durationDenominator <= 0n || durationNumerator <= 0n || durationNumerator % durationDenominator !== 0n) {
1823
+ throw new Error("FINAL_CUT_NATIVE_TRANSITION_DURATION_UNAVAILABLE: transition duration is not representable as whole sequence frames");
1824
+ }
1825
+ return (durationNumerator / durationDenominator).toString();
1826
+ }
1827
+ function parseRationalString(value, label) {
1828
+ const match = value.match(/^(-?\d+)\/(\d+)$/);
1829
+ if (!match || match[2] === "0")
1830
+ throw new Error(`FINAL_CUT_NATIVE_PROTOCOL: ${label} is not a valid rational time`);
1831
+ return normalizeRational(BigInt(match[1]), BigInt(match[2]));
1832
+ }
1833
+ function parseRationalInput(value, label) {
1834
+ if (!/^-?\d+$/.test(value.value) || !/^\d+$/.test(value.timescale) || value.timescale === "0") {
1835
+ throw new Error(`INVALID_OPERATION: ${label} is not a valid rational time`);
1836
+ }
1837
+ return normalizeRational(BigInt(value.value), BigInt(value.timescale));
1838
+ }
1839
+ function rationalText(value) {
1840
+ return `${value.value}/${value.timescale}`;
1841
+ }
1426
1842
  async function runAppleScript(script, options = {}) {
1427
1843
  try {
1428
1844
  const result = await execFile("osascript", ["-e", script], { maxBuffer: 1_000_000, signal: options.signal });
@@ -1701,27 +2117,92 @@ end tell`;
1701
2117
  }
1702
2118
  function inspectScript() {
1703
2119
  return `
2120
+ using terms from application "System Events"
2121
+ on splitText(valueText, delimiter)
2122
+ set oldDelimiters to AppleScript's text item delimiters
2123
+ set AppleScript's text item delimiters to delimiter
2124
+ set parts to text items of valueText
2125
+ set AppleScript's text item delimiters to oldDelimiters
2126
+ return parts
2127
+ end splitText
2128
+
2129
+ on selectedTimelineItem(containerItem, depth, mainOrigin, mainSize)
2130
+ if depth > 12 then return ""
2131
+ set output to ""
2132
+ repeat with candidateRef in UI elements of containerItem
2133
+ try
2134
+ set candidate to contents of candidateRef
2135
+ set candidatePosition to position of candidate
2136
+ set candidateSize to size of candidate
2137
+ set candidateX to item 1 of candidatePosition
2138
+ set candidateY to item 2 of candidatePosition
2139
+ set candidateWidth to item 1 of candidateSize
2140
+ set candidateHeight to item 2 of candidateSize
2141
+ set timelineTop to (item 2 of mainOrigin) + ((item 2 of mainSize) * 0.62)
2142
+ set timelineLeft to (item 1 of mainOrigin) + ((item 1 of mainSize) * 0.20)
2143
+ set inTimelineRegion to (candidateX + candidateWidth) is greater than timelineLeft and (candidateY + candidateHeight) is greater than timelineTop
2144
+ if inTimelineRegion then
2145
+ set candidateSelected to false
2146
+ try
2147
+ set candidateSelected to (selected of candidate) is true
2148
+ end try
2149
+ if candidateSelected then
2150
+ set candidateRole to role of candidate as text
2151
+ set candidateName to ""
2152
+ try
2153
+ set candidateName to description of candidate as text
2154
+ end try
2155
+ if candidateName is "" then
2156
+ try
2157
+ set candidateName to value of candidate as text
2158
+ end try
2159
+ end if
2160
+ if candidateName is "missing value" then set candidateName to ""
2161
+ set candidateIdentity to ""
2162
+ try
2163
+ set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
2164
+ end try
2165
+ return candidateName & (ASCII character 31) & candidateRole & (ASCII character 31) & candidateIdentity
2166
+ end if
2167
+ set output to my selectedTimelineItem(candidate, depth + 1, mainOrigin, mainSize)
2168
+ if output is not "" then return output
2169
+ end if
2170
+ on error
2171
+ -- Ignore inaccessible descendants and continue the bounded scan.
2172
+ end try
2173
+ end repeat
2174
+ return ""
2175
+ end selectedTimelineItem
2176
+ end using terms from
2177
+
1704
2178
  tell application "System Events"
1705
2179
  tell process "Final Cut Pro"
1706
2180
  ${activateFinalCutWindowAppleScript()}
1707
2181
  set frontWindow to window "Final Cut Pro"
1708
2182
  set frontWindowName to name of frontWindow
2183
+ set mainOrigin to position of frontWindow
2184
+ set mainSize to size of frontWindow
1709
2185
  set selectedName to ""
1710
2186
  set selectedRole to ""
2187
+ set selectedIdentity to ""
1711
2188
  set selectedCount to 0
2189
+ set selectedRecord to ""
2190
+ set selectionLookupAvailable to false
2191
+ -- Final Cut exposes the Project Timeline as a stable bounded AX node.
2192
+ -- Start there instead of traversing Browser and Effects Library trees.
1712
2193
  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
2194
+ set timelineArea to UI element 1 of UI element 8 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of frontWindow
2195
+ set selectionLookupAvailable to true
2196
+ set selectedRecord to my selectedTimelineItem(timelineArea, 0, mainOrigin, mainSize)
1724
2197
  end try
2198
+ if selectedRecord is not "" then
2199
+ set selectedFields to my splitText(selectedRecord, ASCII character 31)
2200
+ set selectedName to item 1 of selectedFields
2201
+ set selectedRole to item 2 of selectedFields
2202
+ set selectedIdentity to item 3 of selectedFields
2203
+ set selectedCount to 1
2204
+ end if
2205
+ if not selectionLookupAvailable then set selectedCount to -1
1725
2206
  set undoEnabled to false
1726
2207
  set undoCommand to ""
1727
2208
  try
@@ -1742,13 +2223,6 @@ function inspectScript() {
1742
2223
  end try
1743
2224
  set inspectorName to ""
1744
2225
  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
2226
  set focusedName to ""
1753
2227
  set focusedRole to ""
1754
2228
  set focusedDescription to ""
@@ -1759,7 +2233,7 @@ function inspectScript() {
1759
2233
  set focusedDescription to description of focusedElement as text
1760
2234
  end try
1761
2235
  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
2236
+ 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) & "true" & (ASCII character 31) & "true" & (ASCII character 31) & "timeline" & (ASCII character 31) & "0" & (ASCII character 31) & "false" & (ASCII character 31) & "true" & (ASCII character 31) & frontWindowName & (ASCII character 31) & "false" & (ASCII character 31) & undoCommand & (ASCII character 31) & selectedIdentity
1763
2237
  end tell
1764
2238
  end tell`;
1765
2239
  }
@@ -1775,7 +2249,11 @@ function searchMediaScript(query) {
1775
2249
  set origin to position of mainWindow
1776
2250
  ${browserSearchFieldScript()}
1777
2251
  set searchQuery to ${appleScriptString(query)}
2252
+ -- Assigning AXValue alone updates the visible text without always
2253
+ -- dispatching Final Cut's Browser filter. Commit the value through the
2254
+ -- focused field so the result collection observes the requested query.
1778
2255
  set value of searchField to searchQuery
2256
+ key code 36
1779
2257
  delay 0.5
1780
2258
  set output to my collectBrowserMedia(browserRoot, 0, searchQuery, origin, false, {}, "root")
1781
2259
  return output
@@ -1799,7 +2277,7 @@ function selectedBrowserMediaScript() {
1799
2277
  set seenSourceIdentities to {}
1800
2278
  set browserRoot to mainWindow
1801
2279
  try
1802
- set browserSearchResult to my findBrowserSearchControl(mainWindow, 0)
2280
+ set browserSearchResult to my findBrowserSearchControl(mainWindow, 0, origin, size of mainWindow)
1803
2281
  if browserSearchResult is not missing value then set browserRoot to item 2 of browserSearchResult
1804
2282
  end try
1805
2283
  try
@@ -1847,20 +2325,32 @@ end tell`;
1847
2325
  function browserSearchFieldScript() {
1848
2326
  return `
1849
2327
  set origin to position of mainWindow
2328
+ set windowSize to size of mainWindow
1850
2329
  set searchFieldFound to false
1851
2330
  set searchField to missing value
1852
2331
  set searchButton to missing value
1853
2332
  set browserRoot to mainWindow
2333
+ -- The Transitions browser may already be open. Prefer the bounded
2334
+ -- Browser search control so its Effects Library field cannot capture a
2335
+ -- media query.
1854
2336
  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
2337
+ set searchField to UI element 4 of UI element 5 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
2338
+ set searchFieldFound to true
2339
+ on error
2340
+ set searchField to missing value
2341
+ end try
2342
+ try
2343
+ if not searchFieldFound then
2344
+ set focusedCandidate to value of attribute "AXFocusedUIElement"
2345
+ set focusedRole to role of focusedCandidate as text
2346
+ set focusedDescription to ""
2347
+ try
2348
+ set focusedDescription to description of focusedCandidate as text
2349
+ end try
2350
+ if (focusedRole is "AXSearchField" or (focusedRole is "AXTextField" and (focusedDescription contains "search" or focusedDescription contains "Search"))) and my browserSearchCandidateVisible(focusedCandidate, origin, windowSize) then
2351
+ set searchField to focusedCandidate
2352
+ set searchFieldFound to true
2353
+ end if
1864
2354
  end if
1865
2355
  end try
1866
2356
  if not searchFieldFound then
@@ -1889,7 +2379,7 @@ function browserSearchFieldScript() {
1889
2379
  if my revealBrowser(mainWindow, 0) then delay 0.5
1890
2380
  end try
1891
2381
  try
1892
- set searchControlResult to my findBrowserSearchControl(mainWindow, 0)
2382
+ set searchControlResult to my findBrowserSearchControl(mainWindow, 0, origin, windowSize)
1893
2383
  if searchControlResult is not missing value then
1894
2384
  set searchControl to item 1 of searchControlResult
1895
2385
  set browserRoot to item 2 of searchControlResult
@@ -1904,7 +2394,7 @@ function browserSearchFieldScript() {
1904
2394
  end try
1905
2395
  if not searchFieldFound then
1906
2396
  try
1907
- set searchControlResult to my findBrowserSearchControl(mainWindow, 0)
2397
+ set searchControlResult to my findBrowserSearchControl(mainWindow, 0, origin, windowSize)
1908
2398
  if searchControlResult is not missing value then
1909
2399
  set searchControl to item 1 of searchControlResult
1910
2400
  set browserRoot to item 2 of searchControlResult
@@ -1959,14 +2449,25 @@ function browserSearchFieldScript() {
1959
2449
  function browserSearchControlFinderScript() {
1960
2450
  return `
1961
2451
  using terms from application "System Events"
1962
- on findBrowserSearchControl(containerItem, depth)
2452
+ on browserSearchCandidateVisible(candidate, mainOrigin, mainSize)
2453
+ try
2454
+ set candidatePosition to position of candidate
2455
+ set candidateX to item 1 of candidatePosition
2456
+ set candidateY to item 2 of candidatePosition
2457
+ return candidateX is less than ((item 1 of mainOrigin) + ((item 1 of mainSize) * 0.60)) and candidateY is less than ((item 2 of mainOrigin) + ((item 2 of mainSize) * 0.60))
2458
+ on error
2459
+ return false
2460
+ end try
2461
+ end browserSearchCandidateVisible
2462
+
2463
+ on findBrowserSearchControl(containerItem, depth, mainOrigin, mainSize)
1963
2464
  if depth > 12 then return missing value
1964
2465
  set candidateItems to UI elements of containerItem
1965
2466
  repeat with candidateIndex in my orderedChildIndices(containerItem)
1966
2467
  try
1967
2468
  set candidate to item (contents of candidateIndex) of candidateItems
1968
2469
  set candidateRole to role of candidate as text
1969
- if candidateRole is "AXSearchField" then
2470
+ if candidateRole is "AXSearchField" and my browserSearchCandidateVisible(candidate, mainOrigin, mainSize) then
1970
2471
  return {candidate, containerItem}
1971
2472
  end if
1972
2473
  if candidateRole is "AXTextField" then
@@ -1978,19 +2479,19 @@ function browserSearchControlFinderScript() {
1978
2479
  try
1979
2480
  set candidateDescription to description of candidate as text
1980
2481
  end try
1981
- if candidateName contains "search" or candidateName contains "Search" or candidateDescription contains "search" or candidateDescription contains "Search" then
2482
+ if (candidateName contains "search" or candidateName contains "Search" or candidateDescription contains "search" or candidateDescription contains "Search") and my browserSearchCandidateVisible(candidate, mainOrigin, mainSize) then
1982
2483
  return {candidate, containerItem}
1983
2484
  end if
1984
2485
  end if
1985
2486
  if candidateRole is "AXButton" then
1986
2487
  set candidateDescription to description of candidate as text
1987
- if candidateDescription contains "search" or candidateDescription contains "Search" then
2488
+ if (candidateDescription contains "search" or candidateDescription contains "Search") and my browserSearchCandidateVisible(candidate, mainOrigin, mainSize) then
1988
2489
  return {candidate, containerItem}
1989
2490
  end if
1990
2491
  end if
1991
2492
  end try
1992
2493
  try
1993
- set nestedCandidate to my findBrowserSearchControl(candidate, depth + 1)
2494
+ set nestedCandidate to my findBrowserSearchControl(candidate, depth + 1, mainOrigin, mainSize)
1994
2495
  if nestedCandidate is not missing value then
1995
2496
  return nestedCandidate
1996
2497
  end if
@@ -2455,10 +2956,63 @@ function selectMediaScript(match) {
2455
2956
  end tell`;
2456
2957
  }
2457
2958
  function locateOccurrenceScript(match, scanAll) {
2458
- const timelineOffsets = scanAll
2459
- ? [40, 160, 224, 256, 400, 640, 880, 1120, 1360, 1500].join(", ")
2460
- : "800";
2461
2959
  return `
2960
+ using terms from application "System Events"
2961
+ on collectTimelineClipMatches(containerItem, depth, targetName, sourceIdentity, mainOrigin, mainSize)
2962
+ if depth > 12 then return ""
2963
+ set output to ""
2964
+ set candidateItems to UI elements of containerItem
2965
+ repeat with candidateRef in candidateItems
2966
+ try
2967
+ set candidate to contents of candidateRef
2968
+ set candidateRole to role of candidate as text
2969
+ set candidateDescription to ""
2970
+ try
2971
+ set candidateDescription to description of candidate as text
2972
+ end try
2973
+ if candidateRole is "AXLayoutItem" and candidateDescription contains ("Video-Clip:" & targetName) then
2974
+ set candidatePosition to position of candidate
2975
+ set candidateStart to ""
2976
+ set candidateDuration to ""
2977
+ try
2978
+ set candidateDuration to value of candidate as text
2979
+ end try
2980
+ repeat with childRef in UI elements of candidate
2981
+ try
2982
+ set child to contents of childRef
2983
+ set childRole to role of child as text
2984
+ set childDescription to description of child as text
2985
+ if childRole is "AXHandle" and childDescription is "Leading Edge" then set candidateStart to value of child as text
2986
+ end try
2987
+ end repeat
2988
+ if candidateStart is not "" and candidateDuration is not "" then
2989
+ 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)
2991
+ end if
2992
+ else
2993
+ set shouldDescend to false
2994
+ try
2995
+ set candidatePosition to position of candidate
2996
+ set candidateSize to size of candidate
2997
+ set candidateX to item 1 of candidatePosition
2998
+ set candidateY to item 2 of candidatePosition
2999
+ set candidateWidth to item 1 of candidateSize
3000
+ set candidateHeight to item 2 of candidateSize
3001
+ set timelineLeft to (item 1 of mainOrigin) + ((item 1 of mainSize) * 0.25)
3002
+ set timelineTop to (item 2 of mainOrigin) + ((item 2 of mainSize) * 0.55)
3003
+ set shouldDescend to (candidateX + candidateWidth) is greater than timelineLeft and (candidateY + candidateHeight) is greater than timelineTop
3004
+ end try
3005
+ if shouldDescend then set output to output & my collectTimelineClipMatches(candidate, depth + 1, targetName, sourceIdentity, mainOrigin, mainSize)
3006
+ end if
3007
+ on error
3008
+ -- Accessibility nodes can disappear while Final Cut redraws the
3009
+ -- timeline. Ignore that node and continue the bounded traversal.
3010
+ end try
3011
+ end repeat
3012
+ return output
3013
+ end collectTimelineClipMatches
3014
+ end using terms from
3015
+
2462
3016
  tell application "System Events"
2463
3017
  tell process "Final Cut Pro"
2464
3018
  ${requireFrontmostAppleScript()}
@@ -2466,56 +3020,27 @@ function locateOccurrenceScript(match, scanAll) {
2466
3020
  if sourceIdentity is "" then error "FINAL_CUT_NATIVE_MEDIA_ID_UNAVAILABLE: timeline lookup requires a shared source-media identifier"
2467
3021
  set mainWindow to window "Final Cut Pro"
2468
3022
  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
3023
+ set windowSize to size of mainWindow
3024
+ set targetName to ${appleScriptString(match.name)}
3025
+ -- Make every occurrence visible before scanning. This keeps discovery
3026
+ -- independent of the current timeline zoom/playhead viewport.
3027
+ try
3028
+ click menu bar item "View" of menu bar 1
3029
+ click menu item "Zoom to Fit" of menu 1 of menu bar item "View" of menu bar 1
3030
+ delay 0.5
3031
+ end try
3032
+ return my collectTimelineClipMatches(mainWindow, 0, targetName, sourceIdentity, origin, windowSize)
2508
3033
  end tell
2509
3034
  end tell`;
2510
3035
  }
2511
3036
  async function selectTimelineOccurrence(executor, timelineOffset) {
2512
3037
  const coordinates = (await executor(timelineSelectionCoordinatesScript())).split("|").map(Number);
2513
- const [originX, originY] = coordinates;
2514
- if (!Number.isFinite(originX) || !Number.isFinite(originY)) {
3038
+ const [originX, originY, windowWidth, windowHeight] = coordinates;
3039
+ if (!Number.isFinite(originX) || !Number.isFinite(originY) || !Number.isFinite(windowWidth) || !Number.isFinite(windowHeight)) {
2515
3040
  throw new Error("FINAL_CUT_NATIVE_AUTOMATION_FAILED: could not resolve Final Cut window coordinates");
2516
3041
  }
2517
3042
  const x = Math.round(originX + timelineOffset);
2518
- const y = Math.round(originY + 650);
3043
+ const y = Math.round(originY + (windowHeight * 0.77));
2519
3044
  try {
2520
3045
  await execFile("swift", ["-e", nativeMouseSelectionSource(x, y)]);
2521
3046
  }
@@ -2530,7 +3055,8 @@ tell application "System Events"
2530
3055
  ${requireFrontmostAppleScript()}
2531
3056
  set mainWindow to window "Final Cut Pro"
2532
3057
  set origin to position of mainWindow
2533
- return ((item 1 of origin) as text) & "|" & ((item 2 of origin) as text)
3058
+ set windowSize to size of mainWindow
3059
+ 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)
2534
3060
  end tell
2535
3061
  end tell`;
2536
3062
  }
@@ -2627,6 +3153,355 @@ tell application "System Events"
2627
3153
  end tell
2628
3154
  end tell`;
2629
3155
  }
3156
+ function transitionSearchScript(query, identityQuery = false) {
3157
+ const searchQuery = identityQuery ? "" : query;
3158
+ return `
3159
+ ${transitionBrowserTraversalScript()}
3160
+ tell application "System Events"
3161
+ tell process "Final Cut Pro"
3162
+ ${requireFrontmostAppleScript()}
3163
+ set mainWindow to first window whose name is "Final Cut Pro"
3164
+ ${transitionBrowserOpenScript()}
3165
+ ${transitionBrowserFocusScript()}
3166
+ set value of transitionSearchField to ${appleScriptString(searchQuery)}
3167
+ if ${searchQuery === "" ? "false" : "true"} then
3168
+ try
3169
+ if (value of transitionSearchField as text) is not ${appleScriptString(searchQuery)} then
3170
+ click at {(item 1 of mainOrigin) + ((item 1 of mainSize) * 0.72), (item 2 of mainOrigin) + ((item 2 of mainSize) * 0.96)}
3171
+ delay 0.15
3172
+ set transitionSearchField to value of attribute "AXFocusedUIElement"
3173
+ set value of transitionSearchField to ${appleScriptString(searchQuery)}
3174
+ end if
3175
+ end try
3176
+ end if
3177
+ delay 0.6
3178
+ set seenIdentities to {}
3179
+ return my collectTransitionMatches(UI elements of mainWindow, 0, ${appleScriptString(identityQuery ? query : searchQuery)}, ${identityQuery ? "true" : "false"}, seenIdentities, mainOrigin, mainSize)
3180
+ end tell
3181
+ end tell`;
3182
+ }
3183
+ function transitionAssetSelectionScript(assetName, assetIdentity) {
3184
+ return `
3185
+ ${transitionBrowserTraversalScript()}
3186
+ tell application "System Events"
3187
+ tell process "Final Cut Pro"
3188
+ ${requireFrontmostAppleScript()}
3189
+ set mainWindow to first window whose name is "Final Cut Pro"
3190
+ ${transitionBrowserFocusScript()}
3191
+ set value of transitionSearchField to ${appleScriptString(assetName)}
3192
+ try
3193
+ if (value of transitionSearchField as text) is not ${appleScriptString(assetName)} then
3194
+ click at {(item 1 of mainOrigin) + ((item 1 of mainSize) * 0.72), (item 2 of mainOrigin) + ((item 2 of mainSize) * 0.96)}
3195
+ delay 0.15
3196
+ set transitionSearchField to value of attribute "AXFocusedUIElement"
3197
+ set value of transitionSearchField to ${appleScriptString(assetName)}
3198
+ end if
3199
+ end try
3200
+ delay 0.6
3201
+ set exactCount to my countTransitionItems(UI elements of mainWindow, 0, ${appleScriptString(assetIdentity)}, mainOrigin, mainSize)
3202
+ if exactCount is greater than 1 then error "FINAL_CUT_NATIVE_TRANSITION_ASSET_AMBIGUOUS: multiple exact transition matches were visible"
3203
+ if exactCount is 0 then error "FINAL_CUT_NATIVE_TRANSITION_ASSET_NOT_FOUND: installed transition was not visible"
3204
+ if not my pressTransitionItem(UI elements of mainWindow, 0, ${appleScriptString(assetIdentity)}, mainOrigin, mainSize) then error "FINAL_CUT_NATIVE_TRANSITION_ASSET_NOT_FOUND: installed transition was not selectable"
3205
+ end tell
3206
+ end tell`;
3207
+ }
3208
+ function transitionBrowserTraversalScript() {
3209
+ return `
3210
+ using terms from application "System Events"
3211
+ on transitionBrowserVisible(nodes, depth, mainOrigin, mainSize)
3212
+ if depth > 12 then return false
3213
+ repeat with candidateIndex from 1 to count of nodes
3214
+ try
3215
+ set candidate to contents of item candidateIndex of nodes
3216
+ set candidateRole to role of candidate as text
3217
+ if candidateRole is "AXGroup" and my transitionPaneVisible(candidate, mainOrigin, mainSize) then
3218
+ set candidatePosition to position of candidate
3219
+ set candidateSize to size of candidate
3220
+ set lowerPaneTop to (item 2 of mainOrigin) + ((item 2 of mainSize) * 0.55)
3221
+ if (item 2 of candidatePosition) is greater than lowerPaneTop and (item 1 of candidateSize) is less than 600 and (item 2 of candidateSize) is greater than 200 then return true
3222
+ end if
3223
+ if my transitionBrowserVisible(UI elements of candidate, depth + 1, mainOrigin, mainSize) then return true
3224
+ on error
3225
+ -- Ignore inaccessible descendants and continue the bounded scan.
3226
+ end try
3227
+ end repeat
3228
+ return false
3229
+ end transitionBrowserVisible
3230
+
3231
+ on transitionChildIndices(containerItem)
3232
+ set childCount to count of UI elements of containerItem
3233
+ set orderedIndices to {}
3234
+ repeat with candidateIndex from 1 to childCount
3235
+ set end of orderedIndices to contents of candidateIndex
3236
+ end repeat
3237
+ return orderedIndices
3238
+ end transitionChildIndices
3239
+
3240
+ on transitionCandidateName(candidate)
3241
+ set candidateName to ""
3242
+ try
3243
+ set candidateName to name of candidate as text
3244
+ end try
3245
+ if candidateName is "missing value" then set candidateName to ""
3246
+ if candidateName is "" then
3247
+ try
3248
+ set candidateName to value of candidate as text
3249
+ end try
3250
+ end if
3251
+ if candidateName is "missing value" then set candidateName to ""
3252
+ return candidateName
3253
+ end transitionCandidateName
3254
+
3255
+ on transitionPaneVisible(candidate, mainOrigin, mainSize)
3256
+ set minimumX to (item 1 of mainOrigin) + ((item 1 of mainSize) * 0.60)
3257
+ set minimumY to (item 2 of mainOrigin) + ((item 2 of mainSize) * 0.50)
3258
+ set maximumX to (item 1 of mainOrigin) + (item 1 of mainSize)
3259
+ set maximumY to (item 2 of mainOrigin) + (item 2 of mainSize)
3260
+ try
3261
+ set candidatePosition to position of candidate
3262
+ set candidateSize to size of candidate
3263
+ set candidateX to item 1 of candidatePosition
3264
+ set candidateY to item 2 of candidatePosition
3265
+ set candidateRight to candidateX + (item 1 of candidateSize)
3266
+ set candidateBottom to candidateY + (item 2 of candidateSize)
3267
+ return candidateRight is greater than minimumX and candidateBottom is greater than minimumY and candidateX is less than maximumX and candidateY is less than maximumY
3268
+ on error
3269
+ return false
3270
+ end try
3271
+ end transitionPaneVisible
3272
+
3273
+ on collectTransitionMatches(nodes, depth, queryText, identityQuery, seenIdentities, mainOrigin, mainSize)
3274
+ if depth > 12 then return ""
3275
+ set output to ""
3276
+ repeat with candidateIndex from 1 to count of nodes
3277
+ try
3278
+ set candidate to contents of item candidateIndex of nodes
3279
+ if my transitionPaneVisible(candidate, mainOrigin, mainSize) then
3280
+ set candidateName to my transitionCandidateName(candidate)
3281
+ set candidateIdentity to ""
3282
+ try
3283
+ set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
3284
+ end try
3285
+ set matches to false
3286
+ if candidateIdentity is not "" then
3287
+ if identityQuery then
3288
+ set matches to candidateIdentity is queryText
3289
+ else
3290
+ set matches to candidateName contains queryText
3291
+ end if
3292
+ end if
3293
+ if matches and seenIdentities does not contain candidateIdentity then
3294
+ set end of seenIdentities to candidateIdentity
3295
+ set output to output & candidateName & (ASCII character 31) & candidateIdentity & (ASCII character 30)
3296
+ end if
3297
+ set output to output & my collectTransitionMatches(UI elements of candidate, depth + 1, queryText, identityQuery, seenIdentities, mainOrigin, mainSize)
3298
+ end if
3299
+ on error
3300
+ -- Ignore inaccessible descendants and continue the bounded scan.
3301
+ end try
3302
+ end repeat
3303
+ return output
3304
+ end collectTransitionMatches
3305
+
3306
+ on countTransitionItems(nodes, depth, targetIdentity, mainOrigin, mainSize)
3307
+ if depth > 12 then return 0
3308
+ set matchCount to 0
3309
+ repeat with candidateIndex from 1 to count of nodes
3310
+ try
3311
+ set candidate to contents of item candidateIndex of nodes
3312
+ if my transitionPaneVisible(candidate, mainOrigin, mainSize) then
3313
+ set candidateIdentity to ""
3314
+ try
3315
+ set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
3316
+ end try
3317
+ if candidateIdentity is targetIdentity then set matchCount to matchCount + 1
3318
+ set matchCount to matchCount + my countTransitionItems(UI elements of candidate, depth + 1, targetIdentity, mainOrigin, mainSize)
3319
+ end if
3320
+ on error
3321
+ -- Ignore inaccessible descendants and continue the bounded scan.
3322
+ end try
3323
+ end repeat
3324
+ return matchCount
3325
+ end countTransitionItems
3326
+
3327
+ on pressTransitionItem(nodes, depth, targetIdentity, mainOrigin, mainSize)
3328
+ if depth > 12 then return false
3329
+ repeat with candidateIndex from 1 to count of nodes
3330
+ try
3331
+ set candidate to contents of item candidateIndex of nodes
3332
+ if my transitionPaneVisible(candidate, mainOrigin, mainSize) then
3333
+ set candidateIdentity to ""
3334
+ try
3335
+ set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
3336
+ end try
3337
+ if candidateIdentity is targetIdentity then
3338
+ try
3339
+ perform action "AXPress" of candidate
3340
+ on error
3341
+ click candidate
3342
+ end try
3343
+ return true
3344
+ end if
3345
+ if my pressTransitionItem(UI elements of candidate, depth + 1, targetIdentity, mainOrigin, mainSize) then return true
3346
+ end if
3347
+ on error
3348
+ -- Ignore inaccessible descendants and continue the bounded scan.
3349
+ end try
3350
+ end repeat
3351
+ return false
3352
+ end pressTransitionItem
3353
+ end using terms from`;
3354
+ }
3355
+ function transitionBrowserOpenScript() {
3356
+ return `
3357
+ -- Final Cut exposes the Transitions browser through the workspace menu;
3358
+ -- fixed coordinates vary with sidebar and window layout.
3359
+ set mainOrigin to position of mainWindow
3360
+ set mainSize to size of mainWindow
3361
+ if not my transitionBrowserVisible(UI elements of mainWindow, 0, mainOrigin, mainSize) then
3362
+ click menu bar item "Window" of menu bar 1
3363
+ delay 0.1
3364
+ click menu item "Transitions" of menu 1 of menu item "Show in Workspace" of menu 1 of menu bar item "Window" of menu bar 1
3365
+ delay 0.3
3366
+ end if`;
3367
+ }
3368
+ function transitionBrowserFocusScript() {
3369
+ return `
3370
+ set mainOrigin to position of mainWindow
3371
+ set mainSize to size of mainWindow
3372
+ set transitionSearchField to missing value
3373
+ -- Final Cut exposes the installed-transition search field as the third
3374
+ -- control in the lower-right Effects Library group. Prefer that bounded
3375
+ -- control so a previously focused Browser search field cannot capture the
3376
+ -- transition query.
3377
+ try
3378
+ set transitionSearchField to UI element 3 of UI element 10 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of mainWindow
3379
+ perform action "AXPress" of transitionSearchField
3380
+ set value of attribute "AXFocused" of transitionSearchField to true
3381
+ on error
3382
+ set transitionSearchField to missing value
3383
+ end try
3384
+ try
3385
+ if transitionSearchField is missing value then
3386
+ set focusedCandidate to value of attribute "AXFocusedUIElement"
3387
+ set focusedRole to role of focusedCandidate as text
3388
+ set focusedPosition to position of focusedCandidate
3389
+ set focusedSearchX to item 1 of focusedPosition
3390
+ set focusedSearchY to item 2 of focusedPosition
3391
+ if (focusedRole is "AXSearchField" or focusedRole is "AXTextField") and focusedSearchX is greater than ((item 1 of mainOrigin) + ((item 1 of mainSize) * 0.60)) and focusedSearchY is greater than ((item 2 of mainOrigin) + ((item 2 of mainSize) * 0.70)) then set transitionSearchField to focusedCandidate
3392
+ end if
3393
+ end try
3394
+ if transitionSearchField is missing value then
3395
+ set transitionSearchPoints to {{0.72, 0.96}, {0.68, 0.96}, {0.76, 0.96}, {0.72, 0.91}}
3396
+ repeat with transitionPoint in transitionSearchPoints
3397
+ try
3398
+ click at {(item 1 of mainOrigin) + ((item 1 of mainSize) * (item 1 of transitionPoint)), (item 2 of mainOrigin) + ((item 2 of mainSize) * (item 2 of transitionPoint))}
3399
+ delay 0.15
3400
+ set focusedCandidate to value of attribute "AXFocusedUIElement"
3401
+ set focusedRole to role of focusedCandidate as text
3402
+ set focusedPosition to position of focusedCandidate
3403
+ set focusedSearchX to item 1 of focusedPosition
3404
+ set focusedSearchY to item 2 of focusedPosition
3405
+ set focusedDescription to ""
3406
+ try
3407
+ set focusedDescription to description of focusedCandidate as text
3408
+ end try
3409
+ if (focusedRole is "AXSearchField" or focusedRole is "AXTextField") and focusedSearchX is greater than ((item 1 of mainOrigin) + ((item 1 of mainSize) * 0.60)) and focusedSearchY is greater than ((item 2 of mainOrigin) + ((item 2 of mainSize) * 0.70)) and (focusedDescription contains "search" or focusedDescription contains "Search" or focusedRole is "AXSearchField") then
3410
+ set transitionSearchField to focusedCandidate
3411
+ exit repeat
3412
+ end if
3413
+ end try
3414
+ end repeat
3415
+ end if
3416
+ if transitionSearchField is missing value then error "FINAL_CUT_NATIVE_TRANSITION_SEARCH_UNAVAILABLE: transition search field was not exposed"`;
3417
+ }
3418
+ function selectTransitionEditPointScript(timecode) {
3419
+ return `
3420
+ tell application "System Events"
3421
+ tell process "Final Cut Pro"
3422
+ ${requireFrontmostAppleScript()}
3423
+ set mainWindow to first window whose name is "Final Cut Pro"
3424
+ set origin to position of mainWindow
3425
+ -- Browser asset selection leaves focus in the Browser. Return focus to
3426
+ -- the timeline, then use Final Cut's timecode entry for the exact
3427
+ -- rational edit point captured from the adjacent clip ranges.
3428
+ set windowSize to size of mainWindow
3429
+ click at {(item 1 of origin) + ((item 1 of windowSize) * 0.50), (item 2 of origin) + ((item 2 of windowSize) * 0.82)}
3430
+ delay 0.1
3431
+ keystroke "p" using {control down}
3432
+ keystroke ${appleScriptString(timecode)}
3433
+ key code 36
3434
+ delay 0.2
3435
+ end tell
3436
+ end tell`;
3437
+ }
3438
+ function applyTransitionScript(duration, frameDuration) {
3439
+ const durationText = transitionDurationInput(duration, frameDuration);
3440
+ return `
3441
+ tell application "System Events"
3442
+ tell process "Final Cut Pro"
3443
+ ${requireFrontmostAppleScript()}
3444
+ -- Command-T applies the selected compatible transition. Control-D opens
3445
+ -- Final Cut's duration editor for the selected transition.
3446
+ keystroke "t" using {command down}
3447
+ delay 0.5
3448
+ -- Source clips without overlap handles trigger Final Cut's explicit
3449
+ -- ripple-trim confirmation. Accept it for this requested transition;
3450
+ -- Cancel remains the user's escape hatch outside automation.
3451
+ set transitionConfirmation to missing value
3452
+ repeat with candidateWindow in windows
3453
+ try
3454
+ if exists button "Create Transition" of candidateWindow then
3455
+ set transitionConfirmation to candidateWindow
3456
+ exit repeat
3457
+ end if
3458
+ end try
3459
+ end repeat
3460
+ if transitionConfirmation is not missing value then
3461
+ click button "Create Transition" of transitionConfirmation
3462
+ delay 0.5
3463
+ end if
3464
+ keystroke "d" using {control down}
3465
+ delay 0.2
3466
+ set durationText to ${appleScriptString(durationText)}
3467
+ set durationApplied to false
3468
+ set observedDuration to ""
3469
+ repeat with candidate in text fields of front window
3470
+ try
3471
+ if focused of candidate then
3472
+ set value of candidate to durationText
3473
+ key code 36
3474
+ delay 0.1
3475
+ set observedDuration to value of candidate as text
3476
+ set durationApplied to true
3477
+ exit repeat
3478
+ end if
3479
+ end try
3480
+ end repeat
3481
+ if not durationApplied then error "FINAL_CUT_NATIVE_TRANSITION_DURATION_UNAVAILABLE: Final Cut did not expose a focused transition duration field"
3482
+ if observedDuration is "" then error "FINAL_CUT_NATIVE_TRANSITION_DURATION_UNAVAILABLE: Final Cut did not expose the applied transition duration"
3483
+ return "FRAMEKIT_NATIVE_TRANSITION_DURATION=" & observedDuration
3484
+ end tell
3485
+ end tell`;
3486
+ }
3487
+ function occurrenceRangeEndpointScript(timelineOffset, endpoint) {
3488
+ const shortcut = endpoint === "start" ? "i" : "o";
3489
+ return `
3490
+ tell application "System Events"
3491
+ tell process "Final Cut Pro"
3492
+ ${requireFrontmostAppleScript()}
3493
+ set mainWindow to first window whose name is "Final Cut Pro"
3494
+ set origin to position of mainWindow
3495
+ set windowSize to size of mainWindow
3496
+ -- Framekit occurrence range ${endpoint}: select the actual clip and ask
3497
+ -- Final Cut for its range endpoint rather than inferring from pixels.
3498
+ click at {(item 1 of origin) + ${Math.round(timelineOffset)}, (item 2 of origin) + ((item 2 of windowSize) * 0.77)}
3499
+ delay 0.1
3500
+ keystroke "${shortcut}" using {shift down}
3501
+ delay 0.2
3502
+ end tell
3503
+ end tell`;
3504
+ }
2630
3505
  function titleAssetSelectionScript(assetName) {
2631
3506
  return `
2632
3507
  tell application "System Events"
@@ -2850,14 +3725,16 @@ function parseContext(output) {
2850
3725
  : timelineFocused
2851
3726
  ? "timeline"
2852
3727
  : "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" };
3728
+ const target = selectedCount < 0
3729
+ ? { kind: "unknown" }
3730
+ : selectedCount === 1
3731
+ ? { kind: "selected-clip", ...(selectedName ? { name: selectedName } : {}), ...(selectedRole ? { role: selectedRole } : {}), ...(targetIdentity ? { identity: targetIdentity } : {}) }
3732
+ : selectedCount > 1
3733
+ ? { kind: "unknown" }
3734
+ : (focusedRole === "AXTextField" && (focusedDescription === "text field" || focusedDescription === "Title")
3735
+ || focusedRole === "AXTextArea" && focusedDescription === "text entry area") && focusedName
3736
+ ? { kind: "selected-clip", name: focusedName, role: focusedRole }
3737
+ : { kind: "playhead" };
2861
3738
  return {
2862
3739
  available: true,
2863
3740
  application: "Final Cut Pro",
@@ -2907,25 +3784,48 @@ function parseOccurrences(output, mediaHandle) {
2907
3784
  .map((record) => record.trim())
2908
3785
  .filter(Boolean)
2909
3786
  .map((record, index) => {
2910
- const [name = "", role = "", sourceIdentity = "", timelineOffsetOrDuration = "", legacyTimelineOffset] = record.split(String.fromCharCode(31));
2911
- const legacyRecord = legacyTimelineOffset !== undefined;
3787
+ const fields = record.split(String.fromCharCode(31));
3788
+ const [name = "", role = "", sourceIdentity = "", timelineOffsetOrDuration = "", legacyTimelineOffset, nativeDuration] = fields;
3789
+ const nativeRange = nativeDuration !== undefined;
3790
+ const legacyRecord = legacyTimelineOffset !== undefined && !nativeRange;
2912
3791
  const identityOrStart = sourceIdentity;
2913
- const timelineOffsetText = legacyRecord ? legacyTimelineOffset : timelineOffsetOrDuration;
2914
- const legacyRange = legacyRecord || (!legacyRecord && isRational(identityOrStart) && isRational(timelineOffsetOrDuration));
3792
+ const timelineOffsetText = nativeRange ? timelineOffsetOrDuration : legacyRecord ? legacyTimelineOffset : timelineOffsetOrDuration;
3793
+ const legacyRange = !nativeRange && (legacyRecord || (!legacyRecord && isRational(identityOrStart) && isRational(timelineOffsetOrDuration)));
2915
3794
  return {
2916
- handle: opaqueHandle("occurrence", index),
3795
+ handle: opaqueHandle("occurrence"),
2917
3796
  mediaHandle,
2918
3797
  name,
2919
3798
  ...(role ? { role } : {}),
2920
3799
  ...(sourceIdentity && !legacyRange ? { sourceIdentity } : {}),
3800
+ ...(nativeRange ? { start: legacyTimelineOffset, duration: nativeDuration } : {}),
2921
3801
  ...(legacyRange ? { start: identityOrStart, duration: timelineOffsetOrDuration } : {}),
2922
3802
  ...(timelineOffsetText && Number.isFinite(Number(timelineOffsetText)) ? { timelineOffset: Number(timelineOffsetText) } : {}),
2923
3803
  };
2924
3804
  });
2925
3805
  }
3806
+ function normalizeOccurrenceTimes(occurrences, sequence) {
3807
+ for (const occurrence of occurrences) {
3808
+ if (occurrence.start && !isRational(occurrence.start)) {
3809
+ occurrence.start = rationalText(timelineTimecodeToRational(occurrence.start, sequence, "occurrence start", true));
3810
+ }
3811
+ if (occurrence.duration && !isRational(occurrence.duration)) {
3812
+ occurrence.duration = rationalText(timelineTimecodeToRational(occurrence.duration, sequence, "occurrence duration", false));
3813
+ }
3814
+ }
3815
+ }
2926
3816
  function isRational(value) {
2927
3817
  return /^-?\d+\/\d+$/.test(value);
2928
3818
  }
3819
+ function timelineTimecodeToRational(value, sequence, label, absolute) {
3820
+ const match = value.match(/^(\d+):(\d{2}):(\d{2}):(\d{2})$/);
3821
+ if (!match || !sequence?.frameDuration || !sequence.startTime) {
3822
+ throw new Error(`FINAL_CUT_NATIVE_EDIT_POINT_POSITION_UNAVAILABLE: Final Cut returned an unsupported ${label} ${value || "<empty>"}`);
3823
+ }
3824
+ const framesPerSecond = Math.max(1, Math.round(Number(sequence.frameDuration.timescale) / Number(sequence.frameDuration.value)));
3825
+ const totalFrames = (((BigInt(match[1]) * 60n + BigInt(match[2])) * 60n + BigInt(match[3])) * BigInt(framesPerSecond)) + BigInt(match[4]);
3826
+ const relative = normalizeRational(totalFrames * BigInt(sequence.frameDuration.value), BigInt(sequence.frameDuration.timescale));
3827
+ return absolute ? addRational(sequence.startTime, relative) : relative;
3828
+ }
2929
3829
  function opaqueHandle(kind, suffix) {
2930
3830
  return `${kind}-${Date.now().toString(36)}-${suffix ?? Math.random().toString(36).slice(2, 8)}`;
2931
3831
  }