@blotch/angular-lynx-native 22.2.19 → 22.2.21

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 (50) hide show
  1. package/README.md +4 -4
  2. package/dist/android/icon.d.ts +29 -0
  3. package/dist/android/icon.d.ts.map +1 -0
  4. package/dist/android/icon.js +142 -0
  5. package/dist/android/project.d.ts +2 -1
  6. package/dist/android/project.d.ts.map +1 -1
  7. package/dist/android/project.js +5 -2
  8. package/dist/generate.d.ts +2 -2
  9. package/dist/generate.d.ts.map +1 -1
  10. package/dist/generate.js +11 -4
  11. package/dist/index.d.ts +1 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +12 -4
  14. package/dist/ios/build.d.ts +55 -12
  15. package/dist/ios/build.d.ts.map +1 -1
  16. package/dist/ios/build.js +203 -42
  17. package/dist/ios/iphone.d.ts +99 -0
  18. package/dist/ios/iphone.d.ts.map +1 -0
  19. package/dist/ios/iphone.js +204 -0
  20. package/dist/ios/project.d.ts +2 -0
  21. package/dist/ios/project.d.ts.map +1 -1
  22. package/dist/ios/project.js +10 -1
  23. package/dist/ios/run.d.ts +17 -2
  24. package/dist/ios/run.d.ts.map +1 -1
  25. package/dist/ios/run.js +30 -4
  26. package/dist/options.d.ts +49 -3
  27. package/dist/options.d.ts.map +1 -1
  28. package/dist/options.js +33 -1
  29. package/dist/permissions.d.ts.map +1 -1
  30. package/dist/permissions.js +6 -0
  31. package/dist/png.d.ts +38 -0
  32. package/dist/png.d.ts.map +1 -1
  33. package/dist/png.js +167 -0
  34. package/dist/run.d.ts +12 -4
  35. package/dist/run.d.ts.map +1 -1
  36. package/package.json +5 -1
  37. package/templates/android/README.md +5 -1
  38. package/templates/android/app/src/main/AndroidManifest.xml +16 -0
  39. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +16 -0
  40. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareModule.kt +274 -0
  41. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +57 -0
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +95 -0
  43. package/templates/android/app/src/main/res/mipmap/ic_launcher_round.xml +6 -0
  44. package/templates/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml +6 -0
  45. package/templates/android/app/src/main/res/xml/share_paths.xml +8 -0
  46. package/templates/ios/App/AngularLynxWebGL.h +7 -0
  47. package/templates/ios/App/AngularLynxWebGL.m +27 -0
  48. package/templates/ios/App/AngularLynxWebGLContext.m +139 -0
  49. package/templates/ios/App/LynxViewController.swift +2 -0
  50. package/templates/ios/App/ShareModule.swift +215 -0
@@ -4,6 +4,7 @@
4
4
  #import <EGL/eglext.h>
5
5
  #import <EGL/eglext_angle.h>
6
6
  #import <GLES3/gl3.h>
7
+ #import <ImageIO/ImageIO.h>
7
8
  #import <QuartzCore/QuartzCore.h>
8
9
 
9
10
  #import "AngularLynxWebGLOps.h"
@@ -432,6 +433,10 @@ static NSUInteger componentsOf(GLenum format) {
432
433
  }
433
434
  }
434
435
 
436
+ - (void)viewDidLayOut:(AngularLynxCanvasView *)view {
437
+ if (view == _view && _framePending) [self present];
438
+ }
439
+
435
440
  /// Shows the finished frame: copies the default framebuffer (resolving it
436
441
  /// when it's multisampled) into the view's layer, scaled to its size, and
437
442
  /// presents it. Without a laid-out view, the frame waits for one.
@@ -524,6 +529,140 @@ static NSUInteger componentsOf(GLenum format) {
524
529
  if (resolved) glBindFramebuffer(GL_READ_FRAMEBUFFER, _readFramebuffer);
525
530
  }
526
531
 
532
+ #pragma mark - Image files
533
+
534
+ /// The drawing buffer as an image file, for the runtime's canvas.toBlob() and
535
+ /// toDataURL(): `{ base64, type }`, or `{ error }`.
536
+ ///
537
+ /// It reads what the drawing buffer holds now, as a browser does: what the
538
+ /// app has drawn since the last frame was shown, or, once a frame has been
539
+ /// shown without preserveDrawingBuffer, the cleared buffer. The pixels are
540
+ /// encoded here rather than sent to the runtime, which would have to carry
541
+ /// 11 MB of RGBA for a 2048 by 1365 photo across the bridge as numbers, and
542
+ /// encode it in JavaScript on PrimJS, which has no JIT. The file crosses as
543
+ /// base64: the bridge can't return bytes (see webgl-bridge.ts).
544
+ - (NSDictionary *)encodeImageOfType:(NSString *)type
545
+ quality:(double)quality
546
+ premultiplied:(BOOL)premultiplied {
547
+ if (_context == EGL_NO_CONTEXT) return @{@"error" : @"The WebGL context is gone"};
548
+ [self makeCurrent];
549
+ size_t width = (size_t)_width;
550
+ size_t height = (size_t)_height;
551
+ size_t stride = width * 4;
552
+ NSMutableData *pixels = [NSMutableData dataWithLength:stride * height];
553
+ if (!pixels) return @{@"error" : @"Could not allocate the canvas's pixels"};
554
+
555
+ // A plain read of the whole default framebuffer, whatever the app has
556
+ // bound and set: its pixel pack buffer and pack parameters would move or
557
+ // redirect the read. The app's state is put back after.
558
+ GLint packBuffer = 0, alignment = 4, rowLength = 0, skipPixels = 0, skipRows = 0;
559
+ glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &packBuffer);
560
+ glGetIntegerv(GL_PACK_ALIGNMENT, &alignment);
561
+ glGetIntegerv(GL_PACK_ROW_LENGTH, &rowLength);
562
+ glGetIntegerv(GL_PACK_SKIP_PIXELS, &skipPixels);
563
+ glGetIntegerv(GL_PACK_SKIP_ROWS, &skipRows);
564
+ glPixelStorei(GL_PACK_ALIGNMENT, 4);
565
+ glPixelStorei(GL_PACK_ROW_LENGTH, 0);
566
+ glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
567
+ glPixelStorei(GL_PACK_SKIP_ROWS, 0);
568
+ GLuint source = _framebuffer;
569
+ if (_samples > 0) {
570
+ // GLES can't read a multisampled framebuffer: its samples are resolved
571
+ // first, as present and beginRead do. A blit is clipped by the scissor
572
+ // test, and skipped with rasterizer discard on, so both are off for it.
573
+ GLboolean scissor = glIsEnabled(GL_SCISSOR_TEST);
574
+ GLboolean discard = glIsEnabled(GL_RASTERIZER_DISCARD);
575
+ glDisable(GL_SCISSOR_TEST);
576
+ glDisable(GL_RASTERIZER_DISCARD);
577
+ glBindFramebuffer(GL_READ_FRAMEBUFFER, _framebuffer);
578
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _resolveFramebuffer);
579
+ glBlitFramebuffer(0, 0, _width, _height, 0, 0, _width, _height, GL_COLOR_BUFFER_BIT,
580
+ GL_NEAREST);
581
+ if (scissor) glEnable(GL_SCISSOR_TEST);
582
+ if (discard) glEnable(GL_RASTERIZER_DISCARD);
583
+ source = _resolveFramebuffer;
584
+ }
585
+ glBindFramebuffer(GL_READ_FRAMEBUFFER, source);
586
+ glReadBuffer(GL_COLOR_ATTACHMENT0);
587
+ // Read into a pixel pack buffer and mapped, rather than straight into
588
+ // memory: ANGLE on Metal reads a 2048 by 1365 canvas into memory in
589
+ // about 145 ms on the Simulator, and into a buffer, mapped, in about 5.
590
+ GLuint pack = 0;
591
+ glGenBuffers(1, &pack);
592
+ glBindBuffer(GL_PIXEL_PACK_BUFFER, pack);
593
+ glBufferData(GL_PIXEL_PACK_BUFFER, (GLsizeiptr)(stride * height), NULL, GL_STREAM_READ);
594
+ glReadPixels(0, 0, _width, _height, GL_RGBA, GL_UNSIGNED_BYTE, 0);
595
+ const uint8_t *read =
596
+ glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, (GLsizeiptr)(stride * height), GL_MAP_READ_BIT);
597
+ uint8_t *bytes = pixels.mutableBytes;
598
+ if (read) {
599
+ // GL's first row is the bottom of the image; an image file's is the
600
+ // top. So the rows are copied in the other order.
601
+ for (size_t y = 0; y < height; y++) {
602
+ memcpy(bytes + y * stride, read + (height - 1 - y) * stride, stride);
603
+ }
604
+ glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
605
+ }
606
+ glDeleteBuffers(1, &pack);
607
+ glBindBuffer(GL_PIXEL_PACK_BUFFER, (GLuint)packBuffer);
608
+ glPixelStorei(GL_PACK_ALIGNMENT, alignment);
609
+ glPixelStorei(GL_PACK_ROW_LENGTH, rowLength);
610
+ glPixelStorei(GL_PACK_SKIP_PIXELS, skipPixels);
611
+ glPixelStorei(GL_PACK_SKIP_ROWS, skipRows);
612
+ [self restoreBindings];
613
+ if (!read) return @{@"error" : @"Could not read the canvas's pixels"};
614
+
615
+ BOOL jpeg = [type isEqualToString:@"image/jpeg"];
616
+ CGBitmapInfo alphaInfo;
617
+ if (!_alpha) {
618
+ alphaInfo = (CGBitmapInfo)kCGImageAlphaNoneSkipLast;
619
+ } else if (jpeg) {
620
+ // A JPEG has no transparency. Browsers draw a canvas's transparent
621
+ // pixels over black for one, which premultiplied colors already are:
622
+ // straight ones are multiplied first.
623
+ if (!premultiplied) {
624
+ for (size_t i = 0; i < stride * height; i += 4) {
625
+ uint8_t alpha = bytes[i + 3];
626
+ if (alpha == 255) continue;
627
+ bytes[i] = (uint8_t)((bytes[i] * alpha + 127) / 255);
628
+ bytes[i + 1] = (uint8_t)((bytes[i + 1] * alpha + 127) / 255);
629
+ bytes[i + 2] = (uint8_t)((bytes[i + 2] * alpha + 127) / 255);
630
+ }
631
+ }
632
+ alphaInfo = (CGBitmapInfo)kCGImageAlphaNoneSkipLast;
633
+ } else {
634
+ // The drawing buffer's colors are premultiplied by alpha unless the app
635
+ // asked for premultipliedAlpha: false. ImageIO writes the PNG's straight
636
+ // colors from either.
637
+ alphaInfo = (CGBitmapInfo)(premultiplied ? kCGImageAlphaPremultipliedLast : kCGImageAlphaLast);
638
+ }
639
+ CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)pixels);
640
+ CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
641
+ CGImageRef image =
642
+ CGImageCreate(width, height, 8, 32, stride, colorSpace,
643
+ alphaInfo | kCGBitmapByteOrder32Big, provider, NULL, false,
644
+ kCGRenderingIntentDefault);
645
+ CGColorSpaceRelease(colorSpace);
646
+ CGDataProviderRelease(provider);
647
+ if (!image) return @{@"error" : @"Could not make an image of the canvas's pixels"};
648
+ NSMutableData *file = [NSMutableData data];
649
+ NSString *fileType = jpeg ? @"public.jpeg" : @"public.png";
650
+ CGImageDestinationRef destination = CGImageDestinationCreateWithData(
651
+ (__bridge CFMutableDataRef)file, (__bridge CFStringRef)fileType, 1, NULL);
652
+ BOOL written = NO;
653
+ if (destination) {
654
+ NSDictionary *properties =
655
+ jpeg ? @{(__bridge NSString *)kCGImageDestinationLossyCompressionQuality : @(quality)}
656
+ : @{};
657
+ CGImageDestinationAddImage(destination, image, (__bridge CFDictionaryRef)properties);
658
+ written = CGImageDestinationFinalize(destination);
659
+ CFRelease(destination);
660
+ }
661
+ CGImageRelease(image);
662
+ if (!written) return @{@"error" : @"Could not encode the canvas's pixels"};
663
+ return @{@"base64" : [file base64EncodedStringWithOptions:0], @"type" : type};
664
+ }
665
+
527
666
  #pragma mark - Objects
528
667
 
529
668
  - (GLuint)nameOf:(GLuint)objectId {
@@ -30,6 +30,8 @@ final class LynxViewController: UIViewController {
30
30
  config.register(LinkingModule.self)
31
31
  // The photo picker behind LynxImagePicker (ImagePickerModule).
32
32
  config.register(ImagePickerModule.self)
33
+ // The share sheet behind LynxShare (ShareModule).
34
+ config.register(ShareModule.self)
33
35
  // <canvas>'s WebGL (AngularLynxWebGL.h), which the runtime calls from
34
36
  // the main thread. It's Objective-C, which Swift reaches without a
35
37
  // bridging header by name.
@@ -0,0 +1,215 @@
1
+ import Lynx
2
+ import UIKit
3
+
4
+ /// The native module behind the runtime's `LynxShare`, which calls it as
5
+ /// `NativeModules.AngularLynxShare` (from the background thread, where
6
+ /// NativeModules lives).
7
+ ///
8
+ /// Lynx has no `navigator.share()`. The system share sheet,
9
+ /// UIActivityViewController, stands in for it. Each file is written to a
10
+ /// temporary file of its own name first, rather than handed over as data or
11
+ /// a UIImage, so "Save to Files" and AirDrop get the name the app gave it,
12
+ /// and the sheet knows its type from the extension: a JPEG gets "Save Image".
13
+ ///
14
+ /// The files come as base64, since the runtime's relay from the main thread
15
+ /// and the module's arguments carry only what JSON can.
16
+ final class ShareModule: NSObject, LynxModule {
17
+ static var name: String { "AngularLynxShare" }
18
+
19
+ static var methodLookup: [String: String] {
20
+ ["share": NSStringFromSelector(#selector(share(_:callback:)))]
21
+ }
22
+
23
+ /// Whether a share sheet is open. Only touched on the main thread.
24
+ private var open = false
25
+
26
+ override init() {
27
+ super.init()
28
+ }
29
+
30
+ // Swift can't import an optional initializer as optional, so Lynx's
31
+ // initWithParam: is required here. Registered without a param, the module
32
+ // ignores it.
33
+ init(param: Any) {
34
+ super.init()
35
+ }
36
+
37
+ /// Opens the share sheet with `request`'s `files` (`{ base64, name, type }`),
38
+ /// `title`, `text` and `url`, and calls back once with `{ shared }`, or with
39
+ /// `{ error: "failed", message }`.
40
+ @objc func share(_ request: [String: Any], callback: @escaping LynxCallbackBlock) {
41
+ // Decoding and writing the files takes a moment for a photo: on the
42
+ // module's own thread, before the sheet, which is UI, opens on the main
43
+ // thread.
44
+ let directory = FileManager.default.temporaryDirectory
45
+ .appendingPathComponent("AngularLynxShare", isDirectory: true)
46
+ .appendingPathComponent(UUID().uuidString, isDirectory: true)
47
+ var items: [Any] = []
48
+ do {
49
+ let files = request["files"] as? [[String: Any]] ?? []
50
+ if !files.isEmpty {
51
+ try FileManager.default.createDirectory(
52
+ at: directory, withIntermediateDirectories: true)
53
+ }
54
+ var used = Set<String>()
55
+ for file in files {
56
+ guard let base64 = file["base64"] as? String,
57
+ let data = Data(base64Encoded: base64)
58
+ else {
59
+ throw ShareFailure("A file's bytes couldn't be read.")
60
+ }
61
+ let name = Self.uniqueName(Self.safeName(file["name"] as? String), in: &used)
62
+ let url = directory.appendingPathComponent(name, isDirectory: false)
63
+ try data.write(to: url)
64
+ items.append(url)
65
+ }
66
+ } catch {
67
+ try? FileManager.default.removeItem(at: directory)
68
+ callback(["error": "failed", "message": "The files couldn't be written to share: \(error.localizedDescription)"])
69
+ return
70
+ }
71
+ let title = request["title"] as? String
72
+ let text = request["text"] as? String
73
+ let link = (request["url"] as? String).flatMap(URL.init(string:))
74
+ // The title goes with the text, or the link, as its subject (Mail's
75
+ // subject line). Shared on its own, as the Web Share API allows, it's
76
+ // the text.
77
+ if let text {
78
+ items.append(TextSource(text, subject: title))
79
+ } else if link == nil, let title, items.isEmpty {
80
+ items.append(TextSource(title, subject: nil))
81
+ }
82
+ if let link {
83
+ items.append(text == nil ? TextSource(link, subject: title) : link)
84
+ }
85
+ DispatchQueue.main.async {
86
+ self.present(items, directory: directory, callback: callback)
87
+ }
88
+ }
89
+
90
+ private func present(
91
+ _ items: [Any], directory: URL, callback: @escaping LynxCallbackBlock
92
+ ) {
93
+ let cleanUp = { try? FileManager.default.removeItem(at: directory) }
94
+ guard !open else {
95
+ cleanUp()
96
+ callback(["error": "failed", "message": "A share sheet is already open."])
97
+ return
98
+ }
99
+ guard let presenter = topViewController() else {
100
+ cleanUp()
101
+ callback(["error": "failed", "message": "There's no screen to open the share sheet over."])
102
+ return
103
+ }
104
+ let controller = UIActivityViewController(activityItems: items, applicationActivities: nil)
105
+ // "Save Image" adds to the photo library, which crashes an app whose
106
+ // Info.plist gives no reason for it. The apps `ng build --platform` makes
107
+ // have one; a project ejected before they did leaves the action out
108
+ // rather than crash.
109
+ if Bundle.main.object(forInfoDictionaryKey: "NSPhotoLibraryAddUsageDescription") == nil {
110
+ controller.excludedActivityTypes = [.saveToCameraRoll]
111
+ }
112
+ // On iPad the sheet is a popover, which needs somewhere to point:
113
+ // the middle of the screen, without an arrow, since the tap that opened
114
+ // it was in the LynxView, which UIKit can't see into.
115
+ if let popover = controller.popoverPresentationController, let view = presenter.view {
116
+ popover.sourceView = view
117
+ popover.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
118
+ popover.permittedArrowDirections = []
119
+ }
120
+ // The callback takes one answer, and UIKit may finish a sheet more than
121
+ // once: iOS 27 logs completing twice as the sheet closes.
122
+ var answered = false
123
+ controller.completionWithItemsHandler = { [weak self, weak controller] activity, completed, _, error in
124
+ if answered { return }
125
+ // From iOS 13, closing an action's own screen without finishing it,
126
+ // such as Save to Files' picker, calls this with the action, while the
127
+ // sheet stays open for another choice. The sheet itself closing calls
128
+ // it without one.
129
+ if !completed, error == nil, activity != nil, controller?.viewIfLoaded?.window != nil {
130
+ return
131
+ }
132
+ answered = true
133
+ self?.open = false
134
+ cleanUp()
135
+ if let error {
136
+ callback(["error": "failed", "message": error.localizedDescription])
137
+ } else {
138
+ callback(["shared": completed])
139
+ }
140
+ }
141
+ open = true
142
+ presenter.present(controller, animated: true)
143
+ }
144
+
145
+ /// A file name the file system takes: no folders, and something there.
146
+ private static func safeName(_ name: String?) -> String {
147
+ let base = (name ?? "")
148
+ .replacingOccurrences(of: "/", with: "_")
149
+ .replacingOccurrences(of: ":", with: "_")
150
+ .trimmingCharacters(in: .whitespacesAndNewlines)
151
+ return base.isEmpty || base == "." || base == ".." ? "file" : base
152
+ }
153
+
154
+ /// `photo.jpg`, then `photo 2.jpg`: two files of one name in one share
155
+ /// would otherwise overwrite each other.
156
+ private static func uniqueName(_ name: String, in used: inout Set<String>) -> String {
157
+ var candidate = name
158
+ var number = 2
159
+ let url = URL(fileURLWithPath: name)
160
+ let stem = url.deletingPathExtension().lastPathComponent
161
+ let ext = url.pathExtension
162
+ while used.contains(candidate.lowercased()) {
163
+ candidate = ext.isEmpty ? "\(stem) \(number)" : "\(stem) \(number).\(ext)"
164
+ number += 1
165
+ }
166
+ used.insert(candidate.lowercased())
167
+ return candidate
168
+ }
169
+
170
+ /// The view controller on top, which the share sheet opens over.
171
+ private func topViewController() -> UIViewController? {
172
+ let window = UIApplication.shared.connectedScenes
173
+ .compactMap { $0 as? UIWindowScene }
174
+ .flatMap(\.windows)
175
+ .first(where: \.isKeyWindow)
176
+ var top = window?.rootViewController
177
+ while let presented = top?.presentedViewController {
178
+ top = presented
179
+ }
180
+ return top
181
+ }
182
+ }
183
+
184
+ private struct ShareFailure: LocalizedError {
185
+ let errorDescription: String?
186
+ init(_ message: String) { errorDescription = message }
187
+ }
188
+
189
+ /// Text or a link with a subject: UIActivityViewController takes a subject,
190
+ /// which Mail uses for its subject line, only from an item source.
191
+ private final class TextSource: NSObject, UIActivityItemSource {
192
+ private let item: Any
193
+ private let subject: String?
194
+
195
+ init(_ item: Any, subject: String?) {
196
+ self.item = item
197
+ self.subject = subject
198
+ }
199
+
200
+ func activityViewControllerPlaceholderItem(_ controller: UIActivityViewController) -> Any {
201
+ item
202
+ }
203
+
204
+ func activityViewController(
205
+ _ controller: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?
206
+ ) -> Any? {
207
+ item
208
+ }
209
+
210
+ func activityViewController(
211
+ _ controller: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?
212
+ ) -> String {
213
+ subject ?? ""
214
+ }
215
+ }