@blotch/angular-lynx-native 22.2.20 → 22.2.22

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 (70) hide show
  1. package/README.md +8 -4
  2. package/dist/android/build.d.ts +6 -1
  3. package/dist/android/build.d.ts.map +1 -1
  4. package/dist/android/build.js +14 -3
  5. package/dist/android/icon.d.ts +29 -0
  6. package/dist/android/icon.d.ts.map +1 -0
  7. package/dist/android/icon.js +142 -0
  8. package/dist/android/project.d.ts +2 -1
  9. package/dist/android/project.d.ts.map +1 -1
  10. package/dist/android/project.js +5 -2
  11. package/dist/android/run.d.ts +10 -1
  12. package/dist/android/run.d.ts.map +1 -1
  13. package/dist/android/run.js +46 -1
  14. package/dist/dev-build.d.ts +16 -0
  15. package/dist/dev-build.d.ts.map +1 -0
  16. package/dist/dev-build.js +44 -0
  17. package/dist/generate.d.ts +26 -7
  18. package/dist/generate.d.ts.map +1 -1
  19. package/dist/generate.js +25 -10
  20. package/dist/index.d.ts +13 -4
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +77 -13
  23. package/dist/ios/build.d.ts +68 -12
  24. package/dist/ios/build.d.ts.map +1 -1
  25. package/dist/ios/build.js +210 -45
  26. package/dist/ios/iphone.d.ts +99 -0
  27. package/dist/ios/iphone.d.ts.map +1 -0
  28. package/dist/ios/iphone.js +207 -0
  29. package/dist/ios/project.d.ts +10 -1
  30. package/dist/ios/project.d.ts.map +1 -1
  31. package/dist/ios/project.js +27 -4
  32. package/dist/ios/run.d.ts +18 -3
  33. package/dist/ios/run.d.ts.map +1 -1
  34. package/dist/ios/run.js +34 -5
  35. package/dist/options.d.ts +49 -3
  36. package/dist/options.d.ts.map +1 -1
  37. package/dist/options.js +33 -1
  38. package/dist/permissions.d.ts.map +1 -1
  39. package/dist/permissions.js +6 -0
  40. package/dist/png.d.ts +38 -0
  41. package/dist/png.d.ts.map +1 -1
  42. package/dist/png.js +167 -0
  43. package/dist/run.d.ts +54 -6
  44. package/dist/run.d.ts.map +1 -1
  45. package/dist/run.js +16 -1
  46. package/package.json +5 -1
  47. package/templates/android/README.md +5 -1
  48. package/templates/android/app/src/debug/java/dev/angularlynx/shell/DevServer.kt +159 -0
  49. package/templates/android/app/src/debug/java/dev/angularlynx/shell/DevServerModules.kt +163 -0
  50. package/templates/android/app/src/debug/res/xml/network_security_config.xml +13 -0
  51. package/templates/android/app/src/main/AndroidManifest.xml +16 -0
  52. package/templates/android/app/src/main/java/dev/angularlynx/shell/AssetsModule.kt +22 -0
  53. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +24 -1
  54. package/templates/android/app/src/main/java/dev/angularlynx/shell/ResourceFetchers.kt +12 -6
  55. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareModule.kt +274 -0
  56. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +57 -0
  57. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +95 -0
  58. package/templates/android/app/src/main/res/mipmap/ic_launcher_round.xml +6 -0
  59. package/templates/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml +6 -0
  60. package/templates/android/app/src/main/res/xml/share_paths.xml +8 -0
  61. package/templates/android/app/src/release/java/dev/angularlynx/shell/DevServer.kt +24 -0
  62. package/templates/ios/App/AngularLynxWebGL.h +7 -0
  63. package/templates/ios/App/AngularLynxWebGL.m +27 -0
  64. package/templates/ios/App/AngularLynxWebGLContext.m +139 -0
  65. package/templates/ios/App/AssetsModule.swift +21 -3
  66. package/templates/ios/App/BundleResourceFetcher.swift +46 -2
  67. package/templates/ios/App/DevServer.swift +190 -0
  68. package/templates/ios/App/DevServerModules.swift +223 -0
  69. package/templates/ios/App/LynxViewController.swift +11 -1
  70. 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 {
@@ -31,9 +31,7 @@ final class AssetsModule: NSObject, LynxModule {
31
31
  /// in the runtime's webgl-bridge.ts: Lynx's bridge carries no binary), or
32
32
  /// nil when the app doesn't bundle it.
33
33
  @objc func read(_ url: String) -> [NSNumber]? {
34
- guard let file = BundleResourceFetcher.shared.localFile(for: url),
35
- let data = try? Data(contentsOf: file)
36
- else { return nil }
34
+ guard let data = Self.contents(of: url) else { return nil }
37
35
  var words = [NSNumber]()
38
36
  words.reserveCapacity(data.count / 4 + 2)
39
37
  data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
@@ -50,4 +48,24 @@ final class AssetsModule: NSObject, LynxModule {
50
48
  words.append(NSNumber(value: data.count))
51
49
  return words
52
50
  }
51
+
52
+ /// The file in LynxBundle, or in the development build, on the dev server,
53
+ /// which has the current copy. The call is synchronous, so that request is
54
+ /// too; URLSession answers on its own queue, so waiting here can't block it.
55
+ private static func contents(of url: String) -> Data? {
56
+ if let remote = DevServer.shared.remoteURL(for: url) {
57
+ var result: Data?
58
+ let done = DispatchSemaphore(value: 0)
59
+ URLSession.shared.dataTask(
60
+ with: URLRequest(url: remote, cachePolicy: .reloadIgnoringLocalCacheData)
61
+ ) { data, response, _ in
62
+ if (response as? HTTPURLResponse)?.statusCode == 200 { result = data }
63
+ done.signal()
64
+ }.resume()
65
+ done.wait()
66
+ return result
67
+ }
68
+ guard let file = BundleResourceFetcher.shared.localFile(for: url) else { return nil }
69
+ return try? Data(contentsOf: file)
70
+ }
53
71
  }
@@ -3,7 +3,9 @@ import Lynx
3
3
 
4
4
  /// Serves the app's Lynx bundles and assets from the `LynxBundle` folder that
5
5
  /// the generator copies `dist/` into, and falls back to the network for
6
- /// anything else (remote images, a dev server).
6
+ /// anything else (remote images, an API). The development build that
7
+ /// `ng serve --platform ios` runs has no LynxBundle: it loads everything the
8
+ /// bundle names from the dev server instead (see DevServer).
7
9
  ///
8
10
  /// One class covers every loader Lynx asks for: the global template provider
9
11
  /// (`LynxTemplateProvider`), and the per-view template, generic and media
@@ -54,6 +56,24 @@ final class BundleResourceFetcher: NSObject, LynxTemplateProvider,
54
56
  }
55
57
 
56
58
  private func load(_ url: String, completion: @escaping (Data?, Error?) -> Void) {
59
+ if let remote = DevServer.shared.remoteURL(for: url) {
60
+ // Never from URLSession's cache: the server has a new build after
61
+ // every edit, under the same URL.
62
+ let request = URLRequest(url: remote, cachePolicy: .reloadIgnoringLocalCacheData)
63
+ URLSession.shared.dataTask(with: request) { data, response, error in
64
+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0
65
+ let failure =
66
+ error
67
+ ?? (status >= 400
68
+ ? NSError(
69
+ domain: "AngularLynx", code: status,
70
+ userInfo: [NSLocalizedDescriptionKey: "The dev server answered \(status) for \(remote)."])
71
+ : nil)
72
+ DevServer.shared.loaded(url, error: failure)
73
+ completion(failure == nil ? data : nil, failure)
74
+ }.resume()
75
+ return
76
+ }
57
77
  if let file = localFile(for: url) {
58
78
  do {
59
79
  completion(try Data(contentsOf: file), nil)
@@ -114,6 +134,29 @@ final class BundleResourceFetcher: NSObject, LynxTemplateProvider,
114
134
  _ request: LynxResourceRequest,
115
135
  onComplete callback: @escaping LynxGenericResourcePathCompletionBlock
116
136
  ) -> () -> Void {
137
+ if let remote = DevServer.shared.remoteURL(for: request.url) {
138
+ // A file the bundle loads by path is on the dev server, so it's
139
+ // downloaded to a file first.
140
+ let task = URLSession.shared.downloadTask(
141
+ with: URLRequest(url: remote, cachePolicy: .reloadIgnoringLocalCacheData)
142
+ ) { location, _, error in
143
+ guard let location else {
144
+ callback(nil, error)
145
+ return
146
+ }
147
+ let file = FileManager.default.temporaryDirectory
148
+ .appendingPathComponent(UUID().uuidString)
149
+ .appendingPathExtension(remote.pathExtension)
150
+ do {
151
+ try FileManager.default.moveItem(at: location, to: file)
152
+ callback(file.path, nil)
153
+ } catch {
154
+ callback(nil, error)
155
+ }
156
+ }
157
+ task.resume()
158
+ return { task.cancel() }
159
+ }
117
160
  if let file = localFile(for: request.url) {
118
161
  callback(file.path, nil)
119
162
  } else {
@@ -131,6 +174,7 @@ final class BundleResourceFetcher: NSObject, LynxTemplateProvider,
131
174
  /// Images load through LynxService's SDWebImage service, which reads
132
175
  /// `file://` URLs itself, so local images only need their URL rewritten.
133
176
  func shouldRedirectUrl(_ request: LynxResourceRequest) -> String {
134
- localFile(for: request.url)?.absoluteString ?? request.url
177
+ DevServer.shared.remoteURL(for: request.url)?.absoluteString
178
+ ?? localFile(for: request.url)?.absoluteString ?? request.url
135
179
  }
136
180
  }
@@ -0,0 +1,190 @@
1
+ import Foundation
2
+ import Lynx
3
+ import UIKit
4
+
5
+ /// `ng serve --platform ios`: the development app loads its bundle from the
6
+ /// dev server rather than from the copy in LynxBundle (which it doesn't
7
+ /// have), and reloads it on every edit, as Lynx Explorer does.
8
+ ///
9
+ /// Only the Debug configuration, which `ng serve --platform ios` builds,
10
+ /// compiles any of it in. A Release build (`ng build --platform ios`, the App
11
+ /// Store's) gets the stubs at the bottom, so nothing can point it at another
12
+ /// server: its bundle is always the one inside it.
13
+ ///
14
+ /// The builder opens the app with the bundle's URL as a launch argument,
15
+ /// `-AngularLynxDevServer <url>`, which iOS puts in UserDefaults' argument
16
+ /// domain. It's kept, so opening the app from the home screen later loads
17
+ /// from the same server.
18
+ final class DevServer {
19
+ static let shared = DevServer()
20
+
21
+ #if DEBUG
22
+ private static let argument = "AngularLynxDevServer"
23
+ private static let lastServerKey = "AngularLynxDevServerLast"
24
+
25
+ /// The bundle on the dev server, e.g. `http://192.168.1.20:3000/main.lynx.bundle`.
26
+ private let bundle: URL?
27
+
28
+ /// The folder it's in, which every relative URL the bundle asks for
29
+ /// resolves against: lazy bundles, images, files it fetches.
30
+ private let base: URL?
31
+
32
+ /// Reloads the LynxView, which LynxViewController sets.
33
+ private var reload: (() -> Void)?
34
+
35
+ /// Tells the person the dev server can't be reached, over the page.
36
+ private var status: UILabel?
37
+ private var statusScreen: UIView?
38
+ private var retry: DispatchWorkItem?
39
+
40
+ private init() {
41
+ let defaults = UserDefaults.standard
42
+ let launched = defaults.volatileDomain(forName: UserDefaults.argumentDomain)[
43
+ Self.argument] as? String
44
+ if let launched {
45
+ defaults.set(launched, forKey: Self.lastServerKey)
46
+ }
47
+ bundle = (launched ?? defaults.string(forKey: Self.lastServerKey)).flatMap(URL.init(string:))
48
+ base = bundle?.deletingLastPathComponent()
49
+ }
50
+ #endif
51
+
52
+ /// The URL the LynxView loads: the dev server's bundle in a development
53
+ /// build, else the one inside the app.
54
+ var templateURL: String {
55
+ #if DEBUG
56
+ return bundle?.absoluteString ?? "main.lynx.bundle"
57
+ #else
58
+ return "main.lynx.bundle"
59
+ #endif
60
+ }
61
+
62
+ /// Where a URL the bundle asks for is on the dev server, or nil when the
63
+ /// app isn't loading from one, or the URL is somewhere else (an API, a
64
+ /// CDN, a data: URL, a file the app wrote).
65
+ ///
66
+ /// rspeedy builds a development bundle with the server's address in its
67
+ /// asset URLs, so most arrive absolute already; anything relative is
68
+ /// relative to the server, as it would be to LynxBundle in a release build.
69
+ func remoteURL(for url: String) -> URL? {
70
+ #if DEBUG
71
+ guard let base else { return nil }
72
+ if url.hasPrefix(base.absoluteString) {
73
+ return URL(string: url)
74
+ }
75
+ if url.hasPrefix("http://") || url.hasPrefix("https://") || url.hasPrefix("data:")
76
+ || url.hasPrefix("file://")
77
+ {
78
+ return nil
79
+ }
80
+ var path = url
81
+ for prefix in ["asset:///", "asset://"] where path.hasPrefix(prefix) {
82
+ path = String(path.dropFirst(prefix.count))
83
+ break
84
+ }
85
+ while path.hasPrefix("./") { path.removeFirst(2) }
86
+ while path.hasPrefix("/") { path.removeFirst() }
87
+ return URL(string: path, relativeTo: base)?.absoluteURL
88
+ #else
89
+ return nil
90
+ #endif
91
+ }
92
+
93
+ /// Adds the dev server's modules to the LynxView's config: the WebSocket
94
+ /// that rspeedy's live reload listens on, and the reload it asks for.
95
+ func register(in config: LynxConfig) {
96
+ #if DEBUG
97
+ guard bundle != nil else { return }
98
+ config.register(DevWebSocketModule.self)
99
+ config.register(DevReloadModule.self)
100
+ #endif
101
+ }
102
+
103
+ /// Gives the dev server the view to show its status over and the
104
+ /// LynxView's reload.
105
+ func attach(to view: UIView, reload: @escaping () -> Void) {
106
+ #if DEBUG
107
+ self.reload = reload
108
+ // A screen over the page, with the message in the middle.
109
+ let screen = UIView()
110
+ screen.backgroundColor = .systemBackground
111
+ screen.isHidden = true
112
+ screen.translatesAutoresizingMaskIntoConstraints = false
113
+ let label = UILabel()
114
+ label.numberOfLines = 0
115
+ label.textAlignment = .center
116
+ label.font = .preferredFont(forTextStyle: .body)
117
+ label.textColor = .label
118
+ label.translatesAutoresizingMaskIntoConstraints = false
119
+ screen.addSubview(label)
120
+ view.addSubview(screen)
121
+ NSLayoutConstraint.activate([
122
+ screen.leadingAnchor.constraint(equalTo: view.leadingAnchor),
123
+ screen.trailingAnchor.constraint(equalTo: view.trailingAnchor),
124
+ screen.topAnchor.constraint(equalTo: view.topAnchor),
125
+ screen.bottomAnchor.constraint(equalTo: view.bottomAnchor),
126
+ label.leadingAnchor.constraint(equalTo: screen.layoutMarginsGuide.leadingAnchor, constant: 8),
127
+ label.trailingAnchor.constraint(equalTo: screen.layoutMarginsGuide.trailingAnchor, constant: -8),
128
+ label.centerYAnchor.constraint(equalTo: screen.centerYAnchor),
129
+ ])
130
+ status = label
131
+ statusScreen = screen
132
+ if bundle == nil {
133
+ show(
134
+ "This is the development build of the app, which loads the app from `ng serve`.\n\nRun `ng serve --platform ios` to open it."
135
+ )
136
+ }
137
+ #endif
138
+ }
139
+
140
+ /// Reloads the bundle from the dev server, from any thread.
141
+ func reloadBundle() {
142
+ #if DEBUG
143
+ DispatchQueue.main.async { self.reload?() }
144
+ #endif
145
+ }
146
+
147
+ /// Called with the outcome of each load. When the bundle itself didn't
148
+ /// load (the server is stopped, or on another network), the app says so
149
+ /// rather than show nothing, and tries again every two seconds.
150
+ func loaded(_ url: String, error: Error?) {
151
+ #if DEBUG
152
+ guard let bundle, url == bundle.absoluteString else { return }
153
+ DispatchQueue.main.async {
154
+ self.retry?.cancel()
155
+ guard let error else {
156
+ self.statusScreen?.isHidden = true
157
+ return
158
+ }
159
+ self.show(
160
+ "Can't reach the dev server at \(bundle.host ?? "")\(bundle.port.map { ":\($0)" } ?? "").\n\n\(error.localizedDescription)\n\nIs `ng serve --platform ios` running, and is this device on the same network?\(Self.localNetworkHint) Trying again…"
161
+ )
162
+ let retry = DispatchWorkItem { [weak self] in self?.reload?() }
163
+ self.retry = retry
164
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: retry)
165
+ }
166
+ #endif
167
+ }
168
+
169
+ #if DEBUG
170
+ /// On an iPhone, iOS blocks the dev server until the person allows the
171
+ /// app on the local network, which it asks about the first time. Tapping
172
+ /// Don't Allow leaves the app failing like this, with nothing to say why,
173
+ /// so it says where to turn it back on. The simulator never asks.
174
+ private static var localNetworkHint: String {
175
+ #if targetEnvironment(simulator)
176
+ return ""
177
+ #else
178
+ return
179
+ " If you tapped Don't Allow when iOS asked to find devices on your local network, turn on this app in Settings > Privacy & Security > Local Network."
180
+ #endif
181
+ }
182
+
183
+ private func show(_ message: String) {
184
+ guard let status, let statusScreen else { return }
185
+ status.text = message
186
+ statusScreen.isHidden = false
187
+ statusScreen.superview?.bringSubviewToFront(statusScreen)
188
+ }
189
+ #endif
190
+ }
@@ -0,0 +1,223 @@
1
+ // The two native modules rspeedy's live reload needs, in the development
2
+ // build only (see DevServer.swift). Lynx Explorer has them from Lynx DevTool,
3
+ // which the shell doesn't link: the dev server's client, which rspeedy puts
4
+ // in every development bundle, talks to the server over
5
+ // `NativeModules.LynxWebSocketModule` (through @lynx-js/websocket) and reloads
6
+ // the page with `NativeModules.LynxDevToolSetModule.invokeCdp`, a DevTool
7
+ // protocol `Page.reload`. These answer to the same names and calls, so the
8
+ // bundle runs here as it does in Lynx Explorer.
9
+ #if DEBUG
10
+ import Foundation
11
+ import Lynx
12
+
13
+ /// `NativeModules.LynxWebSocketModule`, as Lynx DevTool's
14
+ /// (LynxWebSocketModule.mm): `connect`, `send`, `ping` and `close`, each
15
+ /// with the socket's ID, and the `websocketOpen`, `websocketMessage`,
16
+ /// `websocketClosed` and `websocketFailed` global events @lynx-js/websocket
17
+ /// listens for.
18
+ final class DevWebSocketModule: NSObject, LynxContextModule, URLSessionWebSocketDelegate {
19
+ static var name: String { "LynxWebSocketModule" }
20
+
21
+ static var methodLookup: [String: String] {
22
+ [
23
+ "connect": NSStringFromSelector(#selector(connect(_:protocols:options:socketID:))),
24
+ "send": NSStringFromSelector(#selector(send(_:socketID:))),
25
+ "ping": NSStringFromSelector(#selector(ping(_:))),
26
+ "close": NSStringFromSelector(#selector(close(_:reason:socketID:))),
27
+ ]
28
+ }
29
+
30
+ private weak var context: LynxContext?
31
+ private var sockets: [Int: URLSessionWebSocketTask] = [:]
32
+ private let lock = NSLock()
33
+ private lazy var session = URLSession(
34
+ configuration: .default, delegate: self, delegateQueue: nil)
35
+
36
+ override init() {
37
+ super.init()
38
+ }
39
+
40
+ // Swift can't import an optional initializer as optional, so Lynx's
41
+ // initWithParam: and initWithLynxContext:WithParam: are required here.
42
+ init(param: Any) {
43
+ super.init()
44
+ }
45
+
46
+ init(lynxContext context: LynxContext) {
47
+ self.context = context
48
+ super.init()
49
+ }
50
+
51
+ init(lynxContext context: LynxContext, withParam param: Any) {
52
+ self.context = context
53
+ super.init()
54
+ }
55
+
56
+ func destroy() {
57
+ lock.lock()
58
+ let open = Array(sockets.values)
59
+ sockets.removeAll()
60
+ lock.unlock()
61
+ open.forEach { $0.cancel(with: .goingAway, reason: nil) }
62
+ session.invalidateAndCancel()
63
+ }
64
+
65
+ @objc func connect(
66
+ _ url: String, protocols: [String]?, options: [String: Any]?, socketID: Double
67
+ ) {
68
+ let id = Int(socketID)
69
+ // The address the bundle was built with may not be the one this
70
+ // device reaches the server at.
71
+ let address = DevServer.shared.remoteURL(for: url.replacingOccurrences(
72
+ of: "^ws", with: "http", options: .regularExpression))
73
+ .map { $0.absoluteString.replacingOccurrences(
74
+ of: "^http", with: "ws", options: .regularExpression) } ?? url
75
+ guard let target = URL(string: address) else {
76
+ send("websocketFailed", ["id": id, "message": "\(url) is not a valid URL."])
77
+ return
78
+ }
79
+ // With an empty list, URLSession still sends an empty
80
+ // Sec-WebSocket-Protocol header, which the dev server rejects.
81
+ let names = (protocols ?? []).filter { !$0.isEmpty }
82
+ let task =
83
+ names.isEmpty
84
+ ? session.webSocketTask(with: target)
85
+ : session.webSocketTask(with: target, protocols: names)
86
+ task.taskDescription = String(id)
87
+ lock.lock()
88
+ sockets[id] = task
89
+ lock.unlock()
90
+ task.resume()
91
+ receive(task, id: id)
92
+ }
93
+
94
+ @objc func send(_ message: String, socketID: Double) {
95
+ socket(socketID)?.send(.string(message)) { [weak self] error in
96
+ if let error {
97
+ self?.send("websocketFailed", ["id": Int(socketID), "message": error.localizedDescription])
98
+ }
99
+ }
100
+ }
101
+
102
+ @objc func ping(_ socketID: Double) {
103
+ socket(socketID)?.sendPing { _ in }
104
+ }
105
+
106
+ @objc func close(_ code: Double, reason: String, socketID: Double) {
107
+ let id = Int(socketID)
108
+ lock.lock()
109
+ let task = sockets.removeValue(forKey: id)
110
+ lock.unlock()
111
+ task?.cancel(
112
+ with: URLSessionWebSocketTask.CloseCode(rawValue: Int(code)) ?? .normalClosure,
113
+ reason: reason.data(using: .utf8))
114
+ }
115
+
116
+ private func socket(_ socketID: Double) -> URLSessionWebSocketTask? {
117
+ lock.lock()
118
+ defer { lock.unlock() }
119
+ return sockets[Int(socketID)]
120
+ }
121
+
122
+ /// Reads one message, sends it on, and waits for the next, for as long as
123
+ /// the socket is open.
124
+ private func receive(_ task: URLSessionWebSocketTask, id: Int) {
125
+ task.receive { [weak self] result in
126
+ guard let self else { return }
127
+ switch result {
128
+ case .success(.string(let text)):
129
+ self.send("websocketMessage", ["id": id, "type": "text", "data": text])
130
+ case .success(.data(let data)):
131
+ self.send(
132
+ "websocketMessage", ["id": id, "type": "binary", "data": data.base64EncodedString()])
133
+ case .success:
134
+ break
135
+ case .failure:
136
+ // The delegate reports why the socket ended.
137
+ return
138
+ }
139
+ self.receive(task, id: id)
140
+ }
141
+ }
142
+
143
+ private func send(_ event: String, _ params: [String: Any]) {
144
+ context?.sendGlobalEvent(event, withParams: [params])
145
+ }
146
+
147
+ func urlSession(
148
+ _ session: URLSession, webSocketTask: URLSessionWebSocketTask,
149
+ didOpenWithProtocol protocolName: String?
150
+ ) {
151
+ guard let id = webSocketTask.taskDescription.flatMap(Int.init) else { return }
152
+ send("websocketOpen", ["id": id, "protocol": protocolName ?? ""])
153
+ }
154
+
155
+ func urlSession(
156
+ _ session: URLSession, webSocketTask: URLSessionWebSocketTask,
157
+ didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?
158
+ ) {
159
+ guard let id = webSocketTask.taskDescription.flatMap(Int.init) else { return }
160
+ lock.lock()
161
+ sockets.removeValue(forKey: id)
162
+ lock.unlock()
163
+ send(
164
+ "websocketClosed",
165
+ [
166
+ "id": id, "code": closeCode.rawValue,
167
+ "reason": reason.flatMap { String(data: $0, encoding: .utf8) } ?? "",
168
+ ])
169
+ }
170
+
171
+ /// The connection failed or dropped (the server stopped): the dev
172
+ /// server's client then tries again, with a growing delay.
173
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
174
+ {
175
+ guard let error, let id = task.taskDescription.flatMap(Int.init) else { return }
176
+ lock.lock()
177
+ let known = sockets.removeValue(forKey: id) != nil
178
+ lock.unlock()
179
+ guard known else { return }
180
+ send("websocketFailed", ["id": id, "message": error.localizedDescription])
181
+ send("websocketClosed", ["id": id, "code": 1006, "reason": error.localizedDescription])
182
+ }
183
+ }
184
+
185
+ /// `NativeModules.LynxDevToolSetModule`, as far as rspeedy's live reload
186
+ /// uses Lynx DevTool's: `invokeCdp` with a `Page.reload`, which loads the
187
+ /// bundle from the dev server again, as Lynx DevTool's LynxPageReloadHelper
188
+ /// does. It answers any other DevTool method with an error.
189
+ final class DevReloadModule: NSObject, LynxModule {
190
+ static var name: String { "LynxDevToolSetModule" }
191
+
192
+ static var methodLookup: [String: String] {
193
+ ["invokeCdp": NSStringFromSelector(#selector(invokeCdp(_:callback:)))]
194
+ }
195
+
196
+ override init() {
197
+ super.init()
198
+ }
199
+
200
+ init(param: Any) {
201
+ super.init()
202
+ }
203
+
204
+ @objc func invokeCdp(_ message: String, callback: LynxCallbackBlock?) {
205
+ let request =
206
+ (try? JSONSerialization.jsonObject(with: Data(message.utf8))) as? [String: Any] ?? [:]
207
+ let id = request["id"] ?? 0
208
+ let method = request["method"] as? String ?? ""
209
+ let reply: [String: Any]
210
+ if method == "Page.reload" {
211
+ DevServer.shared.reloadBundle()
212
+ reply = ["id": id, "result": [String: Any]()]
213
+ } else {
214
+ reply = [
215
+ "id": id,
216
+ "error": ["code": -32601, "message": "\(method) needs Lynx DevTool, which this app doesn't have."],
217
+ ]
218
+ }
219
+ let data = (try? JSONSerialization.data(withJSONObject: reply)) ?? Data()
220
+ callback?(String(data: data, encoding: .utf8) ?? "{}")
221
+ }
222
+ }
223
+ #endif