nitro-ui-macos 0.0.0 → 0.0.1

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 (128) hide show
  1. package/CONTRIBUTING.md +56 -0
  2. package/LICENSE +3 -3
  3. package/PARITY.md +373 -0
  4. package/README.md +144 -5
  5. package/native/nitro-core/Package.swift +78 -0
  6. package/native/nitro-ui-core/Package.swift +112 -0
  7. package/native/nitro-ui-core/Sources/NitroUICoreMac/AnimationFrameDisplayLink.swift +127 -0
  8. package/native/nitro-ui-core/Sources/NitroUICoreMac/HybridAnimationFrameScheduler.swift +91 -0
  9. package/native/nitro-ui-core/Sources/NitroUICoreMac/HybridLinking.swift +18 -0
  10. package/native/nitro-ui-dev/Package.swift +102 -0
  11. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevBundleLoad.swift +14 -0
  12. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevBundleLoader.swift +85 -0
  13. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevLauncher.swift +192 -0
  14. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevMenu.swift +172 -0
  15. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevServerBrowser.swift +86 -0
  16. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevSession.swift +151 -0
  17. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevShortcuts.swift +85 -0
  18. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevToast.swift +85 -0
  19. package/native/nitro-ui-dev/Sources/NitroUIDevMac/DevTools.swift +141 -0
  20. package/native/nitro-ui-dev/Sources/NitroUIDevMac/ErrorModels.swift +97 -0
  21. package/native/nitro-ui-dev/Sources/NitroUIDevMac/ErrorOverlay.swift +698 -0
  22. package/native/nitro-ui-dev/Sources/NitroUIDevMac/HybridDevBundles.swift +64 -0
  23. package/native/nitro-ui-dev/Sources/NitroUIDevMac/HybridDevErrors.swift +56 -0
  24. package/native/nitro-ui-dev/Sources/NitroUIDevMac/HybridDevLoadingView.swift +27 -0
  25. package/native/nitro-ui-dev/Sources/NitroUIDevMac/HybridDevMenu.swift +40 -0
  26. package/native/nitro-ui-dev/Sources/NitroUIDevMac/HybridDevToast.swift +19 -0
  27. package/native/nitro-ui-dev/Sources/NitroUIDevMac/LauncherWindowController.swift +217 -0
  28. package/native/nitro-ui-dev/Sources/NitroUIDevMac/LoadingOverlay.swift +104 -0
  29. package/native/nitro-ui-dev/Sources/NitroUIDevMac/RegisterDevLoader.swift +22 -0
  30. package/native/nitro-ui-dev/Sources/NitroUIDevMac/SavedBundles.swift +70 -0
  31. package/native/nitro-ui-glass/Package.swift +103 -0
  32. package/native/nitro-ui-glass/macos/HybridLiquidGlass.swift +5 -0
  33. package/native/nitro-ui-glass/macos/HybridNativeLiquidGlassContainerView.swift +40 -0
  34. package/native/nitro-ui-glass/macos/HybridNativeLiquidGlassView.swift +80 -0
  35. package/native/nitro-ui-glass/macos/LiquidGlassEffectView.swift +181 -0
  36. package/native/nitro-ui-glass/macos/LiquidGlassSupport.swift +17 -0
  37. package/native/nitro-ui-navigation/Package.swift +105 -0
  38. package/native/nitro-ui-navigation/Sources/NitroUINavigationMac/HybridNavigationScreen.swift +199 -0
  39. package/native/nitro-ui-navigation/Sources/NitroUINavigationMac/HybridNavigationSharedElement.swift +17 -0
  40. package/native/nitro-ui-navigation/Sources/NitroUINavigationMac/HybridNavigationSplit.swift +889 -0
  41. package/native/nitro-ui-navigation/Sources/NitroUINavigationMac/HybridNavigationStack.swift +404 -0
  42. package/native/nitro-ui-navigation/Sources/NitroUINavigationMac/HybridNavigationTabs.swift +186 -0
  43. package/native/nitro-ui-navigation/Sources/NitroUINavigationMac/MacStackContainerController.swift +260 -0
  44. package/native/nitro-ui-navigation/Sources/NitroUINavigationMac/NavigationSharedElementView.swift +28 -0
  45. package/native/nitro-ui-renderer/Package.swift +105 -0
  46. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Animations/HybridAnimator.swift +502 -0
  47. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Animations/NitroAnimationContext.swift +54 -0
  48. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Animations/View+Animations.swift +35 -0
  49. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/AssetFonts.swift +36 -0
  50. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/FlippedView.swift +360 -0
  51. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/HybridContainerView.swift +28 -0
  52. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/HybridFonts.swift +7 -0
  53. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/HybridLabel.swift +127 -0
  54. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/HybridMaskedView.swift +185 -0
  55. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/HybridScrollView.swift +255 -0
  56. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/HybridScrollViewContent.swift +22 -0
  57. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/HybridView.swift +18 -0
  58. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/Image/HybridImage.swift +281 -0
  59. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/Image/HybridImageFactory.swift +132 -0
  60. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/Image/HybridImageLoader.swift +149 -0
  61. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/Image/HybridImageView.swift +601 -0
  62. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/Image/ImagePixelSupport.swift +418 -0
  63. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/LabelView.swift +198 -0
  64. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/HybridListView.swift +177 -0
  65. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/NativeListCell.swift +98 -0
  66. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/NativeListContentView.swift +12 -0
  67. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/NativeListFenwickTree.swift +94 -0
  68. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/NativeListScrollView.swift +1100 -0
  69. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/NativeListSnapshot.swift +24 -0
  70. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/NativeListUpdate.swift +11 -0
  71. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/List/NativeListView.swift +260 -0
  72. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/NativeContainerView.swift +443 -0
  73. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/NitroViewProtocols.swift +275 -0
  74. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/ShadowLayers.swift +338 -0
  75. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/TextInput/HybridTextInput.swift +252 -0
  76. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/TextInput/NitroTextInputView.swift +447 -0
  77. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Components/View.swift +660 -0
  78. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/CustomViewController.swift +254 -0
  79. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/DesktopHostDelegate.swift +14 -0
  80. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Extensions.swift +102 -0
  81. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Gestures/GestureRecognizerDelegate.swift +24 -0
  82. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Gestures/HybridGestureRecognizer.swift +41 -0
  83. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Gestures/HybridLongPressGestureRecognizer.swift +172 -0
  84. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Gestures/HybridPanGestureRecognizer.swift +193 -0
  85. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Gestures/HybridTapGestureRecognizer.swift +165 -0
  86. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/HybridAppearance.swift +75 -0
  87. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/HybridApplication.swift +29 -0
  88. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/HybridKeyboard.swift +26 -0
  89. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/HybridScreen.swift +29 -0
  90. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/HybridViewController.swift +232 -0
  91. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/HybridWindow.swift +61 -0
  92. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/HybridWindowScene.swift +17 -0
  93. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/LayoutNode.swift +73 -0
  94. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/NSColor+rgba.swift +29 -0
  95. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/RegisterRootCallback.swift +27 -0
  96. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/RuntimeReloadableAppDelegate.swift +7 -0
  97. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/SafeAreaInsetsListeners.swift +26 -0
  98. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/SizeListeners.swift +27 -0
  99. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/UIErrorHandler.swift +15 -0
  100. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/ViewController.swift +6 -0
  101. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/Window.swift +156 -0
  102. package/native/nitro-ui-renderer/Sources/NitroUIRendererMac/WindowScene.swift +23 -0
  103. package/native/nitro-ui-runtime/Package.swift +67 -0
  104. package/native/nitro-ui-runtime/Sources/NitroUIRuntimeMac/DevLoader.swift +16 -0
  105. package/native/nitro-ui-runtime/Sources/NitroUIRuntimeMac/NitroUIAppDelegate.swift +253 -0
  106. package/package.json +57 -8
  107. package/src/Platform.ts +43 -0
  108. package/src/bin.js +18 -0
  109. package/src/build.ts +453 -0
  110. package/src/bundleWorker.ts +80 -0
  111. package/src/cli.ts +157 -0
  112. package/src/config.ts +233 -0
  113. package/src/create.ts +67 -0
  114. package/src/files.ts +70 -0
  115. package/src/index.ts +1 -0
  116. package/src/init.ts +301 -0
  117. package/src/inlinePlatform.ts +140 -0
  118. package/src/modules.ts +385 -0
  119. package/src/packageApp.ts +103 -0
  120. package/src/packageDirectory.ts +61 -0
  121. package/src/preload.ts +40 -0
  122. package/src/prepare.ts +433 -0
  123. package/src/run.ts +41 -0
  124. package/src/runApp.ts +81 -0
  125. package/src/start.ts +152 -0
  126. package/src/toolchain.ts +83 -0
  127. package/src/versions.ts +103 -0
  128. package/templates/AppIcon.icns +0 -0
@@ -0,0 +1,78 @@
1
+ // swift-tools-version: 6.4
2
+
3
+ import PackageDescription
4
+
5
+ // `native` is linked from the installed nitro-core package during `nitro-ui-macos prepare`.
6
+ let cxxSettings: [CXXSetting] = [
7
+ .define("DEBUG", .when(configuration: .debug)),
8
+ .define("NDEBUG", .when(configuration: .release)),
9
+ // This host uses Hermes' native UTF-16 string creation.
10
+ .define("NITRO_JSI_HAS_FAST_UTF16", to: "true"),
11
+ .disableWarning("nullability-extension"),
12
+ ]
13
+
14
+ let package = Package(
15
+ name: "NitroCore",
16
+ platforms: [.macOS(.v13)],
17
+ products: [
18
+ .library(
19
+ name: "NitroModules",
20
+ targets: [
21
+ "NitroModulesCxx", "NitroModulesAppleCxx", "NitroModules", "NitroModulesSwiftBridge",
22
+ ])
23
+ ],
24
+ dependencies: [
25
+ .package(path: "../nitro-hermes"),
26
+ .package(
27
+ url: "https://github.com/margelo/simdutf-swift.git",
28
+ from: "1.1.0",
29
+ traits: ["UTF8", "UTF16", "ASCII"]
30
+ ),
31
+ ],
32
+ targets: [
33
+ .target(
34
+ name: "NitroModulesCxx",
35
+ dependencies: [.product(name: "HermesJSI", package: "nitro-hermes")],
36
+ path: "native/cpp",
37
+ sources: ["src"],
38
+ publicHeadersPath: "include",
39
+ cxxSettings: cxxSettings
40
+ ),
41
+ .target(
42
+ name: "NitroModulesAppleCxx",
43
+ dependencies: ["NitroModulesCxx"],
44
+ path: "native/apple",
45
+ sources: ["src"],
46
+ publicHeadersPath: "include",
47
+ cxxSettings: cxxSettings
48
+ ),
49
+ .target(
50
+ name: "NitroModules",
51
+ dependencies: [
52
+ "NitroModulesCxx", "NitroModulesAppleCxx",
53
+ .product(name: "SimdUTF", package: "simdutf-swift"),
54
+ ],
55
+ path: "native/apple",
56
+ sources: ["core", "utils"],
57
+ cxxSettings: cxxSettings,
58
+ swiftSettings: [
59
+ .swiftLanguageMode(.v6),
60
+ .enableUpcomingFeature("InternalImportsByDefault"),
61
+ .enableUpcomingFeature("MemberImportVisibility"),
62
+ .interoperabilityMode(.Cxx),
63
+ .unsafeFlags(["-Xfrontend", "-clang-header-expose-decls=has-expose-attr-or-stdlib"]),
64
+ ]
65
+ ),
66
+ .target(
67
+ name: "NitroModulesSwiftBridge",
68
+ dependencies: ["NitroModules", "NitroModulesAppleCxx"],
69
+ path: "native/apple/swift-bridge",
70
+ sources: ["src"],
71
+ publicHeadersPath: "include",
72
+ cxxSettings: cxxSettings + [
73
+ .unsafeFlags(["-I${GENERATED_MODULEMAP_DIR}", "-fno-modules"])
74
+ ]
75
+ ),
76
+ ],
77
+ cxxLanguageStandard: .cxx20
78
+ )
@@ -0,0 +1,112 @@
1
+ // swift-tools-version: 6.4
2
+
3
+ import Foundation
4
+ import PackageDescription
5
+
6
+ let name = "NitroUICore"
7
+ let generated = "nitrogen/generated"
8
+ let nitroDependencies: [Target.Dependency] = [
9
+ .product(name: "NitroModules", package: "nitro-core")
10
+ ]
11
+ let cxxSettings: [CXXSetting] = [
12
+ .define("DEBUG", .when(configuration: .debug)),
13
+ .define("NDEBUG", .when(configuration: .release)),
14
+ .disableWarning("nullability-extension"),
15
+ ]
16
+ let swiftSources = ["Sources/NitroUICore", "\(generated)/apple/swift"]
17
+ let bridgeSources = ["c++", "NitroUICore-Swift-Cxx-Bridge.cpp", "NitroUICoreAutolinking.cpp"]
18
+
19
+ let package = Package(
20
+ name: name,
21
+ platforms: [.macOS(.v13)],
22
+ products: [
23
+ .library(name: name, targets: ["\(name)Cxx", name, "\(name)SwiftBridge"])
24
+ ],
25
+ dependencies: [
26
+ .package(path: "../nitro-core"),
27
+ .package(url: "https://github.com/margelo/simdutf-swift.git", from: "1.1.0", traits: ["UTF8", "UTF16"]),
28
+ ],
29
+ targets: [
30
+ .target(
31
+ name: "AdaURL",
32
+ path: "third-party/ada",
33
+ sources: ["src/ada.cpp"],
34
+ publicHeadersPath: "include",
35
+ cxxSettings: [.define("ADA_INCLUDE_URL_PATTERN", to: "0")]
36
+ ),
37
+ .target(
38
+ name: "NitroUIURL",
39
+ dependencies: ["AdaURL", .product(name: "SimdUTF", package: "simdutf-swift"), .target(name: "\(name)Cxx")] + nitroDependencies,
40
+ cxxSettings: cxxSettings + [.define("ADA_INCLUDE_URL_PATTERN", to: "0")]
41
+ ),
42
+ .target(
43
+ name: "\(name)Cxx",
44
+ dependencies: nitroDependencies,
45
+ path: "\(generated)/shared/c++",
46
+ exclude: ["include"],
47
+ publicHeadersPath: "include",
48
+ cxxSettings: cxxSettings
49
+ ),
50
+ .target(
51
+ name: "\(name)AppleCxx",
52
+ dependencies: [.target(name: "\(name)Cxx")] + nitroDependencies,
53
+ path: "\(generated)/apple/\(name)AppleCxx",
54
+ cxxSettings: cxxSettings
55
+ ),
56
+ .target(
57
+ name: name,
58
+ dependencies: [.target(name: "\(name)AppleCxx")] + nitroDependencies,
59
+ path: ".",
60
+ exclude: excludes(in: ".", keeping: swiftSources),
61
+ sources: swiftSources,
62
+ cxxSettings: cxxSettings,
63
+ swiftSettings: [
64
+ .swiftLanguageMode(.v5),
65
+ .unsafeFlags(["-strict-concurrency=minimal"]),
66
+ .enableUpcomingFeature("InternalImportsByDefault"),
67
+ .enableUpcomingFeature("MemberImportVisibility"),
68
+ .interoperabilityMode(.Cxx),
69
+ .unsafeFlags(["-Xfrontend", "-clang-header-expose-decls=has-expose-attr-or-stdlib"]),
70
+ .unsafeFlags([
71
+ "-Xfrontend", "-clang-header-expose-module",
72
+ "-Xfrontend", "NitroModules=NitroModules-Swift.h",
73
+ ]),
74
+ ]
75
+ ),
76
+ .target(
77
+ name: "\(name)SwiftBridge",
78
+ dependencies: ["NitroUIURL", .target(name: name), .target(name: "\(name)AppleCxx")] + nitroDependencies,
79
+ path: "\(generated)/apple",
80
+ exclude: excludes(in: "\(generated)/apple", keeping: bridgeSources) + ["c++/include"],
81
+ sources: bridgeSources,
82
+ publicHeadersPath: "c++/include",
83
+ cxxSettings: cxxSettings + [
84
+ .define("ADA_INCLUDE_URL_PATTERN", to: "0"),
85
+ .unsafeFlags(["-I${GENERATED_MODULEMAP_DIR}", "-fno-modules"]),
86
+ ]
87
+ ),
88
+ ],
89
+ cxxLanguageStandard: .cxx20
90
+ )
91
+
92
+ func excludes(in path: String, keeping sources: [String]) -> [String] {
93
+ var parents: Set<String> = [""]
94
+ for source in sources {
95
+ var components = source.split(separator: "/").dropLast()
96
+ while !components.isEmpty {
97
+ parents.insert(components.joined(separator: "/"))
98
+ components = components.dropLast()
99
+ }
100
+ }
101
+ let root = URL(fileURLWithPath: Context.packageDirectory).appendingPathComponent(path)
102
+ return parents.sorted().flatMap { parent in
103
+ let entries =
104
+ (try? FileManager.default.contentsOfDirectory(
105
+ atPath: root.appendingPathComponent(parent).path)) ?? []
106
+ return entries.sorted().compactMap { entry in
107
+ let entryPath = parent.isEmpty ? entry : "\(parent)/\(entry)"
108
+ return entry.hasPrefix(".") || sources.contains(entryPath) || parents.contains(entryPath)
109
+ ? nil : entryPath
110
+ }
111
+ }
112
+ }
@@ -0,0 +1,127 @@
1
+ internal import CoreGraphics
2
+ internal import CoreVideo
3
+ internal import Foundation
4
+ internal import NitroModules
5
+ internal import QuartzCore
6
+
7
+ /// Delivers native display timestamps on the main queue on macOS.
8
+ ///
9
+ /// Uses `CVDisplayLinkCreateWithActiveCGDisplays` first, falls back to
10
+ /// `CVDisplayLinkCreateWithCGDisplay(CGMainDisplayID())` when the display is asleep
11
+ /// (where active-display links fail and `NSScreen.displayLink` pauses), and falls back
12
+ /// to a 60 Hz dispatch timer if no CoreVideo display link can be started (e.g. headless CI).
13
+ final class AnimationFrameDisplayLink: NSObject, @unchecked Sendable {
14
+ private let callback: (Double) -> Void
15
+ private var displayLink: CVDisplayLink?
16
+ private var fallbackTimer: DispatchSourceTimer?
17
+ private var running = false
18
+
19
+ init(callback: @escaping (Double) -> Void) throws {
20
+ self.callback = callback
21
+ super.init()
22
+ self.displayLink = Self.createDisplayLink(callback: { [weak self] timestamp in
23
+ self?.callback(timestamp)
24
+ })
25
+ }
26
+
27
+ private static func createDisplayLink(callback: @escaping @Sendable (Double) -> Void) -> CVDisplayLink? {
28
+ var link: CVDisplayLink?
29
+ var result = CVDisplayLinkCreateWithActiveCGDisplays(&link)
30
+ if result != kCVReturnSuccess || link == nil {
31
+ link = nil
32
+ result = CVDisplayLinkCreateWithCGDisplay(CGMainDisplayID(), &link)
33
+ }
34
+ guard result == kCVReturnSuccess, let resolvedLink = link else {
35
+ return nil
36
+ }
37
+ let handlerResult = CVDisplayLinkSetOutputHandler(resolvedLink) { _, now, _, _, _ in
38
+ let hostFrequency = CVGetHostClockFrequency()
39
+ let timestamp = hostFrequency > 0
40
+ ? Double(now.pointee.hostTime) / hostFrequency
41
+ : CACurrentMediaTime()
42
+ DispatchQueue.main.async(execute: DispatchWorkItem {
43
+ callback(timestamp)
44
+ })
45
+ return kCVReturnSuccess
46
+ }
47
+ guard handlerResult == kCVReturnSuccess else {
48
+ return nil
49
+ }
50
+ return resolvedLink
51
+ }
52
+
53
+ func start() throws {
54
+ guard running == false else { return }
55
+
56
+ if displayLink == nil {
57
+ displayLink = Self.createDisplayLink(callback: { [weak self] timestamp in
58
+ self?.callback(timestamp)
59
+ })
60
+ }
61
+
62
+ if let link = displayLink {
63
+ if CVDisplayLinkIsRunning(link) {
64
+ running = true
65
+ return
66
+ }
67
+ let result = CVDisplayLinkStart(link)
68
+ if result == kCVReturnSuccess {
69
+ running = true
70
+ return
71
+ }
72
+ // The active display link could not start (for example, display state changed);
73
+ // retry once with the main display ID before falling back to a 60 Hz timer.
74
+ var mainLink: CVDisplayLink?
75
+ if CVDisplayLinkCreateWithCGDisplay(CGMainDisplayID(), &mainLink) == kCVReturnSuccess,
76
+ let fallbackLink = mainLink,
77
+ CVDisplayLinkSetOutputHandler(fallbackLink, { [weak self] _, now, _, _, _ in
78
+ let hostFrequency = CVGetHostClockFrequency()
79
+ let timestamp = hostFrequency > 0
80
+ ? Double(now.pointee.hostTime) / hostFrequency
81
+ : CACurrentMediaTime()
82
+ DispatchQueue.main.async(execute: DispatchWorkItem { [weak self] in
83
+ self?.callback(timestamp)
84
+ })
85
+ return kCVReturnSuccess
86
+ }) == kCVReturnSuccess,
87
+ CVDisplayLinkStart(fallbackLink) == kCVReturnSuccess {
88
+ displayLink = fallbackLink
89
+ running = true
90
+ return
91
+ }
92
+ displayLink = nil
93
+ }
94
+
95
+ startFallbackTimer()
96
+ running = true
97
+ }
98
+
99
+ func stop() {
100
+ running = false
101
+ if let link = displayLink, CVDisplayLinkIsRunning(link) {
102
+ CVDisplayLinkStop(link)
103
+ }
104
+ if let timer = fallbackTimer {
105
+ timer.cancel()
106
+ fallbackTimer = nil
107
+ }
108
+ }
109
+
110
+ private func startFallbackTimer() {
111
+ if let existing = fallbackTimer {
112
+ existing.cancel()
113
+ fallbackTimer = nil
114
+ }
115
+ let timer = DispatchSource.makeTimerSource(queue: .main)
116
+ timer.schedule(deadline: .now() + .milliseconds(16), repeating: .milliseconds(16), leeway: .milliseconds(2))
117
+ timer.setEventHandler { [weak self] in
118
+ self?.callback(CACurrentMediaTime())
119
+ }
120
+ fallbackTimer = timer
121
+ timer.resume()
122
+ }
123
+
124
+ deinit {
125
+ stop()
126
+ }
127
+ }
@@ -0,0 +1,91 @@
1
+ internal import Foundation
2
+ internal import NitroModules
3
+ internal import NitroModulesCxx
4
+ internal import QuartzCore
5
+
6
+ /// Owns frame requests separately from the platform display link.
7
+ /// Tracks the link's running state explicitly so a failed start never leaves future requests stuck.
8
+ final class HybridAnimationFrameScheduler: HybridAnimationFrameSchedulerSpec {
9
+ private let timeOrigin = CACurrentMediaTime()
10
+ private let lock = NSLock()
11
+ private var callbacks: [Double: any Callback<(Double), Void>] = [:]
12
+ private var nextId: Double = 1
13
+ private var displayLink: AnimationFrameDisplayLink?
14
+ private var isLinkRunning = false
15
+
16
+ func requestAnimationFrame(callback: any Callback<(Double), Void>) throws -> Double {
17
+ lock.lock()
18
+ defer { lock.unlock() }
19
+
20
+ if displayLink == nil {
21
+ displayLink = try AnimationFrameDisplayLink { [weak self] timestamp in
22
+ self?.fire(timestamp: timestamp)
23
+ }
24
+ }
25
+ if isLinkRunning == false {
26
+ do {
27
+ try displayLink?.start()
28
+ isLinkRunning = true
29
+ } catch {
30
+ displayLink?.stop()
31
+ displayLink = nil
32
+ isLinkRunning = false
33
+ throw error
34
+ }
35
+ }
36
+ let id = nextId
37
+ nextId += 1
38
+ callbacks[id] = callback
39
+ return id
40
+ }
41
+
42
+ func cancelAnimationFrame(id: Double) throws {
43
+ lock.lock()
44
+ defer { lock.unlock() }
45
+ callbacks.removeValue(forKey: id)
46
+ if callbacks.isEmpty && isLinkRunning {
47
+ displayLink?.stop()
48
+ isLinkRunning = false
49
+ }
50
+ }
51
+
52
+ private func fire(timestamp: Double) {
53
+ lock.lock()
54
+ let ids = callbacks.keys.sorted()
55
+ lock.unlock()
56
+
57
+ let timestampMs = max(0, timestamp - timeOrigin) * 1_000
58
+ for id in ids {
59
+ lock.lock()
60
+ let callback = callbacks.removeValue(forKey: id)
61
+ lock.unlock()
62
+ // Remove each request just before calling it so cancellation can affect
63
+ // later callbacks, and newly requested callbacks wait for the next frame.
64
+ do {
65
+ try callback?.callSync(timestampMs)
66
+ } catch {
67
+ margelo.nitro.GlobalErrorHandler.reportError(.animationFrame, error.toCpp())
68
+ }
69
+ }
70
+
71
+ lock.lock()
72
+ if callbacks.isEmpty && isLinkRunning {
73
+ displayLink?.stop()
74
+ isLinkRunning = false
75
+ }
76
+ lock.unlock()
77
+ }
78
+
79
+ func dispose() {
80
+ lock.lock()
81
+ callbacks.removeAll()
82
+ displayLink?.stop()
83
+ displayLink = nil
84
+ isLinkRunning = false
85
+ lock.unlock()
86
+ }
87
+
88
+ deinit {
89
+ dispose()
90
+ }
91
+ }
@@ -0,0 +1,18 @@
1
+ internal import AppKit
2
+ internal import Foundation
3
+ internal import NitroModules
4
+
5
+ final class HybridLinking: HybridLinkingSpec {
6
+ static func openURL(url: String) throws -> any Promise<Void> {
7
+ guard let target = URL(string: url) else {
8
+ throw RuntimeError("\(url) is not a valid URL.")
9
+ }
10
+ let promise: any Promise<Void> = .pending()
11
+ if NSWorkspace.shared.open(target) {
12
+ promise.resolve()
13
+ } else {
14
+ promise.reject(error: RuntimeError("No app could open \(url)."))
15
+ }
16
+ return promise
17
+ }
18
+ }
@@ -0,0 +1,102 @@
1
+ // swift-tools-version: 6.4
2
+
3
+ import Foundation
4
+ import PackageDescription
5
+
6
+ let name = "NitroUIDev"
7
+ let generated = "nitrogen/generated"
8
+ let nitroDependencies: [Target.Dependency] = [
9
+ .product(name: "NitroModules", package: "nitro-core")
10
+ ]
11
+ let cxxSettings: [CXXSetting] = [
12
+ .define("DEBUG", .when(configuration: .debug)),
13
+ .define("NDEBUG", .when(configuration: .release)),
14
+ .disableWarning("nullability-extension"),
15
+ ]
16
+ let swiftSources = ["Sources/NitroUIDevMac", "\(generated)/apple/swift"]
17
+ let bridgeSources = [
18
+ "c++", "NitroUIDev-Swift-Cxx-Bridge.cpp", "NitroUIDevAutolinking.cpp",
19
+ ]
20
+
21
+ let package = Package(
22
+ name: name,
23
+ platforms: [.macOS(.v13)],
24
+ products: [
25
+ .library(name: name, targets: ["\(name)Cxx", name, "\(name)SwiftBridge"])
26
+ ],
27
+ dependencies: [
28
+ .package(path: "../nitro-core"),
29
+ .package(path: "../nitro-ui-runtime"),
30
+ ],
31
+ targets: [
32
+ .target(
33
+ name: "\(name)Cxx",
34
+ dependencies: nitroDependencies,
35
+ path: "\(generated)/shared/c++",
36
+ exclude: ["include"],
37
+ publicHeadersPath: "include",
38
+ cxxSettings: cxxSettings
39
+ ),
40
+ .target(
41
+ name: "\(name)AppleCxx",
42
+ dependencies: [.target(name: "\(name)Cxx")] + nitroDependencies,
43
+ path: "\(generated)/apple/\(name)AppleCxx",
44
+ cxxSettings: cxxSettings
45
+ ),
46
+ .target(
47
+ name: name,
48
+ dependencies: [
49
+ .target(name: "\(name)AppleCxx"),
50
+ .product(name: "NitroUIRuntime", package: "nitro-ui-runtime"),
51
+ ] + nitroDependencies,
52
+ path: ".",
53
+ exclude: excludes(in: ".", keeping: swiftSources),
54
+ sources: swiftSources,
55
+ cxxSettings: cxxSettings,
56
+ swiftSettings: [
57
+ .swiftLanguageMode(.v5),
58
+ .unsafeFlags(["-strict-concurrency=minimal"]),
59
+ .interoperabilityMode(.Cxx),
60
+ .unsafeFlags(["-Xfrontend", "-clang-header-expose-decls=has-expose-attr-or-stdlib"]),
61
+ .unsafeFlags([
62
+ "-Xfrontend", "-clang-header-expose-module",
63
+ "-Xfrontend", "NitroModules=NitroModules-Swift.h",
64
+ ]),
65
+ ]
66
+ ),
67
+ .target(
68
+ name: "\(name)SwiftBridge",
69
+ dependencies: [.target(name: name), .target(name: "\(name)AppleCxx")] + nitroDependencies,
70
+ path: "\(generated)/apple",
71
+ exclude: excludes(in: "\(generated)/apple", keeping: bridgeSources) + ["c++/include"],
72
+ sources: bridgeSources,
73
+ publicHeadersPath: "c++/include",
74
+ cxxSettings: cxxSettings + [
75
+ .unsafeFlags(["-I${GENERATED_MODULEMAP_DIR}", "-fno-modules"])
76
+ ]
77
+ ),
78
+ ],
79
+ cxxLanguageStandard: .cxx20
80
+ )
81
+
82
+ func excludes(in path: String, keeping sources: [String]) -> [String] {
83
+ var parents: Set<String> = [""]
84
+ for source in sources {
85
+ var components = source.split(separator: "/").dropLast()
86
+ while !components.isEmpty {
87
+ parents.insert(components.joined(separator: "/"))
88
+ components = components.dropLast()
89
+ }
90
+ }
91
+ let root = URL(fileURLWithPath: Context.packageDirectory).appendingPathComponent(path)
92
+ return parents.sorted().flatMap { parent in
93
+ let entries =
94
+ (try? FileManager.default.contentsOfDirectory(
95
+ atPath: root.appendingPathComponent(parent).path)) ?? []
96
+ return entries.sorted().compactMap { entry in
97
+ let entryPath = parent.isEmpty ? entry : "\(parent)/\(entry)"
98
+ return entry.hasPrefix(".") || sources.contains(entryPath) || parents.contains(entryPath)
99
+ ? nil : entryPath
100
+ }
101
+ }
102
+ }
@@ -0,0 +1,14 @@
1
+ #if DEBUG
2
+ import Foundation
3
+
4
+ /// The scripts a Debug runtime can run from a server or its local cache.
5
+ public enum DevBundleLoad {
6
+ case ready(client: URL, app: URL, fromCache: Bool)
7
+ case buildError(client: URL, title: String, message: String)
8
+ }
9
+
10
+ struct DevServerBuildError: Decodable {
11
+ let title: String
12
+ let message: String
13
+ }
14
+ #endif
@@ -0,0 +1,85 @@
1
+ #if DEBUG
2
+ import Foundation
3
+
4
+ /// Downloads Debug scripts to local files so Hermes can map them without a JS string copy.
5
+ public enum DevBundleLoader {
6
+ public static func load(from serverURL: String, useSavedBundle: Bool) async throws -> DevBundleLoad {
7
+ guard let base = URL(string: serverURL),
8
+ (base.scheme == "http" || base.scheme == "https"), base.host != nil else {
9
+ throw URLError(.badURL)
10
+ }
11
+ if useSavedBundle, let saved = SavedBundles.files(from: serverURL) {
12
+ return .ready(client: saved.client, app: saved.app, fromCache: true)
13
+ }
14
+
15
+ do {
16
+ let (client, clientStatus) = try await download(base.appendingPathComponent("client.js"), timeout: 8)
17
+ guard clientStatus == 200 else {
18
+ discard(client)
19
+ throw URLError(.badServerResponse)
20
+ }
21
+ do {
22
+ let appURL = base.appendingPathComponent("app.js").appending(queryItems: [URLQueryItem(name: "platform", value: "ios")])
23
+ let (app, appStatus) = try await download(appURL, timeout: 60)
24
+ if appStatus == 500 {
25
+ defer { discard(app) }
26
+ let error = try JSONDecoder().decode(DevServerBuildError.self, from: Data(contentsOf: app))
27
+ return .buildError(client: client, title: error.title, message: error.message)
28
+ }
29
+ guard appStatus == 200 else {
30
+ discard(app)
31
+ throw URLError(.badServerResponse)
32
+ }
33
+ return .ready(client: client, app: app, fromCache: false)
34
+ } catch {
35
+ discard(client)
36
+ throw error
37
+ }
38
+ } catch {
39
+ if Task.isCancelled == false,
40
+ useSavedBundle,
41
+ let urlError = error as? URLError,
42
+ [.timedOut, .cannotFindHost, .cannotConnectToHost, .networkConnectionLost, .notConnectedToInternet, .dnsLookupFailed].contains(urlError.code),
43
+ let saved = SavedBundles.files(from: serverURL) {
44
+ return .ready(client: saved.client, app: saved.app, fromCache: true)
45
+ }
46
+ throw error
47
+ }
48
+ }
49
+
50
+ /// Saves both scripts only after Hermes has run the app successfully.
51
+ public static func save(_ load: DevBundleLoad, from serverURL: String) async throws {
52
+ guard case .ready(let client, let app, false) = load else { return }
53
+ defer { discard(client); discard(app) }
54
+ try SavedBundles.save(client: client, app: app, from: serverURL)
55
+ }
56
+
57
+ public static func discard(_ load: DevBundleLoad) {
58
+ switch load {
59
+ case .ready(let client, let app, let fromCache):
60
+ if fromCache == false { discard(client); discard(app) }
61
+ case .buildError(let client, _, _):
62
+ discard(client)
63
+ }
64
+ }
65
+
66
+ private static func download(_ url: URL, timeout: TimeInterval) async throws -> (URL, Int) {
67
+ var request = URLRequest(url: url)
68
+ request.timeoutInterval = timeout
69
+ request.cachePolicy = .reloadIgnoringLocalCacheData
70
+ let (temporary, response) = try await URLSession.shared.download(for: request)
71
+ try Task.checkCancellation()
72
+ guard let status = (response as? HTTPURLResponse)?.statusCode else {
73
+ throw URLError(.badServerResponse)
74
+ }
75
+ let file = FileManager.default.temporaryDirectory
76
+ .appendingPathComponent(UUID().uuidString).appendingPathExtension("js")
77
+ try FileManager.default.moveItem(at: temporary, to: file)
78
+ return (file, status)
79
+ }
80
+
81
+ private static func discard(_ file: URL) {
82
+ try? FileManager.default.removeItem(at: file)
83
+ }
84
+ }
85
+ #endif