ruby_everywhere 0.7.0 → 0.9.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 (73) hide show
  1. checksums.yaml +4 -4
  2. data/exe/every +2 -13
  3. data/exe/rbe +2 -13
  4. data/lib/everywhere/boot.rb +9 -2
  5. data/lib/everywhere/builders/android.rb +55 -42
  6. data/lib/everywhere/builders/base.rb +53 -0
  7. data/lib/everywhere/builders/desktop.rb +7 -23
  8. data/lib/everywhere/builders/ios.rb +49 -52
  9. data/lib/everywhere/builders/native_sources.rb +38 -0
  10. data/lib/everywhere/child_processes.rb +4 -4
  11. data/lib/everywhere/child_supervision.rb +172 -0
  12. data/lib/everywhere/clock.rb +12 -0
  13. data/lib/everywhere/commands/build.rb +20 -9
  14. data/lib/everywhere/commands/dev.rb +59 -284
  15. data/lib/everywhere/commands/doctor.rb +6 -6
  16. data/lib/everywhere/commands/install.rb +1 -0
  17. data/lib/everywhere/commands/platform/auth_status.rb +1 -0
  18. data/lib/everywhere/commands/platform/build.rb +5 -6
  19. data/lib/everywhere/commands/platform/login.rb +4 -4
  20. data/lib/everywhere/commands/platform/logout.rb +1 -0
  21. data/lib/everywhere/commands/platform/runner.rb +62 -7
  22. data/lib/everywhere/commands/preview.rb +24 -97
  23. data/lib/everywhere/commands/publish.rb +2 -0
  24. data/lib/everywhere/commands/release.rb +14 -11
  25. data/lib/everywhere/commands/shell_dir.rb +2 -0
  26. data/lib/everywhere/commands/updates_keygen.rb +25 -1
  27. data/lib/everywhere/config/app.rb +126 -0
  28. data/lib/everywhere/config/auth.rb +108 -0
  29. data/lib/everywhere/config/data.rb +50 -0
  30. data/lib/everywhere/config/deep_linking.rb +107 -0
  31. data/lib/everywhere/config/desktop_ui.rb +153 -0
  32. data/lib/everywhere/config/mobile.rb +223 -0
  33. data/lib/everywhere/config/native_desktop.rb +168 -0
  34. data/lib/everywhere/config/native_mobile.rb +337 -0
  35. data/lib/everywhere/config/shell.rb +57 -0
  36. data/lib/everywhere/config/updates.rb +63 -0
  37. data/lib/everywhere/config.rb +30 -1423
  38. data/lib/everywhere/desktop_dev_app.rb +138 -0
  39. data/lib/everywhere/dock/state.rb +3 -1
  40. data/lib/everywhere/entrypoint.rb +24 -0
  41. data/lib/everywhere/error.rb +8 -0
  42. data/lib/everywhere/framework.rb +2 -2
  43. data/lib/everywhere/host.rb +11 -0
  44. data/lib/everywhere/ignore.rb +11 -5
  45. data/lib/everywhere/line_pump.rb +3 -1
  46. data/lib/everywhere/minisign.rb +1 -0
  47. data/lib/everywhere/native_platform.rb +44 -0
  48. data/lib/everywhere/paths.rb +23 -7
  49. data/lib/everywhere/platform/client.rb +19 -1
  50. data/lib/everywhere/platform/snapshot.rb +6 -4
  51. data/lib/everywhere/plist.rb +17 -0
  52. data/lib/everywhere/png.rb +1 -0
  53. data/lib/everywhere/raw_tty.rb +51 -0
  54. data/lib/everywhere/s3.rb +1 -0
  55. data/lib/everywhere/shell_pages.rb +109 -0
  56. data/lib/everywhere/tab_filter.rb +36 -0
  57. data/lib/everywhere/task_pool.rb +3 -4
  58. data/lib/everywhere/ui.rb +6 -1
  59. data/lib/everywhere/version.rb +6 -4
  60. data/lib/everywhere.rb +1 -2
  61. data/support/mobile/android/app/src/main/java/com/rubyeverywhere/shell/EverywhereApplication.kt +65 -4
  62. data/support/mobile/android/app/src/main/java/com/rubyeverywhere/shell/EverywhereConfig.kt +21 -0
  63. data/support/mobile/android/app/src/main/java/com/rubyeverywhere/shell/MainActivity.kt +75 -17
  64. data/support/mobile/android/app/src/main/java/com/rubyeverywhere/shell/MissingExtensionFragment.kt +105 -0
  65. data/support/mobile/android/app/src/main/java/com/rubyeverywhere/shell/WebFragment.kt +31 -4
  66. data/support/mobile/android/app/src/main/java/com/rubyeverywhere/shell/bridge/WebControlChannel.kt +6 -10
  67. data/support/mobile/android/app/src/main/res/layout/everywhere_error.xml +60 -0
  68. data/support/mobile/android/app/src/main/res/values/strings.xml +19 -0
  69. data/support/mobile/ios/App/ErrorViewController.swift +21 -3
  70. data/support/mobile/ios/App/SceneDelegate.swift +12 -1
  71. data/support/mobile/ios/App.xcodeproj/project.pbxproj +0 -2
  72. data/support/release/macos/notarize.sh +3 -0
  73. metadata +26 -1
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Everywhere
4
+ class << self
5
+ # The tiny page served at /everywhere/reset. Auth flows redirect the native
6
+ # app here so it resets cleanly (fresh web views, re-fetched tabs) before
7
+ # continuing — the standard Hotwire Native "reset the app" pattern. It talks
8
+ # to the shell's control channel directly (no bridge/importmap dependency);
9
+ # in a plain browser it just forwards to the target. `to` is constrained to
10
+ # a same-origin path.
11
+ #
12
+ # Both shells are addressed inline, and differently, for the same reason
13
+ # the bridge normalizes them: WKWebView's message handler takes an object,
14
+ # while Android's WebMessageListener channel takes a string. Reaching for
15
+ # the bridge here instead would trade that one line for an importmap
16
+ # dependency on a page whose whole job is to work before anything loads.
17
+ def mobile_reset_html(to)
18
+ require "json"
19
+ target = to.to_s
20
+ target = "/" unless target.start_with?("/") && !target.start_with?("//")
21
+ # script_safe, not to_json: this lands inside <script>, and outside Rails
22
+ # nothing escapes "</script>" in a plain JSON string.
23
+ encoded = JSON.generate(target, script_safe: true)
24
+
25
+ <<~HTML
26
+ <!DOCTYPE html><html><head><meta charset="utf-8"><title>One moment…</title>
27
+ <meta name="viewport" content="width=device-width,initial-scale=1"></head>
28
+ <body><script>
29
+ (function(){var to=#{encoded};var msg={action:"reset",to:to};
30
+ var ios=window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.everywhereControl;
31
+ var android=window.everywhereControl;
32
+ if(ios){ios.postMessage(msg);}
33
+ else if(android&&android.postMessage){android.postMessage(JSON.stringify(msg));}
34
+ else{window.location.replace(to);}})();
35
+ </script></body></html>
36
+ HTML
37
+ end
38
+
39
+ # The page served at /everywhere/jump/leave — the way OUT of a Jump
40
+ # preview. Once Jump re-roots onto a previewed app (instance.set), every
41
+ # Jump surface — launcher, scanner, tabs — resolves against the previewed
42
+ # app, so the escape hatch has to be served by the previewed app itself:
43
+ # this gem is the one thing guaranteed to be there. Posts clearInstance on
44
+ # the shell's control channel; shells that aren't multi-instance ignore
45
+ # it, and a plain browser just goes home.
46
+ # Fires clearInstance only once VISIBLE. This page rides in the previewed
47
+ # app's tab bar; shells preload tabs eagerly, but a preloaded webview is
48
+ # offscreen and reports visibilityState "hidden" — firing on load would
49
+ # bounce every preview the instant it connects, and a tap on the tab
50
+ # never re-proposes a visit, so visibility flipping is the ONLY signal a
51
+ # tab tap gives the page. The button is a belt for browsers and any
52
+ # webview that lies about visibility.
53
+ def mobile_jump_leave_html
54
+ <<~HTML
55
+ <!DOCTYPE html><html><head><meta charset="utf-8"><title>Jump</title>
56
+ <meta name="viewport" content="width=device-width,initial-scale=1">
57
+ <style>
58
+ body{font-family:-apple-system,system-ui,sans-serif;margin:0;min-height:100vh;
59
+ display:flex;flex-direction:column;align-items:center;justify-content:center;
60
+ gap:12px;padding:24px;text-align:center;background:#fff;color:#171717}
61
+ @media(prefers-color-scheme:dark){body{background:#171717;color:#fafafa}}
62
+ p{margin:0;opacity:.6}
63
+ button{font:inherit;font-weight:600;font-size:18px;color:#fff;background:#dc2626;
64
+ border:0;border-radius:12px;padding:16px 32px}
65
+ </style></head>
66
+ <body>
67
+ <p>Returning to Jump…</p>
68
+ <button onclick="everywhereJumpLeave()">Return to Jump</button>
69
+ <script>
70
+ function everywhereJumpLeave(){var msg={action:"clearInstance"};
71
+ var ios=window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.everywhereControl;
72
+ var android=window.everywhereControl;
73
+ if(ios){ios.postMessage(msg);}
74
+ else if(android&&android.postMessage){android.postMessage(JSON.stringify(msg));}
75
+ else{window.location.replace("/");}}
76
+ if(document.visibilityState==="visible"){everywhereJumpLeave();}
77
+ else{document.addEventListener("visibilitychange",function(){
78
+ if(document.visibilityState==="visible"){everywhereJumpLeave();}});}
79
+ </script></body></html>
80
+ HTML
81
+ end
82
+
83
+ # The page served at /everywhere/auth/native. The shell normally diverts a
84
+ # provider path natively, before the request is ever made; this covers the
85
+ # visits it can't see — a `data-turbo="false"` link, or the POST OmniAuth 2
86
+ # requires — by asking the shell, from the page, to open the auth session.
87
+ # In a browser it just continues to the provider.
88
+ def mobile_auth_html(to)
89
+ require "json"
90
+ target = to.to_s
91
+ target = "/" unless target.start_with?("/") && !target.start_with?("//")
92
+ # script_safe, as in mobile_reset_html: `to` is request input.
93
+ encoded = JSON.generate(target, script_safe: true)
94
+
95
+ <<~HTML
96
+ <!DOCTYPE html><html><head><meta charset="utf-8"><title>Signing in…</title>
97
+ <meta name="viewport" content="width=device-width,initial-scale=1"></head>
98
+ <body><p>Opening secure sign-in…</p><script>
99
+ (function(){var to=#{encoded};var msg={action:"authFlow",to:to};
100
+ var ios=window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.everywhereControl;
101
+ var android=window.everywhereControl;
102
+ if(ios){ios.postMessage(msg);}
103
+ else if(android&&android.postMessage){android.postMessage(JSON.stringify(msg));}
104
+ else{window.location.replace(to);}})();
105
+ </script></body></html>
106
+ HTML
107
+ end
108
+ end
109
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Everywhere
4
+ class << self
5
+ # Register a per-request filter for the mobile tab bar. The block receives
6
+ # the resolved tab list (`[{ "title" =>, "path" =>, "icon" => }, …]`) and
7
+ # the current request, and returns the subset to show — return `[]` to hide
8
+ # the tab bar entirely (the shell falls back to single-screen navigation).
9
+ #
10
+ # It runs inside the mobile config endpoint, which shares the app's session
11
+ # and cookies, so it can branch on auth or any request state:
12
+ #
13
+ # # config/initializers/everywhere.rb
14
+ # Everywhere.filter_tabs do |tabs, request|
15
+ # request.session[:user_id] ? tabs : []
16
+ # end
17
+ #
18
+ # Live like the rest of the config: the shell re-reads it on launch and on
19
+ # every foreground, so a sign-in shows the tabs on next foreground — no
20
+ # rebuild, no app-store release.
21
+ def filter_tabs(&block)
22
+ @tabs_filter = block
23
+ end
24
+
25
+ # Apply the registered filter (identity when none is set). Always returns
26
+ # an Array so a stray nil/scalar from a block can't break serialization.
27
+ def resolve_tabs(tabs, request)
28
+ return tabs unless @tabs_filter
29
+
30
+ Array(@tabs_filter.call(tabs, request))
31
+ end
32
+
33
+ # Test/reset hook.
34
+ attr_writer :tabs_filter
35
+ end
36
+ end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "clock"
3
4
  require_relative "console"
4
5
  require_relative "child_processes"
5
6
 
@@ -78,8 +79,8 @@ module Everywhere
78
79
  return if live.empty?
79
80
 
80
81
  live.each { |thread| ChildProcesses.terminate(thread, grace: grace) }
81
- deadline = now + grace
82
- live.each { |thread| thread.join([deadline - now, 0].max) }
82
+ deadline = Clock.monotonic + grace
83
+ live.each { |thread| thread.join([deadline - Clock.monotonic, 0].max) }
83
84
  live.select(&:alive?).each(&:kill)
84
85
  Console.multiplexed = false
85
86
  end
@@ -117,7 +118,5 @@ module Everywhere
117
118
  live = @threads.each_value.count { |t| t.alive? && t != Thread.current }
118
119
  Console.multiplexed = live > 1
119
120
  end
120
-
121
- def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
122
121
  end
123
122
  end
data/lib/everywhere/ui.rb CHANGED
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "clock"
3
4
  require_relative "fatal"
4
5
  require_relative "console"
5
6
 
@@ -164,7 +165,7 @@ module Everywhere
164
165
  private
165
166
 
166
167
  def headless(text)
167
- now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
168
+ now = Clock.monotonic
168
169
  return if @last_headless && (now - @last_headless) < HEADLESS_INTERVAL
169
170
 
170
171
  @last_headless = now
@@ -217,5 +218,9 @@ module Everywhere
217
218
  s = s.gsub("#{home}/", "~/") if home && !home.empty?
218
219
  s
219
220
  end
221
+
222
+ # short_path for a path we know the root of: drop the project root (or the
223
+ # cwd, when the command runs from somewhere else) before shortening.
224
+ def rel_path(path, root) = short_path(path.to_s.sub("#{root}/", "").sub("#{Dir.pwd}/", ""))
220
225
  end
221
226
  end
@@ -1,14 +1,16 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "json"
4
+
3
5
  module Everywhere
4
- VERSION = "0.7.0"
6
+ VERSION = "0.9.0"
5
7
 
6
8
  # Version of the @rubyeverywhere/bridge JS this gem ships. bridge/ in the
7
9
  # gem IS the npm package (served to Rails apps by Everywhere::Engine,
8
10
  # vendored to public/ for Sinatra/Hanami), so its package.json is the single
9
11
  # source of truth. The build receipt records it; it versions independently
10
12
  # of the CLI.
11
- BRIDGE_VERSION = File.read(
12
- File.expand_path("../../bridge/package.json", __dir__)
13
- )[/"version":\s*"([^"]+)"/, 1]
13
+ BRIDGE_VERSION = JSON.parse(
14
+ File.read(File.expand_path("../../bridge/package.json", __dir__))
15
+ )["version"]
14
16
  end
data/lib/everywhere.rb CHANGED
@@ -3,6 +3,7 @@
3
3
  # Runtime entry point: what an app gets from `require "ruby_everywhere"`.
4
4
  # The CLI lives in everywhere/cli and is only loaded by the every/rbe executables.
5
5
  require_relative "everywhere/version"
6
+ require_relative "everywhere/error"
6
7
  require_relative "everywhere/config"
7
8
  require_relative "everywhere/framework"
8
9
  require_relative "everywhere/database"
@@ -12,8 +13,6 @@ require_relative "everywhere/boot"
12
13
  require_relative "everywhere/engine" if defined?(::Rails::Engine)
13
14
 
14
15
  module Everywhere
15
- class Error < StandardError; end
16
-
17
16
  # App-facing runtime configuration. Apps register overrides at load time:
18
17
  #
19
18
  # # config/initializers/everywhere.rb (Rails) or anywhere loaded by config.ru
@@ -2,6 +2,8 @@ package com.rubyeverywhere.shell
2
2
 
3
3
  import android.app.Application
4
4
  import android.webkit.CookieManager
5
+ import android.webkit.WebSettings
6
+ import android.widget.Toast
5
7
  import androidx.core.net.toUri
6
8
  import com.rubyeverywhere.shell.bridge.BiometricsComponent
7
9
  import com.rubyeverywhere.shell.bridge.HapticsComponent
@@ -20,6 +22,7 @@ import dev.hotwire.core.turbo.visit.VisitProposal
20
22
  import dev.hotwire.core.turbo.webview.HotwireWebView
21
23
  import dev.hotwire.navigation.activities.HotwireActivity
22
24
  import dev.hotwire.navigation.config.defaultFragmentDestination
25
+ import dev.hotwire.navigation.destinations.HotwireDestinationDeepLink
23
26
  import dev.hotwire.navigation.config.registerBridgeComponents
24
27
  import dev.hotwire.navigation.config.registerFragmentDestinations
25
28
  import dev.hotwire.navigation.config.registerRouteDecisionHandlers
@@ -55,12 +58,22 @@ class EverywhereApplication : Application() {
55
58
 
56
59
  Hotwire.defaultFragmentDestination = WebFragment::class
57
60
 
58
- Hotwire.registerFragmentDestinations(
61
+ val fragmentDestinations = listOf(
59
62
  WebFragment::class,
60
63
  WebBottomSheetFragment::class,
61
- // App-provided native screens (everywhere.yml native.android.screens).
62
- *EverywhereExtensions.fragmentDestinations.toTypedArray()
63
- )
64
+ // Where a rule's fallback_uri lands when its primary uri names a
65
+ // Fragment this build doesn't contain (previewing another app).
66
+ MissingExtensionFragment::class
67
+ ) + EverywhereExtensions.fragmentDestinations // everywhere.yml native.android.screens
68
+ Hotwire.registerFragmentDestinations(*fragmentDestinations.toTypedArray())
69
+
70
+ // Every uri those destinations answer to, read from the same
71
+ // annotation Hotwire itself matches against — handed to the
72
+ // missing-screen guard below so it can tell a resolvable rule from
73
+ // one that would go nowhere.
74
+ val registeredUris = fragmentDestinations
75
+ .mapNotNull { it.java.getAnnotation(HotwireDestinationDeepLink::class.java)?.uri }
76
+ .toSet()
64
77
 
65
78
  Hotwire.registerBridgeComponents(
66
79
  BridgeComponentFactory("everywhere--notification", ::NotificationComponent),
@@ -78,6 +91,7 @@ class EverywhereApplication : Application() {
78
91
  Hotwire.registerRouteDecisionHandlers(
79
92
  ResetRouteDecisionHandler(),
80
93
  AuthFlowRouteDecisionHandler(),
94
+ MissingScreenRouteDecisionHandler(registeredUris),
81
95
  AppNavigationRouteDecisionHandler(),
82
96
  BrowserTabRouteDecisionHandler(),
83
97
  SystemNavigationRouteDecisionHandler()
@@ -99,6 +113,16 @@ class EverywhereApplication : Application() {
99
113
  Hotwire.config.makeCustomWebView = { context ->
100
114
  HotwireWebView(context, null).also { webView ->
101
115
  WebControlChannel.install(webView, config.webConfigJson)
116
+ // Instance apps pair with LAN-hosted previews: the picker page
117
+ // is https but the app it probes is plain http, which WebView
118
+ // blocks as mixed content — and then the picker reports a live
119
+ // preview as "not answering". Scoped to remote.instances so
120
+ // ordinary apps keep the strict default. The main-frame http
121
+ // load itself is governed by network_security_config.xml,
122
+ // which `every build` opens up under the same flag.
123
+ if (config.remoteInstances) {
124
+ webView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
125
+ }
102
126
  }
103
127
  }
104
128
  }
@@ -154,6 +178,43 @@ private class ResetRouteDecisionHandler : Router.RouteDecisionHandler {
154
178
  }
155
179
  }
156
180
 
181
+ /**
182
+ * The last line of defence for a native-screen rule this build can't serve.
183
+ *
184
+ * A previewed app on a current gem serves `fallback_uri` pointing at
185
+ * [MissingExtensionFragment], and the visit lands there — this handler never
186
+ * matches. An app on an older gem serves only `uri: hotwire://fragment/<id>`,
187
+ * and Hotwire's answer to a uri no registered destination claims is to do
188
+ * nothing at all — which reads as a spinner that never ends. Refuse the visit
189
+ * loudly instead: a toast naming the screen, and the user stays on the page
190
+ * they tapped from.
191
+ */
192
+ private class MissingScreenRouteDecisionHandler(
193
+ private val registeredUris: Set<String>
194
+ ) : Router.RouteDecisionHandler {
195
+ override val name = "everywhere-missing-screen"
196
+
197
+ override fun matches(proposal: VisitProposal, configuration: NavigatorConfiguration): Boolean {
198
+ val uri = proposal.properties["uri"]?.toString() ?: return false
199
+ val fallback = proposal.properties["fallback_uri"]?.toString()
200
+ return uri !in registeredUris && (fallback == null || fallback !in registeredUris)
201
+ }
202
+
203
+ override fun handle(
204
+ proposal: VisitProposal,
205
+ configuration: NavigatorConfiguration,
206
+ activity: HotwireActivity
207
+ ): Router.Decision {
208
+ val identifier = proposal.properties["view_controller"]?.toString() ?: "native"
209
+ Toast.makeText(
210
+ activity,
211
+ activity.getString(R.string.everywhere_missing_screen_toast, identifier),
212
+ Toast.LENGTH_LONG
213
+ ).show()
214
+ return Router.Decision.CANCEL
215
+ }
216
+ }
217
+
157
218
  /**
158
219
  * A provider sign-in: hand it to a Custom Tab instead of loading it in the web
159
220
  * view. Cancelling leaves the user on the page they tapped from, which is where
@@ -189,6 +189,27 @@ class EverywhereConfig private constructor(
189
189
  return if (path.isNullOrEmpty() || path == "/") rootUrl else url(forPath = path)
190
190
  }
191
191
 
192
+ /**
193
+ * Every origin the shell's own pages can be served from: the stamped
194
+ * root, the dev override, and a picked instance. The control channel is
195
+ * offered to all of them, not just the current [rootUrl] — while rooted
196
+ * on an instance, the picker's pages still come from the stamped origin,
197
+ * and without the channel there they could switch in but never switch
198
+ * again (`Everywhere.instance.*` would fall back to a plain navigation).
199
+ */
200
+ val trustedRootOrigins: Set<String>
201
+ get() = listOfNotNull(stampedRemoteUrl, devUrl, instanceUrl)
202
+ .mapNotNull(::originOf)
203
+ .toSet()
204
+
205
+ private fun originOf(url: String): String? {
206
+ val uri = url.toUri()
207
+ val scheme = uri.scheme ?: return null
208
+ val host = uri.host ?: return null
209
+ val port = if (uri.port > 0) ":${uri.port}" else ""
210
+ return "$scheme://$host$port"
211
+ }
212
+
192
213
  /**
193
214
  * The server half of the path configuration (rules + settings.tabs),
194
215
  * generated from everywhere.yml by the gem's MobileConfigEndpoint — so tab
@@ -140,7 +140,16 @@ class MainActivity : HotwireActivity() {
140
140
  // Swap to the real theme before the content view inflates.
141
141
  setTheme(R.style.Theme_Everywhere)
142
142
  enableEdgeToEdge()
143
- super.onCreate(savedInstanceState)
143
+
144
+ // A rebuild ([rebuildAndRoute]: reset, sign-in/out, instance switch)
145
+ // arrives with EXTRA_ROUTE on the Intent and must start from scratch:
146
+ // handing the saved state to super restores every navigator's back
147
+ // stack, climbing the page the user just left back on top of the new
148
+ // root. Dropped here, the recreate behaves like a fresh launch — while
149
+ // a real config change or process death (no EXTRA_ROUTE) restores
150
+ // normally.
151
+ val state = if (intent.hasExtra(EXTRA_ROUTE)) null else savedInstanceState
152
+ super.onCreate(state)
144
153
 
145
154
  setContentView(R.layout.activity_main)
146
155
  findViewById<View>(R.id.root).applyDefaultImeWindowInsets()
@@ -148,7 +157,7 @@ class MainActivity : HotwireActivity() {
148
157
  splash = findViewById(R.id.splash)
149
158
  showSplash()
150
159
 
151
- initializeTabs(savedInstanceState?.getInt(STATE_SELECTED_TAB) ?: 0)
160
+ initializeTabs(state?.getInt(STATE_SELECTED_TAB) ?: 0)
152
161
 
153
162
  observeEvents()
154
163
  observePathConfiguration()
@@ -220,7 +229,14 @@ class MainActivity : HotwireActivity() {
220
229
 
221
230
  pendingRoute = null
222
231
  pendingRouteHostId = null
223
- navigator.route(route)
232
+ // Post, don't call: this callback fires from onAttachFragment while
233
+ // the host's start fragment is still mid-transaction — no view, no
234
+ // web delegate — and routing into it synchronously crashes Hotwire
235
+ // ("lateinit property webDelegate has not been initialized"). One
236
+ // trip through the main queue lets the transaction finish first.
237
+ window.decorView.post {
238
+ if (!isFinishing && !isDestroyed) navigator.route(route)
239
+ }
224
240
  }
225
241
 
226
242
  // ------------------------------------------------------------------------
@@ -380,19 +396,32 @@ class MainActivity : HotwireActivity() {
380
396
  * handling selection would make More a one-shot.
381
397
  */
382
398
  private fun installTabListeners(arrangement: MainTabs.Arrangement) {
383
- if (!arrangement.hasMore) return
399
+ val hasLeaveSlot = arrangement.slots.any { isLeaveTab(it.entry?.path) }
400
+ if (!arrangement.hasMore && !hasLeaveSlot) return
384
401
 
385
402
  bottomNav.setOnItemSelectedListener { item ->
386
403
  val index = item.itemId
387
- // selectingMoreForRoute is the one case where selecting More IS the
388
- // intent: something routed to an overflow path and the host has to
389
- // come forward to receive it.
390
- if (arrangement.isMoreIndex(index) && !selectingMoreForRoute) {
391
- showMoreSheet(arrangement)
392
- false
393
- } else {
394
- switchToSlot(index)
395
- true
404
+ when {
405
+ // The Jump leave tab is a native action, exactly as on iOS
406
+ // (EverywhereTabBarController): the page behind it is a
407
+ // gem-served Turbo-less fallback, so selecting its host could
408
+ // only end at the error view. The tap clears the picked
409
+ // instance directly and never becomes a selection.
410
+ isLeaveTab(arrangement.entryAt(index)?.path) -> {
411
+ leaveInstance()
412
+ false
413
+ }
414
+ // selectingMoreForRoute is the one case where selecting More IS
415
+ // the intent: something routed to an overflow path and the host
416
+ // has to come forward to receive it.
417
+ arrangement.isMoreIndex(index) && !selectingMoreForRoute -> {
418
+ showMoreSheet(arrangement)
419
+ false
420
+ }
421
+ else -> {
422
+ switchToSlot(index)
423
+ true
424
+ }
396
425
  }
397
426
  }
398
427
 
@@ -408,6 +437,19 @@ class MainActivity : HotwireActivity() {
408
437
  }
409
438
  }
410
439
 
440
+ /**
441
+ * The injected "leave preview" tab (a Jump instance's way home), matched
442
+ * by its gem-reserved path. Only meaningful for instance apps — for
443
+ * everyone else no such tab is ever injected, and the guard keeps an
444
+ * unlucky app path from being swallowed.
445
+ */
446
+ private fun isLeaveTab(path: String?): Boolean =
447
+ config.remoteInstances && path == JUMP_LEAVE_PATH
448
+
449
+ private fun leaveInstance() {
450
+ EverywhereEvents.emit(EverywhereEvents.Event.ClearInstance(null))
451
+ }
452
+
411
453
  /**
412
454
  * Bring a slot's host forward — upstream `HotwireBottomNavigationController`'s
413
455
  * private `switchTab`, which taking over the item-selected listener costs us.
@@ -466,7 +508,11 @@ class MainActivity : HotwireActivity() {
466
508
 
467
509
  row.setOnClickListener {
468
510
  dialog.dismiss()
469
- route(config.url(forPath = entry.path))
511
+ // The leave row is the same native action as a leave SLOT —
512
+ // see installTabListeners; routing it would load the
513
+ // Turbo-less fallback page and end at the error view.
514
+ if (isLeaveTab(entry.path)) leaveInstance()
515
+ else route(config.url(forPath = entry.path))
470
516
  }
471
517
  list.addView(row)
472
518
  }
@@ -777,9 +823,17 @@ class MainActivity : HotwireActivity() {
777
823
  }
778
824
 
779
825
  /**
780
- * `recreate()` loses every field, so the landing page rides along on the
781
- * Intent which `recreate()` does preserve and is picked up by the next
782
- * `onCreate`.
826
+ * `recreate()` for an in-place rebuild a CLEAR_TASK relaunch tears the
827
+ * task down first, which plays as the app closing and cold-starting on
828
+ * every reset (sign-in, sign-out, instance switch). recreate() keeps the
829
+ * window; the landing page rides along on the Intent, which recreate()
830
+ * preserves while fields are lost.
831
+ *
832
+ * The saved instance state, however, must NOT come back: it carries every
833
+ * navigator's back stack, and restoring it climbs the page the user just
834
+ * left (Jump's connect screen, a pre-sign-in page) right back on top of
835
+ * the new root. `onCreate` treats the presence of [EXTRA_ROUTE] as the
836
+ * fresh-start flag and drops the state — see the top of [onCreate].
783
837
  */
784
838
  private fun rebuildAndRoute(target: String) {
785
839
  AuthFlow.cancel()
@@ -956,6 +1010,10 @@ class MainActivity : HotwireActivity() {
956
1010
  const val EXTRA_ROUTE = "everywhere.route"
957
1011
  const val EXTRA_LAST_REBUILD = "everywhere.lastRebuild"
958
1012
 
1013
+ /** The injected leave tab's path — same constant iOS keeps on
1014
+ * EverywhereTabBarController.jumpLeavePath. */
1015
+ const val JUMP_LEAVE_PATH = "/everywhere/jump/leave"
1016
+
959
1017
  /**
960
1018
  * How close two path-change rebuilds have to be before the second is
961
1019
  * treated as a loop rather than a legitimate config change. Generous
@@ -0,0 +1,105 @@
1
+ package com.rubyeverywhere.shell
2
+
3
+ import android.graphics.drawable.Drawable
4
+ import android.os.Bundle
5
+ import android.util.TypedValue
6
+ import android.view.Gravity
7
+ import android.view.LayoutInflater
8
+ import android.view.View
9
+ import android.view.ViewGroup
10
+ import android.widget.FrameLayout
11
+ import android.widget.ImageView
12
+ import android.widget.LinearLayout
13
+ import android.widget.TextView
14
+ import androidx.appcompat.widget.Toolbar
15
+ import androidx.core.graphics.drawable.DrawableCompat
16
+ import com.google.android.material.appbar.AppBarLayout
17
+ import dev.hotwire.navigation.destinations.HotwireDestinationDeepLink
18
+ import dev.hotwire.navigation.fragments.HotwireFragment
19
+
20
+ /**
21
+ * The per-rule fallback destination for native screens this build doesn't
22
+ * contain — the Android half of iOS's `MissingExtensionScreen`.
23
+ *
24
+ * The gem writes `fallback_uri: hotwire://fragment/everywhere-missing` next to
25
+ * every derived screen `uri` (see the gem's Config::Mobile), so when a
26
+ * Jump-style shell previews an app whose rules name Fragments compiled into
27
+ * THAT app's build, the visit lands here and says so — instead of Hotwire
28
+ * finding no destination and leaving the user on a spinner forever. An app's
29
+ * own build resolves the primary uri and never consults the fallback.
30
+ */
31
+ @HotwireDestinationDeepLink(uri = "hotwire://fragment/everywhere-missing")
32
+ class MissingExtensionFragment : HotwireFragment() {
33
+ private lateinit var toolbar: Toolbar
34
+
35
+ override fun onCreateView(
36
+ inflater: LayoutInflater,
37
+ container: ViewGroup?,
38
+ savedInstanceState: Bundle?
39
+ ): View {
40
+ val context = requireContext()
41
+ // The rule that routed here still carries the screen's identifier.
42
+ val identifier = pathProperties["view_controller"]?.toString() ?: "native"
43
+
44
+ toolbar = Toolbar(context).apply {
45
+ title = getString(R.string.everywhere_missing_screen_nav_title)
46
+ }
47
+ val appBar = AppBarLayout(context).apply {
48
+ fitsSystemWindows = true
49
+ addView(toolbar, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
50
+ }
51
+
52
+ val secondary = TypedValue().let {
53
+ context.theme.resolveAttribute(android.R.attr.textColorSecondary, it, true)
54
+ requireNotNull(context.getColorStateList(it.resourceId)).defaultColor
55
+ }
56
+
57
+ val icon = ImageView(context).apply {
58
+ setImageDrawable(tinted(IconFont.drawable(context, "extension", dp(44)), secondary))
59
+ }
60
+ val title = TextView(context).apply {
61
+ text = getString(R.string.everywhere_missing_screen_title)
62
+ textSize = 20f
63
+ setTypeface(typeface, android.graphics.Typeface.BOLD)
64
+ gravity = Gravity.CENTER
65
+ }
66
+ val body = TextView(context).apply {
67
+ text = getString(R.string.everywhere_missing_screen_body, identifier)
68
+ textSize = 15f
69
+ setTextColor(secondary)
70
+ gravity = Gravity.CENTER
71
+ }
72
+
73
+ val column = LinearLayout(context).apply {
74
+ orientation = LinearLayout.VERTICAL
75
+ gravity = Gravity.CENTER_HORIZONTAL
76
+ setPadding(dp(32), 0, dp(32), 0)
77
+ addView(icon)
78
+ addView(title, spaced(dp(14)))
79
+ addView(body, spaced(dp(14)))
80
+ }
81
+ val content = FrameLayout(context).apply {
82
+ addView(column, FrameLayout.LayoutParams(
83
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,
84
+ Gravity.CENTER
85
+ ))
86
+ }
87
+
88
+ return LinearLayout(context).apply {
89
+ orientation = LinearLayout.VERTICAL
90
+ addView(appBar, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
91
+ addView(content, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f))
92
+ }
93
+ }
94
+
95
+ override fun toolbarForNavigation(): Toolbar = toolbar
96
+
97
+ private fun tinted(drawable: Drawable, color: Int): Drawable =
98
+ DrawableCompat.wrap(drawable).mutate().also { DrawableCompat.setTint(it, color) }
99
+
100
+ private fun spaced(marginTop: Int) = LinearLayout.LayoutParams(
101
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
102
+ ).apply { topMargin = marginTop }
103
+
104
+ private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt()
105
+ }