@tokamakdev/platform-macos-x64 0.1.1-beta.161 → 0.1.1-beta.163

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.
@@ -127,14 +127,16 @@ if [[ "$platform" == macos ]]; then
127
127
  resources_dir=$contents/Resources
128
128
  app_dir=$resources_dir/app
129
129
  icon=${TOKAMAK_MACOS_ICON:-}
130
- app_files=("${TOKAMAK_MACOS_PLIST:-}" "${TOKAMAK_MACOS_ENTITLEMENTS:-}")
130
+ splash=${TOKAMAK_MACOS_SPLASH_WIDTH:-}
131
+ app_files=("${TOKAMAK_MACOS_PLIST:-}" "${TOKAMAK_MACOS_ENTITLEMENTS:-}" "${TOKAMAK_MACOS_SPLASH_IMAGE:-}" "${TOKAMAK_MACOS_SPLASH_IMAGE_DARK:-}")
131
132
  else
132
133
  contents=$bundle
133
134
  executable_dir=$bundle
134
135
  resources_dir=$bundle
135
136
  app_dir=$bundle/app
136
137
  icon=${TOKAMAK_IOS_ICON:-}
137
- app_files=("${TOKAMAK_IOS_PLIST:-}" "${TOKAMAK_IOS_ENTITLEMENTS:-}")
138
+ splash=${TOKAMAK_IOS_SPLASH_WIDTH:-}
139
+ app_files=("${TOKAMAK_IOS_PLIST:-}" "${TOKAMAK_IOS_ENTITLEMENTS:-}" "${TOKAMAK_IOS_SPLASH_IMAGE:-}" "${TOKAMAK_IOS_SPLASH_IMAGE_DARK:-}")
138
140
  fi
139
141
  if [[ -n "$icon" && ! ( -d "$icon" && "$icon" == *.[iI][cC][oO][nN] ) ]]; then
140
142
  echo "$platform.icon must be an Icon Composer .icon package: $icon" >&2
@@ -200,23 +202,34 @@ rm -rf "$bundle"
200
202
  mkdir -p "$executable_dir" "$app_dir" "$output_parent/.tokamak"
201
203
  cp -R "$input/app/." "$app_dir/"
202
204
 
205
+ # The asset catalog holds the app icon and the splash background colour.
206
+ asset_options=()
207
+ asset_inputs=()
208
+ if [[ -n "$splash" ]]; then
209
+ "$apple_tool" splash --platform "$platform" --resources "$resources_dir" --catalog "$temporary/TokamakSplash.xcassets"
210
+ asset_inputs+=("$temporary/TokamakSplash.xcassets")
211
+ fi
203
212
  if [[ -n "$icon" ]]; then
213
+ # actool names the app icon after its package.
214
+ cp -R "$icon" "$temporary/AppIcon.icon"
215
+ asset_options+=(--app-icon AppIcon)
216
+ asset_inputs+=("$temporary/AppIcon.icon")
217
+ fi
218
+ if [[ ${#asset_inputs[@]} -gt 0 ]]; then
204
219
  if [[ "$platform" == macos ]]; then
205
- icon_targets=(--target-device mac)
220
+ asset_targets=(--target-device mac)
206
221
  else
207
- icon_targets=(--target-device iphone --target-device ipad)
222
+ asset_targets=(--target-device iphone --target-device ipad)
208
223
  fi
209
- # actool names the app icon after its package.
210
- cp -R "$icon" "$temporary/AppIcon.icon"
211
224
  xcrun --sdk "$sdk" actool \
212
225
  --compile "$resources_dir" \
213
226
  --platform "$sdk" \
214
227
  --minimum-deployment-target "$minimum" \
215
- --app-icon AppIcon \
216
- "${icon_targets[@]}" \
228
+ ${asset_options[@]+"${asset_options[@]}"} \
229
+ "${asset_targets[@]}" \
217
230
  --output-partial-info-plist "$icon_info_plist" \
218
231
  --output-format human-readable-text \
219
- "$temporary/AppIcon.icon"
232
+ "${asset_inputs[@]}"
220
233
  fi
221
234
 
222
235
  shopt -s nullglob
@@ -39,14 +39,15 @@ typedef struct {
39
39
 
40
40
  void *tokamak_runtime_start(const char *packaged_dir, const char *state_dir,
41
41
  const char *storage_dir, const char *host,
42
- bool foreground, TokamakPluginHandler plugins,
43
- char *error, size_t error_len);
42
+ TokamakPluginHandler plugins, char *error,
43
+ size_t error_len);
44
44
  void *tokamak_runtime_start_development(const char *state_dir, const char *host,
45
45
  const char *endpoint,
46
46
  const char *session_token,
47
- bool foreground,
48
47
  TokamakPluginHandler plugins,
49
48
  char *error, size_t error_len);
49
+ bool tokamak_has_handler(const char *packaged_dir, const char *handler);
50
+ void tokamak_runtime_deliver_start(const void *runtime, bool foreground);
50
51
  uint16_t tokamak_runtime_port(const void *runtime);
51
52
  uint16_t tokamak_runtime_await_port_change(const void *runtime, uint16_t known,
52
53
  uint64_t timeout_ms);
@@ -8,8 +8,10 @@ import WebKit
8
8
  #endif
9
9
 
10
10
  private let startupErrorFile = "startup-error.log"
11
- /// How long the Worker has for `resume` and `suspend`.
11
+ /// How long the Worker has for `_onResume` and `_onSuspend`.
12
12
  private let lifecycleDeadline: TimeInterval = 10
13
+ /// How long launch waits for the Worker's `_beforeStart`.
14
+ private let beforeStartDeadline: TimeInterval = 1
13
15
  #if os(iOS)
14
16
  /// The system gives an app about 30 seconds after it leaves the foreground.
15
17
  private let suspendDeadline: TimeInterval = 25
@@ -28,7 +30,7 @@ final class TokamakApp: TokamakHostApp {
28
30
  private var waiting: [(Result<RuntimeHandle, Error>) -> Void] = []
29
31
  /// The Worker's calls and subscriptions on the plugins.
30
32
  private var workerRequests: TokamakPluginRequests<UInt64>!
31
- /// Delivers `resume` and `suspend` one at a time, in order.
33
+ /// Delivers `_onResume` and `_onSuspend` one at a time, in order.
32
34
  private let lifecycle = DispatchQueue(label: "tokamak.lifecycle")
33
35
  #if os(iOS)
34
36
  /// The scenes in the foreground.
@@ -55,14 +57,39 @@ final class TokamakApp: TokamakHostApp {
55
57
  })
56
58
  }
57
59
 
58
- /// Starts the runtime in the background, which delivers `start` with
59
- /// `foreground`. Call it once, on the main thread.
60
- func start(foreground: Bool) {
60
+ /// Starts the runtime in the background. When the Worker receives
61
+ /// `_beforeStart`, waits until it returns or its deadline passes, running
62
+ /// the plugin calls it makes on the main thread. Call it once, on the main
63
+ /// thread, inside the platform's launch.
64
+ func start() {
61
65
  dispatchPrecondition(condition: .onQueue(.main))
62
66
  let plugins = workerPlugins
63
- DispatchQueue.global(qos: .userInitiated).async {
64
- let result = Result { try RuntimeHandle(foreground: foreground, plugins: plugins) }
65
- DispatchQueue.main.async { self.started(result) }
67
+ let waits = RuntimeHandle.receivesBeforeStart
68
+ let deadline = Date() + beforeStartDeadline
69
+ let launch = {
70
+ let result = Result { try RuntimeHandle(plugins: plugins) }
71
+ TokamakMainThread.post { self.started(result) }
72
+ guard waits, case .success(let runtime) = result else { return }
73
+ do {
74
+ _ = try runtime.emit(
75
+ "_beforeStart", payload: Data("{}".utf8), timeout: deadline.timeIntervalSinceNow)
76
+ } catch {
77
+ print("tokamak _beforeStart failed: \(error)")
78
+ }
79
+ }
80
+ if waits {
81
+ TokamakMainThread.run(until: deadline, work: launch)
82
+ } else {
83
+ DispatchQueue.global(qos: .userInitiated).async(execute: launch)
84
+ }
85
+ }
86
+
87
+ /// Records whether the app starts in the `foreground` and delivers
88
+ /// `_onStart` with it, once the runtime has started. Call it once, on the
89
+ /// main thread, after the platform's launch.
90
+ func deliverStart(foreground: Bool) {
91
+ ready { started in
92
+ if case .success(let runtime) = started { runtime.deliverStart(foreground: foreground) }
66
93
  }
67
94
  }
68
95
 
@@ -124,10 +151,10 @@ final class TokamakApp: TokamakHostApp {
124
151
  }
125
152
 
126
153
  /// Delivers the event `name`, whose encoded data is `payload`, to the
127
- /// Worker's listeners, and calls `completion` on the main thread with their
128
- /// encoded reply, which is empty when none replied. Fails unless they
129
- /// return within `timeout`, which includes runtime startup. Call it on the
130
- /// main thread.
154
+ /// Worker's method of that name, and calls `completion` on the main thread
155
+ /// with its encoded reply, which is empty when it returns nothing. Fails
156
+ /// unless it returns within `timeout`, which includes runtime startup. Call
157
+ /// it on the main thread.
131
158
  func emit(
132
159
  _ name: String,
133
160
  payload: Data,
@@ -188,10 +215,10 @@ final class TokamakApp: TokamakHostApp {
188
215
  }
189
216
 
190
217
  /// Records the app moving into or out of the foreground once the runtime
191
- /// has started, and delivers `resume` or `suspend` when that changed its
192
- /// stage. Call it on the main thread.
218
+ /// has started, and delivers `_onResume` or `_onSuspend` when that changed
219
+ /// its stage. Call it on the main thread.
193
220
  func moved(toForeground foreground: Bool) {
194
- let name = foreground ? "resume" : "suspend"
221
+ let name = foreground ? "_onResume" : "_onSuspend"
195
222
  #if os(iOS)
196
223
  // The system suspends the app soon after it leaves the foreground
197
224
  // unless a background task holds it there.
@@ -225,7 +252,7 @@ final class TokamakApp: TokamakHostApp {
225
252
  }
226
253
 
227
254
  #if os(iOS)
228
- /// Delivers `resume` as the first scene enters the foreground.
255
+ /// Delivers `_onResume` as the first scene enters the foreground.
229
256
  func sceneWillEnterForeground() {
230
257
  foregroundScenes += 1
231
258
  if foregroundScenes == 1 {
@@ -233,7 +260,7 @@ final class TokamakApp: TokamakHostApp {
233
260
  }
234
261
  }
235
262
 
236
- /// Delivers `suspend` as the last scene leaves the foreground.
263
+ /// Delivers `_onSuspend` as the last scene leaves the foreground.
237
264
  func sceneDidEnterBackground() {
238
265
  foregroundScenes -= 1
239
266
  if foregroundScenes == 0 {
@@ -320,9 +347,18 @@ final class RuntimeHandle {
320
347
  let appHost: String
321
348
  private var handle: UnsafeMutableRawPointer?
322
349
 
323
- /// Starts the runtime, which delivers `start` with `foreground`, and whose
324
- /// Worker calls `plugins`.
325
- init(foreground: Bool, plugins: TokamakPluginHandler) throws {
350
+ /// Whether the Worker receives `_beforeStart`: its packaged class has that
351
+ /// method, or it runs in the development server, which receives every event.
352
+ static var receivesBeforeStart: Bool {
353
+ if Bundle.main.object(forInfoDictionaryKey: "TokamakDevEndpoint") is String { return true }
354
+ guard let app = Bundle.main.resourceURL?.appendingPathComponent("app") else { return false }
355
+ return app.path.withCString { app in
356
+ "_beforeStart".withCString { tokamak_has_handler(app, $0) }
357
+ }
358
+ }
359
+
360
+ /// Starts the runtime, whose Worker calls `plugins`.
361
+ init(plugins: TokamakPluginHandler) throws {
326
362
  guard let appHost = Bundle.main.tokamakHost, !appHost.isEmpty else {
327
363
  throw RuntimeError(description: "TokamakHost is required")
328
364
  }
@@ -344,7 +380,6 @@ final class RuntimeHandle {
344
380
  appHost,
345
381
  endpoint,
346
382
  sessionToken,
347
- foreground,
348
383
  plugins,
349
384
  error.baseAddress,
350
385
  error.count
@@ -370,7 +405,6 @@ final class RuntimeHandle {
370
405
  statePath,
371
406
  storagePath,
372
407
  appHost,
373
- foreground,
374
408
  plugins,
375
409
  error.baseAddress,
376
410
  error.count
@@ -415,9 +449,16 @@ final class RuntimeHandle {
415
449
  return port
416
450
  }
417
451
 
452
+ /// Records whether the app starts in the `foreground`, and delivers
453
+ /// `_onStart` with it in the background.
454
+ func deliverStart(foreground: Bool) {
455
+ tokamak_runtime_deliver_start(handle, foreground)
456
+ }
457
+
418
458
  /// Delivers the event `name`, whose encoded data is `payload`, to the
419
- /// Worker's listeners, blocking until they return or `timeout` passes, and
420
- /// returns their encoded reply, which is empty when none replied.
459
+ /// Worker's method of that name, blocking until it returns or `timeout`
460
+ /// passes, and returns its encoded reply, which is empty when it returns
461
+ /// nothing.
421
462
  func emit(_ name: String, payload: Data, timeout: TimeInterval) throws -> Data {
422
463
  var reply = TokamakBytes()
423
464
  var error = [CChar](repeating: 0, count: 1024)
@@ -14,9 +14,12 @@ private let failurePage =
14
14
 
15
15
  private final class NavigationDelegate: NSObject, WKNavigationDelegate, WKUIDelegate {
16
16
  private let runtime: RuntimeHandle
17
+ /// Called once, when the first navigation finishes or fails.
18
+ private var firstLoad: (() -> Void)?
17
19
 
18
- init(runtime: RuntimeHandle) {
20
+ init(runtime: RuntimeHandle, firstLoad: @escaping () -> Void) {
19
21
  self.runtime = runtime
22
+ self.firstLoad = firstLoad
20
23
  }
21
24
 
22
25
  func webView(
@@ -122,12 +125,31 @@ private final class NavigationDelegate: NSObject, WKNavigationDelegate, WKUIDele
122
125
  }
123
126
  }
124
127
 
128
+ func webView(_ webView: WKWebView, didFinish navigation: WKNavigation?) {
129
+ finishFirstLoad()
130
+ }
131
+
132
+ func webView(
133
+ _ webView: WKWebView,
134
+ didFail navigation: WKNavigation?,
135
+ withError error: Error
136
+ ) {
137
+ print("tokamak WebView navigation failed: \(error)")
138
+ finishFirstLoad()
139
+ }
140
+
125
141
  func webView(
126
142
  _ webView: WKWebView,
127
143
  didFailProvisionalNavigation navigation: WKNavigation?,
128
144
  withError error: Error
129
145
  ) {
130
146
  print("tokamak WebView navigation failed: \(error)")
147
+ finishFirstLoad()
148
+ }
149
+
150
+ private func finishFirstLoad() {
151
+ firstLoad?()
152
+ firstLoad = nil
131
153
  }
132
154
 
133
155
  private func openExternal(_ url: URL) {
@@ -226,14 +248,22 @@ private final class TokamakController {
226
248
  self.app = app
227
249
  }
228
250
 
229
- func start(frame: CGRect, completion: @escaping (WKWebView) -> Void) {
251
+ /// Creates the WebView once the runtime has started, and calls `firstLoad`
252
+ /// once its first page has loaded or failed, or at once with the failure
253
+ /// page.
254
+ func start(
255
+ frame: CGRect,
256
+ firstLoad: @escaping () -> Void,
257
+ completion: @escaping (WKWebView) -> Void
258
+ ) {
230
259
  app.whenStarted { result in
231
260
  switch result {
232
261
  case .success(let runtime):
233
262
  self.runtime = runtime
234
- completion(self.webView(frame: frame, runtime: runtime))
263
+ completion(self.webView(frame: frame, runtime: runtime, firstLoad: firstLoad))
235
264
  case .failure:
236
265
  completion(self.failureWebView(frame: frame))
266
+ firstLoad()
237
267
  }
238
268
  }
239
269
  }
@@ -272,7 +302,11 @@ private final class TokamakController {
272
302
  }.start()
273
303
  }
274
304
 
275
- private func webView(frame: CGRect, runtime: RuntimeHandle) -> WKWebView {
305
+ private func webView(
306
+ frame: CGRect,
307
+ runtime: RuntimeHandle,
308
+ firstLoad: @escaping () -> Void
309
+ ) -> WKWebView {
276
310
  let configuration = WKWebViewConfiguration()
277
311
  let dataStore = WKWebsiteDataStore.default()
278
312
  let port = runtime.port
@@ -286,7 +320,7 @@ private final class TokamakController {
286
320
  #endif
287
321
  configuration.mediaTypesRequiringUserActionForPlayback = []
288
322
 
289
- let navigation = NavigationDelegate(runtime: runtime)
323
+ let navigation = NavigationDelegate(runtime: runtime, firstLoad: firstLoad)
290
324
  self.navigation = navigation
291
325
  let webView = WKWebView(frame: frame, configuration: configuration)
292
326
  #if os(iOS)
@@ -327,6 +361,7 @@ private final class TokamakController {
327
361
  private var visible = false
328
362
 
329
363
  func applicationDidFinishLaunching(_ notification: Notification) {
364
+ app.start()
330
365
  let window = NSWindow(
331
366
  contentRect: NSRect(x: 0, y: 0, width: 1024, height: 768),
332
367
  styleMask: [.titled, .closable, .miniaturizable, .resizable],
@@ -340,14 +375,23 @@ private final class TokamakController {
340
375
  NSApplication.shared.activate(ignoringOtherApps: true)
341
376
  self.window = window
342
377
  visible = !NSApplication.shared.isHidden
343
- app.start(foreground: visible)
378
+ app.deliverStart(foreground: visible)
344
379
  observeVisibility()
345
380
 
346
381
  guard let content = window.contentView else { return }
347
- controller.start(frame: content.bounds) { webView in
348
- webView.autoresizingMask = [.width, .height]
349
- content.addSubview(webView)
382
+ let dark = window.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua
383
+ let splash = TokamakSplash(frame: content.bounds, dark: dark)
384
+ if let splash {
385
+ content.addSubview(splash.view)
350
386
  }
387
+ controller.start(
388
+ frame: content.bounds,
389
+ firstLoad: { splash?.remove() },
390
+ completion: { webView in
391
+ webView.autoresizingMask = [.width, .height]
392
+ content.addSubview(webView, positioned: .below, relativeTo: nil)
393
+ }
394
+ )
351
395
  }
352
396
 
353
397
  func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
@@ -434,14 +478,15 @@ private final class TokamakController {
434
478
  /// Exists from launch, whether or not a scene connects.
435
479
  let app = TokamakApp()
436
480
 
437
- /// Starts the runtime once launch finishes. A scene a user launches the
438
- /// app into has entered the foreground by then.
481
+ /// Starts the runtime, and delivers `_onStart` once launch finishes. A
482
+ /// scene a user launches the app into has entered the foreground by then.
439
483
  func application(
440
484
  _ application: UIApplication,
441
485
  didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
442
486
  ) -> Bool {
487
+ app.start()
443
488
  DispatchQueue.main.async {
444
- self.app.start(foreground: self.app.hasForegroundScene)
489
+ self.app.deliverStart(foreground: self.app.hasForegroundScene)
445
490
  }
446
491
  return true
447
492
  }
@@ -498,11 +543,23 @@ private final class TokamakController {
498
543
  window.makeKeyAndVisible()
499
544
  self.window = window
500
545
 
501
- let controller = TokamakController(app: app)
502
- controller.start(frame: viewController.view.bounds) { webView in
503
- webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
504
- viewController.view.addSubview(webView)
546
+ let view: UIView = viewController.view
547
+ let splash = TokamakSplash(
548
+ frame: view.bounds,
549
+ dark: scene.traitCollection.userInterfaceStyle == .dark
550
+ )
551
+ if let splash {
552
+ view.addSubview(splash.view)
505
553
  }
554
+ let controller = TokamakController(app: app)
555
+ controller.start(
556
+ frame: view.bounds,
557
+ firstLoad: { splash?.remove() },
558
+ completion: { webView in
559
+ webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
560
+ view.insertSubview(webView, at: 0)
561
+ }
562
+ )
506
563
  self.controller = controller
507
564
  }
508
565
 
@@ -0,0 +1,125 @@
1
+ import Foundation
2
+ import ImageIO
3
+
4
+ #if os(macOS)
5
+ import AppKit
6
+ #else
7
+ import UIKit
8
+ #endif
9
+
10
+ /// The asset catalog colour the build writes from the splash background.
11
+ private let backgroundColorName = "TokamakSplashBackground"
12
+
13
+ /// The app's splash screen: its image centred on its background colour, shown
14
+ /// over the WebView from launch until the app's first page has loaded. The
15
+ /// build names the images and width in Info.plist.
16
+ final class TokamakSplash {
17
+ #if os(macOS)
18
+ let view: NSView
19
+ #else
20
+ let view: UIView
21
+ /// Whether the image's animation stops at its next frame.
22
+ private var stopped = false
23
+ #endif
24
+
25
+ /// The width the image is drawn at, in points.
26
+ private static var width: CGFloat? {
27
+ (Bundle.main.object(forInfoDictionaryKey: "TokamakSplashWidth") as? NSNumber)
28
+ .map { CGFloat($0.doubleValue) }
29
+ }
30
+
31
+ /// The image file for the appearance, if the splash has one.
32
+ private static func imageURL(dark: Bool) -> URL? {
33
+ let key = dark ? "TokamakSplashImageDark" : "TokamakSplashImage"
34
+ return (Bundle.main.object(forInfoDictionaryKey: key) as? String)
35
+ .flatMap { Bundle.main.url(forResource: $0, withExtension: nil) }
36
+ }
37
+
38
+ /// The image's frame: `width` wide at its aspect ratio, centred in `bounds`.
39
+ private static func imageFrame(size: CGSize, width: CGFloat, in bounds: CGRect) -> CGRect {
40
+ let height = size.width > 0 ? width * size.height / size.width : 0
41
+ return CGRect(
42
+ x: bounds.midX - width / 2, y: bounds.midY - height / 2, width: width, height: height
43
+ )
44
+ }
45
+
46
+ #if os(macOS)
47
+ /// The app's splash filling `frame`, in dark mode or not, or nil when the app has none.
48
+ init?(frame: CGRect, dark: Bool) {
49
+ guard let width = Self.width else { return nil }
50
+ view = BackgroundView(frame: frame)
51
+ view.autoresizingMask = [.width, .height]
52
+ view.setAccessibilityElement(false)
53
+ guard let url = Self.imageURL(dark: dark), let image = NSImage(contentsOf: url) else {
54
+ return
55
+ }
56
+ // An image view plays an animated GIF by itself.
57
+ let imageView = NSImageView(
58
+ frame: Self.imageFrame(size: image.size, width: width, in: view.bounds)
59
+ )
60
+ imageView.image = image
61
+ imageView.imageScaling = .scaleProportionallyUpOrDown
62
+ imageView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
63
+ imageView.setAccessibilityElement(false)
64
+ view.addSubview(imageView)
65
+ }
66
+
67
+ func remove() {
68
+ view.removeFromSuperview()
69
+ }
70
+
71
+ /// A view filled with the splash background in its appearance.
72
+ private final class BackgroundView: NSView {
73
+ override var wantsUpdateLayer: Bool { true }
74
+
75
+ override func updateLayer() {
76
+ layer?.backgroundColor = NSColor(named: backgroundColorName)?.cgColor
77
+ }
78
+ }
79
+ #else
80
+ /// The app's splash filling `frame`, in dark mode or not, or nil when the app has none.
81
+ init?(frame: CGRect, dark: Bool) {
82
+ guard let width = Self.width else { return nil }
83
+ view = UIView(frame: frame)
84
+ view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
85
+ view.backgroundColor = UIColor(named: backgroundColorName)
86
+ view.accessibilityElementsHidden = true
87
+ guard
88
+ let url = Self.imageURL(dark: dark),
89
+ let source = CGImageSourceCreateWithURL(url as CFURL, nil)
90
+ else { return }
91
+ let animated = CGImageSourceGetCount(source) > 1
92
+ // A JPEG's orientation applies through UIImage; a GIF has none.
93
+ let image =
94
+ animated
95
+ ? CGImageSourceCreateImageAtIndex(source, 0, nil).map { UIImage(cgImage: $0) }
96
+ : UIImage(contentsOfFile: url.path)
97
+ guard let image else { return }
98
+ let imageView = UIImageView(
99
+ frame: Self.imageFrame(size: image.size, width: width, in: view.bounds)
100
+ )
101
+ imageView.image = image
102
+ imageView.contentMode = .scaleAspectFit
103
+ imageView.autoresizingMask = [
104
+ .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin,
105
+ ]
106
+ view.addSubview(imageView)
107
+ guard animated else { return }
108
+ // An image view does not play a GIF, so each frame is shown at the
109
+ // file's timing, from the main queue.
110
+ CGAnimateImageAtURLWithBlock(url as CFURL, nil) {
111
+ [weak self, weak imageView] _, frame, stop in
112
+ guard let self, let imageView, !self.stopped else {
113
+ stop.pointee = true
114
+ return
115
+ }
116
+ imageView.image = UIImage(cgImage: frame)
117
+ }
118
+ }
119
+
120
+ func remove() {
121
+ stopped = true
122
+ view.removeFromSuperview()
123
+ }
124
+ #endif
125
+ }
@@ -13,7 +13,7 @@ public protocol TokamakExports: TokamakPlugin {
13
13
  /// `event` as the JSON data of the event `name`, which the registration lists.
14
14
  func eventPayload(_ name: String, _ event: Any) throws(TokamakPluginError) -> Data
15
15
 
16
- /// The listeners' JSON `reply` to the event `name`, which the registration
16
+ /// The handler's JSON `reply` to the event `name`, which the registration
17
17
  /// lists with a reply, as its type, or nil for null.
18
18
  func eventReply(_ name: String, _ reply: Data) throws(TokamakPluginError) -> Any?
19
19
  }
@@ -40,10 +40,11 @@ public enum TokamakOverflow {
40
40
  /// replies are `Decodable`, method results and events `Encodable`, and options
41
41
  /// literal values.
42
42
  public struct TokamakExporter<Plugin> {
43
- /// Lists the event `name`, whose listeners receive an `E`.
43
+ /// Lists the event `name`: the Worker's method `name`, which starts with
44
+ /// `_`, receives an `E`.
44
45
  public mutating func event<E: Encodable>(_ name: String, _ type: E.Type, doc: String = "") {}
45
46
 
46
- /// Lists the event `name`, whose listeners receive an `E` and may reply with an `R`.
47
+ /// Lists the event `name`, whose handler receives an `E` and may reply with an `R`.
47
48
  public mutating func event<E: Encodable, R: Decodable>(
48
49
  _ name: String, _ type: E.Type, reply: R.Type, doc: String = ""
49
50
  ) {}
@@ -333,7 +334,7 @@ public func tokamakEncode<T: Encodable>(
333
334
  }
334
335
  }
335
336
 
336
- /// `event` as the JSON data of the event `name`, whose listeners receive a `T`.
337
+ /// `event` as the JSON data of the event `name`, whose handler receives a `T`.
337
338
  public func tokamakEvent<T: Encodable>(
338
339
  _ name: String, _ event: Any, as type: T.Type
339
340
  ) throws(TokamakPluginError) -> Data {
@@ -125,9 +125,9 @@ public protocol TokamakHostApp: AnyObject {
125
125
  #endif
126
126
 
127
127
  /// Delivers the event `name`, whose encoded data is `payload`, to the
128
- /// Worker's listeners, and calls `completion` on the main thread with their
129
- /// encoded reply, which is empty when none replied. Fails unless they return
130
- /// within `timeout`, which includes runtime startup.
128
+ /// Worker's method of that name, and calls `completion` on the main thread
129
+ /// with its encoded reply, which is empty when it returns nothing. Fails
130
+ /// unless it returns within `timeout`, which includes runtime startup.
131
131
  func emit(
132
132
  _ name: String, payload: Data, timeout: TimeInterval,
133
133
  completion: @escaping (Result<Data, Error>) -> Void)
@@ -183,23 +183,23 @@ public final class TokamakHost {
183
183
  }
184
184
  #endif
185
185
 
186
- /// Delivers the plugin's event `name`, which the Worker's listeners
187
- /// receive as `<plugin>.apple.<name>`, with its encoded `payload`, and calls
188
- /// `completion` on the main thread with their encoded reply, which is empty
189
- /// when none replied. Fails unless they return within `timeout`, which
190
- /// includes runtime startup. Call it on the main thread.
186
+ /// Delivers the plugin's event `name` to the Worker's method of that name,
187
+ /// with its encoded `payload`, and calls `completion` on the main thread
188
+ /// with the method's encoded reply, which is empty when it returns nothing.
189
+ /// Fails unless it returns within `timeout`, which includes runtime
190
+ /// startup. Call it on the main thread.
191
191
  public func emitBytes(
192
192
  _ name: String,
193
193
  payload: Data,
194
194
  timeout: TimeInterval,
195
195
  completion: @escaping (Result<Data, Error>) -> Void
196
196
  ) {
197
- app.emit("\(plugin).apple.\(name)", payload: payload, timeout: timeout, completion: completion)
197
+ app.emit(name, payload: payload, timeout: timeout, completion: completion)
198
198
  }
199
199
 
200
- /// Delivers `event` to the Worker's listeners of the plugin's event `name`,
201
- /// which `Exports.swift` lists, then calls `completion` on the main
202
- /// thread. Fails unless they return within `timeout`, which includes runtime
200
+ /// Delivers `event` to the Worker's method `name`, the plugin's event that
201
+ /// `Exports.swift` lists, then calls `completion` on the main thread. Fails
202
+ /// unless the method returns within `timeout`, which includes runtime
203
203
  /// startup. Call it on the main thread.
204
204
  public func emit(
205
205
  _ name: String,
@@ -210,9 +210,9 @@ public final class TokamakHost {
210
210
  send(name, event, timeout: timeout) { completion($0.map { _ in }) }
211
211
  }
212
212
 
213
- /// `emit` of an event whose listeners may reply, calling `completion` with
213
+ /// `emit` of an event whose handler may reply, calling `completion` with
214
214
  /// the reply as the plugin's generated dispatch decodes it, which is a
215
- /// `Reply`, or nil when none replied.
215
+ /// `Reply`, or nil without one.
216
216
  public func emit<Reply>(
217
217
  _ name: String,
218
218
  event: some Encodable,
@@ -242,7 +242,7 @@ public final class TokamakHost {
242
242
  emitBytes(name, payload: payload, timeout: timeout, completion: completion)
243
243
  }
244
244
 
245
- /// The listeners' `reply` to the event `name` as a `Reply`, or nil when none replied.
245
+ /// The handler's `reply` to the event `name` as a `Reply`, or nil without one.
246
246
  private func decoded<Reply>(
247
247
  _ reply: Data, to name: String, as type: Reply.Type
248
248
  ) throws(TokamakPluginError) -> Reply? {
@@ -426,6 +426,57 @@ public enum TokamakPluginRequest {
426
426
  case call, callWithBody, subscribe
427
427
  }
428
428
 
429
+ /// Work for the main thread. Its queue runs the work, except while the main
430
+ /// thread waits in `run`, which then runs it.
431
+ public enum TokamakMainThread {
432
+ private static let condition = NSCondition()
433
+ /// The work posted while the main thread waits, which is nil otherwise.
434
+ private static var waiting: [() -> Void]?
435
+ private static var finished = false
436
+
437
+ public static func post(_ work: @escaping () -> Void) {
438
+ let taken = condition.withLock {
439
+ waiting?.append(work)
440
+ condition.signal()
441
+ return waiting != nil
442
+ }
443
+ if !taken { DispatchQueue.main.async(execute: work) }
444
+ }
445
+
446
+ /// Blocks the main thread until `work`, which runs on another thread,
447
+ /// returns or `deadline` passes, running the work posted meanwhile.
448
+ public static func run(until deadline: Date, work: @escaping () -> Void) {
449
+ condition.withLock {
450
+ waiting = []
451
+ finished = false
452
+ }
453
+ DispatchQueue.global(qos: .userInitiated).async {
454
+ work()
455
+ condition.withLock {
456
+ finished = true
457
+ condition.signal()
458
+ }
459
+ }
460
+ condition.lock()
461
+ while !finished {
462
+ if let posted = waiting?.first {
463
+ waiting?.removeFirst()
464
+ condition.unlock()
465
+ posted()
466
+ condition.lock()
467
+ } else if !condition.wait(until: deadline) {
468
+ break
469
+ }
470
+ }
471
+ let rest = waiting ?? []
472
+ waiting = nil
473
+ condition.unlock()
474
+ for posted in rest {
475
+ DispatchQueue.main.async(execute: posted)
476
+ }
477
+ }
478
+ }
479
+
429
480
  /// Runs the Worker's requests on the executor each plugin chooses, and passes
430
481
  /// replies straight to the runtime.
431
482
  public final class TokamakPluginRequests<Key: Hashable> {
@@ -477,7 +528,7 @@ public final class TokamakPluginRequests<Key: Hashable> {
477
528
  send(key, result)
478
529
  if subscribe && result.done { cancel(request) }
479
530
  }
480
- request.queue.async { [self] in
531
+ let start = { [self] in
481
532
  guard isPending(key, request) else { return }
482
533
  do throws(TokamakPluginError) {
483
534
  if subscribe {
@@ -494,6 +545,11 @@ public final class TokamakPluginRequests<Key: Hashable> {
494
545
  if remove(key, request) { send(key, TokamakPluginResult(.failure(error), done: true)) }
495
546
  }
496
547
  }
548
+ if request.queue === DispatchQueue.main {
549
+ TokamakMainThread.post(start)
550
+ } else {
551
+ request.queue.async(execute: start)
552
+ }
497
553
  }
498
554
 
499
555
  /// Answers the pending read of the call `key`'s body with the chunk the
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/macos-x64/tools/tokamak-swift-describe
3
3
  size: 34571400 bytes
4
- sha256: 8666d8d24119446960921ebfb3a903cdb236e8cde565f8961c70bf4cafb637db
4
+ sha256: 46bebdce722eeb346ca9d2b3c7ef1b53bdba6bbd69aa3f5366d5db4904be25bc
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokamakdev/platform-macos-x64",
3
- "version": "0.1.1-beta.161",
3
+ "version": "0.1.1-beta.163",
4
4
  "description": "The tokamak platform pack for macos-x64",
5
5
  "repository": {
6
6
  "type": "git",