nitro-ui-macos 0.0.0 → 0.0.2

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 +49 -0
  2. package/LICENSE +4 -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 +59 -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,418 @@
1
+ internal import AppKit
2
+ internal import CoreGraphics
3
+ internal import Foundation
4
+ internal import ImageIO
5
+ internal import NitroModules
6
+ internal import NitroModulesCxx
7
+ internal import UniformTypeIdentifiers
8
+
9
+ extension String {
10
+ var normalizedFilePath: String {
11
+ if hasPrefix("file://"), let url = URL(string: self) {
12
+ return url.path
13
+ }
14
+ return self
15
+ }
16
+ }
17
+
18
+ extension Color {
19
+ func toNSColor() -> NSColor {
20
+ return NSColor(srgbRed: CGFloat(r), green: CGFloat(g), blue: CGFloat(b), alpha: CGFloat(a ?? 1))
21
+ }
22
+ }
23
+
24
+ extension CGImage {
25
+ private var isLittleEndian: Bool {
26
+ switch byteOrderInfo {
27
+ case .orderDefault, .order16Big, .order32Big:
28
+ return false
29
+ case .order16Little, .order32Little:
30
+ return true
31
+ case .orderMask:
32
+ fatalError(".orderMask is an unknown value for endianness!")
33
+ @unknown default:
34
+ fatalError("CGImage has unknown .byteOrderInfo!")
35
+ }
36
+ }
37
+
38
+ var pixelFormat: PixelFormat {
39
+ guard bitsPerComponent == 8, bitsPerPixel == 32 else {
40
+ return .unknown
41
+ }
42
+ switch alphaInfo {
43
+ case .premultipliedFirst, .first, .noneSkipFirst:
44
+ return isLittleEndian ? .bgra : .argb
45
+ case .premultipliedLast, .last, .noneSkipLast:
46
+ return isLittleEndian ? .abgr : .rgba
47
+ case .none:
48
+ return isLittleEndian ? .bgr : .rgb
49
+ default:
50
+ return .unknown
51
+ }
52
+ }
53
+ }
54
+
55
+ extension CGBitmapInfo {
56
+ init(pixelFormat: PixelFormat) throws {
57
+ let alphaFirst = CGImageAlphaInfo.premultipliedFirst.rawValue
58
+ let alphaLast = CGImageAlphaInfo.premultipliedLast.rawValue
59
+ let noneFirst = CGImageAlphaInfo.noneSkipFirst.rawValue
60
+ let noneLast = CGImageAlphaInfo.noneSkipLast.rawValue
61
+ let o32L = CGBitmapInfo.byteOrder32Little.rawValue
62
+ let o32B = CGBitmapInfo.byteOrder32Big.rawValue
63
+
64
+ switch pixelFormat {
65
+ case .argb: self.init(rawValue: alphaFirst | o32B)
66
+ case .bgra: self.init(rawValue: alphaFirst | o32L)
67
+ case .abgr: self.init(rawValue: alphaLast | o32L)
68
+ case .rgba: self.init(rawValue: alphaLast | o32B)
69
+ case .xrgb: self.init(rawValue: noneFirst | o32B)
70
+ case .bgrx: self.init(rawValue: noneFirst | o32L)
71
+ case .xbgr: self.init(rawValue: noneLast | o32L)
72
+ case .rgbx: self.init(rawValue: noneLast | o32B)
73
+ case .rgb: self.init(rawValue: CGImageAlphaInfo.none.rawValue)
74
+ case .bgr:
75
+ throw RuntimeError("Core Graphics does not support 24-bit BGR - expand the data to BGRX first!")
76
+ case .unknown:
77
+ throw RuntimeError("Cannot initialize CGBitmapInfo with .unknown PixelFormat!")
78
+ }
79
+ }
80
+ }
81
+
82
+ private func expandBGRToBGRX(_ bgr: ArrayBuffer, width: Int, height: Int) throws -> ArrayBuffer {
83
+ let pixelCount = width * height
84
+ guard bgr.size >= pixelCount * 3 else {
85
+ throw RuntimeError("BGR buffer is too small! (Size: \(bgr.size), Expected: \(pixelCount * 3))")
86
+ }
87
+ guard let source = bgr.data else {
88
+ throw RuntimeError("Cannot expand BGR pixel data from an ArrayBuffer without a data pointer!")
89
+ }
90
+ let bgrx = ArrayBuffer.allocate(pixelCount * 4)
91
+ guard let destination = bgrx.data else {
92
+ throw RuntimeError("Cannot write BGRX pixel data to an ArrayBuffer without a data pointer!")
93
+ }
94
+ for i in 0 ..< pixelCount {
95
+ destination[i * 4] = source[i * 3]
96
+ destination[i * 4 + 1] = source[i * 3 + 1]
97
+ destination[i * 4 + 2] = source[i * 3 + 2]
98
+ destination[i * 4 + 3] = 0xFF
99
+ }
100
+ return bgrx
101
+ }
102
+
103
+ extension CGDataProvider {
104
+ static func fromArrayBuffer(_ arrayBuffer: ArrayBuffer) throws -> CGDataProvider {
105
+ guard arrayBuffer.isOwner else {
106
+ throw RuntimeError(
107
+ "Cannot create CGDataProvider from a non-owning ArrayBuffer! Copy the buffer first to make it owning."
108
+ )
109
+ }
110
+ guard let data = arrayBuffer.data else {
111
+ throw RuntimeError("Cannot create CGDataProvider from an ArrayBuffer without a data pointer!")
112
+ }
113
+
114
+ final class ArrayBufferHolder {
115
+ let arrayBuffer: ArrayBuffer
116
+ init(arrayBuffer: ArrayBuffer) {
117
+ self.arrayBuffer = arrayBuffer
118
+ }
119
+ }
120
+ let holder = ArrayBufferHolder(arrayBuffer: arrayBuffer)
121
+ let provider = CGDataProvider(
122
+ dataInfo: Unmanaged.passRetained(holder).toOpaque(),
123
+ data: data,
124
+ size: arrayBuffer.size
125
+ ) { info, _, _ in
126
+ guard let info else {
127
+ fatalError("CGDataProvider releaseFunc called without a pointer to our ArrayBufferHolder!")
128
+ }
129
+ _ = Unmanaged<ArrayBufferHolder>.fromOpaque(info).takeRetainedValue()
130
+ }
131
+ guard let provider else {
132
+ throw RuntimeError("Failed to create CGDataProvider from ArrayBuffer! (Size: \(arrayBuffer.size))")
133
+ }
134
+ return provider
135
+ }
136
+ }
137
+
138
+ extension NSImage {
139
+ var nitroCGImage: CGImage? {
140
+ var rect = NSRect(origin: .zero, size: size)
141
+ if let cg = cgImage(forProposedRect: &rect, context: nil, hints: nil) {
142
+ return cg
143
+ }
144
+ let width = Int(ceil(size.width))
145
+ let height = Int(ceil(size.height))
146
+ guard width > 0, height > 0 else { return nil }
147
+ let colorSpace = CGColorSpaceCreateDeviceRGB()
148
+ let bitmapInfo = CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue
149
+ guard let ctx = CGContext(
150
+ data: nil,
151
+ width: width,
152
+ height: height,
153
+ bitsPerComponent: 8,
154
+ bytesPerRow: width * 4,
155
+ space: colorSpace,
156
+ bitmapInfo: bitmapInfo
157
+ ) else {
158
+ return nil
159
+ }
160
+ let graphicsContext = NSGraphicsContext(cgContext: ctx, flipped: false)
161
+ let previous = NSGraphicsContext.current
162
+ NSGraphicsContext.current = graphicsContext
163
+ draw(in: NSRect(origin: .zero, size: CGSize(width: width, height: height)))
164
+ NSGraphicsContext.current = previous
165
+ return ctx.makeImage()
166
+ }
167
+
168
+ var memorySize: Int {
169
+ guard let cg = nitroCGImage else {
170
+ return Int(size.width * size.height) * 4
171
+ }
172
+ return cg.bytesPerRow * cg.height
173
+ }
174
+
175
+ convenience init(fromRawPixelData data: RawPixelData) throws {
176
+ let width = Int(data.width)
177
+ let height = Int(data.height)
178
+ guard width > 0, height > 0 else {
179
+ throw RuntimeError("RawPixelData width and height must be positive! (\(data.width)x\(data.height))")
180
+ }
181
+ let bitsPerComponent = 8
182
+ var buffer = data.buffer.asOwning()
183
+ var pixelFormat = data.pixelFormat
184
+ if pixelFormat == .bgr {
185
+ buffer = try expandBGRToBGRX(buffer, width: width, height: height)
186
+ pixelFormat = .bgrx
187
+ }
188
+ let bytesPerPixel = pixelFormat == .rgb ? 3 : 4
189
+ let bytesPerRow = width * bytesPerPixel
190
+ let dataProvider = try CGDataProvider.fromArrayBuffer(buffer)
191
+ let colorSpace = CGColorSpaceCreateDeviceRGB()
192
+ let bitmapInfo = try CGBitmapInfo(pixelFormat: pixelFormat)
193
+
194
+ guard let cg = CGImage(
195
+ width: width,
196
+ height: height,
197
+ bitsPerComponent: bitsPerComponent,
198
+ bitsPerPixel: bitsPerComponent * bytesPerPixel,
199
+ bytesPerRow: bytesPerRow,
200
+ space: colorSpace,
201
+ bitmapInfo: bitmapInfo,
202
+ provider: dataProvider,
203
+ decode: nil,
204
+ shouldInterpolate: false,
205
+ intent: .defaultIntent
206
+ ) else {
207
+ throw RuntimeError(
208
+ "Failed to create CGImage from the given RawPixelData! (Size: \(data.buffer.size), Format: \(data.pixelFormat))"
209
+ )
210
+ }
211
+ self.init(cgImage: cg, size: NSSize(width: width, height: height))
212
+ }
213
+
214
+ func toRawPixelData() throws -> RawPixelData {
215
+ guard let cg = nitroCGImage else {
216
+ throw RuntimeError("Failed to get Image's underlying cgImage!")
217
+ }
218
+ let width = cg.width
219
+ let height = cg.height
220
+ let bytesPerPixel = 4
221
+ let bytesPerRow = bytesPerPixel * width
222
+ let bitsPerComponent = 8
223
+ let totalBytesSize = width * height * bytesPerPixel
224
+
225
+ let is32Bit = cg.bitsPerComponent == 8 && cg.bitsPerPixel == 32
226
+ let isTight = cg.bytesPerRow == width * bytesPerPixel
227
+ if is32Bit, isTight,
228
+ let cfData = cg.dataProvider?.data,
229
+ CFDataGetLength(cfData) == totalBytesSize,
230
+ let sourceData = CFDataGetBytePtr(cfData) {
231
+ let arrayBuffer = ArrayBuffer.allocate(totalBytesSize)
232
+ memcpy(arrayBuffer.data, sourceData, totalBytesSize)
233
+ return RawPixelData(
234
+ buffer: arrayBuffer,
235
+ width: Double(width),
236
+ height: Double(height),
237
+ pixelFormat: cg.pixelFormat
238
+ )
239
+ }
240
+
241
+ let arrayBuffer = ArrayBuffer.allocate(totalBytesSize)
242
+ let colorSpace = CGColorSpaceCreateDeviceRGB()
243
+ let bitmapInfo = CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue
244
+ guard let ctx = CGContext(
245
+ data: arrayBuffer.data,
246
+ width: width,
247
+ height: height,
248
+ bitsPerComponent: bitsPerComponent,
249
+ bytesPerRow: bytesPerRow,
250
+ space: colorSpace,
251
+ bitmapInfo: bitmapInfo
252
+ ) else {
253
+ throw RuntimeError("Failed to create CGContext for \(width)x\(height) RGBA Image!")
254
+ }
255
+ ctx.draw(cg, in: CGRect(x: 0, y: 0, width: width, height: height))
256
+ return RawPixelData(
257
+ buffer: arrayBuffer,
258
+ width: Double(width),
259
+ height: Double(height),
260
+ pixelFormat: .bgra
261
+ )
262
+ }
263
+
264
+ func getData(in format: ImageFormat, quality: CGFloat) throws -> Data {
265
+ guard quality.isFinite, quality >= 0, quality <= 100 else {
266
+ throw RuntimeError("Image quality has to be between 0 and 100! (Received: \(quality))")
267
+ }
268
+ guard let cg = nitroCGImage else {
269
+ throw RuntimeError("Failed to get Image's underlying cgImage!")
270
+ }
271
+ let typeIdentifier: CFString
272
+ switch format {
273
+ case .png:
274
+ typeIdentifier = UTType.png.identifier as CFString
275
+ case .jpg:
276
+ typeIdentifier = UTType.jpeg.identifier as CFString
277
+ case .heic:
278
+ typeIdentifier = UTType.heic.identifier as CFString
279
+ }
280
+ let mutableData = NSMutableData()
281
+ guard let destination = CGImageDestinationCreateWithData(mutableData, typeIdentifier, 1, nil) else {
282
+ throw RuntimeError("Failed to create image encoder for format \(format.stringValue)!")
283
+ }
284
+ var options: [CFString: Any] = [:]
285
+ if format == .jpg || format == .heic {
286
+ options[kCGImageDestinationLossyCompressionQuality] = quality.rounded() / 100.0
287
+ }
288
+ CGImageDestinationAddImage(destination, cg, options as CFDictionary)
289
+ guard CGImageDestinationFinalize(destination) else {
290
+ throw RuntimeError("Failed to encode \(size.width)x\(size.height) Image as \(format.stringValue)!")
291
+ }
292
+ return mutableData as Data
293
+ }
294
+
295
+ func toEncodedImageData(format: ImageFormat, quality: Double) throws -> EncodedImageData {
296
+ let data = try getData(in: format, quality: CGFloat(quality))
297
+ let arrayBuffer = try ArrayBuffer.copy(data: data)
298
+ return EncodedImageData(
299
+ buffer: arrayBuffer,
300
+ width: Double(size.width),
301
+ height: Double(size.height),
302
+ imageFormat: format
303
+ )
304
+ }
305
+
306
+ func toBase64(format: ImageFormat, quality: Double) throws -> String {
307
+ let data = try getData(in: format, quality: CGFloat(quality))
308
+ return data.base64EncodedString()
309
+ }
310
+
311
+ func tintedCGImage(with color: NSColor) -> CGImage? {
312
+ guard let cg = nitroCGImage else { return nil }
313
+ let width = cg.width
314
+ let height = cg.height
315
+ let colorSpace = CGColorSpaceCreateDeviceRGB()
316
+ let bitmapInfo = CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue
317
+ guard let ctx = CGContext(
318
+ data: nil,
319
+ width: width,
320
+ height: height,
321
+ bitsPerComponent: 8,
322
+ bytesPerRow: width * 4,
323
+ space: colorSpace,
324
+ bitmapInfo: bitmapInfo
325
+ ) else {
326
+ return nil
327
+ }
328
+ let rect = CGRect(x: 0, y: 0, width: width, height: height)
329
+ ctx.clip(to: rect, mask: cg)
330
+ ctx.setFillColor(color.cgColor)
331
+ ctx.fill(rect)
332
+ return ctx.makeImage()
333
+ }
334
+
335
+ static func decoded(from data: Data, scale: CGFloat = 1) -> NSImage? {
336
+ if let source = CGImageSourceCreateWithData(data as CFData, nil),
337
+ let cg = CGImageSourceCreateImageAtIndex(source, 0, nil) {
338
+ let pointSize = NSSize(
339
+ width: CGFloat(cg.width) / max(1, scale),
340
+ height: CGFloat(cg.height) / max(1, scale)
341
+ )
342
+ return NSImage(cgImage: cg, size: pointSize)
343
+ }
344
+ return NSImage(data: data)
345
+ }
346
+ }
347
+
348
+ enum BundledImage {
349
+ static func load(named name: String, displayScale: CGFloat) -> NSImage? {
350
+ let resolvedScale = displayScale > 0 ? displayScale : (NSScreen.main?.backingScaleFactor ?? 2)
351
+ guard name.hasPrefix("nitro_webp_") else {
352
+ if let image = Bundle.main.image(forResource: NSImage.Name(name)) {
353
+ return image
354
+ }
355
+ return NSImage(named: NSImage.Name(name))
356
+ }
357
+
358
+ let scales: [Int]
359
+ switch resolvedScale {
360
+ case 3...: scales = [3, 2, 1]
361
+ case 2..<3: scales = [2, 1, 3]
362
+ default: scales = [1, 2, 3]
363
+ }
364
+ for scale in scales {
365
+ let assetName = "\(name)_\(scale)x"
366
+ if let asset = NSDataAsset(name: assetName) {
367
+ return NSImage.decoded(from: asset.data, scale: CGFloat(scale))
368
+ }
369
+ }
370
+ return nil
371
+ }
372
+ }
373
+
374
+ struct ImageDecodeTarget: Equatable {
375
+ let width: CGFloat
376
+ let height: CGFloat
377
+ let contain: Bool
378
+
379
+ private func scale(for size: CGSize) -> CGFloat {
380
+ let horizontal = width / size.width
381
+ let vertical = height / size.height
382
+ return contain ? min(horizontal, vertical) : max(horizontal, vertical)
383
+ }
384
+
385
+ static func decode(_ data: Data, target: Self?, prepare: Bool) throws -> NSImage {
386
+ if let target {
387
+ let options = [kCGImageSourceShouldCache: false] as CFDictionary
388
+ if let source = CGImageSourceCreateWithData(data as CFData, options),
389
+ CGImageSourceGetCount(source) == 1,
390
+ let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, options) as? [CFString: Any],
391
+ let width = properties[kCGImagePropertyPixelWidth] as? CGFloat,
392
+ let height = properties[kCGImagePropertyPixelHeight] as? CGFloat,
393
+ width > 0, height > 0 {
394
+ let orientation = properties[kCGImagePropertyOrientation] as? Int ?? 1
395
+ let rotated = (5...8).contains(orientation)
396
+ let size = rotated ? CGSize(width: height, height: width) : CGSize(width: width, height: height)
397
+ let factor = target.scale(for: size)
398
+ if factor < 1 {
399
+ let longestSide = max(width, height)
400
+ let thumbOptions: [CFString: Any] = [
401
+ kCGImageSourceThumbnailMaxPixelSize: ceil(longestSide * factor),
402
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
403
+ kCGImageSourceCreateThumbnailWithTransform: true,
404
+ kCGImageSourceShouldCacheImmediately: prepare,
405
+ ]
406
+ guard let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, thumbOptions as CFDictionary) else {
407
+ throw RuntimeError("Could not decode the image at the requested size.")
408
+ }
409
+ return NSImage(cgImage: thumbnail, size: NSSize(width: thumbnail.width, height: thumbnail.height))
410
+ }
411
+ }
412
+ }
413
+ guard let image = NSImage.decoded(from: data) else {
414
+ throw RuntimeError("The given ArrayBuffer could not be converted to an NSImage!")
415
+ }
416
+ return image
417
+ }
418
+ }
@@ -0,0 +1,198 @@
1
+ internal import AppKit
2
+ internal import Foundation
3
+
4
+ final class LabelView: FlippedView {
5
+ // Drawing TextKit stack — never mutated during layout measurement.
6
+ private let drawTextStorage = NSTextStorage()
7
+ private let drawLayoutManager = NSLayoutManager()
8
+ private let drawTextContainer = NSTextContainer(size: .zero)
9
+
10
+ // Dedicated scratch TextKit stack used exclusively by `sizeThatFits(_:)`.
11
+ private let measureTextStorage = NSTextStorage()
12
+ private let measureLayoutManager = NSLayoutManager()
13
+ private let measureTextContainer = NSTextContainer(size: .zero)
14
+
15
+ private var appliedParagraphAlignment: NSTextAlignment = .natural
16
+
17
+ var text: String?
18
+ var paragraphAlignment: TextAlignment?
19
+
20
+ var resolvedParagraphAlignment: NSTextAlignment {
21
+ switch paragraphAlignment {
22
+ case .center: return .center
23
+ case .start: return userInterfaceLayoutDirection == .rightToLeft ? .right : .left
24
+ case .end: return userInterfaceLayoutDirection == .rightToLeft ? .left : .right
25
+ case .justify: return .justified
26
+ case nil: return .natural
27
+ }
28
+ }
29
+
30
+ var numberOfLines: Int = 0 {
31
+ didSet {
32
+ drawTextContainer.maximumNumberOfLines = numberOfLines
33
+ measureTextContainer.maximumNumberOfLines = numberOfLines
34
+ needsDisplay = true
35
+ }
36
+ }
37
+
38
+ var lineBreakMode: NSLineBreakMode = .byTruncatingTail {
39
+ didSet {
40
+ drawTextContainer.lineBreakMode = lineBreakMode
41
+ measureTextContainer.lineBreakMode = lineBreakMode
42
+ needsDisplay = true
43
+ }
44
+ }
45
+
46
+ var attributedText: NSAttributedString = NSAttributedString() {
47
+ didSet {
48
+ appliedParagraphAlignment = resolvedParagraphAlignment
49
+ drawTextStorage.setAttributedString(attributedText)
50
+ measureTextStorage.setAttributedString(attributedText)
51
+ needsDisplay = true
52
+ }
53
+ }
54
+
55
+ var contentInsets: NSEdgeInsets = NSEdgeInsets() {
56
+ didSet {
57
+ guard contentInsets.top != oldValue.top
58
+ || contentInsets.left != oldValue.left
59
+ || contentInsets.bottom != oldValue.bottom
60
+ || contentInsets.right != oldValue.right
61
+ else { return }
62
+ needsDisplay = true
63
+ }
64
+ }
65
+
66
+ override init(frame frameRect: NSRect) {
67
+ super.init(frame: frameRect)
68
+ // Match UILabel: labels do not intercept pointer clicks unless gesture recognizers are attached.
69
+ isUserInteractionEnabled = false
70
+
71
+ for (storage, layoutManager, container) in [
72
+ (drawTextStorage, drawLayoutManager, drawTextContainer),
73
+ (measureTextStorage, measureLayoutManager, measureTextContainer),
74
+ ] {
75
+ container.lineFragmentPadding = 0
76
+ container.maximumNumberOfLines = 0
77
+ container.lineBreakMode = .byTruncatingTail
78
+ layoutManager.addTextContainer(container)
79
+ storage.addLayoutManager(layoutManager)
80
+ }
81
+ }
82
+
83
+ override func isAccessibilityElement() -> Bool {
84
+ return !isHidden
85
+ }
86
+
87
+ override func accessibilityRole() -> NSAccessibility.Role? {
88
+ return nitroAccessibilityRole ?? .staticText
89
+ }
90
+
91
+ override func accessibilityValue() -> Any? {
92
+ return text ?? ""
93
+ }
94
+
95
+ override func accessibilityLabel() -> String? {
96
+ return nitroAccessibilityLabel ?? text
97
+ }
98
+
99
+ override func setFrameSize(_ newSize: NSSize) {
100
+ super.setFrameSize(newSize)
101
+ needsDisplay = true
102
+ }
103
+
104
+ override func layout() {
105
+ super.layout()
106
+ syncParagraphAlignmentIfNeeded()
107
+ }
108
+
109
+ override func viewDidChangeEffectiveAppearance() {
110
+ super.viewDidChangeEffectiveAppearance()
111
+ needsDisplay = true
112
+ }
113
+
114
+ private func syncParagraphAlignmentIfNeeded() {
115
+ let alignment = resolvedParagraphAlignment
116
+ guard alignment != appliedParagraphAlignment, drawTextStorage.length > 0 else {
117
+ return
118
+ }
119
+ appliedParagraphAlignment = alignment
120
+ let fullRange = NSRange(location: 0, length: drawTextStorage.length)
121
+ for storage in [drawTextStorage, measureTextStorage] {
122
+ storage.beginEditing()
123
+ storage.enumerateAttribute(.paragraphStyle, in: fullRange) { value, range, _ in
124
+ let mutable = (value as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle
125
+ ?? NSMutableParagraphStyle()
126
+ mutable.alignment = alignment
127
+ storage.addAttribute(.paragraphStyle, value: mutable, range: range)
128
+ }
129
+ storage.endEditing()
130
+ }
131
+ needsDisplay = true
132
+ }
133
+
134
+ /// Measures text content inside `availableSize` without mutating the drawing container.
135
+ /// Matches UIKit's `UILabel.sizeThatFits(_:)`: Starlight handles `contentInsets` outside `measure`.
136
+ func sizeThatFits(_ availableSize: CGSize) -> CGSize {
137
+ syncParagraphAlignmentIfNeeded()
138
+ guard measureTextStorage.length > 0 else {
139
+ return .zero
140
+ }
141
+ let containerWidth = availableSize.width.isFinite
142
+ ? max(0, availableSize.width)
143
+ : CGFloat.greatestFiniteMagnitude
144
+ let containerHeight = availableSize.height.isFinite
145
+ ? max(0, availableSize.height)
146
+ : CGFloat.greatestFiniteMagnitude
147
+ measureTextContainer.size = CGSize(width: containerWidth, height: containerHeight)
148
+ measureLayoutManager.ensureLayout(for: measureTextContainer)
149
+ let used = measureLayoutManager.usedRect(for: measureTextContainer)
150
+ return CGSize(width: ceil(used.width), height: ceil(used.height))
151
+ }
152
+
153
+ /// Reports whether the most recent drawing layout truncated any glyphs.
154
+ var isTruncatedInCurrentLayout: Bool {
155
+ guard drawTextStorage.length > 0 else { return false }
156
+ let contentRect = currentContentRect()
157
+ guard contentRect.width > 0, contentRect.height > 0 else { return false }
158
+ drawTextContainer.size = contentRect.size
159
+ drawLayoutManager.ensureLayout(for: drawTextContainer)
160
+ let glyphRange = drawLayoutManager.glyphRange(for: drawTextContainer)
161
+ if glyphRange.length < drawLayoutManager.numberOfGlyphs {
162
+ return true
163
+ }
164
+ if glyphRange.length > 0 {
165
+ let truncated = drawLayoutManager.truncatedGlyphRange(inLineFragmentForGlyphAt: glyphRange.upperBound - 1)
166
+ if truncated.location != NSNotFound && truncated.length > 0 {
167
+ return true
168
+ }
169
+ }
170
+ return false
171
+ }
172
+
173
+ private func currentContentRect() -> NSRect {
174
+ return NSRect(
175
+ x: bounds.minX + contentInsets.left,
176
+ y: bounds.minY + contentInsets.top,
177
+ width: max(0, bounds.width - contentInsets.left - contentInsets.right),
178
+ height: max(0, bounds.height - contentInsets.top - contentInsets.bottom)
179
+ )
180
+ }
181
+
182
+ override func draw(_ dirtyRect: NSRect) {
183
+ super.draw(dirtyRect)
184
+ syncParagraphAlignmentIfNeeded()
185
+ guard drawTextStorage.length > 0 else { return }
186
+ let contentRect = currentContentRect()
187
+ guard contentRect.width > 0, contentRect.height > 0 else { return }
188
+ drawTextContainer.size = contentRect.size
189
+ drawLayoutManager.ensureLayout(for: drawTextContainer)
190
+ let glyphRange = drawLayoutManager.glyphRange(for: drawTextContainer)
191
+ guard glyphRange.length > 0 else { return }
192
+ let used = drawLayoutManager.usedRect(for: drawTextContainer)
193
+ let verticalOffset = max(0, (contentRect.height - used.height) / 2)
194
+ let origin = NSPoint(x: contentRect.minX, y: contentRect.minY + verticalOffset)
195
+ drawLayoutManager.drawBackground(forGlyphRange: glyphRange, at: origin)
196
+ drawLayoutManager.drawGlyphs(forGlyphRange: glyphRange, at: origin)
197
+ }
198
+ }