@ng-native/desktop 0.0.0 → 0.24.0

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 (401) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -0
  3. package/app.plugin.cjs +17 -0
  4. package/bin/app-config.mjs +168 -0
  5. package/bin/autolink.mjs +224 -0
  6. package/bin/cli.mjs +158 -0
  7. package/bin/host.mjs +427 -0
  8. package/bin/ng-native-desktop.mjs +4 -0
  9. package/bin/package.mjs +971 -0
  10. package/bin/plist.mjs +68 -0
  11. package/bin/prebuilt.mjs +328 -0
  12. package/bin/toolchain.mjs +192 -0
  13. package/native/CMakeLists.txt +277 -0
  14. package/native/appkit/CMakeLists.txt +130 -0
  15. package/native/appkit/address-search.h +26 -0
  16. package/native/appkit/address-search.mm +277 -0
  17. package/native/appkit/animation-frames.h +14 -0
  18. package/native/appkit/animation-frames.mm +106 -0
  19. package/native/appkit/app-info.h +12 -0
  20. package/native/appkit/app-info.mm +98 -0
  21. package/native/appkit/app-updater.mm +128 -0
  22. package/native/appkit/app-windows.h +81 -0
  23. package/native/appkit/app-windows.mm +318 -0
  24. package/native/appkit/appkit-backend.h +73 -0
  25. package/native/appkit/appkit-backend.mm +276 -0
  26. package/native/appkit/apple-authentication.h +19 -0
  27. package/native/appkit/apple-authentication.mm +248 -0
  28. package/native/appkit/apple-button-view.h +10 -0
  29. package/native/appkit/apple-button-view.mm +37 -0
  30. package/native/appkit/apple-id-button.h +16 -0
  31. package/native/appkit/apple-id-button.mm +50 -0
  32. package/native/appkit/audio.h +16 -0
  33. package/native/appkit/audio.mm +275 -0
  34. package/native/appkit/battery.h +13 -0
  35. package/native/appkit/battery.mm +92 -0
  36. package/native/appkit/bookmarks.h +17 -0
  37. package/native/appkit/bookmarks.mm +145 -0
  38. package/native/appkit/calendar.h +25 -0
  39. package/native/appkit/calendar.mm +660 -0
  40. package/native/appkit/camera-sheet.h +59 -0
  41. package/native/appkit/camera-sheet.mm +344 -0
  42. package/native/appkit/camera-view.h +15 -0
  43. package/native/appkit/camera-view.mm +134 -0
  44. package/native/appkit/camera.h +61 -0
  45. package/native/appkit/camera.mm +496 -0
  46. package/native/appkit/cg-canvas.h +24 -0
  47. package/native/appkit/cg-canvas.mm +663 -0
  48. package/native/appkit/component-view.h +17 -0
  49. package/native/appkit/crypto.h +19 -0
  50. package/native/appkit/crypto.mm +78 -0
  51. package/native/appkit/desktop-expo.h +29 -0
  52. package/native/appkit/desktop-expo.mm +385 -0
  53. package/native/appkit/expo-image-drawing.h +46 -0
  54. package/native/appkit/expo-image-drawing.mm +131 -0
  55. package/native/appkit/expo-image-view.h +15 -0
  56. package/native/appkit/expo-image-view.mm +182 -0
  57. package/native/appkit/expo-ui-renderer.h +68 -0
  58. package/native/appkit/expo-ui-renderer.mm +101 -0
  59. package/native/appkit/expo-ui-view.h +26 -0
  60. package/native/appkit/expo-ui-view.mm +134 -0
  61. package/native/appkit/expo-ui.swift +1284 -0
  62. package/native/appkit/file-system.h +16 -0
  63. package/native/appkit/file-system.mm +140 -0
  64. package/native/appkit/fonts.h +12 -0
  65. package/native/appkit/fonts.mm +48 -0
  66. package/native/appkit/geocoder.h +19 -0
  67. package/native/appkit/geocoder.mm +101 -0
  68. package/native/appkit/glass-effect.h +22 -0
  69. package/native/appkit/glass-effect.mm +63 -0
  70. package/native/appkit/glass-view.h +8 -0
  71. package/native/appkit/glass-view.mm +65 -0
  72. package/native/appkit/header-toolbar.h +60 -0
  73. package/native/appkit/header-toolbar.mm +632 -0
  74. package/native/appkit/host-view.h +54 -0
  75. package/native/appkit/host-view.mm +1228 -0
  76. package/native/appkit/image-manipulator.h +14 -0
  77. package/native/appkit/image-manipulator.mm +191 -0
  78. package/native/appkit/image-request.h +22 -0
  79. package/native/appkit/image-request.mm +62 -0
  80. package/native/appkit/image-view.h +8 -0
  81. package/native/appkit/image-view.mm +142 -0
  82. package/native/appkit/input-replay.h +25 -0
  83. package/native/appkit/input-replay.mm +418 -0
  84. package/native/appkit/language-model.h +14 -0
  85. package/native/appkit/language-model.mm +99 -0
  86. package/native/appkit/language-model.swift +472 -0
  87. package/native/appkit/local-authentication.h +15 -0
  88. package/native/appkit/local-authentication.mm +133 -0
  89. package/native/appkit/location.h +16 -0
  90. package/native/appkit/location.mm +214 -0
  91. package/native/appkit/main.mm +1475 -0
  92. package/native/appkit/map-view.h +15 -0
  93. package/native/appkit/map-view.mm +109 -0
  94. package/native/appkit/maps.h +35 -0
  95. package/native/appkit/maps.mm +343 -0
  96. package/native/appkit/menu-bar.h +22 -0
  97. package/native/appkit/menu-bar.mm +208 -0
  98. package/native/appkit/modal-focus.h +16 -0
  99. package/native/appkit/modal-focus.mm +26 -0
  100. package/native/appkit/modal-host-view.h +79 -0
  101. package/native/appkit/modal-host-view.mm +442 -0
  102. package/native/appkit/native-controls.h +22 -0
  103. package/native/appkit/native-controls.mm +431 -0
  104. package/native/appkit/network-state.h +12 -0
  105. package/native/appkit/network-state.mm +64 -0
  106. package/native/appkit/network.h +14 -0
  107. package/native/appkit/network.mm +396 -0
  108. package/native/appkit/notifications.h +19 -0
  109. package/native/appkit/notifications.mm +309 -0
  110. package/native/appkit/photo-library.h +33 -0
  111. package/native/appkit/photo-library.mm +548 -0
  112. package/native/appkit/pointer-buttons.h +32 -0
  113. package/native/appkit/presentation-label.h +15 -0
  114. package/native/appkit/presentation-label.mm +12 -0
  115. package/native/appkit/presented-screen.h +19 -0
  116. package/native/appkit/presented-screen.mm +181 -0
  117. package/native/appkit/printing.h +42 -0
  118. package/native/appkit/printing.mm +393 -0
  119. package/native/appkit/push.h +19 -0
  120. package/native/appkit/push.mm +81 -0
  121. package/native/appkit/red-box.h +26 -0
  122. package/native/appkit/red-box.mm +387 -0
  123. package/native/appkit/screen-capture.h +21 -0
  124. package/native/appkit/screen-capture.mm +92 -0
  125. package/native/appkit/scroll-view.h +13 -0
  126. package/native/appkit/scroll-view.mm +251 -0
  127. package/native/appkit/scrollers.h +25 -0
  128. package/native/appkit/scrollers.mm +43 -0
  129. package/native/appkit/search-field.h +34 -0
  130. package/native/appkit/search-field.mm +291 -0
  131. package/native/appkit/search-toolbar-item.h +19 -0
  132. package/native/appkit/search-toolbar-item.mm +269 -0
  133. package/native/appkit/share-picker.h +34 -0
  134. package/native/appkit/share-picker.mm +121 -0
  135. package/native/appkit/split-view.h +77 -0
  136. package/native/appkit/split-view.mm +1206 -0
  137. package/native/appkit/store-review.h +13 -0
  138. package/native/appkit/store-review.mm +28 -0
  139. package/native/appkit/surface-view.h +45 -0
  140. package/native/appkit/surface-view.mm +562 -0
  141. package/native/appkit/svg-view.h +18 -0
  142. package/native/appkit/svg-view.mm +103 -0
  143. package/native/appkit/symbol-drawing.h +24 -0
  144. package/native/appkit/symbol-drawing.mm +117 -0
  145. package/native/appkit/symbol-view.h +8 -0
  146. package/native/appkit/symbol-view.mm +33 -0
  147. package/native/appkit/system-access.h +34 -0
  148. package/native/appkit/system-access.mm +210 -0
  149. package/native/appkit/system.h +24 -0
  150. package/native/appkit/system.mm +403 -0
  151. package/native/appkit/tab-walk.h +31 -0
  152. package/native/appkit/tab-walk.mm +64 -0
  153. package/native/appkit/test-launch.h +36 -0
  154. package/native/appkit/test-launch.mm +115 -0
  155. package/native/appkit/text-input-field.h +81 -0
  156. package/native/appkit/text-input-field.mm +525 -0
  157. package/native/appkit/text-layout.h +58 -0
  158. package/native/appkit/text-layout.mm +485 -0
  159. package/native/appkit/text-recognition.h +13 -0
  160. package/native/appkit/text-recognition.mm +102 -0
  161. package/native/appkit/tracking.h +13 -0
  162. package/native/appkit/tracking.mm +51 -0
  163. package/native/appkit/tray-and-dock.h +45 -0
  164. package/native/appkit/tray-and-dock.mm +130 -0
  165. package/native/appkit/undo.h +23 -0
  166. package/native/appkit/undo.mm +125 -0
  167. package/native/appkit/updates.h +17 -0
  168. package/native/appkit/updates.mm +71 -0
  169. package/native/appkit/video-view.h +10 -0
  170. package/native/appkit/video-view.mm +42 -0
  171. package/native/appkit/video.h +38 -0
  172. package/native/appkit/video.mm +404 -0
  173. package/native/appkit/web-browser.h +12 -0
  174. package/native/appkit/web-browser.mm +97 -0
  175. package/native/appkit/web-view-component.h +10 -0
  176. package/native/appkit/web-view-component.mm +62 -0
  177. package/native/appkit/web-view.h +31 -0
  178. package/native/appkit/web-view.mm +401 -0
  179. package/native/cmake/libraries/react-native-reanimated.cmake +45 -0
  180. package/native/cmake/libraries/react-native-worklets.cmake +46 -0
  181. package/native/cmake/libraries.cmake +109 -0
  182. package/native/cmake/linked-modules.cmake +112 -0
  183. package/native/cmake/react-native.cmake +175 -0
  184. package/native/cmake/runtime-dependencies.cmake +34 -0
  185. package/native/cmake/swift.cmake +43 -0
  186. package/native/cmake/third-party.cmake +74 -0
  187. package/native/core/include/ngn/absent-views.h +27 -0
  188. package/native/core/include/ngn/accessibility.h +140 -0
  189. package/native/core/include/ngn/address-search.h +69 -0
  190. package/native/core/include/ngn/animation-frames.h +39 -0
  191. package/native/core/include/ngn/app-info.h +52 -0
  192. package/native/core/include/ngn/app-menus.h +151 -0
  193. package/native/core/include/ngn/app-windows.h +181 -0
  194. package/native/core/include/ngn/apple-authentication.h +116 -0
  195. package/native/core/include/ngn/asset.h +28 -0
  196. package/native/core/include/ngn/audio.h +125 -0
  197. package/native/core/include/ngn/back-swipe.h +121 -0
  198. package/native/core/include/ngn/battery.h +48 -0
  199. package/native/core/include/ngn/bytes.h +59 -0
  200. package/native/core/include/ngn/calendar.h +180 -0
  201. package/native/core/include/ngn/camera.h +222 -0
  202. package/native/core/include/ngn/control-sizes.h +111 -0
  203. package/native/core/include/ngn/core-modules.h +108 -0
  204. package/native/core/include/ngn/crypto.h +38 -0
  205. package/native/core/include/ngn/default-menu.h +91 -0
  206. package/native/core/include/ngn/desktop-expo.h +193 -0
  207. package/native/core/include/ngn/desktop-modal.h +109 -0
  208. package/native/core/include/ngn/desktop-props.h +75 -0
  209. package/native/core/include/ngn/desktop-view-props.h +110 -0
  210. package/native/core/include/ngn/dev-server.h +33 -0
  211. package/native/core/include/ngn/dom-web-view.h +53 -0
  212. package/native/core/include/ngn/download.h +24 -0
  213. package/native/core/include/ngn/expo-image.h +192 -0
  214. package/native/core/include/ngn/expo-ui.h +133 -0
  215. package/native/core/include/ngn/file-system.h +274 -0
  216. package/native/core/include/ngn/focus-order.h +63 -0
  217. package/native/core/include/ngn/fonts.h +64 -0
  218. package/native/core/include/ngn/gestures.h +305 -0
  219. package/native/core/include/ngn/glass.h +67 -0
  220. package/native/core/include/ngn/header-bar.h +112 -0
  221. package/native/core/include/ngn/host-state.h +243 -0
  222. package/native/core/include/ngn/image-manipulator.h +70 -0
  223. package/native/core/include/ngn/input-dispatcher.h +211 -0
  224. package/native/core/include/ngn/input-script.h +56 -0
  225. package/native/core/include/ngn/input.h +112 -0
  226. package/native/core/include/ngn/key-value-store.h +41 -0
  227. package/native/core/include/ngn/language-model.h +69 -0
  228. package/native/core/include/ngn/launch-frame.h +47 -0
  229. package/native/core/include/ngn/launch-settings.h +98 -0
  230. package/native/core/include/ngn/layout-animations.h +24 -0
  231. package/native/core/include/ngn/library-components.h +13 -0
  232. package/native/core/include/ngn/library-glue.h +53 -0
  233. package/native/core/include/ngn/live-regions.h +54 -0
  234. package/native/core/include/ngn/local-authentication.h +74 -0
  235. package/native/core/include/ngn/location.h +89 -0
  236. package/native/core/include/ngn/maps.h +226 -0
  237. package/native/core/include/ngn/module-registry.h +51 -0
  238. package/native/core/include/ngn/mounting-backend.h +96 -0
  239. package/native/core/include/ngn/mounting-manager.h +155 -0
  240. package/native/core/include/ngn/native-controls.h +161 -0
  241. package/native/core/include/ngn/native-module.h +109 -0
  242. package/native/core/include/ngn/network-state.h +44 -0
  243. package/native/core/include/ngn/network.h +100 -0
  244. package/native/core/include/ngn/notifications.h +185 -0
  245. package/native/core/include/ngn/photo-library.h +134 -0
  246. package/native/core/include/ngn/printing.h +69 -0
  247. package/native/core/include/ngn/processes.h +114 -0
  248. package/native/core/include/ngn/red-box.h +119 -0
  249. package/native/core/include/ngn/reload-thread.h +258 -0
  250. package/native/core/include/ngn/runtime.h +163 -0
  251. package/native/core/include/ngn/safe-areas.h +82 -0
  252. package/native/core/include/ngn/screen-capture.h +35 -0
  253. package/native/core/include/ngn/screen-presentation.h +85 -0
  254. package/native/core/include/ngn/screen-stacks.h +80 -0
  255. package/native/core/include/ngn/scrollers.h +106 -0
  256. package/native/core/include/ngn/sharing.h +39 -0
  257. package/native/core/include/ngn/spawn-rules.h +78 -0
  258. package/native/core/include/ngn/splash-screen.h +41 -0
  259. package/native/core/include/ngn/split-view.h +270 -0
  260. package/native/core/include/ngn/sqlite.h +38 -0
  261. package/native/core/include/ngn/store-review.h +26 -0
  262. package/native/core/include/ngn/surface-book.h +101 -0
  263. package/native/core/include/ngn/surface-metrics.h +51 -0
  264. package/native/core/include/ngn/svg.h +434 -0
  265. package/native/core/include/ngn/symbol.h +90 -0
  266. package/native/core/include/ngn/system.h +102 -0
  267. package/native/core/include/ngn/tabs-host.h +171 -0
  268. package/native/core/include/ngn/text-input.h +134 -0
  269. package/native/core/include/ngn/text-measurer.h +38 -0
  270. package/native/core/include/ngn/text-recognition.h +55 -0
  271. package/native/core/include/ngn/tracking.h +34 -0
  272. package/native/core/include/ngn/tray-and-dock.h +107 -0
  273. package/native/core/include/ngn/undo.h +37 -0
  274. package/native/core/include/ngn/updates.h +253 -0
  275. package/native/core/include/ngn/video.h +126 -0
  276. package/native/core/include/ngn/view-box.h +126 -0
  277. package/native/core/include/ngn/view-transform.h +26 -0
  278. package/native/core/include/ngn/view-tree.h +85 -0
  279. package/native/core/include/ngn/web-browser.h +45 -0
  280. package/native/core/include/ngn/web-view.h +137 -0
  281. package/native/core/include/ngn/worklet-host.h +98 -0
  282. package/native/core/src/absent-views.cpp +41 -0
  283. package/native/core/src/accessibility.cpp +374 -0
  284. package/native/core/src/animation-frames.cpp +49 -0
  285. package/native/core/src/app-menus.cpp +359 -0
  286. package/native/core/src/app-windows.cpp +444 -0
  287. package/native/core/src/back-swipe.cpp +98 -0
  288. package/native/core/src/bytes.cpp +158 -0
  289. package/native/core/src/control-sizes.cpp +232 -0
  290. package/native/core/src/default-menu.cpp +96 -0
  291. package/native/core/src/desktop-modal.cpp +162 -0
  292. package/native/core/src/desktop-view-props.cpp +80 -0
  293. package/native/core/src/dev-server-helper.cpp +152 -0
  294. package/native/core/src/dev-server.cpp +103 -0
  295. package/native/core/src/dom-web-view.cpp +45 -0
  296. package/native/core/src/download.cpp +53 -0
  297. package/native/core/src/expo-image.cpp +548 -0
  298. package/native/core/src/expo-ui.cpp +203 -0
  299. package/native/core/src/focus-order.cpp +441 -0
  300. package/native/core/src/gestures.cpp +1806 -0
  301. package/native/core/src/glass.cpp +49 -0
  302. package/native/core/src/header-bar.cpp +104 -0
  303. package/native/core/src/host-services.cpp +50 -0
  304. package/native/core/src/host-state.cpp +61 -0
  305. package/native/core/src/input-dispatcher.cpp +727 -0
  306. package/native/core/src/input-script.cpp +123 -0
  307. package/native/core/src/key-value-store.cpp +169 -0
  308. package/native/core/src/launch-settings.cpp +148 -0
  309. package/native/core/src/layout-animations.cpp +62 -0
  310. package/native/core/src/libraries/RNCWebViewSpec.cpp +80 -0
  311. package/native/core/src/libraries/react-native-reanimated.cpp +216 -0
  312. package/native/core/src/libraries/react-native-worklets.cpp +192 -0
  313. package/native/core/src/libraries/rnscreens.cpp +125 -0
  314. package/native/core/src/libraries/rnsvg.cpp +358 -0
  315. package/native/core/src/libraries/safeareacontext.cpp +70 -0
  316. package/native/core/src/libraries/worklets-idle-frames.js +70 -0
  317. package/native/core/src/library-glue.cpp +35 -0
  318. package/native/core/src/live-regions.cpp +122 -0
  319. package/native/core/src/module-registry.cpp +50 -0
  320. package/native/core/src/modules/accessibility-manager.cpp +98 -0
  321. package/native/core/src/modules/address-search.cpp +219 -0
  322. package/native/core/src/modules/alert-manager.cpp +140 -0
  323. package/native/core/src/modules/app-info.cpp +74 -0
  324. package/native/core/src/modules/app-modules.cpp +412 -0
  325. package/native/core/src/modules/apple-authentication.cpp +188 -0
  326. package/native/core/src/modules/asset.cpp +111 -0
  327. package/native/core/src/modules/async-storage.cpp +192 -0
  328. package/native/core/src/modules/audio.cpp +541 -0
  329. package/native/core/src/modules/battery.cpp +88 -0
  330. package/native/core/src/modules/calendar.cpp +457 -0
  331. package/native/core/src/modules/camera.cpp +401 -0
  332. package/native/core/src/modules/core-modules.cpp +62 -0
  333. package/native/core/src/modules/crypto.cpp +117 -0
  334. package/native/core/src/modules/desktop-expo.cpp +527 -0
  335. package/native/core/src/modules/file-system.cpp +941 -0
  336. package/native/core/src/modules/fonts.cpp +163 -0
  337. package/native/core/src/modules/image-loader.cpp +105 -0
  338. package/native/core/src/modules/image-manipulator.cpp +305 -0
  339. package/native/core/src/modules/language-model.cpp +195 -0
  340. package/native/core/src/modules/local-authentication.cpp +140 -0
  341. package/native/core/src/modules/location.cpp +186 -0
  342. package/native/core/src/modules/maps.cpp +500 -0
  343. package/native/core/src/modules/network-state.cpp +72 -0
  344. package/native/core/src/modules/networking.cpp +387 -0
  345. package/native/core/src/modules/notifications.cpp +549 -0
  346. package/native/core/src/modules/photo-library.cpp +385 -0
  347. package/native/core/src/modules/printing.cpp +201 -0
  348. package/native/core/src/modules/screen-capture.cpp +71 -0
  349. package/native/core/src/modules/sharing.cpp +59 -0
  350. package/native/core/src/modules/splash-screen.cpp +70 -0
  351. package/native/core/src/modules/sqlite.cpp +421 -0
  352. package/native/core/src/modules/store-review.cpp +23 -0
  353. package/native/core/src/modules/text-recognition.cpp +107 -0
  354. package/native/core/src/modules/tracking.cpp +46 -0
  355. package/native/core/src/modules/undo.cpp +59 -0
  356. package/native/core/src/modules/video.cpp +366 -0
  357. package/native/core/src/modules/web-browser.cpp +100 -0
  358. package/native/core/src/modules/web-socket.cpp +266 -0
  359. package/native/core/src/mounting-manager.cpp +384 -0
  360. package/native/core/src/native-controls.cpp +129 -0
  361. package/native/core/src/native-module.cpp +250 -0
  362. package/native/core/src/network.cpp +219 -0
  363. package/native/core/src/posix-launcher.cpp +366 -0
  364. package/native/core/src/processes.cpp +324 -0
  365. package/native/core/src/red-box-errors.js +83 -0
  366. package/native/core/src/red-box.cpp +306 -0
  367. package/native/core/src/runtime.cpp +420 -0
  368. package/native/core/src/safe-areas.cpp +137 -0
  369. package/native/core/src/screen-presentation.cpp +61 -0
  370. package/native/core/src/screen-stacks.cpp +254 -0
  371. package/native/core/src/scrollers.cpp +181 -0
  372. package/native/core/src/spawn-rules.cpp +292 -0
  373. package/native/core/src/split-view.cpp +343 -0
  374. package/native/core/src/svg.cpp +2190 -0
  375. package/native/core/src/symbol.cpp +94 -0
  376. package/native/core/src/tabs-host.cpp +234 -0
  377. package/native/core/src/text-input.cpp +139 -0
  378. package/native/core/src/text-layout-manager.cpp +63 -0
  379. package/native/core/src/tray-and-dock.cpp +154 -0
  380. package/native/core/src/updates.cpp +965 -0
  381. package/native/core/src/view-box.cpp +788 -0
  382. package/native/core/src/view-transform.cpp +45 -0
  383. package/native/core/src/view-tree.cpp +234 -0
  384. package/native/core/src/web-view.cpp +143 -0
  385. package/native/core/src/worklet-host.cpp +10 -0
  386. package/native/scripts/build-hermes.sh +44 -0
  387. package/native/scripts/build.sh +175 -0
  388. package/native/scripts/cache-dir.sh +18 -0
  389. package/native/scripts/codegen-library.sh +193 -0
  390. package/native/scripts/compiler-launcher.sh +17 -0
  391. package/native/scripts/fetch.sh +174 -0
  392. package/native/scripts/hermes-built.sh +10 -0
  393. package/native/scripts/host-dir.sh +16 -0
  394. package/native/scripts/launch-probe.sh +60 -0
  395. package/native/scripts/macos-target.sh +8 -0
  396. package/native/scripts/make-prebuilt.mjs +360 -0
  397. package/native/scripts/prebuilt-host-cache.mjs +158 -0
  398. package/native/shim/openssl/sha.h +22 -0
  399. package/native/shim/view-platform/react/renderer/components/view/HostPlatformViewTraitsInitializer.h +37 -0
  400. package/package.json +73 -1
  401. package/prebuilt.json +33 -0
@@ -0,0 +1,1475 @@
1
+ // ngn-macos: the macOS desktop host. Loads a bundle into one runtime, starts the app on a surface
2
+ // that is never shown, and gives each window the app opens (NgNativeWindows) a surface of its own.
3
+ //
4
+ // ngn-macos <bundle> [--module <name>] [--title <title>] [--app-id <id>] [--capabilities <json>]
5
+ // ngn-macos (a packaged app: what its Info.plist names; argv and env are ignored)
6
+ //
7
+ // <bundle> is a JavaScript or Hermes bytecode file on disk, or a Metro bundle URL, which turns on
8
+ // the dev loop: reload and Fast Refresh from the dev server, and the Developer menu. The module
9
+ // defaults to "main", the name an ng-native app registers. The app id names the app's data and
10
+ // preferences until it is packaged with a bundle identifier (default: the title).
11
+ #import <AppKit/AppKit.h>
12
+ #import <QuartzCore/QuartzCore.h>
13
+
14
+ #import "animation-frames.h"
15
+ #import "input-replay.h"
16
+ #include "ngn/gestures.h"
17
+ #include "ngn/worklet-host.h"
18
+ #import "notifications.h"
19
+ #import "undo.h"
20
+ #import "app-windows.h"
21
+ #import "appkit-backend.h"
22
+ #import "header-toolbar.h"
23
+ #import "menu-bar.h"
24
+ #import "modal-host-view.h"
25
+ #import "network.h"
26
+ #import "red-box.h"
27
+ #import "scroll-view.h"
28
+ #import "split-view.h"
29
+ #import "system.h"
30
+ #import "system-access.h"
31
+ #import "desktop-expo.h"
32
+ #import "local-authentication.h"
33
+ #import "location.h"
34
+ #import "crypto.h"
35
+ #import "app-info.h"
36
+ #import "network-state.h"
37
+ #import "battery.h"
38
+ #import "fonts.h"
39
+ #import "web-browser.h"
40
+ #import "text-recognition.h"
41
+ #import "calendar.h"
42
+ #import "audio.h"
43
+ #import "video.h"
44
+ #import "language-model.h"
45
+ #import "screen-capture.h"
46
+ #import "photo-library.h"
47
+ #import "tracking.h"
48
+ #import "image-manipulator.h"
49
+ #import "printing.h"
50
+ #import "expo-image-view.h"
51
+ #import "camera-sheet.h"
52
+ #import "camera-view.h"
53
+ #import "camera.h"
54
+ #import "map-view.h"
55
+ #import "apple-authentication.h"
56
+ #include "ngn/web-view.h"
57
+ #import "geocoder.h"
58
+ #import "address-search.h"
59
+ #include "ngn/asset.h"
60
+ #import "symbol-drawing.h"
61
+ #import "share-picker.h"
62
+ #include "ngn/splash-screen.h"
63
+ #include "ngn/launch-frame.h"
64
+ #import "store-review.h"
65
+ #import "bookmarks.h"
66
+ #import "push.h"
67
+ #import "file-system.h"
68
+ #import "tray-and-dock.h"
69
+ #import "test-launch.h"
70
+ #import "updates.h"
71
+ #import "surface-view.h"
72
+ #import "tab-walk.h"
73
+ #include "text-layout.h"
74
+
75
+ #include "ngn/app-menus.h"
76
+ #include "ngn/back-swipe.h"
77
+ #include "ngn/core-modules.h"
78
+ #include "ngn/default-menu.h"
79
+ #include "ngn/desktop-modal.h"
80
+ #include "ngn/input-dispatcher.h"
81
+ #import "native-controls.h"
82
+ #include "ngn/focus-order.h"
83
+ #include "ngn/layout-animations.h"
84
+ #include "ngn/launch-settings.h"
85
+ #include "ngn/runtime.h"
86
+ #include "ngn/sqlite.h"
87
+
88
+ #include <sys/sysctl.h>
89
+ #include <unistd.h>
90
+
91
+ #include <mutex>
92
+ #include <unordered_map>
93
+ #include <string>
94
+
95
+ using namespace facebook::react;
96
+
97
+ namespace {
98
+
99
+ // The surface the app starts on, which the host never shows: the app renders each window on a
100
+ // surface of its own (app-windows.h).
101
+ constexpr SurfaceId kAppSurface = 1;
102
+
103
+ struct Host {
104
+ std::shared_ptr<ngn::appkit::AppKitBackend> backend;
105
+ std::shared_ptr<ngn::MountingManager> mounting;
106
+ std::unique_ptr<ngn::InputDispatcher> input;
107
+ std::shared_ptr<ngn::HostState> state;
108
+ std::unique_ptr<ngn::Runtime> runtime;
109
+ std::shared_ptr<ngn::appkit::AppKitWindows> windows;
110
+ std::shared_ptr<ngn::WindowHost> windowHost;
111
+ std::shared_ptr<ngn::MenuHost> menus;
112
+ std::shared_ptr<ngn::TrayHost> tray;
113
+ std::shared_ptr<ngn::DockHost> dockHost;
114
+ std::shared_ptr<ngn::appkit::AppKitDock> dock;
115
+ NGNSurfaceView *appSurface;
116
+ // The app's own surface in a window, for an app that renders there instead of opening windows.
117
+ NSWindow *appWindow;
118
+ NSString *title;
119
+ std::shared_ptr<ngn::ProcessLauncher> launcher;
120
+ // Ticks the layout animations while they run, at the display's rate.
121
+ NSTimer *animationTimer;
122
+ bool firstFrameLogged = false;
123
+ // What the host runs and how (launch-settings.h), set once at launch.
124
+ const ngn::LaunchSettings *launch = nullptr;
125
+ // The app window is ordered front once, when its safe areas settle (showAppWindowWhenSettled).
126
+ bool appWindowShown = false;
127
+ // The launch running, the first or a reload's, has yet to put content its own JavaScript
128
+ // instance mounted in a window on screen, which starts its success timer (launch-frame.h).
129
+ ngn::LaunchFrame launchFrame;
130
+ // The Expo Updates client, for a bundle on disk (updates.h).
131
+ std::shared_ptr<ngn::UpdatesClient> updates;
132
+ // Remote notifications: the device token's registration, and where a silent one is heard.
133
+ std::shared_ptr<ngn::PushTokens> push;
134
+ std::shared_ptr<ngn::NotificationEvents> notificationEvents;
135
+ // A dev run's red box (red-box.h).
136
+ std::shared_ptr<ngn::RedBox> redBox;
137
+ };
138
+
139
+ Host gHost;
140
+
141
+ // The bundle the runtime runs now, for SourceCode's scriptURL: set at launch and before a reload
142
+ // into an update, read on the JavaScript thread.
143
+ std::mutex gBundleMutex;
144
+ std::string gBundle;
145
+
146
+ void setRunningBundle(const std::string &bundle) {
147
+ std::lock_guard lock(gBundleMutex);
148
+ gBundle = bundle;
149
+ }
150
+
151
+ ngn::WindowMetrics windowMetrics(NSWindow *window) {
152
+ NSSize size = window.contentView.bounds.size;
153
+ NSSize screen = (window.screen != nil ? window.screen : NSScreen.mainScreen).frame.size;
154
+ double scale = window.backingScaleFactor;
155
+ return {
156
+ .window = {.width = size.width, .height = size.height, .scale = scale, .fontScale = 1},
157
+ .screen = {.width = screen.width, .height = screen.height, .scale = scale, .fontScale = 1},
158
+ };
159
+ }
160
+
161
+ ngn::SurfaceMetrics metricsFor(NSSize size, double scale) {
162
+ return {
163
+ .size = {static_cast<Float>(size.width), static_cast<Float>(size.height)},
164
+ .pointScale = static_cast<float>(scale),
165
+ .fontScale = 1,
166
+ };
167
+ }
168
+
169
+ ngn::SurfaceMetrics metricsFor(NSWindow *window) {
170
+ return metricsFor(window.contentView.bounds.size, window.backingScaleFactor);
171
+ }
172
+
173
+ // Milliseconds since the process started, dyld and all, from the kernel's start time.
174
+ double msSinceLaunch() {
175
+ struct kinfo_proc info {};
176
+ size_t size = sizeof(info);
177
+ int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()};
178
+ if (sysctl(mib, 4, &info, &size, nullptr, 0) != 0) {
179
+ return -1;
180
+ }
181
+ struct timeval now {};
182
+ gettimeofday(&now, nullptr);
183
+ const auto &start = info.kp_proc.p_starttime;
184
+ return (now.tv_sec - start.tv_sec) * 1000.0 + (now.tv_usec - start.tv_usec) / 1000.0;
185
+ }
186
+
187
+ void logFirstFrame(NSWindow *window) {
188
+ if (gHost.firstFrameLogged || window == nil || !window.visible) {
189
+ return;
190
+ }
191
+ gHost.firstFrameLogged = true;
192
+ // Draw now rather than at the end of this run loop pass, so the time covers the first frame.
193
+ [window displayIfNeeded];
194
+ [CATransaction flush];
195
+ fprintf(stderr, "[ngn] first frame %.0f ms after launch\n", msSinceLaunch());
196
+ // A dev run's input script (input-script.h), played into the first window once it shows.
197
+ if (const auto &path = gHost.launch->inputScript; !path.empty() && gHost.runtime && gHost.runtime->devServer()) {
198
+ NSString *text = [NSString stringWithContentsOfFile:@(path.c_str()) encoding:NSUTF8StringEncoding error:nil];
199
+ auto script = ngn::parseInputScript(text ? std::string(text.UTF8String) : std::string());
200
+ if (!text || script.error) {
201
+ fprintf(stderr, "[ngn] input script %s: %s\n", path.c_str(), text ? script.error->c_str() : "cannot be read");
202
+ } else {
203
+ ngn::appkit::replayInputScript(window, std::move(script));
204
+ }
205
+ }
206
+ if (gHost.launch->logRotors) {
207
+ // A second after the first frame, when the app has settled.
208
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(), ^{
209
+ if (auto *surface = (NGNSurfaceView *)window.contentView; [surface isKindOfClass:NGNSurfaceView.class]) {
210
+ fprintf(stderr, "[ngn] rotors\n%s\n", surface.rotorItemsDescription.UTF8String);
211
+ }
212
+ });
213
+ }
214
+ }
215
+
216
+ // Tab and Shift-Tab (tab-walk.h). True when the key is used.
217
+ bool moveFocus(NSEvent *event) {
218
+ // Option-Tab reaches every focusable view, whatever the keyboard navigation setting.
219
+ bool everything = NSApp.isFullKeyboardAccessEnabled || (event.modifierFlags & NSEventModifierFlagOption) != 0;
220
+ auto reach = everything ? ngn::TabReach::All : ngn::TabReach::TextInputs;
221
+ bool backwards = (event.modifierFlags & NSEventModifierFlagShift) != 0;
222
+ return ngn::appkit::moveFocus(event.window, gHost.mounting->tree(), *gHost.backend, backwards, reach);
223
+ }
224
+
225
+ // Arrow keys, Home and End inside a composite widget (a tablist, radiogroup, menu, menubar, listbox
226
+ // or grid), walked in the core (focus-order.h compositeMove). True when the key is used.
227
+ bool moveInComposite(NSEvent *event) {
228
+ static const std::unordered_map<unsigned short, ngn::CompositeKey> keys{
229
+ {123, ngn::CompositeKey::Left}, {124, ngn::CompositeKey::Right}, {125, ngn::CompositeKey::Down},
230
+ {126, ngn::CompositeKey::Up}, {115, ngn::CompositeKey::Home}, {119, ngn::CompositeKey::End},
231
+ };
232
+ auto key = keys.find(event.keyCode);
233
+ auto mods = event.modifierFlags & (NSEventModifierFlagCommand | NSEventModifierFlagOption | NSEventModifierFlagShift);
234
+ if (key == keys.end() || mods != 0) {
235
+ return false;
236
+ }
237
+ NSWindow *window = event.window;
238
+ auto [container, focused] = ngn::appkit::focusContext(window);
239
+ if (container == nil || focused == nil || window.firstResponder != focused) {
240
+ return false;
241
+ }
242
+ bool control = (event.modifierFlags & NSEventModifierFlagControl) != 0;
243
+ auto next = ngn::compositeMove(
244
+ gHost.mounting->tree(), container.rootTag, static_cast<Tag>(focused.reactTag), key->second, control);
245
+ if (!next) {
246
+ return false;
247
+ }
248
+ if (NGNView *view = gHost.backend->view(*next); view != nil && view != focused) {
249
+ [window makeFirstResponder:view.keyboardResponder];
250
+ }
251
+ return true;
252
+ }
253
+
254
+ // The surface of the window `window` is, or belongs to (a sheet's or a popover's parent), if any.
255
+ std::optional<SurfaceId> surfaceOf(NSWindow *window) {
256
+ for (NSWindow *w = window; w != nil; w = w.sheetParent != nil ? w.sheetParent : w.parentWindow) {
257
+ if (auto surface = gHost.windows->surfaceOf(w)) {
258
+ return surface;
259
+ }
260
+ }
261
+ return std::nullopt;
262
+ }
263
+
264
+ void reloadLaunched(uint64_t generation, uint64_t instance);
265
+ void reloadSameLaunch();
266
+
267
+ // The menu bar the core asks for, drawn on the main thread.
268
+ struct AppKitMenus final : ngn::MenuBackend {
269
+ void setMenuBar(std::vector<ngn::MenuItem> bar) override {
270
+ auto shared = std::make_shared<std::vector<ngn::MenuItem>>(std::move(bar));
271
+ dispatch_async(dispatch_get_main_queue(), ^{
272
+ ngn::appkit::installMenuBar(*shared, [](const ngn::MenuItem &item) {
273
+ if (item.command == ngn::MenuCommand::Reload && gHost.runtime) {
274
+ reloadSameLaunch();
275
+ } else if (item.command == ngn::MenuCommand::OpenDevTools && gHost.runtime) {
276
+ gHost.runtime->openDebugger();
277
+ } else if (gHost.menus) {
278
+ gHost.menus->choose(item, surfaceOf(NSApp.keyWindow));
279
+ }
280
+ });
281
+ });
282
+ }
283
+ };
284
+
285
+ // A key press as the web names it, with the modifiers held.
286
+ ngn::KeyChord chordOf(NSEvent *event) {
287
+ static NSDictionary<NSNumber *, NSString *> *named = @{
288
+ @123 : @"ArrowLeft", @124 : @"ArrowRight", @125 : @"ArrowDown", @126 : @"ArrowUp",
289
+ @36 : @"Enter", @76 : @"Enter", @53 : @"Escape", @51 : @"Backspace", @117 : @"Delete",
290
+ @48 : @"Tab", @115 : @"Home", @119 : @"End", @116 : @"PageUp", @121 : @"PageDown",
291
+ @122 : @"F1", @120 : @"F2", @99 : @"F3", @118 : @"F4", @96 : @"F5", @97 : @"F6",
292
+ @98 : @"F7", @100 : @"F8", @101 : @"F9", @109 : @"F10", @103 : @"F11", @111 : @"F12",
293
+ };
294
+ NSString *key = named[@(event.keyCode)];
295
+ if (key == nil) {
296
+ // Shift still applies, as the web's `key` has it: shift+/ is "?".
297
+ key = event.charactersIgnoringModifiers != nil ? event.charactersIgnoringModifiers : @"";
298
+ }
299
+ unsigned modifiers = 0;
300
+ NSEventModifierFlags flags = event.modifierFlags;
301
+ if (flags & NSEventModifierFlagCommand) modifiers |= ngn::Command;
302
+ if (flags & NSEventModifierFlagShift) modifiers |= ngn::Shift;
303
+ if (flags & NSEventModifierFlagOption) modifiers |= ngn::Option;
304
+ if (flags & NSEventModifierFlagControl) modifiers |= ngn::Control;
305
+ return {.key = std::string(key.UTF8String), .modifiers = modifiers};
306
+ }
307
+
308
+ bool textInputFocused(NSWindow *window) {
309
+ return [window.firstResponder isKindOfClass:NSText.class];
310
+ }
311
+
312
+ // Whether a horizontal scroll at the event belongs to a scroll view that scrolls sideways.
313
+ bool scrollsSideways(NSEvent *event, NSWindow *window) {
314
+ // A replayed scroll the window takes itself has no window, and its location is on the screen.
315
+ NSPoint point = event.window == window ? event.locationInWindow : [window convertPointFromScreen:event.locationInWindow];
316
+ NSView *hit = [window.contentView hitTest:[window.contentView.superview convertPoint:point fromView:nil]];
317
+ for (NSView *v = hit; v != nil; v = v.superview) {
318
+ if ([v isKindOfClass:NSScrollView.class]) {
319
+ NSScrollView *scroll = (NSScrollView *)v;
320
+ if (NSWidth(scroll.documentView.frame) > NSWidth(scroll.contentView.bounds) + 1) {
321
+ return true;
322
+ }
323
+ }
324
+ }
325
+ return false;
326
+ }
327
+
328
+ void navigate(ngn::NavigationDirection direction, NSWindow *window) {
329
+ if (gHost.menus) {
330
+ gHost.menus->navigate(direction, surfaceOf(window));
331
+ }
332
+ }
333
+
334
+ // The interactive back swipe (back-swipe.h) in flight, and the screens it moves.
335
+ struct Swipe {
336
+ ngn::BackSwipe swipe;
337
+ NGNView *top;
338
+ NGNView *below;
339
+ NSWindow *window;
340
+ SurfaceId surface = 0;
341
+ // The direction the swipe began in, which its later moves keep though a reload changes the app's.
342
+ bool rightToLeft = false;
343
+ // The momentum scrolls after a swipe's fingers lift are the swipe's, not the content's.
344
+ bool swallowMomentum = false;
345
+ // Bumped as a swipe starts or ends, so a late animation step or timeout of an old one stops.
346
+ int generation = 0;
347
+ NSTimer *animation;
348
+ };
349
+ Swipe gSwipe;
350
+
351
+ void drawSwipe(const ngn::BackSwipeFrame &frame) {
352
+ gSwipe.top.swipeOffset = frame.offset;
353
+ gSwipe.top.swipeOpacity = frame.opacity;
354
+ gSwipe.below.swipeShown = frame.belowShown;
355
+ }
356
+
357
+ // The swipe is over: every screen as layout and the stack put it.
358
+ void endSwipe() {
359
+ [gSwipe.animation invalidate];
360
+ gSwipe.animation = nil;
361
+ drawSwipe(ngn::BackSwipe::rest());
362
+ gSwipe.top = nil;
363
+ gSwipe.below = nil;
364
+ gSwipe.window = nil;
365
+ gSwipe.surface = 0;
366
+ gSwipe.generation++;
367
+ }
368
+
369
+ // A window closed: a swipe in it ends, whatever its phase, or it would hold every later swipe.
370
+ void swipeWindowClosed(SurfaceId surface) {
371
+ if (gSwipe.window != nil && gSwipe.surface == surface) {
372
+ gSwipe.swipe.abandon();
373
+ endSwipe();
374
+ }
375
+ }
376
+
377
+ // Eases the moving screen from where it is to `to` over a fifth of a second, then calls `done`.
378
+ void animateSwipe(ngn::BackSwipeFrame to, void (^done)(void)) {
379
+ [gSwipe.animation invalidate];
380
+ ngn::BackSwipeFrame from{
381
+ .offset = gSwipe.top.swipeOffset, .opacity = gSwipe.top.swipeOpacity, .belowShown = gSwipe.below.swipeShown == YES};
382
+ CFTimeInterval start = CACurrentMediaTime();
383
+ constexpr CFTimeInterval kDuration = 0.2;
384
+ gSwipe.animation = [NSTimer scheduledTimerWithTimeInterval:1.0 / 120 repeats:YES block:^(NSTimer *timer) {
385
+ double t = std::min(1.0, (CACurrentMediaTime() - start) / kDuration);
386
+ double eased = 1 - (1 - t) * (1 - t) * (1 - t);
387
+ drawSwipe({.offset = from.offset + (to.offset - from.offset) * eased,
388
+ .opacity = from.opacity + (to.opacity - from.opacity) * eased,
389
+ .belowShown = to.belowShown || from.belowShown});
390
+ if (t >= 1) {
391
+ [timer invalidate];
392
+ gSwipe.animation = nil;
393
+ if (done != nil) {
394
+ done();
395
+ }
396
+ }
397
+ }];
398
+ }
399
+
400
+ // How far the fingers moved right: AppKit's delta moves the content, which follows the fingers
401
+ // only with natural scrolling.
402
+ double fingersMovedRight(NSEvent *event) {
403
+ return event.isDirectionInvertedFromDevice ? event.scrollingDeltaX : -event.scrollingDeltaX;
404
+ }
405
+
406
+ // Whether the app lays out right to left, which turns the swipes round: left goes back.
407
+ bool swipesRightToLeft() {
408
+ return gHost.runtime && gHost.runtime->laysOutRightToLeft();
409
+ }
410
+
411
+ // The fingers lifted from a tracking swipe: it goes back, or slides home.
412
+ void liftSwipe(NSEvent *event) {
413
+ bool back = gSwipe.swipe.lifted(event.phase == NSEventPhaseCancelled);
414
+ if (!back) {
415
+ animateSwipe(gSwipe.swipe.settled(), ^{
416
+ gSwipe.swipe.returned();
417
+ endSwipe();
418
+ });
419
+ return;
420
+ }
421
+ animateSwipe(gSwipe.swipe.settled(), nil);
422
+ auto surface = surfaceOf(gSwipe.window);
423
+ if (surface && gHost.menus->history(*surface)) {
424
+ gHost.menus->navigate(ngn::NavigationDirection::Back, surface);
425
+ } else if (auto emitter = gSwipe.top.eventEmitter) {
426
+ // An app that reports no history: the stack's own back, as the back chevron sends it.
427
+ emitter->dispatchEvent("headerBackButtonClicked");
428
+ }
429
+ // A back the app refused (a guard) never pops: the screen comes home.
430
+ int generation = gSwipe.generation;
431
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
432
+ if (gSwipe.generation == generation && gSwipe.swipe.phase() == ngn::BackSwipe::Phase::Leaving) {
433
+ gSwipe.swipe.abandon();
434
+ animateSwipe(ngn::BackSwipe::rest(), ^{
435
+ endSwipe();
436
+ });
437
+ }
438
+ });
439
+ }
440
+
441
+ // A leaving swipe ends once its stack's top screen has changed.
442
+ void swipeMounted() {
443
+ const auto &target = gSwipe.swipe.target();
444
+ if (target && gSwipe.swipe.mounted(gHost.mounting->stackTop(target->stack))) {
445
+ endSwipe();
446
+ }
447
+ }
448
+
449
+ // "Swipe between pages" with two fingers: a sideways scroll that nothing scrolls sideways. A back
450
+ // swipe over a stack with a screen below drags the screen in front; any other goes when it ends.
451
+ // Answers the event to send on, or nil where the swipe took it.
452
+ NSEvent *swipeScroll(NSEvent *event, NSWindow *window) {
453
+ if (event.phase == NSEventPhaseBegan && gSwipe.swipe.fingersDown()) {
454
+ endSwipe();
455
+ }
456
+ if (gSwipe.swipe.phase() == ngn::BackSwipe::Phase::Tracking) {
457
+ if (window != gSwipe.window) {
458
+ return event;
459
+ }
460
+ double dx = ngn::towardsBack(fingersMovedRight(event), gSwipe.rightToLeft);
461
+ if (dx != 0) {
462
+ drawSwipe(gSwipe.swipe.moved(dx));
463
+ }
464
+ if (event.phase == NSEventPhaseEnded || event.phase == NSEventPhaseCancelled) {
465
+ liftSwipe(event);
466
+ }
467
+ return nil;
468
+ }
469
+ if (event.momentumPhase != NSEventPhaseNone && gSwipe.swallowMomentum) {
470
+ return nil;
471
+ }
472
+ if (!NSEvent.isSwipeTrackingFromScrollEventsEnabled || event.phase != NSEventPhaseBegan) {
473
+ return event;
474
+ }
475
+ gSwipe.swallowMomentum = false;
476
+ auto surface = surfaceOf(window);
477
+ if (fabs(event.scrollingDeltaX) <= fabs(event.scrollingDeltaY) || !surface || scrollsSideways(event, window)) {
478
+ return event;
479
+ }
480
+ // Without a history from the app, the stack in front decides.
481
+ auto history = gHost.menus->history(*surface);
482
+ bool canGoBack = !history || !history->back.empty();
483
+ bool canGoForward = !history || !history->forward.empty();
484
+ bool rightToLeft = swipesRightToLeft();
485
+ double dx = ngn::towardsBack(fingersMovedRight(event), rightToLeft);
486
+ if (dx > 0 && canGoBack && gSwipe.swipe.phase() == ngn::BackSwipe::Phase::Idle) {
487
+ auto target = gHost.mounting->backSwipeTarget(*surface);
488
+ NGNView *top = target ? gHost.backend->view(target->top) : nil;
489
+ NGNView *below = target ? gHost.backend->view(target->below) : nil;
490
+ if (top != nil && below != nil && gSwipe.swipe.begin(target, NSWidth(top.bounds), rightToLeft)) {
491
+ endSwipe();
492
+ gSwipe.top = top;
493
+ gSwipe.below = below;
494
+ gSwipe.window = window;
495
+ gSwipe.surface = *surface;
496
+ gSwipe.rightToLeft = rightToLeft;
497
+ gSwipe.swallowMomentum = true;
498
+ drawSwipe(gSwipe.swipe.moved(dx));
499
+ return nil;
500
+ }
501
+ }
502
+ auto bounds = ngn::swipeBounds(canGoBack, canGoForward, rightToLeft);
503
+ if (bounds == ngn::SwipeBounds{}) {
504
+ return event;
505
+ }
506
+ [event trackSwipeEventWithOptions:NSEventSwipeTrackingLockDirection
507
+ dampenAmountThresholdMin:bounds.min
508
+ max:bounds.max
509
+ usingHandler:^(CGFloat amount, NSEventPhase phase, BOOL complete, BOOL *stop) {
510
+ if (phase == NSEventPhaseEnded && amount != 0) {
511
+ navigate(*ngn::navigationFor(
512
+ amount > 0 ? ngn::NavigationInput::SwipeRight : ngn::NavigationInput::SwipeLeft,
513
+ rightToLeft),
514
+ window);
515
+ }
516
+ }];
517
+ return event;
518
+ }
519
+
520
+ // An app that renders on its own surface rather than opening windows (one that is not an
521
+ // ng-native app with AppWindows) gets that surface in a window once it has something on it.
522
+ void showAppWindow();
523
+
524
+ // A launch counts once its window has been up this long: an update that crashes before then is
525
+ // rolled back at the next launch (updates.h).
526
+ constexpr int64_t kLaunchSuccessDelay = 10 * NSEC_PER_SEC;
527
+
528
+ void markLaunchSucceededLater(uint64_t generation) {
529
+ if (!gHost.updates || !gHost.updates->running()) {
530
+ return;
531
+ }
532
+ // For this launch only: a reload since begins another, with a timer of its own.
533
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kLaunchSuccessDelay), dispatch_get_main_queue(), ^{
534
+ gHost.updates->markLaunchSucceeded(generation);
535
+ });
536
+ }
537
+
538
+ // Whether the surface has content on screen in `window`.
539
+ bool showsContent(SurfaceId surface, NSWindow *window) {
540
+ const auto *root = gHost.mounting->tree().find(surface);
541
+ return window != nil && window.visible && root != nullptr && !root->children.empty();
542
+ }
543
+
544
+ // A window shows the surface's content: the launch's first, mounted by its own JavaScript instance
545
+ // while it is still the launch running, starts the launch's success timer. Main thread.
546
+ void launchFrameShown(SurfaceId surface, NSWindow *window) {
547
+ if (!gHost.updates || !showsContent(surface, window)) {
548
+ return;
549
+ }
550
+ if (auto generation = gHost.launchFrame.shown(gHost.mounting->mountedBy(surface), gHost.updates->launchGeneration())) {
551
+ markLaunchSucceededLater(*generation);
552
+ }
553
+ }
554
+
555
+ // A reload's bundle (the launch `generation`) loaded into the JavaScript instance `instance`: its
556
+ // launch counts from its first frame on screen, which may already be there or come with a later
557
+ // mount. Main thread.
558
+ void reloadLaunched(uint64_t generation, uint64_t instance) {
559
+ gHost.launchFrame.loaded(generation, instance);
560
+ launchFrameShown(kAppSurface, gHost.appWindow);
561
+ for (NSWindow *window in NSApp.windows) {
562
+ if (SurfaceId surface = gHost.windows ? gHost.windows->surfaceOf(window) : 0) {
563
+ launchFrameShown(surface, window);
564
+ }
565
+ }
566
+ }
567
+
568
+ // The menu's or the red box's reload: the same launch, in a new instance. Its first frame, if still
569
+ // owed, comes from that instance once the bundle loads; the instance it replaces owes nothing from
570
+ // now, and nothing does if the bundle does not load. Main thread.
571
+ void reloadSameLaunch() {
572
+ uint64_t generation = gHost.updates ? gHost.updates->launchGeneration() : 0;
573
+ gHost.launchFrame.reloadBegan();
574
+ gHost.runtime->reload([generation](bool loaded) {
575
+ if (!loaded) {
576
+ fprintf(stderr, "ngn-macos: the reload could not load the bundle\n");
577
+ return;
578
+ }
579
+ uint64_t instance = gHost.mounting->instance();
580
+ dispatch_async(dispatch_get_main_queue(), ^{
581
+ reloadLaunched(generation, instance);
582
+ });
583
+ });
584
+ }
585
+
586
+ // The splash screen: the first windows wait for the app to hide it (NgNativeSplashScreen).
587
+ std::shared_ptr<ngn::SplashGate> gSplash = std::make_shared<ngn::SplashGate>();
588
+
589
+ // Runs a window's first show now, or on the main thread once the app hides the splash screen.
590
+ void showPastSplash(std::function<void()> show) {
591
+ gSplash->show([show = std::move(show)] {
592
+ if (NSThread.isMainThread) {
593
+ show();
594
+ } else {
595
+ dispatch_async(dispatch_get_main_queue(), ^{
596
+ show();
597
+ });
598
+ }
599
+ });
600
+ }
601
+
602
+ void showAppSurfaceIfUsed() {
603
+ const auto *root = gHost.mounting->tree().find(kAppSurface);
604
+ if (gHost.appWindow != nil || root == nullptr || root->children.empty()) {
605
+ return;
606
+ }
607
+ NSRect visible = NSScreen.mainScreen.visibleFrame;
608
+ gHost.appWindow = [[NSWindow alloc]
609
+ initWithContentRect:gHost.appSurface.frame
610
+ styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable |
611
+ NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskFullSizeContentView
612
+ backing:NSBackingStoreBuffered
613
+ defer:NO];
614
+ gHost.appWindow.releasedWhenClosed = NO;
615
+ gHost.appWindow.title = gHost.title;
616
+ gHost.appWindow.delegate = (id<NSWindowDelegate>)NSApp.delegate;
617
+ gHost.appWindow.contentView = gHost.appSurface;
618
+ [gHost.appWindow setFrameTopLeftPoint:NSMakePoint(NSMinX(visible) + 40, NSMaxY(visible) - 40)];
619
+ // Shown once the content has the insets of the title bar and toolbar it runs under and its native
620
+ // controls their measured sizes, a commit or two later, or after kSettleWait at the latest: shown
621
+ // at once, its first frames would draw under the toolbar and then jump down.
622
+ constexpr int64_t kSettleWait = 300 * NSEC_PER_MSEC;
623
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kSettleWait), dispatch_get_main_queue(), ^{
624
+ showAppWindow();
625
+ });
626
+ }
627
+
628
+ // SIGTERM (a test pool ending its run, or `kill`) ends the host as a clean quit does, after asking
629
+ // the app to run its `willQuit` hooks, though not its `canClose` guards, for at most
630
+ // WindowHost::kTerminateSeconds: the programs it started go with it and a test launch removes what
631
+ // it leaves behind. A main thread that does not get to it within kTermWait is not waited for.
632
+ void endOnTerminateSignal() {
633
+ constexpr int64_t kTermWait = 2500 * NSEC_PER_MSEC;
634
+ signal(SIGTERM, SIG_IGN);
635
+ static dispatch_source_t source =
636
+ dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGTERM, 0, dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0));
637
+ dispatch_source_set_event_handler(source, ^{
638
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kTermWait), dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
639
+ _exit(0);
640
+ });
641
+ dispatch_async(dispatch_get_main_queue(), ^{
642
+ auto end = [] {
643
+ [NSApp.delegate applicationWillTerminate:[NSNotification notificationWithName:NSApplicationWillTerminateNotification
644
+ object:NSApp]];
645
+ exit(0);
646
+ };
647
+ if (gHost.windowHost) {
648
+ // The app's answer arrives on the JavaScript thread; the host ends on the main one.
649
+ gHost.windowHost->terminateRequested([end] { dispatch_async(dispatch_get_main_queue(), end); });
650
+ } else {
651
+ end();
652
+ }
653
+ });
654
+ });
655
+ dispatch_resume(source);
656
+ }
657
+
658
+ void showAppWindow() {
659
+ if (gHost.appWindowShown || gHost.appWindow == nil) {
660
+ return;
661
+ }
662
+ gHost.appWindowShown = true;
663
+ showPastSplash([] {
664
+ ngn::appkit::showWindow(gHost.appWindow);
665
+ logFirstFrame(gHost.appWindow);
666
+ launchFrameShown(kAppSurface, gHost.appWindow);
667
+ });
668
+ }
669
+
670
+ } // namespace
671
+
672
+ // The source of a `[dragItem]` view's drag out: a file url per file, and the text and url on one
673
+ // more item. Finder takes the files, a text field the text, a browser the url. The picks the files
674
+ // read stay open until the session ends.
675
+ @interface NGNDragOutSource : NSObject <NSDraggingSource>
676
+ + (void)begin:(const ngn::DragOutItem &)item from:(NSView *)view event:(NSEvent *)event;
677
+ @end
678
+
679
+ @implementation NGNDragOutSource {
680
+ std::vector<std::shared_ptr<ngn::FileAccess::Use>> _uses;
681
+ }
682
+ + (void)begin:(const ngn::DragOutItem &)item from:(NSView *)view event:(NSEvent *)event {
683
+ static NGNDragOutSource *source = [NGNDragOutSource new];
684
+ // The view as it is drawn, under the pointer where the press started.
685
+ NSBitmapImageRep *rep = [view bitmapImageRepForCachingDisplayInRect:view.bounds];
686
+ NSImage *image = nil;
687
+ if (rep != nil) {
688
+ [view cacheDisplayInRect:view.bounds toBitmapImageRep:rep];
689
+ image = [[NSImage alloc] initWithSize:view.bounds.size];
690
+ [image addRepresentation:rep];
691
+ }
692
+ NSMutableArray<NSDraggingItem *> *items = [NSMutableArray array];
693
+ auto add = [&](id<NSPasteboardWriting> writer) {
694
+ NSDraggingItem *dragging = [[NSDraggingItem alloc] initWithPasteboardWriter:writer];
695
+ [dragging setDraggingFrame:view.bounds contents:image];
696
+ [items addObject:dragging];
697
+ };
698
+ for (const auto &file : item.files) {
699
+ if (NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:file.c_str()]]) {
700
+ add(url);
701
+ }
702
+ }
703
+ if (item.text || item.url) {
704
+ NSPasteboardItem *extra = [NSPasteboardItem new];
705
+ if (item.url) {
706
+ [extra setString:[NSString stringWithUTF8String:item.url->c_str()] forType:NSPasteboardTypeURL];
707
+ }
708
+ const std::string &text = item.text ? *item.text : *item.url;
709
+ [extra setString:[NSString stringWithUTF8String:text.c_str()] forType:NSPasteboardTypeString];
710
+ add(extra);
711
+ }
712
+ if (items.count > 0) {
713
+ source->_uses = item.uses;
714
+ [view beginDraggingSessionWithItems:items event:event source:source];
715
+ }
716
+ }
717
+ - (NSDragOperation)draggingSession:(NSDraggingSession *)session
718
+ sourceOperationMaskForDraggingContext:(NSDraggingContext)context {
719
+ return NSDragOperationCopy | NSDragOperationGeneric;
720
+ }
721
+ - (void)draggingSession:(NSDraggingSession *)session
722
+ endedAtPoint:(NSPoint)screenPoint
723
+ operation:(NSDragOperation)operation {
724
+ _uses.clear();
725
+ }
726
+ @end
727
+
728
+ @interface NGNAppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate>
729
+ @end
730
+
731
+ @implementation NGNAppDelegate {
732
+ BOOL _launched;
733
+ }
734
+ - (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window {
735
+ return ngn::appkit::undoManagerFor(window);
736
+ }
737
+ - (void)applicationDidFinishLaunching:(NSNotification *)note {
738
+ _launched = YES;
739
+ }
740
+ // Open With, a drop on the Dock icon and a double click on one of the app's document types in
741
+ // Finder: each file reaches Linking (DeepLinks) as its file:// url. Links to the app's scheme come
742
+ // through the AppleEvent handler (system.mm) instead.
743
+ - (void)application:(NSApplication *)app openURLs:(NSArray<NSURL *> *)urls {
744
+ for (NSURL *url in urls) {
745
+ NSURL *plain = url.isFileReferenceURL ? url.filePathURL : url;
746
+ if (plain.absoluteString != nil && gHost.state) {
747
+ gHost.state->receiveUrl(plain.absoluteString.UTF8String, _launched);
748
+ }
749
+ }
750
+ }
751
+ // The app decides (AppWindows and provideAppLifecycle): closing the last window never quits.
752
+ - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)app {
753
+ return gHost.appWindow != nil;
754
+ }
755
+ - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
756
+ switch (gHost.windowHost->quitRequested()) {
757
+ case ngn::QuitReply::Now:
758
+ return NSTerminateNow;
759
+ case ngn::QuitReply::Later:
760
+ return NSTerminateLater;
761
+ case ngn::QuitReply::Cancel:
762
+ return NSTerminateCancel;
763
+ }
764
+ return NSTerminateNow;
765
+ }
766
+ // The app's own items above the Dock menu's standard ones.
767
+ - (NSMenu *)applicationDockMenu:(NSApplication *)sender {
768
+ return gHost.dock ? gHost.dock->menu() : nil;
769
+ }
770
+ - (BOOL)applicationShouldHandleReopen:(NSApplication *)sender hasVisibleWindows:(BOOL)visible {
771
+ gHost.windowHost->reopen(visible);
772
+ return YES;
773
+ }
774
+ // APNs' answers to registerForRemoteNotifications (push.mm), for the core's PushTokens.
775
+ - (void)application:(NSApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token {
776
+ if (gHost.push) {
777
+ gHost.push->registered(std::string(static_cast<const char *>(token.bytes), token.length));
778
+ }
779
+ }
780
+ - (void)application:(NSApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
781
+ if (gHost.push) {
782
+ gHost.push->failed(error.localizedDescription.UTF8String);
783
+ }
784
+ }
785
+ // Every remote notification while the app runs. One with an alert is heard through the
786
+ // notification centre's delegate as it is presented (notifications.mm); a silent one only here.
787
+ - (void)application:(NSApplication *)app didReceiveRemoteNotification:(NSDictionary<NSString *, id> *)userInfo {
788
+ auto payload = ngn::appkit::pushPayload(userInfo);
789
+ if (gHost.notificationEvents && ngn::silentPush(payload)) {
790
+ gHost.notificationEvents->received(
791
+ NSDate.date.timeIntervalSince1970 * 1000, ngn::remoteNotificationRequest(NSUUID.UUID.UUIDString.UTF8String, payload));
792
+ }
793
+ }
794
+ - (void)applicationWillTerminate:(NSNotification *)note {
795
+ ngn::appkit::endTestLaunch();
796
+ // A clean quit is no crash: the update running is not rolled back, however soon it quit.
797
+ if (gHost.updates) {
798
+ gHost.updates->markLaunchSucceeded();
799
+ }
800
+ // The programs the app started go with it, rather than run on with no one to read them.
801
+ if (gHost.launcher) {
802
+ gHost.launcher->killAll(SIGKILL);
803
+ }
804
+ // Stop the surfaces and the runtime before exit tears down what they still use.
805
+ if (gHost.runtime) {
806
+ gHost.runtime->shutdown();
807
+ }
808
+ // The surface views still hold the input sink as exit destroys the host: it lives on until the
809
+ // process ends, so none of them reaches a sink that is gone.
810
+ (void)gHost.input.release();
811
+ }
812
+ // The app's own surface, when it is in a window.
813
+ - (void)windowDidResize:(NSNotification *)note {
814
+ if (gHost.runtime) {
815
+ gHost.runtime->updateSurface(kAppSurface, metricsFor(gHost.appWindow));
816
+ }
817
+ gHost.state->metrics.set(windowMetrics(gHost.appWindow));
818
+ }
819
+ - (void)windowDidChangeBackingProperties:(NSNotification *)note {
820
+ [self windowDidResize:note];
821
+ }
822
+ @end
823
+
824
+ int main(int argc, const char *argv[]) {
825
+ @autoreleasepool {
826
+ // What to run: argv and the environment in a dev run, and only the Info.plist in a packaged
827
+ // app (launch-settings.h).
828
+ NSDictionary *info = NSBundle.mainBundle.infoDictionary;
829
+ std::vector<std::string> args(argv + 1, argv + argc);
830
+ auto launch = ngn::launchSettings({
831
+ .args = args,
832
+ .env = [](const std::string &name) -> std::optional<std::string> {
833
+ const char *value = getenv(name.c_str());
834
+ return value != nullptr ? std::optional<std::string>(value) : std::nullopt;
835
+ },
836
+ .plist = [info](const std::string &key) -> std::optional<std::string> {
837
+ NSString *value = info[[NSString stringWithUTF8String:key.c_str()]];
838
+ return [value isKindOfClass:NSString.class] ? std::optional<std::string>(value.UTF8String) : std::nullopt;
839
+ },
840
+ .resourcePath = NSBundle.mainBundle.resourcePath != nil ? NSBundle.mainBundle.resourcePath.UTF8String : "",
841
+ });
842
+ if (auto *usage = std::get_if<std::string>(&launch)) {
843
+ fprintf(stderr, "%s\n", usage->c_str());
844
+ return 2;
845
+ }
846
+ static const auto settings = std::get<ngn::LaunchSettings>(launch);
847
+ gHost.launch = &settings;
848
+ std::string bundle = settings.bundle;
849
+ std::string module = settings.module;
850
+ NSString *title = [NSString stringWithUTF8String:settings.title.c_str()];
851
+ std::string appId = settings.appId;
852
+ std::string capabilities = settings.capabilitiesJson;
853
+ ngn::appkit::beginTestLaunch(settings.test);
854
+
855
+ NSApplication *app = NSApplication.sharedApplication;
856
+ // A test launch has no Dock icon, and never takes focus, until a test asks for the key window.
857
+ app.activationPolicy = settings.test ? NSApplicationActivationPolicyAccessory : NSApplicationActivationPolicyRegular;
858
+ endOnTerminateSignal();
859
+ NGNAppDelegate *delegate = [NGNAppDelegate new];
860
+ app.delegate = delegate;
861
+
862
+ gHost.backend = std::make_shared<ngn::appkit::AppKitBackend>();
863
+ gHost.mounting = std::make_shared<ngn::MountingManager>(gHost.backend, gHost.backend);
864
+ gHost.input = std::make_unique<ngn::InputDispatcher>(gHost.mounting->tree());
865
+ ngn::appkit::installWorkletHost(gHost.mounting);
866
+ // react-native-gesture-handler's recognisers over the view tree, fed by the input dispatcher,
867
+ // their timers on the main queue.
868
+ static auto gestures = std::make_shared<ngn::Gestures>(
869
+ gHost.mounting->tree(), [](double ms, std::function<void()> fn) -> std::function<void()> {
870
+ auto cancelled = std::make_shared<std::atomic<bool>>(false);
871
+ auto shared = std::make_shared<std::function<void()>>(std::move(fn));
872
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, static_cast<int64_t>(ms * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
873
+ if (!*cancelled) {
874
+ (*shared)();
875
+ }
876
+ });
877
+ return [cancelled] { *cancelled = true; };
878
+ });
879
+ gHost.input->setGestures(gestures.get());
880
+ // A worklet gesture's events go to Reanimated's handlers on the UI runtime, and a worklet's
881
+ // state manager comes back to the recognisers, while Reanimated is running.
882
+ gestures->onWorkletEvent = [](const std::string &name, Tag view, const folly::dynamic &body) {
883
+ ngn::workletHost().reanimatedEvent.call(name, view, body);
884
+ };
885
+ ngn::workletHost().setGestureState = [](int handlerTag, int state) { gestures->setState(handlerTag, state); };
886
+ // Each commit's time, for the performance budget (pnpm bench:macos), when asked for: every
887
+ // frame of an animation commits, which would flood a dev run's terminal.
888
+ if (settings.logCommits) {
889
+ gHost.mounting->onCommit = [](SurfaceId, double ms) { fprintf(stderr, "[ngn] commit %.1f ms\n", ms); };
890
+ }
891
+ gHost.backend->onMount = [](SurfaceId surfaceId) {
892
+ gHost.input->didMount(surfaceId);
893
+ swipeMounted();
894
+ if (surfaceId == kAppSurface) {
895
+ showAppSurfaceIfUsed();
896
+ if (gHost.mounting->safeAreasSettled() && gHost.mounting->controlSizesSettled()) {
897
+ showAppWindow();
898
+ }
899
+ launchFrameShown(surfaceId, gHost.appWindow);
900
+ } else {
901
+ // Its first show logs the first frame and may start the success timer (the shown hook).
902
+ gHost.windows->didMount(surfaceId);
903
+ launchFrameShown(surfaceId, gHost.windows->window(surfaceId));
904
+ }
905
+ };
906
+ gHost.input->onCursor = [](ngn::Cursor cursor) { [NGNSurfaceView showCursor:cursor]; };
907
+ // A press that became a drag out of a `[dragItem]` view: the mouse event that crossed the
908
+ // threshold starts the session, which has the mouse from there.
909
+ gHost.input->onDragOut = [](Tag tag, const ngn::PointerInput &, const ngn::DragOutItem &item) {
910
+ NSView *view = gHost.backend->view(tag);
911
+ NSEvent *event = NSApp.currentEvent;
912
+ if (view != nil && event != nil && event.type == NSEventTypeLeftMouseDragged) {
913
+ [NGNDragOutSource begin:item from:view event:event];
914
+ }
915
+ };
916
+ NGNModalHostView.input = gHost.input.get();
917
+ NGNView.activator = gHost.input.get();
918
+ // The focus into a modal as it opens: the first view in its Tab order.
919
+ NGNModalHostView.initialFocus = [](NSInteger tag) -> NSResponder * {
920
+ auto reach = NSApp.isFullKeyboardAccessEnabled ? ngn::TabReach::All : ngn::TabReach::TextInputs;
921
+ auto first = ngn::nextInTabOrder(gHost.mounting->tree(), static_cast<Tag>(tag), std::nullopt, false, reach);
922
+ NGNView *view = first ? gHost.backend->view(*first) : nil;
923
+ return view.keyboardResponder;
924
+ };
925
+ NGNModalHostView.presentationChanged = [](NSInteger tag, BOOL presented) {
926
+ if (presented) {
927
+ gHost.mounting->tree().addContainerRoot(static_cast<Tag>(tag));
928
+ } else {
929
+ gHost.mounting->tree().removeContainerRoot(static_cast<Tag>(tag));
930
+ }
931
+ };
932
+ NGNSurfaceView.insetsChanged = [](Tag root, std::optional<ngn::ContainerInsets> insets) {
933
+ if (insets) {
934
+ gHost.mounting->setContainerInsets(root, *insets);
935
+ } else {
936
+ gHost.mounting->removeContainerInsets(root);
937
+ }
938
+ };
939
+ NGNHeaderToolbar.input = gHost.input.get();
940
+ NGNHeaderToolbar.containerRootChanged = [](NSInteger tag, BOOL isRoot) {
941
+ if (isRoot) {
942
+ gHost.mounting->tree().addContainerRoot(static_cast<Tag>(tag));
943
+ } else {
944
+ gHost.mounting->tree().removeContainerRoot(static_cast<Tag>(tag));
945
+ }
946
+ };
947
+ NGNSplitView.input = gHost.input.get();
948
+ NGNSplitView.containerRootChanged = NGNHeaderToolbar.containerRootChanged;
949
+ NGNSplitView.rowContentTakesClick = [](NSInteger row, NSPoint point) {
950
+ const auto &tree = gHost.mounting->tree();
951
+ auto chain = tree.hitTest(static_cast<Tag>(row), {static_cast<Float>(point.x), static_cast<Float>(point.y)});
952
+ return ngn::rowContentTakesClick(tree, chain);
953
+ };
954
+ NGNTabsHostView.tabChosen = [](NSInteger surface, NSInteger host, NSInteger screen) {
955
+ gHost.mounting->chooseTab(static_cast<SurfaceId>(surface), static_cast<Tag>(host), static_cast<Tag>(screen));
956
+ };
957
+ NGNModalHostView.sheetSizer = [](NSInteger surface, NSInteger tag, NSSize window) {
958
+ ngn::SheetNode empty;
959
+ auto node = gHost.runtime ? gHost.runtime->sheetNode(static_cast<SurfaceId>(surface), static_cast<Tag>(tag))
960
+ : std::nullopt;
961
+ auto size = ngn::sheetSize(
962
+ node ? *node : empty, {static_cast<Float>(window.width), static_cast<Float>(window.height)});
963
+ return NSMakeSize(size.width, size.height);
964
+ };
965
+ NGNModalHostView.popoverSizer = [](NSInteger surface, NSInteger tag, NSSize window) {
966
+ auto node = gHost.runtime ? gHost.runtime->sheetNode(static_cast<SurfaceId>(surface), static_cast<Tag>(tag))
967
+ : std::nullopt;
968
+ auto size = node ? ngn::popoverSize(*node, {static_cast<Float>(window.width), static_cast<Float>(window.height)})
969
+ : facebook::react::Size{0, 0};
970
+ return NSMakeSize(size.width, size.height);
971
+ };
972
+ NGNModalHostView.viewForTag = [](NSInteger tag) -> NSView * {
973
+ return gHost.backend->view(static_cast<Tag>(tag));
974
+ };
975
+ NGNScrollView.offsetChanged = [](NSInteger tag, CGPoint offset) {
976
+ gHost.mounting->tree().setScrollOffset(
977
+ static_cast<Tag>(tag), {static_cast<Float>(offset.x), static_cast<Float>(offset.y)});
978
+ };
979
+
980
+ gHost.title = title;
981
+ NSRect frame = NSMakeRect(0, 0, ngn::kDefaultWindowWidth, ngn::kDefaultWindowHeight);
982
+ gHost.appSurface = [[NGNSurfaceView alloc] initWithFrame:frame surfaceId:kAppSurface input:gHost.input.get()];
983
+ gHost.backend->addSurface(gHost.appSurface);
984
+
985
+ if (appId.empty()) {
986
+ appId = std::string(title.UTF8String);
987
+ }
988
+ auto system = ngn::appkit::makeSystem(appId);
989
+ gHost.state = std::make_shared<ngn::HostState>();
990
+ {
991
+ NSSize screen = NSScreen.mainScreen.frame.size;
992
+ double scale = NSScreen.mainScreen.backingScaleFactor;
993
+ gHost.state->metrics.set({
994
+ .window = {.width = frame.size.width, .height = frame.size.height, .scale = scale, .fontScale = 1},
995
+ .screen = {.width = screen.width, .height = screen.height, .scale = scale, .fontScale = 1},
996
+ });
997
+ }
998
+ if (!settings.initialUrl.empty()) {
999
+ gHost.state->setInitialUrl(settings.initialUrl);
1000
+ }
1001
+ ngn::appkit::watchApp(gHost.state, system);
1002
+ ngn::NetworkClients network{ngn::appkit::makeHttp(), ngn::appkit::makeWebSockets()};
1003
+ // The capabilities the app declares, for the process.
1004
+ static auto processes = ngn::appkit::processesSetup(capabilities);
1005
+ static auto caches = ngn::appkit::cacheDirectory(appId);
1006
+ // The one set of rules for every path JavaScript names (FileSystem, a request body, ImageEditor
1007
+ // and the other modules that read a file): the app's folders, the user's picks, the declared
1008
+ // paths (none in a Mac App Store build, whose sandbox reaches only picks) and, for assets, a
1009
+ // packaged app's bundle.
1010
+ static auto fileAccess = [&] {
1011
+ auto folders = ngn::appkit::fileFolders(system->appDataDirectory(), caches);
1012
+ if (settings.packaged && NSBundle.mainBundle.resourcePath != nil) {
1013
+ folders.bundle = NSBundle.mainBundle.resourcePath.UTF8String;
1014
+ } else if (auto path = ngn::pathOfUri(bundle); path && !settings.packaged) {
1015
+ // A dev run of an exported bundle on disk: its assets are beside it.
1016
+ folders.bundle = [NSString stringWithUTF8String:path->c_str()].stringByDeletingLastPathComponent.UTF8String;
1017
+ }
1018
+ auto access = std::make_shared<ngn::FileAccess>(
1019
+ folders, processes.sandboxed ? folly::dynamic::array() : processes.capabilities.paths);
1020
+ // Picks persist across launches through bookmarks, one store per app; a test launch starts
1021
+ // with none and keeps none.
1022
+ if (!settings.test) {
1023
+ access->keepPicks(std::make_shared<ngn::PickStore>(
1024
+ ngn::appkit::pickPersistence("NGNPickedPaths." + appId), ngn::appkit::makeBookmarks()));
1025
+ }
1026
+ return access;
1027
+ }();
1028
+ // The views that load a source JavaScript names (images, players' views, web views, a drag out)
1029
+ // check it against the same rules.
1030
+ ngn::useViewFileAccess(fileAccess);
1031
+ // Kept for the process: ReactHost asks it for modules on every reload.
1032
+ static auto modules = std::make_shared<ngn::ModuleRegistry>();
1033
+ ngn::addCoreModules(
1034
+ *modules,
1035
+ {.system = system,
1036
+ .state = gHost.state,
1037
+ .http = network.http,
1038
+ .webSockets = network.webSockets,
1039
+ .files = fileAccess,
1040
+ .reactNativeVersion = NGN_REACT_NATIVE_VERSION,
1041
+ .bundle = [] {
1042
+ std::lock_guard lock(gBundleMutex);
1043
+ return gBundle;
1044
+ },
1045
+ // VoiceOver goes where the layout-changed notification points it; a view that takes the
1046
+ // keyboard takes it too, as setAccessibilityFocus moves both on iOS's keyboard.
1047
+ .focusAccessibility = [](int tag) {
1048
+ dispatch_async(dispatch_get_main_queue(), ^{
1049
+ NGNView *view = gHost.backend ? gHost.backend->view(tag) : nil;
1050
+ if (view == nil || view.window == nil) {
1051
+ return;
1052
+ }
1053
+ if (view.acceptsFirstResponder) {
1054
+ [view.window makeFirstResponder:view];
1055
+ }
1056
+ NSAccessibilityPostNotificationWithUserInfo(
1057
+ view.window, NSAccessibilityLayoutChangedNotification, @{NSAccessibilityUIElementsKey : @[ view ]});
1058
+ });
1059
+ },
1060
+ .fakeSystemUI = settings.test && settings.test->fakeSystemUI,
1061
+ .gestures = gestures,
1062
+ .runOnUiThread = [](std::function<void()> task) {
1063
+ auto shared = std::make_shared<std::function<void()>>(std::move(task));
1064
+ dispatch_async(dispatch_get_main_queue(), ^{
1065
+ (*shared)();
1066
+ });
1067
+ }});
1068
+
1069
+ gHost.windows = std::make_shared<ngn::appkit::AppKitWindows>(ngn::appkit::AppKitWindows::Hooks{
1070
+ .makeSurface = [](SurfaceId surface, NSRect bounds) -> NGNSurfaceView * {
1071
+ NGNSurfaceView *view = [[NGNSurfaceView alloc] initWithFrame:bounds surfaceId:surface input:gHost.input.get()];
1072
+ gHost.backend->addSurface(view);
1073
+ return view;
1074
+ },
1075
+ .startSurface = [](SurfaceId surface, NSWindow *window) {
1076
+ gHost.runtime->startSurface(surface, "", metricsFor(window));
1077
+ },
1078
+ .resizeSurface = [](SurfaceId surface, NSWindow *window) {
1079
+ gHost.runtime->updateSurface(surface, metricsFor(window));
1080
+ },
1081
+ .stopSurface = [](SurfaceId surface) {
1082
+ swipeWindowClosed(surface);
1083
+ gHost.menus->forgetHistory(surface);
1084
+ gHost.runtime->stopSurface(surface);
1085
+ gHost.backend->removeSurface(surface);
1086
+ },
1087
+ .keyWindowChanged = [](NSWindow *window) { gHost.state->metrics.set(windowMetrics(window)); },
1088
+ .whenShown = [](std::function<void()> show) { showPastSplash(std::move(show)); },
1089
+ // Shown once the splash lets it go, which may be after its last commit: the first frame's
1090
+ // actions and the launch's success timer start from here.
1091
+ .shown =
1092
+ [](NSWindow *window) {
1093
+ logFirstFrame(window);
1094
+ launchFrameShown(gHost.windows->surfaceOf(window), window);
1095
+ },
1096
+ });
1097
+ gHost.windowHost = std::make_shared<ngn::WindowHost>(gHost.windows, system);
1098
+ gHost.windows->setHost(gHost.windowHost);
1099
+ ngn::addModule(*modules, "NgNativeWindows", [] { return ngn::makeWindowsModule(gHost.windowHost); });
1100
+
1101
+ gHost.menus = std::make_shared<ngn::MenuHost>(
1102
+ std::make_shared<AppKitMenus>(),
1103
+ ngn::DefaultMenuOptions{
1104
+ .appName = std::string(title.UTF8String), .developer = ngn::DevServer::fromBundleUrl(bundle).has_value()});
1105
+ ngn::addModule(*modules, "NgNativeMenus", [] { return ngn::makeMenusModule(gHost.menus); });
1106
+ // Each window's history, as the app's router reports it, for its toolbar's chevrons.
1107
+ gHost.menus->historyChanged = [](SurfaceId surface) {
1108
+ dispatch_async(dispatch_get_main_queue(), ^{
1109
+ gHost.backend->setHistory(surface, gHost.menus->history(surface));
1110
+ });
1111
+ };
1112
+ gHost.backend->historyOf = [](SurfaceId surface) { return gHost.menus->history(surface); };
1113
+ NGNHeaderToolbar.navigate = [](NSWindow *window, ngn::NavigationDirection direction, int steps) {
1114
+ gHost.menus->navigate(direction, surfaceOf(window), steps);
1115
+ };
1116
+ // File > Print with no print item of the app's: what the window shows (printing.h).
1117
+ gHost.menus->printWindow = [](std::optional<SurfaceId> surface) {
1118
+ NSWindow *window = surface ? (*surface == kAppSurface ? gHost.appWindow : gHost.windows->window(*surface)) : nil;
1119
+ ngn::appkit::printWindow(window != nil ? window : NSApp.keyWindow, false, [](const std::string &error) {
1120
+ if (!error.empty()) {
1121
+ fprintf(stderr, "[ngn] print: %s\n", error.c_str());
1122
+ }
1123
+ });
1124
+ };
1125
+ gHost.tray = std::make_shared<ngn::TrayHost>(std::make_shared<ngn::appkit::AppKitTray>(
1126
+ [](const std::string &icon) { gHost.tray->press(icon); },
1127
+ [](const std::string &icon, const std::string &id) { gHost.tray->menuSelect(icon, id); }));
1128
+ ngn::addModule(*modules, "NgNativeTray", [] { return ngn::makeTrayModule(gHost.tray); });
1129
+ gHost.dock = std::make_shared<ngn::appkit::AppKitDock>([](const std::string &id) { gHost.dockHost->menuSelect(id); });
1130
+ gHost.dockHost = std::make_shared<ngn::DockHost>(gHost.dock);
1131
+ ngn::addModule(*modules, "NgNativeDock", [] { return ngn::makeDockModule(gHost.dockHost); });
1132
+ {
1133
+ // One launcher and one declaration for the process: a reload gets a new module over them.
1134
+ static auto launcher = ngn::makePosixLauncher();
1135
+ gHost.launcher = launcher;
1136
+ static auto opener = ngn::appkit::makeShellOpener();
1137
+ ngn::addModule(*modules, "NgNativeProcesses", [] { return ngn::makeProcessesModule(launcher, processes); });
1138
+ ngn::addModule(*modules, "NgNativeShell", [] { return ngn::makeShellModule(opener, fileAccess); });
1139
+ // The desktop Expo modules (DESKTOP_MODULES in @ng-native/expo).
1140
+ static std::shared_ptr<ngn::SecretStore> keychain = ngn::appkit::makeKeychain();
1141
+ static auto keychainService = appId;
1142
+ if (settings.test) {
1143
+ // The run's own items, removed as it ends, and any a crashed run left.
1144
+ ngn::appkit::removeStaleTestItems(*settings.test);
1145
+ auto prefixed = std::make_shared<ngn::PrefixedSecretStore>(keychain, settings.test->keychainPrefix());
1146
+ ngn::appkit::onTestLaunchEnd([prefixed] { prefixed->clear(); });
1147
+ keychain = prefixed;
1148
+ }
1149
+ static auto expoSystem = system;
1150
+ static auto awake = std::make_shared<ngn::KeepAwakeTags>(ngn::appkit::makeSleepPreventer());
1151
+ static auto haptics = ngn::appkit::makeHapticPlayer();
1152
+ ngn::addModule(*modules, "NgNativeSecureStore", [] { return ngn::makeSecureStoreModule(keychain, keychainService); });
1153
+ ngn::addModule(*modules, "NgNativeClipboard", [] { return ngn::makeDesktopClipboardModule(expoSystem, gHost.state); });
1154
+ static auto notificationEvents = std::make_shared<ngn::NotificationEvents>();
1155
+ static auto notifications = ngn::appkit::makeNotificationCenter(notificationEvents);
1156
+ static auto pushTokens = std::make_shared<ngn::PushTokens>(ngn::appkit::makePushRegistrar(), notificationEvents);
1157
+ gHost.push = pushTokens;
1158
+ gHost.notificationEvents = notificationEvents;
1159
+ ngn::addModule(*modules, "NgNativeNotifications", [] {
1160
+ return ngn::makeNotificationsModule(notifications, notificationEvents, pushTokens);
1161
+ });
1162
+ static auto undo = ngn::appkit::makeUndoManager();
1163
+ ngn::addModule(*modules, "NgNativeUndo", [] { return ngn::makeUndoModule(undo); });
1164
+ ngn::addModule(*modules, "NgNativeKeepAwake", [] { return ngn::makeKeepAwakeModule(awake); });
1165
+ ngn::addModule(*modules, "NgNativeHaptics", [] { return ngn::makeHapticsModule(haptics); });
1166
+ static auto dialogs = settings.test && settings.test->fakeSystemUI ? ngn::makeDismissedFileDialogs()
1167
+ : ngn::appkit::makeFileDialogs();
1168
+ static auto fileWatcher = ngn::appkit::makeFileWatcher();
1169
+ ngn::addModule(*modules, "NgNativeFileSystem", [] { return ngn::makeFileSystemModule(fileAccess, fileWatcher); });
1170
+ ngn::addModule(*modules, "NgNativeDocumentPicker", [] { return ngn::makeDocumentPickerModule(dialogs, caches, fileAccess); });
1171
+ // expo-sqlite keeps its databases in the app's documents, under SQLite; here, in its data.
1172
+ static auto databases = system->appDataDirectory() + "/SQLite";
1173
+ ngn::addModule(*modules, "NgNativeSqlite", [] { return ngn::makeSqliteModule(databases, fileAccess); });
1174
+ static auto location = ngn::appkit::makeLocationSource();
1175
+ static bool noPrompts = settings.noPrompts;
1176
+ static auto geocoder = ngn::appkit::makeGeocoder();
1177
+ ngn::addModule(*modules, "NgNativeLocation", [] { return ngn::makeLocationModule(location, noPrompts, geocoder); });
1178
+ static auto authenticator = ngn::appkit::makeAuthenticator(noPrompts);
1179
+ ngn::addModule(*modules, "NgNativeLocalAuthentication", [] { return ngn::makeLocalAuthenticationModule(authenticator); });
1180
+ static auto bundleFacts = ngn::appkit::mainBundleFacts();
1181
+ static auto appName = std::string(title.UTF8String);
1182
+ ngn::addModule(*modules, "NgNativeApplication", [] { return ngn::makeApplicationModule(bundleFacts, keychainService, appName); });
1183
+ static auto machine = ngn::appkit::machineFacts();
1184
+ ngn::addModule(*modules, "NgNativeDevice", [] { return ngn::makeDeviceModule(machine); });
1185
+ static auto pathMonitor = ngn::appkit::makePathMonitor();
1186
+ ngn::addModule(*modules, "NgNativeNetwork", [] { return ngn::makeNetworkModule(pathMonitor); });
1187
+ static auto power = ngn::appkit::makePowerSource();
1188
+ ngn::addModule(*modules, "NgNativeBattery", [] { return ngn::makeBatteryModule(power); });
1189
+ // The fonts loaded stay registered for the process, so their names outlast a reload too.
1190
+ static auto fontLibrary = std::make_shared<ngn::FontLibrary>();
1191
+ static auto fontRegistrar = ngn::appkit::makeFontRegistrar();
1192
+ static auto fontHttp = network.http;
1193
+ ngn::useFontLibrary(fontLibrary);
1194
+ ngn::addModule(*modules, "NgNativeFont", [] {
1195
+ return ngn::makeFontModule(fontRegistrar, fontLibrary, fontHttp, caches + "/fonts", fileAccess);
1196
+ });
1197
+ static auto authSession = ngn::appkit::makeAuthSession();
1198
+ ngn::addModule(*modules, "NgNativeWebBrowser", [] { return ngn::makeWebBrowserModule(expoSystem, authSession, noPrompts); });
1199
+ static auto textReader = ngn::appkit::makeTextReader();
1200
+ ngn::addModule(*modules, "NgNativeTextRecognition", [] { return ngn::makeTextRecognitionModule(textReader, fileAccess); });
1201
+ static auto calendars = ngn::appkit::makeCalendarStore();
1202
+ ngn::addModule(*modules, "NgNativeCalendar", [] { return ngn::makeCalendarModule(calendars, noPrompts); });
1203
+ // Players and recorders end with the runtime: a reload stops what the app played.
1204
+ static auto audioOutput = ngn::appkit::makeAudioOutput();
1205
+ static auto audioInput = ngn::appkit::makeAudioInput();
1206
+ ngn::addModule(*modules, "NgNativeAudio", [] { return ngn::makeAudioModule(audioOutput, audioInput, caches + "/Audio", noPrompts, fileAccess); });
1207
+ static auto videoOutput = ngn::appkit::makeVideoOutput();
1208
+ ngn::addModule(*modules, "NgNativeVideo", [] { return ngn::makeVideoModule(videoOutput, fileAccess); });
1209
+ static auto languageModel = ngn::appkit::makeLanguageModelEngine();
1210
+ ngn::addModule(*modules, "NgNativeLocalLlm", [] { return ngn::makeLocalLlmModule(languageModel); });
1211
+ ngn::addModule(*modules, "NgNativeScreenCapture", [] { return ngn::makeScreenCaptureModule(ngn::appkit::captureShield()); });
1212
+ ngn::addModule(*modules, "NgNativeSplashScreen", [] { return ngn::makeSplashScreenModule(gSplash); });
1213
+ static auto photos = ngn::appkit::makePhotoLibrary(caches);
1214
+ ngn::addModule(*modules, "NgNativeMediaLibrary", [] { return ngn::makeMediaLibraryModule(photos, noPrompts, fileAccess); });
1215
+ static auto cameraHardware = ngn::appkit::makeCameraHardware();
1216
+ static auto cameraSheet = ngn::appkit::makeCameraSheet();
1217
+ ngn::addModule(*modules, "NgNativeImagePicker", [] {
1218
+ return ngn::makeImagePickerModule(photos, noPrompts, ngn::PickerCamera{.hardware = cameraHardware, .microphone = audioInput, .sheet = cameraSheet, .folder = caches + "/ImagePicker"});
1219
+ });
1220
+ static auto tracking = ngn::appkit::makeTrackingAuthority();
1221
+ ngn::addModule(*modules, "NgNativeTrackingTransparency", [] { return ngn::makeTrackingModule(tracking, noPrompts); });
1222
+ static auto imageHttp = network.http;
1223
+ static auto addressLookup = ngn::appkit::makeAddressLookup();
1224
+ ngn::addModule(*modules, "NgNativeAddressSearch", [] { return ngn::makeAddressSearchModule(addressLookup); });
1225
+ ngn::addModule(*modules, "NgNativeAsset", [] { return ngn::makeAssetModule(imageHttp, caches, fileAccess); });
1226
+ static auto symbolMeasurer = ngn::appkit::makeSymbolMeasurer();
1227
+ ngn::addModule(*modules, "NgNativeSymbol", [] { return ngn::makeSymbolModule(symbolMeasurer); });
1228
+ static auto sharePicker = ngn::appkit::makeSharePicker();
1229
+ ngn::addModule(*modules, "NgNativeSharing", [] { return ngn::makeSharingModule(sharePicker, noPrompts, fileAccess); });
1230
+ static auto imageCodec = ngn::appkit::makeImageCodec();
1231
+ ngn::addModule(*modules, "NgNativeImageManipulator", [] {
1232
+ return ngn::makeImageManipulatorModule(imageCodec, imageHttp, caches + "/ImageManipulator", fileAccess);
1233
+ });
1234
+ // <expo-image>'s bytes: 64 MB of them in memory, the rest on disk in the caches.
1235
+ [NGNExpoImageView useHttp:imageHttp cache:std::make_shared<ngn::ImageCache>(caches + "/ExpoImage", 64 << 20)];
1236
+ static auto cameraViews = std::make_shared<ngn::CameraViews>();
1237
+ [NGNCameraView useHardware:cameraHardware views:cameraViews noPrompts:noPrompts];
1238
+ ngn::addModule(*modules, "NgNativeCamera", [] { return ngn::makeCameraModule(cameraHardware, cameraViews, caches + "/Camera", noPrompts); });
1239
+ static auto mapViews = std::make_shared<ngn::MapViews>();
1240
+ [NGNMapView useViews:mapViews location:location];
1241
+ ngn::addModule(*modules, "NgNativeMaps", [] { return ngn::makeMapsModule(mapViews); });
1242
+ // Sign in with Apple: available only to an app signed with its entitlement.
1243
+ static auto appleId = ngn::appkit::makeAppleIdProvider();
1244
+ ngn::addModule(*modules, "NgNativeAppleAuthentication", [] { return ngn::makeAppleAuthenticationModule(appleId, noPrompts); });
1245
+ static auto printSystem = ngn::appkit::makePrintSystem([](SurfaceId surface) -> NSWindow * {
1246
+ return surface == kAppSurface ? gHost.appWindow : gHost.windows->window(surface);
1247
+ });
1248
+ ngn::addModule(*modules, "NgNativePrint", [] { return ngn::makePrintModule(printSystem, imageHttp, caches + "/Print", fileAccess, noPrompts); });
1249
+ // react-native-webview's navigation answers; harmless in a host built without the library.
1250
+ ngn::addModule(*modules, "RNCWebViewModule", [] { return ngn::makeWebViewModule(ngn::sharedNavigationLocks()); });
1251
+ // A rating prompt only in a Mac App Store build: one sandboxed but shipped another way has none.
1252
+ static auto packaged = ngn::appkit::packagedApp();
1253
+ static auto reviewPrompt = ngn::appkit::makeReviewPrompt(packaged && packaged->distribution == "mas");
1254
+ ngn::addModule(*modules, "NgNativeStoreReview", [] { return ngn::makeStoreReviewModule(reviewPrompt, noPrompts); });
1255
+ static auto crypto = ngn::appkit::makeCryptoSource();
1256
+ ngn::addModule(*modules, "NgNativeCrypto", [] { return ngn::makeCryptoModule(crypto); });
1257
+ static auto locales = ngn::appkit::makeLocaleSource();
1258
+ ngn::addModule(*modules, "NgNativeLocalization", [] {
1259
+ return ngn::makeLocalizationModule(locales, ngn::appkit::systemRegionCode());
1260
+ });
1261
+ }
1262
+
1263
+ // A bundle on disk runs the newest update the Expo Updates client keeps, when the app has an
1264
+ // updates URL; one from a dev server never does.
1265
+ {
1266
+ bool fromDevServer = ngn::DevServer::fromBundleUrl(bundle).has_value();
1267
+ gHost.updates = std::make_shared<ngn::UpdatesClient>(
1268
+ ngn::updatesConfigFrom(settings, system->appDataDirectory(), bundle), network.http, ngn::appkit::makeUpdateCrypto());
1269
+ if (!fromDevServer && gHost.updates->enabled()) {
1270
+ bundle = gHost.updates->launch();
1271
+ if (auto running = gHost.updates->running()) {
1272
+ fprintf(stderr, "[ngn] running update %s\n", running->id.c_str());
1273
+ }
1274
+ }
1275
+ // Sparkle starts with the app, as its own updater does: one for the process.
1276
+ static auto appUpdater = ngn::appkit::makeSparkleUpdater();
1277
+ ngn::addModule(*modules, "NgNativeUpdates", [fromDevServer] {
1278
+ return ngn::makeUpdatesModule(gHost.updates, fromDevServer, [](const std::string &next, std::function<void(bool)> done) {
1279
+ setRunningBundle(next);
1280
+ // The launch the module's beginReload just began.
1281
+ uint64_t generation = gHost.updates->launchGeneration();
1282
+ gHost.runtime->reload(next, [next, done, generation](bool loaded) {
1283
+ if (!loaded) {
1284
+ fprintf(stderr, "ngn-macos: the update's bundle %s did not load\n", next.c_str());
1285
+ }
1286
+ // A bundle that did not load never counts as a launch that succeeded; one that did counts
1287
+ // from the first frame its own instance mounts on screen.
1288
+ if (loaded) {
1289
+ uint64_t instance = gHost.mounting->instance();
1290
+ dispatch_async(dispatch_get_main_queue(), ^{
1291
+ reloadLaunched(generation, instance);
1292
+ });
1293
+ }
1294
+ done(loaded);
1295
+ });
1296
+ }, appUpdater);
1297
+ });
1298
+ }
1299
+
1300
+ setRunningBundle(bundle);
1301
+ gHost.runtime = std::make_unique<ngn::Runtime>(
1302
+ gHost.mounting,
1303
+ std::make_shared<ngn::CoreTextMeasurer>(),
1304
+ std::make_shared<ngn::appkit::AppKitControlMeasurer>(),
1305
+ modules, network, bundle,
1306
+ ngn::DebuggerIdentity{
1307
+ .appId = appId,
1308
+ .deviceName = NSHost.currentHost.localizedName ? NSHost.currentHost.localizedName.UTF8String : "Mac"});
1309
+ // Each surface lays out the way I18nManager.isRTL says for the instance running, read again
1310
+ // as a reload starts the next.
1311
+ gHost.runtime->rightToLeft = [system] { return ngn::appRightToLeft(*system); };
1312
+ // The first launch owes its first frame from the instance the runtime just began.
1313
+ gHost.launchFrame.loaded(gHost.updates->launchGeneration(), gHost.mounting->instance());
1314
+
1315
+ bool developer = gHost.runtime->devServer().has_value();
1316
+ if (developer) {
1317
+ const auto &server = *gHost.runtime->devServer();
1318
+ gHost.redBox = std::make_shared<ngn::RedBox>(
1319
+ ngn::appkit::makeRedBoxWindow({
1320
+ .dismiss = [] { gHost.redBox->dismiss(); },
1321
+ .reload =
1322
+ [] {
1323
+ gHost.redBox->reloaded();
1324
+ reloadSameLaunch();
1325
+ },
1326
+ .step = [](int delta) { gHost.redBox->step(delta); },
1327
+ }),
1328
+ network.http,
1329
+ server.scheme + "://" + server.host + ":" + std::to_string(server.port));
1330
+ std::weak_ptr<ngn::RedBox> redBox = gHost.redBox;
1331
+ gHost.runtime->onJsError = [redBox](const folly::dynamic &data) {
1332
+ auto box = redBox.lock();
1333
+ auto error = data.getDefault("source") == "console" ? ngn::jsErrorFromConsole(data) : ngn::jsErrorFrom(data);
1334
+ if (box && error) {
1335
+ box->report(std::move(*error));
1336
+ }
1337
+ };
1338
+ gHost.runtime->onDebuggerPaused = [](std::function<void()> resume) {
1339
+ ngn::appkit::showDebuggerPaused(std::move(resume));
1340
+ };
1341
+ gHost.runtime->onDebuggerResumed = [] { ngn::appkit::hideDebuggerPaused(); };
1342
+ gHost.runtime->onInstanceStart = [redBox] {
1343
+ if (auto box = redBox.lock()) {
1344
+ box->reloaded();
1345
+ }
1346
+ };
1347
+ }
1348
+ // VoiceOver's rotors list what the core's walk of the tree finds (accessibility.h).
1349
+ NGNSurfaceView.rotorViews = [](Tag root, ngn::AxRotor kind) -> NSArray<NSView *> * {
1350
+ NSMutableArray<NSView *> *views = [NSMutableArray array];
1351
+ for (auto tag : ngn::rotorItems(gHost.mounting->tree(), root, kind)) {
1352
+ if (NSView *view = gHost.backend->view(tag)) {
1353
+ [views addObject:view];
1354
+ }
1355
+ }
1356
+ return views;
1357
+ };
1358
+ NGNSurfaceView.contextMenuShower = [](NGNSurfaceView *view, NSEvent *event, const ngn::PointerInput &input) {
1359
+ auto target = gHost.input->contextMenuAt(input);
1360
+ if (!target) {
1361
+ return false;
1362
+ }
1363
+ Tag tag = target->tag;
1364
+ NSWindow *window = view.window;
1365
+ NSMenu *menu = ngn::appkit::buildMenu("", target->items, [tag, window](const ngn::MenuItem &item) {
1366
+ if (item.command == ngn::MenuCommand::Back || item.command == ngn::MenuCommand::Forward) {
1367
+ navigate(item.command == ngn::MenuCommand::Back ? ngn::NavigationDirection::Back
1368
+ : ngn::NavigationDirection::Forward,
1369
+ window);
1370
+ } else {
1371
+ gHost.input->contextMenuSelect(tag, item.id);
1372
+ }
1373
+ });
1374
+ [NSMenu popUpContextMenu:menu withEvent:event forView:view];
1375
+ return true;
1376
+ };
1377
+
1378
+ ngn::onLayoutAnimationsRunning([](bool running) {
1379
+ dispatch_async(dispatch_get_main_queue(), ^{
1380
+ if (running && gHost.animationTimer == nil) {
1381
+ gHost.animationTimer = [NSTimer timerWithTimeInterval:1.0 / 120
1382
+ repeats:YES
1383
+ block:^(NSTimer *) {
1384
+ if (gHost.runtime) {
1385
+ gHost.runtime->animationTick();
1386
+ }
1387
+ }];
1388
+ [NSRunLoop.mainRunLoop addTimer:gHost.animationTimer forMode:NSRunLoopCommonModes];
1389
+ } else if (!running) {
1390
+ [gHost.animationTimer invalidate];
1391
+ gHost.animationTimer = nil;
1392
+ }
1393
+ });
1394
+ });
1395
+
1396
+ // The event beat: React Native's RunLoopObserverManager wants a tick when the UI thread is about
1397
+ // to go idle, which is the main run loop about to wait (the approach Basalt takes).
1398
+ CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler(
1399
+ kCFAllocatorDefault, kCFRunLoopBeforeWaiting, true, 2000000, ^(CFRunLoopObserverRef, CFRunLoopActivity) {
1400
+ if (gHost.runtime) {
1401
+ gHost.runtime->beat();
1402
+ }
1403
+ });
1404
+ CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopCommonModes);
1405
+
1406
+ if (!gHost.runtime->loadBundle()) {
1407
+ if (developer) {
1408
+ fprintf(stderr,
1409
+ "ngn-macos: could not load %s. Is the dev server running? Start it with npm start.\n",
1410
+ bundle.c_str());
1411
+ } else {
1412
+ fprintf(stderr, "ngn-macos: could not load %s\n", bundle.c_str());
1413
+ }
1414
+ return 1;
1415
+ }
1416
+ gHost.runtime->startSurface(
1417
+ kAppSurface, module, metricsFor(frame.size, NSScreen.mainScreen.backingScaleFactor));
1418
+
1419
+ [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown
1420
+ handler:^NSEvent *(NSEvent *event) {
1421
+ // The app's shortcuts come before the menus' keys.
1422
+ if (gHost.menus->keyDown(chordOf(event), textInputFocused(event.window))) {
1423
+ return nil;
1424
+ }
1425
+ constexpr unsigned short kTab = 48;
1426
+ auto mods = event.modifierFlags &
1427
+ (NSEventModifierFlagCommand | NSEventModifierFlagControl);
1428
+ if (event.keyCode == kTab && mods == 0 && moveFocus(event)) {
1429
+ return nil;
1430
+ }
1431
+ if (moveInComposite(event)) {
1432
+ return nil;
1433
+ }
1434
+ return event;
1435
+ }];
1436
+ // A chevron's history list on a secondary click (a long press is the control's own).
1437
+ [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskRightMouseDown
1438
+ handler:^NSEvent *(NSEvent *event) {
1439
+ return [NGNHeaderToolbar showHistoryMenuForEvent:event] ? nil : event;
1440
+ }];
1441
+ // Back and forward from the mouse's side buttons and the trackpad.
1442
+ [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskOtherMouseDown
1443
+ handler:^NSEvent *(NSEvent *event) {
1444
+ auto input = event.buttonNumber == 3 ? ngn::NavigationInput::MouseButton4
1445
+ : event.buttonNumber == 4 ? ngn::NavigationInput::MouseButton5
1446
+ : std::optional<ngn::NavigationInput>{};
1447
+ if (!input) {
1448
+ return event;
1449
+ }
1450
+ navigate(*ngn::navigationFor(*input), event.window);
1451
+ return nil;
1452
+ }];
1453
+ [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskSwipe
1454
+ handler:^NSEvent *(NSEvent *event) {
1455
+ if (event.deltaX == 0) {
1456
+ return event;
1457
+ }
1458
+ auto input = event.deltaX > 0 ? ngn::NavigationInput::SwipeRight
1459
+ : ngn::NavigationInput::SwipeLeft;
1460
+ navigate(*ngn::navigationFor(input, swipesRightToLeft()), event.window);
1461
+ return nil;
1462
+ }];
1463
+ // "Swipe between pages" with two fingers (swipeScroll), for real scrolls and replayed ones.
1464
+ [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskScrollWheel
1465
+ handler:^NSEvent *(NSEvent *event) {
1466
+ return swipeScroll(event, event.window);
1467
+ }];
1468
+ ngn::appkit::setReplayScrollMonitor([](NSEvent *event, NSWindow *window) { return swipeScroll(event, window); });
1469
+ if (!settings.test) {
1470
+ [app activateIgnoringOtherApps:YES];
1471
+ }
1472
+ [app run];
1473
+ }
1474
+ return 0;
1475
+ }