diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index d6ca7390..831e6ad4 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -76,6 +76,8 @@ jobs: # This parallel job is short; keep download hits without a second Wasm target tree. cache-targets: false save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Check rake-core dependencies (native and Wasm) + run: bash scripts/check-core-dependencies.sh - name: Portable API lints run: cargo clippy -p rake-client -p rake-http -p rake-protocol -p rake-diagnostics --lib --locked -- -D warnings -D clippy::missing_errors_doc -D clippy::must_use_candidate -D clippy::return_self_not_must_use - run: cargo test -p rake-client -p rake-http -p rake-protocol --locked @@ -94,6 +96,7 @@ jobs: run: | cargo clippy -p rake-web-host-fixture --lib --target wasm32-unknown-unknown --locked -- -D warnings cargo clippy -p rake-app --no-default-features --target wasm32-unknown-unknown --locked -- -D warnings + cargo check -p rake-core --target wasm32-unknown-unknown --locked - name: Wasm feature checks run: | cargo check -p rake-app --features tray --target wasm32-unknown-unknown --locked @@ -239,13 +242,13 @@ jobs: - name: View tests without devtools or kit if: ${{ !cancelled() }} run: >- - cargo test -p rake-app -p rake-ui -p rake-view -p rake-notes - --features rake-app/view-test-support,rake-view/view-test-support,rake-notes/view-test-support + cargo test -p rake-app -p rake-gpui -p rake-ui -p rake-view -p rake-notes + --features rake-app/view-test-support,rake-gpui/view-test-support,rake-view/view-test-support,rake-notes/view-test-support --locked --no-fail-fast - name: Devtools view tests without kit if: ${{ !cancelled() }} run: >- - cargo test -p rake-app --features view-test-support,devtools + cargo test -p rake-app -p rake-gpui --features rake-app/view-test-support,rake-app/devtools,rake-gpui/view-test-support,rake-gpui/devtools --lib --test view_state --test element_inspection --locked --no-fail-fast - name: Desktop feature lints if: ${{ !cancelled() && runner.os != 'Windows' }} @@ -258,10 +261,10 @@ jobs: - name: Desktop feature tests (devtools, kit, tray, updates) if: ${{ !cancelled() && runner.os != 'Windows' }} run: >- - cargo test -p rake-app -p rake-ui -p rake-view -p rake-notes + cargo test -p rake-app -p rake-gpui -p rake-ui -p rake-view -p rake-notes -p rake-foundation -p rake-routing -p rake-files -p rake-tray -p rake-autostart -p rake-updates -p rake-client -p rake-http -p rake-protocol --locked --no-fail-fast - --features rake-app/view-test-support,rake-app/devtools,rake-app/kit,rake-app/tray,rake-app/launch-at-login,rake-app/${{ matrix.updates }},rake-notes/view-test-support,rake-view/view-test-support + --features rake-gpui/view-test-support,rake-app/view-test-support,rake-app/devtools,rake-app/kit,rake-app/tray,rake-app/launch-at-login,rake-app/${{ matrix.updates }},rake-notes/view-test-support,rake-view/view-test-support - name: GPUI fast desktop lints if: ${{ !cancelled() && runner.os != 'Windows' }} run: >- @@ -402,13 +405,13 @@ jobs: - name: View tests without devtools or kit if: ${{ !cancelled() }} run: >- - cargo test -p rake-app -p rake-ui -p rake-view -p rake-notes - --features rake-app/view-test-support,rake-view/view-test-support,rake-notes/view-test-support + cargo test -p rake-app -p rake-gpui -p rake-ui -p rake-view -p rake-notes + --features rake-app/view-test-support,rake-gpui/view-test-support,rake-view/view-test-support,rake-notes/view-test-support --locked --no-fail-fast - name: Devtools view tests without kit if: ${{ !cancelled() }} run: >- - cargo test -p rake-app --features view-test-support,devtools + cargo test -p rake-app -p rake-gpui --features rake-app/view-test-support,rake-app/devtools,rake-gpui/view-test-support,rake-gpui/devtools --lib --test view_state --test element_inspection --locked --no-fail-fast - name: Estimate dependency cache size if: ${{ always() }} @@ -458,10 +461,10 @@ jobs: - name: Desktop feature tests (devtools, kit, tray, updates) if: ${{ !cancelled() }} run: >- - cargo test -p rake-app -p rake-ui -p rake-view -p rake-notes + cargo test -p rake-app -p rake-gpui -p rake-ui -p rake-view -p rake-notes -p rake-foundation -p rake-routing -p rake-files -p rake-tray -p rake-autostart -p rake-updates -p rake-client -p rake-http -p rake-protocol --locked --no-fail-fast - --features rake-app/view-test-support,rake-app/devtools,rake-app/kit,rake-app/tray,rake-app/launch-at-login,rake-app/updates-velopack,rake-notes/view-test-support,rake-view/view-test-support + --features rake-gpui/view-test-support,rake-app/view-test-support,rake-app/devtools,rake-app/kit,rake-app/tray,rake-app/launch-at-login,rake-app/updates-velopack,rake-notes/view-test-support,rake-view/view-test-support - name: GPUI fast desktop lints if: ${{ !cancelled() }} run: >- @@ -510,13 +513,14 @@ jobs: - run: cargo test -p rake-files --lib --locked - run: cargo test -p rake-app --test platform --locked - run: cargo clippy -p rake-app --features tray --all-targets --locked -- -D warnings - - run: cargo test -p rake-app --features tray,view-test-support --lib --locked + - run: cargo test -p rake-gpui --features tray,view-test-support --lib --locked - run: cargo check -p rake-app --features tray,gpui-fast --all-targets --locked - run: cargo check -p renamed-facade --features tray --locked - run: cargo check -p rake-tray-example --locked + - run: cargo test -p rake-gpui --features view-test-support --lib --locked - run: cargo test -p rake-app --features view-test-support --lib --test view_state --test actions --test inspection_compiled_out --locked - run: cargo test -p rake-view --features view-test-support --lib --locked - - run: cargo test -p rake-app --features view-test-support,devtools --lib --test view_state --test element_inspection --locked + - run: cargo test -p rake-app -p rake-gpui --features rake-app/view-test-support,rake-app/devtools,rake-gpui/view-test-support,rake-gpui/devtools --lib --test view_state --test element_inspection --locked - run: cargo clippy -p rake-app --all-targets --features view-test-support,devtools --locked -- -D warnings - run: cargo test -p rake-ui --features kit --test semantic --locked - run: cargo test -p rake-app --features kit,view-test-support,devtools --lib --test view_state --locked diff --git a/.github/workflows/function-components.yml b/.github/workflows/function-components.yml index a3e1db80..2a652b8d 100644 --- a/.github/workflows/function-components.yml +++ b/.github/workflows/function-components.yml @@ -59,7 +59,7 @@ jobs: mesa-vulkan-drivers xvfb fonts-dejavu-core - name: Test runtime and inspection run: >- - cargo test -p rake-app --features experimental-reactive,view-test-support,devtools --lib --locked + cargo test -p rake-gpui --features experimental-reactive,view-test-support,devtools --lib --locked - name: Test consumer behavior run: cargo test -p rake-app --locked --features experimental-reactive,view-test-support,devtools --test function_components --test view --test view_components --test view_state - name: Check component consumers and targets @@ -69,7 +69,7 @@ jobs: cargo check -p rake-view --locked --all-targets --features rake/experimental-reactive,rake/view-test-support cargo test -p rake-view-syntax -p rake-macros -p rake-protocol --locked --features rake-macros/reactive cargo test -p rake-view-syntax --locked - cargo test -p rake-app --locked --features experimental-reactive,view-test-support --doc + cargo test -p rake-gpui --locked --features experimental-reactive,view-test-support --doc cargo check -p rake-app -p renamed-facade --locked --features rake-app/experimental-reactive,renamed-facade/experimental-reactive --target wasm32-unknown-unknown --lib cargo check -p rake-app --locked --features view-test-support --lib cargo check -p rake-app -p rake-macros --locked --no-default-features --lib diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c0078eed..c87dda41 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,6 +21,13 @@ LibreSSL. [`check.yml`](.github/workflows/check.yml) holds the complete native, Wasm, DevTools and documentation checks. It currently runs only when started by hand. +## Application crates + +Use [`rake-core`](crates/rake-core) for portable runtime and routing code, and +[`rake-gpui`](crates/rake-gpui) for the GPUI hosts, views and window bindings. +Examples and consumer tests use the [`rake-app`](crates/rake) facade. See the +[development guide](docs/development.md#workspace-crates) for crate-specific checks. + ## Project conventions - Compiling isn't proof that something works on a platform. Say what you actually ran. diff --git a/Cargo.lock b/Cargo.lock index 1216a1e2..1c291ee6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7350,76 +7350,28 @@ dependencies = [ name = "rake-app" version = "0.1.0-alpha.7" dependencies = [ - "anyhow", "async-io", - "backtrace", - "block2 0.6.2", - "blocking", - "console_error_panic_hook", - "event-listener", - "fixed_decimal", - "fluent-bundle", - "foreign-types", "futures", - "gpui-fast", - "gpui-fast-apple", "gpui-fast-platform", - "gpui-pre", - "gpui-pre-apple", "gpui-pre-platform", - "icu_calendar", - "icu_datetime", - "icu_decimal", - "icu_locale_core", - "icu_plurals", - "icu_provider", - "icu_provider_blob", - "image", - "js-sys", "libc", - "metal", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", - "objc2-foundation 0.3.2", - "objc2-quartz-core 0.3.2", - "objc2-user-notifications", - "oo7", - "pathfinder_simd", - "rake-autostart", - "rake-blaze-live", "rake-client", + "rake-core", "rake-diagnostics", + "rake-gpui", "rake-http", "rake-macros", - "rake-native", "rake-protocol", - "rake-resources", - "rake-shortcuts", - "rake-tray", "rake-ui", - "rake-updates", - "raw-window-handle", - "schemars 1.2.3", "serde", "serde_json", - "slotmap", - "sys-locale", "tempfile", "thiserror 2.0.21", "tracing", "tracing-subscriber", "trybuild", - "url", "uuid", "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "web-time", - "windows 0.62.2", - "windows-sys 0.61.2", - "writeable", - "zbus", - "zeroize", ] [[package]] @@ -7513,6 +7465,42 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rake-core" +version = "0.1.0-alpha.7" +dependencies = [ + "async-io", + "backtrace", + "blocking", + "console_error_panic_hook", + "event-listener", + "futures", + "js-sys", + "libc", + "rake-autostart", + "rake-client", + "rake-diagnostics", + "rake-http", + "rake-macros", + "rake-protocol", + "rake-resources", + "rake-updates", + "schemars 1.2.3", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.21", + "tracing", + "tracing-subscriber", + "url", + "uuid", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", + "zeroize", +] + [[package]] name = "rake-desktop-example" version = "0.1.0" @@ -7674,6 +7662,77 @@ dependencies = [ "web-time", ] +[[package]] +name = "rake-gpui" +version = "0.1.0-alpha.7" +dependencies = [ + "anyhow", + "block2 0.6.2", + "blocking", + "console_error_panic_hook", + "event-listener", + "fixed_decimal", + "fluent-bundle", + "foreign-types", + "futures", + "gpui-fast", + "gpui-fast-apple", + "gpui-fast-platform", + "gpui-pre", + "gpui-pre-apple", + "gpui-pre-platform", + "icu_calendar", + "icu_datetime", + "icu_decimal", + "icu_locale_core", + "icu_plurals", + "icu_provider", + "icu_provider_blob", + "image", + "js-sys", + "libc", + "metal", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "objc2-user-notifications", + "oo7", + "pathfinder_simd", + "rake-blaze-live", + "rake-client", + "rake-core", + "rake-diagnostics", + "rake-macros", + "rake-native", + "rake-protocol", + "rake-resources", + "rake-shortcuts", + "rake-tray", + "rake-ui", + "rake-updates", + "raw-window-handle", + "schemars 1.2.3", + "serde", + "serde_json", + "slotmap", + "sys-locale", + "tempfile", + "thiserror 2.0.21", + "tracing", + "tracing-subscriber", + "url", + "uuid", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", + "windows 0.62.2", + "windows-sys 0.61.2", + "writeable", + "zbus", +] + [[package]] name = "rake-http" version = "0.1.0-alpha.7" diff --git a/Cargo.toml b/Cargo.toml index 1ea22252..18e2556e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/rake-shortcuts", "vendor/blaze-live", "crates/rake-autostart", "crates/rake-view-syntax", "crates/rake-tray", "crates/rake-native", "crates/rake-dist-linux", "crates/rake-updates", "crates/rake-dist-macos", "crates/rake-build", "crates/rake-resources", "crates/rake-dist-windows", "crates/rake-dist-core", "crates/rake-dist", "crates/rake", "crates/rake-diagnostics", "crates/rake-http", "crates/rake-ui", "crates/rake-protocol", "crates/rake-client", "crates/rake-macros", "crates/rake-cli", "examples/tray", "examples/gpu-surface", "examples/gpu-surface/renderer", "examples/kit", "examples/desktop", "examples/distribution", "examples/foundation", "examples/files", "examples/routing", "examples/notes", "examples/view", "examples/preview", "examples/file-icons", "examples/agent", "tests/renamed-facade", "tests/web-platform"] +members = ["crates/rake-shortcuts", "vendor/blaze-live", "crates/rake-autostart", "crates/rake-view-syntax", "crates/rake-tray", "crates/rake-native", "crates/rake-dist-linux", "crates/rake-updates", "crates/rake-dist-macos", "crates/rake-build", "crates/rake-resources", "crates/rake-dist-windows", "crates/rake-dist-core", "crates/rake-dist", "crates/rake", "crates/rake-core", "crates/rake-gpui", "crates/rake-diagnostics", "crates/rake-http", "crates/rake-ui", "crates/rake-protocol", "crates/rake-client", "crates/rake-macros", "crates/rake-cli", "examples/tray", "examples/gpu-surface", "examples/gpu-surface/renderer", "examples/kit", "examples/desktop", "examples/distribution", "examples/foundation", "examples/files", "examples/routing", "examples/notes", "examples/view", "examples/preview", "examples/file-icons", "examples/agent", "tests/renamed-facade", "tests/web-platform"] exclude = ["crates/rake-cli/lints/rake-gpui", "examples/inspector", "vendor/gpui-base", "vendor/gpui-pre-web"] resolver = "3" @@ -20,6 +20,8 @@ gpui_fast_platform = { package = "gpui-fast-platform", version = "=0.1.13", defa gpui-base = "=0.9.0" gpui-kit = "=0.9.0" rake = { package = "rake-app", version = "=0.1.0-alpha.7", path = "crates/rake" } +rake-core = { version = "=0.1.0-alpha.7", path = "crates/rake-core" } +rake-gpui = { version = "=0.1.0-alpha.7", path = "crates/rake-gpui" } rake-diagnostics = { version = "=0.1.0-alpha.7", path = "crates/rake-diagnostics" } rake-http = { version = "=0.1.0-alpha.7", path = "crates/rake-http" } rake-ui = { version = "=0.1.0-alpha.7", path = "crates/rake-ui" } diff --git a/crates/rake-cli/tests/project_dev.rs b/crates/rake-cli/tests/project_dev.rs index 06c1d5c4..59282bc0 100644 --- a/crates/rake-cli/tests/project_dev.rs +++ b/crates/rake-cli/tests/project_dev.rs @@ -234,6 +234,7 @@ impl Running { serde_json::from_slice(&fs::read(self.session.join("status.json")).unwrap()).unwrap() } + #[track_caller] fn phase(&self, phase: &str) -> Value { wait(|| { let value = self.status(); @@ -307,8 +308,10 @@ fn remove_early_session(pid: u32, started: SystemTime) { } } +#[track_caller] fn wait(mut probe: impl FnMut() -> Option) -> T { - let deadline = Instant::now() + Duration::from_secs(15); + // Parallel supervisor fixtures compete to start and schedule child processes. + let deadline = Instant::now() + Duration::from_secs(30); loop { if let Some(value) = probe() { @@ -1163,7 +1166,11 @@ fn browser_opening_honors_browser_and_cdp_opens_only_the_companion() { let mut running = fixture.start_options(&args, false); running.phase("watching"); - let args = wait(|| fs::read_to_string(running.control.join("browser-args")).ok()); + let args = wait(|| { + let args = fs::read_to_string(running.control.join("browser-args")).ok()?; + + (args.lines().count() >= 2 && args.ends_with('\n')).then_some(args) + }); assert_eq!(args.lines().take(1).collect::>(), ["--test"]); assert_eq!(args.lines().count(), 2, "open exactly one browser URL"); diff --git a/crates/rake-core/Cargo.toml b/crates/rake-core/Cargo.toml new file mode 100644 index 00000000..a53dcb9f --- /dev/null +++ b/crates/rake-core/Cargo.toml @@ -0,0 +1,65 @@ +[package] +name = "rake-core" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish = ["crates-io"] +description = "Framework-free runtime for the Rake application framework" +readme = "README.md" + +[lints] +workspace = true + +[features] +default = [] +launch-at-login = ["dep:rake-autostart"] +updates = ["dep:rake-updates", "rake-updates/native-lifecycle"] +updates-sparkle = ["updates", "rake-updates/sparkle"] +updates-appimage = ["updates", "rake-updates/appimage"] +updates-velopack = ["updates", "rake-updates/velopack"] +devtools = ["rake-diagnostics/devtools", "rake-http/devtools"] +devtools-memory = ["devtools", "dep:backtrace"] + +[dependencies] +zeroize = "1" +rake-autostart = { version = "=0.1.0-alpha.7", path = "../rake-autostart", optional = true } +rake-updates = { version = "=0.1.0-alpha.7", path = "../rake-updates", optional = true } +rake-resources = { version = "=0.1.0-alpha.7", path = "../rake-resources" } +rake-http = { workspace = true, features = ["task-errors"] } +rake-protocol.workspace = true +rake-macros = { version = "=0.1.0-alpha.7", path = "../rake-macros" } +rake-diagnostics.workspace = true +serde.workspace = true +serde_json.workspace = true +schemars = "1.2.3" +tracing.workspace = true +futures.workspace = true +thiserror.workspace = true +url = "2.5" +uuid = { version = "1", features = ["v4", "serde", "js"] } +event-listener = "5.4" +web-time.workspace = true + +[target.'cfg(any(unix, windows))'.dependencies] +rake-client.workspace = true + +[target.'cfg(unix)'.dependencies] +backtrace = { version = "0.3.76", optional = true } + +[target.'cfg(not(target_family = "wasm"))'.dependencies] +libc = "0.2" +async-io = "2.6" +blocking = "1.7" +tempfile = "3" + +[target.'cfg(target_family = "wasm")'.dependencies] +wasm-bindgen = "0.2" +wasm-bindgen-futures = "0.4" +js-sys = "0.3" +console_error_panic_hook = "0.1" +web-sys = { version = "0.3", features = ["console", "Window", "History", "Location", "Event", "BeforeUnloadEvent", "EventTarget", "Document", "Element", "HtmlElement", "Node", "Storage", "ClipboardEvent", "DataTransfer"] } + +[dev-dependencies] +tracing-subscriber.workspace = true diff --git a/crates/rake-core/LICENSE-APACHE b/crates/rake-core/LICENSE-APACHE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/crates/rake-core/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/crates/rake-core/LICENSE-MIT b/crates/rake-core/LICENSE-MIT new file mode 100644 index 00000000..ac298920 --- /dev/null +++ b/crates/rake-core/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Yurii Hulyk + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/rake-core/README.md b/crates/rake-core/README.md new file mode 100644 index 00000000..42c340c2 --- /dev/null +++ b/crates/rake-core/README.md @@ -0,0 +1,6 @@ +# rake-core + +Framework-free route mounting, application services, managed work, guarded quit, +checkpointing and local runtime control for Rake. Hosts provide a route mount +adapter and poll the router on their own event loop. GPUI applications use the +`rake-app` facade. diff --git a/crates/rake/src/control/commands.rs b/crates/rake-core/src/control/commands.rs similarity index 94% rename from crates/rake/src/control/commands.rs rename to crates/rake-core/src/control/commands.rs index eec06e7e..4e76d827 100644 --- a/crates/rake/src/control/commands.rs +++ b/crates/rake-core/src/control/commands.rs @@ -67,6 +67,7 @@ impl CommandDescriptor { /// Serde decoding and handler validation remain authoritative. /// /// ``` +/// # use rake_core as rake; /// use rake::control::{ApplicationCommand, ExecutionCapability}; /// #[rake::data(schema)] /// #[derive(rake::Command)] @@ -81,6 +82,7 @@ impl CommandDescriptor { /// Duplicate metadata is rejected by the derive: /// /// ```compile_fail +/// # use rake_core as rake; /// #[rake::data(schema)] /// #[derive(rake::Command)] /// #[command(id = "one", id = "two")] @@ -90,6 +92,7 @@ impl CommandDescriptor { /// Commands have a closed schema and stable identity, rather than generic variants: /// /// ```compile_fail +/// # use rake_core as rake; /// #[rake::data(schema)] /// #[derive(rake::Command)] /// #[command(id = "generic")] @@ -99,6 +102,7 @@ impl CommandDescriptor { /// The schema flag is required unless JSON Schema is implemented separately: /// /// ```compile_fail +/// # use rake_core as rake; /// #[rake::data] /// #[derive(rake::Command)] /// #[command(id = "missing.schema")] @@ -205,12 +209,15 @@ struct Registered { state: CommandState, } +type ValidateShortcut = fn(&str, &str) -> Result<(), CommandError>; + /// Explicit registry shared by GUI, Rust client and external runtime messages. /// Registration is bounded at 256 commands; replacing a handler is not implicit. #[derive(Clone, Default)] pub struct Commands( Rc>>, Rc, + Option, ); impl Commands { @@ -219,6 +226,13 @@ impl Commands { Self::default() } + #[doc(hidden)] + pub fn with_shortcut_validation(mut self, validate: ValidateShortcut) -> Self { + self.2 = Some(validate); + + self + } + /// Registers typed local-future arguments/results without a `Send` requirement. /// Deserialization happens before invoking the user handler. pub fn register(&self, handler: F) -> Result<(), CommandError> @@ -291,19 +305,8 @@ impl Commands { )); } - #[cfg(feature = "gpui")] - for stroke in shortcut.split_whitespace() { - let os = if cfg!(target_os = "macos") { - gpui::OperatingSystem::Mac - } else if cfg!(target_os = "windows") { - gpui::OperatingSystem::Windows - } else { - gpui::OperatingSystem::Linux - }; - - gpui::Keystroke::parse_with_os(stroke, os).map_err(|error| { - CommandError::Arguments(format!("invalid shortcut for {id}: {error}")) - })?; + if let Some(validate) = self.2 { + validate(id, shortcut)?; } } @@ -346,8 +349,8 @@ impl Commands { .ok_or_else(|| CommandError::Unknown(id.into())) } - #[cfg(feature = "gpui")] - pub(crate) fn listen(&self) -> event_listener::EventListener { + #[doc(hidden)] + pub fn listen(&self) -> event_listener::EventListener { self.1.listen() } diff --git a/crates/rake/src/control/host.rs b/crates/rake-core/src/control/host.rs similarity index 98% rename from crates/rake/src/control/host.rs rename to crates/rake-core/src/control/host.rs index 84d71d0a..3a8da9bb 100644 --- a/crates/rake/src/control/host.rs +++ b/crates/rake-core/src/control/host.rs @@ -55,7 +55,8 @@ pub(super) trait Host { } #[derive(Clone)] -pub(crate) struct HostClient(Rc); +#[doc(hidden)] +pub struct HostClient(Rc); impl HostClient { pub(super) fn new(client: impl Host + 'static) -> Self { diff --git a/crates/rake/src/control/local.rs b/crates/rake-core/src/control/local.rs similarity index 97% rename from crates/rake/src/control/local.rs rename to crates/rake-core/src/control/local.rs index 2f1278fe..90ed07f9 100644 --- a/crates/rake/src/control/local.rs +++ b/crates/rake-core/src/control/local.rs @@ -52,11 +52,8 @@ impl LocalServer { Self::bind_host(&HostClient::new(client.clone()), application_id, path) } - pub(crate) fn bind_host( - client: &HostClient, - application_id: &str, - path: &Path, - ) -> io::Result { + #[doc(hidden)] + pub fn bind_host(client: &HostClient, application_id: &str, path: &Path) -> io::Result { Self::bind_info(client.info(), application_id, path) } @@ -117,7 +114,8 @@ impl LocalServer { self.run_host(HostClient::new(client)).await } - pub(crate) async fn run_host(&self, client: HostClient) -> io::Result<()> { + #[doc(hidden)] + pub async fn run_host(&self, client: HostClient) -> io::Result<()> { let mut connections = FuturesUnordered::new(); loop { diff --git a/crates/rake/src/control/memory.rs b/crates/rake-core/src/control/memory.rs similarity index 100% rename from crates/rake/src/control/memory.rs rename to crates/rake-core/src/control/memory.rs diff --git a/crates/rake/src/control/mod.rs b/crates/rake-core/src/control/mod.rs similarity index 83% rename from crates/rake/src/control/mod.rs rename to crates/rake-core/src/control/mod.rs index c8f22ab0..21360c08 100644 --- a/crates/rake/src/control/mod.rs +++ b/crates/rake-core/src/control/mod.rs @@ -5,6 +5,7 @@ //! Operation submission is eager; disconnecting only stops observation. //! //! ``` +//! # use rake_core as rake; //! use rake::control::{Message, Query, Reply, Request, PROTOCOL_VERSION}; //! use rake::router::{NoRoute, Router, RouterConfig}; //! let router = Router::::new(RouterConfig::default()); @@ -21,7 +22,8 @@ mod host; mod memory; #[cfg(any(unix, windows, target_family = "wasm"))] -pub(crate) use host::HostClient; +#[doc(hidden)] +pub use host::HostClient; pub use commands::*; @@ -48,7 +50,8 @@ struct SavedRequest { } pub(crate) struct ClientState { - pub(crate) inspection: crate::inspection::Store, + #[cfg(feature = "devtools")] + inspection: std::cell::OnceCell>, commands: RefCell, services: RefCell, responses: Cell, @@ -60,7 +63,8 @@ pub(crate) struct ClientState { impl ClientState { pub(crate) fn new(capacity: usize) -> Self { Self { - inspection: crate::inspection::Store::default(), + #[cfg(feature = "devtools")] + inspection: std::cell::OnceCell::new(), commands: RefCell::new(Commands::new()), services: RefCell::new(crate::services::ServiceRegistry::new()), responses: Cell::new(0), @@ -110,8 +114,9 @@ impl RuntimeClient { ResponseGuard(self.state.clone()) } - #[cfg(all(feature = "gpui", not(target_family = "wasm")))] - pub(crate) async fn responses_idle(&self) { + #[cfg(not(target_family = "wasm"))] + #[doc(hidden)] + pub async fn responses_idle(&self) { loop { let listener = self.state.response_event.listen(); @@ -128,8 +133,8 @@ impl RuntimeClient { let (completed_operations, pending_operations) = self.router.operation_limits(); RuntimeInfo { - element_inspection: self.state.inspection.status(), - element_interaction: self.state.inspection.status() + element_inspection: self.inspection().status(), + element_interaction: self.inspection().status() != crate::inspection::Status::Unavailable, protocol: PROTOCOL_VERSION, runtime_id: self.router.runtime_id(), @@ -143,16 +148,14 @@ impl RuntimeClient { .iter() .filter(|name| **name != "record_memory" || memory::available()) .filter(|name| **name != "edit_storage" || cfg!(feature = "devtools")) - .filter(|name| **name != "preview_input" || self.state.inspection.preview_enabled()) + .filter(|name| **name != "preview_input" || self.inspection().preview_enabled()) .map(|name| (*name).into()) .collect(), queries: Query::names() .iter() .filter(|name| **name != "memory" || memory::available()) .filter(|name| **name != "storage" || cfg!(feature = "devtools")) - .filter(|name| { - !name.starts_with("preview") || self.state.inspection.preview_enabled() - }) + .filter(|name| !name.starts_with("preview") || self.inspection().preview_enabled()) .map(|name| (*name).into()) .collect(), supported_targets: self.router.supported_targets(), @@ -314,12 +317,13 @@ impl RuntimeClient { } } - #[cfg(feature = "gpui")] - pub(crate) fn set_commands(&self, commands: Commands) { + #[doc(hidden)] + pub fn set_commands(&self, commands: Commands) { *self.state.commands.borrow_mut() = commands; } - pub(crate) fn set_services(&self, services: crate::services::ServiceRegistry) { + #[doc(hidden)] + pub fn set_services(&self, services: crate::services::ServiceRegistry) { *self.state.services.borrow_mut() = services; } @@ -365,7 +369,8 @@ impl RuntimeClient { ) } - pub(crate) fn dispatch_local_command( + #[doc(hidden)] + pub fn dispatch_local_command( &self, id: String, arguments: serde_json::Value, @@ -397,7 +402,7 @@ impl RuntimeClient { return memory::record(owner, *enabled, *interval, *lease_ms); } Command::RecordFrames { enabled, lease_ms } => { - self.state.inspection.record_frames(*enabled, *lease_ms)?; + self.inspection().record_frames(*enabled, *lease_ms)?; return Ok(Reply::Acknowledged); } @@ -406,7 +411,7 @@ impl RuntimeClient { generation, edit, } => { - self.state.inspection.edit_text(id, generation, edit)?; + self.inspection().edit_text(id, generation, edit)?; return Ok(Reply::Acknowledged); } @@ -415,7 +420,7 @@ impl RuntimeClient { generation, edit, } => { - self.state.inspection.edit_style(id, generation, edit)?; + self.inspection().edit_style(id, generation, edit)?; return Ok(Reply::Acknowledged); } @@ -424,22 +429,22 @@ impl RuntimeClient { generation, action, } => { - self.state.inspection.navigate(id, generation, *action)?; + self.inspection().navigate(id, generation, *action)?; return Ok(Reply::Acknowledged); } Command::PreviewInput { point, input } => { - self.state.inspection.preview_input(point, input)?; + self.inspection().preview_input(point, input)?; return Ok(Reply::Acknowledged); } Command::HighlightElement { id, generation } => { - self.state.inspection.highlight(id.as_deref(), generation)?; + self.inspection().highlight(id.as_deref(), generation)?; return Ok(Reply::Acknowledged); } Command::InspectMode { enabled, lease_ms } => { - self.state.inspection.inspect_mode(*enabled, *lease_ms)?; + self.inspection().inspect_mode(*enabled, *lease_ms)?; return Ok(Reply::Acknowledged); } @@ -525,9 +530,32 @@ impl RuntimeClient { Ok(Reply::Submitted { operation_id: id }) } - #[cfg(all(feature = "gpui", feature = "devtools"))] - pub(crate) fn inspection(&self) -> crate::inspection::Store { - self.state.inspection.clone() + #[cfg(any(unix, windows, target_family = "wasm"))] + #[doc(hidden)] + pub fn into_host(self) -> HostClient { + HostClient::new(self) + } + + fn inspection(&self) -> &dyn crate::inspection::InspectionHost { + #[cfg(feature = "devtools")] + if let Some(host) = self.state.inspection.get() { + return host.as_ref(); + } + + &crate::inspection::Unavailable + } + + #[doc(hidden)] + #[cfg(feature = "devtools")] + pub fn inspection_host( + &self, + init: impl FnOnce() -> T, + ) -> &T { + let host = self.state.inspection.get_or_init(|| Box::new(init())); + + (host.as_ref() as &dyn std::any::Any) + .downcast_ref() + .expect("a runtime has one inspection provider") } fn query(&self, query: Query) -> Result { @@ -544,40 +572,38 @@ impl RuntimeClient { Ok(Reply::Snapshot(self.router.snapshot_in_window(window)?)) } Query::Quit {} => Ok(Reply::Quit(self.router.quit_status())), - Query::InspectPick {} => Ok(Reply::InspectPick(self.state.inspection.pick()?)), + Query::InspectPick {} => Ok(Reply::InspectPick(self.inspection().pick()?)), Query::Preview {} => Ok(Reply::Data( - serde_json::to_value(self.state.inspection.preview_windows()) + serde_json::to_value(self.inspection().preview_windows()) .expect("preview windows serialize"), )), - Query::PreviewElement { point } => Ok(Reply::Element( - self.state.inspection.preview_element(&point)?, - )), + Query::PreviewElement { point } => { + Ok(Reply::Element(self.inspection().preview_element(&point)?)) + } Query::InspectTreePage { generation, offset } => Ok(Reply::ElementPage( - self.state - .inspection - .tree_page(generation.as_deref(), offset)?, + self.inspection().tree_page(generation.as_deref(), offset)?, )), Query::Frames { after } => Ok(Reply::Frames( - self.router.frame_records(&self.state.inspection, after), + self.router.frame_records(self.inspection(), after), )), Query::Memory { owner, include_freed, } => memory::snapshot(&owner, include_freed), - Query::InspectTree {} => Ok(Reply::Elements(self.state.inspection.snapshot())), + Query::InspectTree {} => Ok(Reply::Elements(self.inspection().snapshot())), Query::InspectWindow { window, presentation, offset, - } => Ok(Reply::InspectionWindow(self.state.inspection.window_page( + } => Ok(Reply::InspectionWindow(self.inspection().window_page( window, presentation.as_deref(), offset, )?)), - Query::InspectRevision {} => Ok(Reply::InspectionRevision( - self.state.inspection.tree_revision(), - )), - Query::InspectElement { id } => Ok(Reply::Element(self.state.inspection.element(&id)?)), + Query::InspectRevision {} => { + Ok(Reply::InspectionRevision(self.inspection().tree_revision())) + } + Query::InspectElement { id } => Ok(Reply::Element(self.inspection().element(&id)?)), Query::Reload {} => Ok(Reply::Reload(self.router.reload_status())), Query::Checkpoint { application_id } => Ok(Reply::Checkpoint( self.router.reload_checkpoint(&application_id)?, @@ -729,109 +755,13 @@ pub enum ControlConfig { FromEnvironment, } -#[cfg(feature = "gpui")] -impl ControlConfig { - #[cfg(any(feature = "devtools", test))] - pub(crate) fn inspection_enabled(self) -> bool { - #[cfg(not(feature = "devtools"))] - { - let _ = self; - - false - } - - #[cfg(feature = "devtools")] - { - if !matches!(self, Self::FromEnvironment) { - return false; - } - - #[cfg(any(unix, windows))] - { - std::env::var("RAKE_DEV_CONTROL").as_deref() == Ok("1") - } - #[cfg(target_family = "wasm")] - { - WebBridgeConfig::from_document().is_ok_and(|config| config.is_some()) - } - - #[cfg(not(any(unix, windows, target_family = "wasm")))] - { - false - } - } - } -} - -#[cfg(feature = "gpui")] -pub(crate) async fn run_host( - config: ControlConfig, - client: RuntimeClient, - application_id: String, -) { - #[cfg(any(unix, windows, target_family = "wasm"))] - run_host_client(config, HostClient::new(client), application_id).await; - - #[cfg(not(any(unix, windows, target_family = "wasm")))] - { - let _ = (config, client, application_id); - - futures::future::pending::<()>().await; - } -} - -#[cfg(all(feature = "gpui", any(unix, windows, target_family = "wasm")))] -pub(crate) async fn run_host_client( - config: ControlConfig, - client: HostClient, - application_id: String, -) { - if matches!(config, ControlConfig::FromEnvironment) { - #[cfg(any(unix, windows))] - if std::env::var("RAKE_DEV_CONTROL").as_deref() == Ok("1") { - match local::LocalServer::bind_host(&client, &application_id, &local::directory()) { - Ok(server) => { - if let Err(error) = server.run_host(client).await { - crate::error!( - error_type = std::any::type_name_of_val(&error), - "Development control stopped" - ); - } - } - Err(error) => crate::error!( - error_type = std::any::type_name_of_val(&error), - "Development control could not start" - ), - } - } - - #[cfg(target_family = "wasm")] - match WebBridgeConfig::from_document() { - Ok(Some(config)) => match WebBridge::new(config) { - Ok(bridge) => bridge.run_host(client, &application_id).await, - Err(error) => crate::error!( - error_type = std::any::type_name_of_val(&error), - "Development bridge could not start" - ), - }, - Ok(None) => {} - Err(error) => crate::error!( - error_type = std::any::type_name_of_val(&error), - "Invalid development bridge configuration" - ), - } - } - - futures::future::pending::<()>().await; -} - #[cfg(test)] #[cfg(feature = "devtools")] mod inspection_control_tests { //! Covers: leased commands bypass operation/key retention while preserving runtime validation. //! Real: shared client dispatcher and inspection store. Doubles: an empty captured host. use super::*; - use crate::router::{NoRoute, RouterConfig, WindowId}; + use crate::router::{NoRoute, RouterConfig}; #[test] fn development_lease_renewals_never_fill_application_retry_capacity() { @@ -839,9 +769,23 @@ mod inspection_control_tests { let client = router.client(); assert!(!client.info().element_interaction); - let snapshot = client.state.inspection.begin(0); + struct Captured; + + impl crate::inspection::InspectionHost for Captured { + fn status(&self) -> crate::inspection::Status { + crate::inspection::Status::Captured + } + + fn inspect_mode( + &self, + _: bool, + _: u64, + ) -> Result<(), crate::inspection::InspectionError> { + Ok(()) + } + } - client.state.inspection.publish(WindowId(1), snapshot); + client.inspection_host(|| Captured); for _ in 0..2048 { let reply = client diff --git a/crates/rake/src/control/web.rs b/crates/rake-core/src/control/web.rs similarity index 98% rename from crates/rake/src/control/web.rs rename to crates/rake-core/src/control/web.rs index 19e06d92..ef672a59 100644 --- a/crates/rake/src/control/web.rs +++ b/crates/rake-core/src/control/web.rs @@ -191,7 +191,8 @@ impl WebBridge { self.run_host(HostClient::new(client), application_id).await; } - pub(crate) async fn run_host(&self, client: HostClient, application_id: &str) { + #[doc(hidden)] + pub async fn run_host(&self, client: HostClient, application_id: &str) { loop { let session = async { let _: serde_json::Value = self.post("connect", &serde_json::json!({"application_id": application_id, "info": client.info(), "build_id": self.config.build_id, "reload": client.reload_status()})).await?; diff --git a/crates/rake/src/crash.rs b/crates/rake-core/src/crash.rs similarity index 94% rename from crates/rake/src/crash.rs rename to crates/rake-core/src/crash.rs index a4c12c4d..ebc6a35e 100644 --- a/crates/rake/src/crash.rs +++ b/crates/rake-core/src/crash.rs @@ -12,6 +12,7 @@ //! establish that the application exited. //! //! ```no_run +//! # use rake_core as rake; //! use rake::crash::{CrashLimits, CrashRecord}; //! use rake::diagnostics::Collector; //! # fn main() -> std::io::Result<()> { @@ -38,17 +39,16 @@ use serde::{Deserialize, Serialize}; #[cfg(not(target_family = "wasm"))] mod native; -#[cfg(any(not(target_family = "wasm"), feature = "gpui", test))] mod record; -#[cfg(all(target_family = "wasm", any(feature = "gpui", test)))] +#[cfg(target_family = "wasm")] mod web; #[cfg(not(target_family = "wasm"))] pub use native::CrashReporter; -#[cfg(feature = "gpui")] -pub(crate) mod startup; +#[doc(hidden)] +pub mod startup; /// Creates crash configuration using the consuming crate's Cargo package version. /// @@ -57,6 +57,7 @@ pub(crate) mod startup; /// explicit sink, or with native `CrashConfig::open` for a headless host. /// /// ``` +/// # use rake_core as rake; /// let _config = rake::crash_config!().include_panic_message(false); /// ``` #[macro_export] @@ -92,17 +93,12 @@ impl Default for CrashLimits { #[must_use] pub struct CrashConfig { directory: Option, - #[cfg_attr( - all(target_family = "wasm", not(any(feature = "gpui", test))), - expect(dead_code, reason = "headless Web has no implicit crash hook") - )] version: String, limits: CrashLimits, include_panic_message: bool, } impl CrashConfig { - #[cfg(any(not(target_family = "wasm"), feature = "gpui", test))] fn validate(&self, application_id: &str) -> io::Result<()> { if application_id.is_empty() || application_id.len() > 128 diff --git a/crates/rake/src/crash/browser.js b/crates/rake-core/src/crash/browser.js similarity index 100% rename from crates/rake/src/crash/browser.js rename to crates/rake-core/src/crash/browser.js diff --git a/crates/rake/src/crash/native.rs b/crates/rake-core/src/crash/native.rs similarity index 100% rename from crates/rake/src/crash/native.rs rename to crates/rake-core/src/crash/native.rs diff --git a/crates/rake/src/crash/record.rs b/crates/rake-core/src/crash/record.rs similarity index 100% rename from crates/rake/src/crash/record.rs rename to crates/rake-core/src/crash/record.rs diff --git a/crates/rake/src/crash/startup.rs b/crates/rake-core/src/crash/startup.rs similarity index 90% rename from crates/rake/src/crash/startup.rs rename to crates/rake-core/src/crash/startup.rs index dc0206aa..59fc337f 100644 --- a/crates/rake/src/crash/startup.rs +++ b/crates/rake-core/src/crash/startup.rs @@ -6,7 +6,7 @@ use super::{CrashConfig, CrashSink}; use crate::diagnostics::Collector; #[derive(Default)] -pub(crate) enum CrashReports { +pub enum CrashReports { #[default] Automatic, Disabled, @@ -14,15 +14,15 @@ pub(crate) enum CrashReports { } impl CrashReports { - pub(crate) fn configure(&mut self, config: CrashConfig, sink: impl CrashSink) { + pub fn configure(&mut self, config: CrashConfig, sink: impl CrashSink) { *self = Self::Configured(config, Box::new(sink)); } - pub(crate) fn disable(&mut self) { + pub fn disable(&mut self) { *self = Self::Disabled; } - pub(crate) fn initialize( + pub fn initialize( self, application_id: &str, version: Option<&str>, @@ -75,7 +75,8 @@ impl CrashReports { } } -pub(crate) fn version_from_policy(policy: Option<&str>) -> Option { +#[doc(hidden)] +pub fn version_from_policy(policy: Option<&str>) -> Option { #[derive(serde::Deserialize)] struct Version { version: String, diff --git a/crates/rake/src/crash/tests.rs b/crates/rake-core/src/crash/tests.rs similarity index 100% rename from crates/rake/src/crash/tests.rs rename to crates/rake-core/src/crash/tests.rs diff --git a/crates/rake/src/crash/web.rs b/crates/rake-core/src/crash/web.rs similarity index 100% rename from crates/rake/src/crash/web.rs rename to crates/rake-core/src/crash/web.rs diff --git a/crates/rake-core/src/inspection.rs b/crates/rake-core/src/inspection.rs new file mode 100644 index 00000000..38d5aacc --- /dev/null +++ b/crates/rake-core/src/inspection.rs @@ -0,0 +1,111 @@ +//! Framework-free inspection wire types and control dispatch provided by the host. + +pub use rake_protocol::inspection::*; + +#[doc(hidden)] +pub trait InspectionHost: std::any::Any { + fn window_page( + &self, + _: crate::router::WindowId, + _: Option<&str>, + _: usize, + ) -> Result { + Err(InspectionError::Unavailable) + } + + fn preview_enabled(&self) -> bool { + false + } + + fn preview_windows(&self) -> Vec { + Vec::new() + } + + fn preview_element(&self, _: &preview::Point) -> Result { + Err(InspectionError::Unavailable) + } + + fn preview_input(&self, _: &preview::Point, _: &preview::Input) -> Result<(), InspectionError> { + Err(InspectionError::Unavailable) + } + + fn edit_text(&self, _: &str, _: &str, _: &TextEdit) -> Result<(), InspectionError> { + Err(InspectionError::Unavailable) + } + + fn status(&self) -> Status { + Status::Unavailable + } + + fn snapshot(&self) -> Snapshot { + Snapshot { + status: Status::Unavailable, + capture: "0".into(), + router_revision: 0, + locale: None, + elements: Vec::new(), + omitted: 0, + coverage: if cfg!(feature = "devtools") { + "Rake inspection boundaries, including automatic view! nodes; opaque GPUI descendants and reused cached subtrees are not enumerated. Layout is before clipping; content_mask records the visible intersection. Authored styles are separate from live resolved Div/Stateful
/view! button styles, which include current interaction states and inherited text. Relative layout lengths retain their units. Box geometry resolves absolute edges from the layout-phase style; used auto/percentage edges and scrollbar metrics may be unavailable. Style origins describe observed defaults, inherited text, authored base, interaction changes and measured size; macro-authored style attribute locations are captured separately, while opaque per-method declaration locations and equal-valued overrides are unavailable. Rendered text is captured at text boundaries (16 KiB UTF-8 prefix); editable control values are excluded. Bounded accessibility labels and descriptions include macro-generated control names." + } else { + "Inspection was compiled out; enable rake/devtools" + }.into(), + } + } + + fn tree_page(&self, _: Option<&str>, _: usize) -> Result { + Err(InspectionError::Unavailable) + } + + fn tree_revision(&self) -> TreeRevision { + TreeRevision { + metadata: None, + capture: "0".into(), + status: Status::Unavailable, + } + } + + fn element(&self, _: &str) -> Result { + Err(InspectionError::Unavailable) + } + + fn pick(&self) -> Result { + Err(InspectionError::Unavailable) + } + + fn highlight(&self, _: Option<&str>, _: &str) -> Result<(), InspectionError> { + Err(InspectionError::Unavailable) + } + + fn inspect_mode(&self, _: bool, _: u64) -> Result<(), InspectionError> { + Err(InspectionError::Unavailable) + } + + fn navigate(&self, _: &str, _: &str, _: NavigationAction) -> Result<(), InspectionError> { + Err(InspectionError::Unavailable) + } + + fn edit_style(&self, _: &str, _: &str, _: &StyleEdit) -> Result<(), InspectionError> { + Err(InspectionError::Unavailable) + } + + fn record_frames(&self, _: bool, _: u64) -> Result<(), InspectionError> { + Err(InspectionError::RecordingUnavailable) + } + + fn frames(&self, _: u64, _: &rake_diagnostics::Collector) -> Frames { + Frames { + clock: None, + recording: false, + frames: Vec::new(), + cursor: 0, + more: false, + dropped: 0, + gap: false, + } + } +} + +pub(crate) struct Unavailable; + +impl InspectionHost for Unavailable {} diff --git a/crates/rake/src/inspection/macros.rs b/crates/rake-core/src/inspection_macros.rs similarity index 76% rename from crates/rake/src/inspection/macros.rs rename to crates/rake-core/src/inspection_macros.rs index 6fc09d18..42d737a8 100644 --- a/crates/rake/src/inspection/macros.rs +++ b/crates/rake-core/src/inspection_macros.rs @@ -1,9 +1,8 @@ -//! Facade-owned expansion gate: never consult a downstream crate's feature names. +//! Inspection expansions selected by the facade or GPUI adapter. -#[cfg(feature = "devtools")] #[doc(hidden)] #[macro_export] -macro_rules! __rake_inspection { +macro_rules! __rake_inspection_enabled { ($value:expr, |$node:ident| $enabled:expr $(,)?) => {{ let $node = $value; $enabled @@ -17,10 +16,9 @@ macro_rules! __rake_inspection { }; } -#[cfg(not(feature = "devtools"))] #[doc(hidden)] #[macro_export] -macro_rules! __rake_inspection { +macro_rules! __rake_inspection_disabled { ($value:expr, |$node:ident| $enabled:expr $(,)?) => { $value }; diff --git a/crates/rake-core/src/lib.rs b/crates/rake-core/src/lib.rs new file mode 100644 index 00000000..5cbba3f6 --- /dev/null +++ b/crates/rake-core/src/lib.rs @@ -0,0 +1,78 @@ +//! Framework-free application runtime, route mounts, services and local control. + +extern crate self as rake_core; + +#[cfg(feature = "launch-at-login")] +pub use rake_autostart as login_item; +#[cfg(feature = "updates")] +pub use rake_updates as updates; +#[cfg(feature = "updates")] +pub use rake_updates::updates; + +pub mod control; +pub mod crash; +#[doc(hidden)] +pub mod inspection; +mod inspection_macros; +pub mod loading; +pub mod logging; +#[cfg(all(feature = "devtools-memory", unix))] +pub mod memory; +pub mod platform; +pub mod quit; +pub mod reload; +pub mod router; +pub mod runtime; +pub mod services; +pub mod storage; +pub mod tasks; +pub mod web; +pub mod window_state; + +pub use rake_diagnostics as diagnostics; +pub use rake_http as http; +pub use rake_macros::{Command, Props, Route, data, instrument}; +pub use rake_resources as resources; +pub use rake_resources::{Resources, resources}; +pub use router::Route; +pub use schemars; +pub use serde; +pub use serde_json; +pub use services::{ServiceError, ServiceRegistry, Services}; +pub use tracing::{debug, error, info, trace, warn}; + +/// Common application and service imports. +pub mod prelude { + pub use crate::control::{ + ApplicationCommand, CommandContext, CommandDescriptor, CommandError, Commands, + ControlConfig, ExecutionCapability, RuntimeClient, + }; + + pub use crate::diagnostics::{Collector, DiagnosticsConfig, SubscriberMode}; + pub use crate::http::{CancellationToken, HttpClient, HttpConfig}; + pub use crate::loading::{LoadState, LoadStatus, LoadToken}; + + pub use crate::quit::{ + QuitGuardContext, QuitJobs, QuitOptions, QuitPhase, QuitResult, QuitStatus, + }; + + pub use crate::reload::{Checkpoint, ReloadError, ReloadState}; + pub use crate::runtime::{Runtime, RuntimeContext}; + pub use crate::services::{ServiceError, ServiceRegistry, Services}; + pub use crate::tasks::{ActivityRun, AppHandle, TaskError, TaskHandle, TaskScope}; + + pub use crate::router::{ + Activation, Admission, AdmissionContext, DecisionChoice, DecisionRequest, EntryHandle, + GuardResult, Navigator, OpenOptions, OpenTarget, Outcome, RevealScope, Route, Router, + RouterConfig, TabMode, WebConfig, WebRouting, + }; + + pub use rake_macros::{Command, Route}; +} + +#[doc(hidden)] +pub mod __private { + pub use tracing; + #[cfg(target_family = "wasm")] + pub use wasm_bindgen; +} diff --git a/crates/rake/src/loading.rs b/crates/rake-core/src/loading.rs similarity index 98% rename from crates/rake/src/loading.rs rename to crates/rake-core/src/loading.rs index 7884e4c9..ae62aabb 100644 --- a/crates/rake/src/loading.rs +++ b/crates/rake-core/src/loading.rs @@ -6,6 +6,7 @@ //! rejected without touching the current state. //! //! ```no_run +//! # use rake_core as rake; //! use rake::loading::{LoadState, LoadStatus}; //! //! let mut load = LoadState::::default(); @@ -17,12 +18,6 @@ use std::fmt; -#[cfg(feature = "gpui")] -mod binding; - -#[cfg(feature = "gpui")] -pub use binding::{AsyncAction, LoadContext, LoadError, Loader}; - /// One private generation identity returned by [`LoadState::begin`]. /// /// Both fields are private so callers can retain and compare tokens only diff --git a/crates/rake/src/logging.rs b/crates/rake-core/src/logging.rs similarity index 96% rename from crates/rake/src/logging.rs rename to crates/rake-core/src/logging.rs index 4b68fb9b..dc842e2d 100644 --- a/crates/rake/src/logging.rs +++ b/crates/rake-core/src/logging.rs @@ -1,11 +1,8 @@ //! Bounded private application logs, written only by the diagnostics worker. -#[cfg(any(not(target_family = "wasm"), feature = "gpui", test))] use std::path::PathBuf; -#[cfg(any(not(target_family = "wasm"), feature = "gpui", test))] use std::sync::OnceLock; -#[cfg(any(not(target_family = "wasm"), feature = "gpui", test))] static PATH: OnceLock = OnceLock::new(); /// Configuration for automatic application logging. @@ -17,12 +14,11 @@ pub struct LogConfig { pub level: Option, } -#[cfg(any(not(target_family = "wasm"), feature = "gpui", test))] pub(crate) fn path() -> Option { PATH.get().map(|path| path.to_string_lossy().into_owned()) } -#[cfg(all(not(target_family = "wasm"), any(feature = "gpui", test)))] +#[cfg(not(target_family = "wasm"))] mod native { use super::PATH; use crate::storage::file::{check_directory, check_file, private_options}; @@ -34,7 +30,6 @@ mod native { const FILE_BYTES: u64 = 1024 * 1024; const ROTATIONS: usize = 3; - #[cfg(feature = "gpui")] pub(super) fn directory(id: &str) -> Option { if id.is_empty() || id.len() > 128 @@ -324,8 +319,8 @@ mod native { } } -#[cfg(feature = "gpui")] -pub(crate) fn configure( +#[doc(hidden)] +pub fn configure( mut diagnostics: crate::diagnostics::DiagnosticsConfig, id: &str, config: LogConfig, diff --git a/crates/rake/src/memory.rs b/crates/rake-core/src/memory.rs similarity index 99% rename from crates/rake/src/memory.rs rename to crates/rake-core/src/memory.rs index 6e302e2e..b897f807 100644 --- a/crates/rake/src/memory.rs +++ b/crates/rake-core/src/memory.rs @@ -2,6 +2,7 @@ //! //! Install the wrapper in the executable, around its existing global allocator: //! ``` +//! # use rake_core as rake; //! #[global_allocator] //! static ALLOCATOR: rake::memory::TrackingAllocator = //! rake::memory::TrackingAllocator::new(std::alloc::System); diff --git a/crates/rake-core/src/platform/browser.js b/crates/rake-core/src/platform/browser.js new file mode 100644 index 00000000..7889e24f --- /dev/null +++ b/crates/rake-core/src/platform/browser.js @@ -0,0 +1,27 @@ +// Browser adapter shared by Wasm bindings and host-boundary tests. +export function capabilities() { + let bits = 0; + if (globalThis.document?.body) bits |= 1 | 2 | 32; + if (globalThis.isSecureContext && globalThis.navigator?.clipboard?.readText) bits |= 4; + if (globalThis.isSecureContext && globalThis.navigator?.clipboard?.writeText) bits |= 8; + try { if (globalThis.localStorage) bits |= 16; } catch (_) { /* Access denied. */ } + return bits; +} + +export async function clipboard_permission(write) { + try { + return (await navigator.permissions.query({name: write ? 'clipboard-write' : 'clipboard-read'})).state; + } catch (_) { return 'unknown'; } // Firefox/Safari need not implement this permission query. +} + +export function preference_get(namespace, key) { + if (!(capabilities() & 16)) throw new DOMException('preferences access denied', 'SecurityError'); + return localStorage.getItem(`rake:prefs:${namespace}:${key}`); +} + +export function preference_set(namespace, key, value) { + if (!(capabilities() & 16)) throw new DOMException('preferences access denied', 'SecurityError'); + const id = `rake:prefs:${namespace}:${key}`; + if (value === undefined || value === null) localStorage.removeItem(id); + else localStorage.setItem(id, value); +} diff --git a/crates/rake-core/src/platform/browser.rs b/crates/rake-core/src/platform/browser.rs new file mode 100644 index 00000000..e8f430bd --- /dev/null +++ b/crates/rake-core/src/platform/browser.rs @@ -0,0 +1,85 @@ +//! Browser extensions. Availability, permission and user activation are independent. + +use wasm_bindgen::prelude::*; +use wasm_bindgen_futures::JsFuture; + +use super::{Capabilities, Capability, Error, PermissionState}; + +#[wasm_bindgen(module = "/src/platform/browser.js")] +extern "C" { + #[wasm_bindgen(js_name = capabilities)] + fn detect() -> u32; + #[wasm_bindgen(js_name = clipboard_permission)] + fn permission(write: bool) -> js_sys::Promise; + #[wasm_bindgen(catch, js_name = preference_get)] + fn storage_get(namespace: &str, key: &str) -> Result, JsValue>; + #[wasm_bindgen(catch, js_name = preference_set)] + fn storage_set(namespace: &str, key: &str, value: Option<&str>) -> Result<(), JsValue>; +} + +#[doc(hidden)] +pub fn error(operation: &'static str, value: JsValue) -> Error { + let string = |key| { + js_sys::Reflect::get(&value, &JsValue::from_str(key)) + .ok() + .and_then(|value| value.as_string()) + }; + match string("name").as_deref() { + Some("NotSupportedError") => Error::Unsupported(operation), + Some("NotAllowedError" | "SecurityError") => Error::PermissionDenied(operation), + Some("QuotaExceededError") => Error::QuotaExceeded, + _ => Error::Unavailable { + operation, + message: string("message").unwrap_or_else(|| format!("{value:?}")), + }, + } +} + +pub(super) fn capabilities() -> Capabilities { + let bits = detect(); + let capability = |bit, gesture| Capability { + supported: bits & bit != 0, + permission: PermissionState::Unknown, + requires_user_gesture: gesture, + }; + Capabilities { + notifications: super::notifications::capability(), + global_shortcuts: super::GlobalShortcuts.capability(), + file_import: capability(1, true), + file_export: capability(2, true), + clipboard_read: capability(4, true), + clipboard_write: capability(8, true), + preferences: capability(16, false), + open_url: capability(32, true), + } +} + +/// Queries clipboard permission where supported. `Unknown` is expected on hosts +/// without this query; it does not imply that reading/writing is unavailable. +pub async fn clipboard_permission(write: bool) -> PermissionState { + match JsFuture::from(permission(write)) + .await + .ok() + .and_then(|value| value.as_string()) + .as_deref() + { + Some("granted") => PermissionState::Granted, + Some("prompt") => PermissionState::Prompt, + Some("denied") => PermissionState::Denied, + _ => PermissionState::Unknown, + } +} + +/// Reads text from a trusted DOM paste event without invoking clipboard permissions. +/// Do not suppress the browser's paste shortcut before this event can arrive. +pub fn text_from_paste_event(event: &web_sys::ClipboardEvent) -> Option { + event.clipboard_data()?.get_data("text/plain").ok() +} + +pub(super) fn preference_get(namespace: &str, key: &str) -> Result, Error> { + storage_get(namespace, key).map_err(|value| error("preferences read", value)) +} + +pub(super) fn preference_set(namespace: &str, key: &str, value: Option<&str>) -> Result<(), Error> { + storage_set(namespace, key, value).map_err(|value| error("preferences write", value)) +} diff --git a/crates/rake/src/platform/mod.rs b/crates/rake-core/src/platform/mod.rs similarity index 70% rename from crates/rake/src/platform/mod.rs rename to crates/rake-core/src/platform/mod.rs index 463cdbda..f952a362 100644 --- a/crates/rake/src/platform/mod.rs +++ b/crates/rake-core/src/platform/mod.rs @@ -6,31 +6,19 @@ //! observation, but cannot undo an OS dialog, clipboard write or browser download. mod notifications; +mod preferences; mod secrets; mod shortcuts; -pub use secrets::{Secret, Secrets}; - -#[cfg(feature = "gpui")] -pub use shortcuts::GlobalShortcut; -pub use shortcuts::GlobalShortcuts; - -mod preferences; - pub use notifications::{Notification, NotificationOutcome}; - pub use preferences::Preferences; - -#[cfg(feature = "gpui")] -mod files; - -#[cfg(feature = "gpui")] -pub use files::{FileHandle, SaveOutcome}; +pub use secrets::{Secret, Secrets}; +pub use shortcuts::GlobalShortcuts; #[cfg(target_family = "wasm")] pub mod browser; -use std::cell::RefCell; +use std::cell::{OnceCell, RefCell}; use std::collections::VecDeque; use std::future::Future; use std::pin::Pin; @@ -144,14 +132,30 @@ struct Activations { changed: event_listener::Event, } +impl Activations { + fn receive(&self, value: &str) -> Result<(), Error> { + let url = activation_url(value)?; + let mut urls = self.urls.borrow_mut(); + + if urls.len() == 32 { + urls.pop_front(); + } + + urls.push_back(url); + drop(urls); + self.changed.notify(usize::MAX); + + Ok(()) + } +} + /// Shared application host services and a bounded URL activation inbox. #[derive(Clone, Default)] pub struct Platform { application_id: Option>, activations: Rc, shortcuts: GlobalShortcuts, - #[cfg(any(feature = "gpui", test))] - notifications: Rc, + host: Rc>>, } impl std::fmt::Debug for Platform { @@ -161,8 +165,8 @@ impl std::fmt::Debug for Platform { } impl Platform { - #[cfg(any(feature = "gpui", test))] - pub(crate) fn for_application(application_id: &str) -> Self { + #[doc(hidden)] + pub fn for_application(application_id: &str) -> Self { Self { application_id: Some(application_id.into()), ..Self::default() @@ -177,7 +181,7 @@ impl Platform { #[cfg(not(target_family = "wasm"))] { let ui = Capability { - supported: cfg!(feature = "gpui"), + supported: false, permission: PermissionState::NotRequired, requires_user_gesture: false, }; @@ -214,18 +218,7 @@ impl Platform { /// # Errors /// Rejects malformed or oversized URLs before queuing them. pub fn receive_open_url(&self, value: &str) -> Result<(), Error> { - let url = activation_url(value)?; - let mut urls = self.activations.urls.borrow_mut(); - - if urls.len() == 32 { - urls.pop_front(); - } - - urls.push_back(url); - drop(urls); - self.activations.changed.notify(usize::MAX); - - Ok(()) + self.activations.receive(value) } /// Waits for the next activation. Clones share one inbox; competing consumers @@ -242,67 +235,24 @@ impl Platform { } } - /// Initiates a clipboard read. An empty clipboard yields `None` on native; - /// an empty text value is `Some("")`. Browser callers should also accept paste - /// events, since programmatic clipboard permission varies between browsers. - #[cfg(feature = "gpui")] - pub fn read_clipboard(&self, cx: &gpui::App) -> Request> { - #[cfg(target_family = "wasm")] - { - let _ = cx; - - browser::read_clipboard() - } + #[cfg(target_family = "wasm")] + #[doc(hidden)] + pub fn open_url_receiver(&self) -> impl Fn(&str) + use<> { + let activations = Rc::downgrade(&self.activations); - #[cfg(not(target_family = "wasm"))] - { - let value = cx.read_from_clipboard().and_then(|item| item.text()); - - Box::pin(async move { Ok(value) }) - } - } - - /// Initiates a clipboard write. Failure is observable on browser hosts; - /// native GPUI delegates to the system without a completion acknowledgement. - #[cfg(feature = "gpui")] - pub fn write_clipboard(&self, text: &str, cx: &gpui::App) -> Request<()> { - #[cfg(target_family = "wasm")] - { - let _ = cx; - - browser::write_clipboard(text) - } - - #[cfg(not(target_family = "wasm"))] - { - cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.to_owned())); - - Box::pin(async { Ok(()) }) + move |value| { + if let Some(activations) = activations.upgrade() { + let _ = activations.receive(value); + } } } - /// Opens an HTTP, HTTPS or mailto URL. Browser popup denial is an error; - /// native GPUI acknowledges delegation, not successful external navigation. - /// - /// # Errors - /// Rejects malformed/other-scheme URLs and browser permission failures. - #[cfg(feature = "gpui")] - pub fn open_url(&self, value: &str, cx: &gpui::App) -> Result<(), Error> { - let url = external_url(value)?; - - #[cfg(target_family = "wasm")] - { - let _ = cx; - - browser::open_url(url.as_str()) - } - - #[cfg(not(target_family = "wasm"))] - { - cx.open_url(url.as_str()); - - Ok(()) - } + #[doc(hidden)] + pub fn host_state(&self, init: impl FnOnce() -> T) -> &T { + self.host + .get_or_init(|| Box::new(init())) + .downcast_ref() + .expect("a platform has one host state type") } } @@ -321,45 +271,3 @@ fn activation_url(value: &str) -> Result { Ok(url) } - -#[cfg(any(feature = "gpui", test))] -fn external_url(value: &str) -> Result { - let url = url::Url::parse(value).map_err(|error| Error::InvalidInput(error.to_string()))?; - - if !matches!(url.scheme(), "https" | "http" | "mailto") { - return Err(Error::InvalidInput( - "external URL must use http, https or mailto".into(), - )); - } - - if !url.username().is_empty() || url.password().is_some() { - return Err(Error::InvalidInput( - "external URLs cannot contain credentials".into(), - )); - } - - Ok(url) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn external_urls_reject_executable_schemes_and_credentials() { - for invalid in [ - "javascript:alert(1)", - "file:///etc/passwd", - "data:text/html,hi", - "https://user:secret@example.com", - ] { - assert!(external_url(invalid).is_err(), "accepted {invalid}"); - } - - assert!(external_url("https://example.com/path?q=a").is_ok()); - assert!(external_url("mailto:hello@example.com").is_ok()); - } -} - -#[cfg(feature = "gpui")] -pub mod icons; diff --git a/crates/rake-core/src/platform/notifications.rs b/crates/rake-core/src/platform/notifications.rs new file mode 100644 index 00000000..49744913 --- /dev/null +++ b/crates/rake-core/src/platform/notifications.rs @@ -0,0 +1,92 @@ +//! Notification contracts and permissions in headless hosts. + +use super::{Capability, Error, PermissionState, Platform, Request}; + +/// Notification with an application URL delivered when its body is clicked. +/// Tags replace payloads and, where supported, earlier host notifications. Payloads are +/// kept in memory, so activation after process exit is not supported. +/// +/// ``` +/// # use rake_core as rake; +/// use rake::platform::Notification; +/// let notification = Notification { +/// tag: "export-42".into(), +/// title: "Export finished".into(), +/// body: "Open the exported document".into(), +/// activation_url: "myapp://exports/42".into(), +/// }; +/// assert_eq!(notification.tag, "export-42"); +/// ``` +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Notification { + /// Stable nonempty identifier, at most 128 UTF-8 bytes. + pub tag: String, + /// Nonempty headline, at most 1 KiB of UTF-8 text. + pub title: String, + /// Additional text, at most 16 KiB of UTF-8 text; rendering follows host policy. + pub body: String, + /// Absolute application URL, at most 16 KiB; validate its arguments on receipt. + pub activation_url: String, +} + +impl Notification { + #[doc(hidden)] + pub fn validate(&self) -> Result { + if self.tag.is_empty() + || self.tag.len() > 128 + || self.title.is_empty() + || self.title.len() > 1024 + || self.body.len() > 16 * 1024 + { + return Err(Error::InvalidInput( + "notification tag/title/body exceeds its limits".into(), + )); + } + + super::activation_url(&self.activation_url) + } +} + +/// Delegation is distinct from permission denial and actual on-screen delivery. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NotificationOutcome { + /// Submitted to the host; focus modes and host policy may suppress delivery. + Submitted, + /// Permission is absent. The application can continue or request authorization. + Denied, +} + +#[cfg(target_family = "wasm")] +mod browser; + +pub(super) fn capability() -> Capability { + #[cfg(target_family = "wasm")] + return browser::capability(); + + #[cfg(not(target_family = "wasm"))] + Capability { + supported: false, + permission: PermissionState::Unknown, + requires_user_gesture: false, + } +} + +impl Platform { + /// Queries notification permission without prompting. + pub fn notification_permission(&self) -> Request { + #[cfg(target_family = "wasm")] + return browser::permission(false); + + #[cfg(not(target_family = "wasm"))] + Box::pin(async { Err(Error::Unsupported("notifications")) }) + } + + /// Requests notification permission when the host supports it. + pub fn request_notification_permission(&self) -> Request { + #[cfg(target_family = "wasm")] + return browser::permission(true); + + #[cfg(not(target_family = "wasm"))] + self.notification_permission() + } +} diff --git a/crates/rake-core/src/platform/notifications/browser.js b/crates/rake-core/src/platform/notifications/browser.js new file mode 100644 index 00000000..1b9443f9 --- /dev/null +++ b/crates/rake-core/src/platform/notifications/browser.js @@ -0,0 +1,16 @@ +// Shared by Wasm bindings and deterministic host tests. No permission prompt at startup. +export function notification_permission() { + if (!globalThis.isSecureContext || typeof globalThis.Notification !== 'function') + throw new DOMException('notifications are unavailable', 'NotSupportedError'); + return Notification.permission; +} + +export function request_notification_permission() { + try { + const permission = notification_permission(); + if (permission !== 'default') return Promise.resolve(permission); + if (globalThis.navigator?.userActivation?.isActive === false) + throw new DOMException('notification permission requires a user gesture', 'NotAllowedError'); + return Notification.requestPermission(); + } catch (error) { return Promise.reject(error); } +} diff --git a/crates/rake-core/src/platform/notifications/browser.rs b/crates/rake-core/src/platform/notifications/browser.rs new file mode 100644 index 00000000..3f3204e6 --- /dev/null +++ b/crates/rake-core/src/platform/notifications/browser.rs @@ -0,0 +1,55 @@ +//! Browser host requests with retained callback ownership and best-effort focus. + +use super::{Capability, PermissionState, Request}; +use wasm_bindgen::prelude::*; +use wasm_bindgen_futures::JsFuture; + +#[wasm_bindgen(module = "/src/platform/notifications/browser.js")] +extern "C" { + #[wasm_bindgen(catch, js_name = notification_permission)] + fn query() -> Result; + #[wasm_bindgen(js_name = request_notification_permission)] + fn request() -> js_sys::Promise; +} + +fn state(value: &str) -> PermissionState { + match value { + "granted" => PermissionState::Granted, + "denied" => PermissionState::Denied, + "default" => PermissionState::Prompt, + _ => PermissionState::Unknown, + } +} + +pub(super) fn capability() -> Capability { + let permission = query(); + + Capability { + supported: permission.is_ok(), + permission: permission + .as_deref() + .map(state) + .unwrap_or(PermissionState::Unknown), + requires_user_gesture: true, + } +} + +pub(super) fn permission(prompt: bool) -> Request { + if prompt { + let request = JsFuture::from(request()); + + Box::pin(async move { + let value = request.await.map_err(|error| { + super::super::browser::error("notification authorization", error) + })?; + + Ok(state(value.as_string().as_deref().unwrap_or("unknown"))) + }) + } else { + let result = query() + .map(|value| state(&value)) + .map_err(|error| super::super::browser::error("notifications", error)); + + Box::pin(async { result }) + } +} diff --git a/crates/rake/src/platform/preferences.rs b/crates/rake-core/src/platform/preferences.rs similarity index 100% rename from crates/rake/src/platform/preferences.rs rename to crates/rake-core/src/platform/preferences.rs diff --git a/crates/rake-core/src/platform/secrets.rs b/crates/rake-core/src/platform/secrets.rs new file mode 100644 index 00000000..afeabc79 --- /dev/null +++ b/crates/rake-core/src/platform/secrets.rs @@ -0,0 +1,143 @@ +//! App-namespaced credentials; values never enter Rake's storage or inspection registry. +use super::{Error, Platform}; +use zeroize::Zeroizing; + +/// Owned secret bytes. Debug is redacted; serialization and Display are deliberately absent. +/// Rake-owned bytes are zeroized on drop; GPUI and OS copies are outside that guarantee. +pub struct Secret(Zeroizing>); + +impl Secret { + /// Takes ownership of bytes without making another copy. + pub fn new(bytes: Vec) -> Self { + Self(Zeroizing::new(bytes)) + } + + /// Explicitly exposes bytes for authentication. Never log or inspect this slice. + pub fn expose(&self) -> &[u8] { + &self.0 + } +} + +impl From for Secret { + fn from(token: String) -> Self { + Self::new(token.into_bytes()) + } +} + +impl From> for Secret { + fn from(bytes: Vec) -> Self { + Self::new(bytes) + } +} + +impl std::fmt::Debug for Secret { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Secret([REDACTED])") + } +} + +/// A credential namespace. Use the same application id across restarts. +#[derive(Clone)] +pub struct Secrets { + app_id: String, +} + +impl std::fmt::Debug for Secrets { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Secrets") + .field("app_id", &self.app_id) + .finish() + } +} + +impl Platform { + /// Opens the configured application's credential namespace without accessing the keychain. + /// + /// # Errors + /// Returns [`Error::MissingApplicationId`] when the platform has no configured + /// application id, or [`Error::InvalidInput`] if the id is outside 1–128 UTF-8 bytes. + /// Credential operations apply the same length limit to names. + pub fn secrets(&self) -> Result { + let app_id = self + .application_id + .as_deref() + .ok_or(Error::MissingApplicationId)?; + + validate(app_id)?; + + Ok(Secrets { + app_id: app_id.into(), + }) + } +} + +fn validate(value: &str) -> Result<(), Error> { + if value.is_empty() || value.len() > 128 { + return Err(Error::InvalidInput( + "secret id/name must contain 1..=128 bytes".into(), + )); + } + + Ok(()) +} + +impl Secrets { + #[doc(hidden)] + pub fn key(&self, name: &str) -> Result { + validate(name)?; + // Hex is injective, preserves case and cannot introduce URL delimiters or NULs. + fn hex(value: &str) -> String { + value + .as_bytes() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() + } + + Ok(format!( + "rake-secret://v1/{}/{}", + hex(&self.app_id), + hex(name) + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_platform_has_no_secret_namespace() { + assert!(matches!( + Platform::default().secrets(), + Err(Error::MissingApplicationId) + )); + } + + #[test] + fn names_do_not_collide() { + let first = Platform::for_application("a/b").secrets().unwrap(); + let second = Platform::for_application("a").secrets().unwrap(); + + assert_ne!(first.key("c").unwrap(), second.key("b/c").unwrap()); + assert_ne!(first.key("A").unwrap(), first.key("a").unwrap()); + assert!(first.key("").is_err()); + } + + #[test] + fn conversions_reuse_owned_buffers() { + let token = String::from("tökén"); + let token_ptr = token.as_ptr(); + let secret = Secret::from(token); + + assert_eq!(secret.expose(), "tökén".as_bytes()); + assert_eq!(secret.expose().as_ptr(), token_ptr); + + let bytes = vec![0, 255, 42]; + let bytes_ptr = bytes.as_ptr(); + let secret = Secret::from(bytes); + + assert_eq!(secret.expose(), &[0, 255, 42]); + assert_eq!(secret.expose().as_ptr(), bytes_ptr); + } +} diff --git a/crates/rake-core/src/platform/shortcuts.rs b/crates/rake-core/src/platform/shortcuts.rs new file mode 100644 index 00000000..a8833354 --- /dev/null +++ b/crates/rake-core/src/platform/shortcuts.rs @@ -0,0 +1,34 @@ +use super::{Capability, PermissionState, Platform, Request}; + +/// Global shortcut service. Enable `global-shortcuts` (also enabled by `tray`). +#[derive(Clone, Debug, Default)] +pub struct GlobalShortcuts; + +impl Platform { + /// Returns the global shortcut service, including on unsupported hosts. + pub fn global_shortcuts(&self) -> GlobalShortcuts { + self.shortcuts.clone() + } +} + +impl GlobalShortcuts { + pub(super) fn capability(&self) -> Capability { + Capability { + supported: false, + permission: if cfg!(target_os = "linux") { + PermissionState::Unknown + } else { + PermissionState::NotRequired + }, + requires_user_gesture: false, + } + } +} + +impl GlobalShortcuts { + /// Queries the current native session, including Wayland portal availability. + /// Does not register keys or request permission. + pub fn available(&self) -> Request { + Box::pin(async { Ok(false) }) + } +} diff --git a/crates/rake/src/quit.rs b/crates/rake-core/src/quit.rs similarity index 83% rename from crates/rake/src/quit.rs rename to crates/rake-core/src/quit.rs index d10b35f8..664232b7 100644 --- a/crates/rake/src/quit.rs +++ b/crates/rake-core/src/quit.rs @@ -6,6 +6,7 @@ //! futures stopped and entries were disposed; the host owns process/page lifetime. //! //! ``` +//! # use rake_core as rake; //! use rake::prelude::*; //! use rake::router::NoRoute; //! let router = Router::::new(RouterConfig::default()); @@ -17,12 +18,3 @@ pub use crate::router::QuitGuardContext; pub use rake_protocol::quit::*; - -#[cfg(feature = "gpui")] -gpui::actions!( - rake, - [ - /// Requests guarded application quit with the default wait-for-jobs policy. - RequestQuit, - ] -); diff --git a/crates/rake-core/src/reload/host.rs b/crates/rake-core/src/reload/host.rs new file mode 100644 index 00000000..79140301 --- /dev/null +++ b/crates/rake-core/src/reload/host.rs @@ -0,0 +1,22 @@ +//! Browser development checkpoint transport. +use super::{MAX_CHECKPOINT_BYTES, WorkspaceCheckpoint}; + +#[doc(hidden)] +pub const STORAGE_KEY: &str = "rake-dev-workspace"; + +#[cfg(target_family = "wasm")] +pub(crate) fn store(checkpoint: &WorkspaceCheckpoint) -> Result<(), String> { + let bytes = serde_json::to_string(checkpoint).map_err(|error| error.to_string())?; + + if bytes.len() > MAX_CHECKPOINT_BYTES { + return Err("reload checkpoint exceeds 512 KiB".into()); + } + + web_sys::window() + .ok_or("browser unavailable")? + .session_storage() + .map_err(|error| format!("{error:?}"))? + .ok_or("session storage unavailable")? + .set_item(STORAGE_KEY, &bytes) + .map_err(|error| format!("{error:?}")) +} diff --git a/crates/rake-core/src/reload/mod.rs b/crates/rake-core/src/reload/mod.rs new file mode 100644 index 00000000..d5a85579 --- /dev/null +++ b/crates/rake-core/src/reload/mod.rs @@ -0,0 +1,6 @@ +//! Development checkpoint contracts. +pub use rake_protocol::reload::*; + +#[cfg(target_family = "wasm")] +#[doc(hidden)] +pub mod host; diff --git a/crates/rake/src/router/admission.rs b/crates/rake-core/src/router/admission.rs similarity index 88% rename from crates/rake/src/router/admission.rs rename to crates/rake-core/src/router/admission.rs index 008206be..3c39a599 100644 --- a/crates/rake/src/router/admission.rs +++ b/crates/rake-core/src/router/admission.rs @@ -29,7 +29,7 @@ pub enum Admission { /// The context intentionally has no entry ID, revision, dirty state, or view /// handle: admission runs before entry allocation, host creation, and mounting. #[derive(Clone)] -pub struct AdmissionContext { +pub struct AdmissionContext { /// Operation being admitted. pub operation_id: OperationId, /// Origin/presenting host. A provisional NewWindow has no host yet. @@ -39,8 +39,8 @@ pub struct AdmissionContext { /// Candidate typed destination. pub destination: R, /// Immutable application service composition. - pub services: ServiceRegistry, + pub services: Services, } -pub(crate) type Callback = - Rc) -> LocalBoxFuture<'static, Admission>>; +#[doc(hidden)] +pub type Callback = Rc) -> LocalBoxFuture<'static, Admission>>; diff --git a/crates/rake/src/router/mod.rs b/crates/rake-core/src/router/mod.rs similarity index 71% rename from crates/rake/src/router/mod.rs rename to crates/rake-core/src/router/mod.rs index 1d0d2beb..cbe47e60 100644 --- a/crates/rake/src/router/mod.rs +++ b/crates/rake-core/src/router/mod.rs @@ -4,6 +4,7 @@ //! submission queues eagerly, while one host-owned driver executes local futures. //! //! ``` +//! # use rake_core as rake; //! use rake::prelude::*; //! //! #[derive(Clone, Route)] @@ -24,6 +25,7 @@ //! Ambiguous schemas fail at compile time: //! //! ```compile_fail +//! # use rake_core as rake; //! #[derive(Clone, rake::Route)] //! enum Bad { //! #[route(id = "same", path = "/a")] @@ -33,40 +35,19 @@ //! } //! ``` -#[cfg(feature = "gpui")] -pub(crate) mod layout; - -#[cfg(feature = "gpui")] -pub use layout::LayoutContext; - -#[cfg(feature = "gpui")] -mod navigation_view; - -#[cfg(feature = "gpui")] -pub use navigation_view::NavigationBoundary; - pub(crate) mod admission; -#[cfg(feature = "gpui")] -mod page; +pub(crate) mod mount; pub(crate) mod runtime; mod types; -#[cfg(feature = "gpui")] -pub(crate) mod view; pub(crate) mod web; pub use admission::{Admission, AdmissionContext}; +pub use mount::{MountedRoute, RouteMount, RouteMountContext, RoutePresentation}; -#[cfg(feature = "gpui")] -#[doc(hidden)] -pub use page::{ - __mount_loaded_page, __mount_page, __prepare_loaded_page, __routes, __routes_prepared, -}; - -#[cfg(feature = "gpui")] -pub use page::{LoadedPage, Page}; pub use rake_protocol::router::*; pub use runtime::{EntryHandle, Navigator, Router, TabHandle}; pub use types::*; -#[cfg(feature = "gpui")] -pub use view::{PageContext, RouteOutlet, RouteViews, TabBar}; pub use web::{BrowserCheckpoint, HistoryChange, WebConfig, WebRouting}; + +#[doc(hidden)] +pub use runtime::{AdmissionCallback, Guard, HostBinding, QuitGuard}; diff --git a/crates/rake-core/src/router/mount.rs b/crates/rake-core/src/router/mount.rs new file mode 100644 index 00000000..8500f4da --- /dev/null +++ b/crates/rake-core/src/router/mount.rs @@ -0,0 +1,115 @@ +//! Local route preparation, attachment and retained mount lifetime. + +use std::any::Any; + +use futures::future::LocalBoxFuture; + +use crate::http::CancellationToken; +use crate::services::ServiceRegistry; +use crate::tasks::HostVisibility; + +use super::{EntryHandle, EntryId, MountError, Navigator, PreparedPage, Route, WindowId}; + +/// The router's presentation of a committed mount. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum RoutePresentation { + /// The entry is alive in a tab or its history, but is not the window's selected entry. + Retained, + /// The entry is selected in its window, which may itself be hidden. + Presented(HostVisibility), +} + +/// The provisional entry and its host, supplied when mounting a fresh route. +pub struct RouteMountContext { + /// Window that owns the entry. A secondary host has already been opened. + pub window_id: WindowId, + /// Stable identity of this visit, preserved across history and checkpoint restore. + pub entry_id: EntryId, + /// Weak handle valid during mount, including for reading restored entry state. + pub entry: EntryHandle, + /// Weak navigator bound to the entry's window and tab. + pub navigator: Navigator, +} + +/// The host's concrete view and resources for one retained route entry. +/// +/// The router takes ownership of the handle and retains it across history +/// traversal. Implementations can hold local UI state and weak runtime handles +/// and should avoid owning the router or a strong runtime client. +pub trait MountedRoute: Any { + /// Applies a presentation change synchronously on the host's event loop. + /// + /// The first call follows commit, with the entry already in the router + /// snapshot. A hidden history entry receives `Retained`. When selection + /// changes, the previous entry is hidden before the next is shown. Changes + /// to the selected window's reported visibility are also delivered here. + /// A provisional mount never receives this callback. + /// + /// During checkpoint restore, apply the initial presentation before + /// returning. The router reports `Restored` after all initial callbacks + /// return. A host can report its first painted frame separately. + fn presentation_changed(&self, _presentation: RoutePresentation) {} + + /// Releases host resources once, after the entry's weak handle is invalidated. + /// + /// A presented entry is first told it is retained. A rolled-back mount + /// receives only disposal. The router releases its ownership after this + /// call. Implement this for framework resources that need explicit cleanup. + fn dispose(&self) {} +} + +/// Prepares and mounts typed destinations on the caller-driven router loop. +/// +/// Both callbacks can use local futures. The router owns admission and history, +/// and publishes the mount only after the transition commits. +pub trait RouteMount: 'static { + /// Prepares owned data after admission and initial guards, before mounting + /// or opening a secondary host. During restore, all entries prepare before + /// any secondary host is opened. + /// + /// The router can drop the future on cancellation. Use the token for + /// cooperative work, and release provisional resources on drop. + /// + /// # Errors + /// Return a preparation error to leave the current workspace intact. + fn prepare( + &self, + _destination: &R, + _services: ServiceRegistry, + _cancellation: CancellationToken, + ) -> LocalBoxFuture<'static, Result> { + Box::pin(async { Ok(PreparedPage::empty()) }) + } + + /// Consumes prepared data and creates a provisional mount. + /// + /// Keep it hidden until committed presentation. During restore, read + /// entry checkpoints through the weak handle before returning. On error or + /// cancellation before a handle is returned, the adapter must clean up + /// resources it has created. After it returns a handle, the router disposes + /// it on rollback, removal, close or shutdown. + /// + /// # Errors + /// Return a mount error to leave the current workspace intact. + fn mount( + &self, + destination: &R, + prepared: PreparedPage, + context: RouteMountContext, + ) -> LocalBoxFuture<'static, Result, MountError>>; +} + +pub(crate) struct Headless; + +impl MountedRoute for Headless {} + +impl RouteMount for Headless { + fn mount( + &self, + _destination: &R, + _prepared: PreparedPage, + _context: RouteMountContext, + ) -> LocalBoxFuture<'static, Result, MountError>> { + Box::pin(async { Ok(Box::new(Self) as Box) }) + } +} diff --git a/crates/rake/src/router/runtime.rs b/crates/rake-core/src/router/runtime.rs similarity index 92% rename from crates/rake/src/router/runtime.rs rename to crates/rake-core/src/router/runtime.rs index eea43a97..96a0e1c9 100644 --- a/crates/rake/src/router/runtime.rs +++ b/crates/rake-core/src/router/runtime.rs @@ -1,5 +1,6 @@ //! Local operation scheduler and the authoritative router state owner. +#[cfg(test)] use std::any::Any; use std::cell::{Cell, RefCell}; use std::collections::{BTreeMap, BTreeSet, VecDeque}; @@ -25,11 +26,11 @@ use super::{ Activation, BlockReason, BrowserCheckpoint, CancelReason, ChoiceAction, Closed, DecisionChoice, DecisionError, DecisionId, DecisionRequest, DecisionSnapshot, DisposeReason, Entered, EntryId, EntrySnapshot, GuardContext, GuardKind, GuardReason, GuardResult, HistoryChange, ModeChanged, - MountError, NavigationKey, NavigationState, NavigationStatus, OpenOptions, OpenTarget, Opened, - Operation, OperationError, OperationId, OperationState, Outcome, PreparedPage, - QuitGuardContext, RevealScope, Revealed, Route, RouteDecodeError, RouterConfig, RouterSnapshot, - RuntimeId, Selected, TabId, TabMode, TabSnapshot, WindowClosed, WindowHost, WindowId, - WindowSnapshot, + MountError, MountedRoute, NavigationKey, NavigationState, NavigationStatus, OpenOptions, + OpenTarget, Opened, Operation, OperationError, OperationId, OperationState, Outcome, + PreparedPage, QuitGuardContext, RevealScope, Revealed, Route, RouteDecodeError, RouteMount, + RouteMountContext, RoutePresentation, RouterConfig, RouterSnapshot, RuntimeId, Selected, TabId, + TabMode, TabSnapshot, WindowClosed, WindowHost, WindowId, WindowSnapshot, }; mod admission; @@ -40,28 +41,26 @@ mod reload; mod updates; mod windows; +#[doc(hidden)] +pub use windows::HostBinding; + #[cfg(test)] mod tests; -pub(crate) type Guard = Rc) -> LocalBoxFuture<'static, GuardResult>>; +#[doc(hidden)] +pub type Guard = Rc) -> LocalBoxFuture<'static, GuardResult>>; -pub(crate) use crate::router::admission::Callback as AdmissionCallback; +#[doc(hidden)] +pub use crate::router::admission::Callback as AdmissionCallback; -pub(crate) type QuitGuard = +#[doc(hidden)] +pub type QuitGuard = Rc LocalBoxFuture<'static, Result<(), GuardReason>>>; +#[cfg(test)] pub(crate) type Resource = Rc; -#[cfg(feature = "gpui")] -type WindowContexts = Rc>>; - -#[cfg(feature = "gpui")] -#[derive(Clone, Copy)] -enum HostClosePolicy { - Guarded, - Detach, -} - +#[cfg(test)] pub(crate) type Mount = Rc< dyn Fn( R, @@ -79,6 +78,7 @@ pub(crate) type Prepare = Rc< ) -> LocalBoxFuture<'static, Result>, >; +#[cfg(test)] pub(crate) type PreparedMount = Rc< dyn Fn( R, @@ -88,6 +88,17 @@ pub(crate) type PreparedMount = Rc< ) -> LocalBoxFuture<'static, Result>, >; +type Attach = Rc< + dyn Fn( + &R, + PreparedPage, + RouteMountContext, + ) -> LocalBoxFuture<'static, Result, MountError>>, +>; + +#[cfg(test)] +impl MountedRoute for Resource {} + type ReloadCapture = Rc Result>; type HistorySink = Rc Result<(), String>>; @@ -103,7 +114,8 @@ struct Entry { dirty: Cell, alive: Cell, guards: RefCell>>, - resource: RefCell>, + mount: RefCell>>, + presentation: Cell>, cancellation: CancellationToken, reload_capture: RefCell>, restored_state: RefCell>, @@ -111,10 +123,33 @@ struct Entry { } impl Entry { + fn present(&self, presentation: RoutePresentation) { + let mount = self.mount.borrow().clone(); + + if let Some(mount) = mount + && self.presentation.replace(Some(presentation)) != Some(presentation) + { + mount.presentation_changed(presentation); + } + } + fn dispose(&self) { - self.scope.close(); self.alive.set(false); + self.scope.close(); self.cancellation.cancel(); + + let mount = self.mount.take(); + + if let Some(mount) = mount { + if matches!( + self.presentation.take(), + Some(RoutePresentation::Presented(_)) + ) { + mount.presentation_changed(RoutePresentation::Retained); + } + + mount.dispose(); + } } } @@ -300,26 +335,18 @@ struct Core { update_restart_error: RefCell>, #[cfg(feature = "updates")] update_exit: Cell, - #[cfg(all(feature = "native-lifecycle", feature = "gpui", target_os = "macos"))] - native_quit: RefCell>>, - #[cfg(all(feature = "updates", feature = "gpui", not(target_family = "wasm")))] - update_revision: Cell, reload: RefCell, - reload_ui_ready: RefCell>, #[cfg(target_family = "wasm")] page_reload: Cell, control: Rc, - #[cfg(feature = "gpui")] - host: RefCell>, - #[cfg(feature = "gpui")] - view_contexts: RefCell>, + host_binding: std::cell::OnceCell>, state: RefCell>, runtime: RuntimeId, initial_window: Cell, config: RouterConfig, collector: Collector, prepare: Prepare, - prepared_mount: PreparedMount, + attach: Attach, window_host: RefCell>>, window_closes: RefCell>>, guards: RefCell>>, @@ -337,6 +364,55 @@ impl Core { self.event.notify(usize::MAX); } + fn sync_presentation(&self, window: WindowId) { + let (retained, presented) = { + let state = self.state.borrow(); + + let Some(host) = state.windows.get(&window) else { + return; + }; + + let mut retained = Vec::new(); + let mut presented = None; + + for tab in state.tabs.iter().filter(|tab| tab.window == window) { + for entry in &tab.entries { + let current = entry.id == tab.entries[tab.cursor].id; + let selected = current && host.selected == Some(tab.id); + + entry + .scope + .update(current, selected, tab.mode == TabMode::Live); + + if selected { + presented = Some(entry.clone()); + } else { + retained.push(entry.clone()); + } + } + } + + (retained, presented) + }; + + for entry in retained { + entry.present(RoutePresentation::Retained); + } + + if let Some(entry) = presented { + let visibility = self + .state + .borrow() + .windows + .get(&window) + .map(|host| host.visibility); + + if let Some(visibility) = visibility { + entry.present(RoutePresentation::Presented(visibility)); + } + } + } + fn status(&self, id: OperationId, status: OperationState) { self.state.borrow_mut().operations.insert(id, status); self.notify(); @@ -714,24 +790,57 @@ impl Core { pub struct Router(Rc>); impl Router { - /// Creates a headless routing runtime. GPUI applications install their real mount adapter. + /// Creates a headless routing runtime. pub fn new(config: RouterConfig) -> Self { - Self::with_mount( - config, - Collector::default(), - Rc::new(|_, _, _| Box::pin(async { Ok(Rc::new(()) as Resource) })), - ) + Self::with_services(config, crate::services::ServiceRegistry::new()) } /// Creates a headless runtime with a fixed typed application composition. pub fn with_services(config: RouterConfig, services: crate::services::ServiceRegistry) -> Self { - let router = Self::new(config); + Self::with_route_mount(config, services, super::mount::Headless) + } + + /// Creates a router whose retained route views are owned by the host adapter. + /// + /// The host polls [`Self::run`] on its event loop, supplies visibility with + /// [`Self::set_window_visibility`] and stops the router on host teardown. + /// The initial window already exists. Install a [`WindowHost`] to support + /// opening additional physical hosts. + pub fn with_route_mount( + config: RouterConfig, + services: crate::services::ServiceRegistry, + adapter: impl RouteMount, + ) -> Self { + Self::with_route_mount_and_collector(config, services, Collector::default(), adapter) + } + + #[doc(hidden)] + pub fn with_route_mount_and_collector( + config: RouterConfig, + services: crate::services::ServiceRegistry, + collector: Collector, + adapter: impl RouteMount, + ) -> Self { + let adapter = Rc::new(adapter); + let preparing = adapter.clone(); + let preparation_services = services.clone(); + + let prepare = Rc::new(move |destination: R, _, _, cancellation| { + preparing.prepare(&destination, preparation_services.clone(), cancellation) + }); + + let attach: Attach = Rc::new(move |destination, prepared, context| { + adapter.mount(destination, prepared, context) + }); + + let router = Self::with_mount_callbacks(config, collector, prepare, attach); router.client().set_services(services); router } + #[cfg(test)] pub(crate) fn with_mount(config: RouterConfig, collector: Collector, mount: Mount) -> Self { let prepared_mount: PreparedMount = Rc::new(move |destination, entry, navigator, _| mount(destination, entry, navigator)); @@ -742,11 +851,32 @@ impl Router { Self::with_prepared_mount(config, collector, prepare, prepared_mount) } + #[cfg(test)] pub(crate) fn with_prepared_mount( config: RouterConfig, collector: Collector, prepare: Prepare, mount: PreparedMount, + ) -> Self { + let attach: Attach = Rc::new(move |destination, prepared, context| { + let mounted = mount( + destination.clone(), + context.entry, + context.navigator, + prepared, + ); + + Box::pin(async move { Ok(Box::new(mounted.await?) as Box) }) + }); + + Self::with_mount_callbacks(config, collector, prepare, attach) + } + + fn with_mount_callbacks( + config: RouterConfig, + collector: Collector, + prepare: Prepare, + attach: Attach, ) -> Self { let runtime = RuntimeId(uuid::Uuid::new_v4()); let tasks = WorkRuntime::new(runtime, config.tasks.clone(), collector.clone()); @@ -760,14 +890,10 @@ impl Router { request: None, error: None, }), - reload_ui_ready: RefCell::new(BTreeSet::new()), #[cfg(target_family = "wasm")] page_reload: Cell::new(false), control: Rc::new(crate::control::ClientState::new(config.control_requests)), - #[cfg(feature = "gpui")] - host: RefCell::new(BTreeMap::new()), - #[cfg(feature = "gpui")] - view_contexts: RefCell::new(None), + host_binding: std::cell::OnceCell::new(), state: RefCell::new(State { windows: BTreeMap::from([(WindowId(1), WindowState::default())]), tabs: Vec::new(), @@ -791,7 +917,7 @@ impl Router { config, collector, prepare, - prepared_mount: mount, + attach, window_host: RefCell::new(None), window_closes: RefCell::new(BTreeMap::new()), guards: RefCell::new(Vec::new()), @@ -810,10 +936,6 @@ impl Router { update_restart_error: RefCell::new(None), #[cfg(feature = "updates")] update_exit: Cell::new(rake_updates::RestartDisposition::ExitHost), - #[cfg(all(feature = "native-lifecycle", feature = "gpui", target_os = "macos"))] - native_quit: RefCell::new(None), - #[cfg(all(feature = "updates", feature = "gpui", not(target_family = "wasm")))] - update_revision: Cell::new(u64::MAX), has_window: Cell::new(false), shutdown: Cell::new(false), })) @@ -1207,7 +1329,7 @@ impl Router { pub(crate) fn frame_records( &self, - store: &crate::inspection::Store, + store: &dyn crate::inspection::InspectionHost, after: u64, ) -> crate::inspection::Frames { store.frames(after, &self.0.collector) @@ -1240,7 +1362,8 @@ impl Router { self.0.collector.snapshot_after(after, kind) } - pub(crate) fn cancel_task(&self, id: crate::tasks::TaskId) -> Result { + #[doc(hidden)] + pub fn cancel_task(&self, id: crate::tasks::TaskId) -> Result { self.0.tasks.cancel(id) } @@ -1265,7 +1388,8 @@ impl Router { }) } - pub(crate) fn revision(&self) -> u64 { + #[doc(hidden)] + pub fn revision(&self) -> u64 { self.0.state.borrow().revision + self.0.tasks.revision() } @@ -1316,19 +1440,31 @@ impl Router { pub fn shutdown(&self) { self.0.shutdown.set(true); self.0.tasks.shutdown(); - #[cfg(feature = "gpui")] - self.0.host.borrow_mut().clear(); - for token in self.0.state.borrow().tokens.values() { - token.cancel(); + if let Some(host) = self.0.host_binding.get() { + host.shutdown(); } - for tab in &self.0.state.borrow().tabs { - tab.scope.close(); + let entries: Vec<_> = { + let state = self.0.state.borrow(); + + for token in state.tokens.values() { + token.cancel(); + } - for entry in &tab.entries { - entry.dispose(); + for tab in &state.tabs { + tab.scope.close(); } + + state + .tabs + .iter() + .flat_map(|tab| tab.entries.iter().cloned()) + .collect() + }; + + for entry in entries { + entry.dispose(); } self.0.work.notify(usize::MAX); @@ -1422,157 +1558,8 @@ impl Router { let _ = self.set_window_visibility(self.0.initial_window.get(), visibility); } - #[cfg(feature = "gpui")] - pub(crate) fn observe_host(&self, window: &gpui::Window, cx: &gpui::App) { - self.observe_host_in_with_policy( - self.0.initial_window.get(), - window, - cx, - HostClosePolicy::Guarded, - ); - } - - /// Observes a standalone root while allowing its native window to close - /// without requesting application quit. The runtime remains available for - /// tray/background work until its owning host explicitly shuts it down. - #[cfg(feature = "gpui")] - pub(crate) fn observe_root_host(&self, window: &gpui::Window, cx: &gpui::App) { - self.observe_host_in_with_policy( - self.0.initial_window.get(), - window, - cx, - HostClosePolicy::Detach, - ); - } - - #[cfg(feature = "gpui")] - pub(crate) fn observe_host_in(&self, id: WindowId, window: &gpui::Window, cx: &gpui::App) { - self.observe_host_in_with_policy(id, window, cx, HostClosePolicy::Guarded); - } - - #[cfg(feature = "gpui")] - fn observe_host_in_with_policy( - &self, - id: WindowId, - window: &gpui::Window, - cx: &gpui::App, - close_policy: HostClosePolicy, - ) { - #[cfg(target_family = "wasm")] - let _ = close_policy; - - self.0.has_window.set(true); - let core = Rc::downgrade(&self.0); - let shutdown = core.clone(); - let unload = core.clone(); - - #[cfg(not(target_family = "wasm"))] - { - let closing = core.clone(); - - window.on_window_should_close(cx, move |window, cx| { - crate::window_state::native::capture(window, cx); - - let Some(core) = closing.upgrade() else { - return true; - }; - - if matches!(close_policy, HostClosePolicy::Detach) { - Router(core).detach_host(id); - - return true; - } - - if core.quit.borrow().phase == crate::quit::QuitPhase::Ready { - return true; - } - - if core.window_host.borrow().is_none() { - drop(Router(core).quit(crate::quit::QuitOptions::default())); - - return false; - } - - let opening = core - .state - .borrow() - .windows - .get(&id) - .and_then(|window| window.opening); - - if let Some(operation) = opening { - let _ = Router(core).cancel(operation); - } else if !core.state.borrow().windows.contains_key(&id) { - return true; - } else { - drop(Router(core).close_window(id)); - } - - false - }); - } - - let observer = crate::tasks::host::HostObserver::attach( - move |visibility| { - if let Some(core) = core.upgrade() { - let _ = Router(core).set_window_visibility(id, visibility); - } - }, - move || { - if let Some(core) = shutdown.upgrade() { - Router(core).shutdown(); - } - }, - move || { - let Some(core) = unload.upgrade() else { - return false; - }; - - #[cfg(target_family = "wasm")] - if core.page_reload.replace(false) { - return false; - } - - let router = Router(core); - let snapshot = router.snapshot(); - - snapshot.quit.phase != crate::quit::QuitPhase::Ready - && (snapshot.quit.phase.is_pending() - || snapshot - .tabs - .iter() - .flat_map(|tab| &tab.entries) - .any(|entry| entry.dirty) - || !snapshot.quit.pending_tasks.is_empty() - || !snapshot.quit.pending_operations.is_empty() - || !router.0.quit_guards.borrow().is_empty()) - }, - window, - cx, - ); - - self.0.host.borrow_mut().insert(id, observer); - } - - #[cfg(feature = "gpui")] - pub(crate) fn detach_host(&self, id: WindowId) { - let _ = self.set_window_visibility(id, HostVisibility::Hidden); - - let empty = { - let mut hosts = self.0.host.borrow_mut(); - - hosts.remove(&id); - - hosts.is_empty() - }; - - if empty { - self.0.has_window.set(false); - } - } - - #[cfg(feature = "gpui")] - pub(crate) fn resource(&self, window: WindowId) -> Option { + #[doc(hidden)] + pub fn presented_mount(&self, window: WindowId) -> Option> { let state = self.0.state.borrow(); let entry = state @@ -1580,7 +1567,7 @@ impl Router { .ok()? .current(); - entry.resource.borrow().clone() + entry.mount.borrow().clone() } } @@ -1606,7 +1593,8 @@ pub struct Navigator { impl Navigator { /// Waits without retaining the runtime until it shuts down or disappears. - pub(crate) async fn stopped(&self) { + #[doc(hidden)] + pub async fn stopped(&self) { loop { let Some(core) = self.core.upgrade() else { return; @@ -1648,7 +1636,8 @@ impl Navigator { } } - pub(crate) fn runtime(&self) -> Result, OperationError> { + #[doc(hidden)] + pub fn runtime(&self) -> Result, OperationError> { let core = self.core.upgrade().ok_or(OperationError::RuntimeShutdown)?; if core.shutdown.get() { @@ -1698,7 +1687,7 @@ impl Navigator { return Err(OperationError::InvalidOptions); } - if options.target == OpenTarget::NewWindow && core.window_host.borrow().is_none() { + if options.target == OpenTarget::NewWindow && !core.supports_new_windows() { return Err(OperationError::UnsupportedCapability(options.target)); } @@ -1854,7 +1843,8 @@ impl Navigator { result } - pub(crate) fn reconcile_history(&self, error: String) { + #[doc(hidden)] + pub fn reconcile_history(&self, error: String) { if let Ok(core) = self.core() { core.state.borrow_mut().advance_browser(); core.emit_history(true); @@ -2489,7 +2479,8 @@ fn fresh( dirty: Cell::new(false), alive: Cell::new(true), guards: RefCell::new(Vec::new()), - resource: RefCell::new(None), + mount: RefCell::new(None), + presentation: Cell::new(None), cancellation: CancellationToken::new(), reload_capture: RefCell::new(None), restored_state: RefCell::new(None), @@ -2863,10 +2854,11 @@ async fn transition( 'plan: loop { action.check(core)?; + // Drop the provisional entry before closing its native host on rollback. + let mut provisional = None; let plan = plan(core, &action, window)?; core.navigation_plan(id, &action, window, &plan.entry); - let mut provisional = None; loop { let mut approvals = Vec::new(); @@ -2896,7 +2888,7 @@ async fn transition( let mut prepared = PreparedPage::empty(); let mut mount_input = None; - if plan.entry.resource.borrow().is_none() + if plan.entry.mount.borrow().is_none() && !matches!(plan.transition, Transition::Close | Transition::Mode(_)) { let handle = EntryHandle { @@ -3020,11 +3012,15 @@ async fn transition( } if let Some((handle, navigator)) = mount_input { - let resource = (core.prepared_mount)( - plan.entry.destination.clone(), - handle, - navigator, + let mounted = (core.attach)( + &plan.entry.destination, prepared, + RouteMountContext { + window_id: plan.entry.window, + entry_id: plan.entry.id, + entry: handle, + navigator, + }, ) .instrument(tracing::info_span!("router.mount", entry_id = %plan.entry.id)) .await @@ -3034,7 +3030,7 @@ async fn transition( OperationError::Mount(error) })?; - *plan.entry.resource.borrow_mut() = Some(resource); + *plan.entry.mount.borrow_mut() = Some(Rc::from(mounted)); } action.check(core)?; @@ -3150,11 +3146,6 @@ fn commit( let tab = plan.entry.tab; - for (entry, _) in &plan.disposed { - entry.dispose(); - state.invalidate(Some(entry.id)); - } - match plan.transition { Transition::New(activation, mode) => { state.tabs.push(Tab { @@ -3269,26 +3260,17 @@ fn commit( .operations .insert(operation_id, OperationState::Committed); + for (entry, _) in &plan.disposed { + state.invalidate(Some(entry.id)); + } + drop(state); - { - let state = core.state.borrow(); - for tab in &state.tabs { - for entry in &tab.entries { - let current = entry.id == tab.current().id; - - entry.scope.update( - current, - current - && state - .windows - .get(&tab.window) - .is_some_and(|host| host.selected == Some(tab.id)), - tab.mode == TabMode::Live, - ); - } - } + for (entry, _) in &plan.disposed { + entry.dispose(); } + + core.sync_presentation(window); core.notify(); if matches!(action, Action::Reveal(..) | Action::Select(_)) { diff --git a/crates/rake/src/router/runtime/admission.rs b/crates/rake-core/src/router/runtime/admission.rs similarity index 100% rename from crates/rake/src/router/runtime/admission.rs rename to crates/rake-core/src/router/runtime/admission.rs diff --git a/crates/rake/src/router/runtime/navigation.rs b/crates/rake-core/src/router/runtime/navigation.rs similarity index 100% rename from crates/rake/src/router/runtime/navigation.rs rename to crates/rake-core/src/router/runtime/navigation.rs diff --git a/crates/rake/src/router/runtime/quit.rs b/crates/rake-core/src/router/runtime/quit.rs similarity index 85% rename from crates/rake/src/router/runtime/quit.rs rename to crates/rake-core/src/router/runtime/quit.rs index e5e0a40f..c36d8773 100644 --- a/crates/rake/src/router/runtime/quit.rs +++ b/crates/rake-core/src/router/runtime/quit.rs @@ -20,7 +20,8 @@ use tracing::Instrument; #[cfg(target_family = "wasm")] impl Router { - pub(crate) fn request_browser_reload( + #[doc(hidden)] + pub fn request_browser_reload( &self, options: QuitOptions, ) -> Result, crate::web::Error> { @@ -155,6 +156,33 @@ impl Router { self.0.update_restart_error.borrow().clone() } + #[cfg(feature = "updates")] + #[doc(hidden)] + pub fn notify_update_changed(&self) { + self.0.notify(); + } + + #[cfg(feature = "updates")] + #[doc(hidden)] + pub fn awaiting_provider_exit(&self) -> bool { + self.0.update_exit.get() == rake_updates::RestartDisposition::ProviderHandlesExit + } + + #[cfg(feature = "updates")] + #[doc(hidden)] + pub fn update_provider_exiting(&self) { + self.0 + .update_exit + .set(rake_updates::RestartDisposition::ExitHost); + } + + #[cfg(feature = "updates")] + #[doc(hidden)] + pub fn report_update_restart_error(&self, error: String) { + *self.0.update_restart_error.borrow_mut() = Some(error); + self.0.notify(); + } + /// Eagerly submits one guarded quit. Concurrent requests join its operation; /// the first request's job policy wins. Dropping handles never cancels quit. pub fn quit(&self, options: QuitOptions) -> Operation { @@ -491,90 +519,3 @@ async fn run_quit_guards( Ok(()) } - -#[cfg(feature = "gpui")] -impl Router { - pub(crate) fn install_quit_action(&self, cx: &mut gpui::App) { - #[cfg(all(feature = "native-lifecycle", target_os = "macos"))] - if self.0.native_quit.borrow().is_none() { - match rake_updates::NativeQuitBridge::new() { - Ok(bridge) => *self.0.native_quit.borrow_mut() = Some(Rc::new(bridge)), - Err(error) => tracing::error!( - error_type = std::any::type_name_of_val(&error), - "native quit guard could not be installed" - ), - } - } - - let core = Rc::downgrade(&self.0); - - cx.on_action(move |_: &crate::quit::RequestQuit, _| { - if let Some(core) = core.upgrade() { - drop(Router(core).quit(QuitOptions::default())); - } - }); - } -} - -#[cfg(all(feature = "native-lifecycle", feature = "gpui", target_os = "macos"))] -impl Router { - pub(crate) fn native_quit_changed(&self) -> futures::future::LocalBoxFuture<'static, ()> { - let changed = self - .0 - .native_quit - .borrow() - .as_ref() - .map(|bridge| bridge.changed()); - - async move { - if let Some(changed) = changed { - changed.await; - } else { - std::future::pending::<()>().await; - } - } - .boxed_local() - } - - #[cfg(not(feature = "updates"))] - pub(crate) async fn changed_with_native_quit(&self, revision: u64) -> u64 { - let changed = self.changed(revision); - let _ = select(Box::pin(changed), self.native_quit_changed()).await; - - self.poll_native_quit(); - - self.revision() - } - - pub(crate) fn poll_native_quit(&self) { - let requested = self - .0 - .native_quit - .borrow() - .as_ref() - .is_some_and(|bridge| bridge.take_request()); - - if requested { - drop(self.quit(QuitOptions::default())); - } - - if matches!( - self.quit_status().phase, - QuitPhase::Cancelled | QuitPhase::Blocked - ) { - self.reply_native_quit(false); - } - } - - pub(crate) fn prepare_native_exit(&self, approved: bool) { - if let Some(bridge) = self.0.native_quit.borrow().as_ref() { - bridge.prepare_exit(approved); - } - } - - pub(crate) fn reply_native_quit(&self, approved: bool) { - if let Some(bridge) = self.0.native_quit.borrow().as_ref() { - bridge.reply(approved); - } - } -} diff --git a/crates/rake/src/router/runtime/reload.rs b/crates/rake-core/src/router/runtime/reload.rs similarity index 93% rename from crates/rake/src/router/runtime/reload.rs rename to crates/rake-core/src/router/runtime/reload.rs index 93d47778..1415bd1a 100644 --- a/crates/rake/src/router/runtime/reload.rs +++ b/crates/rake-core/src/router/runtime/reload.rs @@ -1,4 +1,4 @@ -//! Owned development state and the quiescent reload boundary. +//! Owned development state and workspace checkpoint transactions. use std::cell::{Cell, RefCell}; use std::collections::BTreeSet; @@ -12,7 +12,7 @@ use crate::reload::{ ReloadState, ReloadStatus, TabCheckpoint, WorkspaceCheckpoint, }; -use crate::router::{GenerationId, Route, TabMode}; +use crate::router::{GenerationId, Route, RouteMountContext}; use crate::tasks::{HostVisibility, TaskOwner}; use super::{Entry, EntryHandle, Router, Tab}; @@ -79,18 +79,14 @@ impl Router { pub fn reload_status(&self) -> ReloadStatus { let mut status = self.0.reload.borrow().clone(); - let ready = { - let state = self.0.state.borrow(); + if status.phase == ReloadPhase::Quiescing + && self.0.tasks.quiescent() + && self.0.host_binding.get().is_none_or(|host| { + let state = self.0.state.borrow(); - self.0.reload_ui_ready.borrow().iter().all(|id| { - state - .windows - .get(id) - .is_none_or(|window| window.visibility == HostVisibility::Hidden) + host.reload_ready(&|id| state.windows.get(&id).map(|window| window.visibility)) }) - }; - - if status.phase == ReloadPhase::Quiescing && self.0.tasks.quiescent() && ready { + { status.phase = ReloadPhase::Ready; } @@ -131,22 +127,26 @@ impl Router { request: Some(request), error: None, }; - *self.0.reload_ui_ready.borrow_mut() = if self.0.has_window.get() { - self.0.state.borrow().windows.keys().copied().collect() - } else { - BTreeSet::new() - }; self.0.tasks.pause(); + + if let Some(host) = self.0.host_binding.get() { + let windows = if self.0.has_window.get() { + self.0.state.borrow().windows.keys().copied().collect() + } else { + Vec::new() + }; + + host.begin_reload(windows); + } + self.0.notify(); Ok(self.reload_status()) } - #[cfg(feature = "gpui")] - pub(crate) fn acknowledge_reload_ui(&self, window: super::WindowId) { - if self.0.reload_ui_ready.borrow_mut().remove(&window) { - self.0.notify(); - } + #[doc(hidden)] + pub fn reload_readiness_changed(&self) { + self.0.notify(); } /// Captures a prepared workspace on the UI thread. Application providers can fail; @@ -316,15 +316,15 @@ impl Router { Ok(self.reload_status()) } - #[cfg(feature = "gpui")] - pub(crate) fn reload_failed(&self, error: String) { + #[doc(hidden)] + pub fn reload_failed(&self, error: String) { self.0.reload.borrow_mut().phase = ReloadPhase::RestoreFailed; self.0.reload.borrow_mut().error = Some(error); self.0.notify(); } - #[cfg(feature = "gpui")] - pub(crate) fn clear_reload_error(&self) { + #[doc(hidden)] + pub fn clear_reload_error(&self) { self.0.reload.borrow_mut().phase = ReloadPhase::Idle; self.0.reload.borrow_mut().error = None; self.0.notify(); @@ -409,7 +409,8 @@ impl Router { if windows .iter() .any(|window| window.id.0 == 0 || !window_ids.insert(window.id)) - || (windows.len() != 1 && self.0.window_host.borrow().is_none()) + || (!matches!(windows.as_slice(), [window] if window.id == self.0.initial_window.get()) + && !self.0.supports_new_windows()) { return Err(ReloadError::Incompatible( "invalid or unsupported window identities".into(), @@ -516,7 +517,8 @@ impl Router { dirty: Cell::new(saved.dirty), alive: Cell::new(true), guards: RefCell::new(Vec::new()), - resource: RefCell::new(None), + mount: RefCell::new(None), + presentation: Cell::new(None), cancellation: CancellationToken::new(), reload_capture: RefCell::new(None), restored_state: RefCell::new(saved.state.clone()), @@ -589,10 +591,29 @@ impl Router { let mut entries = Vec::new(); for (saved, entry, handle, navigator, prepared) in pending_entries { - let resource = - (self.0.prepared_mount)(entry.destination.clone(), handle, navigator, prepared) - .await - .map_err(|error| ReloadError::State(error.to_string()))?; + let stopped = navigator.clone(); + + let attaching = (self.0.attach)( + &entry.destination, + prepared, + RouteMountContext { + window_id: entry.window, + entry_id: entry.id, + entry: handle, + navigator, + }, + ); + + let mounted = match select(attaching, Box::pin(stopped.stopped())).await { + Either::Left((result, _)) => { + result.map_err(|error| ReloadError::State(error.to_string()))? + } + Either::Right(((), _)) => { + return Err(ReloadError::State("routing runtime stopped".into())); + } + }; + + *entry.mount.borrow_mut() = Some(Rc::from(mounted)); if self.0.shutdown.get() { return Err(ReloadError::State("routing runtime stopped".into())); @@ -607,7 +628,6 @@ impl Router { entry.dirty.set(saved.dirty); entry.revision.set(saved.revision); - *entry.resource.borrow_mut() = Some(resource); entries.push(entry); } @@ -662,23 +682,14 @@ impl Router { } drop(state); - let host = self.0.window_host.borrow().clone(); for window in retired { - if let Some(host) = &host { - host.close(window); - } - + self.0.remove_window_host(window); self.0.tasks.forget_window(window); + } - #[cfg(feature = "gpui")] - { - self.0.host.borrow_mut().remove(&window); - - if let Some(contexts) = self.0.view_contexts.borrow().as_ref() { - contexts.borrow_mut().remove(&window); - } - } + for window in window_ids { + self.0.sync_presentation(window); } *self.0.reload.borrow_mut() = ReloadStatus { @@ -689,25 +700,6 @@ impl Router { error: None, }; self.0.tasks.resume(generation, checkpoint.run_sequence); - { - let state = self.0.state.borrow(); - - for tab in &state.tabs { - for entry in &tab.entries { - let current = entry.id == tab.current().id; - - entry.scope.update( - current, - current - && state - .windows - .get(&tab.window) - .is_some_and(|host| host.selected == Some(tab.id)), - tab.mode == TabMode::Live, - ); - } - } - } self.0.emit_history(true); self.0.notify(); diff --git a/crates/rake/src/router/runtime/tests.rs b/crates/rake-core/src/router/runtime/tests.rs similarity index 100% rename from crates/rake/src/router/runtime/tests.rs rename to crates/rake-core/src/router/runtime/tests.rs diff --git a/crates/rake-core/src/router/runtime/updates.rs b/crates/rake-core/src/router/runtime/updates.rs new file mode 100644 index 00000000..32f4fcfa --- /dev/null +++ b/crates/rake-core/src/router/runtime/updates.rs @@ -0,0 +1,55 @@ +//! Provider-neutral update actions share the router's existing guarded quit. +use super::{Operation, Route, Router}; +use crate::quit::{QuitOptions, QuitResult}; +use rake_updates::{Error, UpdateController}; +use std::rc::Rc; + +impl Router { + /// Returns the application's shared update model, when installed policy is available. + pub fn updates(&self) -> Option> { + self.client().services().get().ok() + } + + /// Checks the installed provider without downloading or requesting termination. + /// # Errors + /// Rejects unavailable or externally managed providers and concurrent operations. + pub fn check_for_updates(&self) -> Result<(), Error> { + self.updates() + .ok_or_else(|| Error::Policy("no update controller is installed".into()))? + .check() + } + + /// Downloads the selected update; Sparkle uses its native review UI. + /// # Errors + /// Rejects missing availability or another active operation. + pub fn download_update(&self) -> Result<(), Error> { + self.updates() + .ok_or_else(|| Error::Policy("no update controller is installed".into()))? + .download() + } + + /// Submits verified staging to the existing save, work and window quit guards. + /// # Errors + /// Rejects absent staging or a competing quit operation. + pub fn restart_for_update(&self, options: QuitOptions) -> Result, Error> { + #[cfg(target_family = "wasm")] + { + let _ = options; + + Err(Error::Policy( + "native update restart is unavailable in a browser".into(), + )) + } + + #[cfg(not(target_family = "wasm"))] + { + let updates = self + .updates() + .ok_or_else(|| Error::Policy("no update controller is installed".into()))?; + + let handoff = updates.restart_handoff(std::env::args_os().skip(1).collect())?; + + self.quit_for_update(handoff, options) + } + } +} diff --git a/crates/rake/src/router/runtime/windows.rs b/crates/rake-core/src/router/runtime/windows.rs similarity index 72% rename from crates/rake/src/router/runtime/windows.rs rename to crates/rake-core/src/router/runtime/windows.rs index 19b7336d..993ebea5 100644 --- a/crates/rake/src/router/runtime/windows.rs +++ b/crates/rake-core/src/router/runtime/windows.rs @@ -7,44 +7,101 @@ use super::{ WindowHost, WindowId, WindowState, guard, oneshot, select, }; +#[doc(hidden)] +pub trait HostBinding: std::any::Any { + fn detach_window(&self, id: WindowId); + + fn shutdown(&self); + + fn begin_reload(&self, windows: Vec); + + fn reload_ready(&self, visibility: &dyn Fn(WindowId) -> Option) -> bool; +} + impl Router { - #[cfg(feature = "gpui")] - pub(crate) fn bind_initial_window(&self, id: WindowId, contexts: super::WindowContexts) { - *self.0.view_contexts.borrow_mut() = Some(contexts); + #[doc(hidden)] + pub fn bind_host(&self, host: impl HostBinding) { + self.0.host_binding.get_or_init(|| Box::new(host)); + } + + #[doc(hidden)] + pub fn host_binding(&self) -> Option<&dyn HostBinding> { + self.0.host_binding.get().map(Box::as_ref) + } + + #[doc(hidden)] + pub fn set_initial_window(&self, id: WindowId) { self.0.initial_window.set(id); self.0.state.borrow_mut().windows = std::collections::BTreeMap::from([(id, WindowState::default())]); } - /// Registers the UI context of a window reserved by a custom [`WindowHost`]. - /// Call from the host's `open` callback before it resolves. The router must have - /// been created with [`Self::in_window`]; headless routers reject this method. - /// The embedding shell owns redrawing and keeping the shared driver alive. - #[cfg(feature = "gpui")] - pub fn attach_window( - &self, - id: WindowId, - window: &gpui::Window, - cx: &gpui::App, - ) -> Result<(), OperationError> { - if !self.0.state.borrow().windows.contains_key(&id) { - return Err(OperationError::WindowUnavailable); + #[doc(hidden)] + pub fn set_host_attached(&self, attached: bool) { + self.0.has_window.set(attached); + } + + #[cfg(not(target_family = "wasm"))] + #[doc(hidden)] + pub fn request_host_close(&self, id: WindowId) -> bool { + if self.0.quit.borrow().phase == crate::quit::QuitPhase::Ready { + return true; } - let contexts = self.0.view_contexts.borrow(); - let contexts = contexts.as_ref().ok_or(OperationError::InvalidOptions)?; + if self.0.window_host.borrow().is_none() { + drop(self.quit(crate::quit::QuitOptions::default())); - contexts.borrow_mut().insert(id, window.to_async(cx)); - self.observe_host_in(id, window, cx); + return false; + } - Ok(()) + let opening = { + let state = self.0.state.borrow(); + + let Some(window) = state.windows.get(&id) else { + return true; + }; + + window.opening + }; + + if let Some(operation) = opening { + let _ = self.cancel(operation); + } else { + drop(self.close_window(id)); + } + + false } - /// Installs native/embedding window creation before the driver starts. - /// The route mount adapter must mount each destination in its navigator's window. - /// Browser hosts always reject this capability. + #[cfg(target_family = "wasm")] + #[doc(hidden)] + pub fn warn_before_unload(&self) -> bool { + if self.0.page_reload.replace(false) { + return false; + } + + let snapshot = self.snapshot(); + + snapshot.quit.phase != crate::quit::QuitPhase::Ready + && (snapshot.quit.phase.is_pending() + || snapshot + .tabs + .iter() + .flat_map(|tab| &tab.entries) + .any(|entry| entry.dirty) + || !snapshot.quit.pending_tasks.is_empty() + || !snapshot.quit.pending_operations.is_empty() + || !self.0.quit_guards.borrow().is_empty()) + } + + /// Installs guarded host close and, when supported, additional window creation. + /// Install before the driver starts. The route mount adapter must mount each + /// destination in its navigator's window. + /// + /// # Errors + /// Rejects repeat installation, a running driver, or multi-window support in a browser. pub fn window_host(&self, host: impl WindowHost) -> Result<(), OperationError> { - if cfg!(target_family = "wasm") + if (cfg!(target_family = "wasm") && host.supports_new_windows()) || self.0.driving.get() || self.0.window_host.borrow().is_some() { @@ -56,19 +113,19 @@ impl Router { Ok(()) } - /// Advertised targets; Web and hosts without a window adapter omit NewWindow. + /// Advertised targets; single-window and browser hosts omit NewWindow. pub fn supported_targets(&self) -> Vec { let mut targets = vec![OpenTarget::CurrentTab, OpenTarget::NewTab]; - if self.0.window_host.borrow().is_some() { + if self.0.supports_new_windows() { targets.push(OpenTarget::NewWindow); } targets } - #[cfg(feature = "gpui")] - pub(crate) fn presented_snapshot(&self, window: WindowId) -> RouterSnapshot { + #[doc(hidden)] + pub fn presented_snapshot(&self, window: WindowId) -> RouterSnapshot { self.snapshot_in_window(window).unwrap_or_else(|_| { let mut snapshot = self.snapshot(); @@ -83,13 +140,20 @@ impl Router { /// Copies one host's tabs, selection and decisions without changing global state. pub fn snapshot_in_window(&self, window: WindowId) -> Result { - if !self.0.state.borrow().windows.contains_key(&window) { - return Err(OperationError::WindowUnavailable); - } + self.check_window(window)?; Ok(self.snapshot_filtered(Some(window))) } + #[doc(hidden)] + pub fn check_window(&self, window: WindowId) -> Result<(), OperationError> { + if self.0.state.borrow().windows.contains_key(&window) { + Ok(()) + } else { + Err(OperationError::WindowUnavailable) + } + } + /// Guards every retained entry before disposing this window atomically. /// Other windows and application-owned tasks survive. Repeated pending closes /// join the same operation. Cancellation/denial leaves the complete window intact. @@ -235,6 +299,7 @@ impl Router { host.visibility = visibility; drop(state); self.0.tasks.window_visibility(window, visibility); + self.0.sync_presentation(window); self.0.notify(); Ok(()) @@ -245,8 +310,13 @@ impl Navigator { /// Temporarily upgrades this weak handle for custom native GPUI window hosts. /// The returned router keeps state alive; do not store it in the installed /// [`WindowHost`], which would retain the runtime through its own adapter. - #[cfg(all(feature = "gpui", not(target_family = "wasm")))] + #[cfg(not(target_family = "wasm"))] pub fn router(&self) -> Option> { + self.upgrade_router() + } + + #[doc(hidden)] + pub fn upgrade_router(&self) -> Option> { self.core.upgrade().map(Router) } @@ -338,34 +408,45 @@ async fn close( state.tabs = retained; - for tab in &removed { + for entry in removed.iter().flat_map(|tab| &tab.entries) { + state.invalidate(Some(entry.id)); + } + + drop(state); + + for tab in removed { tab.scope.close(); - for entry in &tab.entries { + for entry in tab.entries { entry.dispose(); - state.invalidate(Some(entry.id)); } } - drop(state); - drop(removed); - #[cfg(feature = "gpui")] - core.host.borrow_mut().remove(&window); core.tasks.forget_window(window); - let host = core.window_host.borrow().clone(); + core.remove_window_host(window); + core.notify(); + + return Ok(()); + } +} + +impl Core { + pub(super) fn supports_new_windows(&self) -> bool { + let host = self.window_host.borrow().clone(); + + host.is_some_and(|host| host.supports_new_windows()) + } + + pub(super) fn remove_window_host(&self, id: WindowId) { + let host = self.window_host.borrow().clone(); if let Some(host) = host { - host.close(window); + host.close(id); } - #[cfg(feature = "gpui")] - if let Some(contexts) = core.view_contexts.borrow().as_ref() { - contexts.borrow_mut().remove(&window); + if let Some(binding) = self.host_binding.get() { + binding.detach_window(id); } - - core.notify(); - - return Ok(()); } } @@ -418,19 +499,7 @@ impl Drop for ProvisionalWindow { if !self.committed { self.core.state.borrow_mut().windows.remove(&self.id); self.core.tasks.forget_window(self.id); - #[cfg(feature = "gpui")] - self.core.host.borrow_mut().remove(&self.id); - let host = self.core.window_host.borrow().clone(); - - if let Some(host) = host { - host.close(self.id); - } - - #[cfg(feature = "gpui")] - if let Some(contexts) = self.core.view_contexts.borrow().as_ref() { - contexts.borrow_mut().remove(&self.id); - } - + self.core.remove_window_host(self.id); self.core.notify(); } } diff --git a/crates/rake/src/router/types.rs b/crates/rake-core/src/router/types.rs similarity index 93% rename from crates/rake/src/router/types.rs rename to crates/rake-core/src/router/types.rs index b113d692..a6c4b556 100644 --- a/crates/rake/src/router/types.rs +++ b/crates/rake-core/src/router/types.rs @@ -9,34 +9,29 @@ use super::{ /// Opaque, owned data prepared before a route is mounted. /// -/// This is an internal bridge between the statically dispatched route loader -/// and the runtime's erased mount callback. The value is consumed exactly once; -/// dropping it drops the loaded data as well. Ordinary applications should use -/// the `loaded(...)` arm of `rake::routes!` rather than this type directly. -#[doc(hidden)] +/// The value is consumed by the mount callback or dropped on cancellation. pub struct PreparedPage(Option>); impl PreparedPage { - /// Creates an empty preparation for synchronous route views. - #[doc(hidden)] + /// Creates an empty preparation for routes with no loading step. pub fn empty() -> Self { Self(None) } /// Wraps owned route data for a custom preparation implementation. - #[doc(hidden)] pub fn from_value(value: T) -> Self { Self(Some(Box::new(value))) } /// Returns whether this preparation carries no route data. - #[doc(hidden)] pub fn is_empty(&self) -> bool { self.0.is_none() } /// Consumes the preparation and recovers its concrete route data. - #[doc(hidden)] + /// + /// # Errors + /// Returns a mount error if the preparation is empty or has another type. pub fn downcast(self) -> Result { self.0 .ok_or_else(|| MountError("route preparation is empty".into()))? @@ -220,8 +215,14 @@ pub struct DecisionRequest { /// mount adapter; its future must clean up on failure/cancellation. After success, /// Rake calls `close` if mounting is cancelled or fails. Hosts must not retain a /// strong router in this adapter, which would form an ownership cycle. Browser -/// runtimes reject this capability and never turn NewWindow into NewTab. +/// runtimes only accept single-window hosts and never turn NewWindow into NewTab. pub trait WindowHost: 'static { + /// Whether the host can open additional windows. Keep this fixed after installation. + /// Returning false still enables guarded close for the initial window. + fn supports_new_windows(&self) -> bool { + true + } + /// Creates an empty host on the UI loop, honoring the requested activation. fn open( &self, diff --git a/crates/rake-core/src/router/web.rs b/crates/rake-core/src/router/web.rs new file mode 100644 index 00000000..85cd2e73 --- /dev/null +++ b/crates/rake-core/src/router/web.rs @@ -0,0 +1,152 @@ +//! Browser history is a workspace visit journal, distinct from each tab's history. + +use serde::{Deserialize, Serialize}; + +use super::{EntryId, Route, RouteAddress, RouteDecodeError, RuntimeId, TabId}; + +/// URL representation used by the browser host. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum WebRouting { + /// Absolute paths; the deployment server must serve the app shell for deep links. + #[default] + Path, + /// Application URI in the fragment, for hosts without document-route rewrites. + Hash, +} + +/// Browser routing configuration. Native hosts retain it without changing OS behavior. +#[derive(Clone, Debug)] +pub struct WebConfig { + routing: WebRouting, + base_path: String, +} + +impl Default for WebConfig { + fn default() -> Self { + Self { + routing: WebRouting::Path, + base_path: "/".into(), + } + } +} + +impl WebConfig { + /// Uses path routing. + pub fn new() -> Self { + Self::default() + } + + /// Selects path or hash routing. + pub fn routing(mut self, routing: WebRouting) -> Self { + self.routing = routing; + + self + } + + /// Sets the deployment prefix. It must start/end with `/` and contain only + /// ASCII letters, digits, `-`, `_`, `.`, `~` and nonempty path segments. + /// Dot segments, encoded separators and URL query/fragment syntax are rejected. + pub fn base_path(mut self, path: impl Into) -> Result { + let path = path.into(); + + if !path.starts_with('/') + || !path.ends_with('/') + || !path + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"/-._~".contains(&byte)) + || (path != "/" + && path[1..path.len() - 1] + .split('/') + .any(|part| matches!(part, "" | "." | ".."))) + { + return Err(RouteDecodeError::InvalidUri( + "invalid Web deployment base path".into(), + )); + } + + self.base_path = path; + + Ok(self) + } + + /// Produces a browser path or fragment URL, including this deployment's prefix. + pub fn uri_for(&self, destination: &R) -> Result { + Ok(self.write_uri(&destination.to_uri()?)) + } + + /// Decodes an absolute HTTP(S) URL within this deployment. Path and hash modes + /// use the same typed route codec; paths outside the prefix are rejected. + pub fn destination_from_url(&self, url: &str) -> Result { + let url = url::Url::parse(url) + .map_err(|error| RouteDecodeError::InvalidUri(error.to_string()))?; + + if !matches!(url.scheme(), "http" | "https") { + return Err(RouteDecodeError::InvalidUri( + "Web routes require HTTP(S)".into(), + )); + } + + let path = if url.path() == self.base_path.trim_end_matches('/') { + "" + } else { + url.path().strip_prefix(&self.base_path).ok_or_else(|| { + RouteDecodeError::InvalidUri("URL is outside the Web deployment".into()) + })? + }; + + let uri = match self.routing { + WebRouting::Path => format!( + "/{path}{}", + url.query() + .map(|query| format!("?{query}")) + .unwrap_or_default() + ), + WebRouting::Hash => url + .fragment() + .filter(|fragment| !fragment.is_empty()) + .unwrap_or("/") + .into(), + }; + + R::from_uri(&uri) + } + + #[doc(hidden)] + pub fn routing_mode(&self) -> WebRouting { + self.routing + } + + #[doc(hidden)] + pub fn write_uri(&self, uri: &str) -> String { + match self.routing { + WebRouting::Path => format!("{}{}", self.base_path, uri.trim_start_matches('/')), + WebRouting::Hash => format!("{}#{uri}", self.base_path), + } + } +} + +/// A reconstructible browser visit with optional live-instance hints. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct BrowserCheckpoint { + /// Current schema version, initially 1. + pub version: u32, + /// Runtime in which these hints were created. + pub runtime_id: RuntimeId, + /// Internal application tab hint. + pub tab_id: TabId, + /// Retained screen hint. + pub entry_id: EntryId, + /// Complete canonical destination, authoritative when hints are stale. + pub destination: RouteAddress, +} + +/// A committed workspace's intended URL update. Restore never emits Push. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum HistoryChange { + /// Add a visible workspace visit. + Push(BrowserCheckpoint, String), + /// Initialize, reconcile or replace the current visit without adding one. + Replace(BrowserCheckpoint, String), + /// The last tab closed; clear Rake state and show the root URL. + Clear, +} diff --git a/crates/rake/src/runtime.rs b/crates/rake-core/src/runtime.rs similarity index 72% rename from crates/rake/src/runtime.rs rename to crates/rake-core/src/runtime.rs index 42c07973..9feba7be 100644 --- a/crates/rake/src/runtime.rs +++ b/crates/rake-core/src/runtime.rs @@ -4,6 +4,7 @@ //! [`RuntimeContext`] deliberately keeps only a weak navigator, so a view or //! task may retain its capabilities without retaining the runtime itself. +#[cfg(feature = "updates")] use std::rc::Rc; use futures::future::{Either, select}; @@ -28,21 +29,23 @@ pub struct Runtime { impl Runtime { /// Creates a headless runtime with the supplied application services. pub fn new(config: RouterConfig, services: Services) -> Self { - let router = Router::::with_mount( + let router = Router::with_route_mount_and_collector( config, + services.registry(), services.diagnostics(), - Rc::new(|_, _, _| { - Box::pin(async { Ok(Rc::new(()) as crate::router::runtime::Resource) }) - }), + crate::router::mount::Headless, ); - router.client().set_services(services.registry()); - Self { router, services } } } impl Runtime { + #[doc(hidden)] + pub fn router(&self) -> &Router { + &self.router + } + /// Returns a weak capability context for this runtime. pub fn context(&self) -> RuntimeContext { RuntimeContext::from_router(&self.router, self.services.clone()) @@ -155,79 +158,17 @@ pub struct RuntimeContext { } impl RuntimeContext { - /// Returns weak access to the native application tray host. - /// # Errors - /// Reports an unavailable GUI host or stopped runtime. - #[cfg(feature = "tray")] - pub fn trays(&self) -> Result { - self.client().map_err(|_| crate::tray::Error::Stopped)?; - #[cfg(target_family = "wasm")] - { - Err(crate::tray::Error::Unsupported( - crate::tray::Feature::MultipleItems, - )) - } - - #[cfg(not(target_family = "wasm"))] - { - self.services - .get::() - .map(|c| c.as_ref().clone()) - .map_err(|_| crate::tray::Error::HostUnavailable) - } - } - - /// Binds an initiated user-action future to this view, with automatic redraw, - /// cancellation and finite-work quit tracking. Start gesture-sensitive browser - /// requests before calling this method. For reusable preparation, use `load`. - #[cfg(feature = "gpui")] - pub fn action( - &self, - cx: &mut gpui::Context, - future: Fut, - ) -> crate::loading::AsyncAction - where - E: std::error::Error + 'static, - Fut: std::future::Future> + 'static, - { - crate::loading::AsyncAction::new(Ok(self.tasks()), self.services(), future, cx) - } - - /// Observes the shared update controller and redraws this view automatically. - /// Dropping the handle/view stops observation, without stopping provider work. - /// Missing policy and action failures are represented in the returned handle. - #[cfg(all(feature = "gpui", feature = "updates"))] - pub fn bind_updates(&self, cx: &mut gpui::Context) -> crate::UpdateHandle { - crate::updates_binding::bind_updates(self.clone(), cx) - } - - #[cfg(all(feature = "gpui", feature = "updates"))] - pub(crate) async fn stopped(&self) { + #[doc(hidden)] + pub async fn stopped(&self) { self.navigator.stopped().await; } - /// Starts a view-owned asynchronous value and automatically redraws its view. - /// Work survives hidden views and is cancelled when the loader is dropped. - /// Admission and source failures are exposed by the returned handle. - #[cfg(feature = "gpui")] - pub fn load( - &self, - cx: &mut gpui::Context, - factory: F, - ) -> crate::loading::Loader - where - E: std::error::Error + 'static, - F: Fn(crate::loading::LoadContext) -> Fut + 'static, - Fut: std::future::Future> + 'static, - { - crate::loading::Loader::new(Ok(self.tasks()), self.services(), factory, cx) - } - pub(crate) fn from_router(router: &Router, services: Services) -> Self { Self::from_navigator(router.navigator(), services) } - pub(crate) fn from_navigator(navigator: Navigator, services: Services) -> Self { + #[doc(hidden)] + pub fn from_navigator(navigator: Navigator, services: Services) -> Self { Self { navigator, services, @@ -260,17 +201,6 @@ impl RuntimeContext { Ok(self.router()?.client()) } - /// Reveals the application's registered repeatable standalone main window. - /// # Errors - /// Rejects a stopped runtime, missing factory, browser host or failed mount. - #[cfg(feature = "gpui")] - pub fn show_main_window(&self, cx: &mut gpui::App) -> Result<(), crate::AppError> { - self.client() - .map_err(|error| crate::AppError::Window(error.to_string()))?; - - crate::show_main_window(cx) - } - /// Requests guarded application quit. Dropped/closed contexts return a /// completed operation carrying `RuntimeShutdown`. pub fn quit(&self, options: QuitOptions) -> Operation { diff --git a/crates/rake/src/services.rs b/crates/rake-core/src/services.rs similarity index 98% rename from crates/rake/src/services.rs rename to crates/rake-core/src/services.rs index 20dd4eb6..39e9740a 100644 --- a/crates/rake/src/services.rs +++ b/crates/rake-core/src/services.rs @@ -5,6 +5,7 @@ //! No service needs `Send` or `Sync`; applications own interior mutability. //! //! ``` +//! # use rake_core as rake; //! use rake::services::ServiceRegistry; //! use std::cell::Cell; //! struct Counter(Cell); @@ -169,7 +170,8 @@ impl Services { ) } - pub(crate) fn with_platform( + #[doc(hidden)] + pub fn with_platform( http: HttpClient, collector: Collector, registry: ServiceRegistry, diff --git a/crates/rake/src/storage/cache.rs b/crates/rake-core/src/storage/cache.rs similarity index 100% rename from crates/rake/src/storage/cache.rs rename to crates/rake-core/src/storage/cache.rs diff --git a/crates/rake/src/storage/devtools.rs b/crates/rake-core/src/storage/devtools.rs similarity index 100% rename from crates/rake/src/storage/devtools.rs rename to crates/rake-core/src/storage/devtools.rs diff --git a/crates/rake/src/storage/file.rs b/crates/rake-core/src/storage/file.rs similarity index 100% rename from crates/rake/src/storage/file.rs rename to crates/rake-core/src/storage/file.rs diff --git a/crates/rake/src/storage/memory.rs b/crates/rake-core/src/storage/memory.rs similarity index 100% rename from crates/rake/src/storage/memory.rs rename to crates/rake-core/src/storage/memory.rs diff --git a/crates/rake/src/storage/mod.rs b/crates/rake-core/src/storage/mod.rs similarity index 99% rename from crates/rake/src/storage/mod.rs rename to crates/rake-core/src/storage/mod.rs index 67610137..acbacb79 100644 --- a/crates/rake/src/storage/mod.rs +++ b/crates/rake-core/src/storage/mod.rs @@ -6,6 +6,7 @@ //! Opt in to versioned envelopes and migration-on-read with [`Store::with_schema`]. //! //! ``` +//! # use rake_core as rake; //! use rake::storage::{CacheConfig, MemoryBackend, Store}; //! use serde::{Deserialize, Serialize}; //! #[derive(Serialize, Deserialize)] diff --git a/crates/rake/src/storage/schema.rs b/crates/rake-core/src/storage/schema.rs similarity index 98% rename from crates/rake/src/storage/schema.rs rename to crates/rake-core/src/storage/schema.rs index 884e2375..66ab2ab2 100644 --- a/crates/rake/src/storage/schema.rs +++ b/crates/rake-core/src/storage/schema.rs @@ -14,6 +14,7 @@ type Step = Box Result>; /// and free of external side effects: failed reads can run them again. /// /// ``` +/// # use rake_core as rake; /// use rake::storage::{MemoryBackend, Schema, Store}; /// # fn main() -> Result<(), rake::storage::StorageError> { /// let schema = Schema::new(1).with_migration(0, |value| { @@ -63,6 +64,7 @@ impl Schema { /// /// # Examples /// ``` + /// # use rake_core as rake; /// use rake::storage::{Schema, StorageError}; /// # fn main() -> Result<(), StorageError> { /// let schema = Schema::new(2).with_migration(1, |mut value| { @@ -123,6 +125,7 @@ impl Schema { /// /// # Examples /// ``` + /// # use rake_core as rake; /// use rake::storage::Schema; /// # fn main() -> Result<(), rake::storage::StorageError> { /// let schema = Schema::new(1).with_migration(0, |value| { diff --git a/crates/rake/src/tasks/mod.rs b/crates/rake-core/src/tasks/mod.rs similarity index 81% rename from crates/rake/src/tasks/mod.rs rename to crates/rake-core/src/tasks/mod.rs index 4cec2c6e..df5f161e 100644 --- a/crates/rake/src/tasks/mod.rs +++ b/crates/rake-core/src/tasks/mod.rs @@ -5,6 +5,7 @@ //! and drops the future when the driver next runs; it does not undo external effects. //! //! ``` +//! # use rake_core as rake; //! use rake::prelude::*; //! use rake::tasks::TaskState; //! let router = Router::::new(RouterConfig::default()); @@ -13,8 +14,6 @@ //! // The host drives router.run(); dropping the observation handle does not cancel. //! ``` -#[cfg(feature = "gpui")] -pub(crate) mod host; mod runtime; pub use runtime::{ActivityRun, AppHandle, TaskHandle, TaskScope}; @@ -37,19 +36,7 @@ pub enum VisibilitySupport { /// surface can still report [`HostVisibility::Unknown`]. Linux/Wayland do not infer /// visibility from focus; embedding hosts can use `Router::set_window_visibility`. pub fn visibility_support() -> VisibilitySupport { - if !cfg!(feature = "gpui") { - return VisibilitySupport::Unknown; - } - - if cfg!(target_os = "macos") { - VisibilitySupport::NativeOcclusion - } else if cfg!(target_os = "windows") { - VisibilitySupport::NativeWindowState - } else if cfg!(target_family = "wasm") { - VisibilitySupport::BrowserDocument - } else { - VisibilitySupport::Unknown - } + VisibilitySupport::Unknown } /// Portable host timer. Dropping its future cancels observation of the timer. diff --git a/crates/rake/src/tasks/runtime.rs b/crates/rake-core/src/tasks/runtime.rs similarity index 99% rename from crates/rake/src/tasks/runtime.rs rename to crates/rake-core/src/tasks/runtime.rs index 4a9c4fbf..54ff6d2d 100644 --- a/crates/rake/src/tasks/runtime.rs +++ b/crates/rake-core/src/tasks/runtime.rs @@ -680,8 +680,8 @@ pub struct ActivityRun { } impl ActivityRun { - #[cfg(feature = "gpui")] - pub(crate) fn check(&self) -> Result<(), TaskError> { + #[doc(hidden)] + pub fn check(&self) -> Result<(), TaskError> { self.validate().map(|_| ()) } diff --git a/crates/rake/src/web/browser.js b/crates/rake-core/src/web/browser.js similarity index 100% rename from crates/rake/src/web/browser.js rename to crates/rake-core/src/web/browser.js diff --git a/crates/rake/src/web/browser.rs b/crates/rake-core/src/web/browser.rs similarity index 100% rename from crates/rake/src/web/browser.rs rename to crates/rake-core/src/web/browser.rs diff --git a/crates/rake/src/web/mod.rs b/crates/rake-core/src/web/mod.rs similarity index 100% rename from crates/rake/src/web/mod.rs rename to crates/rake-core/src/web/mod.rs diff --git a/crates/rake/src/window_state.rs b/crates/rake-core/src/window_state.rs similarity index 80% rename from crates/rake/src/window_state.rs rename to crates/rake-core/src/window_state.rs index 10415f2c..3185dbc7 100644 --- a/crates/rake/src/window_state.rs +++ b/crates/rake-core/src/window_state.rs @@ -10,16 +10,15 @@ use std::{cell::RefCell, collections::BTreeMap}; use crate::{platform::Preferences, router::WindowId}; #[cfg(not(target_family = "wasm"))] -mod placement; - -#[cfg(all(feature = "gpui", not(target_family = "wasm")))] -pub(crate) mod native; +#[doc(hidden)] +pub mod placement; #[cfg(not(target_family = "wasm"))] use placement::SavedWindow; #[cfg(not(target_family = "wasm"))] -const PREFERENCE_KEY: &str = "rake-window-state-v1"; +#[doc(hidden)] +pub const PREFERENCE_KEY: &str = "rake-window-state-v1"; /// Shared placement policy and reset handle for an application's native windows. /// @@ -28,6 +27,7 @@ const PREFERENCE_KEY: &str = "rake-window-state-v1"; /// records, writes and resets; use one policy per preference namespace. /// /// ```no_run +/// # use rake_core as rake; /// # fn main() -> Result<(), Box> { /// let preferences = rake::platform::Platform::default().preferences("example.app")?; /// let state = rake::window_state::WindowState::new(preferences); @@ -40,6 +40,7 @@ const PREFERENCE_KEY: &str = "rake-window-state-v1"; pub struct WindowState { #[cfg(not(target_family = "wasm"))] inner: Rc, + #[cfg_attr(target_family = "wasm", allow(dead_code))] keys: Rc Option>, } @@ -112,7 +113,7 @@ impl WindowState { #[cfg(not(target_family = "wasm"))] { - let write = self.inner.writes.clone().lock_owned().await; + let write = self.lock_writes().await; self.load_locked().await?; self.inner.records.borrow_mut().remove(key); @@ -121,6 +122,38 @@ impl WindowState { } } + #[cfg(not(target_family = "wasm"))] + #[doc(hidden)] + pub async fn writes_idle(&self) { + let _write = self.inner.writes.lock().await; + } + + #[cfg(not(target_family = "wasm"))] + #[doc(hidden)] + pub fn key(&self, id: WindowId) -> Option { + (self.keys)(id) + } + + #[cfg(not(target_family = "wasm"))] + #[doc(hidden)] + pub fn record(&self, key: &str) -> Option { + self.inner.records.borrow().get(key).cloned() + } + + #[cfg(not(target_family = "wasm"))] + #[doc(hidden)] + pub fn update_record(&self, key: &str, record: SavedWindow) -> bool { + let mut records = self.inner.records.borrow_mut(); + + if records.get(key) == Some(&record) { + return false; + } + + records.insert(key.to_owned(), record); + + true + } + #[cfg(not(target_family = "wasm"))] async fn load_locked(&self) -> Result<(), crate::platform::Error> { if !self.inner.loaded.get() { @@ -134,6 +167,12 @@ impl WindowState { Ok(()) } + #[cfg(not(target_family = "wasm"))] + #[doc(hidden)] + pub async fn lock_writes(&self) -> futures::lock::OwnedMutexGuard<()> { + self.inner.writes.clone().lock_owned().await + } + #[cfg(not(target_family = "wasm"))] async fn save_locked( &self, @@ -153,8 +192,9 @@ impl WindowState { .await } - #[cfg(all(feature = "gpui", not(target_family = "wasm")))] - pub(crate) fn load(&self) { + #[cfg(not(target_family = "wasm"))] + #[doc(hidden)] + pub fn load(&self) { // Startup runs before GPUI's event loop; the preferences service performs // filesystem work on its blocking pool, never in a window callback. if let Err(error) = futures::executor::block_on(async { @@ -169,9 +209,10 @@ impl WindowState { } } - #[cfg(all(feature = "gpui", not(target_family = "wasm")))] - async fn save(&self) { - let write = self.inner.writes.clone().lock_owned().await; + #[cfg(not(target_family = "wasm"))] + #[doc(hidden)] + pub async fn save(&self) { + let write = self.lock_writes().await; if let Err(error) = self.save_locked(write).await { crate::warn!( diff --git a/crates/rake/src/window_state/placement.rs b/crates/rake-core/src/window_state/placement.rs similarity index 89% rename from crates/rake/src/window_state/placement.rs rename to crates/rake-core/src/window_state/placement.rs index 8f70e216..4b4f6e11 100644 --- a/crates/rake/src/window_state/placement.rs +++ b/crates/rake-core/src/window_state/placement.rs @@ -1,3 +1,5 @@ +#![allow(missing_docs)] + //! Portable validation, versioned storage, and display placement in logical pixels. use std::collections::BTreeMap; @@ -5,7 +7,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub(super) struct Rect { +pub struct Rect { pub x: f32, pub y: f32, pub width: f32, @@ -13,7 +15,7 @@ pub(super) struct Rect { } impl Rect { - pub(super) fn valid(self) -> bool { + pub fn valid(self) -> bool { [self.x, self.y, self.width, self.height] .iter() .all(|value| value.is_finite() && value.abs() <= 1_000_000.) @@ -45,14 +47,14 @@ impl Rect { #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] -pub(super) enum Mode { +pub enum Mode { Windowed, Maximized, Fullscreen, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub(super) struct SavedWindow { +pub struct SavedWindow { pub bounds: Rect, pub display: Option, pub mode: Mode, @@ -70,20 +72,16 @@ impl SavedWindow { // Native GPUI consumes display snapshots; headless builds use them only in tests. #[derive(Debug)] -#[cfg_attr( - not(all(feature = "gpui", not(target_family = "wasm"))), - allow(dead_code) -)] -pub(super) struct Display { +pub struct Display { pub uuid: Option, pub visible: Rect, } -pub(super) fn valid_key(key: &str) -> bool { +pub fn valid_key(key: &str) -> bool { !key.is_empty() && key.len() <= 128 } -pub(super) fn decode(value: &str) -> BTreeMap { +pub fn decode(value: &str) -> BTreeMap { #[derive(Deserialize)] struct Document { version: u32, @@ -109,7 +107,7 @@ pub(super) fn decode(value: &str) -> BTreeMap { .collect() } -pub(super) fn encode(windows: &BTreeMap) -> String { +pub fn encode(windows: &BTreeMap) -> String { serde_json::json!({"version": 1, "windows": windows}).to_string() } @@ -117,11 +115,7 @@ pub(super) fn encode(windows: &BTreeMap) -> String { /// its defaults if no valid display exists. A missing/off-screen display uses /// the app's default display and placement, clamped to that display's work area. // The pure algorithm is also tested in builds without the native GPUI adapter. -#[cfg_attr( - not(all(feature = "gpui", not(target_family = "wasm"))), - allow(dead_code) -)] -pub(super) fn restore( +pub fn restore( saved: &SavedWindow, displays: &[Display], default_display: usize, diff --git a/crates/rake/src/window_state/placement/tests.rs b/crates/rake-core/src/window_state/placement/tests.rs similarity index 100% rename from crates/rake/src/window_state/placement/tests.rs rename to crates/rake-core/src/window_state/placement/tests.rs diff --git a/crates/rake/tests/crash_startup.rs b/crates/rake-core/tests/crash_startup.rs similarity index 96% rename from crates/rake/tests/crash_startup.rs rename to crates/rake-core/tests/crash_startup.rs index e572316b..68d1843d 100644 --- a/crates/rake/tests/crash_startup.rs +++ b/crates/rake-core/tests/crash_startup.rs @@ -11,17 +11,15 @@ use std::process::{Command, Output}; use tracing_subscriber::prelude::*; -use rake::crash::{CrashConfig, CrashSink}; +use rake_core as rake; + +use rake::crash::CrashConfig; +use rake::crash_config; use rake::diagnostics::Collector; -use rake::{crash, crash_config, diagnostics}; use std::io; -// Exercise the exact private startup component without exporting test-only API. -#[path = "../src/crash/startup.rs"] -mod startup; - -use crate::crash::CrashRecord; -use startup::{CrashReports, version_from_policy}; +use rake::crash::CrashRecord; +use rake::crash::startup::{CrashReports, version_from_policy}; const APP_ID: &str = "test.default-crash"; diff --git a/crates/rake-core/tests/route_mount.rs b/crates/rake-core/tests/route_mount.rs new file mode 100644 index 00000000..50d0ac20 --- /dev/null +++ b/crates/rake-core/tests/route_mount.rs @@ -0,0 +1,720 @@ +//! Covers: the public route mount contract through navigation and workspace restore. +//! Real: local router, guards, history and checkpoint APIs. +//! Doubles: retained mounts recording presentation and disposal. +//! Requires: no UI framework. + +use std::cell::RefCell; +use std::rc::{Rc, Weak}; + +use futures::executor::LocalPool; +use futures::future::{LocalBoxFuture, pending}; +use futures::task::LocalSpawnExt as _; +use rake::http::CancellationToken; +use rake::reload::{ReloadMechanism, ReloadPhase, ReloadRequest, ReloadState}; + +use rake::router::{ + Activation, BlockReason, CancelReason, EntryId, GuardReason, GuardResult, MountError, + MountedRoute, OpenTarget, Operation, Outcome, PreparedPage, RouteMount, RouteMountContext, + RoutePresentation, Router, RouterConfig, WindowHost, WindowId, +}; + +use rake::services::ServiceRegistry; +use rake::tasks::HostVisibility; +use rake_core as rake; +use serde::{Deserialize, Serialize}; + +const APP_ID: &str = "test.route-mount"; + +#[derive(Clone, Copy, Debug, Eq, PartialEq, rake::Route)] +enum Destination { + #[route(id = "home", path = "/")] + Home, + #[route(id = "detail", path = "/detail")] + Detail, + #[route(id = "denied", path = "/denied")] + Denied, + #[route(id = "slow", path = "/slow")] + Slow, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +struct Saved(u32); + +impl ReloadState for Saved { + const SCHEMA: &'static str = "test.view"; + const VERSION: u32 = 1; +} + +#[derive(Debug, PartialEq)] +enum Event { + Prepared(Destination), + PrepareDropped, + Mounted(Destination, EntryId, Option), + Opened(WindowId), + Presented(EntryId, RoutePresentation), + Disposed(EntryId), + Closed(WindowId), +} + +type Events = Rc>>; +type Probe = dyn Fn() -> (ReloadPhase, usize); + +struct Adapter { + events: Events, + load_token: Rc>>, + probe: Option>, + skip_restore: Option, +} + +struct PendingPreparation(Events); + +impl Drop for PendingPreparation { + fn drop(&mut self) { + self.0.borrow_mut().push(Event::PrepareDropped); + } +} + +impl RouteMount for Adapter { + fn prepare( + &self, + destination: &Destination, + services: ServiceRegistry, + cancellation: CancellationToken, + ) -> LocalBoxFuture<'static, Result> { + let destination = *destination; + + assert_eq!(*services.get::().expect("route service"), 42); + self.events.borrow_mut().push(Event::Prepared(destination)); + + if destination == Destination::Slow { + *self.load_token.borrow_mut() = Some(cancellation); + let preparation = PendingPreparation(self.events.clone()); + + return Box::pin(async move { + let _preparation = preparation; + + pending().await + }); + } + + Box::pin(async move { Ok(PreparedPage::from_value(destination)) }) + } + + fn mount( + &self, + destination: &Destination, + prepared: PreparedPage, + context: RouteMountContext, + ) -> LocalBoxFuture<'static, Result, MountError>> { + let destination = *destination; + let events = self.events.clone(); + let probe = self.probe.clone(); + let skip_restore = self.skip_restore == Some(destination); + + Box::pin(async move { + assert_eq!(prepared.downcast::()?, destination); + assert_eq!( + context.entry.id().expect("provisional entry"), + context.entry_id + ); + assert_eq!( + context.entry.window_id().expect("provisional window"), + context.window_id + ); + + if let Some(probe) = probe.as_ref().and_then(Weak::upgrade) { + assert_eq!(probe(), (ReloadPhase::Restoring, 0)); + } + + let saved = if skip_restore { + None + } else { + context + .entry + .reload_state::() + .expect("read checkpoint") + }; + + let value = saved.as_ref().map(|saved| saved.0); + + events + .borrow_mut() + .push(Event::Mounted(destination, context.entry_id, value)); + + if destination == Destination::Denied { + // The mount revises the value checked by the initial enter guard. + context + .entry + .set_dirty(true) + .expect("revise provisional entry"); + } + + let initial = if destination == Destination::Detail { + 11 + } else { + 7 + }; + + context + .entry + .on_reload(move || Saved(value.unwrap_or(initial)).checkpoint()) + .expect("register entry checkpoint"); + + Ok(Box::new(View { + events, + context, + probe, + }) as Box) + }) + } +} + +struct View { + events: Events, + context: RouteMountContext, + probe: Option>, +} + +impl MountedRoute for View { + fn presentation_changed(&self, presentation: RoutePresentation) { + if let Some(probe) = self.probe.as_ref().and_then(Weak::upgrade) { + assert_eq!(probe(), (ReloadPhase::Restoring, 2)); + } + + self.events + .borrow_mut() + .push(Event::Presented(self.context.entry_id, presentation)); + } + + fn dispose(&self) { + assert!( + self.context.entry.id().is_err(), + "dispose must invalidate weak handles" + ); + self.events + .borrow_mut() + .push(Event::Disposed(self.context.entry_id)); + } +} + +struct TestWindow(Events); + +impl WindowHost for TestWindow { + fn open(&self, id: WindowId, _: Activation) -> LocalBoxFuture<'static, Result<(), MountError>> { + self.0.borrow_mut().push(Event::Opened(id)); + + Box::pin(async { Ok(()) }) + } + + fn close(&self, id: WindowId) { + self.0.borrow_mut().push(Event::Closed(id)); + } + + fn activate(&self, _: WindowId) {} +} + +fn router(events: Events, token: Rc>>) -> Router { + with_adapter(Adapter { + events, + load_token: token, + probe: None, + skip_restore: None, + }) +} + +fn with_adapter(adapter: Adapter) -> Router { + let services = ServiceRegistry::new() + .with(42u32) + .expect("register route service"); + + Router::with_route_mount(RouterConfig::default(), services, adapter) +} + +fn drive(pool: &LocalPool, router: &Router) { + let router = router.clone(); + + pool.spawner() + .spawn_local(async move { router.run().await.expect("drive router") }) + .expect("spawn driver"); +} + +async fn committed(operation: Operation) -> T { + match operation.wait().await.expect("route operation completed") { + Outcome::Committed(result) => result, + _ => panic!("expected a committed operation"), + } +} + +fn take(events: &Events) -> Vec { + std::mem::take(&mut *events.borrow_mut()) +} + +#[test] +fn transfers_prepared_data_and_preserves_mounts_through_history() { + use Destination::{Detail, Home}; + use Event::{Disposed, Mounted, Prepared, Presented}; + use RoutePresentation::{Presented as Selected, Retained}; + + let events = Events::default(); + let router = router(events.clone(), Default::default()); + + router + .window_host(TestWindow(events.clone())) + .expect("install window host"); + let mut pool = LocalPool::new(); + + drive(&pool, &router); + + pool.run_until(async { + let nav = router.navigator(); + let home = committed(nav.open(Home, OpenTarget::NewTab)).await; + let tab = nav.tab(home.tab_id); + let detail = committed(tab.navigate(Detail)).await; + + router + .set_window_visibility(home.window_id, HostVisibility::Hidden) + .expect("hide window"); + router + .set_window_visibility(home.window_id, HostVisibility::Visible) + .expect("show window"); + + assert_eq!(committed(tab.back()).await.entry_id, home.entry_id); + assert_eq!(committed(tab.forward()).await.entry_id, detail.entry_id); + assert_eq!(committed(tab.back()).await.entry_id, home.entry_id); + + let new = committed(tab.navigate(Detail)).await; + + assert_ne!(new.entry_id, detail.entry_id); + committed(router.close_window(home.window_id)).await; + router.shutdown(); + router.shutdown(); + + let unknown = Selected(HostVisibility::Unknown); + let hidden = Selected(HostVisibility::Hidden); + let visible = Selected(HostVisibility::Visible); + + assert_eq!( + take(&events), + [ + Prepared(Home), + Mounted(Home, home.entry_id, None), + Presented(home.entry_id, unknown), + Prepared(Detail), + Mounted(Detail, detail.entry_id, None), + Presented(home.entry_id, Retained), + Presented(detail.entry_id, unknown), + Presented(detail.entry_id, hidden), + Presented(detail.entry_id, visible), + Presented(detail.entry_id, Retained), + Presented(home.entry_id, visible), + Presented(home.entry_id, Retained), + Presented(detail.entry_id, visible), + Presented(detail.entry_id, Retained), + Presented(home.entry_id, visible), + Prepared(Detail), + Mounted(Detail, new.entry_id, None), + Disposed(detail.entry_id), + Presented(home.entry_id, Retained), + Presented(new.entry_id, visible), + Disposed(home.entry_id), + Presented(new.entry_id, Retained), + Disposed(new.entry_id), + Event::Closed(home.window_id), + ] + ); + }); + pool.run(); + assert!(take(&events).is_empty()); +} + +#[test] +fn replacing_forward_history_disposes_each_truncated_mount_once() { + use Destination::{Detail, Home}; + use Event::{Disposed, Presented}; + use RoutePresentation::Retained; + + let events = Events::default(); + let router = router(events.clone(), Default::default()); + let mut pool = LocalPool::new(); + + drive(&pool, &router); + + let truncated = pool.run_until(async { + let nav = router.navigator(); + let home = committed(nav.open(Home, OpenTarget::NewTab)).await; + let tab = nav.tab(home.tab_id); + let first = committed(tab.navigate(Detail)).await.entry_id; + let second = committed(tab.navigate(Home)).await.entry_id; + + assert_eq!(committed(tab.back()).await.entry_id, first); + assert_eq!(committed(tab.back()).await.entry_id, home.entry_id); + + let replacement = committed(tab.navigate(Detail)).await.entry_id; + + assert_ne!(replacement, first); + assert_ne!(replacement, second); + + for entry in [first, second] { + assert!(router.entry(entry).is_err()); + } + + assert!(matches!( + tab.forward().wait().await, + Ok(Outcome::Blocked(BlockReason::HistoryBoundary)), + )); + router.shutdown(); + + [first, second] + }); + + pool.run(); + let events = take(&events); + + for entry in truncated { + let last_retained = events + .iter() + .rposition(|event| *event == Presented(entry, Retained)) + .expect("truncated mount was hidden"); + + let disposals: Vec<_> = events + .iter() + .enumerate() + .filter_map(|(index, event)| (*event == Disposed(entry)).then_some(index)) + .collect(); + + assert_eq!(disposals.len(), 1, "disposals for {entry:?}"); + assert!( + last_retained < disposals[0], + "hide before disposing {entry:?}" + ); + } +} + +#[test] +fn closing_the_selected_tab_hides_and_disposes_its_mount_once() { + let events = Events::default(); + let router = router(events.clone(), Default::default()); + let mut pool = LocalPool::new(); + + drive(&pool, &router); + + pool.run_until(async { + let nav = router.navigator(); + let home = committed(nav.open(Destination::Home, OpenTarget::NewTab)).await; + + take(&events); + + committed(nav.tab(home.tab_id).close()).await; + assert_eq!( + take(&events), + [ + Event::Presented(home.entry_id, RoutePresentation::Retained), + Event::Disposed(home.entry_id), + ], + ); + assert!(router.entry(home.entry_id).is_err()); + + router.shutdown(); + }); + pool.run(); + assert!(take(&events).is_empty()); +} + +#[test] +fn cancellation_during_prepare_drops_the_future_without_mounting() { + let events = Events::default(); + let token = Rc::default(); + let router = router(events.clone(), Rc::clone(&token)); + let mut pool = LocalPool::new(); + + drive(&pool, &router); + + let open = router + .navigator() + .open(Destination::Slow, OpenTarget::NewTab); + + pool.run_until_stalled(); + + assert_eq!(take(&events), [Event::Prepared(Destination::Slow)]); + assert!(router.cancel(open.id()).expect("cancel prepare")); + assert!(matches!( + pool.run_until(open.wait()), + Ok(Outcome::Cancelled(CancelReason::Requested)) + )); + assert!(token.borrow().as_ref().expect("load token").is_cancelled()); + assert_eq!(take(&events), [Event::PrepareDropped]); + assert!(router.snapshot().tabs.is_empty()); + router.shutdown(); + pool.run(); +} + +#[test] +fn guard_revalidation_rolls_back_a_mount_and_shutdown_disposes_the_committed_entry_once() { + let events = Events::default(); + let router = router(events.clone(), Default::default()); + + router + .window_host(TestWindow(events.clone())) + .expect("install window host"); + router + .entry_guard(|context| async move { + if context.destination == Destination::Denied && context.dirty { + GuardResult::Deny(GuardReason("revision denied".into())) + } else { + GuardResult::Allow + } + }) + .expect("install guard"); + + let mut pool = LocalPool::new(); + + drive(&pool, &router); + + pool.run_until(async { + let nav = router.navigator(); + let home = committed(nav.open(Destination::Home, OpenTarget::NewTab)).await; + + take(&events); + let outcome = nav + .open(Destination::Denied, OpenTarget::NewWindow) + .wait() + .await + .expect("guard outcome"); + + assert!(matches!(outcome, Outcome::Blocked(_))); + + let rollback = take(&events); + + let [ + Event::Prepared(Destination::Denied), + Event::Opened(window), + Event::Mounted(Destination::Denied, denied, None), + Event::Disposed(disposed), + Event::Closed(closed), + ] = rollback.as_slice() + else { + panic!("expected a mounted then rolled-back entry, got {rollback:?}"); + }; + + assert_eq!(denied, disposed); + assert_eq!(window, closed); + assert!(router.entry(*denied).is_err()); + assert!(router.entry(home.entry_id).is_ok()); + assert_eq!(router.snapshot().tabs[0].entries.len(), 1); + + router.shutdown(); + router.shutdown(); + assert_eq!( + take(&events), + [ + Event::Presented(home.entry_id, RoutePresentation::Retained), + Event::Disposed(home.entry_id), + ] + ); + }); + pool.run(); + assert!(take(&events).is_empty()); +} + +#[test] +fn reload_consumes_provisional_checkpoints_and_becomes_ready_after_attachment() { + let mut pool = LocalPool::new(); + let old = router(Events::default(), Default::default()); + + drive(&pool, &old); + + let (home, detail, checkpoint) = pool.run_until(async { + let nav = old.navigator(); + let home = committed(nav.open(Destination::Home, OpenTarget::NewTab)).await; + let detail = committed(nav.tab(home.tab_id).navigate(Destination::Detail)).await; + + old.prepare_reload(ReloadRequest { + id: "new-build".into(), + mechanism: ReloadMechanism::NativeRestart, + }) + .expect("prepare checkpoint"); + + ( + home.entry_id, + detail.entry_id, + old.reload_checkpoint(APP_ID).expect("capture workspace"), + ) + }); + + let events = Events::default(); + let probe = Rc::new(RefCell::new(None::>)); + + let inspect: Rc = Rc::new({ + let probe = probe.clone(); + + move || { + let router = probe.borrow(); + let router = router.as_ref().expect("replacement router"); + + let entry_count = router + .snapshot() + .tabs + .iter() + .map(|tab| tab.entries.len()) + .sum(); + + (router.reload_status().phase, entry_count) + } + }); + + let replacement = with_adapter(Adapter { + events: events.clone(), + load_token: Default::default(), + probe: Some(Rc::downgrade(&inspect)), + skip_restore: None, + }); + + *probe.borrow_mut() = Some(replacement.clone()); + pool.run_until(replacement.restore_workspace(&checkpoint, APP_ID)) + .expect("restore workspace"); + assert_eq!(replacement.reload_status().phase, ReloadPhase::Restored); + assert_eq!( + take(&events), + [ + Event::Prepared(Destination::Home), + Event::Prepared(Destination::Detail), + Event::Mounted(Destination::Home, home, Some(7)), + Event::Mounted(Destination::Detail, detail, Some(11)), + Event::Presented(home, RoutePresentation::Retained), + Event::Presented( + detail, + RoutePresentation::Presented(HostVisibility::Unknown) + ), + ] + ); + drop(inspect); + + let broken = with_adapter(Adapter { + events: events.clone(), + load_token: Default::default(), + probe: None, + skip_restore: Some(Destination::Detail), + }); + + assert!( + pool.run_until(broken.restore_workspace(&checkpoint, APP_ID)) + .is_err() + ); + assert_eq!(broken.reload_status().phase, ReloadPhase::RestoreFailed); + assert!(broken.snapshot().tabs.is_empty()); + let failed = take(&events); + + assert_eq!( + &failed[..4], + [ + Event::Prepared(Destination::Home), + Event::Prepared(Destination::Detail), + Event::Mounted(Destination::Home, home, Some(7)), + Event::Mounted(Destination::Detail, detail, None), + ] + ); + assert_eq!( + &failed[4..], + [Event::Disposed(detail), Event::Disposed(home)] + ); + + old.shutdown(); + replacement.shutdown(); + pool.run(); +} + +struct SingleWindow(Events); + +impl WindowHost for SingleWindow { + fn supports_new_windows(&self) -> bool { + false + } + + fn open(&self, _: WindowId, _: Activation) -> LocalBoxFuture<'static, Result<(), MountError>> { + panic!("a single-window host must never open an additional window") + } + + fn close(&self, id: WindowId) { + self.0.borrow_mut().push(Event::Closed(id)); + } + + fn activate(&self, _: WindowId) {} +} + +#[test] +fn single_window_host_can_guard_close_without_advertising_new_windows() { + use rake::router::{DisposeReason, GuardKind, OperationError}; + use std::cell::Cell; + + let events = Events::default(); + let router = router(events.clone(), Default::default()); + + router + .window_host(SingleWindow(events.clone())) + .expect("install single-window host"); + + let mut pool = LocalPool::new(); + + drive(&pool, &router); + pool.run_until(async { + let nav = router.navigator(); + let home = committed(nav.open(Destination::Home, OpenTarget::NewTab)).await; + let entry = router.entry(home.entry_id).expect("opened entry"); + let allow_close = Rc::new(Cell::new(false)); + + entry + .on_dispose({ + let allow_close = allow_close.clone(); + + move |context| { + let allow_close = allow_close.get(); + + async move { + assert!(matches!( + context.kind, + GuardKind::Dispose(DisposeReason::CloseWindow) + )); + + if allow_close { + GuardResult::Allow + } else { + GuardResult::Deny(GuardReason("Keep the window open".into())) + } + } + } + }) + .expect("install close guard"); + take(&events); + + assert_eq!( + router.supported_targets(), + [OpenTarget::CurrentTab, OpenTarget::NewTab] + ); + assert!(matches!( + nav.open(Destination::Detail, OpenTarget::NewWindow) + .wait() + .await, + Err(OperationError::UnsupportedCapability(OpenTarget::NewWindow)) + )); + assert!(matches!( + router.close_window(home.window_id).wait().await, + Ok(Outcome::Blocked(_)) + )); + assert!(take(&events).is_empty()); + assert!(router.entry(home.entry_id).is_ok()); + + allow_close.set(true); + committed(router.close_window(home.window_id)).await; + router.shutdown(); + assert_eq!( + take(&events), + [ + Event::Presented(home.entry_id, RoutePresentation::Retained), + Event::Disposed(home.entry_id), + Event::Closed(home.window_id), + ], + ); + }); + pool.run(); + assert!(take(&events).is_empty()); +} diff --git a/crates/rake-gpui/Cargo.toml b/crates/rake-gpui/Cargo.toml new file mode 100644 index 00000000..b493e9e7 --- /dev/null +++ b/crates/rake-gpui/Cargo.toml @@ -0,0 +1,125 @@ +[package] +name = "rake-gpui" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish = ["crates-io"] +description = "GPUI integration for the Rake application framework" +readme = "../../README.md" + +[lints] +workspace = true + +[features] +default = ["gpui"] +launch-at-login = ["rake-core/launch-at-login"] +tray = ["gpui", "dep:rake-tray", "global-shortcuts"] +global-shortcuts = ["gpui", "dep:rake-shortcuts"] +gpu-surface = ["gpui-fast", "dep:metal", "dep:foreign-types", "dep:objc2", "dep:objc2-foundation", "dep:objc2-quartz-core", "objc2-app-kit?/objc2-quartz-core", "dep:windows"] +gpui-fast = ["gpui", "dep:gpui_fast_apple", "dep:gpui_fast", "dep:gpui_fast_platform", "rake-ui/gpui-fast", "rake-native?/gpui-fast"] +live = ["gpui", "dep:blaze-live", "dep:pathfinder_simd"] +native-components = ["gpui", "dep:rake-native"] +native-lifecycle = ["dep:rake-updates", "rake-updates/native-lifecycle"] +updates = ["native-lifecycle", "rake-core/updates"] +updates-sparkle = ["updates", "rake-core/updates-sparkle", "rake-updates/sparkle"] +updates-appimage = ["updates", "rake-core/updates-appimage", "rake-updates/appimage"] +updates-velopack = ["updates", "rake-core/updates-velopack", "rake-updates/velopack"] +devtools = ["gpui_pre?/profiler", "gpui_fast?/profiler", "rake-core/devtools", "objc2-app-kit?/objc2-quartz-core", "dep:windows"] +devtools-memory = ["devtools", "rake-core/devtools-memory"] +kit = ["gpui", "rake-ui/kit"] +# Deprecated compatibility alias; UI is provided by gpui (enabled by default). +experimental-view = [] +view-test-support = ["gpui", "gpui_pre/test-support", "gpui_fast?/test-support", "rake-ui/test-support", "gpui_platform/runtime_shaders", "gpui_fast_platform?/runtime_shaders"] +gpui = ["dep:anyhow", "dep:image", "dep:gpui_pre_apple", "dep:windows", "dep:oo7", "dep:zbus", "dep:rake-ui", "rake-macros/view", "dep:gpui_pre", "dep:gpui_platform", "dep:objc2-app-kit", "dep:objc2", "dep:objc2-foundation", "dep:block2", "dep:objc2-user-notifications", "dep:raw-window-handle", "dep:windows-sys", "native-lifecycle"] + +locale = ["gpui", "dep:fluent-bundle", "dep:icu_locale_core", "dep:sys-locale"] + +locale-icu = ["locale", "dep:fixed_decimal", "dep:icu_calendar", "dep:icu_datetime", "dep:icu_decimal", "dep:icu_plurals", "dep:icu_provider", "dep:icu_provider_blob", "dep:writeable"] + +experimental-reactive = ["gpui", "rake-macros/reactive", "dep:slotmap"] + +[dependencies] +slotmap = { version = "1.1", optional = true } +writeable = { version = "0.6", optional = true } +icu_provider_blob = { version = "2.4", optional = true } +icu_provider = { version = "2.4", features = ["sync"], optional = true } +icu_plurals = { version = "2.4", default-features = false, features = ["serde"], optional = true } +icu_decimal = { version = "2.4", default-features = false, features = ["serde"], optional = true } +icu_datetime = { version = "2.4", default-features = false, features = ["serde"], optional = true } +icu_calendar = { version = "2.4", default-features = false, optional = true } +fixed_decimal = { version = "0.7", optional = true } +icu_locale_core = { version = "2.4", optional = true } +fluent-bundle = { version = "0.16", optional = true } +rake-core.workspace = true +rake-shortcuts = { version = "=0.1.0-alpha.7", path = "../rake-shortcuts", optional = true } +image = { version = "0.25.10", default-features = false, features = ["png"], optional = true } +rake-tray = { version = "=0.1.0-alpha.7", path = "../rake-tray", optional = true } +rake-updates = { version = "=0.1.0-alpha.7", path = "../rake-updates", optional = true } +rake-resources = { version = "=0.1.0-alpha.7", path = "../rake-resources" } +rake-ui = { workspace = true, optional = true } +rake-native = { workspace = true, optional = true } +rake-protocol.workspace = true +rake-macros = { version = "=0.1.0-alpha.7", path = "../rake-macros" } +rake-diagnostics.workspace = true +serde.workspace = true +serde_json.workspace = true +schemars = "1.2.3" +tracing.workspace = true +futures.workspace = true +thiserror.workspace = true +url = "2.5" +uuid = { version = "1", features = ["v4", "serde", "js"] } +event-listener = "5.4" +web-time.workspace = true +gpui_pre = { package = "gpui-pre", version = "=0.3.11", default-features = false, optional = true } +gpui_platform = { workspace = true, features = ["font-kit", "wayland", "x11"], optional = true } +gpui_fast = { workspace = true, optional = true } +gpui_fast_platform = { workspace = true, features = ["font-kit", "wayland", "x11"], optional = true } + +[target.'cfg(any(unix, windows))'.dependencies] +rake-client.workspace = true + +[target.'cfg(target_os = "linux")'.dependencies] +oo7 = { version = "0.6", default-features = false, features = ["async-std", "native_crypto"], optional = true } +zbus = { version = "5", default-features = false, features = ["async-io"], optional = true } + +[target.'cfg(not(target_family = "wasm"))'.dependencies] +sys-locale = { version = "0.3", optional = true } +blaze-live = { package = "rake-blaze-live", version = "=0.1.0-alpha.7", path = "../../vendor/blaze-live", optional = true } +anyhow = { version = "1", optional = true } +libc = "0.2" +blocking = "1.7" +tempfile = "3" +raw-window-handle = { version = "0.6", optional = true } + +[target.'cfg(target_family = "wasm")'.dependencies] +wasm-bindgen = "0.2" +wasm-bindgen-futures = "0.4" +js-sys = "0.3" +console_error_panic_hook = "0.1" +web-sys = { version = "0.3", features = ["console", "Window", "History", "Location", "Event", "BeforeUnloadEvent", "EventTarget", "Document", "Element", "HtmlElement", "Node", "Storage", "ClipboardEvent", "DataTransfer"] } + +[target.'cfg(target_os = "macos")'.dependencies] +gpui_fast_apple = { package = "gpui-fast-apple", version = "=0.1.13", optional = true } +gpui_pre_apple = { package = "gpui-pre-apple", version = "=0.3.11", optional = true } +block2 = { version = "0.6", optional = true } +objc2-user-notifications = { version = "0.3.2", default-features = false, features = ["std", "block2", "UNUserNotificationCenter", "UNNotificationSettings"], optional = true } + +metal = { version = "0.33", optional = true } +foreign-types = { version = "0.5", optional = true } +objc2 = { version = "0.6.5", optional = true } +objc2-foundation = { version = "0.3.2", features = ["NSGeometry", "NSBundle", "NSError"], optional = true } +objc2-quartz-core = { version = "0.3.2", features = ["CALayer"], optional = true } +pathfinder_simd = { version = "0.5.6", features = ["pf-no-simd"], optional = true } +objc2-app-kit = { version = "0.3", default-features = false, features = ["NSView", "NSWindow", "NSResponder", "NSWorkspace", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSGraphicsContext", "NSGraphics", "objc2-core-foundation"], optional = true } + +[target.'cfg(target_os = "windows")'.dependencies] +windows = { version = "0.62", features = ["Win32_Graphics_DirectComposition"], optional = true } +windows-sys = { version = "0.61", features = ["Win32_UI_WindowsAndMessaging", "Win32_Graphics_Dwm", "Win32_Storage_FileSystem", "Win32_UI_Shell", "Win32_Graphics_Gdi", "Win32_System_Com"], optional = true } + +[dev-dependencies] +rake-tray = { version = "=0.1.0-alpha.7", path = "../rake-tray", features = ["test-support"] } +futures.workspace = true +tracing-subscriber.workspace = true diff --git a/crates/rake-gpui/LICENSE-APACHE b/crates/rake-gpui/LICENSE-APACHE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/crates/rake-gpui/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/crates/rake-gpui/LICENSE-MIT b/crates/rake-gpui/LICENSE-MIT new file mode 100644 index 00000000..ac298920 --- /dev/null +++ b/crates/rake-gpui/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Yurii Hulyk + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/rake/assets/fonts/IBMPlexSans-Italic.ttf b/crates/rake-gpui/assets/fonts/IBMPlexSans-Italic.ttf similarity index 100% rename from crates/rake/assets/fonts/IBMPlexSans-Italic.ttf rename to crates/rake-gpui/assets/fonts/IBMPlexSans-Italic.ttf diff --git a/crates/rake/assets/fonts/IBMPlexSans-Regular.ttf b/crates/rake-gpui/assets/fonts/IBMPlexSans-Regular.ttf similarity index 100% rename from crates/rake/assets/fonts/IBMPlexSans-Regular.ttf rename to crates/rake-gpui/assets/fonts/IBMPlexSans-Regular.ttf diff --git a/crates/rake/assets/fonts/IBMPlexSans-SemiBold.ttf b/crates/rake-gpui/assets/fonts/IBMPlexSans-SemiBold.ttf similarity index 100% rename from crates/rake/assets/fonts/IBMPlexSans-SemiBold.ttf rename to crates/rake-gpui/assets/fonts/IBMPlexSans-SemiBold.ttf diff --git a/crates/rake/assets/fonts/IBMPlexSans-SemiBoldItalic.ttf b/crates/rake-gpui/assets/fonts/IBMPlexSans-SemiBoldItalic.ttf similarity index 100% rename from crates/rake/assets/fonts/IBMPlexSans-SemiBoldItalic.ttf rename to crates/rake-gpui/assets/fonts/IBMPlexSans-SemiBoldItalic.ttf diff --git a/crates/rake/assets/fonts/LICENSES.txt b/crates/rake-gpui/assets/fonts/LICENSES.txt similarity index 100% rename from crates/rake/assets/fonts/LICENSES.txt rename to crates/rake-gpui/assets/fonts/LICENSES.txt diff --git a/crates/rake/assets/fonts/Lilex-Bold.ttf b/crates/rake-gpui/assets/fonts/Lilex-Bold.ttf similarity index 100% rename from crates/rake/assets/fonts/Lilex-Bold.ttf rename to crates/rake-gpui/assets/fonts/Lilex-Bold.ttf diff --git a/crates/rake/assets/fonts/Lilex-BoldItalic.ttf b/crates/rake-gpui/assets/fonts/Lilex-BoldItalic.ttf similarity index 100% rename from crates/rake/assets/fonts/Lilex-BoldItalic.ttf rename to crates/rake-gpui/assets/fonts/Lilex-BoldItalic.ttf diff --git a/crates/rake/assets/fonts/Lilex-Italic.ttf b/crates/rake-gpui/assets/fonts/Lilex-Italic.ttf similarity index 100% rename from crates/rake/assets/fonts/Lilex-Italic.ttf rename to crates/rake-gpui/assets/fonts/Lilex-Italic.ttf diff --git a/crates/rake/assets/fonts/Lilex-Regular.ttf b/crates/rake-gpui/assets/fonts/Lilex-Regular.ttf similarity index 100% rename from crates/rake/assets/fonts/Lilex-Regular.ttf rename to crates/rake-gpui/assets/fonts/Lilex-Regular.ttf diff --git a/crates/rake/assets/fonts/README.md b/crates/rake-gpui/assets/fonts/README.md similarity index 100% rename from crates/rake/assets/fonts/README.md rename to crates/rake-gpui/assets/fonts/README.md diff --git a/crates/rake/overlays.md b/crates/rake-gpui/overlays.md similarity index 98% rename from crates/rake/overlays.md rename to crates/rake-gpui/overlays.md index bdd06201..6a04c692 100644 --- a/crates/rake/overlays.md +++ b/crates/rake-gpui/overlays.md @@ -13,6 +13,7 @@ syntax, subject to the project's [alpha API policy](https://github.com/1bye/rake Retain `ScrollHandle` in the owning view for a normal scroll area: ```rust +# use rake_gpui as rake; # use rake::gpui::{self, IntoElement, ScrollHandle}; # fn content(scroll: &ScrollHandle) -> impl IntoElement { rake::view! { @@ -30,6 +31,7 @@ row the same height. Keys come from stable model IDs; row-local state belongs in the model or retained entities because offscreen elements unmount. ```rust +# use rake_gpui as rake; # use rake::gpui::{self, prelude::*}; # fn rows(scroll: &gpui::UniformListScrollHandle) -> impl IntoElement { rake::view! { @@ -66,6 +68,7 @@ Create one host in the window's owning entity, outside `render`, then create anchors and overlay handles from it: ```rust +# use rake_gpui as rake; # use rake::gpui::Context; # use rake::overlay::OverlayHostState; # fn create(cx: &Context) { @@ -96,6 +99,7 @@ handlers still need their own availability checks. A render method can compose these components: ```rust +# use rake_gpui as rake; # use rake::gpui::{self, prelude::*}; # use rake::overlay::{Dialog, OverlayAnchor, OverlayHost, OverlayHostState, AnchorState, OverlayState, Popover}; # fn render(overlays: OverlayHostState, anchor: AnchorState, actions: OverlayState, documents: OverlayState, window: &mut gpui::Window, cx: &mut gpui::App) -> impl IntoElement { diff --git a/crates/rake/src/application.rs b/crates/rake-gpui/src/application.rs similarity index 99% rename from crates/rake/src/application.rs rename to crates/rake-gpui/src/application.rs index bf56172f..992bee93 100644 --- a/crates/rake/src/application.rs +++ b/crates/rake-gpui/src/application.rs @@ -7,7 +7,7 @@ use gpui::{AnyView, AppContext, Render, Window, WindowOptions}; use crate::diagnostics::{DiagnosticsConfig, DiagnosticsError}; use crate::http::{HttpClient, HttpConfig}; -use crate::router::runtime::{AdmissionCallback, Guard}; +use crate::router::{AdmissionCallback, Guard}; use crate::services::{ServiceError, ServiceRegistry, Services}; use crate::router::{ @@ -123,7 +123,7 @@ pub struct App { close_policy: ClosePolicy, close_policy_set: bool, route_options: bool, - quit_guards: Vec, + quit_guards: Vec, routes: Option>>, initial: Option, router: RouterConfig, @@ -223,6 +223,7 @@ impl App { /// and admissions. /// /// ```compile_fail + /// # use rake_gpui as rake; /// #[derive(Clone, rake::Route)] /// enum Destination { #[route(id = "home", path = "/")] Home } /// let pages = || rake::router::__routes(|_: &Destination, _, _, _| { @@ -430,6 +431,7 @@ impl App { /// use [`crate::theme::install`] and are not reset by navigation. /// /// ```no_run + /// # use rake_gpui as rake; /// struct Colors { accent: u32 } /// let app = rake::App::new("example.theme").theme(Colors { accent: 0x365849 }); /// ``` diff --git a/crates/rake/src/application/factory.rs b/crates/rake-gpui/src/application/factory.rs similarity index 100% rename from crates/rake/src/application/factory.rs rename to crates/rake-gpui/src/application/factory.rs diff --git a/crates/rake/src/application/http_tests.rs b/crates/rake-gpui/src/application/http_tests.rs similarity index 100% rename from crates/rake/src/application/http_tests.rs rename to crates/rake-gpui/src/application/http_tests.rs diff --git a/crates/rake/src/application/managed.rs b/crates/rake-gpui/src/application/managed.rs similarity index 98% rename from crates/rake/src/application/managed.rs rename to crates/rake-gpui/src/application/managed.rs index 14dac3a7..1bacd57f 100644 --- a/crates/rake/src/application/managed.rs +++ b/crates/rake-gpui/src/application/managed.rs @@ -35,7 +35,7 @@ pub(super) struct ManagedConfig { pub(super) commands: Commands, pub(super) application_id: String, pub(super) close_policy: ClosePolicy, - pub(super) quit_guards: Vec, + pub(super) quit_guards: Vec, } pub(super) fn mount( @@ -156,7 +156,7 @@ fn prepare_background(services: &Services, config: &ManagedConfig, cx: &mut gpui fn configure(runtime: &Runtime, config: &ManagedConfig) { #[cfg(feature = "tray")] - crate::tray::bind(runtime.router.navigator(), &runtime.services); + crate::tray::bind(runtime.router.navigator(), &runtime.context().services()); runtime .router @@ -173,7 +173,7 @@ fn configure(runtime: &Runtime, config: &ManagedConfig) { } #[cfg(feature = "devtools")] - if config.control.inspection_enabled() { + if crate::control::inspection_enabled(config.control) { runtime.router.client().inspection().attach(); } @@ -289,12 +289,9 @@ impl Render for ManagedRoot { } if snapshot.reload.request.is_some() { - let router = self.router.clone(); - if snapshot.reload.phase == crate::reload::ReloadPhase::Quiescing { - window.on_next_frame(move |_, _| { - router.acknowledge_reload_ui(crate::router::WindowId(1)) - }); + self.router + .observe_reload_frame(crate::router::WindowId(1), window); cx.notify(); } diff --git a/crates/rake/src/application/managed/window.rs b/crates/rake-gpui/src/application/managed/window.rs similarity index 100% rename from crates/rake/src/application/managed/window.rs rename to crates/rake-gpui/src/application/managed/window.rs diff --git a/crates/rake/src/application/managed_tooling_tests.rs b/crates/rake-gpui/src/application/managed_tooling_tests.rs similarity index 100% rename from crates/rake/src/application/managed_tooling_tests.rs rename to crates/rake-gpui/src/application/managed_tooling_tests.rs diff --git a/crates/rake/src/application/startup.rs b/crates/rake-gpui/src/application/startup.rs similarity index 100% rename from crates/rake/src/application/startup.rs rename to crates/rake-gpui/src/application/startup.rs diff --git a/crates/rake/src/application/update_services.rs b/crates/rake-gpui/src/application/update_services.rs similarity index 100% rename from crates/rake/src/application/update_services.rs rename to crates/rake-gpui/src/application/update_services.rs diff --git a/crates/rake/src/application/web_fonts.rs b/crates/rake-gpui/src/application/web_fonts.rs similarity index 100% rename from crates/rake/src/application/web_fonts.rs rename to crates/rake-gpui/src/application/web_fonts.rs diff --git a/crates/rake-gpui/src/control.rs b/crates/rake-gpui/src/control.rs new file mode 100644 index 00000000..7133b706 --- /dev/null +++ b/crates/rake-gpui/src/control.rs @@ -0,0 +1,104 @@ +//! Control transport startup for managed applications. +pub use rake_core::control::*; + +mod facade; + +#[cfg(target_family = "wasm")] +pub use facade::WebBridge; +#[cfg(any(unix, windows))] +pub use facade::local; +pub use facade::{CommandContext, Commands, RuntimeClient}; + +use crate::router::Route; + +#[cfg(any(feature = "devtools", test))] +pub(crate) fn inspection_enabled(config: ControlConfig) -> bool { + #[cfg(not(feature = "devtools"))] + { + let _ = config; + + false + } + + #[cfg(feature = "devtools")] + { + if !matches!(config, ControlConfig::FromEnvironment) { + return false; + } + + #[cfg(any(unix, windows))] + { + std::env::var("RAKE_DEV_CONTROL").as_deref() == Ok("1") + } + #[cfg(target_family = "wasm")] + { + WebBridgeConfig::from_document().is_ok_and(|config| config.is_some()) + } + + #[cfg(not(any(unix, windows, target_family = "wasm")))] + { + false + } + } +} + +pub(crate) async fn run_host( + config: ControlConfig, + client: RuntimeClient, + application_id: String, +) { + #[cfg(any(unix, windows, target_family = "wasm"))] + run_host_client(config, client.into_host(), application_id).await; + + #[cfg(not(any(unix, windows, target_family = "wasm")))] + { + let _ = (config, client, application_id); + + futures::future::pending::<()>().await; + } +} + +#[cfg(any(unix, windows, target_family = "wasm"))] +pub(crate) async fn run_host_client( + config: ControlConfig, + client: HostClient, + application_id: String, +) { + if matches!(config, ControlConfig::FromEnvironment) { + #[cfg(any(unix, windows))] + if std::env::var("RAKE_DEV_CONTROL").as_deref() == Ok("1") { + match local::LocalServer::bind_host(&client, &application_id, &local::directory()) { + Ok(server) => { + if let Err(error) = server.run_host(client).await { + crate::error!( + error_type = std::any::type_name_of_val(&error), + "Development control stopped" + ); + } + } + Err(error) => crate::error!( + error_type = std::any::type_name_of_val(&error), + "Development control could not start" + ), + } + } + + #[cfg(target_family = "wasm")] + match WebBridgeConfig::from_document() { + Ok(Some(config)) => match WebBridge::new(config) { + Ok(bridge) => bridge.run_host(client, &application_id).await, + Err(error) => crate::error!( + error_type = std::any::type_name_of_val(&error), + "Development bridge could not start" + ), + }, + Ok(None) => {} + Err(error) => crate::error!( + error_type = std::any::type_name_of_val(&error), + "Invalid development bridge configuration" + ), + } + } + + futures::future::pending::<()>().await; +} diff --git a/crates/rake-gpui/src/control/facade.rs b/crates/rake-gpui/src/control/facade.rs new file mode 100644 index 00000000..d7d2db37 --- /dev/null +++ b/crates/rake-gpui/src/control/facade.rs @@ -0,0 +1,284 @@ +//! Typed command and control handles with the application's GPUI services. + +use std::future::Future; + +use super::{ + ApplicationCommand, CommandDescriptor, CommandError, CommandPresentation, CommandState, + ControlError, Reply, Request, RuntimeInfo, RuntimeWatch, +}; + +use crate::router::Route; +use crate::services::{ServiceError, ServiceRegistry, Services}; + +/// Owned application command context, safe to retain across awaits. +#[derive(Clone)] +pub struct CommandContext { + /// The same typed service values supplied to routed views. + pub services: ServiceRegistry, + /// Application task scope, independent of any selected tab. + pub app: crate::tasks::AppHandle, + /// Cancellation signal for this operation. + pub cancellation: crate::http::CancellationToken, +} + +impl CommandContext { + fn from_core(context: rake_core::control::CommandContext) -> Self { + Self { + services: ServiceRegistry::from_core(context.services), + app: context.app, + cancellation: context.cancellation, + } + } + + /// Returns the standard application HTTP handle, when present. + pub fn http(&self) -> Result { + self.services.http() + } + + /// Returns the standard application diagnostic collector, when present. + pub fn diagnostics(&self) -> Result { + self.services.diagnostics() + } + + /// Reconstructs the standard service view for this command. + pub fn app_services(&self) -> Result { + self.services.standard_services() + } +} + +/// Registry shared by GUI dispatch and the runtime control protocol. +#[derive(Clone)] +pub struct Commands(rake_core::control::Commands); + +impl Default for Commands { + fn default() -> Self { + Self::new() + } +} + +impl Commands { + /// An empty command registry. + pub fn new() -> Self { + Self::from_core(rake_core::control::Commands::new()) + } + + pub(crate) fn from_core(core: rake_core::control::Commands) -> Self { + Self(core.with_shortcut_validation(validate_shortcut)) + } + + pub(crate) fn into_core(self) -> rake_core::control::Commands { + self.0 + } + + /// Registers a typed command whose future runs on the local executor. + pub fn register(&self, handler: F) -> Result<(), CommandError> + where + C: ApplicationCommand, + F: Fn(C, CommandContext) -> Fut + 'static, + Fut: Future> + 'static, + { + self.0.register::(move |args, context| { + handler(args, CommandContext::from_core(context)) + }) + } + + /// Sets command presentation and wakes mounted menu hosts. + pub fn set_presentation( + &self, + id: &str, + presentation: CommandPresentation, + ) -> Result<(), CommandError> { + self.0.set_presentation(id, presentation) + } + + /// Updates availability, checkmark and label. + pub fn set_state(&self, id: &str, state: CommandState) -> Result<(), CommandError> { + self.0.set_state(id, state) + } + + /// Returns a command's presentation and state. + pub fn presentation( + &self, + id: &str, + ) -> Result<(CommandPresentation, CommandState), CommandError> { + self.0.presentation(id) + } + + /// Lists the registered command descriptors. + pub fn descriptors(&self) -> Vec { + self.0.descriptors() + } + + pub(crate) fn listen(&self) -> event_listener::EventListener { + self.0.listen() + } +} + +fn validate_shortcut(id: &str, shortcut: &str) -> Result<(), CommandError> { + let os = if cfg!(target_os = "macos") { + gpui::OperatingSystem::Mac + } else if cfg!(target_os = "windows") { + gpui::OperatingSystem::Windows + } else { + gpui::OperatingSystem::Linux + }; + + for stroke in shortcut.split_whitespace() { + gpui::Keystroke::parse_with_os(stroke, os).map_err(|error| { + CommandError::Arguments(format!("invalid shortcut for {id}: {error}")) + })?; + } + + Ok(()) +} + +/// Local client of the authoritative runtime and its GPUI services. +#[derive(Clone)] +pub struct RuntimeClient(rake_core::control::RuntimeClient); + +impl RuntimeClient { + pub(crate) fn from_core(core: rake_core::control::RuntimeClient) -> Self { + Self(core) + } + + /// Returns runtime capabilities and retention limits. + pub fn info(&self) -> RuntimeInfo { + self.0.info() + } + + /// Validates and dispatches a runtime request. + pub fn request(&self, request: Request) -> Result { + self.0.request(request) + } + + /// Dispatches asynchronous storage inspection and ordinary requests. + #[cfg(feature = "devtools")] + pub async fn request_async(&self, request: Request) -> Result { + self.0.request_async(request).await + } + + /// Captures a snapshot and starts observing the runtime from its revision. + pub fn watch(&self) -> RuntimeWatch { + self.0.watch() + } + + /// Captures the running application's shared service composition. + pub fn services(&self) -> ServiceRegistry { + ServiceRegistry::from_core(self.0.services()) + } + + /// Returns the command registry shared with the application. + pub fn commands(&self) -> Commands { + Commands::from_core(self.0.commands()) + } + + /// Dispatches typed command arguments with an explicit retry key. + pub fn dispatch( + &self, + command: C, + key: String, + ) -> Result { + self.0.dispatch(command, key) + } + + /// Executes a local typed user action through the shared scheduler. + pub fn execute(&self, command: C) -> Result { + self.0.execute(command) + } + + #[cfg(any(unix, windows, target_family = "wasm"))] + pub(crate) fn into_host(self) -> super::HostClient { + self.0.into_host() + } + + pub(crate) fn set_commands(&self, commands: Commands) { + self.0.set_commands(commands.into_core()); + } + + #[cfg(all(test, feature = "view-test-support", not(target_family = "wasm")))] + pub(crate) fn set_services(&self, services: ServiceRegistry) { + self.0.set_services(services.into_core()); + } + + pub(crate) fn dispatch_local_command( + &self, + id: String, + arguments: serde_json::Value, + ) -> Result { + self.0.dispatch_local_command(id, arguments) + } + + #[cfg(not(target_family = "wasm"))] + pub(crate) async fn responses_idle(&self) { + self.0.responses_idle().await; + } + + #[cfg(feature = "devtools")] + pub(crate) fn inspection(&self) -> crate::inspection::Store { + self.0 + .inspection_host(crate::inspection::Store::default) + .clone() + } +} + +#[cfg(any(unix, windows))] +/// Native local control transport. +pub mod local { + use super::{Route, RuntimeClient}; + use std::{io, path::Path}; + + pub use rake_core::control::local::*; + + /// The server and its bound private control socket. + pub struct LocalServer(rake_core::control::local::LocalServer); + + impl LocalServer { + /// Binds this client's discovery record and local socket. + pub fn bind( + client: &RuntimeClient, + application_id: &str, + path: &Path, + ) -> io::Result { + rake_core::control::local::LocalServer::bind(&client.0, application_id, path).map(Self) + } + + /// Serves requests until the future or runtime is dropped. + pub async fn run(&self, client: RuntimeClient) -> io::Result<()> { + self.0.run(client.0).await + } + + pub(crate) fn bind_host( + client: &crate::control::HostClient, + application_id: &str, + path: &Path, + ) -> io::Result { + rake_core::control::local::LocalServer::bind_host(client, application_id, path) + .map(Self) + } + + pub(crate) async fn run_host(&self, client: crate::control::HostClient) -> io::Result<()> { + self.0.run_host(client).await + } + } +} + +#[cfg(target_family = "wasm")] +/// Owns a browser's outbound development connection. +pub struct WebBridge(rake_core::control::WebBridge); + +#[cfg(target_family = "wasm")] +impl WebBridge { + /// Uses a dedicated bounded HTTP client for browser control polling. + pub fn new(config: super::WebBridgeConfig) -> Result { + rake_core::control::WebBridge::new(config).map(Self) + } + + /// Runs the connection until this future is dropped. + pub async fn run(&self, client: RuntimeClient, application_id: &str) { + self.0.run(client.0, application_id).await; + } + + pub(crate) async fn run_host(&self, client: super::HostClient, application_id: &str) { + self.0.run_host(client, application_id).await; + } +} diff --git a/crates/rake/src/inspection.rs b/crates/rake-gpui/src/inspection.rs similarity index 92% rename from crates/rake/src/inspection.rs rename to crates/rake-gpui/src/inspection.rs index f3f20d2d..99470a5a 100644 --- a/crates/rake/src/inspection.rs +++ b/crates/rake-gpui/src/inspection.rs @@ -923,3 +923,84 @@ fn index_page(full: &Captured, offset: usize) -> Result, + limit: usize, + ) -> Result { + self.window_page(window, cursor, limit) + } + fn preview_enabled(&self) -> bool { + self.preview_enabled() + } + fn preview_windows(&self) -> Vec { + self.preview_windows() + } + fn preview_element(&self, point: &preview::Point) -> Result { + self.preview_element(point) + } + fn preview_input( + &self, + point: &preview::Point, + input: &preview::Input, + ) -> Result<(), InspectionError> { + self.preview_input(point, input) + } + fn edit_text( + &self, + id: &str, + generation: &str, + edit: &TextEdit, + ) -> Result<(), InspectionError> { + self.edit_text(id, generation, edit) + } + fn status(&self) -> Status { + self.status() + } + fn snapshot(&self) -> Snapshot { + self.snapshot() + } + fn tree_page(&self, cursor: Option<&str>, limit: usize) -> Result { + self.tree_page(cursor, limit) + } + fn tree_revision(&self) -> TreeRevision { + self.tree_revision() + } + fn element(&self, id: &str) -> Result { + self.element(id) + } + fn pick(&self) -> Result { + self.pick() + } + fn highlight(&self, id: Option<&str>, generation: &str) -> Result<(), InspectionError> { + self.highlight(id, generation) + } + fn inspect_mode(&self, enabled: bool, lease_ms: u64) -> Result<(), InspectionError> { + self.inspect_mode(enabled, lease_ms) + } + fn navigate( + &self, + id: &str, + generation: &str, + action: NavigationAction, + ) -> Result<(), InspectionError> { + self.navigate(id, generation, action) + } + fn edit_style( + &self, + id: &str, + generation: &str, + edit: &StyleEdit, + ) -> Result<(), InspectionError> { + self.edit_style(id, generation, edit) + } + fn record_frames(&self, enabled: bool, lease_ms: u64) -> Result<(), InspectionError> { + self.record_frames(enabled, lease_ms) + } + fn frames(&self, after: u64, collector: &rake_diagnostics::Collector) -> Frames { + self.frames(after, collector) + } +} diff --git a/crates/rake/src/inspection/budget.rs b/crates/rake-gpui/src/inspection/budget.rs similarity index 100% rename from crates/rake/src/inspection/budget.rs rename to crates/rake-gpui/src/inspection/budget.rs diff --git a/crates/rake-gpui/src/inspection/disabled.rs b/crates/rake-gpui/src/inspection/disabled.rs new file mode 100644 index 00000000..2b1bb808 --- /dev/null +++ b/crates/rake-gpui/src/inspection/disabled.rs @@ -0,0 +1,95 @@ +//! Inspection contracts without capture, editing, recording or retained state. +//! +//! Enable `rake/devtools` to compile instrumentation. Manual identity builders +//! return their input unchanged; use `inspect_with` for lazily constructed names. + +pub use rake_protocol::inspection::*; + +#[derive(Clone, Default)] +pub(crate) struct Store {} + +#[cfg(test)] +impl rake_core::inspection::InspectionHost for Store {} + +#[cfg(feature = "gpui")] +mod view { + use gpui::IntoElement; + + /// The original element type when inspection is compiled out. + pub type Inspected = E; + + /// Returns the original value without converting or wrapping it. + #[inline(always)] + pub fn inspect(element: E) -> E { + element + } + + /// Identity builders when inspection is compiled out. No metadata is retained. + /// Arguments to ordinary methods still follow Rust's evaluation rules; use + /// `inspect_with` to avoid constructing a dynamic name in production. + pub trait InspectElement: IntoElement { + /// Returns the original value, discarding the supplied identity. + #[inline(always)] + fn inspect(self, _: impl Into) -> Self { + self + } + + /// Returns the original value without invoking the name builder. + #[inline(always)] + fn inspect_with(self, _: impl FnOnce() -> String) -> Self { + self + } + + /// Returns the original value without retaining handler metadata. + #[inline(always)] + fn inspect_handler(self, _: impl Into) -> Self { + self + } + + /// Returns the original value without retaining an identity. + #[inline(always)] + fn semantic_id(self, _: impl Into) -> Self { + self + } + + /// Returns the original value without cloning the focus handle. + #[inline(always)] + fn focus_handle(self, _: &gpui::FocusHandle) -> Self { + self + } + + /// Returns the original value without cloning the scroll handle. + #[inline(always)] + fn scroll_handle(self, _: &gpui::ScrollHandle) -> Self { + self + } + } + + impl InspectElement for T {} + + pub(crate) trait InspectRoot: IntoElement { + #[inline(always)] + fn root(self, _: super::Store, _: u64, _: crate::router::WindowId) -> Self { + self + } + } + + impl InspectRoot for T {} +} + +#[cfg(feature = "gpui")] +pub(crate) use view::InspectRoot; +#[cfg(feature = "gpui")] +pub use view::{InspectElement, Inspected, inspect}; + +#[cfg(test)] +mod tests { + #[test] + fn disabled_store_has_no_retained_state() { + assert_eq!(std::mem::size_of::(), 0); + #[cfg(feature = "gpui")] + assert!(!crate::control::inspection_enabled( + crate::control::ControlConfig::FromEnvironment + )); + } +} diff --git a/crates/rake/src/inspection/editing.rs b/crates/rake-gpui/src/inspection/editing.rs similarity index 100% rename from crates/rake/src/inspection/editing.rs rename to crates/rake-gpui/src/inspection/editing.rs diff --git a/crates/rake/src/inspection/preview.rs b/crates/rake-gpui/src/inspection/preview.rs similarity index 100% rename from crates/rake/src/inspection/preview.rs rename to crates/rake-gpui/src/inspection/preview.rs diff --git a/crates/rake/src/inspection/recording.rs b/crates/rake-gpui/src/inspection/recording.rs similarity index 100% rename from crates/rake/src/inspection/recording.rs rename to crates/rake-gpui/src/inspection/recording.rs diff --git a/crates/rake/src/inspection/snapshot.rs b/crates/rake-gpui/src/inspection/snapshot.rs similarity index 100% rename from crates/rake/src/inspection/snapshot.rs rename to crates/rake-gpui/src/inspection/snapshot.rs diff --git a/crates/rake/src/inspection/tests.rs b/crates/rake-gpui/src/inspection/tests.rs similarity index 100% rename from crates/rake/src/inspection/tests.rs rename to crates/rake-gpui/src/inspection/tests.rs diff --git a/crates/rake/src/inspection/text_editing.rs b/crates/rake-gpui/src/inspection/text_editing.rs similarity index 100% rename from crates/rake/src/inspection/text_editing.rs rename to crates/rake-gpui/src/inspection/text_editing.rs diff --git a/crates/rake/src/inspection/view.rs b/crates/rake-gpui/src/inspection/view.rs similarity index 98% rename from crates/rake/src/inspection/view.rs rename to crates/rake-gpui/src/inspection/view.rs index 8ea637b6..cfbdee3d 100644 --- a/crates/rake/src/inspection/view.rs +++ b/crates/rake-gpui/src/inspection/view.rs @@ -1752,6 +1752,27 @@ mod tests { #[test] fn live_frame_recording_uses_gpui_draws_and_source_attributed_callbacks() { + // GPUI collects draws process-wide, but window IDs are local to each test app. + const ISOLATED: &str = "RAKE_TEST_FRAME_RECORDING_ISOLATED"; + if std::env::var_os(ISOLATED).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "inspection::view::tests::live_frame_recording_uses_gpui_draws_and_source_attributed_callbacks", + ]) + .env(ISOLATED, "1") + .output() + .expect("run frame-recording fixture in a fresh process"); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + output.status.success() && stdout.contains("1 passed;"), + "{stdout}\n{stderr}" + ); + + return; + } + let mut app = gpui::TestAppContext::single(); let store = Store::default(); store.attach(); @@ -1773,7 +1794,7 @@ mod tests { assert!(store.record_frames(true, 5001).is_err()); store.record_frames(true, 5000).unwrap(); - // Concurrent test apps can fill the first page with draws that have no callbacks for this store. + // Fill the first page with draws that have no callbacks for this store. cx.update(|window, _| { let now = std::time::Instant::now(); diff --git a/crates/rake/src/inspection/view/accessibility.rs b/crates/rake-gpui/src/inspection/view/accessibility.rs similarity index 100% rename from crates/rake/src/inspection/view/accessibility.rs rename to crates/rake-gpui/src/inspection/view/accessibility.rs diff --git a/crates/rake/src/inspection/view/authored.rs b/crates/rake-gpui/src/inspection/view/authored.rs similarity index 100% rename from crates/rake/src/inspection/view/authored.rs rename to crates/rake-gpui/src/inspection/view/authored.rs diff --git a/crates/rake/src/inspection/view/authored/tests.rs b/crates/rake-gpui/src/inspection/view/authored/tests.rs similarity index 100% rename from crates/rake/src/inspection/view/authored/tests.rs rename to crates/rake-gpui/src/inspection/view/authored/tests.rs diff --git a/crates/rake/src/inspection/view/cache.rs b/crates/rake-gpui/src/inspection/view/cache.rs similarity index 100% rename from crates/rake/src/inspection/view/cache.rs rename to crates/rake-gpui/src/inspection/view/cache.rs diff --git a/crates/rake/src/inspection/view/geometry.rs b/crates/rake-gpui/src/inspection/view/geometry.rs similarity index 100% rename from crates/rake/src/inspection/view/geometry.rs rename to crates/rake-gpui/src/inspection/view/geometry.rs diff --git a/crates/rake/src/inspection/view/provenance.rs b/crates/rake-gpui/src/inspection/view/provenance.rs similarity index 100% rename from crates/rake/src/inspection/view/provenance.rs rename to crates/rake-gpui/src/inspection/view/provenance.rs diff --git a/crates/rake/src/inspection/view/text.rs b/crates/rake-gpui/src/inspection/view/text.rs similarity index 100% rename from crates/rake/src/inspection/view/text.rs rename to crates/rake-gpui/src/inspection/view/text.rs diff --git a/crates/rake/src/inspection/view/virtual_lists.rs b/crates/rake-gpui/src/inspection/view/virtual_lists.rs similarity index 100% rename from crates/rake/src/inspection/view/virtual_lists.rs rename to crates/rake-gpui/src/inspection/view/virtual_lists.rs diff --git a/crates/rake/src/inspection/view/window.rs b/crates/rake-gpui/src/inspection/view/window.rs similarity index 100% rename from crates/rake/src/inspection/view/window.rs rename to crates/rake-gpui/src/inspection/view/window.rs diff --git a/crates/rake/src/inspection/window.rs b/crates/rake-gpui/src/inspection/window.rs similarity index 100% rename from crates/rake/src/inspection/window.rs rename to crates/rake-gpui/src/inspection/window.rs diff --git a/crates/rake-gpui/src/lib.rs b/crates/rake-gpui/src/lib.rs new file mode 100644 index 00000000..bc34abc9 --- /dev/null +++ b/crates/rake-gpui/src/lib.rs @@ -0,0 +1,287 @@ +//! GPUI application and window integration for Rake. +//! +//! Use `rake-core` for HTTP, data and diagnostics consumers that do not need a UI. +//! Inspection and temporary style editing require the opt-in `devtools` feature; +//! ordinary native and WASM builds omit their instrumentation and retained state. + +#![cfg(feature = "gpui")] + +extern crate self as rake; +extern crate self as rake_gpui; + +pub use rake_core::{crash, diagnostics, http, logging, resources, web}; + +/// Optional, GPUI-independent per-user launch-at-login settings. +#[cfg(feature = "launch-at-login")] +pub use rake_core::login_item; + +#[cfg(not(feature = "devtools"))] +#[doc(hidden)] +pub use rake_core::__rake_inspection_disabled as __rake_inspection; +#[cfg(feature = "devtools")] +#[doc(hidden)] +pub use rake_core::__rake_inspection_enabled as __rake_inspection; + +pub use rake_core::Resources; +pub use rake_core::crash_config; + +/// Optional native components; currently exposes the macOS AppKit adapter. +#[cfg(feature = "native-components")] +pub use rake_native as native; + +#[cfg(feature = "updates")] +pub use rake_updates as updates; +#[cfg(feature = "updates")] +pub use rake_updates::updates; + +/// Runs enabled native updater installer callbacks before constructing the app. +/// Manual entry points use `early_startup!()`; `#[rake::app]` does so automatically. +/// # Panics +/// Panics if a hand-written embedded policy is invalid; rake-build validates generated policy. +pub fn early_startup_for(embedded: Option<&str>) { + early_startup_with_desktop(embedded, None); +} + +/// Runs installer startup with common desktop metadata captured by [`early_startup!`]. +/// # Panics +/// Panics if hand-written embedded metadata is invalid; rake-build validates generated metadata. +pub fn early_startup_with_desktop(embedded: Option<&str>, desktop: Option<&str>) { + #[cfg(all(feature = "updates", not(target_family = "wasm")))] + rake_updates::early_startup_with_desktop(embedded, desktop) + .expect("generated Rake distribution policy must be valid"); + #[cfg(any(not(feature = "updates"), target_family = "wasm"))] + let _ = (embedded, desktop); +} + +/// Initializes installer callbacks using policy embedded into the application crate. +#[macro_export] +macro_rules! early_startup { + () => { + $crate::early_startup_with_desktop( + option_env!("RAKE_UPDATE_POLICY"), + option_env!("RAKE_DESKTOP_METADATA"), + ) + }; +} + +pub mod control; + +pub use rake_macros::Props; + +#[doc = "Experimental signals backed by typed GPUI entities."] +#[cfg(feature = "experimental-reactive")] +pub mod reactive; + +#[cfg(feature = "experimental-reactive")] +pub use rake_macros::component; + +#[cfg(feature = "locale")] +pub mod locale; + +#[cfg(all(feature = "devtools-memory", unix))] +pub use rake_core::memory; + +#[cfg(feature = "devtools")] +pub mod inspection; +#[cfg(not(feature = "devtools"))] +#[path = "inspection/disabled.rs"] +pub mod inspection; +pub mod loading; +#[cfg(feature = "gpui")] +pub mod menus; +pub mod platform; +pub mod quit; +pub mod reload; +pub mod router; +pub mod runtime; +pub mod services; + +pub use rake_core::storage; + +#[cfg(all( + feature = "gpu-surface", + any(target_os = "macos", target_os = "linux", target_os = "windows") +))] +pub mod surface; +pub mod tasks; +#[cfg(feature = "tray")] +pub mod tray; +pub mod window_state; + +#[cfg(all(feature = "gpui", feature = "updates"))] +mod updates_binding; + +#[cfg(all(feature = "gpui", feature = "updates"))] +pub use updates_binding::{UpdateHandle, UpdateHandleState}; + +#[cfg(feature = "gpui")] +mod application; + +#[cfg(feature = "gpui")] +use rake_ui::view; + +#[cfg(feature = "gpui")] +pub mod overlay; + +#[cfg(feature = "gpui")] +pub use rake_ui::theme; + +/// Text input components for GPUI views. +#[cfg(feature = "gpui")] +pub mod ui { + pub use rake_ui::input; +} + +/// Initializes Base, optional Kit and theme observation before custom GPUI windows. +/// Rake's application builder calls this automatically. +#[cfg(feature = "gpui")] +pub use rake_ui::init as init_ui; + +/// Optional GPUI Kit components, assets and the matching GPUI API (native targets). +#[cfg(all(feature = "kit", not(target_family = "wasm")))] +pub use rake_ui::kit; + +#[cfg(feature = "gpui")] +pub use application::{App, AppError, ClosePolicy, show_main_window}; +#[cfg(feature = "gpui-fast")] +pub extern crate gpui_fast as gpui; +#[cfg(feature = "gpui-fast")] +extern crate gpui_fast_platform as gpui_platform; +#[cfg(all(feature = "gpui", not(feature = "gpui-fast")))] +pub extern crate gpui_pre as gpui; +#[cfg(feature = "gpui")] +pub use rake_macros::app; +pub use rake_macros::{Command, Route, data, instrument}; +#[cfg(feature = "gpui")] +#[doc = include_str!("../view-macro.md")] +pub use rake_macros::{Theme, style, view}; +pub use router::Route; +pub use schemars; +pub use serde; +pub use serde_json; +pub use services::{ServiceError, ServiceRegistry, Services}; +pub use tracing::{debug, error, info, trace, warn}; + +/// Common application and service imports. +pub mod prelude { + pub use crate::control::{ + ApplicationCommand, CommandContext, CommandDescriptor, CommandError, Commands, + ControlConfig, ExecutionCapability, RuntimeClient, + }; + + #[cfg(feature = "experimental-reactive")] + pub use crate::reactive::{ + Children, Memo, ReactiveApp, Resource, Setup, Signal, SignalContext, + }; + + #[cfg(all(feature = "gpui", feature = "updates"))] + pub use crate::{UpdateHandle, UpdateHandleState}; + + pub use crate::diagnostics::{Collector, DiagnosticsConfig, SubscriberMode}; + pub use crate::http::{CancellationToken, HttpClient, HttpConfig}; + #[cfg(feature = "gpui")] + pub use crate::loading::{AsyncAction, LoadContext, LoadError, Loader}; + pub use crate::loading::{LoadState, LoadStatus, LoadToken}; + + pub use crate::quit::{ + QuitGuardContext, QuitJobs, QuitOptions, QuitPhase, QuitResult, QuitStatus, + }; + + pub use crate::reload::{Checkpoint, ReloadError, ReloadState}; + pub use crate::runtime::{Runtime, RuntimeContext}; + pub use crate::services::{ServiceError, ServiceRegistry, Services}; + pub use crate::tasks::{ActivityRun, AppHandle, TaskError, TaskHandle, TaskScope}; + + pub use crate::router::{ + Activation, Admission, AdmissionContext, DecisionChoice, DecisionRequest, EntryHandle, + GuardResult, Navigator, OpenOptions, OpenTarget, Outcome, RevealScope, Route, Router, + RouterConfig, TabMode, WebConfig, WebRouting, + }; + + #[cfg(feature = "gpui")] + pub use crate::App; + #[cfg(feature = "gpui")] + pub use crate::inspection::InspectElement; + + #[cfg(feature = "gpui")] + pub use crate::router::{ + LayoutContext, LoadedPage, NavigationBoundary, Page, PageContext, RouteOutlet, RouteViews, + TabBar, + }; + + pub use rake_macros::{Command, Route}; +} + +#[doc(hidden)] +pub mod __private { + pub use crate::__rake_inspection as inspection; + #[cfg(feature = "gpui")] + pub use crate::application::{AppFactoryOutput, run_app_factory}; + + #[cfg(feature = "gpui")] + pub use rake_ui::__private::{ + EquivalentProp, IntoAttribute, ParagraphTextValue, PropComparison, PropMissing, PropSet, + PropsBuilder, RequiredProp, Value, + }; + + #[cfg(all(feature = "gpui", feature = "devtools"))] + pub use crate::inspection::authored::{ + Definition as ViewDefinition, HandlerSite as ViewHandlerSite, StyleSite as ViewStyleSite, + child as view_inspect_child, component as view_inspect_component, + component_key as view_component_key, styled as view_inspect, + }; + + #[cfg(feature = "gpui")] + pub use crate::theme::apply::{ + ThemeBackground, ThemeBorder, ThemeFont, ThemeRadius, ThemeRunFont, ThemeRunText, ThemeText, + }; + + #[cfg(feature = "gpui")] + pub use crate::view::{ + Children as ViewChildren, ComponentChildren as ViewComponentChildren, + ParagraphContent as ViewParagraphContent, RunStyle as ViewRunStyle, button as view_button, + button_base as view_button_base, entity as view_entity, focus as view_focus, + image as view_image, svg as view_svg, tab_index as view_tab_index, + tab_navigation as view_tab_navigation, + }; + + /// Deprecated macro event aliases; referenced at the authored attribute span. + #[cfg(feature = "gpui")] + pub mod view_legacy { + #[deprecated(note = "use on:click")] + pub const ONCLICK: () = (); + + #[deprecated(note = "use on:key-down")] + pub const ONKEYDOWN: () = (); + + #[deprecated(note = "use on:key-up")] + pub const ONKEYUP: () = (); + + #[deprecated(note = "use on:mouse-move")] + pub const ONMOUSEMOVE: () = (); + + #[deprecated(note = "use on:mouse-down")] + pub const ONMOUSEDOWN: () = (); + + #[deprecated(note = "use on:mouse-up")] + pub const ONMOUSEUP: () = (); + } + + pub use tracing; + #[cfg(target_family = "wasm")] + pub use wasm_bindgen; +} + +/// Declares this crate's ambient view theme; invoke once at the crate root. +/// Install the value with [`theme::install`] before building themed views. +#[cfg(feature = "gpui")] +#[macro_export] +macro_rules! theme { + ($theme:path) => { + #[doc(hidden)] + pub(crate) type __RakeTheme = $theme; + }; +} + +#[cfg(feature = "gpui")] +pub use platform::icons::Icon; diff --git a/crates/rake-gpui/src/loading.rs b/crates/rake-gpui/src/loading.rs new file mode 100644 index 00000000..6e5e8600 --- /dev/null +++ b/crates/rake-gpui/src/loading.rs @@ -0,0 +1,6 @@ +//! GPUI view bindings for managed asynchronous work. +pub use rake_core::loading::{LoadState, LoadStatus, LoadToken}; + +mod binding; + +pub use binding::{AsyncAction, LoadContext, LoadError, Loader}; diff --git a/crates/rake/src/loading/binding.rs b/crates/rake-gpui/src/loading/binding.rs similarity index 100% rename from crates/rake/src/loading/binding.rs rename to crates/rake-gpui/src/loading/binding.rs diff --git a/crates/rake/src/loading/binding_tests.rs b/crates/rake-gpui/src/loading/binding_tests.rs similarity index 100% rename from crates/rake/src/loading/binding_tests.rs rename to crates/rake-gpui/src/loading/binding_tests.rs diff --git a/crates/rake/src/locale/browser.rs b/crates/rake-gpui/src/locale/browser.rs similarity index 100% rename from crates/rake/src/locale/browser.rs rename to crates/rake-gpui/src/locale/browser.rs diff --git a/crates/rake/src/locale/formatting.rs b/crates/rake-gpui/src/locale/formatting.rs similarity index 100% rename from crates/rake/src/locale/formatting.rs rename to crates/rake-gpui/src/locale/formatting.rs diff --git a/crates/rake/src/locale/mod.rs b/crates/rake-gpui/src/locale/mod.rs similarity index 100% rename from crates/rake/src/locale/mod.rs rename to crates/rake-gpui/src/locale/mod.rs diff --git a/crates/rake/src/locale/tests.rs b/crates/rake-gpui/src/locale/tests.rs similarity index 100% rename from crates/rake/src/locale/tests.rs rename to crates/rake-gpui/src/locale/tests.rs diff --git a/crates/rake/src/locale/text.rs b/crates/rake-gpui/src/locale/text.rs similarity index 100% rename from crates/rake/src/locale/text.rs rename to crates/rake-gpui/src/locale/text.rs diff --git a/crates/rake/src/menus.rs b/crates/rake-gpui/src/menus.rs similarity index 99% rename from crates/rake/src/menus.rs rename to crates/rake-gpui/src/menus.rs index 7509a256..194a4022 100644 --- a/crates/rake/src/menus.rs +++ b/crates/rake-gpui/src/menus.rs @@ -123,6 +123,7 @@ struct Model { /// Shared live menu configuration. Clones update the same mounted host. /// /// ``` +/// # use rake_gpui as rake; /// use rake::menus::{Menu, MenuItem, MenuRole, Menus}; /// let menus = Menus::new([Menu::new("Application", [MenuItem::Role(MenuRole::Quit)])]); /// ``` diff --git a/crates/rake/src/menus/tests.rs b/crates/rake-gpui/src/menus/tests.rs similarity index 99% rename from crates/rake/src/menus/tests.rs rename to crates/rake-gpui/src/menus/tests.rs index 06f42f1e..bdcac860 100644 --- a/crates/rake/src/menus/tests.rs +++ b/crates/rake-gpui/src/menus/tests.rs @@ -51,7 +51,7 @@ fn installed_quit_item_requests_guarded_quit_and_preserves_denied_runtime() { pool.run_until_stalled(); assert!(invoked.get()); assert_eq!(router.quit_status().phase, crate::quit::QuitPhase::Blocked); - assert!(!router.is_shutdown()); + assert!(router.navigator().runtime().is_ok()); } #[test] diff --git a/crates/rake/src/overlay.rs b/crates/rake-gpui/src/overlay.rs similarity index 100% rename from crates/rake/src/overlay.rs rename to crates/rake-gpui/src/overlay.rs diff --git a/crates/rake/src/platform/browser.js b/crates/rake-gpui/src/platform/browser.js similarity index 74% rename from crates/rake/src/platform/browser.js rename to crates/rake-gpui/src/platform/browser.js index 0ae14749..204d6116 100644 --- a/crates/rake/src/platform/browser.js +++ b/crates/rake-gpui/src/platform/browser.js @@ -8,15 +8,6 @@ function activation(operation) { throw new DOMException(`${operation} requires a user gesture`, 'NotAllowedError'); } -export function capabilities() { - let bits = 0; - if (globalThis.document?.body) bits |= 1 | 2 | 32; - if (globalThis.isSecureContext && globalThis.navigator?.clipboard?.readText) bits |= 4; - if (globalThis.isSecureContext && globalThis.navigator?.clipboard?.writeText) bits |= 8; - try { if (globalThis.localStorage) bits |= 16; } catch (_) { /* Access denied. */ } - return bits; -} - export function pick_file() { try { if (!globalThis.document?.body) unsupported('file import'); @@ -60,7 +51,7 @@ export function export_file(name, bytes) { export function read_clipboard() { try { - if (!(capabilities() & 4)) unsupported('clipboard read'); + if (!(globalThis.isSecureContext && globalThis.navigator?.clipboard?.readText)) unsupported('clipboard read'); activation('clipboard read'); return navigator.clipboard.readText(); } catch (error) { return Promise.reject(error); } @@ -68,30 +59,12 @@ export function read_clipboard() { export function write_clipboard(text) { try { - if (!(capabilities() & 8)) unsupported('clipboard write'); + if (!(globalThis.isSecureContext && globalThis.navigator?.clipboard?.writeText)) unsupported('clipboard write'); activation('clipboard write'); return navigator.clipboard.writeText(text); } catch (error) { return Promise.reject(error); } } -export async function clipboard_permission(write) { - try { - return (await navigator.permissions.query({name: write ? 'clipboard-write' : 'clipboard-read'})).state; - } catch (_) { return 'unknown'; } // Firefox/Safari need not implement this permission query. -} - -export function preference_get(namespace, key) { - if (!(capabilities() & 16)) throw new DOMException('preferences access denied', 'SecurityError'); - return localStorage.getItem(`rake:prefs:${namespace}:${key}`); -} - -export function preference_set(namespace, key, value) { - if (!(capabilities() & 16)) throw new DOMException('preferences access denied', 'SecurityError'); - const id = `rake:prefs:${namespace}:${key}`; - if (value === undefined || value === null) localStorage.removeItem(id); - else localStorage.setItem(id, value); -} - export function open_url(url) { activation('open URL'); const opened = window.open('about:blank', '_blank'); diff --git a/crates/rake/src/platform/browser.rs b/crates/rake-gpui/src/platform/browser.rs similarity index 53% rename from crates/rake/src/platform/browser.rs rename to crates/rake-gpui/src/platform/browser.rs index 29a23f9d..787c43bb 100644 --- a/crates/rake/src/platform/browser.rs +++ b/crates/rake-gpui/src/platform/browser.rs @@ -1,112 +1,30 @@ -//! Browser extensions. Availability, permission and user activation are independent. +//! GPUI browser file, clipboard and activation bindings. +pub use rake_core::platform::browser::{clipboard_permission, text_from_paste_event}; + +use super::{Error, Request}; +use rake_core::platform::browser::error; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::JsFuture; -#[cfg(feature = "gpui")] -use super::Request; -use super::{Capabilities, Capability, Error, PermissionState}; - #[wasm_bindgen(module = "/src/platform/browser.js")] extern "C" { - #[wasm_bindgen(js_name = capabilities)] - fn detect() -> u32; - #[cfg(feature = "gpui")] #[wasm_bindgen(js_name = on_canvas_file_drop)] fn listen_canvas_drop(callback: &js_sys::Function) -> js_sys::Function; - #[cfg(feature = "gpui")] #[wasm_bindgen(js_name = pick_file)] fn select_file() -> js_sys::Promise; - #[cfg(feature = "gpui")] #[wasm_bindgen(js_name = read_file)] fn file_bytes(file: &JsValue, limit: f64) -> js_sys::Promise; - #[cfg(feature = "gpui")] #[wasm_bindgen(catch, js_name = export_file)] fn download_file(name: &str, bytes: &[u8]) -> Result<(), JsValue>; - #[cfg(feature = "gpui")] #[wasm_bindgen(js_name = read_clipboard)] fn clipboard_read() -> js_sys::Promise; - #[cfg(feature = "gpui")] #[wasm_bindgen(js_name = write_clipboard)] fn clipboard_write(text: &str) -> js_sys::Promise; - #[wasm_bindgen(js_name = clipboard_permission)] - fn permission(write: bool) -> js_sys::Promise; - #[wasm_bindgen(catch, js_name = preference_get)] - fn storage_get(namespace: &str, key: &str) -> Result, JsValue>; - #[wasm_bindgen(catch, js_name = preference_set)] - fn storage_set(namespace: &str, key: &str, value: Option<&str>) -> Result<(), JsValue>; - #[cfg(feature = "gpui")] #[wasm_bindgen(catch, js_name = open_url)] fn launch_url(url: &str) -> Result<(), JsValue>; } -pub(super) fn error(operation: &'static str, value: JsValue) -> Error { - let string = |key| { - js_sys::Reflect::get(&value, &JsValue::from_str(key)) - .ok() - .and_then(|value| value.as_string()) - }; - match string("name").as_deref() { - Some("NotSupportedError") => Error::Unsupported(operation), - Some("NotAllowedError" | "SecurityError") => Error::PermissionDenied(operation), - Some("QuotaExceededError") => Error::QuotaExceeded, - _ => Error::Unavailable { - operation, - message: string("message").unwrap_or_else(|| format!("{value:?}")), - }, - } -} - -pub(super) fn capabilities() -> Capabilities { - let bits = detect(); - let capability = |bit, gesture| Capability { - supported: bits & bit != 0, - permission: PermissionState::Unknown, - requires_user_gesture: gesture, - }; - Capabilities { - notifications: super::notifications::capability(), - global_shortcuts: super::GlobalShortcuts::default().capability(), - file_import: capability(1, true), - file_export: capability(2, true), - clipboard_read: capability(4, true), - clipboard_write: capability(8, true), - preferences: capability(16, false), - open_url: capability(32, true), - } -} - -/// Queries clipboard permission where supported. `Unknown` is expected on hosts -/// without this query; it does not imply that reading/writing is unavailable. -pub async fn clipboard_permission(write: bool) -> PermissionState { - match JsFuture::from(permission(write)) - .await - .ok() - .and_then(|value| value.as_string()) - .as_deref() - { - Some("granted") => PermissionState::Granted, - Some("prompt") => PermissionState::Prompt, - Some("denied") => PermissionState::Denied, - _ => PermissionState::Unknown, - } -} - -/// Reads text from a trusted DOM paste event without invoking clipboard permissions. -/// Do not suppress the browser's paste shortcut before this event can arrive. -pub fn text_from_paste_event(event: &web_sys::ClipboardEvent) -> Option { - event.clipboard_data()?.get_data("text/plain").ok() -} - -pub(super) fn preference_get(namespace: &str, key: &str) -> Result, Error> { - storage_get(namespace, key).map_err(|value| error("preferences read", value)) -} - -pub(super) fn preference_set(namespace: &str, key: &str, value: Option<&str>) -> Result<(), Error> { - storage_set(namespace, key, value).map_err(|value| error("preferences write", value)) -} - -#[cfg(feature = "gpui")] pub(super) fn pick_file() -> Request> { // Observe rejections even if work admission fails and the request is never polled. let request = JsFuture::from(select_file()); @@ -126,7 +44,6 @@ pub(super) fn pick_file() -> Request> { }) } -#[cfg(feature = "gpui")] pub(super) async fn read_file(file: &JsValue, max_bytes: usize) -> Result, Error> { let bytes = JsFuture::from(file_bytes(file, max_bytes as f64)) .await @@ -145,12 +62,10 @@ pub(super) async fn read_file(file: &JsValue, max_bytes: usize) -> Result Result<(), Error> { download_file(name, bytes).map_err(|value| error("file export", value)) } -#[cfg(feature = "gpui")] pub(super) fn read_clipboard() -> Request> { let request = JsFuture::from(clipboard_read()); Box::pin(async move { @@ -161,7 +76,6 @@ pub(super) fn read_clipboard() -> Request> { }) } -#[cfg(feature = "gpui")] pub(super) fn write_clipboard(text: &str) -> Request<()> { let request = JsFuture::from(clipboard_write(text)); Box::pin(async move { @@ -172,19 +86,16 @@ pub(super) fn write_clipboard(text: &str) -> Request<()> { }) } -#[cfg(feature = "gpui")] pub(super) fn open_url(url: &str) -> Result<(), Error> { launch_url(url).map_err(|value| error("open URL", value)) } /// Owns canvas drop listeners. Retain it while the target view is mounted. -#[cfg(feature = "gpui")] pub struct CanvasFileDrop { dispose: js_sys::Function, _callback: Closure, } -#[cfg(feature = "gpui")] impl Drop for CanvasFileDrop { fn drop(&mut self) { let _ = self.dispose.call0(&JsValue::NULL); @@ -193,7 +104,6 @@ impl Drop for CanvasFileDrop { /// Registers a canvas-wide single-file target without inventing filesystem paths. /// Empty and multi-file drops report invalid input. Reading remains caller bounded. -#[cfg(feature = "gpui")] pub fn on_canvas_file_drop( mut callback: impl FnMut(Result) + 'static, ) -> CanvasFileDrop { diff --git a/crates/rake/src/platform/files.rs b/crates/rake-gpui/src/platform/files.rs similarity index 100% rename from crates/rake/src/platform/files.rs rename to crates/rake-gpui/src/platform/files.rs diff --git a/crates/rake/src/platform/icon_cache.rs b/crates/rake-gpui/src/platform/icon_cache.rs similarity index 100% rename from crates/rake/src/platform/icon_cache.rs rename to crates/rake-gpui/src/platform/icon_cache.rs diff --git a/crates/rake/src/platform/icons.rs b/crates/rake-gpui/src/platform/icons.rs similarity index 100% rename from crates/rake/src/platform/icons.rs rename to crates/rake-gpui/src/platform/icons.rs diff --git a/crates/rake/src/platform/icons/linux.rs b/crates/rake-gpui/src/platform/icons/linux.rs similarity index 100% rename from crates/rake/src/platform/icons/linux.rs rename to crates/rake-gpui/src/platform/icons/linux.rs diff --git a/crates/rake/src/platform/icons/macos.rs b/crates/rake-gpui/src/platform/icons/macos.rs similarity index 100% rename from crates/rake/src/platform/icons/macos.rs rename to crates/rake-gpui/src/platform/icons/macos.rs diff --git a/crates/rake/src/platform/icons/windows.rs b/crates/rake-gpui/src/platform/icons/windows.rs similarity index 100% rename from crates/rake/src/platform/icons/windows.rs rename to crates/rake-gpui/src/platform/icons/windows.rs diff --git a/crates/rake-gpui/src/platform/mod.rs b/crates/rake-gpui/src/platform/mod.rs new file mode 100644 index 00000000..754b9a8e --- /dev/null +++ b/crates/rake-gpui/src/platform/mod.rs @@ -0,0 +1,215 @@ +//! GPUI host services and application permissions. + +pub use files::{FileHandle, SaveOutcome}; + +pub use rake_core::platform::{ + Capabilities, Capability, Error, Notification, NotificationOutcome, PermissionState, + Preferences, Request, Secret, +}; + +pub use shortcuts::{GlobalShortcut, GlobalShortcuts}; + +mod files; +pub mod icons; +mod notifications; +mod secrets; + +pub use secrets::Secrets; + +mod shortcuts; + +#[cfg(target_family = "wasm")] +pub mod browser; + +#[derive(Default)] +struct Host { + shortcuts: GlobalShortcuts, + notifications: std::rc::Rc, +} + +/// Shared GPUI platform services and URL activation inbox. +#[derive(Clone, Debug, Default)] +pub struct Platform { + core: rake_core::platform::Platform, +} + +impl Platform { + pub(crate) fn for_application(application_id: &str) -> Self { + Self::from_core(rake_core::platform::Platform::for_application( + application_id, + )) + } + + pub(crate) fn from_core(core: rake_core::platform::Platform) -> Self { + Self { core } + } + + pub(crate) fn into_core(self) -> rake_core::platform::Platform { + self.core + } + + fn host(&self) -> &Host { + self.core.host_state(Host::default) + } + + /// Detects current host availability without prompting for permission. + pub fn capabilities(&self) -> Capabilities { + #[cfg(target_family = "wasm")] + { + let mut capabilities = self.core.capabilities(); + + capabilities.global_shortcuts = self.host().shortcuts.capability(); + + capabilities + } + + #[cfg(not(target_family = "wasm"))] + { + let mut capabilities = self.core.capabilities(); + + let ui = Capability { + supported: true, + permission: PermissionState::NotRequired, + requires_user_gesture: false, + }; + + capabilities.file_import = ui; + capabilities.file_export = ui; + capabilities.clipboard_read = ui; + capabilities.clipboard_write = ui; + capabilities.open_url = ui; + capabilities.notifications = notifications::capability(); + capabilities.global_shortcuts = self.host().shortcuts.capability(); + + capabilities + } + } + + /// Initiates a clipboard read. An empty clipboard yields `None` on native; + /// an empty text value is `Some("")`. Browser callers should also accept paste + /// events, since programmatic clipboard permission varies between browsers. + #[cfg(feature = "gpui")] + pub fn read_clipboard(&self, cx: &gpui::App) -> Request> { + #[cfg(target_family = "wasm")] + { + let _ = cx; + + browser::read_clipboard() + } + + #[cfg(not(target_family = "wasm"))] + { + let value = cx.read_from_clipboard().and_then(|item| item.text()); + + Box::pin(async move { Ok(value) }) + } + } + + /// Initiates a clipboard write. Failure is observable on browser hosts; + /// native GPUI delegates to the system without a completion acknowledgement. + #[cfg(feature = "gpui")] + pub fn write_clipboard(&self, text: &str, cx: &gpui::App) -> Request<()> { + #[cfg(target_family = "wasm")] + { + let _ = cx; + + browser::write_clipboard(text) + } + + #[cfg(not(target_family = "wasm"))] + { + cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.to_owned())); + + Box::pin(async { Ok(()) }) + } + } + + /// Opens an HTTP, HTTPS or mailto URL. Browser popup denial is an error; + /// native GPUI acknowledges delegation, not successful external navigation. + /// + /// # Errors + /// Rejects malformed/other-scheme URLs and browser permission failures. + #[cfg(feature = "gpui")] + pub fn open_url(&self, value: &str, cx: &gpui::App) -> Result<(), Error> { + let url = external_url(value)?; + + #[cfg(target_family = "wasm")] + { + let _ = cx; + + browser::open_url(url.as_str()) + } + + #[cfg(not(target_family = "wasm"))] + { + cx.open_url(url.as_str()); + + Ok(()) + } + } +} + +fn external_url(value: &str) -> Result { + let url = url::Url::parse(value).map_err(|error| Error::InvalidInput(error.to_string()))?; + + if !matches!(url.scheme(), "https" | "http" | "mailto") { + return Err(Error::InvalidInput( + "external URL must use http, https or mailto".into(), + )); + } + + if !url.username().is_empty() || url.password().is_some() { + return Err(Error::InvalidInput( + "external URLs cannot contain credentials".into(), + )); + } + + Ok(url) +} + +impl Platform { + /// Opens an explicitly namespaced preference store. Values use last-writer-wins + /// replacement; this is not a document database or a multi-key transaction. + /// + /// # Errors + /// Rejects empty/traversal names or an unavailable native application-data root. + pub fn preferences(&self, namespace: &str) -> Result { + self.core.preferences(namespace) + } + + /// Queues a validated application URL received from a host or custom launcher. + /// The oldest activation is discarded beyond 32 pending URLs. This does not + /// navigate automatically; the application owns scheme/host/argument validation. + /// + /// # Errors + /// Rejects malformed or oversized URLs before queuing them. + pub fn receive_open_url(&self, value: &str) -> Result<(), Error> { + self.core.receive_open_url(value) + } + + /// Waits for the next activation. Clones share one inbox; competing consumers + /// divide events. Keep one application-owned consumer and cancel it at shutdown. + pub async fn next_open_url(&self) -> url::Url { + self.core.next_open_url().await + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn external_urls_reject_executable_schemes_and_credentials() { + for invalid in [ + "javascript:alert(1)", + "file:///etc/passwd", + "data:text/html,hi", + "https://user:secret@example.com", + ] { + assert!(external_url(invalid).is_err(), "accepted {invalid}"); + } + + assert!(external_url("https://example.com/path?q=a").is_ok()); + assert!(external_url("mailto:hello@example.com").is_ok()); + } +} diff --git a/crates/rake/src/platform/notifications.rs b/crates/rake-gpui/src/platform/notifications.rs similarity index 80% rename from crates/rake/src/platform/notifications.rs rename to crates/rake-gpui/src/platform/notifications.rs index 1f83f87f..e2babe90 100644 --- a/crates/rake/src/platform/notifications.rs +++ b/crates/rake-gpui/src/platform/notifications.rs @@ -2,7 +2,7 @@ #[cfg(any(feature = "gpui", test, not(target_family = "wasm")))] use super::Error; -use super::{Capability, PermissionState, Platform, Request}; +use super::{Capability, Notification, NotificationOutcome, PermissionState, Platform, Request}; #[cfg(feature = "gpui")] use std::cell::Cell; #[cfg(any(feature = "gpui", test))] @@ -20,59 +20,6 @@ const MAX_PENDING: usize = 128; #[cfg(all(feature = "gpui", not(target_family = "wasm")))] const TAG_PREFIX: &str = "rake.notification:"; -/// Notification with an application URL delivered when its body is clicked. -/// Tags replace payloads and, where supported, earlier host notifications. Payloads are -/// kept in memory, so activation after process exit is not supported. -/// -/// ``` -/// use rake::platform::Notification; -/// let notification = Notification { -/// tag: "export-42".into(), -/// title: "Export finished".into(), -/// body: "Open the exported document".into(), -/// activation_url: "myapp://exports/42".into(), -/// }; -/// assert_eq!(notification.tag, "export-42"); -/// ``` -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Notification { - /// Stable nonempty identifier, at most 128 UTF-8 bytes. - pub tag: String, - /// Nonempty headline, at most 1 KiB of UTF-8 text. - pub title: String, - /// Additional text, at most 16 KiB of UTF-8 text; rendering follows host policy. - pub body: String, - /// Absolute application URL, at most 16 KiB; validate its arguments on receipt. - pub activation_url: String, -} - -#[cfg(any(feature = "gpui", test))] -impl Notification { - fn validate(&self) -> Result { - if self.tag.is_empty() - || self.tag.len() > 128 - || self.title.is_empty() - || self.title.len() > 1024 - || self.body.len() > 16 * 1024 - { - return Err(Error::InvalidInput( - "notification tag/title/body exceeds its limits".into(), - )); - } - - super::activation_url(&self.activation_url) - } -} - -/// Delegation is distinct from permission denial and actual on-screen delivery. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum NotificationOutcome { - /// Submitted to the host; focus modes and host policy may suppress delivery. - Submitted, - /// Permission is absent. The application can continue or request authorization. - Denied, -} - #[cfg(any(feature = "gpui", test))] #[derive(Default)] pub(super) struct Notifications { @@ -85,7 +32,9 @@ pub(super) struct Notifications { pub(super) fn capability() -> Capability { #[cfg(target_family = "wasm")] - return browser::capability(); + return rake_core::platform::Platform::default() + .capabilities() + .notifications; #[cfg(not(target_family = "wasm"))] Capability { @@ -114,7 +63,7 @@ impl Platform { /// and `Unavailable` if the authorization service fails. pub fn notification_permission(&self) -> Request { #[cfg(target_family = "wasm")] - return browser::permission(false); + return self.core.notification_permission(); #[cfg(all(feature = "gpui", target_os = "macos"))] return macos::permission(false); @@ -139,7 +88,7 @@ impl Platform { /// security policy/user-gesture errors. pub fn request_notification_permission(&self) -> Request { #[cfg(target_family = "wasm")] - return browser::permission(true); + return self.core.request_notification_permission(); #[cfg(all(feature = "gpui", target_os = "macos"))] return macos::permission(true); @@ -172,7 +121,7 @@ impl Platform { Err(error) => return Box::pin(async { Err(error) }), }; - if !self.notifications.installed.get() || !capability().supported { + if !self.host().notifications.installed.get() || !capability().supported { return Box::pin(async { Err(Error::Unsupported( "notifications (requires an application host)", @@ -236,7 +185,7 @@ impl Platform { /// Returns `Unsupported` if the application notification host is unavailable. #[cfg(feature = "gpui")] pub fn dismiss_notification(&self, tag: &str, cx: &gpui::App) -> Result<(), Error> { - if !self.notifications.installed.get() || !capability().supported { + if !self.host().notifications.installed.get() || !capability().supported { return Err(Error::Unsupported("notifications")); } @@ -247,7 +196,7 @@ impl Platform { #[cfg(feature = "gpui")] fn dismiss_bound_notification(&self, tag: &str, cx: &gpui::App) { - self.notifications.pending.borrow_mut().remove(tag); + self.host().notifications.pending.borrow_mut().remove(tag); #[cfg(target_family = "wasm")] { @@ -262,7 +211,7 @@ impl Platform { #[cfg(any(feature = "gpui", test))] fn remember(&self, tag: &str, payload: url::Url) -> Result<(), Error> { - let mut pending = self.notifications.pending.borrow_mut(); + let mut pending = self.host().notifications.pending.borrow_mut(); if pending.len() == MAX_PENDING && !pending.contains_key(tag) { return Err(Error::Unavailable { @@ -282,7 +231,7 @@ impl Platform { return false; }; - let payload = self.notifications.pending.borrow_mut().remove(tag); + let payload = self.host().notifications.pending.borrow_mut().remove(tag); if let Some(payload) = payload { // The payload was validated before posting; use the same bounded inbox. @@ -296,7 +245,7 @@ impl Platform { #[cfg(feature = "gpui")] pub(crate) fn install_notifications(&self, identifier: &str, cx: &gpui::App) { - if self.notifications.installed.replace(true) { + if self.host().notifications.installed.replace(true) { return; } @@ -317,7 +266,7 @@ impl Platform { { let _ = (identifier, cx); - *self.notifications.browser.borrow_mut() = Some(browser::install(self)); + *self.host().notifications.browser.borrow_mut() = Some(browser::install(self)); } } } @@ -380,7 +329,10 @@ mod tests { assert!(platform.remember("overflow", payload.clone()).is_err()); assert!(platform.remember("0", payload).is_ok()); - assert_eq!(platform.notifications.pending.borrow().len(), MAX_PENDING); + assert_eq!( + platform.host().notifications.pending.borrow().len(), + MAX_PENDING + ); } } diff --git a/crates/rake/src/platform/notifications/browser.js b/crates/rake-gpui/src/platform/notifications/browser.js similarity index 73% rename from crates/rake/src/platform/notifications/browser.js rename to crates/rake-gpui/src/platform/notifications/browser.js index 5ca486f1..3f6ab5d3 100644 --- a/crates/rake/src/platform/notifications/browser.js +++ b/crates/rake-gpui/src/platform/notifications/browser.js @@ -5,16 +5,6 @@ export function notification_permission() { return Notification.permission; } -export function request_notification_permission() { - try { - const permission = notification_permission(); - if (permission !== 'default') return Promise.resolve(permission); - if (globalThis.navigator?.userActivation?.isActive === false) - throw new DOMException('notification permission requires a user gesture', 'NotAllowedError'); - return Notification.requestPermission(); - } catch (error) { return Promise.reject(error); } -} - export function create_host(activate) { return {activate, posted: new Map()}; } diff --git a/crates/rake/src/platform/notifications/browser.rs b/crates/rake-gpui/src/platform/notifications/browser.rs similarity index 53% rename from crates/rake/src/platform/notifications/browser.rs rename to crates/rake-gpui/src/platform/notifications/browser.rs index 6d1a4195..969f9c6e 100644 --- a/crates/rake/src/platform/notifications/browser.rs +++ b/crates/rake-gpui/src/platform/notifications/browser.rs @@ -1,17 +1,13 @@ //! Browser host requests with retained callback ownership and best-effort focus. -use super::{Capability, PermissionState, Request}; #[cfg(feature = "gpui")] use super::{Error, Notification, NotificationOutcome, Platform}; use wasm_bindgen::prelude::*; -use wasm_bindgen_futures::JsFuture; #[wasm_bindgen(module = "/src/platform/notifications/browser.js")] extern "C" { #[wasm_bindgen(catch, js_name = notification_permission)] fn query() -> Result; - #[wasm_bindgen(js_name = request_notification_permission)] - fn request() -> js_sys::Promise; #[wasm_bindgen(js_name = create_host)] fn create(activate: &js_sys::Function) -> JsValue; #[wasm_bindgen(catch, js_name = show_notification)] @@ -22,48 +18,6 @@ extern "C" { fn dispose(host: &JsValue); } -fn state(value: &str) -> PermissionState { - match value { - "granted" => PermissionState::Granted, - "denied" => PermissionState::Denied, - "default" => PermissionState::Prompt, - _ => PermissionState::Unknown, - } -} - -pub(super) fn capability() -> Capability { - let permission = query(); - - Capability { - supported: permission.is_ok(), - permission: permission - .as_deref() - .map(state) - .unwrap_or(PermissionState::Unknown), - requires_user_gesture: true, - } -} - -pub(super) fn permission(prompt: bool) -> Request { - if prompt { - let request = JsFuture::from(request()); - - Box::pin(async move { - let value = request.await.map_err(|error| { - super::super::browser::error("notification authorization", error) - })?; - - Ok(state(value.as_string().as_deref().unwrap_or("unknown"))) - }) - } else { - let result = query() - .map(|value| state(&value)) - .map_err(|error| super::super::browser::error("notifications", error)); - - Box::pin(async { result }) - } -} - #[cfg(feature = "gpui")] pub(super) struct Host { handle: JsValue, @@ -79,24 +33,14 @@ impl Drop for Host { #[cfg(feature = "gpui")] pub(super) fn install(platform: &Platform) -> Host { - let activations = std::rc::Rc::downgrade(&platform.activations); - let notifications = std::rc::Rc::downgrade(&platform.notifications); - let shortcuts = platform.shortcuts.clone(); - let application_id = platform.application_id.clone(); + let activations = platform.core.open_url_receiver(); + let notifications = std::rc::Rc::downgrade(&platform.host().notifications); let activate = Closure::new(move |tag: String| { - if let (Some(activations), Some(notifications)) = - (activations.upgrade(), notifications.upgrade()) - { + if let Some(notifications) = notifications.upgrade() { let payload = notifications.pending.borrow_mut().remove(&tag); if let Some(payload) = payload { - let platform = Platform { - application_id: application_id.clone(), - activations, - notifications, - shortcuts: shortcuts.clone(), - }; - let _ = platform.receive_open_url(payload.as_str()); + activations(payload.as_str()); } } }); @@ -115,7 +59,7 @@ pub(super) fn show( payload: url::Url, ) -> Result { let permission = - query().map_err(|error| super::super::browser::error("notifications", error))?; + query().map_err(|error| rake_core::platform::browser::error("notifications", error))?; if permission != "granted" { return Ok(NotificationOutcome::Denied); @@ -123,13 +67,14 @@ pub(super) fn show( // Reserve before posting, restoring the previous payload if the host fails. let previous = platform + .host() .notifications .pending .borrow() .get(¬ification.tag) .cloned(); platform.remember(¬ification.tag, payload)?; - let host = platform.notifications.browser.borrow(); + let host = platform.host().notifications.browser.borrow(); let host = host .as_ref() .ok_or(Error::Unsupported("notification host"))?; @@ -143,7 +88,7 @@ pub(super) fn show( match result { Ok(true) => Ok(NotificationOutcome::Submitted), result => { - let mut pending = platform.notifications.pending.borrow_mut(); + let mut pending = platform.host().notifications.pending.borrow_mut(); pending.remove(¬ification.tag); if let Some(previous) = previous { @@ -152,7 +97,7 @@ pub(super) fn show( match result { Ok(_) => Ok(NotificationOutcome::Denied), - Err(error) => Err(super::super::browser::error("notifications", error)), + Err(error) => Err(rake_core::platform::browser::error("notifications", error)), } } } @@ -160,7 +105,7 @@ pub(super) fn show( #[cfg(feature = "gpui")] pub(super) fn dismiss_tag(platform: &Platform, tag: &str) { - if let Some(host) = platform.notifications.browser.borrow().as_ref() { + if let Some(host) = platform.host().notifications.browser.borrow().as_ref() { dismiss(&host.handle, tag); } } diff --git a/crates/rake/src/platform/notifications/macos.rs b/crates/rake-gpui/src/platform/notifications/macos.rs similarity index 100% rename from crates/rake/src/platform/notifications/macos.rs rename to crates/rake-gpui/src/platform/notifications/macos.rs diff --git a/crates/rake/src/platform/notifications/tests.rs b/crates/rake-gpui/src/platform/notifications/tests.rs similarity index 97% rename from crates/rake/src/platform/notifications/tests.rs rename to crates/rake-gpui/src/platform/notifications/tests.rs index 3bcfcd39..41ce3750 100644 --- a/crates/rake/src/platform/notifications/tests.rs +++ b/crates/rake-gpui/src/platform/notifications/tests.rs @@ -45,7 +45,7 @@ async fn denial_does_not_post_or_retain_payload(cx: &mut gpui::TestAppContext) { assert_eq!(request.await.unwrap(), NotificationOutcome::Denied); assert!(cx.shown_system_notifications().is_empty()); - assert!(platform.notifications.pending.borrow().is_empty()); + assert!(platform.host().notifications.pending.borrow().is_empty()); assert!(platform.next_open_url().now_or_never().is_none()); } @@ -88,7 +88,7 @@ async fn replacement_click_and_dismissal_use_one_shared_activation_inbox( assert_eq!(consumer.next_open_url().await.as_str(), "app://external/0"); assert_eq!(consumer.next_open_url().await.as_str(), "app://export/2"); assert!(cx.delivered_system_notifications().is_empty()); - assert!(platform.notifications.pending.borrow().is_empty()); + assert!(platform.host().notifications.pending.borrow().is_empty()); cx.simulate_system_notification_response(gpui::SystemNotificationResponse { tag: "rake.notification:export".into(), action_id: None, diff --git a/crates/rake/src/platform/secrets.rs b/crates/rake-gpui/src/platform/secrets.rs similarity index 68% rename from crates/rake/src/platform/secrets.rs rename to crates/rake-gpui/src/platform/secrets.rs index 906b3a6d..1671c352 100644 --- a/crates/rake/src/platform/secrets.rs +++ b/crates/rake-gpui/src/platform/secrets.rs @@ -1,56 +1,9 @@ -//! App-namespaced credentials; values never enter Rake's storage or inspection registry. -#[cfg(feature = "gpui")] -use super::Request; -use super::{Error, Platform}; -use zeroize::Zeroizing; - -/// Owned secret bytes. Debug is redacted; serialization and Display are deliberately absent. -/// Rake-owned bytes are zeroized on drop; GPUI and OS copies are outside that guarantee. -pub struct Secret(Zeroizing>); - -impl Secret { - /// Takes ownership of bytes without making another copy. - pub fn new(bytes: Vec) -> Self { - Self(Zeroizing::new(bytes)) - } - - /// Explicitly exposes bytes for authentication. Never log or inspect this slice. - pub fn expose(&self) -> &[u8] { - &self.0 - } -} - -impl From for Secret { - fn from(token: String) -> Self { - Self::new(token.into_bytes()) - } -} - -impl From> for Secret { - fn from(bytes: Vec) -> Self { - Self::new(bytes) - } -} - -impl std::fmt::Debug for Secret { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("Secret([REDACTED])") - } -} +//! Credential operations backed by GPUI's host and background executor. +use super::{Error, Platform, Request, Secret}; /// A credential namespace. Use the same application id across restarts. -#[derive(Clone)] -pub struct Secrets { - app_id: String, -} - -impl std::fmt::Debug for Secrets { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Secrets") - .field("app_id", &self.app_id) - .finish() - } -} +#[derive(Clone, Debug)] +pub struct Secrets(rake_core::platform::Secrets); impl Platform { /// Opens the configured application's credential namespace without accessing the keychain. @@ -60,54 +13,16 @@ impl Platform { /// application id, or [`Error::InvalidInput`] if the id is outside 1–128 UTF-8 bytes. /// Credential operations apply the same length limit to names. pub fn secrets(&self) -> Result { - let app_id = self - .application_id - .as_deref() - .ok_or(Error::MissingApplicationId)?; - - validate(app_id)?; - - Ok(Secrets { - app_id: app_id.into(), - }) + self.core.secrets().map(Secrets) } } -fn validate(value: &str) -> Result<(), Error> { - if value.is_empty() || value.len() > 128 { - return Err(Error::InvalidInput( - "secret id/name must contain 1..=128 bytes".into(), - )); - } - - Ok(()) -} - impl Secrets { - #[cfg(any(feature = "gpui", test))] - fn key(&self, name: &str) -> Result { - validate(name)?; - // Hex is injective, preserves case and cannot introduce URL delimiters or NULs. - fn hex(value: &str) -> String { - value - .as_bytes() - .iter() - .map(|byte| format!("{byte:02x}")) - .collect() - } - - Ok(format!( - "rake-secret://v1/{}/{}", - hex(&self.app_id), - hex(name) - )) - } - /// Reads bytes, returning `None` for an absent name. Native work runs on GPUI's /// background executor; Web explicitly fails without touching browser storage. #[cfg(feature = "gpui")] pub fn read(&self, name: &str, cx: &gpui::App) -> Request> { - let key = self.key(name); + let key = self.0.key(name); #[cfg(not(target_family = "wasm"))] { @@ -133,7 +48,7 @@ impl Secrets { /// undo an OS operation. Windows rejects values larger than 2560 bytes. #[cfg(feature = "gpui")] pub fn write(&self, name: &str, value: Secret, cx: &gpui::App) -> Request<()> { - let key = self.key(name); + let key = self.0.key(name); #[cfg(not(target_family = "wasm"))] { @@ -157,7 +72,7 @@ impl Secrets { /// Deletes a name; an absent entry is already deleted. #[cfg(feature = "gpui")] pub fn delete(&self, name: &str, cx: &gpui::App) -> Request<()> { - let key = self.key(name); + let key = self.0.key(name); #[cfg(not(target_family = "wasm"))] { @@ -298,14 +213,6 @@ mod tests { )); } - #[test] - fn default_platform_has_no_secret_namespace() { - assert!(matches!( - Platform::default().secrets(), - Err(Error::MissingApplicationId) - )); - } - #[cfg(feature = "gpui")] #[test] fn app_services_use_the_configured_namespace() { @@ -313,38 +220,11 @@ mod tests { let secrets = services.platform().secrets().unwrap(); assert_eq!( - secrets.key("token").unwrap(), + secrets.0.key("token").unwrap(), "rake-secret://v1/6578616d706c652e617070/746f6b656e" ); } - #[test] - fn names_do_not_collide() { - let first = Platform::for_application("a/b").secrets().unwrap(); - let second = Platform::for_application("a").secrets().unwrap(); - - assert_ne!(first.key("c").unwrap(), second.key("b/c").unwrap()); - assert_ne!(first.key("A").unwrap(), first.key("a").unwrap()); - assert!(first.key("").is_err()); - } - - #[test] - fn conversions_reuse_owned_buffers() { - let token = String::from("tökén"); - let token_ptr = token.as_ptr(); - let secret = Secret::from(token); - - assert_eq!(secret.expose(), "tökén".as_bytes()); - assert_eq!(secret.expose().as_ptr(), token_ptr); - - let bytes = vec![0, 255, 42]; - let bytes_ptr = bytes.as_ptr(); - let secret = Secret::from(bytes); - - assert_eq!(secret.expose(), &[0, 255, 42]); - assert_eq!(secret.expose().as_ptr(), bytes_ptr); - } - #[test] fn diagnostics_and_debug_inspection_redact_values() { let value = Secret::new(b"DO-NOT-EXPOSE-token".to_vec()); @@ -362,7 +242,8 @@ mod tests { assert!(logs.contains("REDACTED")); assert_eq!(format!("{value:?}"), "Secret([REDACTED])"); let inspection = crate::inspection::Store::default(); - let snapshot = serde_json::to_string(&inspection.snapshot()).unwrap(); + let snapshot = rake_core::inspection::InspectionHost::snapshot(&inspection); + let snapshot = serde_json::to_string(&snapshot).unwrap(); assert!(!snapshot.contains("DO-NOT-EXPOSE")); #[cfg(feature = "devtools")] diff --git a/crates/rake/src/platform/shortcuts.rs b/crates/rake-gpui/src/platform/shortcuts.rs similarity index 99% rename from crates/rake/src/platform/shortcuts.rs rename to crates/rake-gpui/src/platform/shortcuts.rs index 4ae06135..14359d62 100644 --- a/crates/rake/src/platform/shortcuts.rs +++ b/crates/rake-gpui/src/platform/shortcuts.rs @@ -21,7 +21,7 @@ impl Default for GlobalShortcuts { impl Platform { /// Returns the global shortcut service, including on unsupported hosts. pub fn global_shortcuts(&self) -> GlobalShortcuts { - self.shortcuts.clone() + self.host().shortcuts.clone() } } diff --git a/crates/rake-gpui/src/quit.rs b/crates/rake-gpui/src/quit.rs new file mode 100644 index 00000000..c74af030 --- /dev/null +++ b/crates/rake-gpui/src/quit.rs @@ -0,0 +1,11 @@ +//! GPUI action for guarded application quit. +pub use rake_core::quit::*; + +#[cfg(feature = "gpui")] +gpui::actions!( + rake, + [ + /// Requests guarded application quit with the default wait-for-jobs policy. + RequestQuit, + ] +); diff --git a/crates/rake/src/reactive/attrs.rs b/crates/rake-gpui/src/reactive/attrs.rs similarity index 100% rename from crates/rake/src/reactive/attrs.rs rename to crates/rake-gpui/src/reactive/attrs.rs diff --git a/crates/rake/src/reactive/children.rs b/crates/rake-gpui/src/reactive/children.rs similarity index 100% rename from crates/rake/src/reactive/children.rs rename to crates/rake-gpui/src/reactive/children.rs diff --git a/crates/rake/src/reactive/component.rs b/crates/rake-gpui/src/reactive/component.rs similarity index 100% rename from crates/rake/src/reactive/component.rs rename to crates/rake-gpui/src/reactive/component.rs diff --git a/crates/rake/src/reactive/context.rs b/crates/rake-gpui/src/reactive/context.rs similarity index 100% rename from crates/rake/src/reactive/context.rs rename to crates/rake-gpui/src/reactive/context.rs diff --git a/crates/rake/src/reactive/effect.rs b/crates/rake-gpui/src/reactive/effect.rs similarity index 100% rename from crates/rake/src/reactive/effect.rs rename to crates/rake-gpui/src/reactive/effect.rs diff --git a/crates/rake/src/reactive/element.rs b/crates/rake-gpui/src/reactive/element.rs similarity index 100% rename from crates/rake/src/reactive/element.rs rename to crates/rake-gpui/src/reactive/element.rs diff --git a/crates/rake/src/reactive/event.rs b/crates/rake-gpui/src/reactive/event.rs similarity index 100% rename from crates/rake/src/reactive/event.rs rename to crates/rake-gpui/src/reactive/event.rs diff --git a/crates/rake/src/reactive/global.rs b/crates/rake-gpui/src/reactive/global.rs similarity index 100% rename from crates/rake/src/reactive/global.rs rename to crates/rake-gpui/src/reactive/global.rs diff --git a/crates/rake/src/reactive/inspection.rs b/crates/rake-gpui/src/reactive/inspection.rs similarity index 100% rename from crates/rake/src/reactive/inspection.rs rename to crates/rake-gpui/src/reactive/inspection.rs diff --git a/crates/rake/src/reactive/memo.rs b/crates/rake-gpui/src/reactive/memo.rs similarity index 100% rename from crates/rake/src/reactive/memo.rs rename to crates/rake-gpui/src/reactive/memo.rs diff --git a/crates/rake/src/reactive/mod.rs b/crates/rake-gpui/src/reactive/mod.rs similarity index 100% rename from crates/rake/src/reactive/mod.rs rename to crates/rake-gpui/src/reactive/mod.rs diff --git a/crates/rake/src/reactive/resource.rs b/crates/rake-gpui/src/reactive/resource.rs similarity index 100% rename from crates/rake/src/reactive/resource.rs rename to crates/rake-gpui/src/reactive/resource.rs diff --git a/crates/rake/src/reactive/signal.rs b/crates/rake-gpui/src/reactive/signal.rs similarity index 100% rename from crates/rake/src/reactive/signal.rs rename to crates/rake-gpui/src/reactive/signal.rs diff --git a/crates/rake/src/reactive/stats.rs b/crates/rake-gpui/src/reactive/stats.rs similarity index 100% rename from crates/rake/src/reactive/stats.rs rename to crates/rake-gpui/src/reactive/stats.rs diff --git a/crates/rake/src/reactive/tests.rs b/crates/rake-gpui/src/reactive/tests.rs similarity index 100% rename from crates/rake/src/reactive/tests.rs rename to crates/rake-gpui/src/reactive/tests.rs diff --git a/crates/rake/src/reactive/tracking.rs b/crates/rake-gpui/src/reactive/tracking.rs similarity index 100% rename from crates/rake/src/reactive/tracking.rs rename to crates/rake-gpui/src/reactive/tracking.rs diff --git a/crates/rake/src/reload/host.rs b/crates/rake-gpui/src/reload/host.rs similarity index 65% rename from crates/rake/src/reload/host.rs rename to crates/rake-gpui/src/reload/host.rs index baa60f05..3401a0c9 100644 --- a/crates/rake/src/reload/host.rs +++ b/crates/rake-gpui/src/reload/host.rs @@ -7,7 +7,7 @@ use super::WorkspaceCheckpoint; use crate::control::ControlConfig; #[cfg(target_family = "wasm")] -const STORAGE_KEY: &str = "rake-dev-workspace"; +use rake_core::reload::host::STORAGE_KEY; #[cfg(feature = "gpui")] pub(crate) fn load(config: ControlConfig) -> Option> { @@ -122,21 +122,75 @@ pub(crate) fn clear() { } } -#[cfg(target_family = "wasm")] -pub(crate) fn store(checkpoint: &WorkspaceCheckpoint) -> Result<(), String> { - let bytes = serde_json::to_string(checkpoint).map_err(|error| error.to_string())?; +#[cfg(feature = "gpui")] +pub(crate) async fn restore( + router: &crate::router::Router, + checkpoint: Option>, + application_id: &str, +) { + let Some(checkpoint) = checkpoint else { return }; + + match checkpoint { + Ok(checkpoint) => match router.restore_workspace(&checkpoint, application_id).await { + Ok(()) => clear(), + Err(error) => router.reload_failed(error.to_string()), + }, + Err(error) => router.reload_failed(error), + } +} - if bytes.len() > MAX_CHECKPOINT_BYTES { - return Err("reload checkpoint exceeds 512 KiB".into()); +#[cfg(feature = "gpui")] +pub(crate) use ui::ReloadUi; + +#[cfg(feature = "gpui")] +mod ui { + use std::cell::RefCell; + use std::collections::BTreeSet; + use std::rc::Rc; + + use crate::router::{Navigator, Route, WindowId}; + use crate::tasks::HostVisibility; + + #[derive(Default)] + pub(crate) struct ReloadUi { + pending: RefCell>>>, } - web_sys::window() - .ok_or("browser unavailable")? - .session_storage() - .map_err(|error| format!("{error:?}"))? - .ok_or("session storage unavailable")? - .set_item(STORAGE_KEY, &bytes) - .map_err(|error| format!("{error:?}")) + impl ReloadUi { + pub(crate) fn begin(&self, windows: Vec) { + // Frames queued for a previous request can only acknowledge that request. + self.pending + .replace(Rc::new(RefCell::new(windows.into_iter().collect()))); + } + + pub(crate) fn ready( + &self, + visibility: &dyn Fn(WindowId) -> Option, + ) -> bool { + self.pending + .borrow() + .borrow() + .iter() + .all(|&id| matches!(visibility(id), None | Some(HostVisibility::Hidden))) + } + + pub(crate) fn observe_frame( + &self, + id: WindowId, + window: &mut gpui::Window, + navigator: Navigator, + ) { + let pending = self.pending.borrow().clone(); + + window.on_next_frame(move |_, _| { + if pending.borrow_mut().remove(&id) + && let Some(router) = navigator.upgrade_router() + { + router.reload_readiness_changed(); + } + }); + } + } } /// Transient live status shares the existing managed/routed reload presentation. diff --git a/crates/rake/src/reload/live.rs b/crates/rake-gpui/src/reload/live.rs similarity index 100% rename from crates/rake/src/reload/live.rs rename to crates/rake-gpui/src/reload/live.rs diff --git a/crates/rake/src/reload/mod.rs b/crates/rake-gpui/src/reload/mod.rs similarity index 62% rename from crates/rake/src/reload/mod.rs rename to crates/rake-gpui/src/reload/mod.rs index bfd754b5..f5f12506 100644 --- a/crates/rake/src/reload/mod.rs +++ b/crates/rake-gpui/src/reload/mod.rs @@ -1,11 +1,10 @@ -//! Development checkpoint contracts and host coordination. +//! GPUI startup and frame coordination for development reload. pub use rake_protocol::reload::*; +pub(crate) mod host; + #[cfg(any( all(feature = "live", not(target_family = "wasm")), all(test, not(target_family = "wasm")) ))] pub(crate) mod live; - -#[cfg(any(feature = "gpui", target_family = "wasm"))] -pub(crate) mod host; diff --git a/crates/rake/src/router/layout.rs b/crates/rake-gpui/src/router/layout.rs similarity index 100% rename from crates/rake/src/router/layout.rs rename to crates/rake-gpui/src/router/layout.rs diff --git a/crates/rake-gpui/src/router/mod.rs b/crates/rake-gpui/src/router/mod.rs new file mode 100644 index 00000000..743a9fb1 --- /dev/null +++ b/crates/rake-gpui/src/router/mod.rs @@ -0,0 +1,133 @@ +//! Typed routing with GPUI-backed route views and window lifecycle. + +use crate::services::ServiceRegistry; +use std::ops::Deref; + +pub use layout::LayoutContext; +pub use navigation_view::NavigationBoundary; + +#[doc(hidden)] +pub use page::{ + __mount_loaded_page, __mount_page, __prepare_loaded_page, __routes, __routes_prepared, +}; + +pub use page::{LoadedPage, Page}; +pub use rake_core::router::*; +pub use view::{PageContext, RouteOutlet, RouteViews, TabBar}; + +/// Owned input to a route admission policy, including the application's services. +pub type AdmissionContext = rake_core::router::AdmissionContext; + +#[doc(hidden)] +pub type AdmissionCallback = std::rc::Rc< + dyn Fn(AdmissionContext) -> futures::future::LocalBoxFuture<'static, Admission>, +>; + +pub(crate) mod layout; +mod mount; +mod navigation_view; +mod page; +mod portable; + +pub use mount::{RouteMount, RouteMountContext}; + +#[cfg(all(test, feature = "view-test-support", not(target_family = "wasm")))] +pub(crate) mod test_mount; +pub(crate) mod view; +#[cfg(target_family = "wasm")] +pub(crate) mod web; + +/// Owns a typed router and exposes GPUI host attachment. +#[derive(Clone)] +pub struct Router(rake_core::router::Router); + +impl Router { + /// Creates a headless routing runtime. + pub fn new(config: RouterConfig) -> Self { + Self(rake_core::router::Router::new(config)) + } + + /// Creates a headless routing runtime with the supplied services. + pub fn with_services(config: RouterConfig, services: ServiceRegistry) -> Self { + Self(rake_core::router::Router::with_services( + config, + services.into_core(), + )) + } + + /// Creates a routing runtime with a retained mount adapter. + pub fn with_route_mount( + config: RouterConfig, + services: ServiceRegistry, + adapter: impl RouteMount, + ) -> Self { + Self(rake_core::router::Router::with_route_mount( + config, + services.into_core(), + mount::FacadeMount(adapter), + )) + } + + pub(crate) fn from_core(core: rake_core::router::Router) -> Self { + Self(core) + } + + /// Returns a local control client with the application's GPUI services. + pub fn client(&self) -> crate::control::RuntimeClient { + crate::control::RuntimeClient::from_core(self.0.client()) + } + + /// Returns a weak navigation handle for this workspace. + pub fn navigator(&self) -> Navigator { + Navigator(self.0.navigator()) + } +} + +impl Deref for Router { + type Target = rake_core::router::Router; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +/// Weak, origin-scoped navigation and GPUI host access. +#[derive(Clone)] +pub struct Navigator(rake_core::router::Navigator); + +impl Navigator { + pub(crate) fn from_core(core: rake_core::router::Navigator) -> Self { + Self(core) + } + + pub(crate) fn into_core(self) -> rake_core::router::Navigator { + self.0 + } + + pub(crate) fn upgrade_router(&self) -> Option> { + self.0.upgrade_router().map(Router::from_core) + } + + pub(crate) fn runtime(&self) -> Result, OperationError> { + self.0.runtime().map(Router::from_core) + } + + /// Retargets this navigator to a physical window. + pub fn for_window(&self, window: WindowId) -> Self { + Self(self.0.for_window(window)) + } + + /// Upgrades this navigator for use in a custom native window host. + #[cfg(not(target_family = "wasm"))] + pub fn router(&self) -> Option> { + self.upgrade_router() + } +} + +impl Deref for Navigator { + type Target = rake_core::router::Navigator; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} diff --git a/crates/rake-gpui/src/router/mount.rs b/crates/rake-gpui/src/router/mount.rs new file mode 100644 index 00000000..49a5b7ea --- /dev/null +++ b/crates/rake-gpui/src/router/mount.rs @@ -0,0 +1,97 @@ +//! Route mount entry points with the GPUI facade's service and navigation handles. + +use super::{ + EntryHandle, EntryId, MountError, MountedRoute, Navigator, PreparedPage, Route, WindowId, +}; + +use crate::http::CancellationToken; +use crate::services::ServiceRegistry; +use futures::future::LocalBoxFuture; + +/// The provisional entry and its host, supplied when mounting a fresh route. +pub struct RouteMountContext { + /// Window that owns the entry. A secondary host has already been opened. + pub window_id: WindowId, + /// Stable identity of this visit, preserved across history and checkpoint restore. + pub entry_id: EntryId, + /// Weak handle valid during mount, including for reading restored entry state. + pub entry: EntryHandle, + /// Weak navigator bound to the entry's window and tab. + pub navigator: Navigator, +} + +/// Prepares and mounts typed destinations on the caller-driven router loop. +/// +/// Both callbacks can use local futures. The router owns admission and history, +/// and publishes the mount only after the transition commits. +pub trait RouteMount: 'static { + /// Prepares owned data after admission and initial guards, before mounting + /// or opening a secondary host. During restore, all entries prepare before + /// any secondary host is opened. + /// + /// The router can drop the future on cancellation. Use the token for + /// cooperative work, and release provisional resources on drop. + /// + /// # Errors + /// Return a preparation error to leave the current workspace intact. + fn prepare( + &self, + _destination: &R, + _services: ServiceRegistry, + _cancellation: CancellationToken, + ) -> LocalBoxFuture<'static, Result> { + Box::pin(async { Ok(PreparedPage::empty()) }) + } + + /// Consumes prepared data and creates a provisional mount. + /// + /// Keep it hidden until committed presentation. During restore, read + /// entry checkpoints through the weak handle before returning. On error or + /// cancellation before a handle is returned, the adapter must clean up + /// resources it has created. After it returns a handle, the router disposes + /// it on rollback, removal, close or shutdown. + /// + /// # Errors + /// Return a mount error to leave the current workspace intact. + fn mount( + &self, + destination: &R, + prepared: PreparedPage, + context: RouteMountContext, + ) -> LocalBoxFuture<'static, Result, MountError>>; +} + +pub(super) struct FacadeMount(pub A); + +impl> rake_core::router::RouteMount for FacadeMount { + fn prepare( + &self, + destination: &R, + services: rake_core::ServiceRegistry, + cancellation: CancellationToken, + ) -> LocalBoxFuture<'static, Result> { + self.0.prepare( + destination, + ServiceRegistry::from_core(services), + cancellation, + ) + } + + fn mount( + &self, + destination: &R, + prepared: PreparedPage, + context: rake_core::router::RouteMountContext, + ) -> LocalBoxFuture<'static, Result, MountError>> { + self.0.mount( + destination, + prepared, + RouteMountContext { + window_id: context.window_id, + entry_id: context.entry_id, + entry: context.entry, + navigator: Navigator::from_core(context.navigator), + }, + ) + } +} diff --git a/crates/rake/src/router/navigation_view.rs b/crates/rake-gpui/src/router/navigation_view.rs similarity index 100% rename from crates/rake/src/router/navigation_view.rs rename to crates/rake-gpui/src/router/navigation_view.rs diff --git a/crates/rake/src/router/page.rs b/crates/rake-gpui/src/router/page.rs similarity index 99% rename from crates/rake/src/router/page.rs rename to crates/rake-gpui/src/router/page.rs index 1aa74c8b..04a4f095 100644 --- a/crates/rake/src/router/page.rs +++ b/crates/rake-gpui/src/router/page.rs @@ -190,6 +190,7 @@ pub fn __mount_loaded_page>( /// for parameters; the page receives the complete typed destination in `mount`. /// /// ``` +/// # use rake_gpui as rake; /// use rake::gpui::{self, AppContext, Context, IntoElement, Render}; /// use rake::prelude::*; /// use rake::router::MountError; @@ -221,6 +222,7 @@ pub fn __mount_loaded_page>( /// A registered component must implement `Page`, not only `Render`: /// /// ```compile_fail +/// # use rake_gpui as rake; /// #[derive(Clone, rake::Route)] /// enum Destination { #[route(id = "home", path = "/")] Home } /// let _ = rake::routes! { Destination::Home => rake::gpui::Empty }; @@ -229,6 +231,7 @@ pub fn __mount_loaded_page>( /// Adding a destination requires updating registration; there is no implicit fallback: /// /// ```compile_fail +/// # use rake_gpui as rake; /// # use rake::gpui::{self, AppContext}; /// # use rake::prelude::*; /// # use rake::router::MountError; diff --git a/crates/rake-gpui/src/router/portable.rs b/crates/rake-gpui/src/router/portable.rs new file mode 100644 index 00000000..be2e9f34 --- /dev/null +++ b/crates/rake-gpui/src/router/portable.rs @@ -0,0 +1,368 @@ +//! Inherent routing methods forwarded to the shared scheduler. + +use std::future::Future; +#[cfg(feature = "updates")] +use std::rc::Rc; + +use super::{ + BrowserCheckpoint, DecisionError, DecisionId, EntryHandle, EntryId, GuardContext, GuardReason, + GuardResult, HistoryChange, NavigationKey, NavigationStatus, Navigator, OpenOptions, + OpenTarget, Opened, Operation, OperationError, OperationId, OperationState, QuitGuardContext, + RevealScope, Revealed, Route, Router, RouterSnapshot, RuntimeId, TabHandle, TabId, + WindowClosed, WindowHost, WindowId, +}; + +use crate::quit::{QuitOptions, QuitResult, QuitStatus}; +use crate::reload::{ReloadError, ReloadRequest, ReloadStatus, WorkspaceCheckpoint}; +use crate::tasks::{AppHandle, HostVisibility}; + +impl Router { + /// Identity of this live runtime, stable until host teardown or full reload. + pub fn runtime_id(&self) -> RuntimeId { + self.0.runtime_id() + } + + /// Registers an access guard before the operation driver starts. + pub fn entry_guard(&self, guard: F) -> Result<(), OperationError> + where + F: Fn(GuardContext) -> Fut + 'static, + Fut: Future + 'static, + { + self.0.entry_guard(guard) + } + + /// Registers typed, side-effect-free route admission before the operation driver starts. + pub fn entry_admission(&self, admission: F) -> Result<(), OperationError> + where + F: Fn(crate::router::AdmissionContext) -> Fut + 'static, + Fut: Future> + 'static, + { + self.0.entry_admission(move |context| { + admission(super::AdmissionContext { + operation_id: context.operation_id, + window_id: context.window_id, + target_tab: context.target_tab, + destination: context.destination, + services: crate::services::ServiceRegistry::from_core(context.services), + }) + }) + } + + /// Returns retained navigation statuses for one presenting window. + pub fn navigation(&self, window: WindowId) -> Vec { + self.0.navigation(window) + } + + /// Retries an exact retained navigation through the normal admission and guard chain. + pub fn retry_navigation( + &self, + key: &NavigationKey, + ) -> Result, OperationError> { + self.0.retry_navigation(key) + } + + /// Removes one exact retained navigation status. + pub fn dismiss_navigation(&self, key: &NavigationKey) -> Result<(), OperationError> { + self.0.dismiss_navigation(key) + } + + /// Registers an application-wide guard for every future quit. + /// + /// Guards run after finite work has settled or been cancelled and after all + /// retained entries have approved their disposal. They run immediately + /// before the router enters `Stopping`; return an error to keep the runtime + /// open. The callback owns its application state and must re-read mutable + /// state before approving, because the router cannot revalidate state that + /// lives outside its model. + /// + /// Register guards before [`Router::run`](Self::run) starts driving the + /// runtime. Registration after that point returns `InvalidOptions`. + pub fn quit_guard(&self, guard: F) -> Result<(), OperationError> + where + F: Fn(QuitGuardContext) -> Fut + 'static, + Fut: Future> + 'static, + { + self.0.quit_guard(guard) + } + + /// Installs the browser/embedding history sink. Failures are exposed in snapshots. + pub fn on_history(&self, sink: impl Fn(HistoryChange) -> Result<(), String> + 'static) { + self.0.on_history(sink) + } + + /// Copies state without exposing retained views or mutable histories. + pub fn snapshot(&self) -> RouterSnapshot { + self.0.snapshot() + } + + /// Returns retained operation state or an explicit expiration/unknown error. + pub fn operation(&self, id: OperationId) -> Result { + self.0.operation(id) + } + + /// Finds a retained entry handle by identity, including non-current history entries. + pub fn entry(&self, id: EntryId) -> Result, OperationError> { + self.0.entry(id) + } + + /// Waits for a newer owned snapshot revision without a snapshot/subscription gap. + pub async fn changed(&self, revision: u64) -> u64 { + self.0.changed(revision).await + } + + /// Requests cancellation. Returns false when the operation already finished. + pub fn cancel(&self, id: OperationId) -> Result { + self.0.cancel(id) + } + + /// Stops admission and cancels pending operations. Host termination is not a guarded quit. + pub fn shutdown(&self) { + self.0.shutdown() + } + + /// Drives eagerly submitted jobs. Conflicting tab jobs run in order; other tabs continue. + /// The host owns this future and must keep polling it for the runtime's lifetime. + pub async fn run(&self) -> Result<(), OperationError> { + self.0.run().await + } + + /// Application-owned tasks survive internal tab close; their origin is retained. + pub fn app(&self) -> AppHandle { + self.0.app() + } + + /// Supplies an actual host visibility signal, independently of keyboard focus. + /// Unknown assumes visible while exposing that visibility is unmeasured. + pub fn set_host_visibility(&self, visibility: HostVisibility) { + self.0.set_host_visibility(visibility) + } + + /// Installs guarded host close and, when supported, additional window creation. + /// Install before the driver starts. The route mount adapter must mount each + /// destination in its navigator's window. + /// + /// # Errors + /// Rejects repeat installation, a running driver, or multi-window support in a browser. + pub fn window_host(&self, host: impl WindowHost) -> Result<(), OperationError> { + self.0.window_host(host) + } + + /// Advertised targets; single-window and browser hosts omit NewWindow. + pub fn supported_targets(&self) -> Vec { + self.0.supported_targets() + } + + /// Copies one host's tabs, selection and decisions without changing global state. + pub fn snapshot_in_window(&self, window: WindowId) -> Result { + self.0.snapshot_in_window(window) + } + + /// Guards every retained entry before disposing this window atomically. + /// Other windows and application-owned tasks survive. Repeated pending closes + /// join the same operation. Cancellation/denial leaves the complete window intact. + pub fn close_window(&self, window: WindowId) -> Operation { + self.0.close_window(window) + } + + /// Reports visibility for exactly one window; hiding it does not stop another host. + pub fn set_window_visibility( + &self, + window: WindowId, + visibility: HostVisibility, + ) -> Result<(), OperationError> { + self.0.set_window_visibility(window, visibility) + } + + /// Latest quit phase and live finite-work identities. Ready remains queryable until host exit. + pub fn quit_status(&self) -> QuitStatus { + self.0.quit_status() + } + + /// Attaches one staged update to a new guarded quit operation. + /// + /// Existing document, history, window and active-work guards run unchanged. + /// Decline/cancellation drops the handoff without installation. Hosts commit + /// it with `complete_update_restart` only after `QuitPhase::Ready`. + /// # Errors + /// Rejects concurrent quits or a quit that was not admitted. + #[cfg(feature = "updates")] + pub fn quit_for_update( + &self, + handoff: rake_updates::RestartHandoff, + options: QuitOptions, + ) -> Result, rake_updates::Error> { + self.0.quit_for_update(handoff, options) + } + + /// Runs a pending updater after all guards and managed work have completed. + /// Native Rake workspaces call this before host exit; custom hosts call it there too. + /// Returns the native SDK/host termination disposition, retained across windows. + /// # Errors + /// Rejects premature calls and preserves native handoff failures for manual restart. + #[cfg(feature = "updates")] + pub fn complete_update_restart( + &self, + ) -> Result { + self.0.complete_update_restart() + } + + /// Returns the updater's failed restart diagnostic, for a manual-restart UI. + #[cfg(feature = "updates")] + pub fn update_restart_error(&self) -> Option { + self.0.update_restart_error() + } + + /// Eagerly submits one guarded quit. Concurrent requests join its operation; + /// the first request's job policy wins. Dropping handles never cancels quit. + pub fn quit(&self, options: QuitOptions) -> Operation { + self.0.quit(options) + } + + /// Current reload state. Ready means managed futures have been dropped and the + /// host UI has acknowledged detachment; it does not prove native code unload safety. + pub fn reload_status(&self) -> ReloadStatus { + self.0.reload_status() + } + + /// Stops admission and invalidates publications before cancelling old managed work. + /// Busy operations/decisions must settle explicitly; preparation never cancels saves. + pub fn prepare_reload(&self, request: ReloadRequest) -> Result { + self.0.prepare_reload(request) + } + + /// Captures a prepared workspace on the UI thread. Application providers can fail; + /// the supervisor must abort or preserve that failure, never silently restart empty. + pub fn reload_checkpoint( + &self, + application_id: &str, + ) -> Result { + self.0.reload_checkpoint(application_id) + } + + /// Resumes eligible factories after abort or supported in-place replacement. + /// `applied=true` is an assertion by the external native reloader: it owns code + /// replacement, ABI compatibility and retirement of every old callback/destructor. + pub fn finish_reload(&self, id: &str, applied: bool) -> Result { + self.0.finish_reload(id, applied) + } + + /// Reconstructs an empty replacement workspace. Validates every route/identity + /// before mounting; mounts are provisional until all checkpoint consumers succeed. + /// On failure, no partial workspace is attached and the caller retains its checkpoint. + pub async fn restore_workspace( + &self, + checkpoint: &WorkspaceCheckpoint, + application_id: &str, + ) -> Result<(), ReloadError> { + self.0.restore_workspace(checkpoint, application_id).await + } + + /// Returns the application's shared update model, when installed policy is available. + #[cfg(feature = "updates")] + pub fn updates(&self) -> Option> { + self.0.updates() + } + + /// Checks the installed provider without downloading or requesting termination. + /// # Errors + /// Rejects unavailable or externally managed providers and concurrent operations. + #[cfg(feature = "updates")] + pub fn check_for_updates(&self) -> Result<(), rake_updates::Error> { + self.0.check_for_updates() + } + + /// Downloads the selected update; Sparkle uses its native review UI. + /// # Errors + /// Rejects missing availability or another active operation. + #[cfg(feature = "updates")] + pub fn download_update(&self) -> Result<(), rake_updates::Error> { + self.0.download_update() + } + + /// Submits verified staging to the existing save, work and window quit guards. + /// # Errors + /// Rejects absent staging or a competing quit operation. + #[cfg(feature = "updates")] + pub fn restart_for_update( + &self, + options: QuitOptions, + ) -> Result, rake_updates::Error> { + self.0.restart_for_update(options) + } +} + +impl Navigator { + /// Dispatches typed application arguments through the same operation as the CLI. + /// The page keeps only its weak navigator, avoiding a retained-view ownership cycle. + pub fn dispatch( + &self, + command: C, + key: String, + ) -> Result { + self.0.dispatch(command, key) + } + + /// Application work with this navigator's original causal tab and entry IDs. + pub fn app(&self) -> AppHandle { + self.0.app() + } + + /// Eagerly opens a destination with default activation and tab mode. + pub fn open(&self, destination: R, target: OpenTarget) -> Operation { + self.0.open(destination, target) + } + + /// Eagerly submits explicit creation options; new tabs never silently deduplicate. + pub fn open_with(&self, destination: R, options: OpenOptions) -> Operation { + self.0.open_with(destination, options) + } + + /// Resolves this navigator's current committed tab without cloning workspace history. + /// Page-bound navigators retain their originating tab; window-bound navigators + /// resolve that window's selection when called. + /// # Errors + /// Returns `NoCurrentTab`, a closed-target error, or a lifecycle admission error. + pub fn current_tab(&self) -> Result, OperationError> { + self.0.current_tab() + } + + /// Targets an exact tab without semantic reuse. + pub fn tab(&self, tab_id: TabId) -> TabHandle { + self.0.tab(tab_id) + } + + /// Reuses the most recently selected matching current entry, or creates one tab. + pub fn reveal(&self, destination: R, scope: RevealScope) -> Operation { + self.0.reveal(destination, scope) + } + + /// Restores a browser checkpoint without pushing another browser visit. + pub fn restore(&self, checkpoint: BrowserCheckpoint) -> Operation { + self.0.restore(checkpoint) + } + + /// Restores a decoded deep link without adding a browser visit or destroying other tabs. + pub fn restore_destination(&self, destination: R) -> Operation { + self.0.restore_destination(destination) + } + + /// Resolves one currently valid decision. Unknown choices leave the decision pending. + pub fn respond(&self, id: DecisionId, choice: &str) -> Result<(), DecisionError> { + self.0.respond(id, choice) + } + + /// Closes this navigator's concrete window, independently of keyboard focus. + pub fn close_window(&self) -> Operation { + self.0.close_window() + } + + /// Host captured by this navigator; it is never inferred from current keyboard focus. + pub fn window_id(&self) -> WindowId { + self.0.window_id() + } + + /// Requests the same application-wide guarded quit as the CLI and native close handler. + pub fn quit(&self, options: QuitOptions) -> Operation { + self.0.quit(options) + } +} diff --git a/crates/rake-gpui/src/router/test_mount.rs b/crates/rake-gpui/src/router/test_mount.rs new file mode 100644 index 00000000..1913726a --- /dev/null +++ b/crates/rake-gpui/src/router/test_mount.rs @@ -0,0 +1,98 @@ +//! Mount callbacks for the GPUI test platform, which has no native host. + +use rake_core::router::{RouteMount, RouteMountContext}; +use std::any::Any; +use std::rc::Rc; + +use futures::future::LocalBoxFuture; + +use super::{ + EntryHandle, MountError, MountedRoute, Navigator, PreparedPage, Route, Router, RouterConfig, +}; +use crate::diagnostics::Collector; +use crate::http::CancellationToken; +use rake_core::services::ServiceRegistry; + +pub(crate) type Resource = Rc; + +pub(crate) type Mount = Rc< + dyn Fn( + R, + EntryHandle, + Navigator, + ) -> LocalBoxFuture<'static, Result>, +>; + +pub(crate) type Prepare = + Rc LocalBoxFuture<'static, Result>>; + +pub(crate) type PreparedMount = Rc< + dyn Fn( + R, + EntryHandle, + Navigator, + PreparedPage, + ) -> LocalBoxFuture<'static, Result>, +>; + +pub(super) struct TestResource(pub Resource); +impl MountedRoute for TestResource {} + +struct TestMount { + prepare: Prepare, + mount: PreparedMount, +} + +impl RouteMount for TestMount { + fn prepare( + &self, + destination: &R, + _services: ServiceRegistry, + cancellation: CancellationToken, + ) -> LocalBoxFuture<'static, Result> { + // Existing fixtures prepare only from destination and cancellation. + (self.prepare)(destination.clone(), cancellation) + } + + fn mount( + &self, + destination: &R, + prepared: PreparedPage, + context: RouteMountContext, + ) -> LocalBoxFuture<'static, Result, MountError>> { + let mount = (self.mount)( + destination.clone(), + context.entry, + Navigator::from_core(context.navigator), + prepared, + ); + Box::pin(async move { Ok(Box::new(TestResource(mount.await?)) as Box) }) + } +} + +impl Router { + pub(crate) fn with_mount(config: RouterConfig, collector: Collector, mount: Mount) -> Self { + let prepared_mount: PreparedMount = + Rc::new(move |destination, entry, navigator, _| mount(destination, entry, navigator)); + + let prepare: Prepare = Rc::new(|_, _| Box::pin(async { Ok(PreparedPage::empty()) })); + + Self::with_prepared_mount(config, collector, prepare, prepared_mount) + } + + pub(crate) fn with_prepared_mount( + config: RouterConfig, + collector: Collector, + prepare: Prepare, + mount: PreparedMount, + ) -> Self { + let adapter = TestMount { prepare, mount }; + + Self::from_core(rake_core::router::Router::with_route_mount_and_collector( + config, + Default::default(), + collector, + adapter, + )) + } +} diff --git a/crates/rake/src/router/view.rs b/crates/rake-gpui/src/router/view.rs similarity index 92% rename from crates/rake/src/router/view.rs rename to crates/rake-gpui/src/router/view.rs index e8950e38..b221c593 100644 --- a/crates/rake/src/router/view.rs +++ b/crates/rake-gpui/src/router/view.rs @@ -1,5 +1,7 @@ //! GPUI mounting and presentation; retained entries own independent view entities. +mod host; + #[cfg(all(test, feature = "view-test-support", not(target_family = "wasm")))] #[path = "view/layout_tests.rs"] mod layout_tests; @@ -19,6 +21,7 @@ use crate::inspection::InspectRoot as _; #[cfg(not(target_family = "wasm"))] use futures::FutureExt as _; +use std::any::Any; use std::cell::RefCell; use std::collections::BTreeMap; use std::rc::Rc; @@ -27,14 +30,17 @@ use gpui::prelude::*; use gpui::{AnyView, Context, ElementId, IntoElement, Render, RenderOnce, Window, div, rgb}; use crate::Services; +use crate::http::CancellationToken; use crate::tasks::{ActivityRun, AppHandle, TaskError, TaskHandle, TaskScope}; +use futures::future::LocalBoxFuture; +use rake_core::services::ServiceRegistry; use super::layout::{LayoutContext, LayoutFactory}; -use super::runtime::{AdmissionCallback, Guard, Prepare, PreparedMount, Resource}; +use rake_core::router::{Guard, RouteMount, RouteMountContext}; use super::{ - EntryHandle, MountError, Navigator, PreparedPage, Route, Router, RouterConfig, TabHandle, - TabId, WebConfig, WindowId, + AdmissionCallback, EntryHandle, MountError, MountedRoute, Navigator, PreparedPage, Route, + Router, RouterConfig, TabHandle, TabId, WebConfig, WindowId, }; #[cfg(not(target_family = "wasm"))] @@ -267,7 +273,7 @@ impl Router { services: Services, views: Rc>, initial_window: WindowId, - contexts: Rc>>, + contexts: host::WindowContexts, window: &Window, cx: &gpui::App, ) -> Self { @@ -275,56 +281,80 @@ impl Router { .borrow_mut() .insert(initial_window, window.to_async(cx)); let collector = services.diagnostics(); - let registry = services.registry(); - let mounting_contexts = contexts.clone(); - let background = cx.background_executor().clone(); - - let preparing_views = views.clone(); - let preparing_services = services.clone(); - - let prepare: Prepare = Rc::new(move |destination, _entry, _navigator, cancellation| { - let views = preparing_views.clone(); + let registry = services.registry().into_core(); - let context = crate::loading::LoadContext::new( - preparing_services.clone(), - cancellation, - background.clone(), - ); + let adapter = GpuiRouteMount { + views, + contexts: contexts.clone(), + services, + background: cx.background_executor().clone(), + }; - Box::pin(async move { views.prepare(&destination, context).await }) - }); + let router = Router::from_core(rake_core::router::Router::with_route_mount_and_collector( + config, registry, collector, adapter, + )); - let mount: PreparedMount = Rc::new(move |destination, entry, navigator, prepared| { - let context = mounting_contexts - .borrow() - .get(&navigator.window_id()) - .cloned(); + router.set_initial_window(initial_window); + router.bind_view_contexts(contexts); + router.observe_host(window, cx); - let views = views.clone(); - let services = services.clone(); + router + } +} - Box::pin(async move { - let mut context = - context.ok_or_else(|| MountError("The target window has closed.".into()))?; +struct GpuiRouteMount { + views: Rc>, + contexts: host::WindowContexts, + services: Services, + background: gpui::BackgroundExecutor, +} - let page = PageContext::new(navigator, entry, services)?; +struct ViewMount(AnyView); - context - .update(|window, cx| { - views.mount_prepared(&destination, prepared, page, window, cx) - }) - .map_err(|error| MountError(error.to_string()))? - .map(|view| Rc::new(view) as Resource) - }) - }); +impl MountedRoute for ViewMount {} - let router = Router::with_prepared_mount(config, collector, prepare, mount); +impl RouteMount for GpuiRouteMount { + fn prepare( + &self, + destination: &R, + _services: ServiceRegistry, + cancellation: CancellationToken, + ) -> LocalBoxFuture<'static, Result> { + let context = crate::loading::LoadContext::new( + self.services.clone(), + cancellation, + self.background.clone(), + ); - router.bind_initial_window(initial_window, contexts); - router.client().set_services(registry); - router.observe_host(window, cx); + self.views.prepare(destination, context) + } - router + fn mount( + &self, + destination: &R, + prepared: PreparedPage, + context: RouteMountContext, + ) -> LocalBoxFuture<'static, Result, MountError>> { + let window = self.contexts.borrow().get(&context.window_id).cloned(); + let destination = destination.clone(); + let views = self.views.clone(); + let services = self.services.clone(); + + Box::pin(async move { + let mut window = + window.ok_or_else(|| MountError("The target window has closed.".into()))?; + + let page = PageContext::new( + Navigator::from_core(context.navigator), + context.entry, + services, + )?; + + window + .update(|window, cx| views.mount_prepared(&destination, prepared, page, window, cx)) + .map_err(|error| MountError(error.to_string()))? + .map(|view| Box::new(ViewMount(view)) as Box) + }) } } @@ -484,9 +514,16 @@ impl RenderOnce for RouteOutlet { let router = self.navigator.runtime().ok(); let view = router.as_ref().and_then(|router| { - router - .resource(self.window) - .and_then(|resource| resource.downcast_ref::().cloned()) + let mounted = router.presented_mount(self.window)?; + let view: &dyn Any = mounted.as_ref(); + + #[cfg(all(test, feature = "view-test-support", not(target_family = "wasm")))] + if let Some(resource) = view.downcast_ref::() { + return resource.0.downcast_ref::().cloned(); + } + + view.downcast_ref::() + .map(|mount| mount.0.clone()) }); #[cfg(feature = "devtools")] @@ -555,7 +592,7 @@ impl Drop for Workspace { pub(crate) struct RoutingRoot { pub(crate) chrome: bool, pub(crate) navigation_feedback: bool, - pub(crate) quit_guards: Vec, + pub(crate) quit_guards: Vec, pub(crate) views: Rc>, pub(crate) initial: Option, pub(crate) checkpoint: Option>, @@ -694,7 +731,7 @@ impl Workspace { #[cfg(not(target_family = "wasm"))] router - .window_host(native.clone()) + .window_host(NativeWindowHost(native.clone())) .map_err(|error| MountError(error.to_string()))?; for guard in quit_guards { @@ -720,7 +757,7 @@ impl Workspace { crate::tray::bind(router.navigator(), &layout_services); #[cfg(feature = "devtools")] - if control.inspection_enabled() { + if crate::control::inspection_enabled(control) { router.client().inspection().attach(); } @@ -775,17 +812,7 @@ impl Workspace { let drive = async move |_view: gpui::WeakEntity, cx: &mut gpui::AsyncApp| { let execute = async { - if let Some(checkpoint) = checkpoint { - match checkpoint { - Ok(checkpoint) => { - match driven.restore_workspace(&checkpoint, &restore_id).await { - Ok(()) => crate::reload::host::clear(), - Err(error) => driven.reload_failed(error.to_string()), - } - } - Err(error) => driven.reload_failed(error), - } - } + crate::reload::host::restore(&driven, checkpoint, &restore_id).await; if let Err(error) = driven.run().await { crate::error!( @@ -983,12 +1010,8 @@ impl Render for Workspace { } if snapshot.reload.request.is_some() { - let router = self.router.clone(); - if snapshot.reload.phase == crate::reload::ReloadPhase::Quiescing { - let host = self.window; - - window.on_next_frame(move |_, _| router.acknowledge_reload_ui(host)); + self.router.observe_reload_frame(self.window, window); cx.notify(); } @@ -1312,7 +1335,7 @@ impl gpui::Global for NativeDriver {} struct NativeWindows { app: gpui::AsyncApp, navigator: Navigator, - contexts: Rc>>, + contexts: host::WindowContexts, views: Rc>>>>, chrome: bool, navigation_feedback: bool, @@ -1322,13 +1345,16 @@ struct NativeWindows { } #[cfg(not(target_family = "wasm"))] -impl WindowHost for Rc> { +struct NativeWindowHost(Rc>); + +#[cfg(not(target_family = "wasm"))] +impl WindowHost for NativeWindowHost { fn open( &self, id: WindowId, activation: Activation, ) -> futures::future::LocalBoxFuture<'static, Result<(), MountError>> { - let host = self.clone(); + let host = self.0.clone(); async move { let router = host @@ -1445,9 +1471,9 @@ impl WindowHost for Rc> { } fn close(&self, id: WindowId) { - let context = self.contexts.borrow_mut().remove(&id); + let context = self.0.contexts.borrow_mut().remove(&id); - self.views.borrow_mut().remove(&id); + self.0.views.borrow_mut().remove(&id); if let Some(mut context) = context { let _ = context.update(|window, cx| { @@ -1458,7 +1484,7 @@ impl WindowHost for Rc> { } fn activate(&self, id: WindowId) { - let context = self.contexts.borrow().get(&id).cloned(); + let context = self.0.contexts.borrow().get(&id).cloned(); if let Some(mut context) = context { let _ = context.update(|window, _| window.activate_window()); diff --git a/crates/rake-gpui/src/router/view/host.rs b/crates/rake-gpui/src/router/view/host.rs new file mode 100644 index 00000000..c5bac726 --- /dev/null +++ b/crates/rake-gpui/src/router/view/host.rs @@ -0,0 +1,210 @@ +//! GPUI window registration and native lifecycle callbacks. + +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::rc::Rc; + +use gpui::{App, AsyncWindowContext, Window}; + +use crate::reload::host::ReloadUi; +use crate::tasks::{HostVisibility, host::HostObserver}; + +use crate::router::OperationError; +use rake_core::router::HostBinding; + +use super::{Route, Router, WindowId}; + +#[cfg(all(feature = "native-lifecycle", target_os = "macos"))] +mod quit; +#[cfg(all(feature = "updates", not(target_family = "wasm")))] +mod updates; + +pub(super) type WindowContexts = Rc>>; + +#[derive(Default)] +struct GpuiHost { + contexts: Option, + observers: RefCell>, + reload: ReloadUi, + #[cfg(all(feature = "native-lifecycle", target_os = "macos"))] + native_quit: RefCell>>, + #[cfg(all(feature = "updates", not(target_family = "wasm")))] + update_revision: std::cell::Cell>, +} + +impl HostBinding for GpuiHost { + fn detach_window(&self, id: WindowId) { + self.observers.borrow_mut().remove(&id); + + if let Some(contexts) = &self.contexts { + contexts.borrow_mut().remove(&id); + } + } + + fn shutdown(&self) { + self.observers.borrow_mut().clear(); + } + + fn begin_reload(&self, windows: Vec) { + self.reload.begin(windows); + } + + fn reload_ready(&self, visibility: &dyn Fn(WindowId) -> Option) -> bool { + self.reload.ready(visibility) + } +} + +impl Router { + pub(super) fn bind_view_contexts(&self, contexts: WindowContexts) { + self.bind_host(GpuiHost { + contexts: Some(contexts), + ..GpuiHost::default() + }); + } + + #[cfg(all(test, feature = "view-test-support", not(target_family = "wasm")))] + pub(in crate::router::view) fn bind_initial_window( + &self, + id: WindowId, + contexts: WindowContexts, + ) { + self.set_initial_window(id); + self.bind_view_contexts(contexts); + } + + /// Registers the UI context of a window reserved by a custom [`WindowHost`](crate::router::WindowHost). + /// Call from the host's `open` callback before it resolves. The router must have + /// been created with [`Self::in_window`]; headless routers reject this method. + /// The embedding shell owns redrawing and keeping the shared driver alive. + pub fn attach_window( + &self, + id: WindowId, + window: &Window, + cx: &App, + ) -> Result<(), OperationError> { + self.check_window(id)?; + + let contexts = self + .gpui_host() + .and_then(|host| host.contexts.as_ref()) + .ok_or(OperationError::InvalidOptions)?; + + contexts.borrow_mut().insert(id, window.to_async(cx)); + self.observe_window(id, window, cx, false); + + Ok(()) + } + + fn gpui_host(&self) -> Option<&GpuiHost> { + (self.host_binding()? as &dyn std::any::Any).downcast_ref() + } + + pub(crate) fn observe_host(&self, window: &Window, cx: &App) { + self.observe_window(self.navigator().window_id(), window, cx, false); + } + + /// Observes a standalone root while allowing its native window to close + /// without requesting application quit. The runtime remains available for + /// tray/background work until its owning host explicitly shuts it down. + pub(crate) fn observe_root_host(&self, window: &Window, cx: &App) { + self.observe_window(self.navigator().window_id(), window, cx, true); + } + + fn observe_window(&self, id: WindowId, window: &Window, cx: &App, detach_on_close: bool) { + if self.host_binding().is_none() { + self.bind_host(GpuiHost::default()); + } + + let host = self.gpui_host().expect("GPUI host binding was installed"); + + self.set_host_attached(true); + + #[cfg(not(target_family = "wasm"))] + { + let closing = self.navigator(); + + window.on_window_should_close(cx, move |window, cx| { + crate::window_state::native::capture(window, cx); + + let Some(router) = closing.upgrade_router() else { + return true; + }; + + if detach_on_close { + router.detach_host(id); + + return true; + } + + router.request_host_close(id) + }); + } + + #[cfg(target_family = "wasm")] + let _ = detach_on_close; + + let reporting = self.navigator(); + let shutdown = reporting.clone(); + + #[cfg(target_family = "wasm")] + let unload = reporting.clone(); + + let observer = HostObserver::attach( + move |visibility| { + if let Some(router) = reporting.upgrade_router() { + let _ = router.set_window_visibility(id, visibility); + } + }, + move || { + if let Some(router) = shutdown.upgrade_router() { + router.shutdown(); + } + }, + move || { + #[cfg(target_family = "wasm")] + return unload + .upgrade_router() + .is_some_and(|router| router.warn_before_unload()); + + #[cfg(not(target_family = "wasm"))] + false + }, + window, + cx, + ); + + host.observers.borrow_mut().insert(id, observer); + } + + pub(crate) fn detach_host(&self, id: WindowId) { + let _ = self.set_window_visibility(id, HostVisibility::Hidden); + + if let Some(host) = self.gpui_host() { + host.detach_window(id); + self.set_host_attached(!host.observers.borrow().is_empty()); + } + } + + pub(crate) fn observe_reload_frame(&self, id: WindowId, window: &mut Window) { + if let Some(host) = self.gpui_host() { + host.reload.observe_frame(id, window, self.navigator()); + } + } + + pub(crate) fn install_quit_action(&self, cx: &mut App) { + if self.host_binding().is_none() { + self.bind_host(GpuiHost::default()); + } + + #[cfg(all(feature = "native-lifecycle", target_os = "macos"))] + self.install_native_quit(); + + let navigator = self.navigator(); + + cx.on_action(move |_: &crate::quit::RequestQuit, _| { + if let Some(router) = navigator.upgrade_router() { + drop(router.quit(crate::quit::QuitOptions::default())); + } + }); + } +} diff --git a/crates/rake-gpui/src/router/view/host/quit.rs b/crates/rake-gpui/src/router/view/host/quit.rs new file mode 100644 index 00000000..abf5dece --- /dev/null +++ b/crates/rake-gpui/src/router/view/host/quit.rs @@ -0,0 +1,82 @@ +//! Native quit bridge for the GPUI host. + +use super::{Route, Router}; +use crate::quit::{QuitOptions, QuitPhase}; +use futures::FutureExt; +#[cfg(not(feature = "updates"))] +use futures::future::select; +use std::rc::Rc; + +impl Router { + pub(crate) fn install_native_quit(&self) { + let Some(host) = self.gpui_host() else { + return; + }; + + if host.native_quit.borrow().is_none() { + match rake_updates::NativeQuitBridge::new() { + Ok(bridge) => *host.native_quit.borrow_mut() = Some(Rc::new(bridge)), + Err(error) => tracing::error!( + error_type = std::any::type_name_of_val(&error), + "native quit guard could not be installed" + ), + } + } + } + + pub(crate) fn native_quit_changed(&self) -> futures::future::LocalBoxFuture<'static, ()> { + let changed = self.native_quit_bridge().map(|bridge| bridge.changed()); + + async move { + if let Some(changed) = changed { + changed.await; + } else { + std::future::pending::<()>().await; + } + } + .boxed_local() + } + + #[cfg(not(feature = "updates"))] + pub(crate) async fn changed_with_native_quit(&self, revision: u64) -> u64 { + let changed = self.changed(revision); + let _ = select(Box::pin(changed), self.native_quit_changed()).await; + + self.poll_native_quit(); + + self.revision() + } + + pub(crate) fn poll_native_quit(&self) { + let requested = self + .native_quit_bridge() + .is_some_and(|bridge| bridge.take_request()); + + if requested { + drop(self.quit(QuitOptions::default())); + } + + if matches!( + self.quit_status().phase, + QuitPhase::Cancelled | QuitPhase::Blocked + ) { + self.reply_native_quit(false); + } + } + + pub(crate) fn prepare_native_exit(&self, approved: bool) { + if let Some(bridge) = self.native_quit_bridge() { + bridge.prepare_exit(approved); + } + } + + pub(crate) fn reply_native_quit(&self, approved: bool) { + if let Some(bridge) = self.native_quit_bridge() { + bridge.reply(approved); + } + } + + pub(super) fn native_quit_bridge(&self) -> Option> { + self.gpui_host()?.native_quit.borrow().clone() + } +} diff --git a/crates/rake-gpui/src/router/view/host/updates.rs b/crates/rake-gpui/src/router/view/host/updates.rs new file mode 100644 index 00000000..ac55363d --- /dev/null +++ b/crates/rake-gpui/src/router/view/host/updates.rs @@ -0,0 +1,108 @@ +//! Provider and native-quit wakeups for the managed GPUI driver. + +use super::{Route, Router}; +#[cfg(all(feature = "updates-sparkle", target_os = "macos"))] +use crate::quit::QuitOptions; +#[cfg(all(feature = "updates-sparkle", target_os = "macos"))] +use rake_updates::{Error, UpdateState}; + +impl Router { + pub(crate) async fn changed_with_updates(&self, revision: u64) -> u64 { + let Some(host) = self.gpui_host() else { + return self.changed(revision).await; + }; + + let updates = self.updates(); + + let update_revision = updates + .as_ref() + .map(|controller| controller.snapshot().revision); + + if let Some(next) = update_revision + && host.update_revision.replace(Some(next)) != Some(next) + { + self.poll_updates(); + self.notify_update_changed(); + + return self.revision(); + } + + let changed = self.changed(revision); + + let update = async { + if let (Some(updates), Some(revision)) = (&updates, update_revision) { + updates.changed(revision).await; + } else { + std::future::pending::<()>().await; + } + }; + + let changed = futures::future::select(Box::pin(changed), Box::pin(update)); + + #[cfg(all(feature = "native-lifecycle", target_os = "macos"))] + let _ = futures::future::select(Box::pin(changed), self.native_quit_changed()).await; + + #[cfg(not(all(feature = "native-lifecycle", target_os = "macos")))] + let _ = changed.await; + + self.poll_updates(); + #[cfg(all(feature = "native-lifecycle", target_os = "macos"))] + self.poll_native_quit(); + + if let Some(updates) = &updates { + let next = updates.snapshot().revision; + + if host.update_revision.replace(Some(next)) != Some(next) { + self.notify_update_changed(); + } + } + + self.revision() + } + + fn poll_updates(&self) { + #[cfg(all(feature = "updates-sparkle", target_os = "macos"))] + if let Some(updates) = self.updates() { + if updates.binding().owner == rake_updates::UpdateOwner::Sparkle + && matches!(updates.state(), UpdateState::ReadyToRestart(_)) + && let Err(error) = self.restart_for_update(QuitOptions::default()) + { + tracing::error!( + error_type = std::any::type_name_of_val(&error), + "native update restart was not admitted" + ); + } + + if self.awaiting_provider_exit() + && let Some(status) = updates.native_status() + { + match status.stage { + rake_updates::SparkleStage::Installing => self.update_provider_exiting(), + rake_updates::SparkleStage::Failed => self.report_update_restart_error( + status + .error + .unwrap_or_else(|| "native installer failed".into()), + ), + _ => {} + } + } + } + } + + #[cfg(all(feature = "updates-sparkle", target_os = "macos"))] + pub(crate) fn install_sparkle(&self) -> Result<(), Error> { + let Some(updates) = self.updates() else { + return Ok(()); + }; + + if updates.binding().owner != rake_updates::UpdateOwner::Sparkle { + return Ok(()); + } + + let quit = self + .native_quit_bridge() + .ok_or_else(|| Error::Policy("Sparkle requires an active native quit bridge".into()))?; + + updates.attach_sparkle(quit) + } +} diff --git a/crates/rake/src/router/view/layout_tests.rs b/crates/rake-gpui/src/router/view/layout_tests.rs similarity index 99% rename from crates/rake/src/router/view/layout_tests.rs rename to crates/rake-gpui/src/router/view/layout_tests.rs index 895b396f..3cec62e3 100644 --- a/crates/rake/src/router/view/layout_tests.rs +++ b/crates/rake-gpui/src/router/view/layout_tests.rs @@ -9,7 +9,7 @@ use super::{LayoutContext, LayoutFactory, Workspace, mount_layout}; use crate::diagnostics::Collector; use crate::gpui::{self, AnyView, Context, Entity, Render, Window, prelude::*}; use crate::http::{HttpClient, HttpConfig}; -use crate::router::runtime::{Mount, Resource}; +use crate::router::test_mount::{Mount, Resource}; use crate::router::{MountError, RouteOutlet, Router, RouterConfig, WindowId}; use crate::services::{ServiceRegistry, Services}; use futures::FutureExt as _; diff --git a/crates/rake/src/router/view/loaded_page_tests.rs b/crates/rake-gpui/src/router/view/loaded_page_tests.rs similarity index 99% rename from crates/rake/src/router/view/loaded_page_tests.rs rename to crates/rake-gpui/src/router/view/loaded_page_tests.rs index d94a1763..11da1baa 100644 --- a/crates/rake/src/router/view/loaded_page_tests.rs +++ b/crates/rake-gpui/src/router/view/loaded_page_tests.rs @@ -10,7 +10,7 @@ use crate::diagnostics::Collector; use crate::gpui::{self, Context, Entity, Render, Window, prelude::*}; use crate::http::{HttpClient, HttpConfig}; use crate::loading::LoadContext; -use crate::router::runtime::{Prepare, PreparedMount, Resource}; +use crate::router::test_mount::{Prepare, PreparedMount, Resource}; use crate::router::{ LoadedPage, MountError, NavigationState, OpenTarget, OperationError, Outcome, Page, PageContext, PreparedPage, RouteViews, Router, RouterConfig, WindowId, @@ -185,7 +185,7 @@ fn add_host(cx: &mut gpui::TestAppContext, services: Services) -> gpui::WindowHa let background = cx.background_executor().clone(); let prepare_views = views.clone(); let prepare_services = services.clone(); - let prepare: Prepare = Rc::new(move |destination, _, _, cancellation| { + let prepare: Prepare = Rc::new(move |destination, cancellation| { let views = prepare_views.clone(); let context = LoadContext::new(prepare_services.clone(), cancellation, background.clone()); diff --git a/crates/rake/src/router/view/navigation_tests.rs b/crates/rake-gpui/src/router/view/navigation_tests.rs similarity index 99% rename from crates/rake/src/router/view/navigation_tests.rs rename to crates/rake-gpui/src/router/view/navigation_tests.rs index d8c69de7..a596013e 100644 --- a/crates/rake/src/router/view/navigation_tests.rs +++ b/crates/rake-gpui/src/router/view/navigation_tests.rs @@ -6,7 +6,7 @@ use crate::diagnostics::Collector; use crate::gpui::{self, AnyView, Context, InputEvent as _, Render, Window, prelude::*}; -use crate::router::runtime::{Mount, Resource}; +use crate::router::test_mount::{Mount, Resource}; use crate::router::{ CancelReason, MountError, NavigationState, NavigationStatus, OpenTarget, OperationError, Outcome, Router, RouterConfig, WindowId, diff --git a/crates/rake/src/router/view/page_tests.rs b/crates/rake-gpui/src/router/view/page_tests.rs similarity index 99% rename from crates/rake/src/router/view/page_tests.rs rename to crates/rake-gpui/src/router/view/page_tests.rs index e0a1763b..effd21dc 100644 --- a/crates/rake/src/router/view/page_tests.rs +++ b/crates/rake-gpui/src/router/view/page_tests.rs @@ -7,7 +7,7 @@ use super::PageContext; use crate::gpui::{self, Context, Entity, Task, WeakEntity, Window, prelude::*}; use crate::prelude::*; -use crate::router::runtime::{Mount, Resource}; +use crate::router::test_mount::{Mount, Resource}; use crate::router::{MountError, OperationError}; use futures::FutureExt as _; use std::cell::{Cell, RefCell}; diff --git a/crates/rake/src/router/web.rs b/crates/rake-gpui/src/router/web.rs similarity index 54% rename from crates/rake/src/router/web.rs rename to crates/rake-gpui/src/router/web.rs index 1ea94b11..db4dcded 100644 --- a/crates/rake/src/router/web.rs +++ b/crates/rake-gpui/src/router/web.rs @@ -1,157 +1,9 @@ -//! Browser history is a workspace visit journal, distinct from each tab's history. - -use serde::{Deserialize, Serialize}; - -use super::{EntryId, Route, RouteAddress, RouteDecodeError, RuntimeId, TabId}; - -/// URL representation used by the browser host. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum WebRouting { - /// Absolute paths; the deployment server must serve the app shell for deep links. - #[default] - Path, - /// Application URI in the fragment, for hosts without document-route rewrites. - Hash, -} - -/// Browser routing configuration. Native hosts retain it without changing OS behavior. -#[derive(Clone, Debug)] -pub struct WebConfig { - pub(crate) routing: WebRouting, - base_path: String, -} - -impl Default for WebConfig { - fn default() -> Self { - Self { - routing: WebRouting::Path, - base_path: "/".into(), - } - } -} - -impl WebConfig { - /// Uses path routing. - pub fn new() -> Self { - Self::default() - } - - /// Selects path or hash routing. - pub fn routing(mut self, routing: WebRouting) -> Self { - self.routing = routing; - - self - } - - /// Sets the deployment prefix. It must start/end with `/` and contain only - /// ASCII letters, digits, `-`, `_`, `.`, `~` and nonempty path segments. - /// Dot segments, encoded separators and URL query/fragment syntax are rejected. - pub fn base_path(mut self, path: impl Into) -> Result { - let path = path.into(); - - if !path.starts_with('/') - || !path.ends_with('/') - || !path - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || b"/-._~".contains(&byte)) - || (path != "/" - && path[1..path.len() - 1] - .split('/') - .any(|part| matches!(part, "" | "." | ".."))) - { - return Err(RouteDecodeError::InvalidUri( - "invalid Web deployment base path".into(), - )); - } - - self.base_path = path; - - Ok(self) - } - - /// Produces a browser path or fragment URL, including this deployment's prefix. - pub fn uri_for(&self, destination: &R) -> Result { - Ok(self.write_uri(&destination.to_uri()?)) - } - - /// Decodes an absolute HTTP(S) URL within this deployment. Path and hash modes - /// use the same typed route codec; paths outside the prefix are rejected. - pub fn destination_from_url(&self, url: &str) -> Result { - let url = url::Url::parse(url) - .map_err(|error| RouteDecodeError::InvalidUri(error.to_string()))?; - - if !matches!(url.scheme(), "http" | "https") { - return Err(RouteDecodeError::InvalidUri( - "Web routes require HTTP(S)".into(), - )); - } - - let path = if url.path() == self.base_path.trim_end_matches('/') { - "" - } else { - url.path().strip_prefix(&self.base_path).ok_or_else(|| { - RouteDecodeError::InvalidUri("URL is outside the Web deployment".into()) - })? - }; - - let uri = match self.routing { - WebRouting::Path => format!( - "/{path}{}", - url.query() - .map(|query| format!("?{query}")) - .unwrap_or_default() - ), - WebRouting::Hash => url - .fragment() - .filter(|fragment| !fragment.is_empty()) - .unwrap_or("/") - .into(), - }; - - R::from_uri(&uri) - } - - fn write_uri(&self, uri: &str) -> String { - match self.routing { - WebRouting::Path => format!("{}{}", self.base_path, uri.trim_start_matches('/')), - WebRouting::Hash => format!("{}#{uri}", self.base_path), - } - } -} - -/// A reconstructible browser visit with optional live-instance hints. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct BrowserCheckpoint { - /// Current schema version, initially 1. - pub version: u32, - /// Runtime in which these hints were created. - pub runtime_id: RuntimeId, - /// Internal application tab hint. - pub tab_id: TabId, - /// Retained screen hint. - pub entry_id: EntryId, - /// Complete canonical destination, authoritative when hints are stale. - pub destination: RouteAddress, -} - -/// A committed workspace's intended URL update. Restore never emits Push. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum HistoryChange { - /// Add a visible workspace visit. - Push(BrowserCheckpoint, String), - /// Initialize, reconcile or replace the current visit without adding one. - Replace(BrowserCheckpoint, String), - /// The last tab closed; clear Rake state and show the root URL. - Clear, -} - -#[cfg(all(target_family = "wasm", feature = "gpui"))] pub(crate) mod browser { use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::{JsCast, JsValue, closure::Closure}; - use super::{BrowserCheckpoint, HistoryChange, WebConfig, WebRouting}; + use crate::router::{BrowserCheckpoint, HistoryChange, WebConfig, WebRouting}; use crate::router::{Navigator, OperationError, Route, RouteDecodeError, Router}; pub(crate) fn configuration(mut config: WebConfig) -> Result { @@ -175,11 +27,11 @@ pub(crate) mod browser { .map_err(|_| invalid("invalid deployment metadata"))?; config = config.base_path(value.base_path)?; - config.routing = match value.routing.as_str() { + config = config.routing(match value.routing.as_str() { "path" => WebRouting::Path, "hash" => WebRouting::Hash, _ => return Err(invalid("invalid deployment routing mode")), - }; + }); } Ok(config) @@ -216,7 +68,7 @@ pub(crate) mod browser { let written_visit = last_visit.clone(); let written_window = window.clone(); let written_config = config.clone(); - let hash_routing = config.routing == WebRouting::Hash; + let hash_routing = config.routing_mode() == WebRouting::Hash; router.on_history(move |change| { let (checkpoint, uri, push) = match change { diff --git a/crates/rake-gpui/src/runtime.rs b/crates/rake-gpui/src/runtime.rs new file mode 100644 index 00000000..4b96ad68 --- /dev/null +++ b/crates/rake-gpui/src/runtime.rs @@ -0,0 +1,282 @@ +//! GPUI bindings for the application runtime and its weak context. + +use crate::quit::{QuitOptions, QuitResult, QuitStatus}; +use crate::router::{Navigator, NoRoute, Route, Router, RouterConfig}; +use crate::router::{Operation, OperationError}; +use crate::services::Services; +use crate::tasks::{AppHandle, TaskScope}; +#[cfg(feature = "updates")] +use std::rc::Rc; + +/// Owns a framework-free runtime and exposes GPUI binding contexts. +pub struct Runtime { + core: rake_core::runtime::Runtime, + pub(crate) router: Router, +} + +impl Runtime { + /// Creates a runtime with the supplied application services. + pub fn new(config: RouterConfig, services: Services) -> Self { + let core = rake_core::runtime::Runtime::new(config, services.into_core()); + let router = Router::from_core(core.router().clone()); + + Self { core, router } + } +} + +impl Runtime { + /// Returns this runtime's local control client. + pub fn client(&self) -> crate::control::RuntimeClient { + self.router.client() + } + + /// Returns the shared command registry. + pub fn commands(&self) -> crate::control::Commands { + self.client().commands() + } + + /// Returns a weak capability context with GPUI view bindings. + pub fn context(&self) -> RuntimeContext { + RuntimeContext { + core: self.core.context(), + } + } +} + +/// Weak application capabilities and GPUI loading/action bindings. +#[derive(Clone)] +pub struct RuntimeContext { + core: rake_core::runtime::RuntimeContext, +} + +impl RuntimeContext { + /// Returns a client while the runtime is live. + pub fn client( + &self, + ) -> Result, crate::router::OperationError> { + self.core + .client() + .map(crate::control::RuntimeClient::from_core) + } + + pub(crate) fn from_navigator(navigator: Navigator, services: Services) -> Self { + Self { + core: rake_core::runtime::RuntimeContext::from_navigator( + navigator.into_core(), + services.into_core(), + ), + } + } + + /// Returns the configured standard and application service handles. + pub fn services(&self) -> Services { + Services::from_core(self.core.services()) + } + + /// Returns weak access to the native application tray host. + /// # Errors + /// Reports an unavailable GUI host or stopped runtime. + #[cfg(feature = "tray")] + pub fn trays(&self) -> Result { + self.client().map_err(|_| crate::tray::Error::Stopped)?; + #[cfg(target_family = "wasm")] + { + Err(crate::tray::Error::Unsupported( + crate::tray::Feature::MultipleItems, + )) + } + + #[cfg(not(target_family = "wasm"))] + { + self.services() + .get::() + .map(|c| c.as_ref().clone()) + .map_err(|_| crate::tray::Error::HostUnavailable) + } + } + + /// Binds an initiated user-action future to this view, with automatic redraw, + /// cancellation and finite-work quit tracking. Start gesture-sensitive browser + /// requests before calling this method. For reusable preparation, use `load`. + #[cfg(feature = "gpui")] + pub fn action( + &self, + cx: &mut gpui::Context, + future: Fut, + ) -> crate::loading::AsyncAction + where + E: std::error::Error + 'static, + Fut: std::future::Future> + 'static, + { + crate::loading::AsyncAction::new(Ok(self.tasks()), self.services(), future, cx) + } + + /// Observes the shared update controller and redraws this view automatically. + /// Dropping the handle/view stops observation, without stopping provider work. + /// Missing policy and action failures are represented in the returned handle. + #[cfg(all(feature = "gpui", feature = "updates"))] + pub fn bind_updates(&self, cx: &mut gpui::Context) -> crate::UpdateHandle { + crate::updates_binding::bind_updates(self.clone(), cx) + } + + #[cfg(all(feature = "gpui", feature = "updates"))] + pub(crate) async fn stopped(&self) { + self.core.stopped().await; + } + + /// Starts a view-owned asynchronous value and automatically redraws its view. + /// Work survives hidden views and is cancelled when the loader is dropped. + /// Admission and source failures are exposed by the returned handle. + #[cfg(feature = "gpui")] + pub fn load( + &self, + cx: &mut gpui::Context, + factory: F, + ) -> crate::loading::Loader + where + E: std::error::Error + 'static, + F: Fn(crate::loading::LoadContext) -> Fut + 'static, + Fut: std::future::Future> + 'static, + { + crate::loading::Loader::new(Ok(self.tasks()), self.services(), factory, cx) + } + + /// Reveals the application's registered repeatable standalone main window. + /// # Errors + /// Rejects a stopped runtime, missing factory, browser host or failed mount. + #[cfg(feature = "gpui")] + pub fn show_main_window(&self, cx: &mut gpui::App) -> Result<(), crate::AppError> { + self.client() + .map_err(|error| crate::AppError::Window(error.to_string()))?; + + crate::show_main_window(cx) + } +} + +impl Runtime { + /// Registers an application-wide guarded quit check. + pub fn quit_guard(&self, guard: F) -> Result<(), OperationError> + where + F: Fn(crate::quit::QuitGuardContext) -> Fut + 'static, + Fut: std::future::Future> + 'static, + { + self.core.quit_guard(guard) + } + + /// Requests the same guarded quit used by the managed application host. + pub fn quit(&self, options: QuitOptions) -> Operation { + self.core.quit(options) + } + + /// Returns the current guarded-quit lifecycle state. + pub fn quit_status(&self) -> QuitStatus { + self.core.quit_status() + } + + /// Stops admission and cancels all managed work. + pub fn shutdown(&self) { + self.core.shutdown() + } + + /// Drives this runtime until explicit shutdown or a committed guarded quit. + /// + /// A headless runtime has no native installer or host-exit authority. A + /// committed quit therefore shuts down this scheduler and returns; update + /// handoff/installation remains the responsibility of a managed host. + pub async fn run(&self) -> Result<(), OperationError> { + self.core.run().await + } + + #[cfg(feature = "updates")] + /// Returns the installed update controller, if application policy supplied one. + pub fn updates(&self) -> Option> { + self.core.updates() + } + + #[cfg(feature = "updates")] + /// Checks for an available update without downloading or restarting. + pub fn check_for_updates(&self) -> Result<(), rake_updates::Error> { + self.core.check_for_updates() + } + + #[cfg(feature = "updates")] + /// Starts the provider's verified update download. + pub fn download_update(&self) -> Result<(), rake_updates::Error> { + self.core.download_update() + } + + #[cfg(feature = "updates")] + /// Submits staged update restart through the guarded quit boundary. + pub fn restart_for_update( + &self, + options: QuitOptions, + ) -> Result, rake_updates::Error> { + self.core.restart_for_update(options) + } +} + +impl RuntimeContext { + /// Returns application-owned task capabilities retaining this origin. + pub fn app(&self) -> AppHandle { + self.core.app() + } + + /// Returns application-owned task capabilities retaining this origin. + pub fn tasks(&self) -> TaskScope { + self.core.tasks() + } + + /// Requests guarded application quit. Dropped/closed contexts return a + /// completed operation carrying `RuntimeShutdown`. + pub fn quit(&self, options: QuitOptions) -> Operation { + self.core.quit(options) + } + + /// Returns quit state while the runtime is alive. + pub fn quit_status(&self) -> Result { + self.core.quit_status() + } + + /// Rechecks a changed browser deployment and submits guarded application reload. + /// The runtime performs reload only after retained-entry/application guards and + /// finite-work policy approve. Cancellation/denial keeps the running app intact. + /// Observe this outside a finite managed task, so quit does not wait on itself. + /// The returned operation may be dropped without cancelling the reload. + /// + /// # Errors + /// Rejects native hosts, unchanged/unreachable deployments and stopped runtimes. + pub async fn reload_web_update( + &self, + deployment: &crate::web::Deployment, + options: QuitOptions, + ) -> Result, crate::web::Error> { + self.core.reload_web_update(deployment, options).await + } + + #[cfg(feature = "updates")] + /// Returns the installed update controller while the runtime is alive. + pub fn updates(&self) -> Result>, OperationError> { + self.core.updates() + } + + #[cfg(feature = "updates")] + /// Checks for an available update while the runtime is alive. + pub fn check_for_updates(&self) -> Result<(), rake_updates::Error> { + self.core.check_for_updates() + } + + #[cfg(feature = "updates")] + /// Starts the provider's verified update download while the runtime is alive. + pub fn download_update(&self) -> Result<(), rake_updates::Error> { + self.core.download_update() + } + + #[cfg(feature = "updates")] + /// Submits staged update restart through the guarded quit boundary. + pub fn restart_for_update( + &self, + options: QuitOptions, + ) -> Result, rake_updates::Error> { + self.core.restart_for_update(options) + } +} diff --git a/crates/rake-gpui/src/services.rs b/crates/rake-gpui/src/services.rs new file mode 100644 index 00000000..b506ae2c --- /dev/null +++ b/crates/rake-gpui/src/services.rs @@ -0,0 +1,130 @@ +//! Shared application services with a GPUI platform handle. + +use crate::{ + diagnostics::Collector, + http::{HttpClient, HttpConfig}, + platform::Platform, +}; + +pub use rake_core::services::ServiceError; +use std::rc::Rc; + +/// One application composition. Clones share service values and standard handles. +#[derive(Clone, Default)] +pub struct ServiceRegistry(rake_core::services::ServiceRegistry); + +impl ServiceRegistry { + /// Creates an empty composition. + pub fn new() -> Self { + Self::default() + } + + /// Adds one concrete service to this snapshot. + pub fn with(self, service: T) -> Result { + self.0.with(service).map(Self) + } + + /// Resolves the shared concrete value without copying it. + pub fn get(&self) -> Result, ServiceError> { + self.0.get() + } + + /// Returns the standard application HTTP handle, when present. + pub fn http(&self) -> Result { + self.0.http() + } + + /// Returns the standard application diagnostic collector, when present. + pub fn diagnostics(&self) -> Result { + self.0.diagnostics() + } + + /// Returns shared host services, if this registry came from [`Services`]. + pub fn platform(&self) -> Result { + self.0.platform().map(Platform::from_core) + } + + /// Reconstructs the standard service view represented by this registry. + pub fn standard_services(&self) -> Result { + self.0.standard_services().map(Services::from_core) + } + + pub(crate) fn from_core(core: rake_core::services::ServiceRegistry) -> Self { + Self(core) + } + + pub(crate) fn into_core(self) -> rake_core::services::ServiceRegistry { + self.0 + } +} + +/// Standard services and the application's typed composition. +#[derive(Clone)] +pub struct Services(rake_core::services::Services); + +impl Services { + /// Constructs standard service handles with an explicit application composition. + pub fn new(http: HttpClient, collector: Collector, registry: ServiceRegistry) -> Self { + Self::with_platform(http, collector, registry, Platform::default()) + } + + pub(crate) fn with_platform( + http: HttpClient, + collector: Collector, + registry: ServiceRegistry, + platform: Platform, + ) -> Self { + Self(rake_core::services::Services::with_platform( + http, + collector, + registry.into_core(), + platform.into_core(), + )) + } + + /// Builds the HTTP service and installs it with the supplied collector. + /// # Errors + /// Returns the HTTP configuration error when the client cannot be constructed. + pub fn from_config( + config: HttpConfig, + collector: Collector, + registry: ServiceRegistry, + ) -> Result { + let http = HttpClient::with_collector(config, collector.clone())?; + + Ok(Self::new(http, collector, registry)) + } + + /// Returns shared platform services bound to the GPUI host. + pub fn platform(&self) -> Platform { + Platform::from_core(self.0.platform()) + } + + pub(crate) fn from_core(services: rake_core::services::Services) -> Self { + Self(services) + } + + pub(crate) fn into_core(self) -> rake_core::services::Services { + self.0 + } + + /// Returns the shared configured HTTP transport handle. + pub fn http(&self) -> HttpClient { + self.0.http() + } + + /// Returns the bounded diagnostic collector. + pub fn diagnostics(&self) -> Collector { + self.0.diagnostics() + } + + /// Resolves the shared concrete service. + pub fn get(&self) -> Result, ServiceError> { + self.0.get() + } + + /// Captures this composition without changing shared value identities. + pub fn registry(&self) -> ServiceRegistry { + ServiceRegistry::from_core(self.0.registry()) + } +} diff --git a/crates/rake/src/surface.rs b/crates/rake-gpui/src/surface.rs similarity index 100% rename from crates/rake/src/surface.rs rename to crates/rake-gpui/src/surface.rs diff --git a/crates/rake/src/surface/macos.rs b/crates/rake-gpui/src/surface/macos.rs similarity index 100% rename from crates/rake/src/surface/macos.rs rename to crates/rake-gpui/src/surface/macos.rs diff --git a/crates/rake/src/surface/native.rs b/crates/rake-gpui/src/surface/native.rs similarity index 100% rename from crates/rake/src/surface/native.rs rename to crates/rake-gpui/src/surface/native.rs diff --git a/crates/rake/src/tasks/host.rs b/crates/rake-gpui/src/tasks/host.rs similarity index 100% rename from crates/rake/src/tasks/host.rs rename to crates/rake-gpui/src/tasks/host.rs diff --git a/crates/rake-gpui/src/tasks/mod.rs b/crates/rake-gpui/src/tasks/mod.rs new file mode 100644 index 00000000..f4f43bf9 --- /dev/null +++ b/crates/rake-gpui/src/tasks/mod.rs @@ -0,0 +1,17 @@ +//! Managed work and GPUI visibility observation. +pub use rake_core::tasks::*; + +pub(crate) mod host; + +/// Reports the managed host's window observation support. +pub fn visibility_support() -> VisibilitySupport { + if cfg!(target_os = "macos") { + VisibilitySupport::NativeOcclusion + } else if cfg!(target_os = "windows") { + VisibilitySupport::NativeWindowState + } else if cfg!(target_family = "wasm") { + VisibilitySupport::BrowserDocument + } else { + VisibilitySupport::Unknown + } +} diff --git a/crates/rake/src/tray.rs b/crates/rake-gpui/src/tray.rs similarity index 100% rename from crates/rake/src/tray.rs rename to crates/rake-gpui/src/tray.rs diff --git a/crates/rake/src/tray/popup.rs b/crates/rake-gpui/src/tray/popup.rs similarity index 100% rename from crates/rake/src/tray/popup.rs rename to crates/rake-gpui/src/tray/popup.rs diff --git a/crates/rake/src/updates_binding.rs b/crates/rake-gpui/src/updates_binding.rs similarity index 100% rename from crates/rake/src/updates_binding.rs rename to crates/rake-gpui/src/updates_binding.rs diff --git a/crates/rake/src/updates_binding_tests.rs b/crates/rake-gpui/src/updates_binding_tests.rs similarity index 99% rename from crates/rake/src/updates_binding_tests.rs rename to crates/rake-gpui/src/updates_binding_tests.rs index 19f13393..0ef903f4 100644 --- a/crates/rake/src/updates_binding_tests.rs +++ b/crates/rake-gpui/src/updates_binding_tests.rs @@ -12,7 +12,7 @@ use crate::diagnostics::Collector; use crate::gpui::{self, Context, Entity, Render, Task, WeakEntity, Window, prelude::*}; use crate::http::{HttpClient, HttpConfig}; use crate::prelude::Runtime; -use crate::router::runtime::{Mount, Resource}; +use crate::router::test_mount::{Mount, Resource}; use crate::router::{ MountError, NoRoute, OpenTarget, Page, PageContext, RouteOutlet, RouteViews, Router, RouterConfig, diff --git a/crates/rake-gpui/src/window_state.rs b/crates/rake-gpui/src/window_state.rs new file mode 100644 index 00000000..e0a19ea5 --- /dev/null +++ b/crates/rake-gpui/src/window_state.rs @@ -0,0 +1,8 @@ +//! Native window placement and GPUI observation. +pub use rake_core::window_state::WindowState; + +#[cfg(not(target_family = "wasm"))] +use rake_core::window_state::placement; + +#[cfg(not(target_family = "wasm"))] +pub(crate) mod native; diff --git a/crates/rake/src/window_state/native.rs b/crates/rake-gpui/src/window_state/native.rs similarity index 96% rename from crates/rake/src/window_state/native.rs rename to crates/rake-gpui/src/window_state/native.rs index 8fd50ec5..41f70806 100644 --- a/crates/rake/src/window_state/native.rs +++ b/crates/rake-gpui/src/window_state/native.rs @@ -148,12 +148,7 @@ impl Observer { decoration_height: self.decoration_height, }; - if self.policy.inner.records.borrow().get(&self.key) != Some(&record) { - self.policy - .inner - .records - .borrow_mut() - .insert(self.key.clone(), record); + if self.policy.update_record(&self.key, record) { self.signals.dirty.set(true); self.signals.changed.notify(usize::MAX); } @@ -275,7 +270,7 @@ pub(crate) fn prepare( cx: &gpui::App, ) -> Option { let driver = cx.try_global::()?; - let key = (driver.policy.keys)(id)?; + let key = driver.policy.key(id)?; if !placement::valid_key(&key) || driver @@ -288,9 +283,7 @@ pub(crate) fn prepare( return None; } - let records = driver.policy.inner.records.borrow(); - - let Some(saved) = records.get(&key) else { + let Some(saved) = driver.policy.record(&key) else { return Some(Prepared { key, mode: requested_mode(options), @@ -330,7 +323,7 @@ pub(crate) fn prepare( if let Some(default_bounds) = default_bounds && let Some((index, bounds)) = - placement::restore(saved, &snapshots, default_display, rect(default_bounds)) + placement::restore(&saved, &snapshots, default_display, rect(default_bounds)) { let bounds = bounds_to_gpui(bounds); diff --git a/crates/rake/src/window_state/native/tests.rs b/crates/rake-gpui/src/window_state/native/tests.rs similarity index 87% rename from crates/rake/src/window_state/native/tests.rs rename to crates/rake-gpui/src/window_state/native/tests.rs index 761551c2..714f7bd6 100644 --- a/crates/rake/src/window_state/native/tests.rs +++ b/crates/rake-gpui/src/window_state/native/tests.rs @@ -4,6 +4,7 @@ use super::*; use crate::platform::Preferences; +use rake_core::window_state::PREFERENCE_KEY; fn policy() -> (tempfile::TempDir, WindowState) { let directory = tempfile::tempdir().expect("isolated preferences directory"); @@ -43,9 +44,7 @@ fn open(app: &gpui::TestAppContext, id: WindowId) -> gpui::AnyWindowHandle { fn finish_writes(app: &gpui::TestAppContext, policy: &WindowState) { app.executor().allow_parking(); - app.foreground_executor().block_test(async { - let _write = policy.inner.writes.lock().await; - }); + app.foreground_executor().block_test(policy.writes_idle()); } #[test] @@ -80,11 +79,8 @@ fn stable_keys_are_independent_and_duplicate_live_keys_opt_out() { app.simulate_window_resize(main, gpui::size(gpui::px(700.), gpui::px(500.))); app.simulate_window_resize(editor, gpui::size(gpui::px(800.), gpui::px(600.))); app.simulate_window_resize(duplicate, gpui::size(gpui::px(900.), gpui::px(700.))); - let records = policy.inner.records.borrow(); - - assert_eq!(records["main"].bounds.width, 700.); - assert_eq!(records["editor"].bounds.width, 800.); - assert_eq!(records.len(), 2); + assert_eq!(policy.record("main").unwrap().bounds.width, 700.); + assert_eq!(policy.record("editor").unwrap().bounds.width, 800.); app.update(|cx| assert_eq!(cx.global::().windows.len(), 2)); } @@ -102,11 +98,11 @@ fn resize_burst_is_coalesced_until_interval_then_saves_latest_bounds() { app.executor() .advance_clock(SAVE_INTERVAL - Duration::from_millis(1)); app.run_until_parked(); - assert!(!directory.path().join(super::super::PREFERENCE_KEY).exists()); + assert!(!directory.path().join(PREFERENCE_KEY).exists()); app.executor().advance_clock(Duration::from_millis(1)); app.run_until_parked(); finish_writes(&app, &policy); - let data = std::fs::read_to_string(directory.path().join(super::super::PREFERENCE_KEY)) + let data = std::fs::read_to_string(directory.path().join(PREFERENCE_KEY)) .expect("coalesced write completed"); assert_eq!(placement::decode(&data)["main"].bounds.width, 750.); @@ -132,7 +128,7 @@ fn close_before_worker_starts_flushes_without_waiting_for_debounce_and_key_reope }); app.run_until_parked(); finish_writes(&app, &policy); - let data = std::fs::read_to_string(directory.path().join(super::super::PREFERENCE_KEY)) + let data = std::fs::read_to_string(directory.path().join(PREFERENCE_KEY)) .expect("final close write completed"); assert_eq!(placement::decode(&data)["main"].bounds.width, 750.); @@ -169,9 +165,7 @@ fn fullscreen_keeps_normal_bounds_and_quit_flushes_before_debounce() { app.simulate_window_resize(window, gpui::size(gpui::px(1920.), gpui::px(1080.))); // Hold the write serialization gate longer than GPUI's quit deadline, as a // slow in-flight fsync can. Quit must drain it and still save the final bounds. - let write = app - .foreground_executor() - .block_test(policy.inner.writes.clone().lock_owned()); + let write = app.foreground_executor().block_test(policy.lock_writes()); let slow_write = std::thread::spawn(move || { let _write = write; @@ -183,7 +177,7 @@ fn fullscreen_keeps_normal_bounds_and_quit_flushes_before_debounce() { slow_write .join() .expect("slow write completed before quit returned"); - let data = std::fs::read_to_string(directory.path().join(super::super::PREFERENCE_KEY)) + let data = std::fs::read_to_string(directory.path().join(PREFERENCE_KEY)) .expect("quit awaits final preference write"); let records = placement::decode(&data); @@ -201,17 +195,15 @@ fn quit_returns_when_a_write_remains_locked_past_the_grace_period() { app.executor().set_block_on_ticks(usize::MAX..=usize::MAX); app.update(|cx| install(policy.clone(), cx)); open(&app, WindowId(1)); - let write = app - .foreground_executor() - .block_test(policy.inner.writes.clone().lock_owned()); + let write = app.foreground_executor().block_test(policy.lock_writes()); let started = std::time::Instant::now(); app.quit(); assert!(started.elapsed() >= QUIT_SAVE_TIMEOUT); - assert!(!directory.path().join(super::super::PREFERENCE_KEY).exists()); + assert!(!directory.path().join(PREFERENCE_KEY).exists()); assert!( - policy.inner.writes.try_lock().is_none(), + futures::FutureExt::now_or_never(policy.lock_writes()).is_none(), "quit returned while the write stayed locked" ); drop(write); @@ -234,8 +226,8 @@ fn reset_serializes_with_queued_saves_and_preserves_other_windows() { app.executor().advance_clock(SAVE_INTERVAL); app.run_until_parked(); finish_writes(&app, &policy); - let data = std::fs::read_to_string(directory.path().join(super::super::PREFERENCE_KEY)) - .expect("preferences exist"); + let data = + std::fs::read_to_string(directory.path().join(PREFERENCE_KEY)).expect("preferences exist"); let records = placement::decode(&data); @@ -244,7 +236,8 @@ fn reset_serializes_with_queued_saves_and_preserves_other_windows() { let fresh = WindowState::new(Preferences::at(directory.path())); fresh.load(); - assert_eq!(*fresh.inner.records.borrow(), records); + assert!(fresh.record("main").is_none()); + assert_eq!(fresh.record("editor").as_ref(), records.get("editor")); } #[test] @@ -264,8 +257,8 @@ fn all_modes_restore_the_same_normal_bounds() { }; for mode in [Mode::Windowed, Mode::Maximized, Mode::Fullscreen] { - policy.inner.records.borrow_mut().insert( - "main".into(), + policy.update_record( + "main", SavedWindow { bounds, display: display.uuid().ok().map(|uuid| uuid.to_string()), @@ -297,7 +290,7 @@ fn invalid_keys_opt_out_without_creating_preference_records() { app.update(|cx| install(policy.clone(), cx)); open(&app, WindowId(1)); - assert!(policy.inner.records.borrow().is_empty()); + assert!(policy.record("").is_none()); app.update(|cx| assert!(cx.global::().windows.is_empty())); } @@ -313,7 +306,7 @@ fn changed_scale_preserves_logical_bounds_and_stable_key_restores_with_new_runti app.simulate_window_resize(editor, gpui::size(gpui::px(750.), gpui::px(550.))); app.simulate_window_scale_factor_change(editor, 2.); - assert_eq!(policy.inner.records.borrow()["editor"].bounds.width, 750.); + assert_eq!(policy.record("editor").unwrap().bounds.width, 750.); app.update(|cx| { editor .update(cx, |_, window, cx| { @@ -380,12 +373,12 @@ fn startup_zoom_frames_keep_restore_bounds_and_rejected_modes_eventually_follow_ // TestPlatform does not implement zoom; these mimic windowed animation frames. app.simulate_window_resize(window, gpui::size(gpui::px(1000.), gpui::px(700.))); app.simulate_window_resize(window, gpui::size(gpui::px(1500.), gpui::px(900.))); - assert_eq!(policy.inner.records.borrow()["main"].bounds, bounds); - assert_eq!(policy.inner.records.borrow()["main"].mode, Mode::Maximized); + assert_eq!(policy.record("main").unwrap().bounds, bounds); + assert_eq!(policy.record("main").unwrap().mode, Mode::Maximized); app.run_until_parked(); app.executor().advance_clock(Duration::from_secs(2)); app.run_until_parked(); - assert_eq!(policy.inner.records.borrow()["main"].mode, Mode::Windowed); - assert_eq!(policy.inner.records.borrow()["main"].bounds.width, 1500.); + assert_eq!(policy.record("main").unwrap().mode, Mode::Windowed); + assert_eq!(policy.record("main").unwrap().bounds.width, 1500.); } diff --git a/crates/rake/tests/icon_cache.rs b/crates/rake-gpui/tests/icon_cache.rs similarity index 100% rename from crates/rake/tests/icon_cache.rs rename to crates/rake-gpui/tests/icon_cache.rs diff --git a/crates/rake/view-macro.md b/crates/rake-gpui/view-macro.md similarity index 94% rename from crates/rake/view-macro.md rename to crates/rake-gpui/view-macro.md index 938003b2..c0d840aa 100644 --- a/crates/rake/view-macro.md +++ b/crates/rake-gpui/view-macro.md @@ -3,6 +3,7 @@ With `devtools`, nodes expose bounded inspection and authored style sources. Without it, inspection wrappers and source descriptors are removed at expansion. ``` +# use rake_gpui as rake; let rows = ["One", "Two"]; let _view = rake::view! {
@@ -21,6 +22,7 @@ let _view = rake::view! { Classes support explicit units, interaction variants and literal branches: ``` +# use rake_gpui as rake; let selected = true; let _ = rake::view! {

}; ``` diff --git a/crates/rake-macros/src/lib.rs b/crates/rake-macros/src/lib.rs index 357a7089..479cfaad 100644 --- a/crates/rake-macros/src/lib.rs +++ b/crates/rake-macros/src/lib.rs @@ -139,10 +139,22 @@ pub fn command(input: TokenStream) -> TokenStream { } fn facade() -> syn::Result { - match crate_name("rake-app").or_else(|_| crate_name("rak")) { + let (package, found) = ["rake-app", "rak", "rake-gpui", "rake-core"] + .into_iter() + .find_map(|package| crate_name(package).ok().map(|found| (package, found))) + .ok_or_else(|| { + syn::Error::new( + proc_macro2::Span::call_site(), + "a rake-app, rake-gpui or rake-core dependency is required", + ) + })?; + + match (package, found) { // Without a dependency rename, Cargo uses the facade library target name. - Ok(FoundCrate::Itself) => Ok(quote!(::rake)), - Ok(FoundCrate::Name(name)) => { + ("rake-core", FoundCrate::Itself) => Ok(quote!(::rake_core)), + ("rake-gpui", FoundCrate::Itself) => Ok(quote!(::rake_gpui)), + (_, FoundCrate::Itself) => Ok(quote!(::rake)), + (_, FoundCrate::Name(name)) => { let name = match name.as_str() { "rake_app" | "rak" => "rake", _ => &name, @@ -152,7 +164,6 @@ fn facade() -> syn::Result { Ok(quote!(::#name)) } - Err(error) => Err(syn::Error::new(proc_macro2::Span::call_site(), error)), } } diff --git a/crates/rake-native/tests/appkit.rs b/crates/rake-native/tests/appkit.rs index f5de72bf..5211cc9d 100644 --- a/crates/rake-native/tests/appkit.rs +++ b/crates/rake-native/tests/appkit.rs @@ -522,19 +522,20 @@ mod suite { } let native_window = button.as_appkit().window().unwrap(); + let content = native_window.contentView().unwrap(); assert!(!has_toolbar(&native_window)); - // SAFETY: NSToolbar and its standard print item are created - // on the main thread; NSWindow retains the installed toolbar. + // SAFETY: The window retains the installed toolbar and its live + // content hierarchy. All AppKit operations run on the main thread. unsafe { let toolbar: Retained = msg_send![AnyClass::get(c"NSToolbar").unwrap(), new]; - let _: () = msg_send![&*toolbar, insertItemWithItemIdentifier: &*NSString::from_str("NSToolbarPrintItem"), atIndex: 0_isize]; let _: () = msg_send![&*native_window, setToolbar: &*toolbar]; + let _: () = msg_send![&*toolbar, insertItemWithItemIdentifier: &*NSString::from_str("NSToolbarPrintItem"), atIndex: 0_isize]; + content.superview().unwrap().layoutSubtreeIfNeeded(); } assert!(has_toolbar(&native_window), "a toolbar added after mounting is immediately discoverable"); let children = native_window.accessibilityChildren().unwrap(); - let content = native_window.contentView().unwrap(); for expected in [&*content, &*group] { assert!( diff --git a/crates/rake/Cargo.toml b/crates/rake/Cargo.toml index 3ae2e851..cc13bc36 100644 --- a/crates/rake/Cargo.toml +++ b/crates/rake/Cargo.toml @@ -17,119 +17,62 @@ workspace = true [features] default = ["gpui"] -launch-at-login = ["dep:rake-autostart"] -tray = ["gpui", "dep:rake-tray", "global-shortcuts"] -global-shortcuts = ["gpui", "dep:rake-shortcuts"] -gpu-surface = ["gpui-fast", "dep:metal", "dep:foreign-types", "dep:objc2", "dep:objc2-foundation", "dep:objc2-quartz-core", "objc2-app-kit?/objc2-quartz-core", "dep:windows"] -gpui-fast = ["gpui", "dep:gpui_fast_apple", "dep:gpui_fast", "dep:gpui_fast_platform", "rake-ui/gpui-fast", "rake-native?/gpui-fast"] -live = ["gpui", "dep:blaze-live", "dep:pathfinder_simd"] -native-components = ["gpui", "dep:rake-native"] -native-lifecycle = ["dep:rake-updates", "rake-updates/native-lifecycle"] -updates = ["native-lifecycle"] -updates-sparkle = ["updates", "rake-updates/sparkle"] -updates-appimage = ["updates", "rake-updates/appimage"] -updates-velopack = ["updates", "rake-updates/velopack"] -devtools = ["gpui_pre?/profiler", "gpui_fast?/profiler", "rake-diagnostics/devtools", "rake-http/devtools", "objc2-app-kit?/objc2-quartz-core", "dep:windows"] -devtools-memory = ["devtools", "dep:backtrace"] -kit = ["gpui", "rake-ui/kit"] -locale = ["gpui", "dep:fluent-bundle", "dep:icu_locale_core", "dep:sys-locale"] -locale-icu = ["locale", "dep:fixed_decimal", "dep:icu_calendar", "dep:icu_datetime", "dep:icu_decimal", "dep:icu_plurals", "dep:icu_provider", "dep:icu_provider_blob", "dep:writeable"] +gpui = ["dep:rake-gpui", "dep:gpui_platform", "native-lifecycle"] +launch-at-login = ["rake-core/launch-at-login", "rake-gpui?/launch-at-login"] +tray = ["gpui", "rake-gpui/tray", "global-shortcuts"] +global-shortcuts = ["gpui", "rake-gpui/global-shortcuts"] +gpu-surface = ["gpui-fast", "rake-gpui/gpu-surface"] +gpui-fast = ["gpui", "dep:gpui_fast_platform", "rake-gpui/gpui-fast"] +live = ["gpui", "rake-gpui/live"] +native-components = ["gpui", "rake-gpui/native-components"] +native-lifecycle = ["rake-gpui?/native-lifecycle"] +updates = ["native-lifecycle", "rake-core/updates", "rake-gpui?/updates"] +updates-sparkle = ["updates", "rake-core/updates-sparkle", "rake-gpui?/updates-sparkle"] +updates-appimage = ["updates", "rake-core/updates-appimage", "rake-gpui?/updates-appimage"] +updates-velopack = ["updates", "rake-core/updates-velopack", "rake-gpui?/updates-velopack"] +devtools = ["rake-core/devtools", "rake-gpui?/devtools"] +devtools-memory = ["devtools", "rake-core/devtools-memory", "rake-gpui?/devtools-memory"] +kit = ["gpui", "rake-gpui/kit"] # Deprecated compatibility alias; UI is provided by gpui (enabled by default). experimental-view = [] -experimental-reactive = ["gpui", "rake-macros/reactive", "dep:slotmap"] -view-test-support = ["gpui", "gpui_pre/test-support", "gpui_fast?/test-support", "rake-ui/test-support", "gpui_platform/runtime_shaders", "gpui_fast_platform?/runtime_shaders"] -gpui = ["dep:gpui_pre_apple", "dep:windows", "dep:oo7", "dep:zbus", "dep:rake-ui", "rake-macros/view", "dep:gpui_pre", "dep:gpui_platform", "dep:objc2-app-kit", "dep:objc2", "dep:objc2-foundation", "dep:block2", "dep:objc2-user-notifications", "dep:raw-window-handle", "dep:windows-sys", "native-lifecycle"] +experimental-reactive = ["gpui", "rake-gpui/experimental-reactive"] +locale = ["gpui", "rake-gpui/locale"] +locale-icu = ["locale", "rake-gpui/locale-icu"] +view-test-support = ["gpui", "rake-gpui/view-test-support", "dep:rake-ui"] [dependencies] -fluent-bundle = { version = "0.16", optional = true } -icu_locale_core = { version = "2.4", optional = true } -fixed_decimal = { version = "0.7", optional = true } -icu_calendar = { version = "2.4", default-features = false, optional = true } -icu_datetime = { version = "2.4", default-features = false, features = ["serde"], optional = true } -icu_decimal = { version = "2.4", default-features = false, features = ["serde"], optional = true } -icu_plurals = { version = "2.4", default-features = false, features = ["serde"], optional = true } -icu_provider = { version = "2.4", features = ["sync"], optional = true } -icu_provider_blob = { version = "2.4", optional = true } -writeable = { version = "0.6", optional = true } -zeroize = "1" -rake-shortcuts = { version = "=0.1.0-alpha.7", path = "../rake-shortcuts", optional = true } -image = { version = "0.25.10", default-features = false, features = ["png"] } -rake-autostart = { version = "=0.1.0-alpha.7", path = "../rake-autostart", optional = true } -rake-tray = { version = "=0.1.0-alpha.7", path = "../rake-tray", optional = true } -rake-updates = { version = "=0.1.0-alpha.7", path = "../rake-updates", optional = true } -rake-resources = { version = "=0.1.0-alpha.7", path = "../rake-resources" } +# The secrets probe and component benchmark open a host directly. +gpui_platform = { workspace = true, optional = true } +gpui_fast_platform = { workspace = true, optional = true } +rake-core.workspace = true +rake-gpui = { workspace = true, optional = true } rake-ui = { workspace = true, optional = true } -rake-native = { workspace = true, optional = true } -rake-http = { workspace = true, features = ["task-errors"] } -rake-protocol.workspace = true rake-macros = { version = "=0.1.0-alpha.7", path = "../rake-macros" } + +[dev-dependencies] +rake-protocol.workspace = true rake-diagnostics.workspace = true serde.workspace = true serde_json.workspace = true -schemars = "1.2.3" -slotmap = { version = "1.1", optional = true } +thiserror.workspace = true tracing.workspace = true futures.workspace = true -thiserror.workspace = true -url = "2.5" -uuid = { version = "1", features = ["v4", "serde", "js"] } -event-listener = "5.4" -web-time.workspace = true -gpui_pre = { package = "gpui-pre", version = "=0.3.11", default-features = false, optional = true } -gpui_platform = { workspace = true, features = ["font-kit", "wayland", "x11"], optional = true } -gpui_fast = { workspace = true, optional = true } -gpui_fast_platform = { workspace = true, features = ["font-kit", "wayland", "x11"], optional = true } - -[target.'cfg(any(unix, windows))'.dependencies] -rake-client.workspace = true - -[target.'cfg(target_os = "linux")'.dependencies] -oo7 = { version = "0.6", default-features = false, features = ["async-std", "native_crypto"], optional = true } -zbus = { version = "5", default-features = false, features = ["async-io"], optional = true } +tracing-subscriber.workspace = true +trybuild = "1" -[target.'cfg(unix)'.dependencies] -backtrace = { version = "0.3.76", optional = true } +rake-http = { workspace = true, features = ["task-errors"] } +uuid = { version = "1", features = ["v4", "serde", "js"] } -[target.'cfg(not(target_family = "wasm"))'.dependencies] -blaze-live = { package = "rake-blaze-live", version = "=0.1.0-alpha.7", path = "../../vendor/blaze-live", optional = true } -sys-locale = { version = "0.3", optional = true } -anyhow = "1" +[target.'cfg(not(target_family = "wasm"))'.dev-dependencies] libc = "0.2" async-io = "2.6" -blocking = "1.7" tempfile = "3" -raw-window-handle = { version = "0.6", optional = true } -[target.'cfg(target_family = "wasm")'.dependencies] -wasm-bindgen = "0.2" -wasm-bindgen-futures = "0.4" -js-sys = "0.3" -console_error_panic_hook = "0.1" -web-sys = { version = "0.3", features = ["console", "Window", "History", "Location", "Navigator", "Event", "BeforeUnloadEvent", "EventTarget", "Document", "Element", "HtmlElement", "Node", "Storage", "ClipboardEvent", "DataTransfer"] } - -[target.'cfg(target_os = "macos")'.dependencies] -gpui_fast_apple = { package = "gpui-fast-apple", version = "=0.1.13", optional = true } -gpui_pre_apple = { package = "gpui-pre-apple", version = "=0.3.11", optional = true } -block2 = { version = "0.6", optional = true } -objc2-user-notifications = { version = "0.3.2", default-features = false, features = ["std", "block2", "UNUserNotificationCenter", "UNNotificationSettings"], optional = true } - -metal = { version = "0.33", optional = true } -foreign-types = { version = "0.5", optional = true } -objc2 = { version = "0.6.5", optional = true } -objc2-foundation = { version = "0.3.2", features = ["NSGeometry", "NSBundle", "NSError"], optional = true } -objc2-quartz-core = { version = "0.3.2", features = ["CALayer"], optional = true } -pathfinder_simd = { version = "0.5.6", features = ["pf-no-simd"], optional = true } -objc2-app-kit = { version = "0.3", default-features = false, features = ["NSView", "NSWindow", "NSResponder", "NSWorkspace", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSGraphicsContext", "NSGraphics", "objc2-core-foundation"], optional = true } - -[target.'cfg(target_os = "windows")'.dependencies] -windows = { version = "0.62", features = ["Win32_Graphics_DirectComposition"], optional = true } -windows-sys = { version = "0.61", features = ["Win32_UI_WindowsAndMessaging", "Win32_Graphics_Dwm", "Win32_Storage_FileSystem", "Win32_UI_Shell", "Win32_Graphics_Gdi", "Win32_System_Com"], optional = true } +[target.'cfg(any(unix, windows))'.dev-dependencies] +rake-client.workspace = true -[dev-dependencies] -rake-tray = { version = "=0.1.0-alpha.7", path = "../rake-tray", features = ["test-support"] } -futures.workspace = true -tracing-subscriber.workspace = true -trybuild = "1" +[target.'cfg(target_family = "wasm")'.dev-dependencies] +wasm-bindgen = "0.2" [[test]] name = "view_state" @@ -139,24 +82,11 @@ required-features = ["view-test-support"] name = "control_queries" harness = false -[[test]] -name = "function_components" -required-features = ["experimental-reactive", "view-test-support"] - -[[bench]] -name = "function_components" -harness = false -required-features = ["experimental-reactive", "view-test-support"] - [[example]] name = "startup-failure" path = "examples/startup_failure.rs" required-features = ["gpui"] -[[example]] -name = "components" -required-features = ["experimental-reactive"] - [[example]] name = "native" required-features = ["native-components"] @@ -171,6 +101,22 @@ path = "examples/web_crash.rs" crate-type = ["cdylib"] required-features = ["gpui"] +[[test]] +name = "function_components" +required-features = ["experimental-reactive", "view-test-support"] + + +[[bench]] +name = "function_components" +harness = false +required-features = ["experimental-reactive", "view-test-support"] + + +[[example]] +name = "components" +required-features = ["experimental-reactive"] + + [[example]] name = "web-locale" path = "examples/web_locale.rs" diff --git a/crates/rake/src/inspection/disabled.rs b/crates/rake/src/inspection/disabled.rs deleted file mode 100644 index ba7eff8d..00000000 --- a/crates/rake/src/inspection/disabled.rs +++ /dev/null @@ -1,204 +0,0 @@ -//! Inspection contracts without capture, editing, recording or retained state. -//! -//! Enable `rake/devtools` to compile instrumentation. Manual identity builders -//! return their input unchanged; use `inspect_with` for lazily constructed names. - -pub use rake_protocol::inspection::*; - -#[derive(Clone, Default)] -pub(crate) struct Store {} - -impl Store { - pub(crate) fn window_page( - &self, - _: crate::router::WindowId, - _: Option<&str>, - _: usize, - ) -> Result { - Err(InspectionError::Unavailable) - } - - pub(crate) fn preview_enabled(&self) -> bool { - false - } - - pub(crate) fn preview_windows(&self) -> Vec { - Vec::new() - } - - pub(crate) fn preview_element(&self, _: &preview::Point) -> Result { - Err(InspectionError::Unavailable) - } - - pub(crate) fn preview_input( - &self, - _: &preview::Point, - _: &preview::Input, - ) -> Result<(), InspectionError> { - Err(InspectionError::Unavailable) - } - - pub(crate) fn edit_text(&self, _: &str, _: &str, _: &TextEdit) -> Result<(), InspectionError> { - Err(InspectionError::Unavailable) - } - - pub(crate) fn status(&self) -> Status { - Status::Unavailable - } - - pub(crate) fn snapshot(&self) -> Snapshot { - Snapshot { - status: Status::Unavailable, - capture: "0".into(), - router_revision: 0, - locale: None, - elements: Vec::new(), - omitted: 0, - coverage: "Inspection was compiled out; enable rake/devtools".into(), - } - } - - pub(crate) fn tree_page(&self, _: Option<&str>, _: usize) -> Result { - Err(InspectionError::Unavailable) - } - - pub(crate) fn tree_revision(&self) -> TreeRevision { - TreeRevision { - metadata: None, - capture: "0".into(), - status: Status::Unavailable, - } - } - - pub(crate) fn element(&self, _: &str) -> Result { - Err(InspectionError::Unavailable) - } - - pub(crate) fn pick(&self) -> Result { - Err(InspectionError::Unavailable) - } - - pub(crate) fn highlight(&self, _: Option<&str>, _: &str) -> Result<(), InspectionError> { - Err(InspectionError::Unavailable) - } - - pub(crate) fn inspect_mode(&self, _: bool, _: u64) -> Result<(), InspectionError> { - Err(InspectionError::Unavailable) - } - - pub(crate) fn navigate( - &self, - _: &str, - _: &str, - _: NavigationAction, - ) -> Result<(), InspectionError> { - Err(InspectionError::Unavailable) - } - - pub(crate) fn edit_style( - &self, - _: &str, - _: &str, - _: &StyleEdit, - ) -> Result<(), InspectionError> { - Err(InspectionError::Unavailable) - } - - pub(crate) fn record_frames(&self, _: bool, _: u64) -> Result<(), InspectionError> { - Err(InspectionError::RecordingUnavailable) - } - - pub(crate) fn frames(&self, _: u64, _: &rake_diagnostics::Collector) -> Frames { - Frames { - clock: None, - recording: false, - frames: Vec::new(), - cursor: 0, - more: false, - dropped: 0, - gap: false, - } - } -} - -#[cfg(feature = "gpui")] -mod view { - use gpui::IntoElement; - - /// The original element type when inspection is compiled out. - pub type Inspected = E; - - /// Returns the original value without converting or wrapping it. - #[inline(always)] - pub fn inspect(element: E) -> E { - element - } - - /// Identity builders when inspection is compiled out. No metadata is retained. - /// Arguments to ordinary methods still follow Rust's evaluation rules; use - /// `inspect_with` to avoid constructing a dynamic name in production. - pub trait InspectElement: IntoElement { - /// Returns the original value, discarding the supplied identity. - #[inline(always)] - fn inspect(self, _: impl Into) -> Self { - self - } - - /// Returns the original value without invoking the name builder. - #[inline(always)] - fn inspect_with(self, _: impl FnOnce() -> String) -> Self { - self - } - - /// Returns the original value without retaining handler metadata. - #[inline(always)] - fn inspect_handler(self, _: impl Into) -> Self { - self - } - - /// Returns the original value without retaining an identity. - #[inline(always)] - fn semantic_id(self, _: impl Into) -> Self { - self - } - - /// Returns the original value without cloning the focus handle. - #[inline(always)] - fn focus_handle(self, _: &gpui::FocusHandle) -> Self { - self - } - - /// Returns the original value without cloning the scroll handle. - #[inline(always)] - fn scroll_handle(self, _: &gpui::ScrollHandle) -> Self { - self - } - } - - impl InspectElement for T {} - - pub(crate) trait InspectRoot: IntoElement { - #[inline(always)] - fn root(self, _: super::Store, _: u64, _: crate::router::WindowId) -> Self { - self - } - } - - impl InspectRoot for T {} -} - -#[cfg(feature = "gpui")] -pub(crate) use view::InspectRoot; -#[cfg(feature = "gpui")] -pub use view::{InspectElement, Inspected, inspect}; - -#[cfg(test)] -mod tests { - #[test] - fn disabled_store_has_no_retained_state() { - assert_eq!(std::mem::size_of::(), 0); - assert_eq!(super::Store::default().status(), super::Status::Unavailable); - #[cfg(feature = "gpui")] - assert!(!crate::control::ControlConfig::FromEnvironment.inspection_enabled()); - } -} diff --git a/crates/rake/src/lib.rs b/crates/rake/src/lib.rs index 848eebf6..994a8619 100644 --- a/crates/rake/src/lib.rs +++ b/crates/rake/src/lib.rs @@ -1,50 +1,43 @@ -//! Rake's portable application foundation. -//! -//! Default builds include the pinned GPUI native/browser adapters. Disable default -//! features for HTTP, data and diagnostics consumers that do not need a UI. -//! Inspection and temporary style editing require the opt-in `devtools` feature; -//! ordinary native and WASM builds omit their instrumentation and retained state. +//! Rake application framework. Default builds include the GPUI integration. -extern crate self as rake; - -/// Optional, GPUI-independent per-user launch-at-login settings. -#[cfg(feature = "launch-at-login")] -pub use rake_autostart as login_item; - -#[path = "inspection/macros.rs"] -mod inspection_macros; - -pub use rake_resources as resources; -pub use rake_resources::{Resources, resources}; +#[cfg(not(feature = "gpui"))] +pub use rake_core::*; +#[cfg(feature = "gpui")] +pub use rake_gpui::*; +#[cfg(not(feature = "gpui"))] +pub use rake_macros::app; -/// Optional native components; currently exposes the macOS AppKit adapter. -#[cfg(feature = "native-components")] -pub use rake_native as native; +#[cfg(all(not(feature = "gpui"), not(feature = "devtools")))] +#[doc(hidden)] +pub use rake_core::__rake_inspection_disabled as __rake_inspection; +#[cfg(all(not(feature = "gpui"), feature = "devtools"))] +#[doc(hidden)] +pub use rake_core::__rake_inspection_enabled as __rake_inspection; -#[cfg(feature = "updates")] -pub use rake_updates as updates; -#[cfg(feature = "updates")] -pub use rake_updates::updates; +#[cfg(not(feature = "gpui"))] +#[doc(hidden)] +pub mod __private { + pub use crate::__rake_inspection as inspection; + pub use rake_core::__private::*; +} -/// Runs enabled native updater installer callbacks before constructing the app. -/// Manual entry points use `early_startup!()`; `#[rake::app]` does so automatically. -/// # Panics -/// Panics if a hand-written embedded policy is invalid; rake-build validates generated policy. +#[cfg(not(feature = "gpui"))] +/// Runs enabled native installer callbacks before constructing the runtime. pub fn early_startup_for(embedded: Option<&str>) { early_startup_with_desktop(embedded, None); } -/// Runs installer startup with common desktop metadata captured by [`early_startup!`]. -/// # Panics -/// Panics if hand-written embedded metadata is invalid; rake-build validates generated metadata. +#[cfg(not(feature = "gpui"))] +/// Runs installer startup with embedded desktop metadata. pub fn early_startup_with_desktop(embedded: Option<&str>, desktop: Option<&str>) { #[cfg(all(feature = "updates", not(target_family = "wasm")))] - rake_updates::early_startup_with_desktop(embedded, desktop) + rake_core::updates::early_startup_with_desktop(embedded, desktop) .expect("generated Rake distribution policy must be valid"); #[cfg(any(not(feature = "updates"), target_family = "wasm"))] let _ = (embedded, desktop); } +#[cfg(not(feature = "gpui"))] /// Initializes installer callbacks using policy embedded into the application crate. #[macro_export] macro_rules! early_startup { @@ -55,228 +48,3 @@ macro_rules! early_startup { ) }; } - -pub mod control; - -pub use rake_macros::Props; - -#[doc = "Experimental signals backed by typed GPUI entities."] -#[cfg(feature = "experimental-reactive")] -pub mod reactive; - -#[cfg(feature = "experimental-reactive")] -pub use rake_macros::component; - -pub mod crash; -#[cfg(feature = "locale")] -pub mod locale; -pub mod logging; - -#[cfg(all(feature = "devtools-memory", unix))] -pub mod memory; - -pub use rake_diagnostics as diagnostics; - -pub use rake_http as http; - -#[cfg(feature = "devtools")] -pub mod inspection; -#[cfg(not(feature = "devtools"))] -#[path = "inspection/disabled.rs"] -pub mod inspection; -pub mod loading; -#[cfg(feature = "gpui")] -pub mod menus; -pub mod platform; -pub mod quit; -pub mod reload; -pub mod router; -pub mod runtime; -pub mod services; -pub mod storage; -#[cfg(all( - feature = "gpu-surface", - any(target_os = "macos", target_os = "linux", target_os = "windows") -))] -pub mod surface; -pub mod tasks; -#[cfg(feature = "tray")] -pub mod tray; -pub mod web; -pub mod window_state; - -#[cfg(all(feature = "gpui", feature = "updates"))] -mod updates_binding; - -#[cfg(all(feature = "gpui", feature = "updates"))] -pub use updates_binding::{UpdateHandle, UpdateHandleState}; - -#[cfg(feature = "gpui")] -mod application; - -#[cfg(feature = "gpui")] -use rake_ui::view; - -#[cfg(feature = "gpui")] -pub mod overlay; - -#[cfg(feature = "gpui")] -pub use rake_ui::theme; - -/// Text input components for GPUI views. -#[cfg(feature = "gpui")] -pub mod ui { - pub use rake_ui::input; -} - -/// Initializes Base, optional Kit and theme observation before custom GPUI windows. -/// Rake's application builder calls this automatically. -#[cfg(feature = "gpui")] -pub use rake_ui::init as init_ui; - -/// Optional GPUI Kit components, assets and the matching GPUI API (native targets). -#[cfg(all(feature = "kit", not(target_family = "wasm")))] -pub use rake_ui::kit; - -#[cfg(feature = "gpui")] -pub use application::{App, AppError, ClosePolicy, show_main_window}; -#[cfg(feature = "gpui-fast")] -pub extern crate gpui_fast as gpui; -#[cfg(feature = "gpui-fast")] -extern crate gpui_fast_platform as gpui_platform; -#[cfg(all(feature = "gpui", not(feature = "gpui-fast")))] -pub extern crate gpui_pre as gpui; -pub use rake_macros::{Command, Route, app, data, instrument}; -#[cfg(feature = "gpui")] -#[doc = include_str!("../view-macro.md")] -pub use rake_macros::{Theme, style, view}; -pub use router::Route; -pub use schemars; -pub use serde; -pub use serde_json; -pub use services::{ServiceError, ServiceRegistry, Services}; -pub use tracing::{debug, error, info, trace, warn}; - -/// Common application and service imports. -pub mod prelude { - pub use crate::control::{ - ApplicationCommand, CommandContext, CommandDescriptor, CommandError, Commands, - ControlConfig, ExecutionCapability, RuntimeClient, - }; - - #[cfg(feature = "experimental-reactive")] - pub use crate::reactive::{ - Children, Memo, ReactiveApp, Resource, Setup, Signal, SignalContext, - }; - - #[cfg(all(feature = "gpui", feature = "updates"))] - pub use crate::{UpdateHandle, UpdateHandleState}; - - pub use crate::diagnostics::{Collector, DiagnosticsConfig, SubscriberMode}; - pub use crate::http::{CancellationToken, HttpClient, HttpConfig}; - #[cfg(feature = "gpui")] - pub use crate::loading::{AsyncAction, LoadContext, LoadError, Loader}; - pub use crate::loading::{LoadState, LoadStatus, LoadToken}; - - pub use crate::quit::{ - QuitGuardContext, QuitJobs, QuitOptions, QuitPhase, QuitResult, QuitStatus, - }; - - pub use crate::reload::{Checkpoint, ReloadError, ReloadState}; - pub use crate::runtime::{Runtime, RuntimeContext}; - pub use crate::services::{ServiceError, ServiceRegistry, Services}; - pub use crate::tasks::{ActivityRun, AppHandle, TaskError, TaskHandle, TaskScope}; - - pub use crate::router::{ - Activation, Admission, AdmissionContext, DecisionChoice, DecisionRequest, EntryHandle, - GuardResult, Navigator, OpenOptions, OpenTarget, Outcome, RevealScope, Route, Router, - RouterConfig, TabMode, WebConfig, WebRouting, - }; - - #[cfg(feature = "gpui")] - pub use crate::App; - #[cfg(feature = "gpui")] - pub use crate::inspection::InspectElement; - - #[cfg(feature = "gpui")] - pub use crate::router::{ - LayoutContext, LoadedPage, NavigationBoundary, Page, PageContext, RouteOutlet, RouteViews, - TabBar, - }; - - pub use rake_macros::{Command, Route}; -} - -#[doc(hidden)] -pub mod __private { - pub use crate::__rake_inspection as inspection; - #[cfg(feature = "gpui")] - pub use crate::application::{AppFactoryOutput, run_app_factory}; - - #[cfg(feature = "gpui")] - pub use rake_ui::__private::{ - EquivalentProp, IntoAttribute, ParagraphTextValue, PropComparison, PropMissing, PropSet, - PropsBuilder, RequiredProp, Value, - }; - - #[cfg(all(feature = "gpui", feature = "devtools"))] - pub use crate::inspection::authored::{ - Definition as ViewDefinition, HandlerSite as ViewHandlerSite, StyleSite as ViewStyleSite, - child as view_inspect_child, component as view_inspect_component, - component_key as view_component_key, styled as view_inspect, - }; - - #[cfg(feature = "gpui")] - pub use crate::theme::apply::{ - ThemeBackground, ThemeBorder, ThemeFont, ThemeRadius, ThemeRunFont, ThemeRunText, ThemeText, - }; - - #[cfg(feature = "gpui")] - pub use crate::view::{ - Children as ViewChildren, ComponentChildren as ViewComponentChildren, - ParagraphContent as ViewParagraphContent, RunStyle as ViewRunStyle, button as view_button, - button_base as view_button_base, entity as view_entity, focus as view_focus, - image as view_image, svg as view_svg, tab_index as view_tab_index, - tab_navigation as view_tab_navigation, - }; - - /// Deprecated macro event aliases; referenced at the authored attribute span. - #[cfg(feature = "gpui")] - pub mod view_legacy { - #[deprecated(note = "use on:click")] - pub const ONCLICK: () = (); - - #[deprecated(note = "use on:key-down")] - pub const ONKEYDOWN: () = (); - - #[deprecated(note = "use on:key-up")] - pub const ONKEYUP: () = (); - - #[deprecated(note = "use on:mouse-move")] - pub const ONMOUSEMOVE: () = (); - - #[deprecated(note = "use on:mouse-down")] - pub const ONMOUSEDOWN: () = (); - - #[deprecated(note = "use on:mouse-up")] - pub const ONMOUSEUP: () = (); - } - - pub use tracing; - #[cfg(target_family = "wasm")] - pub use wasm_bindgen; -} - -/// Declares this crate's ambient view theme; invoke once at the crate root. -/// Install the value with [`theme::install`] before building themed views. -#[cfg(feature = "gpui")] -#[macro_export] -macro_rules! theme { - ($theme:path) => { - #[doc(hidden)] - pub(crate) type __RakeTheme = $theme; - }; -} - -#[cfg(feature = "gpui")] -pub use platform::icons::Icon; diff --git a/crates/rake/src/router/runtime/updates.rs b/crates/rake/src/router/runtime/updates.rs deleted file mode 100644 index f1587fac..00000000 --- a/crates/rake/src/router/runtime/updates.rs +++ /dev/null @@ -1,165 +0,0 @@ -//! Provider-neutral update actions share the router's existing guarded quit. -use super::{Operation, Route, Router}; -use crate::quit::{QuitOptions, QuitResult}; -#[cfg(all(feature = "gpui", feature = "updates-sparkle", target_os = "macos"))] -use rake_updates::UpdateState; -use rake_updates::{Error, UpdateController}; -use std::rc::Rc; - -impl Router { - /// Returns the application's shared update model, when installed policy is available. - pub fn updates(&self) -> Option> { - self.client().services().get().ok() - } - - /// Checks the installed provider without downloading or requesting termination. - /// # Errors - /// Rejects unavailable or externally managed providers and concurrent operations. - pub fn check_for_updates(&self) -> Result<(), Error> { - self.updates() - .ok_or_else(|| Error::Policy("no update controller is installed".into()))? - .check() - } - - /// Downloads the selected update; Sparkle uses its native review UI. - /// # Errors - /// Rejects missing availability or another active operation. - pub fn download_update(&self) -> Result<(), Error> { - self.updates() - .ok_or_else(|| Error::Policy("no update controller is installed".into()))? - .download() - } - - /// Submits verified staging to the existing save, work and window quit guards. - /// # Errors - /// Rejects absent staging or a competing quit operation. - pub fn restart_for_update(&self, options: QuitOptions) -> Result, Error> { - #[cfg(target_family = "wasm")] - { - let _ = options; - - Err(Error::Policy( - "native update restart is unavailable in a browser".into(), - )) - } - - #[cfg(not(target_family = "wasm"))] - { - let updates = self - .updates() - .ok_or_else(|| Error::Policy("no update controller is installed".into()))?; - - let handoff = updates.restart_handoff(std::env::args_os().skip(1).collect())?; - - self.quit_for_update(handoff, options) - } - } -} - -#[cfg(all(feature = "gpui", not(target_family = "wasm")))] -impl Router { - pub(crate) async fn changed_with_updates(&self, revision: u64) -> u64 { - let updates = self.updates(); - - let update_revision = updates - .as_ref() - .map(|controller| controller.snapshot().revision); - - if let Some(next) = update_revision - && self.0.update_revision.replace(next) != next - { - self.poll_updates(); - self.0.notify(); - - return self.revision(); - } - - let changed = self.changed(revision); - - let update = async { - if let (Some(updates), Some(revision)) = (&updates, update_revision) { - updates.changed(revision).await; - } else { - std::future::pending::<()>().await; - } - }; - - let changed = futures::future::select(Box::pin(changed), Box::pin(update)); - - #[cfg(all(feature = "native-lifecycle", target_os = "macos"))] - let _ = futures::future::select(Box::pin(changed), self.native_quit_changed()).await; - - #[cfg(not(all(feature = "native-lifecycle", target_os = "macos")))] - let _ = changed.await; - - self.poll_updates(); - #[cfg(all(feature = "native-lifecycle", target_os = "macos"))] - self.poll_native_quit(); - - if let Some(updates) = &updates { - let next = updates.snapshot().revision; - - if self.0.update_revision.replace(next) != next { - self.0.notify(); - } - } - - self.revision() - } - - fn poll_updates(&self) { - #[cfg(all(feature = "updates-sparkle", target_os = "macos"))] - if let Some(updates) = self.updates() { - if updates.binding().owner == rake_updates::UpdateOwner::Sparkle - && matches!(updates.state(), UpdateState::ReadyToRestart(_)) - && let Err(error) = self.restart_for_update(QuitOptions::default()) - { - tracing::error!( - error_type = std::any::type_name_of_val(&error), - "native update restart was not admitted" - ); - } - - if self.0.update_exit.get() == rake_updates::RestartDisposition::ProviderHandlesExit - && let Some(status) = updates.native_status() - { - match status.stage { - rake_updates::SparkleStage::Installing => self - .0 - .update_exit - .set(rake_updates::RestartDisposition::ExitHost), - rake_updates::SparkleStage::Failed => { - *self.0.update_restart_error.borrow_mut() = Some( - status - .error - .unwrap_or_else(|| "native installer failed".into()), - ); - self.0.notify(); - } - _ => {} - } - } - } - } - - #[cfg(all(feature = "updates-sparkle", target_os = "macos"))] - pub(crate) fn install_sparkle(&self) -> Result<(), Error> { - let Some(updates) = self.updates() else { - return Ok(()); - }; - - if updates.binding().owner != rake_updates::UpdateOwner::Sparkle { - return Ok(()); - } - - let quit = self - .0 - .native_quit - .borrow() - .as_ref() - .cloned() - .ok_or_else(|| Error::Policy("Sparkle requires an active native quit bridge".into()))?; - - updates.attach_sparkle(quit) - } -} diff --git a/docs/README.md b/docs/README.md index 89d73427..be62376d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -27,7 +27,7 @@ New here? Start with [Getting started](getting-started.md), then read | Guide | Covers | | --- | --- | | [View syntax](view.md) | `rake::view!` reference, styling and themes | -| [Overlays and scrolling](../crates/rake/overlays.md) | Dialogs, popovers and scrolling; evolving overlay API | +| [Overlays and scrolling](../crates/rake-gpui/overlays.md) | Dialogs, popovers and scrolling; evolving overlay API | | [GPUI Base and Kit](gpui-kit.md) | Base-backed controls, optional Kit, shared colors | | [Native controls](../crates/rake-native/README.md) | AppKit views in GPUI layouts | diff --git a/docs/dev-preview.md b/docs/dev-preview.md index d6388a15..fe18258f 100644 --- a/docs/dev-preview.md +++ b/docs/dev-preview.md @@ -134,7 +134,7 @@ python3 scripts/test-preview.py node scripts/test-preview-ui.mjs python3 scripts/test-dev-bridge.py cargo test -p rake-app-cli --bin rake --offline -cargo test -p rake-app --no-default-features --features devtools --lib native_preview --offline +cargo test -p rake-gpui --features devtools --lib native_preview --offline cargo test -p rake-app --test inspection_compiled_out --offline ``` diff --git a/docs/development.md b/docs/development.md index 7bb3929e..a4009a64 100644 --- a/docs/development.md +++ b/docs/development.md @@ -5,6 +5,25 @@ Build the CLI with `cargo build -p rake-app-cli` (or install it with toolchain on PATH; no Python interpreter is required. Repository-only Python verification scripts still require Python 3.11+. +## Workspace crates + +- [`rake-app`](../crates/rake) is the public `rake` facade used by apps, + templates and renamed-dependency consumers. +- [`rake-core`](../crates/rake-core) owns the portable runtime, router and + route mount contract, services, tasks, storage, diagnostics and control. + Custom hosts can use it directly on native targets and WASM. +- [`rake-gpui`](../crates/rake-gpui) builds on the core. It implements the + application builder, GPUI routing and view bindings, managed native and + browser startup, window observation and devtools capture. + +Keep application examples on the facade. Run core tests with +`cargo test -p rake-core --locked`, and run GPUI adapter unit tests with +`cargo test -p rake-gpui --features view-test-support --locked`. The facade +retains its integration and UI tests, including macro expansion and public +path checks. + +## Development commands + On Windows, `rake doctor`, `rake build`, native/Web `rake bundle` and the Node agent client are supported. Development supervision and native local inspection (`dev`, `inspect`, `ctl` and `cdp`) currently require Unix. The remaining Windows diff --git a/docs/future/internationalisation.md b/docs/future/internationalisation.md index 22b06186..7102d07f 100644 --- a/docs/future/internationalisation.md +++ b/docs/future/internationalisation.md @@ -214,7 +214,7 @@ checks; defer that to its own issue. Reject a global row-reverse workaround. ## 7. Inspection and agents Inspection reads GPUI a11y metadata, preferring explicit labels and deriving -label names from text ([accessibility.rs:15–45](../../crates/rake/src/inspection/view/accessibility.rs#L15)). +label names from text ([accessibility.rs:15–45](../../crates/rake-gpui/src/inspection/view/accessibility.rs#L15)). CDP emits `name` with label fallback ([accessibility.rs:70–71](../../crates/rake-cli/src/cdp/accessibility.rs#L70)). Semantic queries deserialize a strict selector with `name`, then compare exact diff --git a/docs/future/zgx-spike.md b/docs/future/zgx-spike.md new file mode 100644 index 00000000..198da0b3 --- /dev/null +++ b/docs/future/zgx-spike.md @@ -0,0 +1,103 @@ +# zgx spike: a framework-free Rake core + +The standalone zgx spike lives on the separate `t3/split-rake-core-gpui` +branch. It used zgx 0.1.3 for its macOS window and depended directly on +[rake-core](../../crates/rake-core). +The core builds on macOS and for `wasm32-unknown-unknown`. GPUI and zgx +share route mount and guarded close contracts. GPUI owns its window +registrations, native lifecycle callbacks and frame acknowledgements for reload. +The remaining view boundary is how authored views acquire, update and release +backend state. + +## What builds without GPUI + +- Protocol and clients, HTTP and diagnostics, resources, build/distribution, + updates, autostart, tray and shortcuts already have independent crates. + The tray and shortcut integration in the Rake facade still requires GPUI. +- The core owns typed routes and the mountable `Router`, `Runtime`, guarded + quit, command schemas and dispatch, local IPC, managed tasks, services, + storage, preferences, diagnostics and checkpoint data. Portable loader state + is available from the core and the GPUI view binding is in the integration. +- The spike composes `Services` with HTTP, a diagnostic collector and a + typed store. It opens `Destination::Status`, starts a managed task on + click, observes its terminal state, and exposes the stored result through a + real headless command. `Router::with_route_mount` creates its own scheduler + collector, so the UI reads HTTP diagnostics from the service collector. + +The [`rake-app` facade](../../crates/rake/src/lib.rs) forwards the established +features and paths. Default builds expose the [GPUI integration](../../crates/rake-gpui), +including the application factory and existing view macros. Headless consumers +can depend on the core directly or turn off default features on the facade. +Proc macros still resolve the facade first, including renamed dependencies. + +## Adapter gaps + +| Capability | Current boundary | +| --- | --- | +| Application lifecycle, real windows and window state | `App` starts GPUI and owns its factory callbacks. Standalone windows use `cx.open_window`, and the window-state observer stores GPUI entities and handles. **Window registration and guarded close addressed.** GPUI owns the async contexts and observers, and the router calls a framework-free host binding for removal and shutdown. The zgx spike forwards guarded close and shutdown. A reusable zgx integration still needs window visibility, activation policy and committed application quit. [App](../../crates/rake-gpui/src/application.rs#L101), [run](../../crates/rake-gpui/src/application.rs#L848), [window](../../crates/rake-gpui/src/application/managed/window.rs#L124), [observer](../../crates/rake-gpui/src/window_state/native.rs#L30), [WindowHost](../../crates/rake-core/src/router/types.rs) | +| Routed presentation | **Addressed.** `RouteMount` and `MountedRoute` work without GPUI. The GPUI adapter delegates to `RouteViews` and the outlet projects the retained `AnyView`. zgx mounts hidden trees once, toggles display on presentation changes and explicitly unmounts on disposal. Headless tests verify event order and exactly-once disposal for tab close, history truncation, window close and provisional rollback. [Mount contract](../../crates/rake-core/src/router/mount.rs), [GPUI adapter](../../crates/rake-gpui/src/router/view.rs) | +| Tasks and async view state | `TaskScope` can run on a local executor today. `RuntimeContext::action` and `load` require `gpui::Context`; the implementation observes an entity and calls `cx.notify()`. Host visibility and shutdown observation use GPUI windows, subscriptions and tasks. [Context](../../crates/rake-gpui/src/runtime.rs#L183), [binding](../../crates/rake-gpui/src/loading/binding.rs#L147), [host observation](../../crates/rake-gpui/src/tasks/host.rs#L4) | +| Inspection and devtools | Diagnostics, IPC and wire snapshots are reusable. Element capture wraps `gpui::Element` and intercepts layout, prepaint and paint. Focus, scrolling and style edits hold GPUI handles and style refinements. [Capture](../../crates/rake-gpui/src/inspection/view.rs#L407), [wrapper fields](../../crates/rake-gpui/src/inspection/view.rs#L82) | +| Development reload | **Mount, restore and UI quiescence boundary addressed.** The router retains the capture and restore transactions and reports readiness after portable managed tasks drain and the host reports its UI ready. The GPUI integration tracks frame acknowledgements and drives startup restore and checkpoint cleanup. A zgx host needs its own restart wiring and can supply a first-frame signal if required. [Restore](../../crates/rake-core/src/router/runtime/reload.rs), [startup](../../crates/rake-gpui/src/application.rs), [notice](../../crates/rake-gpui/src/reload/host.rs) | +| Menus and shortcuts | Commands and their presentation data are reusable. Rake's menu resolver produces `gpui::MenuItem` and `gpui::Action`, then registers GPUI key bindings. GPUI supplies validation and resolves the keystrokes for registration. [Resolver](../../crates/rake-gpui/src/menus.rs#L230), [bindings](../../crates/rake-gpui/src/menus.rs#L370), [validation](../../crates/rake-core/src/control/commands.rs#L294) | +| Theme, widgets and `view!` | Theme installation uses `gpui::App` and tokens use GPUI types. Codegen emits GPUI builders, focus and event bindings, style traits and inspection wrappers. [Theme](../../crates/rake-ui/src/theme.rs#L13), [builders](../../crates/rake-view-syntax/src/view.rs#L987), [style presets](../../crates/rake-view-syntax/src/view/preset.rs#L57), [instrumentation](../../crates/rake-view-syntax/src/view/inspection.rs#L116) | + +## Option 1 + +- Keep route identity, admission, command/task policy, typed services and + checkpoints in a core crate. Reuse `WindowHost` for guarded close and + optional additional windows. Expose the framework-free lifecycle and reload + hooks needed across crate boundaries. A host reports visibility and polls + the local driver on its own loop. +- Both backends now use the route mount contract. Preparation + receives the typed destination, service registry and cancellation token. + Mount consumes prepared data with the window and entry IDs and weak + entry and navigation handles. The router retains the returned mount across + history, calls its presentation hook after commit and disposes it on + rollback or removal. +- Keep observation clients on owned protocol snapshots. An optional inspection + provider returns stable node keys, revisions and geometry, and advertises + supported operations such as focus, picking and style edits. A menu adapter + can project command state and dispatch stable command IDs through the registry. +- The GPUI builder, routing views, theme, native bindings and existing + macros are exposed by `rake-gpui`, preserving the current default facade paths + through reexports. `rake-zgx` would map the same lifecycle to zgx windows + and retained view scopes, and map task and route changes to signals. +- Share the `view!` parser and syntax validation and give each backend its + own lowering. Keep GPUI's frame-time builders and event contexts. zgx + lowering needs mount-time construction, signal-aware text/styles, + retained handler and subscription lifetimes, and keyed reconciliation + for changing branches and lists. Specify which expressions capture once + and which are re-evaluated. Preserve stable data keys, authored source + spans, and explicit per-backend extensions for widgets and handlers. + +The zgx spike uses `Ui::mount` to add retained roots without replacing the +document. In zgx 0.1.3, `WindowContext::render` sets up desktop services such as +clipboard, dialogs and scoped tasks and also replaces root content. A reusable +zgx route outlet needs to preserve those services when it attaches a new subtree. + +## Remaining split work + +- Extract an opt-in zgx integration from the standalone spike. Keep zgx + dependencies out of the default GPUI path and verify independent and combined + dependency resolution. Validate the browser adapter separately. +- Share view syntax validation and build the two backend-specific lowerings + and view bindings described above. + +## Risks and effort + +| Effort | Remaining work | +| --- | --- | +| Medium | Build a reusable zgx host around the spike with visibility, application quit, reload startup and task observation. | +| Large | Define backend-specific view state and lower `view!` for retained, signal-driven trees. Dynamic branches and lists need keyed reconciliation and effect lifetimes. Port applicable widgets, accessibility and inspection support. | + +- Cargo features unify additively. Separate integration crates keep each + backend opt-in for a downstream application. The spike's own lockfile + isolates wgpu and the zgx taffy fork from the main lockfile. Its resolution + needed a wider `blocking` range for zgx-desktop's Linux-only 1.6.2 + pin even on macOS. This workspace requires 1.7. + Test dependency resolution again before combining both backends in one app. +- The core WASM check establishes buildability. `zgx-dom` needs its own + spike for DOM mounting, browser history, storage, user activation and + inspection. Check the browser adapter's version and capabilities separately. + [zgx browser overview](https://github.com/zeronsh/zgx#what-it-has). diff --git a/docs/internal/devtools-coverage.md b/docs/internal/devtools-coverage.md index 66ce97f5..b5ebccd9 100644 --- a/docs/internal/devtools-coverage.md +++ b/docs/internal/devtools-coverage.md @@ -61,9 +61,9 @@ automated through Chrome's paste guard. ```sh cargo test -p rake-app-cli --offline -cargo test -p rake-app --features view-test-support,devtools --lib inspection --offline +cargo test -p rake-gpui --features view-test-support,devtools --lib inspection --offline cargo clippy -p rake-app-cli -p rake-app --all-targets --features rake-app/view-test-support --offline -- -D warnings -cargo test -p rake-app --no-default-features --lib --offline +cargo test -p rake-core --lib --offline cargo check -p rake-app -p rake-view --lib --target wasm32-unknown-unknown --offline cargo build -p rake-app-cli -p rake-view --features rake/devtools --offline node scripts/test-elements-cdp.mjs diff --git a/docs/notifications.md b/docs/notifications.md index 98a7847d..dfab0b29 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -110,7 +110,7 @@ Automated checks: ```sh cargo test -p rake-app --no-default-features --lib --test platform -cargo test -p rake-app --features view-test-support --lib +cargo test -p rake-gpui --features view-test-support --lib node scripts/test-platform.mjs ``` diff --git a/docs/routing.md b/docs/routing.md index a1b1dab6..193c0579 100644 --- a/docs/routing.md +++ b/docs/routing.md @@ -75,6 +75,25 @@ The runner installs the default tab strip, route outlet and decision presenter. A custom GPUI host can use `Router::in_window`, own its `run` future, observe `changed`, and compose `TabBar` and `RouteOutlet`. `Router::new` is a headless state model without GPUI resources. +### Mounting routes in another UI framework + +Use `Router::with_route_mount(config, services, adapter)` with default features +disabled. The adapter implements `RouteMount`. Its optional `prepare` loads +owned `PreparedPage` data with typed services and an operation cancellation token. +Its `mount` consumes that data and gets stable window and entry IDs plus weak +entry and navigation handles in `RouteMountContext`. + +The adapter returns a `MountedRoute` while its view is hidden. The router +retains that handle across history traversal, calls `presentation_changed` +after commit and disposes the mount if the entry rolls back or leaves history. +During workspace restore, consume any saved state with +`context.entry.reload_state()` before returning the mount. The router reports +`Restored` after the initial presentation callbacks return. + +Poll `Router::run` on the host's event loop, report host visibility with +`set_window_visibility` and call `shutdown` during teardown. Native integrations +can install a `WindowHost` to open and close routed windows. + ## Tabs, histories and commands `page.navigator()` binds contextual commands to that screen's original tab. diff --git a/docs/tray.md b/docs/tray.md index 7bc989a7..fce7d8e5 100644 --- a/docs/tray.md +++ b/docs/tray.md @@ -225,7 +225,7 @@ See the [unopened upstream proposal](../.agents/reports/ksni-upstream-proposal.m ```sh cargo test -p rake-tray --locked -cargo test -p rake-app --features tray,view-test-support --lib --locked +cargo test -p rake-gpui --features tray,view-test-support --lib --locked cargo clippy -p rake-app --features tray --all-targets --locked -- -D warnings python3 scripts/test-tray-native.py appkit python3 scripts/test-tray-native.py sni diff --git a/docs/view.md b/docs/view.md index c7e3898d..fd779b50 100644 --- a/docs/view.md +++ b/docs/view.md @@ -629,7 +629,7 @@ There's no global component cache or extra state runtime. Retained scroll handles work through `scroll`, and GPUI virtual lists embed through `{expression}`. -The `rake::overlay` module adds `OverlayHost`, `OverlayAnchor`, `Popover` and `Dialog` as typed components, with retained state, live anchor geometry, stacked dismissal and modal focus containment. See [scrolling and overlays](../crates/rake/overlays.md). The example opens a retained 10,000-document virtual list from a nested dialog. +The `rake::overlay` module adds `OverlayHost`, `OverlayAnchor`, `Popover` and `Dialog` as typed components, with retained state, live anchor geometry, stacked dismissal and modal focus containment. See [scrolling and overlays](../crates/rake-gpui/overlays.md). The example opens a retained 10,000-document virtual list from a nested dialog. ## Diagnostics and editing diff --git a/examples/inspector/Cargo.lock b/examples/inspector/Cargo.lock index 2c0a92e5..356aa914 100644 --- a/examples/inspector/Cargo.lock +++ b/examples/inspector/Cargo.lock @@ -4444,28 +4444,48 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rake-app" -version = "0.1.0-alpha.3" +version = "0.1.0-alpha.7" +dependencies = [ + "gpui-pre-platform", + "rake-core", + "rake-gpui", + "rake-macros", +] + +[[package]] +name = "rake-client" +version = "0.1.0-alpha.7" +dependencies = [ + "async-io", + "futures", + "libc", + "rake-http", + "rake-protocol", + "serde", + "serde_json", + "sha2", + "thiserror 2.0.21", + "url", + "windows-sys 0.61.2", +] + +[[package]] +name = "rake-core" +version = "0.1.0-alpha.7" dependencies = [ - "anyhow", "async-io", "blocking", "console_error_panic_hook", "event-listener", "futures", - "gpui-pre", - "gpui-pre-platform", "js-sys", "libc", - "objc2-app-kit 0.3.2", "rake-client", "rake-diagnostics", "rake-http", "rake-macros", "rake-protocol", "rake-resources", - "rake-ui", - "rake-updates", - "raw-window-handle", "schemars", "serde", "serde_json", @@ -4478,31 +4498,17 @@ dependencies = [ "wasm-bindgen-futures", "web-sys", "web-time", - "windows-sys 0.61.2", -] - -[[package]] -name = "rake-client" -version = "0.1.0-alpha.2" -dependencies = [ - "async-io", - "futures", - "libc", - "rake-http", - "rake-protocol", - "serde", - "serde_json", - "thiserror 2.0.21", - "url", + "zeroize", ] [[package]] name = "rake-diagnostics" -version = "0.1.0-alpha.2" +version = "0.1.0-alpha.7" dependencies = [ "serde", "serde_json", "thiserror 2.0.21", + "time", "tracing", "tracing-subscriber", "web-sys", @@ -4511,7 +4517,7 @@ dependencies = [ [[package]] name = "rake-dist-core" -version = "0.1.0-alpha.2" +version = "0.1.0-alpha.7" dependencies = [ "semver", "serde", @@ -4520,9 +4526,56 @@ dependencies = [ "url", ] +[[package]] +name = "rake-gpui" +version = "0.1.0-alpha.7" +dependencies = [ + "anyhow", + "block2 0.6.2", + "blocking", + "console_error_panic_hook", + "event-listener", + "futures", + "gpui-pre", + "gpui-pre-apple", + "gpui-pre-platform", + "image", + "js-sys", + "libc", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "objc2-user-notifications", + "oo7", + "rake-client", + "rake-core", + "rake-diagnostics", + "rake-macros", + "rake-protocol", + "rake-resources", + "rake-ui", + "rake-updates", + "raw-window-handle", + "schemars", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.21", + "tracing", + "url", + "uuid", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", + "windows 0.62.2", + "windows-sys 0.61.2", + "zbus 5.19.0", +] + [[package]] name = "rake-http" -version = "0.1.0-alpha.2" +version = "0.1.0-alpha.7" dependencies = [ "async-compat", "async-io", @@ -4554,7 +4607,7 @@ dependencies = [ [[package]] name = "rake-macros" -version = "0.1.0-alpha.3" +version = "0.1.0-alpha.7" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -4565,7 +4618,7 @@ dependencies = [ [[package]] name = "rake-protocol" -version = "0.1.0-alpha.2" +version = "0.1.0-alpha.7" dependencies = [ "percent-encoding", "rake-diagnostics", @@ -4578,7 +4631,7 @@ dependencies = [ [[package]] name = "rake-resources" -version = "0.1.0-alpha.2" +version = "0.1.0-alpha.7" dependencies = [ "command-group", "rake-dist-core", @@ -4588,17 +4641,18 @@ dependencies = [ [[package]] name = "rake-ui" -version = "0.1.0-alpha.2" +version = "0.1.0-alpha.7" dependencies = [ "gpui-base", "gpui-pre", + "rake-macros", "tracing", "unicode-segmentation", ] [[package]] name = "rake-updates" -version = "0.1.0-alpha.2" +version = "0.1.0-alpha.7" dependencies = [ "cc", "event-listener", @@ -4613,7 +4667,7 @@ dependencies = [ [[package]] name = "rake-view-syntax" -version = "0.1.0-alpha.3" +version = "0.1.0-alpha.7" dependencies = [ "proc-macro2", "quote", @@ -5817,6 +5871,7 @@ dependencies = [ "powerfmt", "serde_core", "time-core", + "time-macros", ] [[package]] @@ -5825,6 +5880,16 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-keccak" version = "2.0.2" diff --git a/scripts/check-core-dependencies.sh b/scripts/check-core-dependencies.sh new file mode 100644 index 00000000..ded82750 --- /dev/null +++ b/scripts/check-core-dependencies.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -eu + +check_tree() { + local tree + tree=$(cargo tree -p rake-core -e normal --locked --prefix none "$@") + + if grep -E '^[^[:space:]]*gpui' <<<"$tree"; then + echo "rake-core has a GPUI dependency (${*:-native})" >&2 + return 1 + fi +} + +check_tree +check_tree --target wasm32-unknown-unknown + +# The web-crash example uses the facade's default features and dev-dependencies. +# Skip host build dependencies and proc macros, which can use native crates. +for package in rake-core rake-app; do + tree=$(cargo tree -p "$package" -e normal,dev,no-proc-macro --locked \ + --prefix none --target wasm32-unknown-unknown) + if grep -E '^errno v' <<<"$tree"; then + echo "$package has an errno dependency (wasm32-unknown-unknown)" >&2 + exit 1 + fi +done diff --git a/scripts/test-file-drop.mjs b/scripts/test-file-drop.mjs index 4e73f7f0..b566d73a 100644 --- a/scripts/test-file-drop.mjs +++ b/scripts/test-file-drop.mjs @@ -1,5 +1,5 @@ import assert from 'node:assert/strict'; -import {on_canvas_file_drop, read_file} from '../crates/rake/src/platform/browser.js'; +import {on_canvas_file_drop, read_file} from '../crates/rake-gpui/src/platform/browser.js'; globalThis.document = new EventTarget(); const canvas = new EventTarget(); canvas.tagName = 'CANVAS'; diff --git a/scripts/test-platform.mjs b/scripts/test-platform.mjs index cf5c3e03..33496d7e 100644 --- a/scripts/test-platform.mjs +++ b/scripts/test-platform.mjs @@ -3,8 +3,14 @@ import assert from 'node:assert/strict'; import {readFile} from 'node:fs/promises'; -const source = await readFile(new URL('../crates/rake/src/platform/browser.js', import.meta.url), 'utf8'); -const adapter = await import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`); +async function load(module) { + const source = await readFile(new URL(`../crates/${module}`, import.meta.url), 'utf8'); + return import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`); +} +const adapter = { + ...await load('rake-core/src/platform/browser.js'), + ...await load('rake-gpui/src/platform/browser.js'), +}; const values = new Map(); globalThis.localStorage = { getItem: key => values.get(key) ?? null, @@ -86,8 +92,10 @@ assert.equal(opened.location.href, 'https://example.com'); console.log('Platform adapter: eager requests, capabilities, denial, cancellation, file limits, quotas and URL opening passed'); // OS notification adapter: permission UI is doubled, delivery/callback code is real. -const notificationsSource = await readFile(new URL('../crates/rake/src/platform/notifications/browser.js', import.meta.url), 'utf8'); -const notifications = await import(`data:text/javascript;base64,${Buffer.from(notificationsSource).toString('base64')}`); +const notifications = { + ...await load('rake-gpui/src/platform/notifications/browser.js'), + ...await load('rake-core/src/platform/notifications/browser.js'), +}; let prompts = 0; let nextPermission = 'granted'; const posted = []; diff --git a/scripts/test-web-crash.mjs b/scripts/test-web-crash.mjs index faf64f2c..4773f1f5 100644 --- a/scripts/test-web-crash.mjs +++ b/scripts/test-web-crash.mjs @@ -69,7 +69,7 @@ try { const path = new URL(request.url, 'http://localhost').pathname; try { if (path === '/') { response.writeHead(200, {'Content-Type':'text/html'}).end(bootstrap); return; } - if (path === '/adapter.js') { response.writeHead(200, {'Content-Type':'text/javascript'}).end(await readFile(join(root, 'crates/rake/src/crash/browser.js'))); return; } + if (path === '/adapter.js') { response.writeHead(200, {'Content-Type':'text/javascript'}).end(await readFile(join(root, 'crates/rake-core/src/crash/browser.js'))); return; } assert(!path.split('/').includes('..')); const data = await readFile(join(temporary, path)); response.writeHead(200, {'Content-Type':path.endsWith('.wasm')?'application/wasm':'text/javascript'}).end(data); diff --git a/scripts/test-web-platform.mjs b/scripts/test-web-platform.mjs index dbbd3f06..3d02a33a 100644 --- a/scripts/test-web-platform.mjs +++ b/scripts/test-web-platform.mjs @@ -22,8 +22,10 @@ cli = Path(os.environ.get('RAKE_CLI', str(Path(os.environ.get('CARGO_TARGET_DIR' for label in ['old', 'new']: site = work / (label + '-source') site.mkdir() - (site / 'platform.js').write_text((root / 'crates/rake/src/platform/browser.js').read_text()) - (site / 'runtime.js').write_text((root / 'crates/rake/src/web/browser.js').read_text()) + for crate in ['rake-core', 'rake-gpui']: + (site / f'{crate}-platform.js').write_text((root / 'crates' / crate / 'src/platform/browser.js').read_text()) + (site / 'platform.js').write_text('export * from "./rake-core-platform.js"; export * from "./rake-gpui-platform.js";') + (site / 'runtime.js').write_text((root / 'crates/rake-core/src/web/browser.js').read_text()) (site / 'count.worker.js').write_text('self.onmessage=e=>self.postMessage(JSON.stringify({length:JSON.parse(e.data).text.length,build:' + json.dumps(label) + '}));') (site / 'never.worker.js').write_text('self.onmessage=()=>{};') (site / 'index.html').write_text('') diff --git a/scripts/test-web-runtime.mjs b/scripts/test-web-runtime.mjs index f2f12990..3fbdd1c0 100644 --- a/scripts/test-web-runtime.mjs +++ b/scripts/test-web-runtime.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import {readFile} from 'node:fs/promises'; -const source = await readFile(new URL('../crates/rake/src/web/browser.js', import.meta.url), 'utf8'); +const source = await readFile(new URL('../crates/rake-core/src/web/browser.js', import.meta.url), 'utf8'); const adapter = await import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`); globalThis.document = {baseURI: 'https://example.test/tools/rake-builds/old/', querySelector: () => ({content: '{"build":"old"}'})}; globalThis.location = {origin: 'https://example.test'};