diff --git a/.gitattributes b/.gitattributes index 1fa8a14f7e..05626c1f19 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,2 @@ -vendor/react-native-gpui/** linguist-vendored packages/app/gpui/package-lock.json linguist-generated packages/app/gpui/desktop/Cargo.lock linguist-generated diff --git a/.gitignore b/.gitignore index 0eb84dde1c..9ca05dbc85 100644 --- a/.gitignore +++ b/.gitignore @@ -100,8 +100,4 @@ app.json # Project-local Serena configuration and memories. .serena/ -# Vendored experimental React Native desktop runtime. -!vendor/ -!vendor/react-native-gpui/ -!vendor/react-native-gpui/** !packages/app/gpui/app.json diff --git a/.oxfmtrc.json b/.oxfmtrc.json index c984d49472..382d38e94c 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -16,7 +16,6 @@ "**/*.gen.ts", "**/*.gen.tsx", "**/*.icon/**", - "packages/react-native-enriched-markdown/**", - "vendor/**" + "packages/react-native-enriched-markdown/**" ] } diff --git a/.oxlintrc.json b/.oxlintrc.json index b07d5385db..56458a4802 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -3,7 +3,7 @@ "options": { "typeAware": false }, - "ignorePatterns": [".dev/**", "packages/react-native-enriched-markdown/**", "vendor/**"], + "ignorePatterns": [".dev/**", "packages/react-native-enriched-markdown/**"], "plugins": ["react", "react-perf", "unicorn", "typescript", "oxc", "import", "promise"], "jsPlugins": ["./scripts/oxlint/paseo-plugin.mjs"], "categories": { diff --git a/packages/app/gpui/README.md b/packages/app/gpui/README.md index 371422b974..af7b9a9f99 100644 --- a/packages/app/gpui/README.md +++ b/packages/app/gpui/README.md @@ -96,7 +96,7 @@ iOS, Android, web, and macOS all run from the same app code. This target does to behind the interface the app already uses. - **Fix the renderer, not the React code.** When something looks or behaves wrong only on GPUI, such as the tab track, the same React code is correct on - every other platform. The defect is in `vendor/react-native-gpui`; fix it there. + every other platform. The defect is in [getpaseo/react-native-gpui](https://github.com/getpaseo/react-native-gpui); fix it there. ## Approach and renderer choice @@ -136,38 +136,26 @@ controlled CPU, memory, startup, or frame-time results against these alternative | Area | Why it is here | | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `vendor/react-native-gpui/` | Editable, pinned runtime source. This accounts for roughly 130,000 lines of the diff. GitHub marks it as vendored; inspect [UPSTREAM](../../../vendor/react-native-gpui/UPSTREAM) for provenance and the local patches. | -| npm and Cargo lockfiles | Reproduce the experiment's dependencies. Roughly 15,000 generated lines, collapsed on GitHub. | +| `packages/app/gpui/package.json` and `package-lock.json` | Pinned tarballs from a [getpaseo/react-native-gpui](https://github.com/getpaseo/react-native-gpui/releases) release (`paseo-*`) for `@react-native-gpui/{cli,codegen,core,hermes}` and the seven `@react-native-gpui/*` modules. | +| `packages/app/gpui/desktop/Cargo.lock` | Pins Rust crates for the desktop shell (`../node_modules/@react-native-gpui/core/ReactGpui/...` path dependencies). | | `desktop/`, `index.js`, `routes.js`, Metro/Babel config, root launcher | Register the full app, select the native runtime, compile native services, and bundle the actual route graph. The explicit route context prevents an apparently successful build with no app routes. | | `adapters/` | Desktop implementations of npm packages used by the app, plus explicit unavailable-capability implementations for mobile packages. Limited ports, not complete replacements for Expo/Unistyles. App-module overrides live next to the shared files as `.gpui.ts` / `.gpui.tsx`. | | Shared app edits | One capability gate for alpha-mask shimmer. GPUI shows the logo and labels without that effect. Existing web/iOS/Android paths keep their behavior. | | Native tests and this guide | Make the working slice reproducible and give contributors bounded follow-up work. | -Upstream examples, its tester/testing package, website, unused fonts/vector-icon -ports, starter navigation dependencies, sample icon, and unused nested Cargo config -are omitted. Build outputs, native binaries, downloaded SDKs, logs, screenshots, -and the exploratory size-measurement copy stay out of Git. +### Testing changes against a local fork checkout -The retained runtime still includes its build machinery, platform backends, -headers, and tests. Arbitrarily deleting those to reduce line count makes an -upstream refresh harder. Vendoring can later be replaced by a pinned dependency -once the local patches are upstreamed and distribution is reproducible. +To build Paseo against a local checkout of `getpaseo/react-native-gpui` instead of the pinned release: -### Editing the runtime +```sh +npm run gpui:install -- --local /path/to/react-native-gpui +``` -Edit `vendor/react-native-gpui`, then run `npm run gpui:install` before rebuilding. -npm copies local packages rather than symlinking them; the install command -refreshes those copies even when their versions have not changed. - -There are two local renderer changes: - -- `node_view.rs`: a `pointerEvents="box-none"` view must not install its own hit - area. Before the patch, Paseo's empty portal overlay intercepted sidebar clicks. -- `StatusBar.desktop.js`: desktop windows do not have the mobile OS status bar. +You can also pass the path via `PASEO_GPUI_LOCAL=/path/to/react-native-gpui npm run gpui:install`. +This installs locked dependencies and the seven `@react-native-gpui/*` modules from the release, then packs `@react-native-gpui/{cli,codegen,core,hermes}` from the local checkout into `packages/app/gpui/node_modules/@react-native-gpui/` without modifying `package.json` or `package-lock.json`. Re-run the same command after editing the fork, then rebuild (`npm run build:gpui` or `npm run dev:gpui`). Run `npm run gpui:install` without `--local` to restore the release packages. GPUI remains a pinned Cargo git dependency. Upstream tooling downloads Hermes -and React Native prebuilt libraries. The snapshot is not an offline or fully -source-built distribution, and release packaging has not been verified. +and builds the C++ runtime when needed; release packaging has not been verified across all platforms. ## Working slice and limits diff --git a/packages/app/gpui/package-lock.json b/packages/app/gpui/package-lock.json index 5ef28329e0..c20abbde09 100644 --- a/packages/app/gpui/package-lock.json +++ b/packages/app/gpui/package-lock.json @@ -15,16 +15,16 @@ "@formatjs/intl-numberformat": "^9.5.0", "@formatjs/intl-pluralrules": "^6.4.0", "@formatjs/intl-segmenter": "^12.3.0", - "@react-native-gpui/codegen": "file:../../../vendor/react-native-gpui/packages/codegen", - "@react-native-gpui/core": "file:../../../vendor/react-native-gpui/packages/core", - "@react-native-gpui/fs": "file:../../../vendor/react-native-gpui/modules/fs", - "@react-native-gpui/gesture-handler": "file:../../../vendor/react-native-gpui/modules/gesture-handler", - "@react-native-gpui/hermes": "file:../../../vendor/react-native-gpui/packages/hermes", - "@react-native-gpui/reanimated": "file:../../../vendor/react-native-gpui/modules/reanimated", - "@react-native-gpui/safe-area-context": "file:../../../vendor/react-native-gpui/modules/safe-area-context", - "@react-native-gpui/screens": "file:../../../vendor/react-native-gpui/modules/screens", - "@react-native-gpui/svg": "file:../../../vendor/react-native-gpui/modules/svg", - "@react-native-gpui/worklets": "file:../../../vendor/react-native-gpui/modules/worklets", + "@react-native-gpui/codegen": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-codegen-0.87.0-alpha.2.tgz", + "@react-native-gpui/core": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-core-0.87.0-alpha.5.tgz", + "@react-native-gpui/fs": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-fs-0.0.1-alpha.1.tgz", + "@react-native-gpui/gesture-handler": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-gesture-handler-3.3.0-alpha.1.tgz", + "@react-native-gpui/hermes": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-hermes-0.87.0-alpha.1.tgz", + "@react-native-gpui/reanimated": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-reanimated-4.7.0-alpha.1.tgz", + "@react-native-gpui/safe-area-context": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-safe-area-context-5.10.0-alpha.0.tgz", + "@react-native-gpui/screens": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-screens-4.28.0-alpha.2.tgz", + "@react-native-gpui/svg": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-svg-15.15.0-alpha.1.tgz", + "@react-native-gpui/worklets": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-worklets-0.13.0-alpha.1.tgz", "@react-native/assets-registry": "^0.87.1", "react": "19.2.3", "react-native": "0.87.1", @@ -37,7 +37,7 @@ }, "devDependencies": { "@react-native-community/cli": "20.2.0", - "@react-native-gpui/cli": "file:../../../vendor/react-native-gpui/packages/cli", + "@react-native-gpui/cli": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-cli-0.87.0-alpha.5.tgz", "@react-native/babel-preset": "0.87.1", "@react-native/metro-config": "0.87.1", "typescript": "^5.8.3" @@ -67,20 +67,20 @@ } }, "node_modules/@babel/core": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", - "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.16.tgz", + "integrity": "sha512-qK40pOeReBJY7B0JX6CCIfauMLAa0IlvuVYJ+aZBYLVJwmNUTvsQcEu0En9hVMmNjeSUSQYwvpi1JgXn5imIQw==", "license": "MIT", "dependencies": { "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.7", - "@babel/helper-compilation-targets": "^7.29.7", - "@babel/helper-module-transforms": "^7.29.7", - "@babel/helpers": "^7.29.7", - "@babel/parser": "^7.29.7", + "@babel/generator": "^7.29.16", + "@babel/helper-compilation-targets": "^7.29.13", + "@babel/helper-module-transforms": "^7.29.16", + "@babel/helpers": "^7.29.16", + "@babel/parser": "^7.29.15", "@babel/template": "^7.29.7", - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7", + "@babel/traverse": "^7.29.16", + "@babel/types": "^7.29.15", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", @@ -97,22 +97,22 @@ } }, "node_modules/@babel/core/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", "license": "ISC", "bin": { "semver": "bin/semver.js" } }, "node_modules/@babel/generator": { - "version": "7.29.12", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.12.tgz", - "integrity": "sha512-2W76mhjrpQFO1lK5e8IvGYB2D0YZ7S2R1Z2BjO2ZUYuW+amcpK/z60U6ZZmzskwoa7sJ6XohP/Wg8H5KxXI/IA==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.16.tgz", + "integrity": "sha512-yRtddtrcYdLJt0l70aP7usb2YpMHNXAdAvJW2hXdka5boR4vKMS/F5BTR5sULkbht9xPk/EKzbY2mCczMutZqQ==", "license": "MIT", "dependencies": { - "@babel/parser": "^7.29.12", - "@babel/types": "^7.29.11", + "@babel/parser": "^7.29.15", + "@babel/types": "^7.29.15", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" @@ -134,9 +134,9 @@ } }, "node_modules/@babel/helper-compilation-targets": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", - "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz", + "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==", "license": "MIT", "dependencies": { "@babel/compat-data": "^7.29.7", @@ -150,26 +150,26 @@ } }, "node_modules/@babel/helper-compilation-targets/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", "license": "ISC", "bin": { "semver": "bin/semver.js" } }, "node_modules/@babel/helper-create-class-features-plugin": { - "version": "7.29.12", - "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.29.12.tgz", - "integrity": "sha512-ACxGoWMV866q/QlZHeCOaQZAR5QclKsIvkAmlDemqjm6+6Bynijs1mH068BzH2N2e+wSuDmBWY87fqKfvhi1Lw==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.29.16.tgz", + "integrity": "sha512-WtgkoMdh0RChZDUirmEzuMRHzswXUyIIiq13tHBgP0mvYuaDWlMK73vsatiba0Q1dsxWCeIceg9q8GE5GynFlw==", "license": "MIT", "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", - "@babel/helper-member-expression-to-functions": "^7.29.7", + "@babel/helper-member-expression-to-functions": "^7.29.14", "@babel/helper-optimise-call-expression": "^7.29.7", - "@babel/helper-replace-supers": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", - "@babel/traverse": "^7.29.12", + "@babel/helper-replace-supers": "^7.29.16", + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.13", + "@babel/traverse": "^7.29.16", "semver": "^6.3.1" }, "engines": { @@ -180,22 +180,22 @@ } }, "node_modules/@babel/helper-create-class-features-plugin/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", "license": "ISC", "bin": { "semver": "bin/semver.js" } }, "node_modules/@babel/helper-create-regexp-features-plugin": { - "version": "7.29.10", - "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.29.10.tgz", - "integrity": "sha512-/YY9soQuWa8TURtHXHT+GbklpbAA+dZErxFGHIr6qgDg96xuGWrTAs1+MfjgVJPF0YLQsOVsOYs8lhgsPbOinQ==", + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.29.14.tgz", + "integrity": "sha512-nKvzhuLMMnFHHsENpUZh4N2e+LqnKDgT0SMibSyv8aW8FqGKWMqLO/zdnRjAYcruH9At6LVicWg7DgTc6IPzNg==", "license": "MIT", "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", - "regexpu-core": "^6.5.3", + "regexpu-core": "^6.5.4", "semver": "^6.3.1" }, "engines": { @@ -206,9 +206,9 @@ } }, "node_modules/@babel/helper-create-regexp-features-plugin/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -241,13 +241,14 @@ } }, "node_modules/@babel/helper-member-expression-to-functions": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.29.7.tgz", - "integrity": "sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg==", + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.29.14.tgz", + "integrity": "sha512-FuTSn8mXKAP+aHXnbkCYQsQAdlEIJptEutwc2NaPd28hyVqsjRDmBnI2EPJX6HCodKIqOHfayQHqtxQCkqwthA==", "license": "MIT", "dependencies": { - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.13", + "@babel/traverse": "^7.29.14", + "@babel/types": "^7.29.14" }, "engines": { "node": ">=6.9.0" @@ -267,14 +268,14 @@ } }, "node_modules/@babel/helper-module-transforms": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", - "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.16.tgz", + "integrity": "sha512-jzdW9nRNJXbNAfcbtfZA75vcQK8c/PRniwNL1KIQukiptryb5JlCl+nwi3idOSj611tMgiZxb9PuKg1FI0BvVQ==", "license": "MIT", "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", - "@babel/traverse": "^7.29.7" + "@babel/traverse": "^7.29.16" }, "engines": { "node": ">=6.9.0" @@ -323,14 +324,14 @@ } }, "node_modules/@babel/helper-replace-supers": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.29.7.tgz", - "integrity": "sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.29.16.tgz", + "integrity": "sha512-dO04oKhF0qDY0xnuZPF8t34lYkuhimqJ4skwGHEPPAmtxMKH2KS5lGdIbFrgz5tQPWqtyPMBbHfpyJLQacpE1Q==", "license": "MIT", "dependencies": { - "@babel/helper-member-expression-to-functions": "^7.29.7", + "@babel/helper-member-expression-to-functions": "^7.29.14", "@babel/helper-optimise-call-expression": "^7.29.7", - "@babel/traverse": "^7.29.7" + "@babel/traverse": "^7.29.16" }, "engines": { "node": ">=6.9.0" @@ -340,22 +341,22 @@ } }, "node_modules/@babel/helper-skip-transparent-expression-wrappers": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.29.7.tgz", - "integrity": "sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.29.13.tgz", + "integrity": "sha512-Abm4rKIH0tmCayJLwcoeOkdzpYUphTbO52fHhyEBHn7S0R+ni4epNLI/8nq1L0DN2Bl0u5qmgWm2Og/z4fBb+Q==", "license": "MIT", "dependencies": { - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" + "@babel/traverse": "^7.29.13", + "@babel/types": "^7.29.11" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-string-parser": { - "version": "7.29.11", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.11.tgz", - "integrity": "sha512-snZbO7MEDOof+hvNa97EjEY7qD7h2kwvQr5AJC3ZhQudKW5dnej6k3kP9NQV88hJwaS8vDqRLFo9rivLEhle2g==", + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.15.tgz", + "integrity": "sha512-C2FuapQ2Kh1OnVHAoLi5rD3GBJ8COb9Q609T6HEpLqaBAo560PDP5OxBE5dCI/h951MBO/+bCUYU5SZ+8ZlV+w==", "license": "MIT", "engines": { "node": ">=6.9.0" @@ -380,40 +381,40 @@ } }, "node_modules/@babel/helper-wrap-function": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.29.7.tgz", - "integrity": "sha512-iES0Skag9ERIF68aXadpO6dbXa03mNWK3sEqJaMnLNs/eC3l0lkImdfoy6Y09/SfkpawdAB4RjQ7PVA7TcVGdw==", + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.29.15.tgz", + "integrity": "sha512-14dKROQSpuNYPw+4wpADe87YLS1VnP/ua3gKTRpEAX1ErBayLMgK/KpWbCP/uYiCSBAVGp/a7bY8MqRfFNRqOQ==", "dev": true, "license": "MIT", "dependencies": { "@babel/template": "^7.29.7", - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" + "@babel/traverse": "^7.29.15", + "@babel/types": "^7.29.15" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helpers": { - "version": "7.29.10", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.10.tgz", - "integrity": "sha512-EMCx3AGZ3WfAl6ht7AyQoPm2Lh+BGYEMdc4Q6Hf7uSCDOZFuLq44qNwL+iaim8VlyYhRAo4X43+weadK8ZB4Yg==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.16.tgz", + "integrity": "sha512-JGNbyEyvOAvceLDQoO6b/w/HbW6KX3sdWgrPCFcAyHfhfsqRoRN14vfaG3GZ90g2dVK7UEe65giopuldeimBjg==", "license": "MIT", "dependencies": { "@babel/template": "^7.29.7", - "@babel/types": "^7.29.8" + "@babel/types": "^7.29.15" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/parser": { - "version": "7.29.12", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.12.tgz", - "integrity": "sha512-WJ7JBp/Q4+z/ImydtI7jS6NVco5++632ExBemSX+Ysb+G1lCwQ5BVo3SY+jGGOcZXI4ZccbZSUSJLNBW6eEpJg==", + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.15.tgz", + "integrity": "sha512-RpKWyisHoP81twtSCgmE02iU0RnPcq1DN5bBEbpUePrjA9Q3wXhufnCJrrayPpoZieqFh3zyZQqwtSK0gGccRA==", "license": "MIT", "dependencies": { - "@babel/types": "^7.29.11" + "@babel/types": "^7.29.15" }, "bin": { "parser": "bin/babel-parser.js" @@ -423,9 +424,9 @@ } }, "node_modules/@babel/plugin-proposal-export-default-from": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-export-default-from/-/plugin-proposal-export-default-from-7.29.7.tgz", - "integrity": "sha512-p+G5BNXDcy3bOXplhY4HybQ1GxH3i2Tppmdm/3epyRu2VgJJZuUlZ61MqRTg582Q7ZLBdP7fePYvsumSEkMxcQ==", + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-export-default-from/-/plugin-proposal-export-default-from-7.29.15.tgz", + "integrity": "sha512-G9TJJ6ZTxhCGuFlYXB2W8ljMXhkaR2nZEV1DVetC0LgwaibQSVBHq2gD4ldxsfT4/vSzy/V2ARtCmGz1NUlSZg==", "dev": true, "license": "MIT", "dependencies": { @@ -591,9 +592,9 @@ } }, "node_modules/@babel/plugin-transform-block-scoping": { - "version": "7.29.12", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.29.12.tgz", - "integrity": "sha512-nEreZBofjfd6FG621xe9Rk3+tMGBXf1nAuFrR6NUGF67fkQbSQf3NrbRuhgWRn+zb0qcy9XVok1GVFI/t9wWVQ==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.29.16.tgz", + "integrity": "sha512-LRtPA4rwT4hkuvoFk/0l32acTAiXVOf58JwsyMcf+3vgKGu7aThsPb/ukWyWv5JfaLe3+StkkkxYLB8peYdZcQ==", "dev": true, "license": "MIT", "dependencies": { @@ -623,17 +624,17 @@ } }, "node_modules/@babel/plugin-transform-classes": { - "version": "7.29.11", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.29.11.tgz", - "integrity": "sha512-f8kTDM/nTvpLeafb+TJ4jboFr/Y3BbC+QzgPpPGzSKJqWLnj9LW0WLqv4XKA11LX5sr+EgvLE6Ix3YsCEusodw==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.29.16.tgz", + "integrity": "sha512-Tg70GK4ewfbGY6sfu8/F+S5rv6Wc8iJFirHbvZ494JCOcSjr5qPXLJbfZruMCsLh8FLqdpWq1S/9gzVpnt9ssw==", "license": "MIT", "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", - "@babel/helper-compilation-targets": "^7.29.7", + "@babel/helper-compilation-targets": "^7.29.13", "@babel/helper-globals": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-replace-supers": "^7.29.7", - "@babel/traverse": "^7.29.10" + "@babel/helper-replace-supers": "^7.29.16", + "@babel/traverse": "^7.29.16" }, "engines": { "node": ">=6.9.0" @@ -643,14 +644,14 @@ } }, "node_modules/@babel/plugin-transform-destructuring": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.29.7.tgz", - "integrity": "sha512-iPX8aD6H9zV5s7ZsqTdNocPN/MGQ5sSMnElKrktxjJRMnB2jN/1p2+R7GkfD6CAYoVFqy5A4XnSIUeGgJzIWpg==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.29.13.tgz", + "integrity": "sha512-X2meXB39NOPPmmshSRJzyd50hX9uCzbscNQwVCjLCtq363PZIJFFxJIeZPpgAewC570vpdeGIHTcltwd0QUlJg==", "dev": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.29.7", - "@babel/traverse": "^7.29.7" + "@babel/traverse": "^7.29.13" }, "engines": { "node": ">=6.9.0" @@ -677,14 +678,14 @@ } }, "node_modules/@babel/plugin-transform-for-of": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.29.7.tgz", - "integrity": "sha512-zeSIHh0+E1Um1WJRXCFlHQYu2ieJNdivLLjlBEp+dIBu3S51n+SZZmIXjxnItw6pz56Cn+KvK68BIBVsxq2JiQ==", + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.29.15.tgz", + "integrity": "sha512-JHa0QfVEG23goXwV1j8HT31EEIZ8nUJBKNTJ/UU1AwfRqY+7xXBEg9M61Tbz60sxKomE2MQBA3vovEbplL964Q==", "dev": true, "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7" + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.13" }, "engines": { "node": ">=6.9.0" @@ -694,12 +695,12 @@ } }, "node_modules/@babel/plugin-transform-modules-commonjs": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.29.7.tgz", - "integrity": "sha512-j0vCldybPC5b5dwCQOJ21uKtHzt7hxLygJTg9eF1ScfaikEDNfzn94XoW5Fi+seBR0nCyL23xaBFFkq7dTM8XQ==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.29.16.tgz", + "integrity": "sha512-bQgsq3VGgNZLoEaT3EA5cH9t2cEbzZWrmaEBPCeDG4SnaXjO0WKycCbOfl/+QKxy8mnja+O+5/YhL/EHdEZrmw==", "license": "MIT", "dependencies": { - "@babel/helper-module-transforms": "^7.29.7", + "@babel/helper-module-transforms": "^7.29.16", "@babel/helper-plugin-utils": "^7.29.7" }, "engines": { @@ -758,13 +759,13 @@ } }, "node_modules/@babel/plugin-transform-optional-chaining": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-7.29.7.tgz", - "integrity": "sha512-6GM1dhvK3gNODkXcEcMCOLEDCLSoZ/sBbro2Ax8HURyasQ4NshagQixkRFdh5niI6E4gmA/jYI/4aT7rRos3ZQ==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-7.29.16.tgz", + "integrity": "sha512-A5R2n4cBu9Rr7jLcu+2N1O9TrbiFOKyD07XU7j7dqYjwRWan3oQEwviEgyf73mLu4Nn/aHg1CJSYot6fsVcoSg==", "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7" + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.13" }, "engines": { "node": ">=6.9.0" @@ -791,14 +792,14 @@ } }, "node_modules/@babel/plugin-transform-private-property-in-object": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-7.29.7.tgz", - "integrity": "sha512-+BNo06dnrzdNNqCm1X6YUaVv0DKk8Q+JYcoZfOkLhYWNCXzlwTSRq8zGWayT1csjcpNXV9CQTBRRbmTLZac5cA==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-7.29.16.tgz", + "integrity": "sha512-GcfGRfUwktYNUN4WAzWBxP2dnXzbgWMGHTlH9pQgoRo6hJ3gGo6KVmVLrW+ziOf9uia8UeXHm0+jOCSgXGCy7A==", "dev": true, "license": "MIT", "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", - "@babel/helper-create-class-features-plugin": "^7.29.7", + "@babel/helper-create-class-features-plugin": "^7.29.16", "@babel/helper-plugin-utils": "^7.29.7" }, "engines": { @@ -877,9 +878,9 @@ } }, "node_modules/@babel/plugin-transform-regenerator": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.29.8.tgz", - "integrity": "sha512-0UpIXPtdDtMXfnV2OJAVMLpj3H/92vmkA6lpSRakmycJvj3VUy6Xs1dM8tXRugupykr5WB+LpiVl0J8LMVg2mg==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.29.16.tgz", + "integrity": "sha512-p3vpw4U5390ReOyc6s0dBMsf7EolYD0t5v8uJ+EXo6Bu39bgh2WLRAgvhiBhWEGyLjzRLMJN/itLg0z0ENWzEQ==", "dev": true, "license": "MIT", "dependencies": { @@ -914,9 +915,9 @@ } }, "node_modules/@babel/plugin-transform-runtime/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", "dev": true, "license": "ISC", "bin": { @@ -954,15 +955,15 @@ } }, "node_modules/@babel/plugin-transform-typescript": { - "version": "7.29.9", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.29.9.tgz", - "integrity": "sha512-FFwIwzU+7SCOuxxV4YtJql6T9981ZVTm+FHO5GhVsRqCTdy0WwrEZh3l42ARpXruJUDGOptdduHW6Zr7pNPLNg==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.29.16.tgz", + "integrity": "sha512-wH2gjNIPmkinpBNvOys3boTY/8uyzP1ER8EbmURCf7auJ+DSWboT2OiOs4DBFbsGM0k9hAburELJqw/d4xvgWA==", "license": "MIT", "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", - "@babel/helper-create-class-features-plugin": "^7.29.7", + "@babel/helper-create-class-features-plugin": "^7.29.16", "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.13", "@babel/plugin-syntax-typescript": "^7.29.7" }, "engines": { @@ -989,16 +990,16 @@ } }, "node_modules/@babel/preset-typescript": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-7.29.7.tgz", - "integrity": "sha512-/Foi8vKY2EVbed/1eZx0gJEEwHAIxogrySI7rULcRIvhZzbvoE/b5qG5Ghc0WKAFKOHA9SD1x7RsFlOYdutIiQ==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-7.29.16.tgz", + "integrity": "sha512-WBpmSQeUIhKvQ6fDgXhuAAvNLgOQbtKlZJHCOw/1Ptq9Tv74bRoex3g5H7f0voMKWmqnAht0dKXKIrn8lQyaKA==", "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "@babel/plugin-syntax-jsx": "^7.29.7", - "@babel/plugin-transform-modules-commonjs": "^7.29.7", - "@babel/plugin-transform-typescript": "^7.29.7" + "@babel/plugin-transform-modules-commonjs": "^7.29.16", + "@babel/plugin-transform-typescript": "^7.29.16" }, "engines": { "node": ">=6.9.0" @@ -1008,9 +1009,9 @@ } }, "node_modules/@babel/runtime": { - "version": "7.29.10", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz", - "integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.16.tgz", + "integrity": "sha512-LKBjGopxrQE0aFucNL69OyyyF143MOWUULEOftU3oCgyD35Sy84UUpVnt/sNvTb7ZmCyALSt7om+fojlW35zYQ==", "license": "MIT", "engines": { "node": ">=6.9.0" @@ -1031,17 +1032,17 @@ } }, "node_modules/@babel/traverse": { - "version": "7.29.12", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.12.tgz", - "integrity": "sha512-MscXe/NAZcOkYEsRajHZFt3ynsb22PUi6CTrp5U7+RYycR9By84mn9mFN54YgfITiqK4hFx3Ju3tZSyzfpS5ew==", + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.16.tgz", + "integrity": "sha512-a16ah9dTLOLUq5BL7NElJ7keefg/276vgfTfExDf1PizddYboqRnQXDTooVPb0VArIqrKe8KLlghnTxlZFEZtQ==", "license": "MIT", "dependencies": { "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.12", + "@babel/generator": "^7.29.16", "@babel/helper-globals": "^7.29.7", - "@babel/parser": "^7.29.12", + "@babel/parser": "^7.29.15", "@babel/template": "^7.29.7", - "@babel/types": "^7.29.11", + "@babel/types": "^7.29.15", "debug": "^4.3.1" }, "engines": { @@ -1049,12 +1050,12 @@ } }, "node_modules/@babel/types": { - "version": "7.29.11", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.11.tgz", - "integrity": "sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ==", + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.15.tgz", + "integrity": "sha512-/XKpKDakL//LZ66bq1XsZOswuqeI5MZqPLDu18o3XdkU1fNJ7bdPtzgnc4ZNS+bBGHV0FJG8jjb8SwcC3nNVQQ==", "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^7.29.11", + "@babel/helper-string-parser": "^7.29.15", "@babel/helper-validator-identifier": "^7.29.7" }, "engines": { @@ -1093,19 +1094,19 @@ } }, "node_modules/@formatjs/intl-getcanonicallocales": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/@formatjs/intl-getcanonicallocales/-/intl-getcanonicallocales-3.3.0.tgz", - "integrity": "sha512-ndj9jw/LHAftSe34D/A6+lj3Y7GHVfPEZ6FZP2wjd8/beYeh3d1sjlSpZSBlzegSKS3U3mUEIzLCpI0+jKNT6w==", + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/@formatjs/intl-getcanonicallocales/-/intl-getcanonicallocales-3.4.2.tgz", + "integrity": "sha512-b0Ywtqh1DS5bc3NXqm2VMbtDN9mYQPVVIEDPkxIi8SlV5eq7NkE0ZET0IHDWgl1lLh74hjGJv8iPy7D/y/SNNA==", "license": "MIT" }, "node_modules/@formatjs/intl-locale": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/@formatjs/intl-locale/-/intl-locale-5.4.1.tgz", - "integrity": "sha512-whv9X0efjqLE6VJGXVr5+mwFfCTiPYDq6/jw5aZEwBJIlTyHJjKLGzXEzyjwmarzYCzLMFhepKYf/XeTR/Z8qA==", + "version": "5.5.2", + "resolved": "https://registry.npmjs.org/@formatjs/intl-locale/-/intl-locale-5.5.2.tgz", + "integrity": "sha512-4v0ZW2KQ8874I4L74zTqk1sWwxogxJzvJV3asaIyyAOJAK5Rjwe9r+SGmLm2HleDq60reuaSRxuiUKIFalWlUw==", "license": "MIT", "dependencies": { - "@formatjs/intl-getcanonicallocales": "3.3.0", - "@formatjs/intl-supportedvaluesof": "2.5.0" + "@formatjs/intl-getcanonicallocales": "3.4.2", + "@formatjs/intl-supportedvaluesof": "3.1.2" } }, "node_modules/@formatjs/intl-localematcher": { @@ -1138,23 +1139,44 @@ } }, "node_modules/@formatjs/intl-segmenter": { - "version": "12.3.0", - "resolved": "https://registry.npmjs.org/@formatjs/intl-segmenter/-/intl-segmenter-12.3.0.tgz", - "integrity": "sha512-Q/IoZDlZpe4eWsol1+O6AKPt1DW9lRoCiVQkYH/ht/eKuO+ty8uXzh/pMtVdoeoyhKjq+H4/Czyta4s5LYYrxg==", + "version": "12.3.4", + "resolved": "https://registry.npmjs.org/@formatjs/intl-segmenter/-/intl-segmenter-12.3.4.tgz", + "integrity": "sha512-p3kBH2FsygwXa3xfK4KmATTF8nN52SxCAZtQw3JWxcornSXS/85OkLuntqjTpBmk8LNxtMTnyNZgtKT6AOkpLg==", "license": "MIT", "dependencies": { - "@formatjs/intl-localematcher": "0.10.0" + "@formatjs/intl-localematcher": "0.10.3" + } + }, + "node_modules/@formatjs/intl-segmenter/node_modules/@formatjs/fast-memoize": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/@formatjs/fast-memoize/-/fast-memoize-3.1.8.tgz", + "integrity": "sha512-Y9YFFfeBDkAWmLWD3LVNHbHlyELsP2lYRNoY6+QhtPh1/ujCiX5QYBzAqe0cWdkCxKVezHLt0qjWz1veEUV7UA==", + "license": "MIT" + }, + "node_modules/@formatjs/intl-segmenter/node_modules/@formatjs/intl-localematcher": { + "version": "0.10.3", + "resolved": "https://registry.npmjs.org/@formatjs/intl-localematcher/-/intl-localematcher-0.10.3.tgz", + "integrity": "sha512-qHGNMjYbewa1uteT7VFPot2+q9glcBMVRQhmQNXgNYia35Arzln7vJ4Zyj6ktm6POzRc3SW/CTAhhSnMQSFvJg==", + "license": "MIT", + "dependencies": { + "@formatjs/fast-memoize": "3.1.8" } }, "node_modules/@formatjs/intl-supportedvaluesof": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@formatjs/intl-supportedvaluesof/-/intl-supportedvaluesof-2.5.0.tgz", - "integrity": "sha512-0nL6a4aMrBVwFZX7udcuxxUtxldY/Q4KoGuQVNx4/roQqnZmOwDvzRb4DkEvtJZ3b76mk+V7zfJmm3nJycOFHQ==", + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@formatjs/intl-supportedvaluesof/-/intl-supportedvaluesof-3.1.2.tgz", + "integrity": "sha512-PKUOWdNCTmQ9JTKdvsmWYwNRb78dfkb4hKY7XqCFc5sPH2c079NTR9G6VeDEnno+BEMAowAvrQcd0fAjziUXIw==", "license": "MIT", "dependencies": { - "@formatjs/fast-memoize": "3.1.7" + "@formatjs/fast-memoize": "3.1.8" } }, + "node_modules/@formatjs/intl-supportedvaluesof/node_modules/@formatjs/fast-memoize": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/@formatjs/fast-memoize/-/fast-memoize-3.1.8.tgz", + "integrity": "sha512-Y9YFFfeBDkAWmLWD3LVNHbHlyELsP2lYRNoY6+QhtPh1/ujCiX5QYBzAqe0cWdkCxKVezHLt0qjWz1veEUV7UA==", + "license": "MIT" + }, "node_modules/@hapi/hoek": { "version": "9.3.0", "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", @@ -1231,9 +1253,9 @@ } }, "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", "license": "MIT", "engines": { "node": ">=6.0.0" @@ -1512,7 +1534,8 @@ }, "node_modules/@react-native-gpui/cli": { "version": "0.87.0-alpha.5", - "resolved": "file:../../../vendor/react-native-gpui/packages/cli", + "resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-cli-0.87.0-alpha.5.tgz", + "integrity": "sha512-UFtxDVt2+S/S4v0GRSM611jfPbE76Ah8/7F4sm/OgfxnyHFKrc6pFXlDYZvWx5i8jnH0WQESoH4azUneR62Nxw==", "dev": true, "license": "MIT", "bin": { @@ -1521,7 +1544,8 @@ }, "node_modules/@react-native-gpui/codegen": { "version": "0.87.0-alpha.2", - "resolved": "file:../../../vendor/react-native-gpui/packages/codegen", + "resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-codegen-0.87.0-alpha.2.tgz", + "integrity": "sha512-VIQDIUELddQTWI5NyAXkopzwCGtEh28LQDpNKsWn4kfomxK1uJ2/TaDjnokw7oQ6ZX/2nJL4hPsmOapvpdpgxg==", "license": "MIT", "dependencies": { "@react-native/codegen": "0.87.1" @@ -1529,7 +1553,8 @@ }, "node_modules/@react-native-gpui/core": { "version": "0.87.0-alpha.5", - "resolved": "file:../../../vendor/react-native-gpui/packages/core", + "resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-core-0.87.0-alpha.5.tgz", + "integrity": "sha512-FKLKmEe8zEENaah/i2lhA1IFzZ4C67vqk7YYY5ORXuSyBl7khSHsJjU2jB+usqZNj9/H7se06GuploXfyt90xA==", "license": "MIT", "dependencies": { "@react-native-gpui/codegen": "0.87.0-alpha.2", @@ -1543,7 +1568,8 @@ }, "node_modules/@react-native-gpui/fs": { "version": "0.0.1-alpha.1", - "resolved": "file:../../../vendor/react-native-gpui/modules/fs", + "resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-fs-0.0.1-alpha.1.tgz", + "integrity": "sha512-rY8P9oeP/b5bD4Eqyar+7HG1zii0SeqNkTRFnxrYe9kFBbWZjIlHIuI3gMJzJxeDklbGkx4P4DgpLiXQafv3rQ==", "license": "MIT", "peerDependencies": { "react-native": "0.87.x" @@ -1551,7 +1577,8 @@ }, "node_modules/@react-native-gpui/gesture-handler": { "version": "3.3.0-alpha.1", - "resolved": "file:../../../vendor/react-native-gpui/modules/gesture-handler", + "resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-gesture-handler-3.3.0-alpha.1.tgz", + "integrity": "sha512-r49zj2PVzKNdsktSFu7nr6lcHLaJLqEwU/NYMxKmoOxL3Wew4HWHIgq9wskQI30CrRAwCdwqXMbgMdTIid+GjQ==", "license": "MIT", "peerDependencies": { "react-native": "0.87.x", @@ -1562,12 +1589,14 @@ }, "node_modules/@react-native-gpui/hermes": { "version": "0.87.0-alpha.1", - "resolved": "file:../../../vendor/react-native-gpui/packages/hermes", + "resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-hermes-0.87.0-alpha.1.tgz", + "integrity": "sha512-Hn7rdXbmOi63i5u02j2dFTyBN73573tsxigu2zS1qo0jCgezc/LwAZruU3p94UQ4/GU2OIyvro3zCSvT+qzr2w==", "license": "MIT" }, "node_modules/@react-native-gpui/reanimated": { "version": "4.7.0-alpha.1", - "resolved": "file:../../../vendor/react-native-gpui/modules/reanimated", + "resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-reanimated-4.7.0-alpha.1.tgz", + "integrity": "sha512-eclRX3zcObjBfnn6QTkIah9lqc1raoV6X4yC84AF7PZVp+5OddpXlwMxlZSVLdGxSfQ6YjOih3LphrzUNJkahA==", "license": "MIT", "peerDependencies": { "@react-native-gpui/worklets": "0.13.0-alpha.1", @@ -1578,7 +1607,8 @@ }, "node_modules/@react-native-gpui/safe-area-context": { "version": "5.10.0-alpha.0", - "resolved": "file:../../../vendor/react-native-gpui/modules/safe-area-context", + "resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-safe-area-context-5.10.0-alpha.0.tgz", + "integrity": "sha512-j+RyCz5J+rQW4FYYNCMvoQSAPnAmgI0iPcCTGmKzSwRcFEx6GZJ8UbosxW1+YbsmiL8hIdEF3baOMYFkr068ZA==", "license": "MIT", "peerDependencies": { "react-native": "0.87.x", @@ -1587,7 +1617,8 @@ }, "node_modules/@react-native-gpui/screens": { "version": "4.28.0-alpha.2", - "resolved": "file:../../../vendor/react-native-gpui/modules/screens", + "resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-screens-4.28.0-alpha.2.tgz", + "integrity": "sha512-ynH6vfr7kIC2tYTSpfZul1i1NKaSiVYJtNyW+/zT5lO3BfuM4Ya68nr0Zc1LUEuczqN2kWpsuQp9YulSql156Q==", "license": "MIT", "peerDependencies": { "react-native": "0.87.x", @@ -1596,7 +1627,8 @@ }, "node_modules/@react-native-gpui/svg": { "version": "15.15.0-alpha.1", - "resolved": "file:../../../vendor/react-native-gpui/modules/svg", + "resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-svg-15.15.0-alpha.1.tgz", + "integrity": "sha512-i/ZTekGbbR1ly8BRtkWBnLt/4WPCZToW54RvDJd2babcFVl7QCkaOHWKUNZQuH4RbOEyDmnMnM6YaoY2gc0fOA==", "license": "MIT", "peerDependencies": { "react-native": "0.87.x", @@ -1605,7 +1637,8 @@ }, "node_modules/@react-native-gpui/worklets": { "version": "0.13.0-alpha.1", - "resolved": "file:../../../vendor/react-native-gpui/modules/worklets", + "resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-worklets-0.13.0-alpha.1.tgz", + "integrity": "sha512-TTN9CFwirHVojJM4s6UHUPU/3qA1zdCcUrokS5gf+G9lmdpKKV3sCr7Cqpdr8MzAAC/4ohpou13JZIbnyP3dSg==", "license": "MIT", "peerDependencies": { "react-native": "0.87.x", @@ -1820,9 +1853,9 @@ } }, "node_modules/@react-native/dev-middleware/node_modules/ws": { - "version": "7.5.13", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", - "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==", + "version": "7.5.14", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.14.tgz", + "integrity": "sha512-u9Oi2nQ8SZnTUAf6spLLKF5TyqoG3Nbbrd4ai6Sjo4P24bycDewhQqtNMIg4bFpnpH/TD4qk4IuAVhT0HIIqug==", "license": "MIT", "engines": { "node": ">=8.3.0" @@ -1978,18 +2011,18 @@ } }, "node_modules/@types/node": { - "version": "26.6.6", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", - "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "version": "26.6.11", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz", + "integrity": "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==", "license": "MIT", "dependencies": { "undici-types": "~8.9.0" } }, "node_modules/@types/react": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", - "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "version": "19.3.3", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.3.tgz", + "integrity": "sha512-K8uWpJc4teiuOPdiP1umjeA9rGMgVPiXuoL66fcS1QlwBT1WMqY8PORmub9FadopIs+RCW6siYEs7Lpq+vDlog==", "license": "MIT", "dependencies": { "csstype": "^3.2.2" @@ -2005,9 +2038,9 @@ } }, "node_modules/@types/react-test-renderer": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/@types/react-test-renderer/-/react-test-renderer-19.3.0.tgz", - "integrity": "sha512-TX4p2D4Z2oigM3SXU7+QyLSUnSR0vR1S1Pfxm/qFL9nHQ3jclgi6ioGoWQmlIr1DeKRVmPJrmNlhgM0JlWlLUg==", + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/@types/react-test-renderer/-/react-test-renderer-19.3.1.tgz", + "integrity": "sha512-9AwMfeBOcXsN5kC4oAauNTOKEwqLHtc69tkJC2CihQ5fCELDwzfQvookvtyaxm6i+vc5LLD0V5OLB8arzY8Smw==", "license": "MIT", "dependencies": { "@types/react": "*" @@ -2198,9 +2231,9 @@ } }, "node_modules/babel-plugin-polyfill-corejs2/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", "dev": true, "license": "ISC", "bin": { @@ -2274,9 +2307,9 @@ "license": "MIT" }, "node_modules/baseline-browser-mapping": { - "version": "2.11.34", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.34.tgz", - "integrity": "sha512-Aqr8mA1kIvyJ3UY5YAY7ib8LSo1DmDMbMnVqGPtsKW1LxaFQFwn9Eb3yvq2fUKJsRvaXjnAV7R5osqETapzNiA==", + "version": "2.11.40", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.40.tgz", + "integrity": "sha512-WJhaQ3kW5+5BpOduI64ewvykhCyK/IHHG5jCIzivmW2nkYPRowUjs0DbBXY4CAr1LLrN7QEzZGL9727aXH9sJA==", "license": "Apache-2.0", "bin": { "baseline-browser-mapping": "dist/cli.cjs" @@ -2342,9 +2375,9 @@ } }, "node_modules/browserslist": { - "version": "4.29.5", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", - "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==", + "version": "4.29.6", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz", + "integrity": "sha512-CmVVIQ3RVc5HxYEc9X84GvxK/C8C1wH8TlKAiO7uTxF8PDwt7r8t9Qk3J9NkMOVzX5O/HbLv3yzxZg9HPrnI9w==", "funding": [ { "type": "opencollective", @@ -2361,11 +2394,11 @@ ], "license": "MIT", "dependencies": { - "baseline-browser-mapping": "^2.11.33", - "caniuse-lite": "^1.0.30001819", - "electron-to-chromium": "^1.5.464", - "node-releases": "^2.0.60", - "update-browserslist-db": "^1.3.4" + "baseline-browser-mapping": "^2.11.37", + "caniuse-lite": "^1.0.30001826", + "electron-to-chromium": "^1.5.486", + "node-releases": "^2.0.64", + "update-browserslist-db": "^1.4.0" }, "bin": { "browserslist": "cli.js" @@ -2478,9 +2511,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001820", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001820.tgz", - "integrity": "sha512-gfWD6MxqVCqAOwmODfZf7DchWvlrA+SRdNX7ceLfg3xRqe5ssjjpF7EgslC/0tiLiNTajdaNN/q8c/5u/7Gz8w==", + "version": "1.0.30001829", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001829.tgz", + "integrity": "sha512-FeVvlaVr3r+cdHIYXyZhtVkqroSYjYaoNxItxQNjusurUE+IqODawDsbzk02HJgi2RdKiaGGFm+EKbXku+yITg==", "funding": [ { "type": "opencollective", @@ -2899,9 +2932,9 @@ } }, "node_modules/csstype": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", - "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz", + "integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==", "license": "MIT" }, "node_modules/dayjs": { @@ -3057,9 +3090,9 @@ "license": "MIT" }, "node_modules/electron-to-chromium": { - "version": "1.5.472", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.472.tgz", - "integrity": "sha512-s4+nfT29b0FKpVKoaIxl2pWsoNcn7A/nMPSrxayw4T3BsmPeV2lF9Y06BsAQeMGhCTQ4nYJ5XST7jkqe4ZEqFw==", + "version": "1.5.495", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.495.tgz", + "integrity": "sha512-dZcmtNbDI5oeT9uP9Z+D7h/H5C1mvBewDTLgZgo9WgyPmqOXSt2cmoCK99evPygUOn9lyXZ4w0Eb8APrkBjqBA==", "license": "ISC" }, "node_modules/emoji-regex": { @@ -3069,9 +3102,9 @@ "license": "MIT" }, "node_modules/encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.4.tgz", + "integrity": "sha512-ImAQpWtQZKdkUxvj9CMNzB8M4IGg0DkRTZzmOHqgVFrf71JDmUacbt+iKljfIpD2yHcxI+HR76d8bwvdvtSvGA==", "license": "MIT", "engines": { "node": ">= 0.8" @@ -3266,9 +3299,9 @@ } }, "node_modules/fast-xml-builder": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.3.1.tgz", - "integrity": "sha512-pIM/1n3ntFXKYrUZwW7QCK0gAW7XY+wzj1YMIV3tLDvPj/V+zTGJK5e3/4WJfwj0qWw2ElNXiTixda/R+3YSug==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.3.2.tgz", + "integrity": "sha512-OX91VSlShLPDgRZV7tk/YQ4l8tT75QziF5Ixg8g4PFbCVPjuTWwN+yQfAxLJ0dufJpprdOd6HlM74Jhd39TcBQ==", "dev": true, "funding": [ { @@ -3283,9 +3316,9 @@ } }, "node_modules/fast-xml-parser": { - "version": "5.11.2", - "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.11.2.tgz", - "integrity": "sha512-R9iDuNrQYeQut46cn2r2wHKn4HYzVDvDm5J1wW+koZewykv0yuO2HChTYeZtrULyHIDM9cj9TUXloCsueCQUog==", + "version": "5.12.1", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.12.1.tgz", + "integrity": "sha512-wR8dO/fx+z8C5exuem1e7BKOWvjsuzvjS/tvA/Xu3Z1zQqJGcXrPzXbcAiaMgp2KjreEROcTkmnnisrcmJ2hYQ==", "dev": true, "funding": [ { @@ -3295,11 +3328,11 @@ ], "license": "MIT", "dependencies": { - "@nodable/entities": "^3.0.1", - "fast-xml-builder": "^1.2.0", - "is-unsafe": "^2.0.0", + "@nodable/entities": "^3.1.0", + "fast-xml-builder": "^1.3.2", + "is-unsafe": "^2.0.3", "path-expression-matcher": "^1.6.2", - "strnum": "^2.4.2", + "strnum": "^2.5.1", "xml-naming": "^0.3.0" }, "bin": { @@ -3587,10 +3620,10 @@ } }, "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "license": "ISC" + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "license": "BlueOak-1.0.0" }, "node_modules/has-flag": { "version": "4.0.0", @@ -3778,9 +3811,9 @@ "license": "MIT" }, "node_modules/is-core-module": { - "version": "2.17.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.17.0.tgz", - "integrity": "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==", + "version": "2.18.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.18.0.tgz", + "integrity": "sha512-qyax9fgaKOEC4qK8WZn7Q4IcoZC9RC1O1fFxRcRTq/oMMkWT/uXpqpXa12kzWR409zAt1drYN9N9BO26UmBCmw==", "dev": true, "license": "MIT", "dependencies": { @@ -3888,9 +3921,9 @@ } }, "node_modules/is-unsafe": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/is-unsafe/-/is-unsafe-2.0.2.tgz", - "integrity": "sha512-HgbIHPBH0KHHCcjLfGsCvhtPTVxjaAZlXjwdz7/GQC40SjSe4sfQsar8J5VFo8JOSbarkpV0OLG95bbaNd9aAQ==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-unsafe/-/is-unsafe-2.0.3.tgz", + "integrity": "sha512-ZBllczCCO267vgdFb6Tq3pv+LhHaCiGMdr+ZsuL+OopruAg7S+3ZDs1vD0RPC0uSrkjzbraxaGjtX1YBxjPeFQ==", "dev": true, "funding": [ { @@ -4444,9 +4477,9 @@ } }, "node_modules/metro": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/metro/-/metro-0.87.2.tgz", - "integrity": "sha512-SPdGRafxrx7pf2bNta9qvwfX6tFMxULEEDM5irfsPH+AinubUoLqZUkguJl6bwCZOVO4hOGgjr7esiSDqPjkoQ==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/metro/-/metro-0.87.3.tgz", + "integrity": "sha512-Wt0Nkme7dVf2+Iaw9Od/MchWfElFyAKCMGX2xauhctc81aIOtYkZqzSN8xtOEMTDZD2EK/h/suJbBm1Bduo3Ow==", "license": "MIT", "dependencies": { "@babel/code-frame": "^7.29.0", @@ -4454,7 +4487,7 @@ "@babel/generator": "^7.29.1", "@babel/parser": "^7.29.9", "@babel/template": "^7.28.6", - "@babel/traverse": "^7.29.0", + "@babel/traverse": "^7.29.10", "@babel/types": "^7.29.8", "accepts": "^2.0.0", "connect": "^3.6.5", @@ -4466,18 +4499,18 @@ "jest-worker": "^29.7.0", "jsc-safe-url": "^0.2.2", "lodash.throttle": "^4.1.1", - "metro-babel-transformer": "0.87.2", - "metro-cache": "0.87.2", - "metro-cache-key": "0.87.2", - "metro-config": "0.87.2", - "metro-core": "0.87.2", - "metro-file-map": "0.87.2", - "metro-resolver": "0.87.2", - "metro-runtime": "0.87.2", - "metro-source-map": "0.87.2", - "metro-symbolicate": "0.87.2", - "metro-transform-plugins": "0.87.2", - "metro-transform-worker": "0.87.2", + "metro-babel-transformer": "0.87.3", + "metro-cache": "0.87.3", + "metro-cache-key": "0.87.3", + "metro-config": "0.87.3", + "metro-core": "0.87.3", + "metro-file-map": "0.87.3", + "metro-resolver": "0.87.3", + "metro-runtime": "0.87.3", + "metro-source-map": "0.87.3", + "metro-symbolicate": "0.87.3", + "metro-transform-plugins": "0.87.3", + "metro-transform-worker": "0.87.3", "mime-types": "^3.0.1", "nullthrows": "^1.1.1", "serialize-error": "^2.1.0", @@ -4494,15 +4527,15 @@ } }, "node_modules/metro-babel-transformer": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/metro-babel-transformer/-/metro-babel-transformer-0.87.2.tgz", - "integrity": "sha512-ZAfqGp0vttJFI6k1LEw//nGgTYfyVHFjcU61Ac7aPuTSaPsT/MeOi710ODfrxWkwK/y6z45NrIejjMwPv0CnxQ==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/metro-babel-transformer/-/metro-babel-transformer-0.87.3.tgz", + "integrity": "sha512-HtbEBlMLywNWEFNNq92smarzDLUKZcqoykq9YWfkgNN7Xm8pNGMCFoaV6NAOs7OSL8biJdbaKBr1BWPD41KHeg==", "license": "MIT", "dependencies": { "@babel/core": "^7.25.2", "flow-enums-runtime": "^0.0.6", "flow-parser": "0.336.0", - "metro-cache-key": "0.87.2", + "metro-cache-key": "0.87.3", "nullthrows": "^1.1.1" }, "engines": { @@ -4510,24 +4543,24 @@ } }, "node_modules/metro-cache": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/metro-cache/-/metro-cache-0.87.2.tgz", - "integrity": "sha512-2hWZsXhEYhhzYneNH8Q/ToZZKogcHDWhXTUloiJg+p+QGLEsDx9LXadxXXHfhPDaSRc9B6VOcB0Te02dPv/tRw==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/metro-cache/-/metro-cache-0.87.3.tgz", + "integrity": "sha512-osREd4eXHIsCCIE2PQlDThtM6qSaZfY59jVdaIRUjixU6emI/RrUetoSEjdAdBoCh95C+f4O51oRgFdwRU3Q0w==", "license": "MIT", "dependencies": { "exponential-backoff": "^3.1.1", "flow-enums-runtime": "^0.0.6", "https-proxy-agent": "^7.0.5", - "metro-core": "0.87.2" + "metro-core": "0.87.3" }, "engines": { "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" } }, "node_modules/metro-cache-key": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/metro-cache-key/-/metro-cache-key-0.87.2.tgz", - "integrity": "sha512-wYtWOqRSaYlVtQe9B5YwobOFjf30IUuZZ6FqZ5cCTzisvh1varAdFCs/CGEWxBtJqe3qcgZKSi7cP4yoR0OZEQ==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/metro-cache-key/-/metro-cache-key-0.87.3.tgz", + "integrity": "sha512-GZmydYeCV/A2RNJXTEmdeoYmxG6Grq9Wj2Zqi53W+W2psc6lTTbuabNOogsTHqnUoqdF80UbO+PQSFBgwHwj+Q==", "license": "MIT", "dependencies": { "flow-enums-runtime": "^0.0.6" @@ -4537,41 +4570,41 @@ } }, "node_modules/metro-config": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/metro-config/-/metro-config-0.87.2.tgz", - "integrity": "sha512-uIlI0RMKHUXI5xEe+7HkWgk8KFDjCCx7o/G/rcyqlUVbjM7N/3rDwCuT++dqC4UzeC4Afv1jDbS+bFI8/gRlNA==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/metro-config/-/metro-config-0.87.3.tgz", + "integrity": "sha512-Y68gCZgzg3KrIRpNQAnPTyucfC0e4v7xBiaaEMZEytthqZ8G1kWyRNbwVMN0Bq4ME1kfYAqDH2aSEwEA7a/PrA==", "license": "MIT", "dependencies": { "connect": "^3.6.5", "flow-enums-runtime": "^0.0.6", "jest-validate": "^29.7.0", - "metro": "0.87.2", - "metro-cache": "0.87.2", - "metro-core": "0.87.2", - "metro-runtime": "0.87.2" + "metro": "0.87.3", + "metro-cache": "0.87.3", + "metro-core": "0.87.3", + "metro-runtime": "0.87.3" }, "engines": { "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" } }, "node_modules/metro-core": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/metro-core/-/metro-core-0.87.2.tgz", - "integrity": "sha512-VlNETRpQXXSyj6hSU5l0xOANSAvJ81wIH/QpXcJ+nPbU6qteofQ0tsYO1HbtBIj/5MwbXjcEeDca9CJ2N40VZA==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/metro-core/-/metro-core-0.87.3.tgz", + "integrity": "sha512-9aleh7DWSQpyntLnDALf86LGIg3NgDST/HEmEeR51CuiHfrzIN08aCbe9y+OAqPzFUOzgUfYMVGfgQOIbitigA==", "license": "MIT", "dependencies": { "flow-enums-runtime": "^0.0.6", "lodash.throttle": "^4.1.1", - "metro-resolver": "0.87.2" + "metro-resolver": "0.87.3" }, "engines": { "node": "^22.13.0 || ^24.3.0 || >= 26.0.0" } }, "node_modules/metro-file-map": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/metro-file-map/-/metro-file-map-0.87.2.tgz", - "integrity": "sha512-zXB6o7Oj/xVGOhHQ+dz8BIAjZqjv1S1v/sJIqqRus8XiZISNspO3DmnKWssW0Gh2XO+Sq4TAjkIuYQnBJ+lnjA==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/metro-file-map/-/metro-file-map-0.87.3.tgz", + "integrity": "sha512-onUyGnS8pkLDf6pSvu6GyETu6CPUd5IAk8Mqhn5P3WqBHexBS6bvbMMVuuc350dleA6HH6Emx//0KP5cEBUOCg==", "license": "MIT", "dependencies": { "debug": "^4.4.0", @@ -4586,9 +4619,9 @@ } }, "node_modules/metro-minify-terser": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/metro-minify-terser/-/metro-minify-terser-0.87.2.tgz", - "integrity": "sha512-+sJo/F9+Xb+duOt4xA1HgNa9FRq1dsPcdTMxVrLsT1RVvgKVuA13qMeYvhR+vdlQbuXFXIrCCDOkMphxlM2/yA==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/metro-minify-terser/-/metro-minify-terser-0.87.3.tgz", + "integrity": "sha512-9IS44WPQljNEutnDCynZa1Dol+Moj51U7lEfFEqYl0G7W8RkNURKwMq1ctibU3U7ZDS+IkLw1cfVsG8ytAGOfA==", "license": "MIT", "dependencies": { "flow-enums-runtime": "^0.0.6", @@ -4599,9 +4632,9 @@ } }, "node_modules/metro-resolver": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/metro-resolver/-/metro-resolver-0.87.2.tgz", - "integrity": "sha512-5irxge/5uJ+OqPwdj4GARrSmJVMVj4mkgn5WKv83X7NP9MH/AedDStqvZaMwEaiH/mQFm5W4GDbEqx1OJJeLBg==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/metro-resolver/-/metro-resolver-0.87.3.tgz", + "integrity": "sha512-O82NUc8KRKem9oxMzADl6a9u7H2hpKt4I9vfApZsBYmc3wlwP4UgffZJZxd8P0KrbY5CYkgW30ou17/W+ujM4w==", "license": "MIT", "dependencies": { "flow-enums-runtime": "^0.0.6" @@ -4611,9 +4644,9 @@ } }, "node_modules/metro-runtime": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/metro-runtime/-/metro-runtime-0.87.2.tgz", - "integrity": "sha512-68CLgcufiI162xyhSyI3Ax1kYPmUxKV6mt7Ll6gNd6Lb5ayJ+tQ1G7G+02Hda2ekV88Vq5zTsJ5hv2qpAhZa8g==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/metro-runtime/-/metro-runtime-0.87.3.tgz", + "integrity": "sha512-2kGsO2ouF5V8m9teQcrmCbH9HonkxgNpyFq1t36x78Xc2fZ3CsE/sKnntEmHS7Uj8bgeObjaXa92caTRk0D6ww==", "license": "MIT", "dependencies": { "@babel/runtime": "^7.25.0", @@ -4624,18 +4657,19 @@ } }, "node_modules/metro-source-map": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/metro-source-map/-/metro-source-map-0.87.2.tgz", - "integrity": "sha512-6jqJ/b+Ho36JmiI1pAjSWvnuDHqLCkF6Pjv4bxyjESu+18TrqvPwOS82QXQwyrr+haoc5kVnguxrgRWFhuqbEg==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/metro-source-map/-/metro-source-map-0.87.3.tgz", + "integrity": "sha512-kvgC0nIP1emXDiMLhmcy1AOxZrfPMWxrvYqOMNVXvKbObtakGXqu60WpeSVlzo3VBfXCMmZDBz1SvsP80Ug+kQ==", "license": "MIT", "dependencies": { - "@babel/traverse": "^7.29.0", + "@babel/core": "^7.25.2", + "@babel/traverse": "^7.29.10", "@babel/types": "^7.29.8", "flow-enums-runtime": "^0.0.6", "invariant": "^2.2.4", - "metro-symbolicate": "0.87.2", + "metro-symbolicate": "0.87.3", "nullthrows": "^1.1.1", - "ob1": "0.87.2", + "ob1": "0.87.3", "source-map": "^0.5.6" }, "engines": { @@ -4643,14 +4677,14 @@ } }, "node_modules/metro-symbolicate": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/metro-symbolicate/-/metro-symbolicate-0.87.2.tgz", - "integrity": "sha512-bAE3KvaYjlyOzBHE+FI7NnG57bGoW+n9Et1leevreuMXYEaIhN/CmfCh3fRuApoj5LnJg1rFlxCXaJsIc4P5Gg==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/metro-symbolicate/-/metro-symbolicate-0.87.3.tgz", + "integrity": "sha512-koHM4gA6iE7OSYACKvJCg/N/9QK6i7vrA3l4gMKtK1Z7XfQVixtWiUTqf+XTkGdVTjioHmlTF/MmG+BmfL301w==", "license": "MIT", "dependencies": { "flow-enums-runtime": "^0.0.6", "invariant": "^2.2.4", - "metro-source-map": "0.87.2", + "metro-source-map": "0.87.3", "nullthrows": "^1.1.1", "source-map": "^0.5.6", "vlq": "^1.0.0" @@ -4663,15 +4697,15 @@ } }, "node_modules/metro-transform-plugins": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/metro-transform-plugins/-/metro-transform-plugins-0.87.2.tgz", - "integrity": "sha512-pjss163wbj3G3bEANVJtzjIsHUeSP025aSlAxAla6QvwXFedD3tMDT19a9q2KRhp5OgfrDm/FbVusJuVHA0NYg==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/metro-transform-plugins/-/metro-transform-plugins-0.87.3.tgz", + "integrity": "sha512-43+RwCr2EV6KaulqxDDxt0c2hVApVQ364YY5aSNZTbsIb16kwZmUsEeKXko1fc89J5eV2xUIcR+6SKQqzQqtkg==", "license": "MIT", "dependencies": { "@babel/core": "^7.25.2", "@babel/generator": "^7.29.1", "@babel/template": "^7.28.6", - "@babel/traverse": "^7.29.0", + "@babel/traverse": "^7.29.10", "flow-enums-runtime": "^0.0.6", "nullthrows": "^1.1.1" }, @@ -4680,23 +4714,24 @@ } }, "node_modules/metro-transform-worker": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/metro-transform-worker/-/metro-transform-worker-0.87.2.tgz", - "integrity": "sha512-DLpo4Xl2vShovtqXfB1JYJPAWsWjzuLlbmWYscOr0qpshjZ8Ii6JBDEnFBOVEzeXNyRG/gr697v61N25N9YvDg==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/metro-transform-worker/-/metro-transform-worker-0.87.3.tgz", + "integrity": "sha512-XchqDAB4g1tImWOuEqHOvSMqIA4ZS1vNy38r8+vU+RvPDz9kva0oYa1S06/RDlYT0xqogQekBNA1n7/rWWzWFw==", "license": "MIT", "dependencies": { "@babel/core": "^7.25.2", "@babel/generator": "^7.29.1", "@babel/parser": "^7.29.9", "@babel/types": "^7.29.8", + "@jridgewell/sourcemap-codec": "^1.5.0", "flow-enums-runtime": "^0.0.6", - "metro": "0.87.2", - "metro-babel-transformer": "0.87.2", - "metro-cache": "0.87.2", - "metro-cache-key": "0.87.2", - "metro-minify-terser": "0.87.2", - "metro-source-map": "0.87.2", - "metro-transform-plugins": "0.87.2", + "metro": "0.87.3", + "metro-babel-transformer": "0.87.3", + "metro-cache": "0.87.3", + "metro-cache-key": "0.87.3", + "metro-minify-terser": "0.87.3", + "metro-source-map": "0.87.3", + "metro-transform-plugins": "0.87.3", "nullthrows": "^1.1.1" }, "engines": { @@ -4749,9 +4784,9 @@ } }, "node_modules/metro/node_modules/ws": { - "version": "7.5.13", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", - "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==", + "version": "7.5.14", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.14.tgz", + "integrity": "sha512-u9Oi2nQ8SZnTUAf6spLLKF5TyqoG3Nbbrd4ai6Sjo4P24bycDewhQqtNMIg4bFpnpH/TD4qk4IuAVhT0HIIqug==", "license": "MIT", "engines": { "node": ">=8.3.0" @@ -4883,9 +4918,9 @@ "license": "MIT" }, "node_modules/node-releases": { - "version": "2.0.63", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.63.tgz", - "integrity": "sha512-6li2QanLsAXpIH2R6j77MzRyvOyrvdTqlKtO4CgBdHGNvN99ZZfyxszHc5o5+IZBWD5u6Hzwg83JoGXmqZNG9Q==", + "version": "2.0.66", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.66.tgz", + "integrity": "sha512-uSMWN9/XtWzxaE0d9ZNHe00Hda6028AXH3WRjTsK71neiPCSeL5nGSD9MXTQX/6Qx0k7Op1AyyinmIUw9fBzrg==", "license": "MIT", "engines": { "node": ">=18" @@ -4937,9 +4972,9 @@ "license": "MIT" }, "node_modules/ob1": { - "version": "0.87.2", - "resolved": "https://registry.npmjs.org/ob1/-/ob1-0.87.2.tgz", - "integrity": "sha512-KLdsz/5QTEG2Y7lhxEOYNBZX7MkD0m3Cu11B72TBJ6sCKGXYatLJ/4WtMKoGLalQyozFYDutPRpsWpDRRA+E4g==", + "version": "0.87.3", + "resolved": "https://registry.npmjs.org/ob1/-/ob1-0.87.3.tgz", + "integrity": "sha512-g3UMN6od3PKhcpNFKZ1tj4pVFMHcipEGLiUdyGbm5yAQAwSvZA5VQBpvoyC2y8s1oFZ5oTknFxxEFaYPRi2M+Q==", "license": "MIT", "dependencies": { "flow-enums-runtime": "^0.0.6" @@ -4949,9 +4984,9 @@ } }, "node_modules/object-inspect": { - "version": "1.13.4", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", - "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.14.0.tgz", + "integrity": "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ==", "dev": true, "license": "MIT", "engines": { @@ -5222,12 +5257,6 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/pretty-format/node_modules/react-is": { - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", - "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", - "license": "MIT" - }, "node_modules/promise": { "version": "8.3.0", "resolved": "https://registry.npmjs.org/promise/-/promise-8.3.0.tgz", @@ -5334,9 +5363,9 @@ } }, "node_modules/react-devtools-core/node_modules/ws": { - "version": "7.5.13", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", - "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==", + "version": "7.5.14", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.14.tgz", + "integrity": "sha512-u9Oi2nQ8SZnTUAf6spLLKF5TyqoG3Nbbrd4ai6Sjo4P24bycDewhQqtNMIg4bFpnpH/TD4qk4IuAVhT0HIIqug==", "license": "MIT", "engines": { "node": ">=8.3.0" @@ -5366,6 +5395,12 @@ "react": ">=17.0.0" } }, + "node_modules/react-is": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "license": "MIT" + }, "node_modules/react-native": { "version": "0.87.1", "resolved": "https://registry.npmjs.org/react-native/-/react-native-0.87.1.tgz", @@ -5536,9 +5571,9 @@ } }, "node_modules/react-native/node_modules/ws": { - "version": "7.5.13", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", - "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==", + "version": "7.5.14", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.14.tgz", + "integrity": "sha512-u9Oi2nQ8SZnTUAf6spLLKF5TyqoG3Nbbrd4ai6Sjo4P24bycDewhQqtNMIg4bFpnpH/TD4qk4IuAVhT0HIIqug==", "license": "MIT", "engines": { "node": ">=8.3.0" @@ -5620,15 +5655,15 @@ "license": "MIT" }, "node_modules/regexpu-core": { - "version": "6.5.3", - "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-6.5.3.tgz", - "integrity": "sha512-E8VgUoSK+LMQrLboDxavm76MTBGrQhx9RiNuomRmYnZ10Uw12HrI8fkxOOncktb2hBpzIZ9SV/347euQHG5z+g==", + "version": "6.5.4", + "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-6.5.4.tgz", + "integrity": "sha512-VpdamrZ9bw4YmvMZfTA3Yg8IHU9Guvg21bonvgjC4l3KfBkOqCPJesHakz7cQeE4Vh4zz4r4Gy6igAcnJxZv9g==", "license": "MIT", "dependencies": { "regenerate": "^1.5.0", "regenerate-unicode-properties": "^10.3.0", "regjsgen": "^0.8.0", - "regjsparser": "^0.13.0", + "regjsparser": "^0.14.0", "unicode-match-property-ecmascript": "^2.0.0", "unicode-match-property-value-ecmascript": "^2.2.1" }, @@ -5643,9 +5678,9 @@ "license": "MIT" }, "node_modules/regjsparser": { - "version": "0.13.4", - "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.13.4.tgz", - "integrity": "sha512-EWV80YgFaVgFrjGCAsV7oybp4GOxbls5RzBg8OB0nKEVXsBJR1JlV8Di1JhCROg3MzTfe1RI8yitIm1eOs68iA==", + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.14.1.tgz", + "integrity": "sha512-IeYboCLG1KBNRksrZQIZ1SV5KVWZiR0ikFokOcA0n63vLvlaFvCsfxN+fd4aXwL0KW3YD+ByRzIgo9ZAHdbldw==", "license": "BSD-2-Clause", "dependencies": { "jsesc": "~3.1.0" @@ -5671,14 +5706,14 @@ "license": "ISC" }, "node_modules/resolve": { - "version": "1.22.13", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.13.tgz", - "integrity": "sha512-Dj/cW9zBV2aRj6XzCxuGIs3ESZKv02jixne3q6jFZYZ3/Tg09gHHviSMDL4kObh9pqSahdRHEnDoaP2gn8YLhA==", + "version": "1.22.14", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.14.tgz", + "integrity": "sha512-1ZjYvR9sbkiwC5+9QHetqW5HmA2pHRMaoupD01t2HlYnV/vydC2zPwLixhsMieSWVZt0JJRg5LVIk0Ow1D/TrA==", "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "is-core-module": "^2.17.0", + "is-core-module": "^2.18.0", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, @@ -5786,9 +5821,9 @@ "license": "MIT" }, "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -5837,9 +5872,9 @@ "license": "MIT" }, "node_modules/send/node_modules/encodeurl": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.1.tgz", - "integrity": "sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.3.tgz", + "integrity": "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==", "license": "MIT", "engines": { "node": ">= 0.8" @@ -5895,9 +5930,9 @@ } }, "node_modules/serve-static/node_modules/encodeurl": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.1.tgz", - "integrity": "sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.3.tgz", + "integrity": "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==", "license": "MIT", "engines": { "node": ">= 0.8" @@ -6144,9 +6179,9 @@ } }, "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.4.0.tgz", + "integrity": "sha512-r8azg21Y67ckRmeG0hHol5CeDXMs4ZFkFT6eXMO39hX7khvJcopBcYTCeWZ0rQXkMoPh8lVdbjmsOMGL8krxRQ==", "dev": true, "license": "MIT", "dependencies": { @@ -6263,9 +6298,9 @@ } }, "node_modules/terser": { - "version": "5.51.2", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz", - "integrity": "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==", + "version": "5.51.4", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.4.tgz", + "integrity": "sha512-VPi1CkDvCWLGUVIToctNBG+NdHbSXwOPjHJnQ3pdB0XknaldnI76wSkAFOGxV2ZdkzOP5d6gpQ5c58XvDghRvw==", "license": "BSD-2-Clause", "dependencies": { "@jridgewell/source-map": "^0.3.3", @@ -6467,9 +6502,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", - "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.4.0.tgz", + "integrity": "sha512-WPJuOnjI9FWDct4fB+ej4Mz8opLaw5CDcZ2t44tFZ0vIQVYWzBhWR3mkixuUj/A7+vY4V9+ApOZ2YYLwdgq46w==", "funding": [ { "type": "opencollective", @@ -6602,9 +6637,9 @@ } }, "node_modules/ws": { - "version": "6.2.6", - "resolved": "https://registry.npmjs.org/ws/-/ws-6.2.6.tgz", - "integrity": "sha512-XTrf1gv7kXoVf1hbC3PAyAiPgR8Wz1blcrYIjEsUmr08BLksT41R8KbjmS9408C2ERx7v1JDLD/BkpLEttjfKA==", + "version": "6.2.7", + "resolved": "https://registry.npmjs.org/ws/-/ws-6.2.7.tgz", + "integrity": "sha512-Zf1UJBlTF9DUHCi6LG990YXwa3modcX6VsSQbZPzdp45f5aqSVmzMFJL+SliIpb4M719yQGYIw5D3CKYEmmB3g==", "dev": true, "license": "MIT", "dependencies": { @@ -6612,9 +6647,9 @@ } }, "node_modules/xml-naming": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.3.0.tgz", - "integrity": "sha512-ghig2TBE/H11aOVgmahA3MhimvkBr6JIYknH/Dhdk10nXwdbIqBJsbfMxpvFPG8bAw77gN29aQWvKpmVoPlvPQ==", + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.3.1.tgz", + "integrity": "sha512-EJ9yNAfjrIz2z7chbVlj4CD3HkPxXNPD6U6LzhKEfIFlRmEHtl7CN6C0qdPGL4hplTuj2wePPgIZN8aklE/2Og==", "dev": true, "funding": [ { diff --git a/packages/app/gpui/package.json b/packages/app/gpui/package.json index 840fc5a6f1..dca1c0bac6 100644 --- a/packages/app/gpui/package.json +++ b/packages/app/gpui/package.json @@ -10,16 +10,16 @@ "@formatjs/intl-numberformat": "^9.5.0", "@formatjs/intl-pluralrules": "^6.4.0", "@formatjs/intl-segmenter": "^12.3.0", - "@react-native-gpui/codegen": "file:../../../vendor/react-native-gpui/packages/codegen", - "@react-native-gpui/core": "file:../../../vendor/react-native-gpui/packages/core", - "@react-native-gpui/fs": "file:../../../vendor/react-native-gpui/modules/fs", - "@react-native-gpui/gesture-handler": "file:../../../vendor/react-native-gpui/modules/gesture-handler", - "@react-native-gpui/hermes": "file:../../../vendor/react-native-gpui/packages/hermes", - "@react-native-gpui/reanimated": "file:../../../vendor/react-native-gpui/modules/reanimated", - "@react-native-gpui/safe-area-context": "file:../../../vendor/react-native-gpui/modules/safe-area-context", - "@react-native-gpui/screens": "file:../../../vendor/react-native-gpui/modules/screens", - "@react-native-gpui/svg": "file:../../../vendor/react-native-gpui/modules/svg", - "@react-native-gpui/worklets": "file:../../../vendor/react-native-gpui/modules/worklets", + "@react-native-gpui/codegen": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-codegen-0.87.0-alpha.2.tgz", + "@react-native-gpui/core": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-core-0.87.0-alpha.5.tgz", + "@react-native-gpui/fs": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-fs-0.0.1-alpha.1.tgz", + "@react-native-gpui/gesture-handler": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-gesture-handler-3.3.0-alpha.1.tgz", + "@react-native-gpui/hermes": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-hermes-0.87.0-alpha.1.tgz", + "@react-native-gpui/reanimated": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-reanimated-4.7.0-alpha.1.tgz", + "@react-native-gpui/safe-area-context": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-safe-area-context-5.10.0-alpha.0.tgz", + "@react-native-gpui/screens": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-screens-4.28.0-alpha.2.tgz", + "@react-native-gpui/svg": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-svg-15.15.0-alpha.1.tgz", + "@react-native-gpui/worklets": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-worklets-0.13.0-alpha.1.tgz", "@react-native/assets-registry": "^0.87.1", "react": "19.2.3", "react-native": "0.87.1", @@ -32,7 +32,7 @@ }, "devDependencies": { "@react-native-community/cli": "20.2.0", - "@react-native-gpui/cli": "file:../../../vendor/react-native-gpui/packages/cli", + "@react-native-gpui/cli": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-2/react-native-gpui-cli-0.87.0-alpha.5.tgz", "@react-native/babel-preset": "0.87.1", "@react-native/metro-config": "0.87.1", "typescript": "^5.8.3" diff --git a/scripts/gpui.mjs b/scripts/gpui.mjs index 6bf3448e3c..27217198c1 100644 --- a/scripts/gpui.mjs +++ b/scripts/gpui.mjs @@ -1,14 +1,17 @@ -import { spawnSync } from "node:child_process"; -import { fileURLToPath } from "node:url"; +import { execFileSync, spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import os from "node:os"; import path from "node:path"; -import { cpSync, mkdirSync, readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; const root = fileURLToPath(new URL("..", import.meta.url)); const project = path.join(root, "packages/app/gpui"); const action = process.argv[2] ?? "run"; const extra = process.argv.slice(3); const artifacts = path.join(root, ".artifacts/gpui"); +const localRuntimePackages = ["cli", "codegen", "core", "hermes"]; mkdirSync(artifacts, { recursive: true }); + function run(command, args, env = {}) { const result = spawnSync(command, args, { cwd: project, @@ -23,21 +26,64 @@ function run(command, args, env = {}) { if (result.error) throw result.error; if (result.status !== 0) process.exit(result.status ?? 1); } -if (action === "install") { - run("npm", ["install", "--workspaces=false"]); - // npm copies file: packages. Refresh vendored source even when its version - // did not change, so edits to the native renderer reach the next Cargo build. - const manifest = JSON.parse(readFileSync(path.join(project, "package.json"), "utf8")); - for (const [name, spec] of Object.entries({ - ...manifest.dependencies, - ...manifest.devDependencies, - })) { - if (spec.startsWith("file:")) - cpSync(path.resolve(project, spec.slice(5)), path.join(project, "node_modules", name), { - recursive: true, - preserveTimestamps: true, - }); + +function parseLocalInstallArg(args) { + let localRepo = process.env.PASEO_GPUI_LOCAL?.trim() || ""; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--local") { + localRepo = args[++i] ?? ""; + if (!localRepo) throw new Error("--local requires a path to a react-native-gpui checkout"); + } else if (arg.startsWith("--local=")) { + localRepo = arg.slice("--local=".length); + } else { + throw new Error(`Unknown gpui:install argument: ${arg}`); + } } + return localRepo ? path.resolve(localRepo) : null; +} + +function installLocalRuntime(localRepo) { + for (const name of localRuntimePackages) { + const manifestPath = path.join(localRepo, "packages", name, "package.json"); + if (!existsSync(manifestPath)) { + throw new Error(`Missing local package manifest: ${manifestPath}`); + } + } + + const stage = mkdtempSync(path.join(os.tmpdir(), "paseo-gpui-local-")); + try { + for (const name of localRuntimePackages) { + const pkgDir = path.join(localRepo, "packages", name); + const output = execFileSync("npm", ["pack", "--json", "--pack-destination", stage], { + cwd: pkgDir, + encoding: "utf8", + shell: process.platform === "win32", + stdio: ["ignore", "pipe", "pipe"], + }); + const [packed] = JSON.parse(output); + if (!packed?.filename) { + throw new Error(`npm pack produced no tarball for local package ${name}`); + } + const destDir = path.join(project, "node_modules", "@react-native-gpui", name); + rmSync(destDir, { recursive: true, force: true }); + mkdirSync(destDir, { recursive: true }); + execFileSync( + "tar", + ["-xzf", path.join(stage, packed.filename), "--strip-components=1", "-C", destDir], + { stdio: "inherit" }, + ); + process.stdout.write(`Installed local @react-native-gpui/${name} from ${pkgDir}\n`); + } + } finally { + rmSync(stage, { recursive: true, force: true }); + } +} + +if (action === "install") { + const localRepo = parseLocalInstallArg(extra); + run("npm", ["ci", "--workspaces=false"]); + if (localRepo) installLocalRuntime(localRepo); } else if (action === "bundle") { run("node", [ "node_modules/react-native/cli.js", diff --git a/vendor/react-native-gpui/LICENSE b/vendor/react-native-gpui/LICENSE deleted file mode 100644 index 149a0f8321..0000000000 --- a/vendor/react-native-gpui/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Streetwriters - -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/vendor/react-native-gpui/UPSTREAM b/vendor/react-native-gpui/UPSTREAM deleted file mode 100644 index 4f03c5cdd1..0000000000 --- a/vendor/react-native-gpui/UPSTREAM +++ /dev/null @@ -1,59 +0,0 @@ -Repository: https://github.com/streetwriters/react-native-gpui -Revision: ad502d80d828fed59c468eb15a90b1fa03d21125 -Modules repository: https://github.com/streetwriters/react-native-gpui-modules -Modules revision: 7435b7f4dfdaa001f10099214ccbb23fe81f9c51 -License: MIT; see LICENSE and the licenses retained within packages. - -Snapshot: packages/{cli,codegen,core,hermes} from react-native-gpui, and -modules/{fs,gesture-handler,reanimated,safe-area-context,screens,svg,worklets} -from react-native-gpui-modules (where upstream moved modules/ in 897fe925). -Examples, tester, testing package, website, unused modules, and unused -fonts/vector-icons ports are not included. Upstream tests and build sources -within retained packages stay with the snapshot so contributors can inspect -and modify the renderer. - -Local patches (all other retained files match the revisions above): -- packages/core/src-gpui/Libraries/Components/Pressable/Pressable.desktop.js: - supply hovered to style and children render props; upstream now carries the - GpuiJsEngine.h W3C hover flag and metro.config.js self-import bypass. - native.test.ts covers callbacks, render props, and nested row hover using - appearance-regression.fixture.js. -- packages/cli/src/package-desktop.js: ad-hoc sign macOS packages so their - bundle resources are sealed, with templates/adhoc.entitlements.plist allowing - bundled ad-hoc dylibs under hardened runtime; covered by package-desktop.test.js. -- packages/cli/src/commands.js: preserve Cargo's generated dSYM symlink so - subsequent builds can replace it; dereference when copying symbols into the - distribution instead of linking back into the build tree. Covered by - commands.test.js. -- packages/core/ReactCxxPlatform/react/io/WebSocketModule.{cpp,h}: release - failed and closed connections on the JS thread. Keeping terminal clients - exhausts file descriptors during daemon retries; deleting them on the IO - thread would join that same thread. websocket.native.test.ts exercises the - real RN API against a loopback peer. ReactGpui/rn-gpui-sys/build.rs tracks - these sources so incremental builds include the fix. -- packages/core/ReactGpui/rn-gpui-sys/build.rs: pass Cargo's - MACOSX_DEPLOYMENT_TARGET to CMake. Otherwise source builds default to the - installed SDK's version even when the app targets an older macOS release. - Also exports `RN_GPUI_LOOM_RENDERER_BUILT` so `store.rs` knows whether Loom - or Fabric owns `topLayout`. -- packages/core/src-gpui/Libraries/NativeComponent/BaseViewConfig.desktop.ts, - packages/core/ReactGpui/rn-gpui-sys/src/lib.rs, - packages/core/ReactGpui/rn-gpui-sys/cpp/{MountBatchBuilder,LoomViewProps}.cpp, - packages/core/ReactGpui/rn-gpui/src/{bootstrap,view_props,store,host}.rs: - restore standard React Native `onLayout` behavior across all components - (Text/Paragraph, TextInput, Image, View, ScrollView, etc.) instead of - hardcoding `topLayout` to `View` and scroll containers. Add `onLayout: true` - to desktop `validAttributes` so JS forwards the listener flag; let Fabric's - `ShadowTree::emitLayoutEvents` emit `topLayout` without double-dispatching - in `store.rs` (selected explicitly via `LayoutEventOwner` at store - construction from `rn_gpui_sys::LOOM_RENDERER`), and propagate `on_layout` - into `ViewPropsFlat` so Loom dispatches `topLayout` for any laid-out node - with `on_layout` set. Covered by `native.test.ts` and `store.rs` unit tests. - -(Upstream now includes box-none pointer pass-through, uniform rounded border -decoration, GpuiJsEngine.h hover flag, metro.config.js self-import bypass, and -StatusBar.desktop.js.) - -GPUI itself remains a pinned Cargo git dependency. Hermes/React Native prebuilt -libraries are downloaded by upstream build tooling; this is not an offline or -fully source-built distribution. diff --git a/vendor/react-native-gpui/modules/fs/CHANGELOG.md b/vendor/react-native-gpui/modules/fs/CHANGELOG.md deleted file mode 100644 index 26e23c208e..0000000000 --- a/vendor/react-native-gpui/modules/fs/CHANGELOG.md +++ /dev/null @@ -1,17 +0,0 @@ -# Changelog - -All notable changes to `@react-native-gpui/fs` are listed here. Each version's section becomes the notes of its GitHub release. - -## Unreleased - -- Honour `RN_GPUI_APP_DATA_DIR`: when set and non-empty, `paths.appData`, `paths.appCache` and `paths.appLogs` become `$RN_GPUI_APP_DATA_DIR/`, `.../cache/` and `.../logs/`, so several copies of an app can run with separate data. - -## 0.0.1-alpha.1 - 2026-11-12 - -- Add `upload(url, path, options)`, which streams a file, or a range of one, as an HTTP request body in small blocks, reports progress, honours an `AbortSignal` and resolves with the response status, headers and the start of its body. -- Add `download(url, path, options)`, which streams an HTTP response to a file through `.part`, reports progress, honours an `AbortSignal` and rejects on a non-2xx status. - -## 0.0.1-alpha.0 - 2026-11-01 - -- First release. -- File system access for desktop apps. diff --git a/vendor/react-native-gpui/modules/fs/LICENSE b/vendor/react-native-gpui/modules/fs/LICENSE deleted file mode 100644 index 149a0f8321..0000000000 --- a/vendor/react-native-gpui/modules/fs/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Streetwriters - -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/vendor/react-native-gpui/modules/fs/README.md b/vendor/react-native-gpui/modules/fs/README.md deleted file mode 100644 index 4ef8aa4e9a..0000000000 --- a/vendor/react-native-gpui/modules/fs/README.md +++ /dev/null @@ -1,41 +0,0 @@ -# @react-native-gpui/fs - -Our own module: a file system API for desktop apps, shaped like Node's `node:fs`, with file dialogs and the operating system's well-known folders. - -Part of [react-native-gpui](https://github.com/streetwriters/react-native-gpui), React Native for macOS, Windows and Linux. - -## Install - -```sh -npm install @react-native-gpui/fs -``` - -## Usage - -```js -import fs, { dialog, paths } from '@react-native-gpui/fs'; - -const text = fs.readFileSync(`${paths.documents}/notes.txt`, 'utf8'); -await fs.promises.writeFile( - `${paths.appData}/state.json`, - JSON.stringify(state), -); - -const [file] = await dialog.open({ - filters: [{ name: 'Text', extensions: ['txt'] }], -}); -``` - -The default export has the synchronous, callback and promise forms of the common `node:fs` calls, with Node's encodings, `Stats`, `Dirent` and error codes. The module runs on its own thread, so slow files never block JavaScript or the interface. - -## Separate app data - -Set `RN_GPUI_APP_DATA_DIR` to a non-empty folder to run several copies of an app side by side with separate data, without overriding `HOME`. `paths.appData` becomes `$RN_GPUI_APP_DATA_DIR/`, `paths.appCache` `$RN_GPUI_APP_DATA_DIR/cache/` and `paths.appLogs` `$RN_GPUI_APP_DATA_DIR/logs/`; the other paths are unchanged. - -## Documentation - -[File system](docs/file-system.md) - -## License - -MIT. See [LICENSE](LICENSE). diff --git a/vendor/react-native-gpui/modules/fs/desktop/Cargo.toml b/vendor/react-native-gpui/modules/fs/desktop/Cargo.toml deleted file mode 100644 index 20de64c796..0000000000 --- a/vendor/react-native-gpui/modules/fs/desktop/Cargo.toml +++ /dev/null @@ -1,29 +0,0 @@ -[package] -name = "rn-gpui-fs" -version = "0.1.0" -edition = "2021" - -[dependencies] -rn-gpui-module = { version = "0.1" } -# Dialogs with file-type filters and a default name on all three platforms, using -# the XDG portal on Linux so no GTK is required. -rfd = "0.15" -# The standard cross-platform watcher. -notify = "6" -# Well-known folders, which differ per platform in ways not worth re-deriving. -dirs = "5" -# `utimes` sets both timestamps of an existing file; `std` cannot. -filetime = "0.2" -# `mkdtemp` with Node's retry-on-collision behaviour. -tempfile = "3" -# `chmod` by descriptor, and the errno constants the error mapping reads. -libc = "0.2" -# `realpath` without the `\\?\` prefix on Windows. -dunce = "1" -# Streams a download; rustls with the system certificate store, as the upload module does. -ureq = { version = "3", default-features = false, features = ["rustls", "platform-verifier"] } -# Hands a download's result back to the async method. -futures = "0.3" - -[build-dependencies] -rn-gpui-module-build = { version = "0.1" } \ No newline at end of file diff --git a/vendor/react-native-gpui/modules/fs/desktop/build.rs b/vendor/react-native-gpui/modules/fs/desktop/build.rs deleted file mode 100644 index dc70db9bb3..0000000000 --- a/vendor/react-native-gpui/modules/fs/desktop/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - rn_gpui_module_build::generate(&["../src/NativeFs.ts"]); -} diff --git a/vendor/react-native-gpui/modules/fs/desktop/src/dialogs.rs b/vendor/react-native-gpui/modules/fs/desktop/src/dialogs.rs deleted file mode 100644 index caac6cd206..0000000000 --- a/vendor/react-native-gpui/modules/fs/desktop/src/dialogs.rs +++ /dev/null @@ -1,394 +0,0 @@ -//! The native pickers, Finder/Explorer reveal, and "open with the default app". -//! -//! `rfd` owns the dialogs, so the platform differences (AppKit panels, the -//! Windows common dialogs, the XDG portal on Linux) stay out of this crate. All -//! of `rfd`'s dialog entry points are blocking, which is acceptable here: the -//! module has a thread of its own (`THREAD = Own`), so a panel left open blocks -//! neither JS nor a frame. -//! -//! # Open question: dialogs on macOS and the main thread -//! -//! The design flags that macOS may require the panel to be created on the main -//! thread, and that this has to be confirmed under GPUI's run loop before it can -//! be called done. What `rfd` 0.15's blocking API actually does on macOS is -//! dispatch the panel onto the main queue when the process already has a running -//! `NSApplication`, run it inline when the caller is already on the main thread, -//! and panic when neither holds. This module is on its own thread, so the first -//! branch is the one that applies, and the call should hop to the main thread and -//! block this module's thread until the panel closes. -//! -//! That is the theory, and it is **not yet verified** under GPUI's run loop. The -//! spike is: run the app, open a dialog from JS, and check that the panel -//! appears, that no main-thread warning is logged, that the module thread -//! resumes when it closes, and that the app does not deadlock while the panel is -//! up. If any of that fails, the fallback is the one the design names: a second -//! module, `GpuiFsDialogs`, with `THREAD = Main`, holding only the two pickers; -//! the rest of this module stays off the main thread. Attaching the panel to the -//! calling window (a sheet on macOS) is a further step that needs a host -//! function exposing the active window's raw handle for `rfd`'s `set_parent`, -//! which does not exist yet either. - -use std::path::{Path, PathBuf}; -use std::process::Command; - -use rn_gpui_module::ModuleError; - -use crate::errors; -use crate::{DialogFilter, OpenDialogOptions, SaveDialogOptions}; - -/// The open picker. An empty list means the user cancelled, which is what the JS -/// layer expects; a cancelled dialog is not a failure. -pub fn show_open(options: OpenDialogOptions) -> Result, ModuleError> { - let dialog = configured( - options.title.as_deref(), - options.default_path.as_deref(), - &options.filters, - ); - - let picked = if options.directory { - // A folder picker cannot return files, and `pick_folder` selects a - // single folder — rfd's blocking folder call has no multi-select mode. - // So `multiple` is honoured only as far as the platform allows: a - // caller asking for `{ directory: true, multiple: true }` gets at most - // one path, which is better than refusing the call outright. - dialog.pick_folder().into_iter().collect() - } else if options.multiple { - dialog.pick_files().unwrap_or_default() - } else { - dialog.pick_file().into_iter().collect() - }; - - Ok(utf8_paths(picked)) -} - -/// The save picker. `None` means the user cancelled; no file is created here -/// either way, the caller decides what to write. -pub fn show_save(options: SaveDialogOptions) -> Result, ModuleError> { - let (_, from_path) = split_default_path(options.default_path.as_deref()); - // `defaultName` wins over the name implied by `defaultPath`, but a path - // ending in a file name is still the only hint a caller may give. - let name = options - .default_name - .filter(|name| !name.trim().is_empty()) - .or(from_path); - - let mut dialog = configured( - options.title.as_deref(), - options.default_path.as_deref(), - &options.filters, - ); - if let Some(name) = name { - dialog = dialog.set_file_name(name); - } - - let picked = dialog.save_file(); - // The picker never writes, so a chosen name the bridge cannot represent is - // reported as "nothing chosen" rather than as an error the user has no way - // to act on; the alternative is a file the caller would try to write at a - // path JS could not have named. - Ok(picked.as_deref().and_then(utf8_path)) -} - -/// Shows `path` in the platform's file manager, selected where the platform has -/// a verb for it. -pub fn reveal(path: String) -> Result<(), ModuleError> { - ensure_exists(&path)?; - run(reveal_command(Path::new(&path)), &path) -} - -/// Opens `path` with whatever the platform associates with it. -pub fn open_external(path: String) -> Result<(), ModuleError> { - ensure_exists(&path)?; - run(open_external_command(Path::new(&path)), &path) -} - -/// A dialog carrying everything the three calls configure the same way: title, -/// starting directory, and the extension filters. -fn configured( - title: Option<&str>, - default_path: Option<&str>, - filters: &[DialogFilter], -) -> rfd::FileDialog { - let mut dialog = rfd::FileDialog::new(); - if let Some(title) = title { - dialog = dialog.set_title(title); - } - if let Some(directory) = split_default_path(default_path).0 { - dialog = dialog.set_directory(directory); - } - for filter in filters { - // An empty extension list carries no information, and on some backends - // a filter is applied as an allow-list, which would hide every file. - if !filter.extensions.is_empty() { - dialog = dialog.add_filter(filter.name.as_str(), &filter.extensions); - } - } - dialog -} - -/// Splits `defaultPath` into the directory a picker should open in, and the file -/// name to prefill when the path names a file rather than a folder. -/// -/// The two pickers need different halves: the open dialog only starts in the -/// directory, the save dialog also offers the name. -fn split_default_path(default_path: Option<&str>) -> (Option, Option) { - let Some(raw) = default_path.map(str::trim).filter(|path| !path.is_empty()) else { - return (None, None); - }; - let path = Path::new(raw); - - let is_directory = match std::fs::metadata(path) { - Ok(metadata) => metadata.is_dir(), - // A save dialog is usually given a path that does not exist yet, so fall - // back to the spelling: a trailing separator promises a directory, and - // anything else is a proposed file name whose parent is the start. - Err(_) => ends_with_separator(raw), - }; - - if is_directory { - (Some(path.to_path_buf()), None) - } else { - ( - path.parent() - .filter(|parent| !parent.as_os_str().is_empty()) - .map(Path::to_path_buf), - path.file_name() - .and_then(|name| name.to_str()) - .map(str::to_string), - ) - } -} - -/// Whether a path is spelled as a directory on any of the platforms this module -/// runs on, so a Windows path still splits correctly when read elsewhere. -fn ends_with_separator(path: &str) -> bool { - path.ends_with('/') || path.ends_with('\\') -} - -/// The picked paths as strings, dropping any the bridge cannot represent. -/// -/// A Unix file name need not be UTF-8, but JS can only hold strings. Failing the -/// whole selection because one of several files has an unusual name would throw -/// away the files the user can use, so the others are returned instead. -fn utf8_paths(paths: Vec) -> Vec { - paths - .into_iter() - .filter_map(|path| utf8_path(&path)) - .collect() -} - -fn utf8_path(path: &Path) -> Option { - path.to_str().map(str::to_string) -} - -/// Fails with the same code `stat` would before a platform command can turn the -/// problem into an opaque non-zero exit. -fn ensure_exists(path: &str) -> Result<(), ModuleError> { - // `symlink_metadata` rather than `metadata`: a dangling symlink is still a - // row in Finder or Explorer, so revealing it is meaningful. - std::fs::symlink_metadata(path) - .map(|_| ()) - .map_err(|error| errors::from_io(error, path)) -} - -/// A command line, kept separate from running it so the platform branches can be -/// asserted on without opening anything. -#[derive(Debug, Clone, PartialEq, Eq)] -struct CommandSpec { - program: &'static str, - args: Vec, -} - -/// The command that reveals `path` in the platform's file manager. -fn reveal_command(path: &Path) -> CommandSpec { - let shown = path.to_string_lossy().into_owned(); - - #[cfg(target_os = "macos")] - { - // `open -R` is the only thing that selects the item rather than opening - // its containing folder. - CommandSpec { - program: "open", - args: vec!["-R".to_string(), shown], - } - } - - #[cfg(target_os = "windows")] - { - // `/select,` is a single argument, comma included. - // - // Note: explorer.exe is known to return exit code 1 even when it does - // open the window, which the non-zero check below would report as a - // failure. That needs a check on a Windows machine; if it does bite, - // this branch should treat a successful spawn as success instead of - // reading the exit code. - CommandSpec { - program: "explorer", - args: vec![format!("/select,{shown}")], - } - } - - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - { - // `xdg-open` has no portable "select this item" verb, so the containing - // folder is the closest equivalent. A path with no parent is its own - // directory and is opened as it is. - let folder = path.parent().unwrap_or(path); - CommandSpec { - program: "xdg-open", - args: vec![folder.to_string_lossy().into_owned()], - } - } -} - -/// The command that opens `path` with the platform's default application. -fn open_external_command(path: &Path) -> CommandSpec { - let shown = path.to_string_lossy().into_owned(); - - #[cfg(target_os = "macos")] - { - CommandSpec { - program: "open", - args: vec![shown], - } - } - - #[cfg(target_os = "windows")] - { - // `start` reads its first quoted argument as the window title, so the - // empty string is required for a path containing spaces to survive. - CommandSpec { - program: "cmd", - args: vec!["/C".to_string(), "start".to_string(), String::new(), shown], - } - } - - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - { - CommandSpec { - program: "xdg-open", - args: vec![shown], - } - } -} - -/// Runs a command and turns a refusal into a Node-shaped error. -/// -/// `Command` is used without a shell, so a path is one argument no matter what -/// characters it contains; quoting and escaping are the platform's problem, not -/// a shell's. -fn run(spec: CommandSpec, path: &str) -> Result<(), ModuleError> { - let status = Command::new(spec.program) - .args(&spec.args) - .status() - // The program itself could not be started (missing, or not executable), - // which is an I/O failure on the path the caller asked about. - .map_err(|error| errors::from_io(error, path))?; - - if status.success() { - return Ok(()); - } - Err(errors::invalid( - "EIO", - format!( - "EIO: i/o error, {path} ({} exited with {status})", - spec.program - ), - )) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_default_path_that_names_a_file_splits_into_parent_and_name() { - let file = std::env::temp_dir().join("rn-gpui-fs-dialog-default.txt"); - let (directory, name) = split_default_path(Some(&file.to_string_lossy())); - assert_eq!(directory.as_deref(), Some(std::env::temp_dir().as_path())); - assert_eq!(name.as_deref(), Some("rn-gpui-fs-dialog-default.txt")); - } - - #[test] - fn a_default_path_that_names_an_existing_directory_stays_a_directory() { - let directory = std::env::temp_dir(); - let (found, name) = split_default_path(Some(&directory.to_string_lossy())); - assert_eq!(found, Some(directory)); - assert_eq!(name, None); - } - - #[test] - fn a_bare_file_name_has_no_directory_to_open_in() { - let (directory, name) = split_default_path(Some("rn-gpui-fs-report.csv")); - assert_eq!(directory, None); - assert_eq!(name.as_deref(), Some("rn-gpui-fs-report.csv")); - } - - #[test] - fn a_trailing_separator_marks_a_path_that_does_not_exist_as_a_directory() { - let missing = std::env::temp_dir().join("rn-gpui-fs-not-created"); - let spelled = format!("{}/", missing.to_string_lossy()); - let (directory, name) = split_default_path(Some(&spelled)); - assert_eq!(directory, Some(missing)); - assert_eq!(name, None); - } - - #[test] - fn no_default_path_means_no_directory_and_no_name() { - assert_eq!(split_default_path(None), (None, None)); - assert_eq!(split_default_path(Some(" ")), (None, None)); - } - - #[test] - fn reveal_targets_the_platform_file_manager() { - let spec = reveal_command(Path::new("/tmp/example.txt")); - #[cfg(target_os = "macos")] - { - assert_eq!(spec.program, "open"); - assert_eq!(spec.args, ["-R", "/tmp/example.txt"]); - } - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - { - assert_eq!(spec.program, "xdg-open"); - // Only the folder, because xdg-open cannot select an item in it. - assert_eq!(spec.args, ["/tmp"]); - } - #[cfg(target_os = "windows")] - { - assert_eq!(spec.program, "explorer"); - assert_eq!(spec.args, ["/select,/tmp/example.txt"]); - } - } - - #[test] - fn open_external_hands_the_path_to_the_default_application() { - let spec = open_external_command(Path::new("/tmp/example.txt")); - assert_eq!( - spec.args.last().map(String::as_str), - Some("/tmp/example.txt") - ); - #[cfg(target_os = "macos")] - { - assert_eq!(spec.program, "open"); - assert_eq!(spec.args.len(), 1); - } - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - assert_eq!(spec.program, "xdg-open"); - #[cfg(target_os = "windows")] - { - assert_eq!(spec.program, "cmd"); - // `/C start "" `: the empty argument is the title `start` - // would otherwise take the path for. - assert_eq!(&spec.args[..3], ["/C", "start", ""]); - } - } - - #[test] - fn a_path_with_spaces_is_still_a_single_argument() { - let spec = open_external_command(Path::new("/tmp/two words.txt")); - assert_eq!( - spec.args.last().map(String::as_str), - Some("/tmp/two words.txt") - ); - } -} diff --git a/vendor/react-native-gpui/modules/fs/desktop/src/dirs.rs b/vendor/react-native-gpui/modules/fs/desktop/src/dirs.rs deleted file mode 100644 index 251c2967bd..0000000000 --- a/vendor/react-native-gpui/modules/fs/desktop/src/dirs.rs +++ /dev/null @@ -1,363 +0,0 @@ -//! Listing, creating and removing directories, and `mkdtemp`. -//! -//! `readdir` returns every entry as a plain `{name, kind, parentPath}` object, -//! which the JS layer turns into `Dirent` instances; there is no per-directory -//! cursor to hold open because the whole listing crosses the bridge at once. - -use std::fs; -use std::path::{Path, PathBuf}; - -use rn_gpui_module::ModuleError; - -use crate::errors; -use crate::module::kind; -use crate::DirEntry; - -pub async fn readdir(path: String, recursive: bool) -> Result, ModuleError> { - readdir_sync(path, recursive) -} - -pub async fn mkdir(path: String, recursive: bool, mode: f64) -> Result<(), ModuleError> { - create_dir(&path, recursive, mode) -} - -pub async fn rm(path: String, recursive: bool, force: bool) -> Result<(), ModuleError> { - remove(&path, recursive, force) -} - -pub async fn mkdtemp(prefix: String) -> Result { - let directory = tempfile::Builder::new() - .prefix(&prefix) - .tempdir_in(std::env::temp_dir()) - .map_err(|error| errors::from_io(error, &prefix))?; - // The caller asked for a directory to keep, so it must outlive this frame; - // dropping the guard would delete it again. - Ok(path_string(directory.keep())) -} - -pub fn readdir_sync(path: String, recursive: bool) -> Result, ModuleError> { - let entries = list(Path::new(&path))?; - if !recursive { - return Ok(entries); - } - let mut collected = entries; - // Depth-first, appending each level as it is reached. Iterative rather than - // recursive: a deep tree should cost heap, not stack. - let mut pending: Vec = collected - .iter() - .filter(|entry| entry.kind == kind::DIRECTORY) - .map(|entry| Path::new(&entry.parent_path).join(&entry.name)) - .collect(); - while let Some(directory) = pending.pop() { - let children = list(&directory)?; - pending.extend( - children - .iter() - .filter(|entry| entry.kind == kind::DIRECTORY) - .map(|entry| Path::new(&entry.parent_path).join(&entry.name)), - ); - collected.extend(children); - } - Ok(collected) -} - -pub fn mkdir_sync(path: String, recursive: bool, mode: f64) -> Result { - create_dir(&path, recursive, mode)?; - Ok(true) -} - -pub fn rm_sync(path: String, recursive: bool, force: bool) -> Result { - remove(&path, recursive, force)?; - Ok(true) -} - -/// The direct children of `path`, in the order the file system lists them. -/// -/// `DirEntry::file_type` does not follow symbolic links, so a link is reported -/// as a link rather than as whatever it points at. -fn list(path: &Path) -> Result, ModuleError> { - let name = path_string(path.to_path_buf()); - let iterator = fs::read_dir(path).map_err(|error| errors::from_io(error, &name))?; - let mut entries = Vec::new(); - for entry in iterator { - let entry = entry.map_err(|error| errors::from_io(error, &name))?; - let file_type = entry - .file_type() - .map_err(|error| errors::from_io(error, &name))?; - entries.push(DirEntry { - name: entry.file_name().to_string_lossy().into_owned(), - kind: entry_kind(&file_type), - parent_path: name.clone(), - }); - } - Ok(entries) -} - -fn entry_kind(file_type: &fs::FileType) -> f64 { - if file_type.is_file() { - kind::FILE - } else if file_type.is_dir() { - kind::DIRECTORY - } else if file_type.is_symlink() { - kind::SYMLINK - } else { - kind::OTHER - } -} - -fn create_dir(path: &str, recursive: bool, mode: f64) -> Result<(), ModuleError> { - if recursive { - // `create_dir_all` succeeds on an existing directory, which is what - // Node's `{recursive: true}` promises. - return fs::create_dir_all(path).map_err(|error| errors::from_io(error, path)); - } - #[cfg(unix)] - { - use std::os::unix::fs::DirBuilderExt as _; - let mut builder = fs::DirBuilder::new(); - builder.mode(crate::module::mode(mode)); - builder - .create(path) - .map_err(|error| errors::from_io(error, path)) - } - // Windows has no mode for a new directory, and `create_dir` would reject - // the `DirBuilder` extension that only exists on Unix. - #[cfg(not(unix))] - { - let _ = mode; - fs::create_dir(path).map_err(|error| errors::from_io(error, path)) - } -} - -fn remove(path: &str, recursive: bool, force: bool) -> Result<(), ModuleError> { - // `symlink_metadata`, so a link is removed as a link instead of acting on - // its target. - let metadata = match fs::symlink_metadata(path) { - Ok(metadata) => metadata, - Err(error) if force && errors::code_for(&error) == "ENOENT" => return Ok(()), - Err(error) => return Err(errors::from_io(error, path)), - }; - if recursive && metadata.is_dir() { - return fs::remove_dir_all(path).map_err(|error| errors::from_io(error, path)); - } - if metadata.is_dir() { - // `remove_dir` fails with ENOTEMPTY on Unix and a folder-not-empty error - // on Windows, which the mapping turns into the same code; removing a - // file with it reports what Node calls ENOTDIR. - fs::remove_dir(path).map_err(|error| errors::from_io(error, path)) - } else { - fs::remove_file(path).map_err(|error| errors::from_io(error, path)) - } -} - -fn path_string(path: PathBuf) -> String { - path.to_string_lossy().into_owned() -} - -#[cfg(test)] -mod tests { - use super::*; - use tempfile::TempDir; - - /// The async wrappers never suspend, so polling once with a no-op waker is - /// enough and keeps the tests independent of a runtime. - fn block_on(future: F) -> F::Output { - let mut future = std::pin::pin!(future); - let waker = std::task::Waker::noop(); - let mut context = std::task::Context::from_waker(waker); - // One poll, no loop: these helpers do their work inline, so a `Pending` - // would mean the helper is not synchronous after all, which the test - // should fail loudly on rather than spin. - match future.as_mut().poll(&mut context) { - std::task::Poll::Ready(value) => value, - std::task::Poll::Pending => panic!("the wrappers are synchronous"), - } - } - - fn tempdir() -> TempDir { - TempDir::new().expect("a temporary directory") - } - - fn text(path: &Path) -> String { - path.to_string_lossy().into_owned() - } - - /// The listed paths, with separators normalised to `/`. - /// - /// The entries themselves carry the platform separator, which on Windows is - /// `\`; building the expected path with `/` and comparing would test the - /// separator rather than the listing. - fn names(entries: &[DirEntry]) -> Vec { - let mut names: Vec = entries - .iter() - .map(|entry| format!("{}/{}", entry.parent_path, entry.name).replace('\\', "/")) - .collect(); - names.sort(); - names - } - - fn tree(root: &Path) { - fs::create_dir_all(root.join("nested").join("deep")).expect("nested"); - fs::write(root.join("top.txt"), b"top").expect("seed"); - fs::write(root.join("nested").join("middle.txt"), b"middle").expect("seed"); - fs::write(root.join("nested").join("deep").join("leaf.txt"), b"leaf").expect("seed"); - } - - #[test] - fn readdir_lists_direct_children_only() { - let dir = tempdir(); - tree(dir.path()); - - let entries = readdir_sync(text(dir.path()), false).expect("readdir"); - // `names` normalises separators, so the expected paths are built from a - // normalised root rather than the platform one. - let root = text(dir.path()).replace('\\', "/"); - assert_eq!( - names(&entries), - vec![format!("{root}/nested"), format!("{root}/top.txt")] - ); - - let top = entries - .iter() - .find(|entry| entry.name == "top.txt") - .expect("top.txt"); - assert_eq!(top.kind, kind::FILE); - assert_eq!(top.parent_path, text(dir.path())); - let nested = entries - .iter() - .find(|entry| entry.name == "nested") - .expect("nested"); - assert_eq!(nested.kind, kind::DIRECTORY); - } - - #[test] - fn readdir_recursive_reaches_every_descendant() { - let dir = tempdir(); - tree(dir.path()); - - let entries = block_on(readdir(text(dir.path()), true)).expect("readdir"); - // Two entries per directory, three directories deep. - assert_eq!(entries.len(), 5); - let listed = names(&entries); - let root = text(dir.path()).replace('\\', "/"); - assert!(listed.contains(&format!("{root}/nested/deep/leaf.txt"))); - assert!(listed.contains(&format!("{root}/nested/deep"))); - - let deep = entries - .iter() - .find(|entry| entry.name == "deep") - .expect("deep"); - assert_eq!( - deep.parent_path, - text(&dir.path().join("nested")), - "parentPath is the containing directory" - ); - } - - #[cfg(unix)] - #[test] - fn readdir_reports_a_link_as_a_link() { - let dir = tempdir(); - let target = dir.path().join("target.txt"); - fs::write(&target, b"x").expect("seed"); - std::os::unix::fs::symlink(&target, dir.path().join("link.txt")).expect("symlink"); - - let entries = readdir_sync(text(dir.path()), false).expect("readdir"); - let link = entries - .iter() - .find(|entry| entry.name == "link.txt") - .expect("link.txt"); - assert_eq!(link.kind, kind::SYMLINK); - } - - #[test] - fn mkdir_with_recursive_creates_the_chain_and_accepts_an_existing_dir() { - let dir = tempdir(); - let nested = dir.path().join("a").join("b").join("c"); - - block_on(mkdir(text(&nested), true, f64::from(0o755u32))).expect("mkdir"); - assert!(nested.is_dir()); - - let again = mkdir_sync(text(&nested), true, f64::from(0o755u32)).expect("mkdir again"); - assert!(again, "recursive mkdir succeeds when the path exists"); - } - - #[test] - fn mkdir_without_recursive_fails_with_eexist() { - let dir = tempdir(); - let path = dir.path().join("single"); - assert!(mkdir_sync(text(&path), false, f64::from(0o755u32)).expect("mkdir")); - assert!(path.is_dir()); - - let error = - block_on(mkdir(text(&path), false, f64::from(0o755u32))).expect_err("mkdir twice"); - assert_eq!(error.code.as_deref(), Some("EEXIST")); - - let missing_parent = text(&dir.path().join("no").join("such").join("dir")); - let error = - mkdir_sync(missing_parent, false, f64::from(0o755u32)).expect_err("missing parent"); - assert_eq!(error.code.as_deref(), Some("ENOENT")); - } - - #[test] - fn rm_force_ignores_a_missing_path() { - let dir = tempdir(); - let missing = text(&dir.path().join("absent")); - - block_on(rm(missing.clone(), false, true)).expect("rm force"); - assert!(rm_sync(missing.clone(), true, true).expect("rm sync force")); - - let error = block_on(rm(missing, false, false)).expect_err("rm without force"); - assert_eq!(error.code.as_deref(), Some("ENOENT")); - } - - #[test] - fn rm_removes_a_file_and_a_tree() { - let dir = tempdir(); - let file = dir.path().join("one.txt"); - fs::write(&file, b"x").expect("seed"); - block_on(rm(text(&file), false, false)).expect("rm file"); - assert!(!file.exists()); - - let root = dir.path().join("tree"); - tree(&root); - assert!(rm_sync(text(&root), true, false).expect("rm tree")); - assert!(!root.exists()); - } - - #[test] - fn rm_without_recursive_refuses_a_non_empty_directory() { - let dir = tempdir(); - let root = dir.path().join("tree"); - tree(&root); - - let error = block_on(rm(text(&root), false, false)).expect_err("non-empty"); - assert_eq!(error.code.as_deref(), Some("ENOTEMPTY")); - assert!(root.exists()); - } - - #[test] - fn mkdtemp_creates_a_random_directory_with_the_prefix() { - let created = block_on(mkdtemp("rn-gpui-fs-".to_string())).expect("mkdtemp"); - let path = Path::new(&created); - let name = path - .file_name() - .expect("the returned path names a directory") - .to_string_lossy() - .into_owned(); - - assert!(name.starts_with("rn-gpui-fs-"), "name was {name}"); - assert!(name.len() > "rn-gpui-fs-".len(), "the rest is random"); - assert!(path.is_dir()); - assert_eq!(path.parent(), Some(std::env::temp_dir().as_path())); - - fs::remove_dir_all(path).expect("clean up"); - } - - #[test] - fn readdir_of_a_missing_directory_is_enoent() { - let dir = tempdir(); - let error = readdir_sync(text(&dir.path().join("absent")), false).expect_err("readdir"); - assert_eq!(error.code.as_deref(), Some("ENOENT")); - } -} diff --git a/vendor/react-native-gpui/modules/fs/desktop/src/download.rs b/vendor/react-native-gpui/modules/fs/desktop/src/download.rs deleted file mode 100644 index cb2db321fd..0000000000 --- a/vendor/react-native-gpui/modules/fs/desktop/src/download.rs +++ /dev/null @@ -1,329 +0,0 @@ -//! `download`: an HTTP body streamed to a file. -//! -//! A transfer is two threads. The network thread makes the request and reads the -//! body in chunks; the coordinator receives them, writes `.part` and renames -//! it onto `path` when the body is complete. Splitting them is what makes a cancel -//! prompt: the coordinator polls the cancel flag between messages, so it does not -//! wait on a socket that has gone quiet, and the network thread simply stops the -//! next time it tries to hand over a chunk. -//! -//! The module's own thread is only waited on through a channel, so a slow download -//! never blocks other file calls. - -use std::collections::HashMap; -use std::fs::File; -use std::io::{Read, Write}; -use std::path::PathBuf; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::{self, RecvTimeoutError, SyncSender}; -use std::sync::{Arc, Mutex, OnceLock}; -use std::time::{Duration, Instant}; - -use rn_gpui_module::ModuleError; -use ureq::config::Config; -use ureq::tls::{RootCerts, TlsConfig}; -use ureq::Agent; - -use crate::{ - errors, DownloadHeader, DownloadOptions, DownloadProgress, DownloadResult, RNFsModule, -}; - -const CHUNK: usize = 64 * 1024; -const PROGRESS_INTERVAL: Duration = Duration::from_millis(100); -const POLL: Duration = Duration::from_millis(25); -/// How much of a failed response's body is kept for the error. -const ERROR_BODY_LIMIT: u64 = 2048; - -pub type Downloads = Mutex>>; - -enum Message { - Head { - status: u16, - headers: Vec, - total: Option, - }, - Rejected { - status: u16, - headers: Vec, - body: String, - }, - Chunk(Vec), - End, - Failed(String), -} - -fn agent() -> &'static Agent { - static AGENT: OnceLock = OnceLock::new(); - AGENT.get_or_init(|| { - let config = Config::builder() - .http_status_as_error(false) - .timeout_connect(Some(Duration::from_secs(30))) - .tls_config( - TlsConfig::builder() - .root_certs(RootCerts::PlatformVerifier) - .build(), - ) - .build(); - Agent::new_with_config(config) - }) -} - -fn aborted() -> ModuleError { - ModuleError::with_code("ABORT_ERR", "The download was aborted") -} - -fn failed(message: impl Into) -> ModuleError { - ModuleError::with_code("ERR_DOWNLOAD", message.into()) -} - -fn id_of(value: f64) -> u32 { - value as u32 -} - -pub fn cancel(module: &RNFsModule, id: f64) -> bool { - match module.downloads.lock().expect("downloads").get(&id_of(id)) { - Some(stop) => { - stop.store(true, Ordering::SeqCst); - true - } - None => false, - } -} - -fn fetch( - url: &str, - method: &str, - headers: &[DownloadHeader], - sender: &SyncSender, - stop: &AtomicBool, -) { - let result = (|| -> Result<(), String> { - let mut builder = ureq::http::Request::builder().method(method).uri(url); - for header in headers { - builder = builder.header(header.name.as_str(), header.value.as_str()); - } - let request = builder.body(()).map_err(|e| e.to_string())?; - let mut response = agent().run(request).map_err(|e| e.to_string())?; - let status = response.status().as_u16(); - let mut listed: Vec = Vec::new(); - for (name, value) in response.headers() { - let value = String::from_utf8_lossy(value.as_bytes()).into_owned(); - match listed.iter_mut().find(|h| h.name == name.as_str()) { - Some(existing) => { - existing.value.push_str(", "); - existing.value.push_str(&value); - } - None => listed.push(DownloadHeader { - name: name.as_str().to_string(), - value, - }), - } - } - let total = response - .headers() - .get("content-length") - .and_then(|v| v.to_str().ok()) - .and_then(|v| v.parse::().ok()); - let mut reader = response.body_mut().as_reader(); - if !(200..300).contains(&status) { - let mut body = Vec::new(); - let _ = reader - .by_ref() - .take(ERROR_BODY_LIMIT) - .read_to_end(&mut body); - let _ = sender.send(Message::Rejected { - status, - headers: listed, - body: String::from_utf8_lossy(&body).into_owned(), - }); - return Ok(()); - } - if sender - .send(Message::Head { - status, - headers: listed, - total, - }) - .is_err() - { - return Ok(()); - } - loop { - if stop.load(Ordering::SeqCst) { - return Ok(()); - } - let mut chunk = vec![0u8; CHUNK]; - let read = reader.read(&mut chunk).map_err(|e| e.to_string())?; - if read == 0 { - let _ = sender.send(Message::End); - return Ok(()); - } - chunk.truncate(read); - if sender.send(Message::Chunk(chunk)).is_err() { - return Ok(()); - } - } - })(); - if let Err(message) = result { - let _ = sender.send(Message::Failed(message)); - } -} - -fn transfer( - module_events: &crate::NativeFsEvents, - id: u32, - url: String, - dest: PathBuf, - method: String, - headers: Vec, - stop: Arc, -) -> Result { - let mut partial = dest.clone().into_os_string(); - partial.push(".part"); - let partial = PathBuf::from(partial); - let shown = dest.display().to_string(); - - let (sender, receiver) = mpsc::sync_channel::(8); - { - let stop = stop.clone(); - std::thread::spawn(move || fetch(&url, &method, &headers, &sender, &stop)); - } - - let mut file: Option = None; - let mut head: Option<(u16, Vec, Option)> = None; - let mut received: u64 = 0; - let mut last_progress = Instant::now() - PROGRESS_INTERVAL; - let emit = |received: u64, total: Option| { - module_events.on_download_progress(DownloadProgress { - id: f64::from(id), - received: received as f64, - total: total.map_or(-1.0, |t| t as f64), - }); - }; - - let outcome: Result = loop { - if stop.load(Ordering::SeqCst) { - break Err(aborted()); - } - let message = match receiver.recv_timeout(POLL) { - Ok(message) => message, - Err(RecvTimeoutError::Timeout) => continue, - Err(RecvTimeoutError::Disconnected) => break Err(failed("the connection closed")), - }; - match message { - Message::Rejected { - status, - headers, - body, - } => { - break Ok(DownloadResult { - status: f64::from(status), - headers, - bytes: 0.0, - body: Some(body), - }); - } - Message::Head { - status, - headers, - total, - } => { - match File::create(&partial) { - Ok(created) => file = Some(created), - Err(e) => break Err(errors::from_io(e, &shown)), - } - head = Some((status, headers, total)); - emit(0, total); - } - Message::Chunk(bytes) => { - let Some(target) = file.as_mut() else { - break Err(failed("data arrived before the response")); - }; - if let Err(e) = target.write_all(&bytes) { - break Err(errors::from_io(e, &shown)); - } - received += bytes.len() as u64; - if last_progress.elapsed() >= PROGRESS_INTERVAL { - last_progress = Instant::now(); - emit(received, head.as_ref().and_then(|h| h.2)); - } - } - Message::End => { - let Some((status, headers, total)) = head.take() else { - break Err(failed("the response had no head")); - }; - if let Some(expected) = total { - if received != expected { - break Err(failed(format!( - "the connection closed after {received} of {expected} bytes" - ))); - } - } - if let Some(mut target) = file.take() { - if let Err(e) = target.flush() { - break Err(errors::from_io(e, &shown)); - } - } - if let Err(e) = std::fs::rename(&partial, &dest) { - break Err(errors::from_io(e, &shown)); - } - emit(received, total); - break Ok(DownloadResult { - status: f64::from(status), - headers, - bytes: received as f64, - body: None, - }); - } - Message::Failed(message) => break Err(failed(message)), - } - }; - - drop(receiver); - drop(file); - let kept = matches!(&outcome, Ok(result) if result.body.is_none()); - if !kept { - let _ = std::fs::remove_file(&partial); - } - outcome -} - -pub async fn download( - module: &RNFsModule, - url: String, - path: String, - options: DownloadOptions, -) -> Result { - let id = id_of(options.id); - let stop = Arc::new(AtomicBool::new(false)); - { - let mut running = module.downloads.lock().expect("downloads"); - if running.contains_key(&id) { - return Err(failed(format!("download {id} is already running"))); - } - running.insert(id, stop.clone()); - } - let (sender, receiver) = futures::channel::oneshot::channel(); - let events = module.events.clone(); - let method = if options.method.is_empty() { - "GET".to_string() - } else { - options.method - }; - let flag = stop.clone(); - std::thread::spawn(move || { - let result = transfer( - &events, - id, - url, - PathBuf::from(path), - method, - options.headers, - flag, - ); - let _ = sender.send(result); - }); - let result = receiver.await; - module.downloads.lock().expect("downloads").remove(&id); - result.unwrap_or_else(|_| Err(failed("the download stopped unexpectedly"))) -} diff --git a/vendor/react-native-gpui/modules/fs/desktop/src/errors.rs b/vendor/react-native-gpui/modules/fs/desktop/src/errors.rs deleted file mode 100644 index c31537a877..0000000000 --- a/vendor/react-native-gpui/modules/fs/desktop/src/errors.rs +++ /dev/null @@ -1,149 +0,0 @@ -//! Node-compatible error mapping. -//! -//! Every failure a caller sees has to look like the one Node would have raised for -//! the same call: a `code` such as `ENOENT`, and a message in Node's format. -//! `std::io::Error` gives a kind and, on Unix, a raw errno; neither is a Node code, -//! so the translation lives here once rather than at each call site. - -use rn_gpui_module::ModuleError; - -/// The Node code for an `std::io::Error`. -/// -/// The raw OS error is consulted before the kind because several distinct errnos -/// share a kind: `EEXIST` and `ENOTEMPTY` are both "already exists"-ish, and -/// `EACCES` versus `EPERM` matter to a caller deciding whether to try again. -pub fn code_for(error: &std::io::Error) -> &'static str { - #[cfg(unix)] - if let Some(errno) = error.raw_os_error() { - let code = match errno { - libc::ENOENT => "ENOENT", - libc::EACCES => "EACCES", - libc::EPERM => "EPERM", - libc::EEXIST => "EEXIST", - libc::ENOTDIR => "ENOTDIR", - libc::EISDIR => "EISDIR", - libc::ENOTEMPTY => "ENOTEMPTY", - libc::EINVAL => "EINVAL", - libc::ELOOP => "ELOOP", - libc::ENOSPC => "ENOSPC", - libc::EROFS => "EROFS", - libc::EMFILE => "EMFILE", - libc::ENAMETOOLONG => "ENAMETOOLONG", - // Windows' share-violation has no Unix equivalent; callers treat it - // as a permission problem, which is what Node's `EPERM` means there. - _ => return code_for_kind(error.kind()), - }; - return code; - } - // Windows exposes `raw_os_error` too, but its values are Win32 codes rather - // than errnos, so the kind is the better signal there, with the few Win32 - // codes whose kind is not enough named below. - #[cfg(not(unix))] - if let Some(code) = win32_code(error.raw_os_error()) { - return code; - } - code_for_kind(error.kind()) -} - -/// The Node code for a Win32 error whose `ErrorKind` is too coarse. -/// -/// `ERROR_PRIVILEGE_NOT_HELD` (1314) has no kind of its own, so it would be `EIO`. -/// Creating a symbolic link without the privilege is the case that hits it, and -/// libuv, which Node is built on, reports it as `EPERM`. -#[cfg(not(unix))] -fn win32_code(raw: Option) -> Option<&'static str> { - match raw { - Some(1314) => Some("EPERM"), - _ => None, - } -} - -fn code_for_kind(kind: std::io::ErrorKind) -> &'static str { - use std::io::ErrorKind; - match kind { - ErrorKind::NotFound => "ENOENT", - ErrorKind::PermissionDenied => "EACCES", - ErrorKind::AlreadyExists => "EEXIST", - ErrorKind::InvalidInput => "EINVAL", - ErrorKind::InvalidData => "EINVAL", - ErrorKind::WriteZero => "ENOSPC", - ErrorKind::StorageFull => "ENOSPC", - ErrorKind::ReadOnlyFilesystem => "EROFS", - ErrorKind::DirectoryNotEmpty => "ENOTEMPTY", - ErrorKind::IsADirectory => "EISDIR", - ErrorKind::NotADirectory => "ENOTDIR", - _ => "EIO", - } -} - -/// The human half of a Node error message, by code. -/// -/// Node's own table, because the tests compare against messages and because these -/// strings are what a developer recognises when a path is wrong. -fn description_for(code: &str) -> &'static str { - match code { - "ENOENT" => "no such file or directory", - "EACCES" => "permission denied", - "EPERM" => "operation not permitted", - "EEXIST" => "file already exists", - "ENOTDIR" => "not a directory", - "EISDIR" => "illegal operation on a directory", - "ENOTEMPTY" => "directory not empty", - "EINVAL" => "invalid argument", - "ELOOP" => "too many symbolic links encountered", - "ENOSPC" => "no space left on device", - "EROFS" => "read-only file system", - "EMFILE" => "too many open files", - "ENAMETOOLONG" => "name too long", - _ => "i/o error", - } -} - -/// An `std::io::Error` as the `ModuleError` JS should receive. -/// -/// `syscall` and `path` are attached by the JS layer, which knows the names the -/// caller used; the native side would have to guess between `open`, `lstat` and -/// the rest for what is already a single `stat` call. -pub fn from_io(error: std::io::Error, path: &str) -> ModuleError { - let code = code_for(&error); - ModuleError::with_code(code, format!("{code}: {}, {path}", description_for(code))) -} - -/// A failure that has no `std::io::Error`, such as a closed file descriptor. -pub fn invalid(code: &str, message: impl Into) -> ModuleError { - ModuleError::with_code(code, message) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_missing_file_is_enoent_with_nodes_message() { - let error = std::io::Error::new(std::io::ErrorKind::NotFound, "gone"); - let mapped = from_io(error, "/nope"); - assert_eq!(mapped.code.as_deref(), Some("ENOENT")); - assert_eq!(mapped.message, "ENOENT: no such file or directory, /nope"); - } - - #[test] - fn a_denied_file_is_eacces() { - let error = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "nope"); - assert_eq!(from_io(error, "/x").code.as_deref(), Some("EACCES")); - } - - #[cfg(windows)] - #[test] - fn a_missing_symlink_privilege_is_eperm_not_eio() { - // ERROR_PRIVILEGE_NOT_HELD: what `symlink_dir` returns without developer - // mode, and what Node reports as EPERM. - let error = std::io::Error::from_raw_os_error(1314); - assert_eq!(from_io(error, "C:\\link").code.as_deref(), Some("EPERM")); - } - - #[test] - fn an_unknown_failure_still_has_a_code() { - let error = std::io::Error::new(std::io::ErrorKind::Other, "odd"); - assert_eq!(from_io(error, "/x").code.as_deref(), Some("EIO")); - } -} diff --git a/vendor/react-native-gpui/modules/fs/desktop/src/files.rs b/vendor/react-native-gpui/modules/fs/desktop/src/files.rs deleted file mode 100644 index bef854b172..0000000000 --- a/vendor/react-native-gpui/modules/fs/desktop/src/files.rs +++ /dev/null @@ -1,640 +0,0 @@ -//! Reading, writing, copying, truncating, permissions and times. -//! -//! The async forms are thin wrappers over the sync ones: `std::fs` is blocking -//! either way, and this module has a thread of its own, so the only difference -//! is which thread the bridge calls the function on. -//! -//! Every failure goes through `errors::from_io`, so JS receives a Node code and -//! Node's message rather than an `std::io::Error` kind. - -use std::fs; -use std::io::Write as _; -use std::path::Path; - -use rn_gpui_module::{ArrayBuffer, ModuleError}; - -use crate::errors; -use crate::module::{kind, millis, open_options, system_time}; -use crate::StatResult; - -pub async fn read_file(path: String) -> Result { - read_file_sync(path) -} - -pub async fn read_text_file(path: String) -> Result { - read_text_file_sync(path) -} - -pub async fn write_file( - path: String, - data: ArrayBuffer, - flags: f64, - mode: f64, -) -> Result<(), ModuleError> { - write_bytes(&path, data.as_slice(), flags, mode) -} - -pub async fn write_text_file( - path: String, - data: String, - flags: f64, - mode: f64, -) -> Result<(), ModuleError> { - write_bytes(&path, data.as_bytes(), flags, mode) -} - -pub async fn stat(path: String, follow_symlinks: bool) -> Result { - stat_of(&path, follow_symlinks) -} - -pub async fn rename(from: String, to: String) -> Result<(), ModuleError> { - fs::rename(&from, &to).map_err(|error| errors::from_io(error, &from)) -} - -pub async fn copy(from: String, to: String, recursive: bool) -> Result<(), ModuleError> { - copy_path(&from, &to, recursive) -} - -pub async fn truncate(path: String, length: f64) -> Result<(), ModuleError> { - let length = crate::module::length(length)?; - let file = fs::OpenOptions::new() - .write(true) - .open(&path) - .map_err(|error| errors::from_io(error, &path))?; - file.set_len(length as u64) - .map_err(|error| errors::from_io(error, &path)) -} - -pub async fn utimes(path: String, atime_ms: f64, mtime_ms: f64) -> Result<(), ModuleError> { - let atime = filetime::FileTime::from_system_time(system_time(atime_ms)); - let mtime = filetime::FileTime::from_system_time(system_time(mtime_ms)); - filetime::set_file_times(&path, atime, mtime).map_err(|error| errors::from_io(error, &path)) -} - -pub async fn chmod(path: String, mode: f64) -> Result<(), ModuleError> { - set_mode(&path, mode) -} - -pub fn read_file_sync(path: String) -> Result { - fs::read(&path) - .map(ArrayBuffer::from) - .map_err(|error| errors::from_io(error, &path)) -} - -pub fn read_text_file_sync(path: String) -> Result { - let bytes = fs::read(&path).map_err(|error| errors::from_io(error, &path))?; - // Node decodes with replacement characters instead of rejecting a file that - // is not valid UTF-8, so reading a mis-encoded file still yields text. - Ok(String::from_utf8_lossy(&bytes).into_owned()) -} - -pub fn write_file_sync( - path: String, - data: ArrayBuffer, - flags: f64, - mode: f64, -) -> Result { - write_bytes(&path, data.as_slice(), flags, mode)?; - Ok(true) -} - -pub fn write_text_file_sync( - path: String, - data: String, - flags: f64, - mode: f64, -) -> Result { - write_bytes(&path, data.as_bytes(), flags, mode)?; - Ok(true) -} - -/// `Ok(None)` for a path that is not there: that is what `existsSync` asks, and -/// only a missing path means "no". A permission failure is still an error. -pub fn stat_sync(path: String, follow_symlinks: bool) -> Result, ModuleError> { - match stat_of(&path, follow_symlinks) { - Ok(result) => Ok(Some(result)), - Err(error) if error.code.as_deref() == Some("ENOENT") => Ok(None), - Err(error) => Err(error), - } -} - -pub fn exists_sync(path: String) -> Result { - Ok(matches!(stat_sync(path, true), Ok(Some(_)))) -} - -pub fn rename_sync(from: String, to: String) -> Result { - fs::rename(&from, &to).map_err(|error| errors::from_io(error, &from))?; - Ok(true) -} - -pub fn copy_file_sync(from: String, to: String) -> Result { - fs::copy(&from, &to).map_err(|error| errors::from_io(error, &from))?; - Ok(true) -} - -/// The one place a write happens, so bytes and text share the flag and mode -/// translation exactly. -fn write_bytes(path: &str, data: &[u8], flags: f64, mode: f64) -> Result<(), ModuleError> { - let mut file = open_options(flags, crate::module::mode(mode)) - .open(path) - .map_err(|error| errors::from_io(error, path))?; - file.write_all(data) - .map_err(|error| errors::from_io(error, path)) -} - -fn stat_of(path: &str, follow_symlinks: bool) -> Result { - let metadata = if follow_symlinks { - fs::metadata(path) - } else { - fs::symlink_metadata(path) - } - .map_err(|error| errors::from_io(error, path))?; - Ok(stat_result(&metadata)) -} - -/// The generated `StatResult`, filled from `std::fs::Metadata`. -/// -/// Node's `Stats` names the Unix inode fields even on Windows, where they have -/// no meaning; zero is what Node itself reports there. -fn stat_result(metadata: &fs::Metadata) -> StatResult { - let file_type = metadata.file_type(); - let kind = if file_type.is_file() { - kind::FILE - } else if file_type.is_dir() { - kind::DIRECTORY - } else if file_type.is_symlink() { - kind::SYMLINK - } else { - kind::OTHER - }; - - #[cfg(unix)] - let (mode, dev, ino, nlink, uid, gid) = { - use std::os::unix::fs::MetadataExt as _; - ( - metadata.mode() as f64, - metadata.dev() as f64, - metadata.ino() as f64, - metadata.nlink() as f64, - metadata.uid() as f64, - metadata.gid() as f64, - ) - }; - #[cfg(not(unix))] - let (mode, dev, ino, nlink, uid, gid) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0); - - // `ctime` is the inode change time on Unix; Windows has no such thing, and - // its creation time is the closest equivalent. - #[cfg(unix)] - let ctime_ms = { - use std::os::unix::fs::MetadataExt as _; - metadata.ctime() as f64 * 1000.0 + metadata.ctime_nsec() as f64 / 1_000_000.0 - }; - #[cfg(not(unix))] - let ctime_ms = metadata - .created() - .map(millis) - .unwrap_or_else(|_| metadata.modified().map(millis).unwrap_or(0.0)); - - // A file system that cannot report creation gives 0, as Node does, rather - // than pretending the modification time is the birth time. - let birthtime_ms = metadata.created().map(millis).unwrap_or(0.0); - - StatResult { - size: metadata.len() as f64, - mode, - kind, - atime_ms: metadata.accessed().map(millis).unwrap_or(0.0), - mtime_ms: metadata.modified().map(millis).unwrap_or(0.0), - ctime_ms, - birthtime_ms, - dev, - ino, - nlink, - uid, - gid, - } -} - -fn copy_path(from: &str, to: &str, recursive: bool) -> Result<(), ModuleError> { - let metadata = fs::symlink_metadata(from).map_err(|error| errors::from_io(error, from))?; - if !metadata.is_dir() { - fs::copy(from, to).map_err(|error| errors::from_io(error, from))?; - return Ok(()); - } - if !recursive { - return Err(errors::invalid( - "EISDIR", - format!("EISDIR: illegal operation on a directory, {from}"), - )); - } - copy_tree(Path::new(from), Path::new(to)) -} - -/// Refuse to copy a directory into itself or a directory beneath it. -/// -/// The destination may not exist yet, so the comparison is against its nearest -/// existing ancestor: `a` into `a/b/c` has to be caught before `a/b/c` exists, -/// which is the whole point. Both sides are canonicalised so a symlinked path -/// cannot slip past the check. -/// -/// Node's code and wording are reproduced rather than invented; `cpSync` reports -/// `ERR_FS_CP_EINVAL` with `Cannot copy /tmp/cpa/ to a subdirectory of self -/// /tmp/cpa/sub`, and callers match on both. -fn refuse_copy_into_self(from: &Path, to: &Path) -> Result<(), ModuleError> { - let resolve = |path: &Path| -> Option { - let mut existing = path.to_path_buf(); - let mut tail = Vec::new(); - loop { - if let Ok(canonical) = existing.canonicalize() { - return Some( - tail.iter() - .rev() - .fold(canonical, |base, part| base.join(part)), - ); - } - let name = existing.file_name().map(|name| name.to_owned())?; - tail.push(name); - if !existing.pop() { - return None; - } - } - }; - let Some(source) = resolve(from) else { - return Ok(()); - }; - let Some(destination) = resolve(to) else { - return Ok(()); - }; - if destination == source || destination.starts_with(&source) { - return Err(errors::invalid( - "ERR_FS_CP_EINVAL", - format!( - "Cannot copy {} to a subdirectory of self {}", - from.display(), - to.display() - ), - )); - } - Ok(()) -} - -fn copy_tree(from: &Path, to: &Path) -> Result<(), ModuleError> { - let target = to.to_string_lossy().into_owned(); - // Checked before anything is created: copying a directory into its own - // subtree would otherwise recurse forever, and the tree it built on the way - // down would have to be cleaned up by the caller. - refuse_copy_into_self(from, to)?; - fs::create_dir_all(to).map_err(|error| errors::from_io(error, &target))?; - let children = fs::read_dir(from).map_err(|error| errors::from_io(error, &source(from)))?; - for child in children { - let child = child.map_err(|error| errors::from_io(error, &source(from)))?; - let path = child.path(); - let destination = to.join(child.file_name()); - // `file_type` does not follow links, which keeps a link cycle in the - // source tree from turning into infinite recursion. - let file_type = child - .file_type() - .map_err(|error| errors::from_io(error, &source(&path)))?; - if file_type.is_dir() { - copy_tree(&path, &destination)?; - } else if file_type.is_symlink() { - copy_symlink(&path, &destination)?; - } else { - fs::copy(&path, &destination) - .map_err(|error| errors::from_io(error, &source(&path)))?; - } - } - Ok(()) -} - -#[cfg(unix)] -fn copy_symlink(from: &Path, to: &Path) -> Result<(), ModuleError> { - let target = fs::read_link(from).map_err(|error| errors::from_io(error, &source(from)))?; - std::os::unix::fs::symlink(&target, to).map_err(|error| errors::from_io(error, &source(from))) -} - -/// Windows needs a privilege to create a symbolic link, so there the link is -/// followed and its target copied, which is what a caller copying a tree wants -/// to end up with anyway. -#[cfg(not(unix))] -fn copy_symlink(from: &Path, to: &Path) -> Result<(), ModuleError> { - fs::copy(from, to) - .map(|_| ()) - .map_err(|error| errors::from_io(error, &source(from))) -} - -fn source(path: &Path) -> String { - path.to_string_lossy().into_owned() -} - -#[cfg(unix)] -fn set_mode(path: &str, mode: f64) -> Result<(), ModuleError> { - use std::os::unix::fs::PermissionsExt as _; - let bits = if mode.is_finite() && mode >= 0.0 { - mode as u32 & 0o7777 - } else { - 0o666 - }; - fs::set_permissions(path, fs::Permissions::from_mode(bits)) - .map_err(|error| errors::from_io(error, path)) -} - -/// Windows has no permission bits. The closest equivalent is the read-only -/// attribute, so a mode without a write bit marks the file read-only and any -/// other mode clears it; nothing else about the mode survives. -#[cfg(not(unix))] -fn set_mode(path: &str, mode: f64) -> Result<(), ModuleError> { - let metadata = fs::metadata(path).map_err(|error| errors::from_io(error, path))?; - let mut permissions = metadata.permissions(); - permissions.set_readonly(mode.is_finite() && mode > 0.0 && mode as u32 & 0o200 == 0); - fs::set_permissions(path, permissions).map_err(|error| errors::from_io(error, path)) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::module::flags; - use tempfile::TempDir; - - /// The async wrappers never actually suspend (they call `std::fs` directly), - /// so a single-poll executor is enough and keeps the tests free of a runtime. - fn block_on(future: F) -> F::Output { - let mut future = std::pin::pin!(future); - let waker = std::task::Waker::noop(); - let mut context = std::task::Context::from_waker(waker); - // One poll, no loop: these helpers do their work inline, so a `Pending` - // would mean the helper is not synchronous after all, which the test - // should fail loudly on rather than spin. - match future.as_mut().poll(&mut context) { - std::task::Poll::Ready(value) => value, - std::task::Poll::Pending => panic!("the wrappers are synchronous"), - } - } - - fn tempdir() -> TempDir { - TempDir::new().expect("a temporary directory") - } - - fn text(path: &Path) -> String { - path.to_string_lossy().into_owned() - } - - /// `'w'` in Node's table. - fn write_flags() -> f64 { - f64::from(flags::WRONLY | flags::CREAT | flags::TRUNC) - } - - #[test] - fn text_round_trip() { - let dir = tempdir(); - let path = dir.path().join("note.txt"); - - block_on(write_text_file( - text(&path), - "hello".to_string(), - write_flags(), - 0.0, - )) - .expect("write"); - assert_eq!( - block_on(read_text_file(text(&path))).expect("read"), - "hello" - ); - assert_eq!( - read_text_file_sync(text(&path)).expect("read sync"), - "hello" - ); - - assert!( - write_text_file_sync(text(&path), "again".to_string(), write_flags(), 0.0) - .expect("write sync") - ); - assert_eq!(fs::read_to_string(&path).expect("on disk"), "again"); - } - - #[test] - fn bytes_round_trip() { - let dir = tempdir(); - let path = dir.path().join("bytes.bin"); - let bytes = ArrayBuffer::from(vec![0u8, 1, 254, 255]); - - block_on(write_file(text(&path), bytes.clone(), write_flags(), 0.0)).expect("write"); - assert_eq!( - block_on(read_file(text(&path))).expect("read").as_slice(), - &[0u8, 1, 254, 255] - ); - assert_eq!( - read_file_sync(text(&path)).expect("read sync").into_vec(), - vec![0u8, 1, 254, 255] - ); - } - - #[test] - fn an_append_flag_keeps_the_existing_bytes() { - let dir = tempdir(); - let path = dir.path().join("log.txt"); - fs::write(&path, b"one").expect("seed"); - - block_on(write_text_file( - text(&path), - "two".to_string(), - f64::from(flags::WRONLY | flags::CREAT | flags::APPEND), - 0.0, - )) - .expect("append"); - - assert_eq!(fs::read_to_string(&path).expect("on disk"), "onetwo"); - } - - #[test] - fn stat_reports_kind_and_size() { - let dir = tempdir(); - let file = dir.path().join("data.bin"); - fs::write(&file, b"12345").expect("seed"); - - let stats = block_on(stat(text(&file), true)).expect("stat"); - assert_eq!(stats.kind, kind::FILE); - assert_eq!(stats.size, 5.0); - assert!(stats.mtime_ms > 0.0); - #[cfg(unix)] - assert_ne!( - stats.mode as u32 & 0o777, - 0, - "the mode bits come from MetadataExt" - ); - - let directory = block_on(stat(text(dir.path()), true)).expect("stat dir"); - assert_eq!(directory.kind, kind::DIRECTORY); - } - - #[cfg(unix)] - #[test] - fn stat_follows_links_only_when_asked() { - let dir = tempdir(); - let target = dir.path().join("target.txt"); - fs::write(&target, b"x").expect("seed"); - let link = dir.path().join("link.txt"); - std::os::unix::fs::symlink(&target, &link).expect("symlink"); - - assert_eq!( - block_on(stat(text(&link), false)).expect("lstat").kind, - kind::SYMLINK - ); - assert_eq!( - block_on(stat(text(&link), true)).expect("stat").kind, - kind::FILE - ); - } - - #[test] - fn stat_sync_is_none_for_a_missing_path() { - let dir = tempdir(); - let missing = text(&dir.path().join("absent.txt")); - assert!(stat_sync(missing, true).expect("stat").is_none()); - } - - #[test] - fn exists_sync_is_false_for_a_missing_path() { - let dir = tempdir(); - assert!(!exists_sync(text(&dir.path().join("absent.txt"))).expect("exists")); - assert!(exists_sync(text(dir.path())).expect("exists")); - } - - #[test] - fn a_missing_file_is_enoent() { - let dir = tempdir(); - let missing = text(&dir.path().join("gone.txt")); - - let error = block_on(read_text_file(missing.clone())).expect_err("read"); - assert_eq!(error.code.as_deref(), Some("ENOENT")); - assert!(error - .message - .starts_with("ENOENT: no such file or directory")); - - let error = read_file_sync(missing).expect_err("read sync"); - assert_eq!(error.code.as_deref(), Some("ENOENT")); - } - - #[test] - fn rename_moves_a_file() { - let dir = tempdir(); - let from = dir.path().join("a.txt"); - let to = dir.path().join("b.txt"); - fs::write(&from, b"a").expect("seed"); - - block_on(rename(text(&from), text(&to))).expect("rename"); - assert!(!from.exists()); - assert_eq!(fs::read_to_string(&to).expect("on disk"), "a"); - - assert!(rename_sync(text(&to), text(&from)).expect("rename sync")); - assert!(from.exists()); - } - - #[test] - fn copy_copies_a_file() { - let dir = tempdir(); - let from = dir.path().join("one.txt"); - fs::write(&from, b"copy me").expect("seed"); - let to = dir.path().join("two.txt"); - - block_on(copy(text(&from), text(&to), false)).expect("copy"); - assert_eq!(fs::read_to_string(&to).expect("on disk"), "copy me"); - - let third = dir.path().join("three.txt"); - assert!(copy_file_sync(text(&from), text(&third)).expect("copy sync")); - assert_eq!(fs::read_to_string(&third).expect("on disk"), "copy me"); - } - - #[test] - fn copy_copies_a_directory_tree_when_recursive() { - let dir = tempdir(); - let from = dir.path().join("tree"); - fs::create_dir_all(from.join("nested")).expect("tree"); - fs::write(from.join("top.txt"), b"top").expect("seed"); - fs::write(from.join("nested").join("deep.txt"), b"deep").expect("seed"); - let to = dir.path().join("copy"); - - block_on(copy(text(&from), text(&to), true)).expect("copy tree"); - assert_eq!( - fs::read_to_string(to.join("nested").join("deep.txt")).expect("on disk"), - "deep" - ); - - let error = block_on(copy(text(&from), text(&dir.path().join("nope")), false)) - .expect_err("a directory without recursive"); - assert_eq!(error.code.as_deref(), Some("EISDIR")); - } - - #[test] - fn copying_a_directory_into_itself_is_refused() { - let dir = tempdir(); - let from = dir.path().join("tree"); - fs::create_dir_all(from.join("sub")).expect("tree"); - fs::write(from.join("top.txt"), b"top").expect("seed"); - - // Into a directory beneath itself. This used to recurse until the path - // got too long, and left whatever it had built on the way down. - let into_self = from.join("sub"); - let error = block_on(copy(text(&from), text(&into_self), true)) - .expect_err("copy into a subdirectory of self"); - assert_eq!(error.code.as_deref(), Some("ERR_FS_CP_EINVAL")); - assert!( - error.message.starts_with("Cannot copy"), - "{}", - error.message - ); - // The check runs before anything is created, so the destination is still - // just the empty directory it was. - assert_eq!( - fs::read_dir(&into_self).expect("still there").count(), - 0, - "nothing may be created when the copy is refused" - ); - - // The directory itself is the same case. - let error = block_on(copy(text(&from), text(&from), true)).expect_err("copy onto itself"); - assert_eq!(error.code.as_deref(), Some("ERR_FS_CP_EINVAL")); - } - - #[test] - fn truncate_changes_the_length() { - let dir = tempdir(); - let path = dir.path().join("long.txt"); - fs::write(&path, b"0123456789").expect("seed"); - - block_on(truncate(text(&path), 4.0)).expect("truncate"); - assert_eq!(fs::read_to_string(&path).expect("on disk"), "0123"); - } - - #[test] - fn utimes_sets_both_times() { - let dir = tempdir(); - let path = dir.path().join("stamp.txt"); - fs::write(&path, b"x").expect("seed"); - - block_on(utimes( - text(&path), - 1_000_000_000_000.0, - 1_100_000_000_000.0, - )) - .expect("utimes"); - - let stats = block_on(stat(text(&path), true)).expect("stat"); - assert_eq!(stats.mtime_ms, 1_100_000_000_000.0); - } - - #[cfg(unix)] - #[test] - fn chmod_sets_the_permission_bits() { - use std::os::unix::fs::PermissionsExt as _; - let dir = tempdir(); - let path = dir.path().join("locked.txt"); - fs::write(&path, b"x").expect("seed"); - - block_on(chmod(text(&path), f64::from(0o640u32))).expect("chmod"); - - let mode = fs::metadata(&path).expect("metadata").permissions().mode() & 0o777; - assert_eq!(mode, 0o640); - } -} diff --git a/vendor/react-native-gpui/modules/fs/desktop/src/handles.rs b/vendor/react-native-gpui/modules/fs/desktop/src/handles.rs deleted file mode 100644 index 8bbb44c745..0000000000 --- a/vendor/react-native-gpui/modules/fs/desktop/src/handles.rs +++ /dev/null @@ -1,697 +0,0 @@ -//! Open descriptors: `open`, `read`, `write`, `fstat`, `fsync`, `ftruncate` -//! and `close`. -//! -//! A descriptor is an id from the module's table plus a clone of the file that -//! shares its offset, which is what a descriptor is to the OS. The table owns -//! the original, so dropping the module closes every handle; ids are never -//! reused, so a stale `fd` that JS kept across a `close` fails with `EBADF` -//! instead of reaching an unrelated file. -//! -//! These functions are synchronous even though the trait methods around them are -//! `async`: the module has a thread of its own, so a blocking call here never -//! blocks JS or the UI. - -use std::fs::File; -use std::io::{Read as _, Seek as _, Write as _}; - -use rn_gpui_module::{ArrayBuffer, ModuleError}; - -use crate::errors; -use crate::module::{bad_fd, descriptor, flags, kind, millis, open_options}; -use crate::StatResult; - -pub fn open( - module: &crate::RNFsModule, - path: String, - flags: f64, - mode: f64, -) -> Result { - // The table owns the file; everything the caller asks of it goes through - // `module.file(fd)`, which hands back a clone sharing the same offset. - let file = open_options(flags, crate::module::mode(mode)) - .open(&path) - .map_err(|error| errors::from_io(error, &path))?; - - let id = module.take_fd(); - // `RDONLY` is zero, so "writable" is the presence of any write bit rather - // than the absence of a read bit. - let writable = (flags as i32) & (flags::WRONLY | flags::RDWR) != 0; - module - .files - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .insert(id, (file, writable)); - Ok(f64::from(id)) -} - -pub fn read( - module: &crate::RNFsModule, - fd: f64, - length: f64, - position: f64, -) -> Result { - let id = descriptor(fd)?; - let length = crate::module::length(length)?; - let mut file = module.file(fd)?; - - // Nothing larger than the file can be read, so the buffer is capped at what - // remains rather than at what was asked for. A caller that passes a huge - // `length` — which `readToEnd` used to do deliberately — would otherwise ask - // for that many bytes up front and get whatever the allocator did with it. - let cap = match offset(position)? { - Some(start) => file - .metadata() - .ok() - .and_then(|meta| meta.len().checked_sub(start)) - .map_or(length, |remaining| length.min(remaining as usize)), - None => file - .metadata() - .ok() - .and_then(|meta| { - // A cursor read starts wherever the handle is, so the remainder - // is measured from there rather than from the start. - let current = file.stream_position().ok()?; - meta.len().checked_sub(current) - }) - .map_or(length, |remaining| length.min(remaining as usize)), - }; - let mut buffer = vec![0u8; cap]; - let filled = match offset(position)? { - Some(start) => read_at(&mut file, &mut buffer, start, id)?, - None => read_cursor(&mut file, &mut buffer, id)?, - }; - // A read that stopped at end of file is a short read, not a failure, so the - // buffer is shrunk to what the OS actually produced rather than padded. - buffer.truncate(filled); - Ok(ArrayBuffer::from(buffer)) -} - -pub fn write( - module: &crate::RNFsModule, - fd: f64, - data: ArrayBuffer, - position: f64, -) -> Result { - let id = descriptor(fd)?; - let (mut file, writable) = module.file_and_writability(fd)?; - // Checked from the flags the handle was opened with, not from what the OS - // says: a write to a read-only handle is `EBADF` in Node, `EACCES` on - // Windows and `EBADF` on Unix. - if !writable { - return Err(bad_fd(id)); - } - let bytes = data.as_slice(); - if bytes.is_empty() { - return Ok(0.0); - } - - // Read before the borrow below: `positioned_write` needs `&mut File` so the - // Windows branch can seek, and a match guard borrowing the file would overlap. - let append_only = appends(&file); - let written = match offset(position)? { - // An append-mode descriptor appends whatever offset the caller passes: - // a cursor write does that because the file was opened with `O_APPEND` - // (or `FILE_APPEND_DATA`), and Linux also appends for a positioned - // write. Ignoring the offset keeps the platforms alike and is what - // callers of `appendFile` expect. - Some(start) if !append_only => write_at(&mut file, bytes, start, id)?, - _ => write_cursor(&mut file, bytes, id)?, - }; - Ok(written as f64) -} - -pub fn fstat(module: &crate::RNFsModule, fd: f64) -> Result { - let id = descriptor(fd)?; - let file = module.file(fd)?; - let metadata = file.metadata().map_err(|error| io_error(error, id))?; - Ok(stat_result(&metadata)) -} - -pub fn fsync(module: &crate::RNFsModule, fd: f64) -> Result<(), ModuleError> { - let id = descriptor(fd)?; - let file = module.file(fd)?; - file.sync_all().map_err(|error| io_error(error, id)) -} - -pub fn ftruncate(module: &crate::RNFsModule, fd: f64, length: f64) -> Result<(), ModuleError> { - let id = descriptor(fd)?; - let length = crate::module::length(length)?; - let file = module.file(fd)?; - file.set_len(length as u64) - .map_err(|error| io_error(error, id)) -} - -pub fn close(module: &crate::RNFsModule, fd: f64) -> Result<(), ModuleError> { - let id = descriptor(fd)?; - let mut files = module - .files - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - // Removing rather than merely dropping the entry is what makes a second - // close report `EBADF`: the id is gone, and it is never handed out again. - files.remove(&id).ok_or_else(|| bad_fd(id))?; - Ok(()) -} - -/// A failure from an operation on a descriptor. -/// -/// The table may still know an id the kernel has already rejected — a write to a -/// read-only descriptor is the usual way — and Node reports that as `EBADF`, not -/// as a generic I/O error. Everything else goes through the shared mapping, with -/// the descriptor standing in for the path a Node message names. -fn io_error(error: std::io::Error, id: u32) -> ModuleError { - #[cfg(unix)] - if error.raw_os_error() == Some(libc::EBADF) { - return bad_fd(id); - } - errors::from_io(error, &id.to_string()) -} - -/// The byte offset a `position` argument names, or `None` for "the current -/// offset", which is what a negative position means to `node:fs`. -fn offset(position: f64) -> Result, ModuleError> { - if !position.is_finite() { - return Err(errors::invalid( - "EINVAL", - format!("EINVAL: invalid argument, position {position}"), - )); - } - if position < 0.0 { - return Ok(None); - } - Ok(Some(position as u64)) -} - -/// Whether the descriptor was opened for append. -/// -/// The table stores only the `File`, so the bit is read back from the descriptor -/// itself with `F_GETFL`: that reports the flag the kernel actually holds, which -/// is more reliable than tracking a second copy beside the table. -#[cfg(unix)] -fn appends(file: &File) -> bool { - use std::os::unix::io::AsRawFd as _; - // SAFETY: `file` owns a valid descriptor for the duration of the call; `F_GETFL` takes no argument. - let flags = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETFL) }; - flags >= 0 && flags & libc::O_APPEND != 0 -} - -/// Windows keeps the append bit inside the handle's granted access, with no -/// portable way to read it back, so the answer is "no" here. Cursor writes still -/// append — `append(true)` opens with `FILE_APPEND_DATA`, which does that in the -/// kernel — and a write with an explicit offset lands at that offset, which is -/// what a caller using `pwrite` on Windows would expect. -#[cfg(not(unix))] -fn appends(_file: &File) -> bool { - false -} - -fn read_at(file: &mut File, buffer: &mut [u8], offset: u64, id: u32) -> Result { - let mut filled = 0; - while filled < buffer.len() { - match positioned_read(file, &mut buffer[filled..], offset + filled as u64) { - Ok(0) => break, - Ok(count) => filled += count, - Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, - Err(error) => return Err(io_error(error, id)), - } - } - Ok(filled) -} - -fn read_cursor(file: &mut File, buffer: &mut [u8], id: u32) -> Result { - let mut filled = 0; - while filled < buffer.len() { - match file.read(&mut buffer[filled..]) { - Ok(0) => break, - Ok(count) => filled += count, - Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, - Err(error) => return Err(io_error(error, id)), - } - } - Ok(filled) -} - -fn write_at(file: &mut File, bytes: &[u8], offset: u64, id: u32) -> Result { - let mut written = 0; - while written < bytes.len() { - match positioned_write(file, &bytes[written..], offset + written as u64) { - // A regular file does not write zero bytes for a non-empty buffer; - // treating it as `EIO` keeps the loop from spinning forever. - Ok(0) => return Err(errors::invalid("EIO", format!("EIO: i/o error, {id}"))), - Ok(count) => written += count, - Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, - Err(error) => return Err(io_error(error, id)), - } - } - Ok(written) -} - -fn write_cursor(file: &mut File, bytes: &[u8], id: u32) -> Result { - file.write_all(bytes).map_err(|error| io_error(error, id))?; - Ok(bytes.len()) -} - -#[cfg(unix)] -fn positioned_read(file: &mut File, buffer: &mut [u8], offset: u64) -> std::io::Result { - use std::os::unix::fs::FileExt as _; - // `read_at` takes `&self`, but the call sites hold `&mut File` so the - // Windows branch — which has to seek — shares one signature. - (&*file).read_at(buffer, offset) -} - -/// Windows' positional read, with the cursor left where it was. -/// -/// `FileExt::seek_read` is documented as not affecting the cursor, but on a -/// synchronous handle — which is what `File::open` gives — the underlying -/// `ReadFile` with an `OVERLAPPED` offset keeps the file position as a side -/// effect. Node's positional forms leave the descriptor alone, and so does the -/// Unix branch above, so the position is saved and restored here. Without this a -/// positioned read moved the cursor, and a following cursor read started from the -/// wrong place. -#[cfg(windows)] -fn positioned_read(file: &mut File, buffer: &mut [u8], offset: u64) -> std::io::Result { - use std::io::Seek as _; - use std::os::windows::fs::FileExt as _; - let saved = file.stream_position(); - let result = file.seek_read(buffer, offset); - if let Ok(position) = saved { - let _ = file.seek(std::io::SeekFrom::Start(position)); - } - result -} - -#[cfg(unix)] -fn positioned_write(file: &mut File, bytes: &[u8], offset: u64) -> std::io::Result { - use std::os::unix::fs::FileExt as _; - (&*file).write_at(bytes, offset) -} - -/// Windows' positional write, with the cursor left where it was. Same reason as -/// `positioned_read` above. -#[cfg(windows)] -fn positioned_write(file: &mut File, bytes: &[u8], offset: u64) -> std::io::Result { - use std::io::Seek as _; - use std::os::windows::fs::FileExt as _; - let saved = file.stream_position(); - let result = file.seek_write(bytes, offset); - if let Ok(position) = saved { - let _ = file.seek(std::io::SeekFrom::Start(position)); - } - result -} - -/// The generated `StatResult`, filled from `std::fs::Metadata`. -/// -/// `files::stat` builds the same shape for a path. The two are deliberately -/// separate: `files` and `handles` are independent, and twenty duplicated lines -/// cost less than one file reaching into the other's internals. -fn stat_result(metadata: &std::fs::Metadata) -> StatResult { - let file_type = metadata.file_type(); - let kind = if file_type.is_file() { - kind::FILE - } else if file_type.is_dir() { - kind::DIRECTORY - } else if file_type.is_symlink() { - kind::SYMLINK - } else { - kind::OTHER - }; - - // Node's `Stats` names the Unix inode fields even on Windows, where they - // have no meaning; zero is what Node reports there too. - #[cfg(unix)] - let (mode, dev, ino, nlink, uid, gid) = { - use std::os::unix::fs::MetadataExt as _; - ( - metadata.mode() as f64, - metadata.dev() as f64, - metadata.ino() as f64, - metadata.nlink() as f64, - metadata.uid() as f64, - metadata.gid() as f64, - ) - }; - #[cfg(not(unix))] - let (mode, dev, ino, nlink, uid, gid) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0); - - // `ctime` is the inode change time on Unix; Windows has no equivalent, and - // its creation time is the closest thing it has. - #[cfg(unix)] - let ctime_ms = { - use std::os::unix::fs::MetadataExt as _; - metadata.ctime() as f64 * 1000.0 + metadata.ctime_nsec() as f64 / 1_000_000.0 - }; - #[cfg(not(unix))] - let ctime_ms = metadata - .created() - .map(millis) - .unwrap_or_else(|_| metadata.modified().map(millis).unwrap_or(0.0)); - - // A file system that cannot report creation gives 0, as Node does, rather - // than pretending the modification time is the birth time. - StatResult { - size: metadata.len() as f64, - mode, - kind, - atime_ms: metadata.accessed().map(millis).unwrap_or(0.0), - mtime_ms: metadata.modified().map(millis).unwrap_or(0.0), - ctime_ms, - birthtime_ms: metadata.created().map(millis).unwrap_or(0.0), - dev, - ino, - nlink, - uid, - gid, - } -} - -#[cfg(test)] -mod tests { - use std::path::Path; - use std::sync::Arc; - - use rn_gpui_module::{EventEmitter, ModuleInstance, Value}; - use tempfile::TempDir; - - use super::*; - use crate::native_fs_module; - - /// The async trait methods never actually suspend — they call these helpers - /// directly — so a single-poll executor drives the generated glue without a - /// runtime. - fn block_on(future: F) -> F::Output { - let mut future = std::pin::pin!(future); - let waker = std::task::Waker::noop(); - let mut context = std::task::Context::from_waker(waker); - loop { - match future.as_mut().poll(&mut context) { - std::task::Poll::Ready(value) => return value, - std::task::Poll::Pending => std::thread::yield_now(), - } - } - } - - /// `NativeFsEvents` has a private emitter and no constructor, so a test - /// cannot call `RNFsModule::create` itself. Building the instance through the - /// descriptor the bridge uses is the supported way in, and it exercises the - /// generated glue as a bonus. - fn module() -> Arc { - (native_fs_module::().create)(EventEmitter::new(1)) - } - - fn index(name: &str) -> usize { - native_fs_module::() - .methods - .iter() - .position(|method| method.name == name) - .unwrap_or_else(|| panic!("the spec has no method {name}")) - } - - fn call( - module: &Arc, - name: &str, - args: Vec, - ) -> Result { - block_on(module.clone().call_promise(index(name), args)?) - } - - fn text(path: &Path) -> String { - path.to_string_lossy().into_owned() - } - - fn open_fd(module: &Arc, path: &Path, flags_value: i32) -> f64 { - let value = call( - module, - "open", - vec![ - Value::String(text(path)), - Value::Number(f64::from(flags_value)), - Value::Number(0.0), - ], - ) - .expect("open"); - match value { - Value::Number(fd) => fd, - other => panic!("expected a descriptor, got {}", other.type_name()), - } - } - - fn read_bytes( - module: &Arc, - fd: f64, - length: f64, - position: f64, - ) -> Result, ModuleError> { - match call( - module, - "read", - vec![ - Value::Number(fd), - Value::Number(length), - Value::Number(position), - ], - )? { - Value::Buffer(bytes) => Ok(bytes), - other => panic!("expected bytes, got {}", other.type_name()), - } - } - - fn write_bytes( - module: &Arc, - fd: f64, - bytes: &[u8], - position: f64, - ) -> Result { - match call( - module, - "write", - vec![ - Value::Number(fd), - Value::Buffer(bytes.to_vec()), - Value::Number(position), - ], - )? { - Value::Number(written) => Ok(written), - other => panic!("expected a count, got {}", other.type_name()), - } - } - - fn stat_size(module: &Arc, fd: f64) -> f64 { - let value = call(module, "fstat", vec![Value::Number(fd)]).expect("fstat"); - let Value::Object(fields) = value else { - panic!("expected a stat object"); - }; - fields - .iter() - .find(|(name, _)| name == "size") - .and_then(|(_, value)| match value { - Value::Number(size) => Some(*size), - _ => None, - }) - .expect("a size field") - } - - fn close_fd(module: &Arc, fd: f64) -> Result { - call(module, "close", vec![Value::Number(fd)]) - } - - /// Open a fresh file containing `contents` and hand back its descriptor. - fn opened(module: &Arc, dir: &TempDir, contents: &str) -> (String, f64) { - let path = dir.path().join("data.txt"); - std::fs::write(&path, contents).expect("write the fixture file"); - let fd = open_fd(module, &path, flags::RDWR); - (text(&path), fd) - } - - #[test] - fn a_handle_reads_back_what_it_wrote() { - let dir = TempDir::new().expect("a temporary directory"); - let path = dir.path().join("note.txt"); - let module = module(); - - let fd = open_fd(&module, &path, flags::WRONLY | flags::CREAT | flags::TRUNC); - assert_eq!( - write_bytes(&module, fd, b"hello", -1.0).expect("write"), - 5.0 - ); - assert_eq!(stat_size(&module, fd), 5.0); - close_fd(&module, fd).expect("close"); - - let fd = open_fd(&module, &path, flags::RDONLY); - assert_eq!(read_bytes(&module, fd, 5.0, -1.0).expect("read"), b"hello"); - close_fd(&module, fd).expect("close"); - } - - #[test] - fn a_positioned_read_leaves_the_cursor_alone() { - let dir = TempDir::new().expect("a temporary directory"); - let module = module(); - let (_, fd) = opened(&module, &dir, "abcdef"); - - assert_eq!(read_bytes(&module, fd, 2.0, 0.0).expect("read"), b"ab"); - // The cursor never moved, so a cursor read starts at the beginning. - assert_eq!(read_bytes(&module, fd, 2.0, -1.0).expect("read"), b"ab"); - assert_eq!(read_bytes(&module, fd, 2.0, -1.0).expect("read"), b"cd"); - close_fd(&module, fd).expect("close"); - } - - #[test] - fn a_positioned_write_only_touches_its_range() { - let dir = TempDir::new().expect("a temporary directory"); - let module = module(); - let (path, fd) = opened(&module, &dir, "abcdef"); - - assert_eq!(write_bytes(&module, fd, b"XY", 2.0).expect("write"), 2.0); - assert_eq!(stat_size(&module, fd), 6.0); - assert_eq!(std::fs::read(&path).expect("on disk"), b"abXYef"); - close_fd(&module, fd).expect("close"); - } - - #[test] - fn reading_past_the_end_is_a_short_read_not_an_error() { - let dir = TempDir::new().expect("a temporary directory"); - let module = module(); - let (_, fd) = opened(&module, &dir, "abc"); - - // Two bytes asked for, one left: the buffer holds exactly one byte. - assert_eq!(read_bytes(&module, fd, 2.0, 2.0).expect("read"), b"c"); - // Nothing left at all: an empty buffer, still a success. - assert_eq!(read_bytes(&module, fd, 8.0, 10.0).expect("read"), b""); - assert_eq!(read_bytes(&module, fd, 8.0, -1.0).expect("read"), b"abc"); - assert_eq!(read_bytes(&module, fd, 8.0, -1.0).expect("read"), b""); - close_fd(&module, fd).expect("close"); - } - - #[test] - fn a_huge_length_only_allocates_what_the_file_holds() { - let dir = TempDir::new().expect("a temporary directory"); - let module = module(); - let (_, fd) = opened(&module, &dir, "0123456789"); - - // The buffer is capped at what remains, so this returns rather than - // trying to allocate four gigabytes. Finishing at all is the check: an - // allocation of `u32::MAX` bytes would abort the test process instead. - let bytes = read_bytes(&module, fd, u32::MAX as f64, 0.0).expect("read"); - assert_eq!(bytes, b"0123456789"); - close_fd(&module, fd).expect("close"); - } - - #[test] - fn appending_ignores_the_position() { - let dir = TempDir::new().expect("a temporary directory"); - let path = dir.path().join("log.txt"); - std::fs::write(&path, b"ab").expect("write the fixture file"); - let module = module(); - - let fd = open_fd(&module, &path, flags::APPEND | flags::WRONLY | flags::CREAT); - write_bytes(&module, fd, b"cd", -1.0).expect("append"); - // An append-mode descriptor appends even when an offset is passed, which - // is what the kernel does on Linux and what `appendFile` means. - write_bytes(&module, fd, b"ef", 0.0).expect("append"); - assert_eq!(stat_size(&module, fd), 6.0); - close_fd(&module, fd).expect("close"); - assert_eq!(std::fs::read(&path).expect("on disk"), b"abcdef"); - } - - #[test] - fn truncating_by_descriptor_changes_the_size() { - let dir = TempDir::new().expect("a temporary directory"); - let module = module(); - let (_, fd) = opened(&module, &dir, "abcdef"); - - call( - &module, - "ftruncate", - vec![Value::Number(fd), Value::Number(3.0)], - ) - .expect("ftruncate"); - assert_eq!(stat_size(&module, fd), 3.0); - assert_eq!(read_bytes(&module, fd, 16.0, 0.0).expect("read"), b"abc"); - close_fd(&module, fd).expect("close"); - } - - #[test] - fn syncing_a_handle_succeeds() { - let dir = TempDir::new().expect("a temporary directory"); - let module = module(); - let (_, fd) = opened(&module, &dir, "abc"); - write_bytes(&module, fd, b"d", 3.0).expect("write"); - call(&module, "fsync", vec![Value::Number(fd)]).expect("fsync"); - close_fd(&module, fd).expect("close"); - } - - #[test] - fn a_second_close_is_ebadf() { - let dir = TempDir::new().expect("a temporary directory"); - let module = module(); - let (_, fd) = opened(&module, &dir, "abc"); - - close_fd(&module, fd).expect("the first close"); - let error = close_fd(&module, fd).expect_err("the second close"); - assert_eq!(error.code.as_deref(), Some("EBADF")); - } - - #[test] - fn a_closed_descriptor_is_ebadf_for_every_op() { - let dir = TempDir::new().expect("a temporary directory"); - let module = module(); - let (_, fd) = opened(&module, &dir, "abc"); - close_fd(&module, fd).expect("close"); - - let error = read_bytes(&module, fd, 1.0, -1.0).expect_err("read"); - assert_eq!(error.code.as_deref(), Some("EBADF")); - let error = write_bytes(&module, fd, b"x", -1.0).expect_err("write"); - assert_eq!(error.code.as_deref(), Some("EBADF")); - let error = call(&module, "fstat", vec![Value::Number(fd)]).expect_err("fstat"); - assert_eq!(error.code.as_deref(), Some("EBADF")); - } - - #[test] - fn opening_a_missing_file_is_enoent() { - let dir = TempDir::new().expect("a temporary directory"); - let path = dir.path().join("gone.txt"); - let module = module(); - - let error = call( - &module, - "open", - vec![ - Value::String(text(&path)), - Value::Number(f64::from(flags::RDONLY)), - Value::Number(0.0), - ], - ) - .expect_err("open"); - assert_eq!(error.code.as_deref(), Some("ENOENT")); - } - - /// A descriptor the table still knows but the kernel rejects: Node says - /// `EBADF` here, and so must this module, rather than a generic `EIO`. - #[test] - fn writing_through_a_read_only_descriptor_is_ebadf() { - let dir = TempDir::new().expect("a temporary directory"); - let module = module(); - let path = dir.path().join("data.txt"); - std::fs::write(&path, b"abc").expect("write the fixture file"); - let fd = open_fd(&module, &path, flags::RDONLY); - - let error = write_bytes(&module, fd, b"x", -1.0).expect_err("write"); - assert_eq!(error.code.as_deref(), Some("EBADF")); - // Reading is still fine, and the file is untouched. - assert_eq!(read_bytes(&module, fd, 3.0, 0.0).expect("read"), b"abc"); - close_fd(&module, fd).expect("close"); - } - - #[test] - fn a_non_finite_position_is_einval() { - let dir = TempDir::new().expect("a temporary directory"); - let module = module(); - let (_, fd) = opened(&module, &dir, "abc"); - - let error = read_bytes(&module, fd, 1.0, f64::NAN).expect_err("read"); - assert_eq!(error.code.as_deref(), Some("EINVAL")); - let error = write_bytes(&module, fd, b"x", f64::INFINITY).expect_err("write"); - assert_eq!(error.code.as_deref(), Some("EINVAL")); - close_fd(&module, fd).expect("close"); - } -} diff --git a/vendor/react-native-gpui/modules/fs/desktop/src/lib.rs b/vendor/react-native-gpui/modules/fs/desktop/src/lib.rs deleted file mode 100644 index 3e847cf8b2..0000000000 --- a/vendor/react-native-gpui/modules/fs/desktop/src/lib.rs +++ /dev/null @@ -1,286 +0,0 @@ -//! `@react-native-gpui/fs`: a Node-shaped file API for the desktop app. -//! -//! The TypeScript spec in `../src/NativeFs.ts` is the contract; the generator -//! turns it into the `NativeFsSpec` trait implemented here. That trait is the -//! only thing the C++ bridge knows about, so the API surface is edited there and -//! regenerated, never in this file. -//! -//! Rust needs a trait's methods in a single `impl` block, so this file holds that -//! block and hands each method to a helper in the file that owns the concern: -//! -//! - `files` — reading, writing, copying, truncating, permissions and times -//! - `dirs` — listing, creating, removing and `mkdtemp` -//! - `handles` — open descriptors, positioned reads and writes -//! - `links` — symbolic links, `realpath` and `access` -//! - `paths` — the well-known folders, created on first read -//! - `dialogs` — the pickers, `reveal` and `openExternal` -//! - `watching` — the watcher behind `watch` and `unwatch` -//! -//! Keeping the bodies in those files is what makes the crate readable; keeping -//! the `impl` here is what makes it compile. - -rn_gpui_module::include_specs!(); - -mod dialogs; -mod dirs; -mod download; -mod errors; -mod files; -mod handles; -mod links; -mod module; -mod paths; -mod upload; -mod watching; - -pub use module::RNFsModule; - -use rn_gpui_module::{ArrayBuffer, ModuleError}; - -impl NativeFsSpec for RNFsModule { - fn new(events: NativeFsEvents) -> Self { - Self::create(events) - } - - async fn read_file(&self, path: String) -> Result { - files::read_file(path).await - } - - async fn read_text_file(&self, path: String) -> Result { - files::read_text_file(path).await - } - - async fn write_file( - &self, - path: String, - data: ArrayBuffer, - flags: f64, - mode: f64, - ) -> Result<(), ModuleError> { - files::write_file(path, data, flags, mode).await - } - - async fn write_text_file( - &self, - path: String, - data: String, - flags: f64, - mode: f64, - ) -> Result<(), ModuleError> { - files::write_text_file(path, data, flags, mode).await - } - - async fn readdir(&self, path: String, recursive: bool) -> Result, ModuleError> { - dirs::readdir(path, recursive).await - } - - async fn stat(&self, path: String, follow_symlinks: bool) -> Result { - files::stat(path, follow_symlinks).await - } - - async fn mkdir(&self, path: String, recursive: bool, mode: f64) -> Result<(), ModuleError> { - dirs::mkdir(path, recursive, mode).await - } - - async fn rm(&self, path: String, recursive: bool, force: bool) -> Result<(), ModuleError> { - dirs::rm(path, recursive, force).await - } - - async fn rename(&self, from: String, to: String) -> Result<(), ModuleError> { - files::rename(from, to).await - } - - async fn copy(&self, from: String, to: String, recursive: bool) -> Result<(), ModuleError> { - files::copy(from, to, recursive).await - } - - async fn access(&self, path: String, mode: f64) -> Result<(), ModuleError> { - links::access(path, mode) - } - - async fn realpath(&self, path: String) -> Result { - links::realpath(path) - } - - async fn readlink(&self, path: String) -> Result { - links::readlink(path) - } - - async fn symlink( - &self, - target: String, - path: String, - kind: Option, - ) -> Result<(), ModuleError> { - links::symlink(target, path, kind.as_deref()) - } - - async fn truncate(&self, path: String, length: f64) -> Result<(), ModuleError> { - files::truncate(path, length).await - } - - async fn utimes(&self, path: String, atime_ms: f64, mtime_ms: f64) -> Result<(), ModuleError> { - files::utimes(path, atime_ms, mtime_ms).await - } - - async fn chmod(&self, path: String, mode: f64) -> Result<(), ModuleError> { - files::chmod(path, mode).await - } - - async fn mkdtemp(&self, prefix: String) -> Result { - dirs::mkdtemp(prefix).await - } - - async fn open(&self, path: String, flags: f64, mode: f64) -> Result { - handles::open(self, path, flags, mode) - } - - async fn read(&self, fd: f64, length: f64, position: f64) -> Result { - handles::read(self, fd, length, position) - } - - async fn write(&self, fd: f64, data: ArrayBuffer, position: f64) -> Result { - handles::write(self, fd, data, position) - } - - async fn fstat(&self, fd: f64) -> Result { - handles::fstat(self, fd) - } - - async fn fsync(&self, fd: f64) -> Result<(), ModuleError> { - handles::fsync(self, fd) - } - - async fn ftruncate(&self, fd: f64, length: f64) -> Result<(), ModuleError> { - handles::ftruncate(self, fd, length) - } - - async fn close(&self, fd: f64) -> Result<(), ModuleError> { - handles::close(self, fd) - } - - async fn show_open_dialog( - &self, - options: OpenDialogOptions, - ) -> Result, ModuleError> { - dialogs::show_open(options) - } - - async fn show_save_dialog( - &self, - options: SaveDialogOptions, - ) -> Result, ModuleError> { - dialogs::show_save(options) - } - - async fn reveal(&self, path: String) -> Result<(), ModuleError> { - dialogs::reveal(path) - } - - async fn open_external(&self, path: String) -> Result<(), ModuleError> { - dialogs::open_external(path) - } - - async fn watch(&self, path: String, recursive: bool) -> Result { - watching::watch(self, path, recursive) - } - - async fn download( - &self, - url: String, - path: String, - options: DownloadOptions, - ) -> Result { - download::download(self, url, path, options).await - } - - async fn upload( - &self, - url: String, - path: String, - options: UploadOptions, - ) -> Result { - upload::upload(self, url, path, options).await - } - - fn cancel_upload(&self, id: f64) -> Result { - Ok(upload::cancel(self, id)) - } - - fn cancel_download(&self, id: f64) -> Result { - Ok(download::cancel(self, id)) - } - - fn unwatch(&self, id: f64) { - watching::unwatch(self, id); - } - - fn read_file_sync(&self, path: String) -> Result { - files::read_file_sync(path) - } - - fn read_text_file_sync(&self, path: String) -> Result { - files::read_text_file_sync(path) - } - - fn write_file_sync( - &self, - path: String, - data: ArrayBuffer, - flags: f64, - mode: f64, - ) -> Result { - files::write_file_sync(path, data, flags, mode) - } - - fn write_text_file_sync( - &self, - path: String, - data: String, - flags: f64, - mode: f64, - ) -> Result { - files::write_text_file_sync(path, data, flags, mode) - } - - fn stat_sync( - &self, - path: String, - follow_symlinks: bool, - ) -> Result, ModuleError> { - files::stat_sync(path, follow_symlinks) - } - - fn exists_sync(&self, path: String) -> Result { - files::exists_sync(path) - } - - fn readdir_sync(&self, path: String, recursive: bool) -> Result, ModuleError> { - dirs::readdir_sync(path, recursive) - } - - fn mkdir_sync(&self, path: String, recursive: bool, mode: f64) -> Result { - dirs::mkdir_sync(path, recursive, mode) - } - - fn rm_sync(&self, path: String, recursive: bool, force: bool) -> Result { - dirs::rm_sync(path, recursive, force) - } - - fn rename_sync(&self, from: String, to: String) -> Result { - files::rename_sync(from, to) - } - - fn copy_file_sync(&self, from: String, to: String) -> Result { - files::copy_file_sync(from, to) - } - - fn get_paths(&self) -> Result { - paths::known_paths() - } -} - -/// Called by the app's autolink shim, which keeps these modules linked in. -pub fn rn_gpui_register() { - rn_gpui_module::register(native_fs_module::()); -} diff --git a/vendor/react-native-gpui/modules/fs/desktop/src/links.rs b/vendor/react-native-gpui/modules/fs/desktop/src/links.rs deleted file mode 100644 index cd49bc4ddf..0000000000 --- a/vendor/react-native-gpui/modules/fs/desktop/src/links.rs +++ /dev/null @@ -1,336 +0,0 @@ -//! Links and path checks: `access`, `realpath`, `readlink` and `symlink`. -//! -//! These are the calls whose exact meaning differs most between the platforms, -//! so each one is written against the platform's own primitive rather than -//! approximated from `std::fs` where that would change the answer. - -use std::path::Path; -use std::path::PathBuf; - -use rn_gpui_module::ModuleError; - -use crate::errors; -use crate::module::access; - -pub fn access(path: String, mode: f64) -> Result<(), ModuleError> { - let mode = access_mode(mode)?; - platform_access(&path, mode) -} - -pub fn realpath(path: String) -> Result { - let resolved = dunce::canonicalize(&path).map_err(|error| errors::from_io(error, &path))?; - // A `String` crosses the bridge as UTF-8, so a path that is not valid UTF-8 - // has no faithful representation. Lossy-converting would hand JS a path it - // cannot open, which is worse than failing: `EINVAL` says the argument could - // not be represented rather than that the path does not exist. - resolved - .into_os_string() - .into_string() - .map_err(|unrepresentable| { - errors::invalid( - "EINVAL", - format!( - "EINVAL: invalid argument, path is not valid UTF-8, {}", - Path::new(&unrepresentable).display() - ), - ) - }) -} - -pub fn readlink(path: String) -> Result { - let target = std::fs::read_link(&path).map_err(|error| errors::from_io(error, &path))?; - // As with `realpath`: the target is returned exactly as the file system - // stores it, and a target that is not UTF-8 cannot be a `String`. - target - .into_os_string() - .into_string() - .map_err(|unrepresentable| { - errors::invalid( - "EINVAL", - format!( - "EINVAL: invalid argument, link target is not valid UTF-8, {}", - Path::new(&unrepresentable).display() - ), - ) - }) -} - -pub fn symlink(target: String, path: String, kind: Option<&str>) -> Result<(), ModuleError> { - platform_symlink(&target, &path, kind) -} - -/// Validate the bitmask Node numbers, returning it unchanged. -/// -/// The caller gets Node's own bits back, not `access(2)`'s: `libc` 0.2 defines -/// `R_OK`, `W_OK` and `X_OK` only for Unix, so a Windows build that named them -/// failed with "cannot find value `R_OK` in crate `libc`". The translation to -/// `access(2)` happens in `platform_access`, which is already Unix-only, and the -/// Windows path reads the same Node bits directly. -/// -/// `F_OK` is 0: the mode is not a flag set, and asking for nothing means "does -/// it exist". -fn access_mode(mode: f64) -> Result { - if !mode.is_finite() || mode < 0.0 || mode.fract() != 0.0 { - return Err(errors::invalid( - "EINVAL", - format!("EINVAL: invalid argument, mode {mode}"), - )); - } - let requested = mode as i32; - let known = access::F_OK | access::R_OK | access::W_OK | access::X_OK; - if requested & !known != 0 { - return Err(errors::invalid( - "EINVAL", - format!("EINVAL: invalid argument, mode {requested}"), - )); - } - Ok(requested) -} - -/// `access(2)` is the only way to get Node's semantics — it asks the kernel about -/// *this* process's real uid and gid, including supplementary groups — so the -/// Unix implementation calls it rather than inspecting the mode bits, which -/// would give a different answer for a file the caller does not own. -#[cfg(unix)] -fn platform_access(path: &str, requested: i32) -> Result<(), ModuleError> { - use std::ffi::CString; - use std::os::unix::ffi::OsStrExt as _; - - // `access(2)` uses the same values Node does for these three, but the - // translation is spelled out so a platform whose constants differ still asks - // the right question. This is the only place the `libc` constants are named. - let mut mask = libc::F_OK; - if requested & access::R_OK != 0 { - mask |= libc::R_OK; - } - if requested & access::W_OK != 0 { - mask |= libc::W_OK; - } - if requested & access::X_OK != 0 { - mask |= libc::X_OK; - } - - // A path with an interior NUL cannot be passed to the C API at all; that is - // an invalid argument rather than a file-system failure. - let name = CString::new(std::ffi::OsStr::new(path).as_bytes()).map_err(|_| { - errors::invalid( - "EINVAL", - format!("EINVAL: invalid argument, path contains a null byte, {path}"), - ) - })?; - // `access` reports failure by return value and sets `errno`, so the error is - // built from `last_os_error` and then mapped like any other. - // SAFETY: `name` is a NUL-terminated string that outlives the call. - let result = unsafe { libc::access(name.as_ptr(), mask) }; - if result == 0 { - Ok(()) - } else { - Err(errors::from_io(std::io::Error::last_os_error(), path)) - } -} - -/// Windows has no `access(2)`, so the checks are approximated from what the -/// platform does offer: `F_OK` and `R_OK` are a `metadata()` call (the read bit -/// is not expressible, and a file the process can stat is one it can normally -/// read), `W_OK` tries to open the file for writing, and `X_OK` uses the -/// executable extensions the shell recognises, because Windows has no execute -/// bit to test. -#[cfg(not(unix))] -fn platform_access(path: &str, requested: i32) -> Result<(), ModuleError> { - // `F_OK` asks only that the path resolves; `metadata` follows links, which - // matches `access`'s "does the name lead to something". - std::fs::metadata(path).map_err(|error| errors::from_io(error, path))?; - if requested & access::W_OK != 0 { - std::fs::OpenOptions::new() - .write(true) - .open(path) - .map_err(|error| errors::from_io(error, path))?; - } - if requested & access::X_OK != 0 && !is_executable(Path::new(path)) { - return Err(errors::invalid( - "EACCES", - format!("EACCES: permission denied, {path}"), - )); - } - Ok(()) -} - -/// The extensions `PATHEXT` names, which is how Windows decides a file is a -/// program. A directory is executable for `access`'s purposes because the caller -/// can `chdir` into it. -#[cfg(not(unix))] -fn is_executable(path: &Path) -> bool { - if path.is_dir() { - return true; - } - let extensions = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string()); - let Some(extension) = path.extension().and_then(|value| value.to_str()) else { - return false; - }; - let extension = format!(".{}", extension.to_ascii_uppercase()); - extensions - .split(';') - .any(|candidate| candidate.eq_ignore_ascii_case(&extension)) -} - -/// Unix ignores the link kind: `symlink(2)` does not have one, and the target is -/// resolved lazily on every traversal, so a link to a directory works without -/// being declared as one. -#[cfg(unix)] -fn platform_symlink(target: &str, path: &str, kind: Option<&str>) -> Result<(), ModuleError> { - let _ = kind; - std::os::unix::fs::symlink(target, path).map_err(|error| errors::from_io(error, path)) -} - -/// Windows needs a different call for a file link and a directory link, and it -/// needs the developer-mode privilege (or SeCreateSymbolicLinkPrivilege) for -/// either. The design says to report the OS error rather than fall back to -/// copying, so a caller without the privilege sees the real reason. -/// -/// The kind decides which call, following Node's rules. It cannot be inferred -/// from the target alone: a link may name a path that does not exist yet, and -/// `metadata` would fail on exactly the case that matters. `'junction'` gets -/// `symlink_dir` — a directory symlink rather than a true NTFS junction, which -/// needs a different API and an absolute target; both are traversable, which is -/// what a caller wants. -#[cfg(not(unix))] -fn platform_symlink(target: &str, path: &str, kind: Option<&str>) -> Result<(), ModuleError> { - let directory = match kind { - Some("dir") | Some("junction") => true, - Some("file") => false, - _ => { - // Node's rule when no type is given: resolve the target relative to - // the link's parent — the shell does the same — and take the answer - // from what is there. - let resolved = match Path::new(path).parent() { - Some(parent) => parent.join(target), - None => PathBuf::from(target), - }; - resolved.is_dir() - } - }; - let result = if directory { - std::os::windows::fs::symlink_dir(target, path) - } else { - std::os::windows::fs::symlink_file(target, path) - }; - result.map_err(|error| errors::from_io(error, path)) -} - -#[cfg(test)] -mod tests { - use super::*; - use tempfile::TempDir; - - fn tempdir() -> TempDir { - TempDir::new().expect("a temporary directory") - } - - fn text(path: &Path) -> String { - path.to_string_lossy().into_owned() - } - - #[test] - fn access_finds_a_present_path_and_reports_a_missing_one() { - let dir = tempdir(); - let present = dir.path().join("here.txt"); - std::fs::write(&present, b"x").expect("write the fixture file"); - let absent = dir.path().join("gone.txt"); - - access(text(&present), f64::from(access::F_OK)).expect("a present path exists"); - access(text(&present), f64::from(access::R_OK | access::W_OK)) - .expect("a file we just wrote is readable and writable"); - - let error = access(text(&absent), f64::from(access::F_OK)).expect_err("a missing path"); - assert_eq!(error.code.as_deref(), Some("ENOENT")); - } - - #[test] - fn access_rejects_a_mode_node_does_not_define() { - let dir = tempdir(); - let error = access(text(dir.path()), 8.0).expect_err("an unknown bit"); - assert_eq!(error.code.as_deref(), Some("EINVAL")); - } - - /// `dunce::canonicalize` resolves the whole chain, so the result is the real - /// file rather than the link. Windows is skipped: creating a symlink there - /// needs developer mode, which a CI runner may not have. - #[cfg(unix)] - #[test] - fn realpath_resolves_a_symlink() { - let dir = tempdir(); - let file = dir.path().join("real.txt"); - std::fs::write(&file, b"x").expect("write the fixture file"); - let link = dir.path().join("link.txt"); - std::os::unix::fs::symlink(&file, &link).expect("create the link"); - - assert_eq!( - realpath(text(&link)).expect("realpath"), - realpath(text(&file)).expect("realpath") - ); - assert_eq!( - realpath(text(&file)).expect("realpath"), - dunce::canonicalize(&file) - .expect("canonical") - .to_string_lossy() - ); - } - - #[test] - fn realpath_of_a_missing_path_is_enoent() { - let dir = tempdir(); - let error = realpath(text(&dir.path().join("gone"))).expect_err("missing"); - assert_eq!(error.code.as_deref(), Some("ENOENT")); - } - - /// The link is read, not followed: the target comes back as it was stored, - /// relative or absolute. - #[cfg(unix)] - #[test] - fn readlink_returns_the_stored_target() { - let dir = tempdir(); - let link = dir.path().join("link.txt"); - std::os::unix::fs::symlink("some/relative/target", &link).expect("create the link"); - assert_eq!( - readlink(text(&link)).expect("readlink"), - "some/relative/target" - ); - - let file = dir.path().join("real.txt"); - std::fs::write(&file, b"x").expect("write the fixture file"); - let error = readlink(text(&file)).expect_err("a plain file is not a link"); - assert_eq!(error.code.as_deref(), Some("EINVAL")); - } - - /// Windows is skipped because creating a symlink there needs developer mode; - /// the OS error would be the correct result, not a test failure. - #[cfg(unix)] - #[test] - fn symlink_round_trips_through_readlink() { - let dir = tempdir(); - let target = dir.path().join("target.txt"); - std::fs::write(&target, b"x").expect("write the fixture file"); - let link = dir.path().join("link.txt"); - - symlink(text(&target), text(&link), None).expect("symlink"); - assert_eq!(readlink(text(&link)).expect("readlink"), text(&target)); - assert_eq!(std::fs::read(&link).expect("through the link"), b"x"); - } - - #[test] - fn symlinking_onto_an_existing_path_is_eexist() { - let dir = tempdir(); - let one = dir.path().join("one.txt"); - let two = dir.path().join("two.txt"); - std::fs::write(&one, b"1").expect("write"); - std::fs::write(&two, b"2").expect("write"); - - let error = symlink(text(&one), text(&two), None).expect_err("the name is taken"); - #[cfg(unix)] - assert_eq!(error.code.as_deref(), Some("EEXIST")); - // Windows reports the same collision, but through a Win32 code whose - // kind is "already exists"; only the presence of an error is portable. - #[cfg(not(unix))] - assert!(error.code.is_some()); - } -} diff --git a/vendor/react-native-gpui/modules/fs/desktop/src/module.rs b/vendor/react-native-gpui/modules/fs/desktop/src/module.rs deleted file mode 100644 index ecc99b06c2..0000000000 --- a/vendor/react-native-gpui/modules/fs/desktop/src/module.rs +++ /dev/null @@ -1,192 +0,0 @@ -//! Shared state and helpers for the file system module. -//! -//! The trait's methods are split across sibling files by concern — `files`, -//! `dirs`, `handles`, `paths`, `dialogs`, `watching` — because they are large and -//! largely independent. Rust allows the trait to be implemented in several files -//! of one crate, so each file owns its own `impl` block. -//! -//! Everything they share is here: the open file table, the flag translation, and -//! the conversions the bridge's `f64` arguments need. - -use std::fs::File; -use std::sync::atomic::AtomicU32; -use std::sync::Mutex; - -use rn_gpui_module::{ModuleError, ModuleThread}; - -use crate::NativeFsEvents; - -use crate::errors; - -/// Flags, as `node:fs` numbers them: Node's table, not the platform's, so these -/// are translated rather than passed through to `OpenOptions`. -pub mod flags { - pub const RDONLY: i32 = 0; - pub const WRONLY: i32 = 1; - pub const RDWR: i32 = 2; - pub const CREAT: i32 = 64; - pub const EXCL: i32 = 128; - pub const TRUNC: i32 = 512; - pub const APPEND: i32 = 1024; -} - -/// Access modes for `access`, matching `node:fs.constants`. -pub mod access { - pub const F_OK: i32 = 0; - pub const X_OK: i32 = 1; - pub const W_OK: i32 = 2; - pub const R_OK: i32 = 4; -} - -/// The kind numbers the JS layer turns into `Stats` predicates. -pub mod kind { - pub const FILE: f64 = 0.0; - pub const DIRECTORY: f64 = 1.0; - pub const SYMLINK: f64 = 2.0; - pub const OTHER: f64 = 3.0; -} - -pub struct RNFsModule { - pub events: NativeFsEvents, - /// Open files, keyed by the number JS holds. The table belongs to the - /// instance, so a reload closes every descriptor when it drops. - /// - /// Each entry records whether the descriptor was opened writable. The OS - /// reports a write to a read-only handle as `EBADF` on Unix and `EACCES` on - /// Windows, and Node reports `EBADF` on both, so the answer is taken from what - /// the handle was opened with rather than from the errno. - pub files: Mutex>, - /// Never reused, so a stale `fd` from JS fails instead of closing an - /// unrelated file. - pub next_fd: AtomicU32, - /// Live watchers, keyed the same way. - pub watchers: Mutex>, - pub next_watcher: AtomicU32, - /// Running downloads, keyed by the id JS chose, with the flag that stops each. - pub downloads: crate::download::Downloads, - pub uploads: crate::upload::Uploads, -} - -impl RNFsModule { - pub fn create(events: NativeFsEvents) -> Self { - Self { - events, - files: Mutex::new(std::collections::HashMap::new()), - next_fd: AtomicU32::new(1), - watchers: Mutex::new(std::collections::HashMap::new()), - next_watcher: AtomicU32::new(1), - downloads: Default::default(), - uploads: Default::default(), - } - } - - pub fn take_fd(&self) -> u32 { - self.next_fd - .fetch_add(1, std::sync::atomic::Ordering::Relaxed) - } - - pub fn take_watcher_id(&self) -> u32 { - self.next_watcher - .fetch_add(1, std::sync::atomic::Ordering::Relaxed) - } - - /// A clone of an open file, sharing its offset — which is what a descriptor - /// is. Holding the lock only for the lookup keeps a slow write from blocking - /// every other call on this thread. - pub fn file(&self, fd: f64) -> Result { - self.file_and_writability(fd).map(|(file, _)| file) - } - - /// The handle and whether it can be written to. - pub fn file_and_writability(&self, fd: f64) -> Result<(File, bool), ModuleError> { - let id = descriptor(fd)?; - let files = self.files.lock().unwrap_or_else(|e| e.into_inner()); - let (file, writable) = files.get(&id).ok_or_else(|| bad_fd(id))?; - let cloned = file - .try_clone() - .map_err(|error| errors::from_io(error, &id.to_string()))?; - Ok((cloned, *writable)) - } -} - -/// The error Node raises for a descriptor it does not know. -pub fn bad_fd(id: u32) -> ModuleError { - errors::invalid("EBADF", format!("EBADF: bad file descriptor, {id}")) -} - -/// A descriptor from the bridge. Anything but a non-negative integer is a -/// programmer error, so it reports as a bad descriptor rather than a file error. -pub fn descriptor(value: f64) -> Result { - if value.is_finite() && value >= 0.0 && value.fract() == 0.0 && value <= u32::MAX as f64 { - Ok(value as u32) - } else { - Err(bad_fd(0)) - } -} - -/// A byte length from the bridge. -pub fn length(value: f64) -> Result { - if value.is_finite() && value >= 0.0 && value.fract() == 0.0 && value <= u32::MAX as f64 { - Ok(value as usize) - } else { - Err(errors::invalid( - "EINVAL", - format!("EINVAL: invalid argument, length {value}"), - )) - } -} - -/// A permission bitmask, clamped to the bits `std::fs` accepts. Zero means the -/// caller passed nothing, which Node treats as `0o666`. -pub fn mode(value: f64) -> u32 { - if value.is_finite() && value > 0.0 { - value as u32 & 0o7777 - } else { - 0o666 - } -} - -/// `node:fs` numeric flags as `OpenOptions`. -pub fn open_options(flags_value: f64, mode: u32) -> std::fs::OpenOptions { - let flags_value = flags_value as i32; - let mut options = std::fs::OpenOptions::new(); - // Bit tests, not `matches!`: `matches!(value, A | B)` is the or-pattern - // `value == A || value == B`, which for Node's flags asks whether the whole - // mask equals 0 or 2. `'w'` is `WRONLY | CREAT | TRUNC` (577), so that test - // was false and every write opened read-only and failed `EINVAL`. - // `RDONLY` is zero, so "read" is the absence of `WRONLY` rather than a bit. - options - .read(flags_value & flags::WRONLY == 0) - .write(flags_value & (flags::WRONLY | flags::RDWR) != 0) - .create(flags_value & flags::CREAT != 0) - .create_new(flags_value & flags::EXCL != 0) - .truncate(flags_value & flags::TRUNC != 0) - .append(flags_value & flags::APPEND != 0); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt as _; - options.mode(mode); - } - #[cfg(not(unix))] - let _ = mode; - options -} - -/// Milliseconds since the epoch, as the bridge sends them. -pub fn system_time(ms: f64) -> std::time::SystemTime { - if ms.is_finite() && ms >= 0.0 { - std::time::UNIX_EPOCH + std::time::Duration::from_millis(ms as u64) - } else { - std::time::UNIX_EPOCH - } -} - -/// A `SystemTime` as milliseconds, which is what `StatResult` carries. -pub fn millis(time: std::time::SystemTime) -> f64 { - time.duration_since(std::time::UNIX_EPOCH) - .map(|elapsed| elapsed.as_millis() as f64) - .unwrap_or(0.0) -} - -// The spec says `THREAD = Own`; this keeps the module compiled against that. -const _: ModuleThread = ModuleThread::Own; diff --git a/vendor/react-native-gpui/modules/fs/desktop/src/paths.rs b/vendor/react-native-gpui/modules/fs/desktop/src/paths.rs deleted file mode 100644 index 2dc6523c6c..0000000000 --- a/vendor/react-native-gpui/modules/fs/desktop/src/paths.rs +++ /dev/null @@ -1,271 +0,0 @@ -//! The well-known folders, as one `KnownPaths` object. -//! -//! `dirs` answers for the folders every platform has. The per-application three -//! — `appData`, `appCache`, `appLogs` — are this module's own convention, because -//! the host does not yet tell modules which app they belong to; see -//! `app_id` below. All three are created on the first read, as the design asks, -//! so a caller can write a log file without a `mkdir` first. - -use std::path::{Path, PathBuf}; - -use rn_gpui_module::ModuleError; - -use crate::KnownPaths; - -/// The public folders plus the three per-application ones, created if needed. -/// -/// Nothing here fails: a folder that does not exist is reported as the temp -/// directory instead. The design treats these as conveniences, and a caller -/// asking where to put a log file is better served by a working stand-in than by -/// a thrown error it cannot recover from — the alternative is a crash on a -/// system where, say, `Desktop` was never created. -pub fn known_paths() -> Result { - let temp = std::env::temp_dir(); - let id = app_id(); - - let root = std::env::var_os("RN_GPUI_APP_DATA_DIR"); - let (app_data, app_cache, app_logs) = app_folders(root.as_deref(), &id); - - Ok(KnownPaths { - home: fallback(dirs::home_dir(), &temp), - documents: fallback(dirs::document_dir(), &temp), - downloads: fallback(dirs::download_dir(), &temp), - desktop: fallback(dirs::desktop_dir(), &temp), - temp: path_string(&temp), - app_data: ensure_directory(app_data, &temp), - app_cache: ensure_directory(app_cache, &temp), - app_logs: ensure_directory(app_logs, &temp), - }) -} - -/// The `appData`, `appCache` and `appLogs` folders for an app id. -/// -/// A non-empty `RN_GPUI_APP_DATA_DIR` moves all three under that root so several -/// copies of an app can run side by side with separate data without overriding -/// `HOME`: `/`, `/cache/` and `/logs/`. -fn app_folders( - root: Option<&std::ffi::OsStr>, - id: &str, -) -> (Option, Option, Option) { - match root.filter(|root| !root.is_empty()).map(PathBuf::from) { - Some(root) => ( - Some(root.join(id)), - Some(root.join("cache").join(id)), - Some(root.join("logs").join(id)), - ), - None => ( - dirs::data_dir().map(|dir| dir.join(id)), - dirs::cache_dir().map(|dir| dir.join(id)), - logs_dir(id), - ), - } -} - -/// A folder as a string, with the temp directory standing in when the platform -/// cannot name it. -fn fallback(found: Option, temp: &Path) -> String { - path_string(found.as_deref().unwrap_or(temp)) -} - -/// A path as `KnownPaths` carries it. A non-UTF-8 path cannot be a JS string, so -/// the lossy form is used rather than failing: it is still a path the platform -/// will resolve, and the folder is only a suggestion to the caller. -fn path_string(path: &Path) -> String { - path.to_string_lossy().into_owned() -} - -/// Creates a directory that the returned path promises exists, falling back to -/// the temp directory if it cannot be created. -/// -/// A failure here means the platform gave no base directory at all, or that it -/// exists but is not writable; temp is the one directory a process can normally -/// count on, so the caller still gets somewhere to write. -fn ensure_directory(found: Option, temp: &Path) -> String { - let Some(directory) = found else { - return path_string(temp); - }; - match std::fs::create_dir_all(&directory) { - Ok(()) => path_string(&directory), - Err(_) => path_string(temp), - } -} - -/// Where `appLogs` lives, which is the one app folder whose convention differs -/// by platform: macOS keeps logs under `~/Library/Logs`, the others under the -/// data directory. Both get the app id as their last component so two apps do -/// not share a log folder. -fn logs_dir(id: &str) -> Option { - #[cfg(target_os = "macos")] - { - dirs::home_dir().map(|home| home.join("Library").join("Logs").join(id)) - } - #[cfg(not(target_os = "macos"))] - { - dirs::data_dir().map(|dir| dir.join(id).join("logs")) - } -} - -/// The id the three per-app folders are namespaced by. -/// -/// This is a **placeholder**. The design wants these paths to be per-app and -/// says the host already knows the id (`DesktopAppConfig::app_id`), but no host -/// function exposes it to modules yet: `host_info().app_id` does not exist. Until -/// that API lands, `RN_GPUI_APP_ID` is honoured when the app sets it, and the -/// executable's file stem is the fallback — stable for a given binary, which is -/// enough to keep the folders apart and across runs. -/// -/// When `host_info().app_id` is added, this function should read it and the two -/// fallbacks should go, because a renamed binary would otherwise move the app's -/// data and cache out from under the user. -fn app_id() -> String { - let from_environment = std::env::var("RN_GPUI_APP_ID").ok(); - let from_executable = std::env::current_exe().ok().and_then(|exe| { - exe.file_stem() - .map(|stem| stem.to_string_lossy().into_owned()) - }); - pick_app_id(from_environment.as_deref(), from_executable.as_deref()) -} - -/// The selection half of `app_id`, split out so the precedence and the fallback -/// can be tested without touching the environment, which other tests share. -fn pick_app_id(from_environment: Option<&str>, from_executable: Option<&str>) -> String { - [from_environment, from_executable] - .into_iter() - .flatten() - .map(sanitise) - .find(|id| !id.is_empty()) - // A process whose executable has no usable name still needs folders, and - // the name only has to be stable, not accurate. - .unwrap_or_else(|| "rn-gpui-app".to_string()) -} - -/// Strips the characters that cannot appear in a directory name on any of the -/// three platforms, so an id from the environment cannot escape its parent -/// directory or fail `create_dir_all` on Windows. -/// -/// Leading and trailing dots and dashes go too: an id that was only separators -/// sanitises to nothing rather than to a directory named `-`, and one that began -/// with `..` cannot end up looking like a parent reference. -fn sanitise(id: &str) -> String { - id.trim() - .chars() - .map(|character| match character { - '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' | '\0' => '-', - other => other, - }) - .collect::() - .trim_matches(|character| character == '.' || character == '-') - .to_string() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn every_known_path_is_a_non_empty_string() { - let paths = known_paths().expect("known paths"); - for (name, value) in [ - ("home", &paths.home), - ("documents", &paths.documents), - ("downloads", &paths.downloads), - ("desktop", &paths.desktop), - ("temp", &paths.temp), - ("appData", &paths.app_data), - ("appCache", &paths.app_cache), - ("appLogs", &paths.app_logs), - ] { - assert!(!value.is_empty(), "{name} was empty"); - } - } - - #[test] - fn the_app_folders_exist_after_the_first_read() { - let paths = known_paths().expect("known paths"); - for (name, value) in [ - ("appData", &paths.app_data), - ("appCache", &paths.app_cache), - ("appLogs", &paths.app_logs), - ] { - assert!( - Path::new(value).is_dir(), - "{name} was not created at {value}" - ); - } - } - - #[test] - fn the_app_folders_are_distinct() { - let paths = known_paths().expect("known paths"); - let app_data = Path::new(&paths.app_data); - let app_cache = Path::new(&paths.app_cache); - let app_logs = Path::new(&paths.app_logs); - - assert_ne!(app_data, app_cache); - assert_ne!(app_data, app_logs); - assert_ne!(app_cache, app_logs); - } - - #[test] - fn a_second_read_returns_the_same_folders() { - // Creating a directory that already exists has to keep succeeding, since - // the JS layer may call `getPaths()` more than once per run. - let first = known_paths().expect("known paths"); - let second = known_paths().expect("known paths"); - assert_eq!(first.app_data, second.app_data); - assert_eq!(first.app_cache, second.app_cache); - assert_eq!(first.app_logs, second.app_logs); - } - - #[test] - fn an_id_from_the_environment_names_the_app_folders() { - // Only the pure part is asserted: mutating the environment would race - // with the other tests in this module, which read it concurrently. - assert_eq!(sanitise("my-app"), "my-app"); - assert_eq!(sanitise(" ../escape "), "escape"); - assert_eq!(sanitise("a/b\\c"), "a-b-c"); - assert_eq!(sanitise(" "), ""); - } - - #[test] - fn a_data_dir_override_roots_the_three_app_folders() { - use std::ffi::OsStr; - let (data, cache, logs) = app_folders(Some(OsStr::new("/srv/instance")), "notes"); - assert_eq!(data, Some(PathBuf::from("/srv/instance/notes"))); - assert_eq!(cache, Some(PathBuf::from("/srv/instance/cache/notes"))); - assert_eq!(logs, Some(PathBuf::from("/srv/instance/logs/notes"))); - } - - #[test] - fn an_empty_or_missing_data_dir_override_keeps_the_platform_folders() { - use std::ffi::OsStr; - let default = app_folders(None, "notes"); - assert_eq!(app_folders(Some(OsStr::new("")), "notes"), default); - assert_eq!(default.0, dirs::data_dir().map(|dir| dir.join("notes"))); - assert_eq!(default.1, dirs::cache_dir().map(|dir| dir.join("notes"))); - } - - #[test] - fn the_environment_id_wins_over_the_executable_name() { - assert_eq!(pick_app_id(Some("from-env"), Some("from-exe")), "from-env"); - } - - #[test] - fn an_unusable_environment_id_falls_through_to_the_executable_name() { - assert_eq!(pick_app_id(Some(" "), Some("from-exe")), "from-exe"); - // A separator-only id would escape its parent, which `sanitise` turns - // into a name rather than a path. - assert_eq!(pick_app_id(Some("/"), Some("from-exe")), "from-exe"); - } - - #[test] - fn no_id_at_all_still_yields_a_stable_name() { - assert_eq!(pick_app_id(None, None), "rn-gpui-app"); - assert_eq!(pick_app_id(Some(""), Some("")), "rn-gpui-app"); - } - - #[test] - fn a_hostile_executable_name_cannot_escape_the_base_directory() { - assert_eq!(pick_app_id(None, Some("../../etc/passwd")), "etc-passwd"); - } -} diff --git a/vendor/react-native-gpui/modules/fs/desktop/src/upload.rs b/vendor/react-native-gpui/modules/fs/desktop/src/upload.rs deleted file mode 100644 index 514fcf6129..0000000000 --- a/vendor/react-native-gpui/modules/fs/desktop/src/upload.rs +++ /dev/null @@ -1,237 +0,0 @@ -//! `upload`: a file, or a range of one, streamed as an HTTP request body. -//! -//! The file is read in small blocks as the connection takes them, so the body is -//! never held in memory. The request runs on its own thread; the cancel flag is -//! checked on every block, which is what makes a cancel prompt while the -//! connection is busy. - -use std::collections::HashMap; -use std::fs::File; -use std::io::{self, Read, Seek, SeekFrom}; -use std::path::PathBuf; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex, OnceLock}; -use std::time::{Duration, Instant}; - -use rn_gpui_module::ModuleError; -use ureq::config::Config; -use ureq::tls::{RootCerts, TlsConfig}; -use ureq::{Agent, SendBody}; - -use crate::{ - errors, DownloadHeader, NativeFsEvents, RNFsModule, UploadOptions, UploadProgress, - UploadResult, -}; - -const BLOCK: usize = 64 * 1024; -const PROGRESS_INTERVAL: Duration = Duration::from_millis(100); -const RESPONSE_BODY_LIMIT: u64 = 2048; - -pub type Uploads = Mutex>>; - -fn agent() -> &'static Agent { - static AGENT: OnceLock = OnceLock::new(); - AGENT.get_or_init(|| { - let config = Config::builder() - .http_status_as_error(false) - .timeout_connect(Some(Duration::from_secs(30))) - .tls_config( - TlsConfig::builder() - .root_certs(RootCerts::PlatformVerifier) - .build(), - ) - .build(); - Agent::new_with_config(config) - }) -} - -fn aborted() -> ModuleError { - ModuleError::with_code("ABORT_ERR", "The upload was aborted") -} - -fn failed(message: impl Into) -> ModuleError { - ModuleError::with_code("ERR_UPLOAD", message.into()) -} - -fn id_of(value: f64) -> u32 { - value as u32 -} - -pub fn cancel(module: &RNFsModule, id: f64) -> bool { - match module.uploads.lock().expect("uploads").get(&id_of(id)) { - Some(stop) => { - stop.store(true, Ordering::SeqCst); - true - } - None => false, - } -} - -struct Body { - file: File, - remaining: u64, - sent: u64, - total: u64, - id: u32, - events: NativeFsEvents, - stop: Arc, - last_progress: Instant, -} - -impl Body { - fn emit(&self) { - self.events.on_upload_progress(UploadProgress { - id: f64::from(self.id), - sent: self.sent as f64, - total: self.total as f64, - }); - } -} - -impl Read for Body { - fn read(&mut self, buffer: &mut [u8]) -> io::Result { - if self.stop.load(Ordering::SeqCst) { - return Err(io::Error::new(io::ErrorKind::Other, "aborted")); - } - if self.remaining == 0 { - return Ok(0); - } - let wanted = buffer.len().min(BLOCK).min(self.remaining as usize); - let read = self.file.read(&mut buffer[..wanted])?; - if read == 0 { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "the file is shorter than the requested range", - )); - } - self.remaining -= read as u64; - self.sent += read as u64; - if self.last_progress.elapsed() >= PROGRESS_INTERVAL || self.remaining == 0 { - self.last_progress = Instant::now(); - self.emit(); - } - Ok(read) - } -} - -fn run( - events: NativeFsEvents, - id: u32, - url: String, - path: PathBuf, - options: UploadOptions, - stop: Arc, -) -> Result { - let shown = path.display().to_string(); - let mut file = File::open(&path).map_err(|e| errors::from_io(e, &shown))?; - let size = file - .metadata() - .map_err(|e| errors::from_io(e, &shown))? - .len(); - let offset = if options.offset > 0.0 { - options.offset as u64 - } else { - 0 - }; - if offset > size { - return Err(failed("the offset is past the end of the file")); - } - let length = if options.length < 0.0 { - size - offset - } else { - options.length as u64 - }; - if offset + length > size { - return Err(failed("the range is past the end of the file")); - } - file.seek(SeekFrom::Start(offset)) - .map_err(|e| errors::from_io(e, &shown))?; - - let method = if options.method.is_empty() { - "PUT".to_string() - } else { - options.method.clone() - }; - let mut builder = ureq::http::Request::builder().method(method.as_str()).uri(&url); - let mut has_length = false; - for header in &options.headers { - if header.name.eq_ignore_ascii_case("content-length") { - has_length = true; - } - builder = builder.header(header.name.as_str(), header.value.as_str()); - } - if !has_length { - builder = builder.header("content-length", length.to_string()); - } - - let mut body = Body { - file, - remaining: length, - sent: 0, - total: length, - id, - events, - stop: stop.clone(), - last_progress: Instant::now() - PROGRESS_INTERVAL, - }; - body.emit(); - let request = builder - .body(SendBody::from_reader(&mut body)) - .map_err(|e| failed(e.to_string()))?; - let outcome = agent().run(request); - if stop.load(Ordering::SeqCst) { - return Err(aborted()); - } - let mut response = outcome.map_err(|e| failed(e.to_string()))?; - let status = response.status().as_u16(); - let mut headers: Vec = Vec::new(); - for (name, value) in response.headers() { - let value = String::from_utf8_lossy(value.as_bytes()).into_owned(); - match headers.iter_mut().find(|h| h.name == name.as_str()) { - Some(existing) => { - existing.value.push_str(", "); - existing.value.push_str(&value); - } - None => headers.push(DownloadHeader { - name: name.as_str().to_string(), - value, - }), - } - } - let mut text = Vec::new(); - let _ = response - .body_mut() - .as_reader() - .take(RESPONSE_BODY_LIMIT) - .read_to_end(&mut text); - Ok(UploadResult { - status: f64::from(status), - headers, - body: String::from_utf8_lossy(&text).into_owned(), - }) -} - -pub async fn upload( - module: &RNFsModule, - url: String, - path: String, - options: UploadOptions, -) -> Result { - let id = id_of(options.id); - let stop = Arc::new(AtomicBool::new(false)); - { - let mut running = module.uploads.lock().expect("uploads"); - if running.contains_key(&id) { - return Err(failed(format!("upload {id} is already running"))); - } - running.insert(id, stop.clone()); - } - let (sender, receiver) = futures::channel::oneshot::channel(); - let events = module.events.clone(); - std::thread::spawn(move || { - let _ = sender.send(run(events, id, url, PathBuf::from(path), options, stop)); - }); - let result = receiver.await; - module.uploads.lock().expect("uploads").remove(&id); - result.unwrap_or_else(|_| Err(failed("the upload stopped unexpectedly"))) -} diff --git a/vendor/react-native-gpui/modules/fs/desktop/src/watching.rs b/vendor/react-native-gpui/modules/fs/desktop/src/watching.rs deleted file mode 100644 index 356db5f517..0000000000 --- a/vendor/react-native-gpui/modules/fs/desktop/src/watching.rs +++ /dev/null @@ -1,392 +0,0 @@ -//! The watcher behind `watch` and `unwatch`. -//! -//! `notify` gives each watcher a thread of its own and calls the handler on it. -//! That handler cannot borrow the module — it may outlive any single call and -//! runs on a thread the module does not own — so it is handed a clone of the -//! event emitter and an `Arc` of the debounce table instead. The module only -//! stores the `RecommendedWatcher`; dropping that value stops the OS watch, and -//! with it the thread, which is how a JS reload closes every watcher at once. - -use std::collections::HashMap; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; - -use notify::event::EventKind; -use notify::Watcher as _; -use notify::{RecommendedWatcher, RecursiveMode}; -use rn_gpui_module::ModuleError; - -use crate::{errors, RNFsModule, WatchEvent}; - -/// How long a path stays quiet after being reported. -/// -/// An editor saving a file usually writes it several times in a burst (write, -/// rename over the original, a truncated open), and a recursive watch on a build -/// directory can see dozens of events for one logical change. Fifty milliseconds -/// collapses a burst into the single event a caller can act on without making a -/// genuinely repeated edit invisible. -const DEBOUNCE: Duration = Duration::from_millis(50); - -/// An installed watch, kept alive by the module's table. -/// -/// The field is never read: it exists so that removing the entry drops it, which -/// is what stops notify's thread and the platform watch. -pub struct Watcher { - _watcher: RecommendedWatcher, -} - -/// What was last reported for a path, and when. -#[derive(Clone, Copy)] -struct LastReport { - at: Instant, - kind: EventKindTag, -} - -/// Which of the three stable names an event carries. -/// -/// A copy of the mapping `kind_name` produces, so the debounce can compare two -/// events without allocating the string it will not send. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -enum EventKindTag { - Create, - Modify, - Remove, - Other, -} - -/// Per-path timestamps of the last event that was reported. -/// -/// Shared with the handler through an `Arc` because the handler owns its state -/// for as long as the watcher lives, which is longer than any borrow of the -/// module. Paths that fall out of the window are pruned on every report, so a -/// long-running recursive watch cannot grow this without bound. -/// -/// The rule, in one sentence: **a burst is collapsed per path and per kind, and a -/// removal is never collapsed away.** Keeping only the first event of a burst -/// lost the end of it — a create followed by a remove reported only `create`, so -/// a caller was told about a file that no longer existed. Two adjustments fix -/// that without giving up the collapsing that makes an editor's write burst -/// readable: -/// -/// - a path's window is per kind, so a `remove` after a `create` is a different -/// event rather than a suppressed one; -/// - a removal always reports, whatever the window, because it is the last state -/// a path can reach and swallowing it leaves the caller's view permanently -/// wrong. The cost is a possible duplicate removal for one logical deletion, -/// which a watcher callback can tolerate; a missing one it cannot. -#[derive(Default)] -struct Debounce { - last: Mutex>, -} - -impl Debounce { - /// Whether this event should be delivered now. - /// - /// Takes `now` rather than reading the clock so the window can be tested - /// without sleeping. - fn should_report_at(&self, path: &Path, kind: EventKindTag, now: Instant) -> bool { - let mut last = self.last.lock().unwrap_or_else(|error| error.into_inner()); - let key = (path.to_path_buf(), kind); - let report = match last.get(&key).copied() { - Some(previous) => { - kind == EventKindTag::Remove || now.saturating_duration_since(previous) >= DEBOUNCE - } - None => true, - }; - if report { - last.retain(|_, previous| now.saturating_duration_since(*previous) < DEBOUNCE); - last.insert(key, now); - } - report - } - - fn should_report(&self, path: &Path, kind: EventKindTag) -> bool { - self.should_report_at(path, kind, Instant::now()) - } -} - -/// The stable string the JS layer matches on. -/// -/// Everything that is not a create, modify or remove — access events, and the -/// catch-all notify reports when a backend cannot be more precise — becomes -/// `other` rather than leaking a platform-specific spelling. -fn kind_name(kind: &EventKind) -> &'static str { - match kind { - EventKind::Create(_) => "create", - EventKind::Modify(_) => "modify", - EventKind::Remove(_) => "remove", - _ => "other", - } -} - -/// The tag `kind_name` corresponds to, for the debounce to compare by. -fn kind_tag(kind: &EventKind) -> EventKindTag { - match kind { - EventKind::Create(_) => EventKindTag::Create, - EventKind::Modify(_) => EventKindTag::Modify, - EventKind::Remove(_) => EventKindTag::Remove, - _ => EventKindTag::Other, - } -} - -/// An event path as the caller should see it. -/// -/// Node reports the path relative to the watch root, and a name alone for a -/// single-file watch. The platform reports an absolute path, and on macOS a -/// *canonical* one: FSEvents resolves `/var` to `/private/var`, so a plain string -/// prefix check against the path the caller gave strips nothing and the callback -/// receives an absolute path. Both roots are therefore tried, and the given one -/// last so a caller watching through a symlink still gets a relative name. -fn relative_event_path(path: &Path, roots: &[PathBuf], watching_file: bool) -> String { - if watching_file { - return path - .file_name() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_else(|| path.to_string_lossy().into_owned()); - } - for root in roots { - if let Ok(rest) = path.strip_prefix(root) { - // Normalised to `/`: Node reports relative paths with forward - // slashes on every platform, and a Windows caller would otherwise get - // `nested\file.txt` where Node gives `nested/file.txt`. - return rest.to_string_lossy().replace('\\', "/"); - } - } - path.to_string_lossy().into_owned() -} - -/// A notify failure as the error JS expects. -/// -/// Most failures wrap an `io::Error` that already maps through `errors::from_io`; -/// the ones that do not are described well enough by notify to be reported with -/// the closest Node code. -fn watcher_error(error: notify::Error, path: &str) -> ModuleError { - use notify::ErrorKind; - let io = match error.kind { - ErrorKind::Io(error) => error, - ErrorKind::PathNotFound => std::io::Error::new(std::io::ErrorKind::NotFound, "not found"), - ErrorKind::MaxFilesWatch => { - std::io::Error::new(std::io::ErrorKind::Other, "OS file watch limit reached") - } - other => std::io::Error::new(std::io::ErrorKind::Other, format!("{other:?}")), - }; - errors::from_io(io, path) -} - -/// Starts watching `path`, returning the id events carry. -pub fn watch(module: &RNFsModule, path: String, recursive: bool) -> Result { - // Node fails a watch on a missing path immediately, and so must this: the - // platform watchers otherwise accept the path and then go silent, which is - // indistinguishable at the call site from a directory nothing ever touches. - let target = PathBuf::from(&path); - if !target.exists() { - return Err(errors::from_io( - std::io::Error::new(std::io::ErrorKind::NotFound, "not found"), - &path, - )); - } - - let id = module.take_watcher_id(); - let debounce = Arc::new(Debounce::default()); - let events = module.events.clone(); - // The canonical root is what macOS actually reports inside, and the given - // root is what the caller passed; keeping both means the relative name - // survives either spelling. - let watching_file = target.is_file(); - let roots: Vec = { - let mut roots = Vec::new(); - if let Ok(canonical) = target.canonicalize() { - roots.push(canonical); - } - roots.push(target.clone()); - roots - }; - let handler = move |result: notify::Result| { - // A backend error has nowhere to go: it is not tied to a call, and - // reporting it through the event stream would make it look like a file - // change. notify's thread keeps running, so later events still arrive. - let Ok(event) = result else { return }; - let kind = kind_name(&event.kind); - let tag = kind_tag(&event.kind); - // One platform event can name several paths — a directory move, for - // instance — and a caller wants one delivery per path. - for path in &event.paths { - if !debounce.should_report(path, tag) { - continue; - } - events.on_watch_event(WatchEvent { - id: f64::from(id), - kind: kind.to_string(), - path: relative_event_path(path, &roots, watching_file), - }); - } - }; - - let mut watcher = - notify::recommended_watcher(handler).map_err(|error| watcher_error(error, &path))?; - let mode = if recursive { - RecursiveMode::Recursive - } else { - RecursiveMode::NonRecursive - }; - watcher - .watch(&target, mode) - .map_err(|error| watcher_error(error, &path))?; - - module - .watchers - .lock() - .unwrap_or_else(|error| error.into_inner()) - .insert(id, Watcher { _watcher: watcher }); - Ok(f64::from(id)) -} - -/// Stops a watcher. An id that is already gone is not a failure: JS may close a -/// watcher twice, or close one whose module has already dropped it. -pub fn unwatch(module: &RNFsModule, id: f64) { - let Ok(id) = crate::module::descriptor(id) else { - return; - }; - // Removing the entry drops the watcher, which stops notify's thread. - module - .watchers - .lock() - .unwrap_or_else(|error| error.into_inner()) - .remove(&id); -} - -#[cfg(test)] -mod tests { - use super::*; - use notify::event::{CreateKind, ModifyKind, RemoveKind}; - - #[test] - fn event_kinds_map_to_stable_names() { - assert_eq!(kind_name(&EventKind::Create(CreateKind::File)), "create"); - assert_eq!(kind_name(&EventKind::Create(CreateKind::Any)), "create"); - assert_eq!(kind_name(&EventKind::Modify(ModifyKind::Any)), "modify"); - assert_eq!(kind_name(&EventKind::Remove(RemoveKind::Any)), "remove"); - assert_eq!(kind_name(&EventKind::Any), "other"); - } - - #[test] - fn the_first_event_for_a_path_is_reported() { - let debounce = Debounce::default(); - let now = Instant::now(); - assert!(debounce.should_report_at(Path::new("/a"), EventKindTag::Modify, now)); - } - - #[test] - fn a_burst_is_collapsed_into_one_event() { - let debounce = Debounce::default(); - let start = Instant::now(); - assert!(debounce.should_report_at(Path::new("/a"), EventKindTag::Modify, start)); - assert!(!debounce.should_report_at( - Path::new("/a"), - EventKindTag::Modify, - start + Duration::from_millis(10) - )); - assert!(!debounce.should_report_at( - Path::new("/a"), - EventKindTag::Modify, - start + Duration::from_millis(49) - )); - assert!(debounce.should_report_at( - Path::new("/a"), - EventKindTag::Modify, - start + Duration::from_millis(50) - )); - } - - #[test] - fn a_remove_inside_a_burst_is_not_swallowed() { - let debounce = Debounce::default(); - let start = Instant::now(); - let path = Path::new("/a"); - // A create and the removal that follows it are two states of the path, - // not one event seen twice: reporting only the create tells a caller - // about a file that is already gone. - assert!(debounce.should_report_at(path, EventKindTag::Create, start)); - assert!(debounce.should_report_at( - path, - EventKindTag::Remove, - start + Duration::from_millis(5) - )); - // A second removal for the same deletion may arrive; a missing one may - // not, so this is deliberately the lenient side of the trade. - assert!(debounce.should_report_at( - path, - EventKindTag::Remove, - start + Duration::from_millis(10) - )); - } - - #[test] - fn a_modify_burst_still_collapses() { - let debounce = Debounce::default(); - let start = Instant::now(); - let path = Path::new("/a"); - assert!(debounce.should_report_at(path, EventKindTag::Modify, start)); - // Two writes a millisecond apart are one logical change. - assert!(!debounce.should_report_at( - path, - EventKindTag::Modify, - start + Duration::from_millis(1) - )); - } - - #[test] - fn a_canonical_root_still_yields_a_relative_name() { - // macOS reports canonical paths, so a watch on `/var/...` sees - // `/private/var/...`. Both roots are tried, and the caller gets a name - // relative to the one they asked about either way. - let canonical = PathBuf::from("/private/var/folders/x/tmp"); - let given = PathBuf::from("/var/folders/x/tmp"); - let roots = vec![canonical.clone(), given]; - let event = canonical.join("nested").join("file.txt"); - assert_eq!( - relative_event_path(&event, &roots, false), - "nested/file.txt" - ); - // A path outside every root is passed through rather than mangled. - assert_eq!( - relative_event_path(Path::new("/elsewhere/file.txt"), &roots, false), - "/elsewhere/file.txt" - ); - // Watching a single file reports its name, which is what Node does. - assert_eq!(relative_event_path(&event, &roots, true), "file.txt"); - } - - #[test] - fn debouncing_is_per_path() { - let debounce = Debounce::default(); - let start = Instant::now(); - assert!(debounce.should_report_at(Path::new("/a"), EventKindTag::Modify, start)); - assert!(debounce.should_report_at( - Path::new("/b"), - EventKindTag::Modify, - start + Duration::from_millis(1) - )); - assert!(!debounce.should_report_at( - Path::new("/a"), - EventKindTag::Modify, - start + Duration::from_millis(2) - )); - } - - #[test] - fn paths_outside_the_window_are_forgotten() { - let debounce = Debounce::default(); - let start = Instant::now(); - assert!(debounce.should_report_at(Path::new("/a"), EventKindTag::Modify, start)); - assert!(debounce.should_report_at( - Path::new("/b"), - EventKindTag::Modify, - start + Duration::from_millis(60) - )); - let last = debounce.last.lock().unwrap(); - assert_eq!(last.len(), 1, "the stale path should have been pruned"); - assert!(last.contains_key(&(PathBuf::from("/b"), EventKindTag::Modify))); - } -} diff --git a/vendor/react-native-gpui/modules/fs/docs/file-system.md b/vendor/react-native-gpui/modules/fs/docs/file-system.md deleted file mode 100644 index f3eb28e87d..0000000000 --- a/vendor/react-native-gpui/modules/fs/docs/file-system.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -id: desktop-file-system -title: File system ---- - -`@react-native-gpui/fs` is a file system API for desktop apps. It follows `node:fs`, so code and habits from Node carry over, and adds file dialogs and the well-known folders of the operating system. - -```shell -npm install @react-native-gpui/fs -``` - -```js -import fs, { dialog, paths } from '@react-native-gpui/fs'; -``` - -The module runs on its own thread, so a slow file never blocks JavaScript or the interface. - -## Reading and writing - -The default export is the `node:fs` object, with synchronous, callback and promise forms: - -```js -const text = fs.readFileSync(`${paths.documents}/notes.txt`, 'utf8'); - -await fs.promises.writeFile( - `${paths.appData}/state.json`, - JSON.stringify(state), -); - -const entries = await fs.promises.readdir(paths.downloads, { - withFileTypes: true, -}); -``` - -The common operations are available: `readFile`, `writeFile`, `appendFile`, `stat`, `lstat`, `readdir`, `mkdir`, `rm`, `rename`, `copyFile`, `cp`, `access`, `realpath`, `readlink`, `symlink`, `truncate`, `utimes`, `chmod`, `mkdtemp`, `open` with `FileHandle`, and `existsSync`. Encodings, `Stats`, `Dirent`, flags and `constants` behave as they do in Node. Errors carry Node's error codes, such as `ENOENT`. - -Text is read and written as UTF-8 directly in native code. Other encodings and binary data go through `ArrayBuffer`. - -## Well-known folders - -`paths` holds the folders the operating system defines. They are created the first time you read them: - -| Name | Folder | -| ----------- | ------------------------------------------ | -| `home` | The user's home folder. | -| `documents` | Documents. | -| `downloads` | Downloads. | -| `desktop` | The desktop. | -| `temp` | The temporary folder. | -| `appData` | Where the app keeps its data. | -| `appCache` | Where the app keeps files it can recreate. | -| `appLogs` | Where the app writes logs. | - -When the environment variable `RN_GPUI_APP_DATA_DIR` is set to a non-empty folder, the three app folders move under it so several copies of an app can run with separate data without overriding `HOME`: `appData` is `$RN_GPUI_APP_DATA_DIR/`, `appCache` is `$RN_GPUI_APP_DATA_DIR/cache/` and `appLogs` is `$RN_GPUI_APP_DATA_DIR/logs/`. They are still created on first read. The other paths are unchanged. - -## Dialogs - -`dialog` opens the platform's file pickers. Cancelling is not an error: `open` resolves with an empty array, and `save` with `null`. - -```js -const [file] = await dialog.open({ - title: 'Choose a document', - filters: [{ name: 'Text', extensions: ['txt', 'md'] }], -}); - -const target = await dialog.save({ defaultName: 'export.json' }); -``` - -| `dialog.open` option | Description | -| -------------------- | ---------------------------------- | -| `title` | The title of the dialog. | -| `defaultPath` | The folder to start in. | -| `multiple` | Allow several files. | -| `directory` | Choose a folder instead of a file. | -| `filters` | `{name, extensions}` entries. | - -`dialog.save` takes `title`, `defaultPath`, `defaultName` and `filters`. On Linux the dialogs use the XDG portal, so GTK is not required. - -## Reveal and open - -```js -await fs.promises.reveal(path); // show the file in Finder, Explorer or the file manager -await fs.promises.openExternal(path); // open a file or URL with its default application -``` - -## Downloading - -`download(url, path, options)` streams an HTTP response into a file without holding it in memory. The body is written to `.part` and renamed onto `path` when it is complete, so `path` never holds half a file; an existing file is replaced only on success. The partial file is removed when the request fails or is aborted. - -```js -const controller = new AbortController(); - -const { status, headers, bytes } = await fs.download( - url, - `${paths.downloads}/report.pdf`, - { - headers: { Authorization: `Bearer ${token}` }, - onProgress: (received, total) => - setProgress(total > 0 ? received / total : 0), - signal: controller.signal, - }, -); -``` - -| Option | Description | -| ------------ | -------------------------------------------------------------------- | -| `method` | `GET` unless set. No request body is sent. | -| `headers` | Request headers. | -| `onProgress` | `(received, total)`; `total` is `-1` when the server gave no length. | -| `signal` | Aborting rejects with an `AbortError` within a fraction of a second. | - -The promise resolves with the final `status`, the response `headers` (lower-cased) and the `bytes` written. A status outside 200 to 299 rejects with `code` `ERR_HTTP_STATUS` and the `status`, `headers` and the first 2 KiB of the `body`, and writes nothing. Redirects are followed. A connection that closes before the announced length rejects, and the parent folder of `path` must exist. Certificates are checked against the operating system's store. - -## Uploading - -`upload(url, path, options)` sends a file, or a range of one, as an HTTP request body without holding it in memory. The native side reads the file in 64 KiB blocks while the connection takes them. - -```js -const { status, headers } = await fs.upload(url, `${paths.temp}/part-1`, { - method: 'PUT', - headers: { 'Content-Type': 'application/octet-stream' }, - offset: 0, - length: 10 * 1024 * 1024, - onProgress: (sent, total) => setProgress(sent / total), - signal: controller.signal, -}); -``` - -| Option | Description | -| ------------ | -------------------------------------------------------------------- | -| `method` | `PUT` unless set. | -| `headers` | Request headers. `Content-Length` is set from the range. | -| `offset` | Where in the file the body starts. Zero unless set. | -| `length` | How many bytes to send. Everything from `offset` unless set. | -| `onProgress` | `(sent, total)`. | -| `signal` | Aborting rejects with an `AbortError` within a fraction of a second. | - -The promise resolves with the final `status`, the response `headers` (lower-cased) and the first 2 KiB of the response `body`, whatever the status is, so a caller can read an `ETag` or an error document. A range past the end of the file rejects. Certificates are checked against the operating system's store. - -## Watching - -`watch(path, listener)` watches a file or folder, as in Node. The listener receives `'rename'` or `'change'` and the file name, and the watcher it returns has a `close()` method. diff --git a/vendor/react-native-gpui/modules/fs/package.json b/vendor/react-native-gpui/modules/fs/package.json deleted file mode 100644 index 601bc4dffd..0000000000 --- a/vendor/react-native-gpui/modules/fs/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@react-native-gpui/fs", - "version": "0.0.1-alpha.1", - "description": "File system access for React Native GPUI apps", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/streetwriters/react-native-gpui-modules.git", - "directory": "modules/fs" - }, - "homepage": "https://github.com/streetwriters/react-native-gpui-modules/tree/main/modules/fs#readme", - "bugs": { - "url": "https://github.com/streetwriters/react-native-gpui-modules/issues" - }, - "main": "src/index.ts", - "files": [ - "src", - "desktop", - "react-native.config.js", - "README.md", - "LICENSE", - "CHANGELOG.md", - "!**/*.test.js", - "!**/*.test.mjs", - "!**/*.test.ts", - "!**/*.test.cjs" - ], - "codegenConfig": { - "name": "RNFsModuleSpec", - "type": "modules", - "jsSrcsDir": "src" - }, - "peerDependencies": { - "react-native": "0.87.x" - }, - "publishConfig": { - "access": "public", - "tag": "latest" - } -} diff --git a/vendor/react-native-gpui/modules/fs/react-native.config.js b/vendor/react-native-gpui/modules/fs/react-native.config.js deleted file mode 100644 index 3ef720686e..0000000000 --- a/vendor/react-native-gpui/modules/fs/react-native.config.js +++ /dev/null @@ -1,9 +0,0 @@ -module.exports = { - dependency: { - platforms: { - desktop: { - crate: 'rn-gpui-fs', - }, - }, - }, -}; diff --git a/vendor/react-native-gpui/modules/fs/src/NativeFs.ts b/vendor/react-native-gpui/modules/fs/src/NativeFs.ts deleted file mode 100644 index fe2da60892..0000000000 --- a/vendor/react-native-gpui/modules/fs/src/NativeFs.ts +++ /dev/null @@ -1,235 +0,0 @@ -import type { CodegenTypes, TurboModule } from 'react-native'; -import { TurboModuleRegistry } from 'react-native'; - -/** - * How a path entry is classified: 0 file, 1 directory, 2 symlink, 3 other. - * - * A plain number rather than a string or enum so it crosses the bridge without a - * lookup table and survives being read back out of a plain object in JS. - */ -export type FileKind = number; - -export type StatResult = { - size: number; - mode: number; - kind: FileKind; - atimeMs: number; - mtimeMs: number; - ctimeMs: number; - birthtimeMs: number; - dev: number; - ino: number; - nlink: number; - uid: number; - gid: number; -}; - -export type DirEntry = { - name: string; - kind: FileKind; - parentPath: string; -}; - -export type DialogFilter = { - name: string; - extensions: Array; -}; - -export type OpenDialogOptions = { - title?: string; - defaultPath?: string; - multiple: boolean; - directory: boolean; - filters: Array; -}; - -export type SaveDialogOptions = { - title?: string; - defaultPath?: string; - defaultName?: string; - filters: Array; -}; - -export type KnownPaths = { - home: string; - documents: string; - downloads: string; - desktop: string; - temp: string; - appData: string; - appCache: string; - appLogs: string; -}; - -export type WatchEvent = { - id: number; - kind: string; - path: string; -}; - -export type DownloadHeader = { - name: string; - value: string; -}; - -export type DownloadOptions = { - id: number; - method: string; - headers: Array; -}; - -/** - * What a download resolves with. A non-2xx answer is not an error here: it - * comes back with its `status` and a small `body`, and no file is written. - */ -export type DownloadResult = { - status: number; - headers: Array; - bytes: number; - body?: string; -}; - -export type DownloadProgress = { - id: number; - received: number; - // -1 when the server did not say how long the body is. - total: number; -}; - -export type UploadOptions = { - id: number; - method: string; - headers: Array; - // Where in the file the body starts. - offset: number; - // How many bytes to send; -1 sends everything from `offset`. - length: number; -}; - -/** - * What an upload resolves with. Any status is a result; `body` is the first - * part of the response. - */ -export type UploadResult = { - status: number; - headers: Array; - body: string; -}; - -export type UploadProgress = { - id: number; - sent: number; - total: number; -}; - -/** - * The file system module: one instance, on its own thread, so a slow file never - * blocks JS or the UI. - * - * A method that returns a value runs on the JS thread; `void` and `Promise` - * methods run on the module's thread. The writers below therefore return - * `boolean` — a `void` method would be moved off the JS thread, which is wrong - * for a `*Sync` call. They always return true and throw on failure. - */ -export interface Spec extends TurboModule { - // Text is separate from bytes so a `utf8` read or write needs no buffer. - readFile(path: string): Promise; - readTextFile(path: string): Promise; - writeFile( - path: string, - data: ArrayBuffer, - flags: number, - mode: number, - ): Promise; - writeTextFile( - path: string, - data: string, - flags: number, - mode: number, - ): Promise; - - readdir(path: string, recursive: boolean): Promise>; - // `followSymlinks` false is `lstat`. - stat(path: string, followSymlinks: boolean): Promise; - mkdir(path: string, recursive: boolean, mode: number): Promise; - rm(path: string, recursive: boolean, force: boolean): Promise; - rename(from: string, to: string): Promise; - copy(from: string, to: string, recursive: boolean): Promise; - access(path: string, mode: number): Promise; - realpath(path: string): Promise; - readlink(path: string): Promise; - // `type` is Node's, and only Windows acts on it: `'dir'` and `'junction'` - // create a directory link, `null` decides from the resolved target, and a - // plain `'file'` is a file link. Unix ignores it, because the syscall does. - // Without it a Windows directory link was created as a file link and could - // not be traversed. - symlink(target: string, path: string, type: string | null): Promise; - truncate(path: string, length: number): Promise; - utimes(path: string, atimeMs: number, mtimeMs: number): Promise; - chmod(path: string, mode: number): Promise; - mkdtemp(prefix: string): Promise; - - // File handles. `position` -1 means "at the current offset". - open(path: string, flags: number, mode: number): Promise; - read(fd: number, length: number, position: number): Promise; - write(fd: number, data: ArrayBuffer, position: number): Promise; - fstat(fd: number): Promise; - fsync(fd: number): Promise; - ftruncate(fd: number, length: number): Promise; - close(fd: number): Promise; - - showOpenDialog(options: OpenDialogOptions): Promise>; - showSaveDialog(options: SaveDialogOptions): Promise; - reveal(path: string): Promise; - openExternal(path: string): Promise; - - // Returns the watcher id; events arrive through `onWatchEvent`. - watch(path: string, recursive: boolean): Promise; - unwatch(id: number): void; - - readFileSync(path: string): ArrayBuffer; - readTextFileSync(path: string): string; - writeFileSync( - path: string, - data: ArrayBuffer, - flags: number, - mode: number, - ): boolean; - writeTextFileSync( - path: string, - data: string, - flags: number, - mode: number, - ): boolean; - statSync(path: string, followSymlinks: boolean): StatResult | null; - existsSync(path: string): boolean; - readdirSync(path: string, recursive: boolean): Array; - mkdirSync(path: string, recursive: boolean, mode: number): boolean; - rmSync(path: string, recursive: boolean, force: boolean): boolean; - renameSync(from: string, to: string): boolean; - copyFileSync(from: string, to: string): boolean; - - download( - url: string, - path: string, - options: DownloadOptions, - ): Promise; - // Returns whether a download with that id was running. - cancelDownload(id: number): boolean; - - upload( - url: string, - path: string, - options: UploadOptions, - ): Promise; - // Returns whether an upload with that id was running. - cancelUpload(id: number): boolean; - - getPaths(): KnownPaths; - - readonly onWatchEvent: CodegenTypes.EventEmitter; - readonly onDownloadProgress: CodegenTypes.EventEmitter; - readonly onUploadProgress: CodegenTypes.EventEmitter; -} - -export default TurboModuleRegistry.getEnforcing('RNFsModule'); diff --git a/vendor/react-native-gpui/modules/fs/src/constants.ts b/vendor/react-native-gpui/modules/fs/src/constants.ts deleted file mode 100644 index c2740f3faa..0000000000 --- a/vendor/react-native-gpui/modules/fs/src/constants.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** - * `fs.constants`, with Node's numbers. - * - * The `O_*` values are Node's table rather than the platform's `open(2)` flags, - * because that is what the Rust side decodes: it translates them into - * `OpenOptions` instead of passing them through. The numbers here must stay in - * step with `modules/fs/desktop/src/module.rs`, which owns the other half of the - * contract. - */ - -export const constants = { - // `access` modes. - F_OK: 0, - X_OK: 1, - W_OK: 2, - R_OK: 4, - - // `open` flags. - O_RDONLY: 0, - O_WRONLY: 1, - O_RDWR: 2, - O_CREAT: 64, - O_EXCL: 128, - O_TRUNC: 512, - O_APPEND: 1024, - - // `copyFile` modes. - COPYFILE_EXCL: 1, - - // File-type bits, for the predicates on `Stats` that cannot be answered from - // the module's coarse `kind` alone (a socket and a block device are both - // "other" there). - S_IFMT: 0o170000, - S_IFREG: 0o100000, - S_IFDIR: 0o040000, - S_IFLNK: 0o120000, - S_IFBLK: 0o060000, - S_IFCHR: 0o020000, - S_IFIFO: 0o010000, - S_IFSOCK: 0o140000, -} as const; - -export type Constants = typeof constants; diff --git a/vendor/react-native-gpui/modules/fs/src/download.ts b/vendor/react-native-gpui/modules/fs/src/download.ts deleted file mode 100644 index c65c8f8ab8..0000000000 --- a/vendor/react-native-gpui/modules/fs/src/download.ts +++ /dev/null @@ -1,110 +0,0 @@ -/** - * `download`: an HTTP response streamed into a file. - * - * The body goes to `.part` as it arrives and is renamed onto `path` once it - * is complete, so `path` never holds half a file. The partial file is removed when - * the request fails or is aborted. - */ - -import NativeFs from './NativeFs'; -import { nodeError, toPath, withContext, type NodeError } from './shared'; - -export interface DownloadOptions { - /** `GET` unless set. No request body is sent. */ - method?: string; - headers?: Record; - /** Called while the body arrives; `total` is `-1` when the server did not say. */ - onProgress?: (received: number, total: number) => void; - /** Aborting rejects with an `AbortError` and removes the partial file. */ - signal?: AbortSignal; -} - -export interface DownloadResult { - status: number; - /** Response headers, lower-cased; repeated headers are joined with `, `. */ - headers: Record; - /** The size of the file that was written. */ - bytes: number; -} - -/** What a non-2xx response rejects with. */ -export interface DownloadHttpError extends NodeError { - status: number; - headers: Record; - /** The first part of the response body. */ - body: string; -} - -let nextId = 1; - -function abortError(): NodeError { - const error = nodeError('ABORT_ERR', 'The download was aborted'); - error.name = 'AbortError'; - return error; -} - -function toRecord(list: Array<{ name: string; value: string }>) { - const record: Record = {}; - for (const { name, value } of list) { - record[name] = value; - } - return record; -} - -export async function download( - url: string, - path: string, - options: DownloadOptions = {}, -): Promise { - const { signal, onProgress } = options; - if (signal?.aborted) { - throw abortError(); - } - const target = toPath(path); - const id = nextId++; - const subscription = onProgress - ? NativeFs.onDownloadProgress(event => { - if (event.id === id) { - onProgress(event.received, event.total); - } - }) - : null; - const onAbort = () => { - NativeFs.cancelDownload(id); - }; - signal?.addEventListener('abort', onAbort); - - try { - const result = await NativeFs.download(url, target, { - id, - method: options.method ?? 'GET', - headers: Object.entries(options.headers ?? {}).map(([name, value]) => ({ - name, - value, - })), - }); - const headers = toRecord(result.headers); - if (result.status < 200 || result.status >= 300) { - const error = nodeError( - 'ERR_HTTP_STATUS', - `HTTP ${result.status} downloading ${url}`, - ) as DownloadHttpError; - error.status = result.status; - error.headers = headers; - error.body = result.body ?? ''; - throw error; - } - return { status: result.status, headers, bytes: result.bytes }; - } catch (error) { - if (signal?.aborted) { - throw abortError(); - } - if ((error as NodeError)?.code === 'ABORT_ERR') { - throw abortError(); - } - throw withContext(error, 'download', target); - } finally { - signal?.removeEventListener('abort', onAbort); - subscription?.remove(); - } -} diff --git a/vendor/react-native-gpui/modules/fs/src/index.ts b/vendor/react-native-gpui/modules/fs/src/index.ts deleted file mode 100644 index c61cb0c096..0000000000 --- a/vendor/react-native-gpui/modules/fs/src/index.ts +++ /dev/null @@ -1,788 +0,0 @@ -/** - * `@react-native-gpui/fs`: a Node-shaped file API for the desktop app. - * - * The native module underneath is one TurboModule on its own thread with - * `ArrayBuffer` arguments and plain-object results. Everything Node adds on top - * of that — encodings, `Stats` and `Dirent` instances, callback forms, the - * `fs/promises` object — lives in this package's JS layer, so the bridge stays a - * byte mover and the API stays recognisably Node's. - * - * The default export is the `node:fs` object; `dialog`, `paths` and `watch` are - * named exports because they have no `fs` counterpart to hang off. - */ - -import { constants } from './constants'; -import NativeFs from './NativeFs'; -import { - Dirent, - FileHandle, - Stats, - promises, - readFileImpl, - type MkdirOptions, - type OpenOptions, - type RmOptions, - type WriteOptions, -} from './promises'; -import { - decodeString, - flagFrom, - missingPath, - modeFrom, - normalizeEncoding, - relativeEntryName, - toArrayBuffer, - toPath, - withContext, - type BinaryData, - type Encoding, - type NodeError, -} from './shared'; -import { download } from './download'; -import { upload } from './upload'; -import { watch } from './watch'; - -export type { - CpOptions, - MkdirOptions, - OpenOptions, - ReaddirOptions, - RmOptions, - TimeLike, - WriteOptions, -} from './promises'; -export type { BinaryData, Encoding, NodeError } from './shared'; -export type { UploadOptions, UploadResult } from './upload'; -export type { - DownloadHttpError, - DownloadOptions, - DownloadResult, -} from './download'; -export type { - FSWatcher, - WatchEventType, - WatchListener, - WatchOptions, -} from './watch'; -export { - Dirent, - Stats, - FileHandle, - promises, - constants, - watch, - download, - upload, -}; - -/* -------------------------------------------------------------------------- */ -/* Dialogs */ -/* -------------------------------------------------------------------------- */ - -export interface DialogFilter { - name: string; - extensions: Array; -} - -export interface OpenDialogOptions { - title?: string; - defaultPath?: string; - multiple?: boolean; - directory?: boolean; - filters?: Array; -} - -export interface SaveDialogOptions { - title?: string; - defaultPath?: string; - defaultName?: string; - filters?: Array; -} - -/** - * The native pickers. - * - * Cancelling is not an error: `open` resolves with `[]` and `save` with `null`, - * which is what the design specifies and what libraries pairing the two expect. - */ -export const dialog = { - async open(options: OpenDialogOptions = {}): Promise { - return NativeFs.showOpenDialog({ - title: options.title, - defaultPath: - options.defaultPath === undefined - ? undefined - : toPath(options.defaultPath), - multiple: options.multiple ?? false, - directory: options.directory ?? false, - filters: options.filters ?? [], - }); - }, - - async save(options: SaveDialogOptions = {}): Promise { - return NativeFs.showSaveDialog({ - title: options.title, - defaultPath: - options.defaultPath === undefined - ? undefined - : toPath(options.defaultPath), - defaultName: options.defaultName, - filters: options.filters ?? [], - }); - }, -}; - -/* -------------------------------------------------------------------------- */ -/* Known paths */ -/* -------------------------------------------------------------------------- */ - -/** The well-known directories, as the native side reports them. */ -export interface KnownPaths { - home: string; - documents: string; - downloads: string; - desktop: string; - temp: string; - appData: string; - appCache: string; - appLogs: string; -} - -const KNOWN_PATH_NAMES = [ - 'home', - 'documents', - 'downloads', - 'desktop', - 'temp', - 'appData', - 'appCache', - 'appLogs', -] as const; - -let cachedPaths: KnownPaths | null = null; - -/** - * Reads the known paths once and remembers them. - * - * Lazy rather than at import time so that importing this package cannot fail: the - * native module is only asked when an app actually names a directory, and the - * native side creates the per-app folders on that first read. - */ -function knownPaths(): KnownPaths { - if (cachedPaths === null) { - cachedPaths = NativeFs.getPaths(); - } - return cachedPaths; -} - -/** - * `paths.home`, `paths.documents` and the rest. - * - * Each property is a getter over one cached native read, so destructuring works - * and the object can be exported before the module has been asked anything. - */ -export const paths: KnownPaths = Object.defineProperties( - {}, - Object.fromEntries( - KNOWN_PATH_NAMES.map(name => [ - name, - { enumerable: true, get: () => knownPaths()[name] }, - ]), - ), -) as KnownPaths; - -/* -------------------------------------------------------------------------- */ -/* Sync forms */ -/* -------------------------------------------------------------------------- */ - -function readFileSync(path: string): Uint8Array; -function readFileSync( - path: string, - options: Encoding | { encoding: Encoding }, -): string; -function readFileSync( - path: string, - options?: Encoding | { encoding?: Encoding | null } | null, -): Uint8Array | string { - const target = toPath(path); - const encoding = - typeof options === 'string' ? options : (options?.encoding ?? null); - try { - if (encoding === null) { - return new Uint8Array(NativeFs.readFileSync(target)); - } - const normalized = normalizeEncoding(encoding) ?? 'utf8'; - if (normalized === 'utf8') { - // The dedicated text method decodes in Rust instead of handing JS bytes - // to decode a second time. - return NativeFs.readTextFileSync(target); - } - return decodeString( - new Uint8Array(NativeFs.readFileSync(target)), - normalized, - ); - } catch (error) { - throw withContext(error, 'open', target); - } -} - -function writeFileSync( - path: string, - data: BinaryData, - options?: WriteOptions | Encoding, -): void { - const target = toPath(path); - const opts: WriteOptions = - typeof options === 'string' ? { encoding: options } : (options ?? {}); - const flag = flagFrom( - opts.flag, - constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC, - ); - const mode = modeFrom(opts.mode); - try { - if (typeof data === 'string') { - const encoding = normalizeEncoding(opts.encoding ?? 'utf8') ?? 'utf8'; - if (encoding === 'utf8') { - NativeFs.writeTextFileSync(target, data, flag, mode); - return; - } - NativeFs.writeFileSync(target, toArrayBuffer(data, encoding), flag, mode); - return; - } - NativeFs.writeFileSync(target, toArrayBuffer(data), flag, mode); - } catch (error) { - throw withContext(error, 'open', target); - } -} - -function appendFileSync( - path: string, - data: BinaryData, - options?: WriteOptions | Encoding, -): void { - const opts: WriteOptions = - typeof options === 'string' ? { encoding: options } : (options ?? {}); - writeFileSync(path, data, { - ...opts, - flag: - opts.flag ?? constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND, - }); -} - -function existsSync(path: string): boolean { - try { - return NativeFs.existsSync(toPath(path)); - } catch { - // `existsSync` answers a question rather than reporting a failure, so every - // error — a permission problem as much as a missing path — is a `false`. - return false; - } -} - -function statSync(path: string): Stats { - const target = toPath(path); - try { - const result = NativeFs.statSync(target, true); - if (result === null) { - throw missingPath(target, 'stat'); - } - return new Stats(result); - } catch (error) { - throw withContext(error, 'stat', target); - } -} - -function lstatSync(path: string): Stats { - const target = toPath(path); - try { - const result = NativeFs.statSync(target, false); - if (result === null) { - throw missingPath(target, 'lstat'); - } - return new Stats(result); - } catch (error) { - throw withContext(error, 'lstat', target); - } -} - -function readdirSync( - path: string, - options?: { withFileTypes?: false; recursive?: boolean } | null, -): string[]; -function readdirSync( - path: string, - options: { withFileTypes: true; recursive?: boolean }, -): Dirent[]; -function readdirSync( - path: string, - options?: { withFileTypes?: boolean; recursive?: boolean } | null, -): string[] | Dirent[] { - const target = toPath(path); - try { - const recursive = options?.recursive ?? false; - const entries = NativeFs.readdirSync(target, recursive); - return options?.withFileTypes - ? entries.map(entry => new Dirent(entry)) - : entries.map(entry => - recursive - ? relativeEntryName(target, entry.parentPath, entry.name) - : entry.name, - ); - } catch (error) { - throw withContext(error, 'scandir', target); - } -} - -function mkdirSync(path: string, options?: MkdirOptions | number): void { - const target = toPath(path); - const opts: MkdirOptions = - typeof options === 'number' ? { mode: options } : (options ?? {}); - try { - NativeFs.mkdirSync( - target, - opts.recursive ?? false, - modeFrom(opts.mode, 0o777), - ); - } catch (error) { - throw withContext(error, 'mkdir', target); - } -} - -function rmSync(path: string, options?: RmOptions): void { - const target = toPath(path); - try { - NativeFs.rmSync( - target, - options?.recursive ?? false, - options?.force ?? false, - ); - } catch (error) { - throw withContext(error, 'rm', target); - } -} - -function renameSync(from: string, to: string): void { - const source = toPath(from); - const destination = toPath(to); - try { - NativeFs.renameSync(source, destination); - } catch (error) { - const wrapped = withContext(error, 'rename', source); - // Node's rename error names both ends; the second is `dest`, not `path`. - if (wrapped.dest === undefined) { - wrapped.dest = destination; - } - throw wrapped; - } -} - -function copyFileSync(from: string, to: string): void { - const source = toPath(from); - const destination = toPath(to); - try { - NativeFs.copyFileSync(source, destination); - } catch (error) { - const wrapped = withContext(error, 'copyfile', source); - if (wrapped.dest === undefined) { - wrapped.dest = destination; - } - throw wrapped; - } -} - -/* -------------------------------------------------------------------------- */ -/* Callback forms */ -/* -------------------------------------------------------------------------- */ - -/** - * The callback forms are wrappers over the promise implementations, as the - * design says, so there is one implementation of each operation. - * - * The trailing argument is the callback in every form; the optional argument - * before it is an options object (or an encoding, or a mode) when it is not a - * function. That is the whole of Node's overloading convention here. - */ - -type NodeCallback = (error: NodeError | null, value?: T) => void; - -function callbackOf(args: unknown[]): NodeCallback { - const callback = args[args.length - 1]; - if (typeof callback !== 'function') { - throw new TypeError('A callback function is required'); - } - return callback as NodeCallback; -} - -/** The options argument, if the caller supplied one rather than the callback. */ -function before(args: unknown[], index: number, fallback: T): T { - const value = args[index]; - return value === undefined || typeof value === 'function' - ? fallback - : (value as T); -} - -/** - * Reports a settled promise the Node way. - * - * A rejection that has a callback is delivered to it; nothing is thrown, because - * a throw from here would escape the caller's stack rather than the callback. - */ -function settle(promise: Promise, callback: NodeCallback): void { - promise.then( - value => callback(null, value), - (error: NodeError) => callback(error), - ); -} - -function readFile( - path: string, - callback: NodeCallback, -): void; -function readFile( - path: string, - options: Encoding | { encoding?: Encoding | null } | null, - callback: NodeCallback, -): void; -function readFile(path: string, ...args: unknown[]): void { - // The promise overloads keep the result precise; the callback form goes - // through the coarse alias because at that point the encoding is a runtime - // value and either shape is possible. - const options = before(args, 0, undefined) as - Encoding | { encoding?: Encoding | null } | null | undefined; - settle(readFileImpl(path, options), callbackOf(args)); -} - -function writeFile( - path: string, - data: BinaryData, - callback: NodeCallback, -): void; -function writeFile( - path: string, - data: BinaryData, - options: WriteOptions | Encoding | null, - callback: NodeCallback, -): void; -function writeFile(path: string, data: BinaryData, ...args: unknown[]): void { - settle( - promises.writeFile( - path, - data, - before(args, 0, undefined) as WriteOptions | Encoding | undefined, - ), - callbackOf(args), - ); -} - -function appendFile( - path: string, - data: BinaryData, - callback: NodeCallback, -): void; -function appendFile( - path: string, - data: BinaryData, - options: WriteOptions | Encoding | null, - callback: NodeCallback, -): void; -function appendFile(path: string, data: BinaryData, ...args: unknown[]): void { - settle( - promises.appendFile( - path, - data, - before(args, 0, undefined) as WriteOptions | Encoding | undefined, - ), - callbackOf(args), - ); -} - -function readdir( - path: string, - callback: NodeCallback, -): void; -function readdir( - path: string, - options: { withFileTypes?: boolean; recursive?: boolean } | null, - callback: NodeCallback, -): void; -function readdir(path: string, ...args: unknown[]): void { - const options = before(args, 0, null) as { - withFileTypes?: boolean; - recursive?: boolean; - } | null; - const pending: Promise = options?.withFileTypes - ? promises.readdir(path, { ...options, withFileTypes: true }) - : promises.readdir(path, { - recursive: options?.recursive, - withFileTypes: false, - }); - settle(pending, callbackOf(args)); -} - -function stat(path: string, callback: NodeCallback): void; -function stat(path: string, ...args: unknown[]): void { - settle(promises.stat(path), callbackOf([...args])); -} - -function lstat(path: string, callback: NodeCallback): void; -function lstat(path: string, ...args: unknown[]): void { - settle(promises.lstat(path), callbackOf([...args])); -} - -function mkdir(path: string, callback: NodeCallback): void; -function mkdir( - path: string, - options: MkdirOptions | number | null, - callback: NodeCallback, -): void; -function mkdir(path: string, ...args: unknown[]): void { - settle( - promises.mkdir( - path, - before(args, 0, undefined) as MkdirOptions | number | undefined, - ), - callbackOf(args), - ); -} - -function rm(path: string, callback: NodeCallback): void; -function rm( - path: string, - options: RmOptions | null, - callback: NodeCallback, -): void; -function rm(path: string, ...args: unknown[]): void { - settle( - promises.rm(path, before(args, 0, undefined) as RmOptions | undefined), - callbackOf(args), - ); -} - -function rename(from: string, to: string, callback: NodeCallback): void; -function rename(from: string, to: string, ...args: unknown[]): void { - settle(promises.rename(from, to), callbackOf([...args])); -} - -function copyFile(from: string, to: string, callback: NodeCallback): void; -function copyFile( - from: string, - to: string, - mode: number, - callback: NodeCallback, -): void; -function copyFile(from: string, to: string, ...args: unknown[]): void { - settle( - promises.copyFile( - from, - to, - before(args, 0, undefined) as number | undefined, - ), - callbackOf(args), - ); -} - -function cp(from: string, to: string, callback: NodeCallback): void; -function cp( - from: string, - to: string, - options: { recursive?: boolean } | null, - callback: NodeCallback, -): void; -function cp(from: string, to: string, ...args: unknown[]): void { - settle( - promises.cp( - from, - to, - before(args, 0, undefined) as { recursive?: boolean } | undefined, - ), - callbackOf(args), - ); -} - -function access(path: string, callback: NodeCallback): void; -function access(path: string, mode: number, callback: NodeCallback): void; -function access(path: string, ...args: unknown[]): void { - settle( - promises.access(path, before(args, 0, undefined) as number | undefined), - callbackOf(args), - ); -} - -function realpath(path: string, callback: NodeCallback): void; -function realpath(path: string, ...args: unknown[]): void { - settle(promises.realpath(path), callbackOf([...args])); -} - -function readlink(path: string, callback: NodeCallback): void; -function readlink(path: string, ...args: unknown[]): void { - settle(promises.readlink(path), callbackOf([...args])); -} - -function symlink( - target: string, - path: string, - callback: NodeCallback, -): void; -function symlink( - target: string, - path: string, - type: string, - callback: NodeCallback, -): void; -function symlink(target: string, path: string, ...args: unknown[]): void { - settle( - promises.symlink( - target, - path, - before(args, 0, undefined) as 'file' | 'dir' | 'junction' | undefined, - ), - callbackOf(args), - ); -} - -function truncate(path: string, callback: NodeCallback): void; -function truncate( - path: string, - length: number, - callback: NodeCallback, -): void; -function truncate(path: string, ...args: unknown[]): void { - settle( - promises.truncate(path, before(args, 0, undefined) as number | undefined), - callbackOf(args), - ); -} - -function utimes( - path: string, - atime: Date | number | string, - mtime: Date | number | string, - callback: NodeCallback, -): void; -function utimes( - path: string, - atime: Date | number | string, - mtime: Date | number | string, - ...args: unknown[] -): void { - settle(promises.utimes(path, atime, mtime), callbackOf([...args])); -} - -function chmod( - path: string, - mode: number | string, - callback: NodeCallback, -): void; -function chmod(path: string, mode: number | string, ...args: unknown[]): void { - settle(promises.chmod(path, mode), callbackOf([...args])); -} - -function mkdtemp(prefix: string, callback: NodeCallback): void; -function mkdtemp( - prefix: string, - options: Encoding | { encoding?: Encoding }, - callback: NodeCallback, -): void; -function mkdtemp(prefix: string, ...args: unknown[]): void { - settle( - promises.mkdtemp( - prefix, - before(args, 0, undefined) as - Encoding | { encoding?: Encoding } | undefined, - ), - callbackOf(args), - ); -} - -function open(path: string, callback: NodeCallback): void; -function open( - path: string, - flags: string | number | OpenOptions, - callback: NodeCallback, -): void; -function open( - path: string, - flags: string | number | OpenOptions, - mode: number | string, - callback: NodeCallback, -): void; -function open(path: string, ...args: unknown[]): void { - const flags = before(args, 0, undefined) as - string | number | OpenOptions | undefined; - const mode = before(args, 1, undefined) as number | string | undefined; - settle( - mode === undefined - ? promises.open(path, flags) - : promises.open(path, flags, mode), - callbackOf(args), - ); -} - -function reveal(path: string, callback: NodeCallback): void; -function reveal(path: string, ...args: unknown[]): void { - settle(promises.reveal(path), callbackOf([...args])); -} - -function openExternal(path: string, callback: NodeCallback): void; -function openExternal(path: string, ...args: unknown[]): void { - settle(promises.openExternal(path), callbackOf([...args])); -} - -/* -------------------------------------------------------------------------- */ -/* The `fs` object */ -/* -------------------------------------------------------------------------- */ - -/** - * Node's `fs`, as far as this platform implements it. - * - * The callback forms wrap the promise implementations; the sync forms call the - * bridge's JS-thread methods directly; `promises` is the same object shape Node - * exposes as `fs.promises`. - */ -const fs = { - constants, - promises, - - readFile, - writeFile, - appendFile, - readdir, - stat, - lstat, - mkdir, - rm, - rename, - copyFile, - cp, - access, - realpath, - readlink, - symlink, - truncate, - utimes, - chmod, - mkdtemp, - open, - reveal, - openExternal, - download, - upload, - - readFileSync, - writeFileSync, - appendFileSync, - existsSync, - statSync, - lstatSync, - readdirSync, - mkdirSync, - rmSync, - renameSync, - copyFileSync, - - Stats, - Dirent, - FileHandle, -}; - -export default fs; diff --git a/vendor/react-native-gpui/modules/fs/src/promises.ts b/vendor/react-native-gpui/modules/fs/src/promises.ts deleted file mode 100644 index 155f3fb467..0000000000 --- a/vendor/react-native-gpui/modules/fs/src/promises.ts +++ /dev/null @@ -1,771 +0,0 @@ -/** - * `fs.promises`: the Node-shaped asynchronous face of the module. - * - * Every call here is a thin translation. The native side does the work on its own - * thread and reports Node codes, so this layer's job is argument shapes, the - * encodings Node implements above the bytes, and the fields (`syscall`, `path`, - * `dest`) that only a wrapper can know. - */ - -import NativeFs from './NativeFs'; -import { constants } from './constants'; -import { - checkBufferRange, - decodeString, - encodeString, - flagFrom, - modeFrom, - nodeError, - normalizeEncoding, - relativeEntryName, - toArrayBuffer, - toBytes, - toPath, - withContext, - type BinaryData, - type Encoding, - type NormalizedEncoding, -} from './shared'; -import { Dirent, Stats, type DirEntryResult, type StatResult } from './stats'; - -/** An encoding, an options object, or nothing, as Node accepts for reads. */ -export type ReadOptions = - Encoding | { encoding?: Encoding | null } | null | undefined; - -export interface WriteOptions { - encoding?: Encoding | null; - mode?: number | string; - flag?: string | number; -} - -export interface MkdirOptions { - recursive?: boolean; - mode?: number | string; -} - -export interface RmOptions { - recursive?: boolean; - force?: boolean; -} - -export interface ReaddirOptions { - withFileTypes?: boolean; - recursive?: boolean; -} - -export interface CpOptions { - recursive?: boolean; -} - -export interface OpenOptions { - flags?: string | number; - mode?: number | string; -} - -/** The chunk size for a read that has no caller-supplied buffer. */ -const READ_CHUNK = 64 * 1024; - -/** A time as Node accepts one: `Date`, milliseconds, or a date string. */ -export type TimeLike = Date | number | string; - -function toMillis(value: TimeLike, name: string): number { - if (value instanceof Date) { - return value.getTime(); - } - if (typeof value === 'number') { - return value; - } - const parsed = Date.parse(value); - if (Number.isNaN(parsed)) { - throw nodeError( - 'ERR_INVALID_ARG_VALUE', - `The argument '${name}' is invalid time. Received '${value}'`, - ); - } - return parsed; -} - -function encodingOf(options: ReadOptions): NormalizedEncoding | null { - if (typeof options === 'string') { - return normalizeEncoding(options); - } - return normalizeEncoding(options?.encoding ?? null); -} - -/** - * `readFile`, in whichever of the two shapes the caller asked for. - * - * UTF-8 goes through the dedicated text method: the native side decodes it while - * the bytes are still in Rust, so a text read never allocates an `ArrayBuffer` - * that JS then copies. Every other encoding is decoded here, because Node's - * `utf16le`, `latin1`, `base64` and `hex` are JS-level conventions rather than - * something `std::fs` has an opinion about. - */ -function readFile(path: string): Promise; -function readFile( - path: string, - options: { encoding?: null } | null | undefined, -): Promise; -function readFile( - path: string, - options: Encoding | { encoding: Encoding }, -): Promise; -async function readFile( - path: string, - options?: ReadOptions, -): Promise { - const target = toPath(path); - const encoding = encodingOf(options); - try { - if (encoding === 'utf8') { - return await NativeFs.readTextFile(target); - } - const buffer = await NativeFs.readFile(target); - const bytes = new Uint8Array(buffer); - return encoding === null ? bytes : decodeString(bytes, encoding); - } catch (error) { - throw withContext(error, 'open', target); - } -} - -/** - * The same read, typed coarsely. - * - * `readFile`'s public overloads are what a caller sees; the callback layer calls - * through this alias because at that point the encoding is a runtime value and - * the result is genuinely either shape. - */ -export const readFileImpl: ( - path: string, - options?: ReadOptions, -) => Promise = readFile; - -/** - * `writeFile`. - * - * A string is written through `writeTextFile` when it is UTF-8; anything else — - * a different encoding, or binary data — is normalised to an `ArrayBuffer` and - * sent through the byte method. - */ -async function writeFile( - path: string, - data: BinaryData, - options?: WriteOptions | Encoding, -): Promise { - const target = toPath(path); - const opts: WriteOptions = - typeof options === 'string' ? { encoding: options } : (options ?? {}); - const flag = flagFrom( - opts.flag, - constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC, - ); - const mode = modeFrom(opts.mode); - try { - if (typeof data === 'string') { - // `normalizeEncoding` answers `null` only when it is given nothing, and a - // default is supplied here, so the fallback to `utf8` is unreachable — it - // exists to keep the type honest instead of asserting it away. - const encoding = normalizeEncoding(opts.encoding ?? 'utf8') ?? 'utf8'; - if (encoding === 'utf8') { - await NativeFs.writeTextFile(target, data, flag, mode); - } else { - await NativeFs.writeFile( - target, - toArrayBuffer(encodeString(data, encoding)), - flag, - mode, - ); - } - return; - } - await NativeFs.writeFile(target, toArrayBuffer(data), flag, mode); - } catch (error) { - throw withContext(error, 'open', target); - } -} - -async function appendFile( - path: string, - data: BinaryData, - options?: WriteOptions | Encoding, -): Promise { - const opts: WriteOptions = - typeof options === 'string' ? { encoding: options } : (options ?? {}); - return writeFile(path, data, { - ...opts, - flag: - opts.flag ?? constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND, - }); -} - -function readdir( - path: string, - options?: { withFileTypes?: false; recursive?: boolean } | null, -): Promise; -function readdir( - path: string, - options: { withFileTypes: true; recursive?: boolean }, -): Promise; -async function readdir( - path: string, - options?: ReaddirOptions | null, -): Promise { - const target = toPath(path); - try { - const recursive = options?.recursive ?? false; - const entries = await NativeFs.readdir(target, recursive); - return options?.withFileTypes - ? entries.map(entry => new Dirent(entry as DirEntryResult)) - : entries.map(entry => - recursive - ? relativeEntryName(target, entry.parentPath, entry.name) - : entry.name, - ); - } catch (error) { - throw withContext(error, 'scandir', target); - } -} - -async function stat(path: string): Promise { - const target = toPath(path); - try { - return new Stats((await NativeFs.stat(target, true)) as StatResult); - } catch (error) { - throw withContext(error, 'stat', target); - } -} - -async function lstat(path: string): Promise { - const target = toPath(path); - try { - return new Stats((await NativeFs.stat(target, false)) as StatResult); - } catch (error) { - throw withContext(error, 'lstat', target); - } -} - -async function mkdir( - path: string, - options?: MkdirOptions | number, -): Promise { - const target = toPath(path); - const opts: MkdirOptions = - typeof options === 'number' ? { mode: options } : (options ?? {}); - try { - await NativeFs.mkdir( - target, - opts.recursive ?? false, - modeFrom(opts.mode, 0o777), - ); - return undefined; - } catch (error) { - throw withContext(error, 'mkdir', target); - } -} - -async function rm(path: string, options?: RmOptions): Promise { - const target = toPath(path); - try { - await NativeFs.rm( - target, - options?.recursive ?? false, - options?.force ?? false, - ); - } catch (error) { - throw withContext(error, 'rm', target); - } -} - -async function rename(from: string, to: string): Promise { - const source = toPath(from); - const destination = toPath(to); - try { - await NativeFs.rename(source, destination); - } catch (error) { - // Node's rename error names both ends; the second is `dest`, not `path`. - const wrapped = withContext(error, 'rename', source); - if (wrapped.dest === undefined) { - wrapped.dest = destination; - } - throw wrapped; - } -} - -async function copyFile( - from: string, - to: string, - mode?: number, -): Promise { - const source = toPath(from); - const destination = toPath(to); - if (mode !== undefined && (mode & constants.COPYFILE_EXCL) !== 0) { - // The native copy has no exclusive flag, so the check is made here. It is - // advisory — a file created between the two calls still wins — but it gives - // the caller the error Node promises for the ordinary case. - try { - await NativeFs.stat(destination, false); - throw nodeError( - 'EEXIST', - `EEXIST: file already exists, copyfile '${source}' -> '${destination}'`, - ); - } catch (error) { - if ((error as { code?: string }).code !== 'ENOENT') { - throw error; - } - } - } - try { - await NativeFs.copy(source, destination, false); - } catch (error) { - const wrapped = withContext(error, 'copyfile', source); - if (wrapped.dest === undefined) { - wrapped.dest = destination; - } - throw wrapped; - } -} - -async function cp( - from: string, - to: string, - options?: CpOptions, -): Promise { - const source = toPath(from); - const destination = toPath(to); - try { - await NativeFs.copy(source, destination, options?.recursive ?? false); - } catch (error) { - const wrapped = withContext(error, 'cp', source); - if (wrapped.dest === undefined) { - wrapped.dest = destination; - } - throw wrapped; - } -} - -async function access(path: string, mode?: number): Promise { - const target = toPath(path); - try { - await NativeFs.access(target, mode ?? constants.F_OK); - } catch (error) { - throw withContext(error, 'access', target); - } -} - -async function realpath(path: string): Promise { - const target = toPath(path); - try { - return await NativeFs.realpath(target); - } catch (error) { - throw withContext(error, 'realpath', target); - } -} - -async function readlink(path: string): Promise { - const target = toPath(path); - try { - return await NativeFs.readlink(target); - } catch (error) { - throw withContext(error, 'readlink', target); - } -} - -async function symlink( - target: string, - path: string, - type?: 'file' | 'dir' | 'junction', -): Promise { - // `type` is passed through rather than dropped. It is the only way to ask for a - // directory link on Windows, where creating one as a file link leaves a path - // that cannot be traversed; Unix ignores it, as the syscall does. - const link = toPath(path); - try { - await NativeFs.symlink(toPath(target), link, type ?? null); - } catch (error) { - throw withContext(error, 'symlink', link); - } -} - -async function truncate(path: string, length?: number): Promise { - const target = toPath(path); - try { - await NativeFs.truncate(target, length ?? 0); - } catch (error) { - throw withContext(error, 'truncate', target); - } -} - -async function utimes( - path: string, - atime: TimeLike, - mtime: TimeLike, -): Promise { - const target = toPath(path); - try { - await NativeFs.utimes( - target, - toMillis(atime, 'atime'), - toMillis(mtime, 'mtime'), - ); - } catch (error) { - throw withContext(error, 'utime', target); - } -} - -async function chmod(path: string, mode: number | string): Promise { - const target = toPath(path); - try { - await NativeFs.chmod(target, modeFrom(mode)); - } catch (error) { - throw withContext(error, 'chmod', target); - } -} - -async function mkdtemp( - prefix: string, - options?: Encoding | { encoding?: Encoding }, -): Promise { - // The native side creates the directory under the system temp directory and - // returns the path; the encoding only affects how a non-ASCII prefix arrives, - // and every string crosses the bridge as UTF-8. - options; - try { - return await NativeFs.mkdtemp(toPath(prefix)); - } catch (error) { - throw withContext(error, 'mkdtemp', prefix); - } -} - -/** - * A descriptor plus the operations Node puts on `FileHandle`. - * - * Positioned reads and writes do not touch the file's offset, which is what - * makes concurrent chunked I/O safe: two readers on one handle cannot move each - * other's cursor. - */ -export class FileHandle { - /** The native descriptor. */ - readonly fd: number; - private closed = false; - - constructor(fd: number) { - this.fd = fd; - } - - private assertOpen(): void { - if (this.closed) { - throw nodeError('EBADF', `EBADF: bad file descriptor, ${this.fd}`); - } - } - - /** Reads from the current offset when `position` is `-1`. */ - async read(): Promise<{ bytesRead: number; buffer: Uint8Array }>; - async read(options: { - buffer?: Uint8Array; - offset?: number; - length?: number; - position?: number | null; - }): Promise<{ bytesRead: number; buffer: Uint8Array }>; - async read( - buffer: Uint8Array, - offset?: number, - length?: number, - position?: number | null, - ): Promise<{ bytesRead: number; buffer: Uint8Array }>; - /** - * Node's positional form with the buffer implied: `read(size, offset, length, - * position)`. `offset` and `length` are a window into the freshly allocated - * buffer, and a missing `position` reads from the cursor. - */ - async read( - size: number, - offset?: number, - length?: number, - position?: number | null, - ): Promise<{ bytesRead: number; buffer: Uint8Array }>; - async read( - first?: - | number - | Uint8Array - | { - buffer?: Uint8Array; - offset?: number; - length?: number; - position?: number | null; - }, - second?: number, - third?: number, - fourth?: number | null, - ): Promise<{ bytesRead: number; buffer: Uint8Array }> { - this.assertOpen(); - let destination: Uint8Array; - let offset = 0; - let length: number; - let position: number; - // The two no-buffer forms mean "read to the end", which is a different - // operation from a single bounded read and is handled by `readToEnd`. - let toEnd = false; - if (first === undefined) { - toEnd = true; - destination = new Uint8Array(0); - length = 0; - position = -1; - } else if (typeof first === 'number') { - // A size instead of a buffer: allocate it and apply the same window - // arguments Node's buffer form takes. - destination = new Uint8Array(first); - offset = second ?? 0; - length = third ?? Math.max(destination.byteLength - offset, 0); - position = fourth ?? -1; - } else if (first instanceof Uint8Array) { - destination = first; - offset = second ?? 0; - length = third ?? destination.byteLength - offset; - position = fourth ?? -1; - } else { - destination = first.buffer ?? new Uint8Array(0); - offset = first.offset ?? 0; - length = first.length ?? Math.max(destination.byteLength - offset, 0); - position = first.position ?? -1; - toEnd = first.buffer === undefined; - } - - try { - if (toEnd) { - const bytes = await this.readToEnd(position); - return { bytesRead: bytes.byteLength, buffer: bytes }; - } - // Validated before the native call, not after. The native side reads - // `length` bytes and advances the cursor, so a window that overruns the - // buffer used to consume bytes and then drop them when the result was - // trimmed to fit. Node rejects the call instead, and so must this. - const window = checkBufferRange(destination, offset, length); - const buffer = await NativeFs.read(this.fd, window.length, position); - const bytes = new Uint8Array(buffer); - const bytesRead = Math.min(bytes.byteLength, window.length); - destination.set(bytes.subarray(0, bytesRead), window.offset); - return { bytesRead, buffer: destination }; - } catch (error) { - throw withContext(error, 'read', undefined); - } - } - - /** - * Reads until a short read, which is end of file. - * - * The native `read` returns at most what it was asked for, so "the rest of the - * file" has to be assembled: a single call with a huge length would ask Rust to - * allocate that much up front. A cursor read (`position` -1) advances the - * handle's offset, so the loop continues where the previous chunk ended. - */ - private async readToEnd(position: number): Promise { - const chunks: Uint8Array[] = []; - let total = 0; - let at = position; - for (;;) { - const buffer = await NativeFs.read(this.fd, READ_CHUNK, at); - const chunk = new Uint8Array(buffer); - if (chunk.byteLength === 0) { - break; - } - chunks.push(chunk); - total += chunk.byteLength; - if (chunk.byteLength < READ_CHUNK) { - break; - } - if (at >= 0) { - at += chunk.byteLength; - } - } - const all = new Uint8Array(total); - let cursor = 0; - for (const chunk of chunks) { - all.set(chunk, cursor); - cursor += chunk.byteLength; - } - return all; - } - - async write( - data: BinaryData, - position?: number | null, - encoding?: Encoding, - ): Promise<{ bytesWritten: number; buffer: Uint8Array }>; - async write( - buffer: Uint8Array, - offset: number, - length: number, - position?: number | null, - ): Promise<{ bytesWritten: number; buffer: Uint8Array }>; - async write( - data: BinaryData, - second?: number | null, - third?: number | Encoding, - fourth?: number | null, - ): Promise<{ bytesWritten: number; buffer: Uint8Array }> { - this.assertOpen(); - let bytes: Uint8Array; - let position: number | null = null; - if (typeof data === 'string') { - // `write(string, position, encoding)`: here the number is a file position. - const encodingName = - typeof third === 'string' ? normalizeEncoding(third) : 'utf8'; - bytes = encodeString(data, encodingName ?? 'utf8'); - position = second ?? null; - } else if ( - data instanceof Uint8Array && - third !== undefined && - typeof third !== 'number' - ) { - // `write(buffer, { offset, length, position })`, which Node also accepts. - const options = third as unknown as { - offset?: number; - length?: number; - position?: number | null; - }; - const window = checkBufferRange(data, options.offset, options.length); - bytes = data.subarray(window.offset, window.offset + window.length); - position = options.position ?? null; - } else if ( - data instanceof Uint8Array && - second !== undefined && - second !== null - ) { - // `write(buffer, offset[, length[, position]])` — the numeric argument is - // into the *buffer*, not into the file. Reading it as a file position - // wrote the whole buffer at that offset instead of a slice at the cursor. - const window = checkBufferRange( - data, - second, - typeof third === 'number' ? third : undefined, - ); - bytes = data.subarray(window.offset, window.offset + window.length); - position = fourth ?? null; - } else { - bytes = toBytes(data); - position = typeof second === 'number' ? second : null; - } - try { - const bytesWritten = await NativeFs.write( - this.fd, - toArrayBuffer(bytes), - position ?? -1, - ); - return { bytesWritten, buffer: bytes }; - } catch (error) { - throw withContext(error, 'write', undefined); - } - } - - async stat(): Promise { - this.assertOpen(); - try { - return new Stats((await NativeFs.fstat(this.fd)) as StatResult); - } catch (error) { - throw withContext(error, 'fstat', undefined); - } - } - - async sync(): Promise { - this.assertOpen(); - try { - await NativeFs.fsync(this.fd); - } catch (error) { - throw withContext(error, 'fsync', undefined); - } - } - - async truncate(length?: number): Promise { - this.assertOpen(); - try { - await NativeFs.ftruncate(this.fd, length ?? 0); - } catch (error) { - throw withContext(error, 'ftruncate', undefined); - } - } - - async close(): Promise { - if (this.closed) { - return; - } - this.closed = true; - try { - await NativeFs.close(this.fd); - } catch (error) { - throw withContext(error, 'close', undefined); - } - } -} - -async function open( - path: string, - flags?: string | number | OpenOptions, - mode?: number | string, -): Promise { - const target = toPath(path); - const opts: OpenOptions = - typeof flags === 'object' && flags !== null ? flags : { flags, mode }; - const flag = flagFrom(opts.flags, constants.O_RDONLY); - try { - const fd = await NativeFs.open(target, flag, modeFrom(opts.mode)); - return new FileHandle(fd); - } catch (error) { - throw withContext(error, 'open', target); - } -} - -async function reveal(path: string): Promise { - const target = toPath(path); - try { - await NativeFs.reveal(target); - } catch (error) { - throw withContext(error, 'reveal', target); - } -} - -async function openExternal(path: string): Promise { - const target = toPath(path); - try { - await NativeFs.openExternal(target); - } catch (error) { - throw withContext(error, 'openExternal', target); - } -} - -/** - * The `fs/promises` object. - * - * The functions are declared separately and collected here so the callback layer - * in `index.ts` can wrap the same implementations rather than reimplementing - * them. - */ -export const promises = { - readFile, - writeFile, - appendFile, - readdir, - stat, - lstat, - mkdir, - rm, - rename, - copyFile, - cp, - access, - realpath, - readlink, - symlink, - truncate, - utimes, - chmod, - mkdtemp, - open, - reveal, - openExternal, -}; - -export type Promises = typeof promises; - -/** Re-exported so `fs.stat` and `fs.promises.stat` share one class identity. */ -export { Dirent, Stats }; -export type { StatResult }; diff --git a/vendor/react-native-gpui/modules/fs/src/shared.ts b/vendor/react-native-gpui/modules/fs/src/shared.ts deleted file mode 100644 index b4714eadc4..0000000000 --- a/vendor/react-native-gpui/modules/fs/src/shared.ts +++ /dev/null @@ -1,539 +0,0 @@ -/** - * The pieces every face of the API needs: Node error objects, `file://` path - * conversion, the encodings Node supports, and the flag/mode translation. - * - * Nothing here touches the native module, so it stays usable from the sync, - * callback and promise layers without a cycle. - */ - -/** Bytes in any of the shapes a caller may hand a writer. */ -export type BinaryData = string | ArrayBuffer | ArrayBufferView; - -/** The encodings this module implements, after aliasing. */ -export type NormalizedEncoding = - 'utf8' | 'utf16le' | 'latin1' | 'base64' | 'hex'; - -/** The encodings accepted in an options object, with Node's aliases. */ -export type Encoding = - | 'utf8' - | 'utf-8' - | 'utf16le' - | 'utf-16le' - | 'ucs2' - | 'ucs-2' - | 'latin1' - | 'binary' - | 'ascii' - | 'base64' - | 'hex'; - -/** What a rejected call looks like: Node's `ErrnoException`. */ -export interface NodeError extends Error { - code?: string; - errno?: number; - syscall?: string; - path?: string; - /** The second path of a two-path call, as Node names it on `rename` and `cp`. */ - dest?: string; -} - -/** Builds an error with a code but no OS call behind it. */ -export function nodeError(code: string, message: string): NodeError { - const error = new Error(message) as NodeError; - error.code = code; - return error; -} - -/** The error Node raises when a path is not there, in its message format. */ -export function missingPath(path: string, syscall: string): NodeError { - return nodeError( - 'ENOENT', - `ENOENT: no such file or directory, ${syscall} '${path}'`, - ); -} - -/** - * Adds the fields only the JS side knows to an error a native call rejected - * with. - * - * The Rust layer reports `code` and a Node-format message, but it deliberately - * does not guess `syscall` — one native `stat` serves `stat` and `lstat`, and it - * cannot know the spelling of the path the caller passed. - */ -export function withContext( - error: unknown, - syscall: string, - path?: string, -): NodeError { - const wrapped: NodeError = - error instanceof Error - ? (error as NodeError) - : nodeError('EIO', String(error)); - if (wrapped.syscall === undefined) { - wrapped.syscall = syscall; - } - if (path !== undefined && wrapped.path === undefined) { - wrapped.path = path; - } - return wrapped; -} - -/** - * `file://` URLs to paths, leaving plain paths alone. - * - * Node accepts `URL` objects and `file:` strings interchangeably; this API takes - * strings, so the conversion is textual. Percent escapes are decoded because a - * path with a space arrives as `file:///a%20b`. - */ -export function toPath(path: string): string { - if (!path.startsWith('file://')) { - return path; - } - let rest = path.slice('file://'.length); - // An empty or `localhost` authority is the local machine. - if (rest.startsWith('localhost/')) { - rest = rest.slice('localhost'.length); - } - const decoded = decodeURIComponent(rest); - // `file:///C:/x` is a drive path on Windows, not a path under `/`. - if (/^\/[A-Za-z]:[\\/]/.test(decoded)) { - return decoded.slice(1); - } - return decoded; -} - -/** - * Node's bounds check for a buffer window, as `RangeError` with - * `code = 'ERR_OUT_OF_RANGE'`. - * - * Both `read` and `write` take a window into a caller's buffer, and the native - * side reads or writes `length` bytes before the result is trimmed to fit — so an - * oversized `length` would consume bytes from the file and silently drop them - * rather than failing. Node rejects the call instead, and its wording is - * reproduced because callers match on it: - * - * The value of "length" is out of range. It must be <= 2. Received 8 - */ -export function checkBufferRange( - buffer: Uint8Array, - offset: number | undefined, - length: number | undefined, -): { offset: number; length: number } { - const start = offset ?? 0; - if (!Number.isInteger(start) || start < 0 || start > buffer.byteLength) { - throw nodeError( - 'ERR_OUT_OF_RANGE', - `The value of "offset" is out of range. It must be >= 0 && <= ${buffer.byteLength}. Received ${start}`, - ); - } - const count = length ?? buffer.byteLength - start; - const available = buffer.byteLength - start; - if (!Number.isInteger(count) || count < 0 || count > available) { - throw nodeError( - 'ERR_OUT_OF_RANGE', - `The value of "length" is out of range. It must be <= ${available}. Received ${count}`, - ); - } - return { offset: start, length: count }; -} - -/** - * A recursive `readdir` entry as the path Node reports. - * - * Node's `readdir(dir, { recursive: true })` returns paths relative to `dir` - * — `nested/deep/leaf.txt`, not `leaf.txt` — so a caller can join them onto the - * root and get a real path. The native side reports each entry's absolute - * containing directory, so the relative name is what remains after removing the - * root. A non-recursive listing names the direct children only, which is already - * what `entry.name` holds, so this is used for the recursive case alone. - * - * The separator is taken from the paths themselves rather than from a platform - * check: the native side returns native separators, and a module that reaches - * for `process.platform` needs Node's types for a question the data already - * answers. - */ -export function relativeEntryName( - root: string, - parentPath: string, - name: string, -): string { - const separator = root.includes('\\') ? '\\' : '/'; - const split = (value: string) => value.split(/[\\/]+/u).filter(Boolean); - const rootParts = split(root); - const parentParts = split(parentPath); - // Compare from the front. A parent that does not start with the root means the - // entry is somewhere the caller did not ask about, which should not happen, so - // the bare name is a safer answer than a fabricated path. - const inside = rootParts.every((part, index) => parentParts[index] === part); - if (!inside) { - return name; - } - return [...parentParts.slice(rootParts.length), name].join(separator); -} - -/** The encoding name, folded to the set implemented here. */ -export function normalizeEncoding( - encoding: string | null | undefined, -): NormalizedEncoding | null { - if (encoding === null || encoding === undefined) { - return null; - } - switch (encoding.toLowerCase()) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'utf16le': - case 'utf-16le': - case 'ucs2': - case 'ucs-2': - return 'utf16le'; - case 'latin1': - case 'binary': - case 'ascii': - return 'latin1'; - case 'base64': - return 'base64'; - case 'hex': - return 'hex'; - default: - throw nodeError( - 'ERR_INVALID_ARG_VALUE', - `The argument 'encoding' is invalid encoding. Received '${encoding}'`, - ); - } -} - -const BASE64_ALPHABET = - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - -const BASE64_VALUES: Record = (() => { - const values: Record = {}; - for (let index = 0; index < BASE64_ALPHABET.length; index += 1) { - values[BASE64_ALPHABET[index]] = index; - } - // The URL-safe alphabet is accepted too: `Buffer` decodes either. - values['-'] = 62; - values._ = 63; - return values; -})(); - -function encodeBase64(bytes: Uint8Array): string { - let out = ''; - for (let index = 0; index < bytes.byteLength; index += 3) { - const first = bytes[index]; - const second = index + 1 < bytes.byteLength ? bytes[index + 1] : 0; - const third = index + 2 < bytes.byteLength ? bytes[index + 2] : 0; - const triple = (first << 16) | (second << 8) | third; - out += BASE64_ALPHABET[(triple >> 18) & 0x3f]; - out += BASE64_ALPHABET[(triple >> 12) & 0x3f]; - out += - index + 1 < bytes.byteLength - ? BASE64_ALPHABET[(triple >> 6) & 0x3f] - : '='; - out += index + 2 < bytes.byteLength ? BASE64_ALPHABET[triple & 0x3f] : '='; - } - return out; -} - -function decodeBase64(text: string): Uint8Array { - const bytes: number[] = []; - let pending = 0; - let bits = 0; - for (const character of text) { - if ( - character === '=' || - character === '\n' || - character === '\r' || - character === ' ' - ) { - continue; - } - const value = BASE64_VALUES[character]; - if (value === undefined) { - // Node stops at the first character that is not base64 rather than - // failing, so `Buffer.from('abc$', 'base64')` decodes the prefix. - break; - } - pending = (pending << 6) | value; - bits += 6; - if (bits >= 8) { - bits -= 8; - bytes.push((pending >> bits) & 0xff); - } - } - return Uint8Array.from(bytes); -} - -function encodeHex(bytes: Uint8Array): string { - let out = ''; - for (let index = 0; index < bytes.byteLength; index += 1) { - out += bytes[index].toString(16).padStart(2, '0'); - } - return out; -} - -function decodeHex(text: string): Uint8Array { - const bytes: number[] = []; - for (let index = 0; index + 1 < text.length; index += 2) { - const value = Number.parseInt(text.slice(index, index + 2), 16); - if (Number.isNaN(value)) { - break; - } - bytes.push(value); - } - return Uint8Array.from(bytes); -} - -function encodeUtf8(text: string): Uint8Array { - const bytes: number[] = []; - for (let index = 0; index < text.length; index += 1) { - let code = text.charCodeAt(index); - // A surrogate pair is one code point; without this an emoji becomes two - // sequences of replacement characters. - if (code >= 0xd800 && code <= 0xdbff && index + 1 < text.length) { - const next = text.charCodeAt(index + 1); - if (next >= 0xdc00 && next <= 0xdfff) { - code = 0x10000 + ((code - 0xd800) << 10) + (next - 0xdc00); - index += 1; - } - } - if (code < 0x80) { - bytes.push(code); - } else if (code < 0x800) { - bytes.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f)); - } else if (code < 0x10000) { - bytes.push( - 0xe0 | (code >> 12), - 0x80 | ((code >> 6) & 0x3f), - 0x80 | (code & 0x3f), - ); - } else { - bytes.push( - 0xf0 | (code >> 18), - 0x80 | ((code >> 12) & 0x3f), - 0x80 | ((code >> 6) & 0x3f), - 0x80 | (code & 0x3f), - ); - } - } - return Uint8Array.from(bytes); -} - -function decodeUtf8(bytes: Uint8Array): string { - let out = ''; - let index = 0; - while (index < bytes.byteLength) { - const first = bytes[index]; - const width = - first < 0x80 - ? 1 - : first >= 0xf0 - ? 4 - : first >= 0xe0 - ? 3 - : first >= 0xc0 - ? 2 - : 0; - if (width === 0 || index + width > bytes.byteLength) { - // Node decodes malformed input with U+FFFD instead of throwing, so a - // file that is not valid UTF-8 still reads as text. - out += '\ufffd'; - index += 1; - continue; - } - let code = width === 1 ? first : first & (0xff >> (width + 1)); - let valid = true; - for (let offset = 1; offset < width; offset += 1) { - const continuation = bytes[index + offset]; - if ((continuation & 0xc0) !== 0x80) { - valid = false; - break; - } - code = (code << 6) | (continuation & 0x3f); - } - if (!valid) { - out += '\ufffd'; - index += 1; - continue; - } - out += String.fromCodePoint(code); - index += width; - } - return out; -} - -function encodeUtf16le(text: string): Uint8Array { - const bytes = new Uint8Array(text.length * 2); - for (let index = 0; index < text.length; index += 1) { - const code = text.charCodeAt(index); - bytes[index * 2] = code & 0xff; - bytes[index * 2 + 1] = code >> 8; - } - return bytes; -} - -function decodeUtf16le(bytes: Uint8Array): string { - const codes: number[] = []; - for (let index = 0; index + 1 < bytes.byteLength; index += 2) { - codes.push(bytes[index] | (bytes[index + 1] << 8)); - } - return chunkedFromCharCode(codes); -} - -function chunkedFromCharCode(codes: number[]): string { - let out = ''; - // `apply` has an argument-count limit, so long strings are built in pieces. - for (let index = 0; index < codes.length; index += 8192) { - out += String.fromCharCode.apply(null, codes.slice(index, index + 8192)); - } - return out; -} - -/** Text to bytes for the encodings implemented in JS. */ -export function encodeString( - text: string, - encoding: NormalizedEncoding, -): Uint8Array { - switch (encoding) { - case 'utf8': - return encodeUtf8(text); - case 'utf16le': - return encodeUtf16le(text); - case 'latin1': { - const bytes = new Uint8Array(text.length); - for (let index = 0; index < text.length; index += 1) { - bytes[index] = text.charCodeAt(index) & 0xff; - } - return bytes; - } - case 'base64': - return decodeBase64(text); - case 'hex': - return decodeHex(text); - } -} - -/** Bytes to text for the encodings implemented in JS. */ -export function decodeString( - bytes: Uint8Array, - encoding: NormalizedEncoding, -): string { - switch (encoding) { - case 'utf8': - return decodeUtf8(bytes); - case 'utf16le': - return decodeUtf16le(bytes); - case 'latin1': { - const codes: number[] = []; - for (let index = 0; index < bytes.byteLength; index += 1) { - codes.push(bytes[index]); - } - return chunkedFromCharCode(codes); - } - case 'base64': - return encodeBase64(bytes); - case 'hex': - return encodeHex(bytes); - } -} - -/** - * Normalises any accepted data shape to an `ArrayBuffer` the bridge can send. - * - * A `Uint8Array` may be a window onto a larger allocation; slicing to the view's - * own range is what stops a writer from sending bytes that belong to something - * else in the same buffer. - */ -export function toArrayBuffer( - data: BinaryData, - encoding: NormalizedEncoding = 'utf8', -): ArrayBuffer { - if (typeof data === 'string') { - const bytes = encodeString(data, encoding); - return bytes.buffer.slice( - bytes.byteOffset, - bytes.byteOffset + bytes.byteLength, - ) as ArrayBuffer; - } - if (data instanceof ArrayBuffer) { - return data; - } - const view = data as ArrayBufferView; - const buffer = view.buffer as ArrayBuffer; - if (view.byteOffset === 0 && view.byteLength === buffer.byteLength) { - return buffer; - } - return buffer.slice(view.byteOffset, view.byteOffset + view.byteLength); -} - -/** A byte view of `toArrayBuffer`'s result, without copying. */ -export function toBytes( - data: BinaryData, - encoding: NormalizedEncoding = 'utf8', -): Uint8Array { - return new Uint8Array(toArrayBuffer(data, encoding)); -} - -/** Node's numeric `open` flags, by their string spelling. */ -const FLAG_STRINGS: Record = { - r: 0, - 'r+': 2, - rs: 0, - sr: 0, - w: 1 | 64 | 512, - wx: 1 | 64 | 512 | 128, - xw: 1 | 64 | 512 | 128, - 'w+': 2 | 64 | 512, - 'wx+': 2 | 64 | 512 | 128, - 'xw+': 2 | 64 | 512 | 128, - a: 1 | 64 | 1024, - ax: 1 | 64 | 1024 | 128, - xa: 1 | 64 | 1024 | 128, - 'a+': 2 | 64 | 1024, - 'ax+': 2 | 64 | 1024 | 128, - 'xa+': 2 | 64 | 1024 | 128, - as: 1 | 64 | 1024, - sa: 1 | 64 | 1024, -}; - -/** A `flag` option as the number the native side decodes. */ -export function flagFrom( - flag: string | number | undefined, - fallback: number, -): number { - if (flag === undefined) { - return fallback; - } - if (typeof flag === 'number') { - return flag; - } - const value = FLAG_STRINGS[flag]; - if (value === undefined) { - throw nodeError( - 'ERR_INVALID_ARG_VALUE', - `The argument 'flag' is invalid. Received '${flag}'`, - ); - } - return value; -} - -/** A `mode` option as a number. A string is octal, as in Node. */ -export function modeFrom( - mode: number | string | undefined, - fallback = 0o666, -): number { - if (mode === undefined) { - return fallback; - } - if (typeof mode === 'number') { - return mode; - } - const parsed = Number.parseInt(mode, 8); - if (Number.isNaN(parsed)) { - throw nodeError( - 'ERR_INVALID_ARG_VALUE', - `The argument 'mode' is invalid. Received '${mode}'`, - ); - } - return parsed; -} diff --git a/vendor/react-native-gpui/modules/fs/src/stats.ts b/vendor/react-native-gpui/modules/fs/src/stats.ts deleted file mode 100644 index 1345af70cc..0000000000 --- a/vendor/react-native-gpui/modules/fs/src/stats.ts +++ /dev/null @@ -1,196 +0,0 @@ -/** - * `Stats` and `Dirent`, built over the plain objects the native module returns. - * - * The module crosses the bridge with numbers rather than methods — a generated - * TurboModule result cannot carry predicates — so the classes live here and - * reproduce the shape Node's callers test for. The `kind` field is the coarse - * classification the native side can make without a platform syscall; `mode` is - * there for the finer predicates, and is zero on Windows where there are no - * Unix mode bits at all. - */ - -import { constants } from './constants'; - -/** The native `FileKind` numbers; must match `module::kind` in Rust. */ -export const FILE_KIND = { - file: 0, - directory: 1, - symlink: 2, - other: 3, -} as const; - -/** The shape `stat`, `lstat` and `fstat` return across the bridge. */ -export interface StatResult { - size: number; - mode: number; - kind: number; - atimeMs: number; - mtimeMs: number; - ctimeMs: number; - birthtimeMs: number; - dev: number; - ino: number; - nlink: number; - uid: number; - gid: number; -} - -/** The shape `readdir` returns across the bridge. */ -export interface DirEntryResult { - name: string; - kind: number; - parentPath: string; -} - -/** The type bits of a mode, or 0 when the platform does not report them. */ -function fileTypeBits(mode: number): number { - return mode & constants.S_IFMT; -} - -/** - * Node's `fs.Stats`. - * - * The fields are plain properties rather than getters: they are copied once from - * the native result, and a caller destructuring the object sees the same values - * Node's does. - */ -export class Stats { - readonly dev: number; - readonly ino: number; - readonly mode: number; - readonly nlink: number; - readonly uid: number; - readonly gid: number; - readonly rdev: number; - readonly size: number; - readonly blksize: number; - readonly blocks: number; - - readonly atimeMs: number; - readonly mtimeMs: number; - readonly ctimeMs: number; - readonly birthtimeMs: number; - - readonly atime: Date; - readonly mtime: Date; - readonly ctime: Date; - readonly birthtime: Date; - - /** The native classification, kept because it answers predicates the mode - * cannot on platforms that report no type bits. */ - private readonly kind: number; - - constructor(result: StatResult) { - this.dev = result.dev; - this.ino = result.ino; - this.mode = result.mode; - this.nlink = result.nlink; - this.uid = result.uid; - this.gid = result.gid; - // The native result has no `rdev`, block size or block count; Node reports - // zero for them where the platform cannot say, so zero is the honest value. - this.rdev = 0; - this.size = result.size; - this.blksize = 0; - this.blocks = 0; - - this.atimeMs = result.atimeMs; - this.mtimeMs = result.mtimeMs; - this.ctimeMs = result.ctimeMs; - this.birthtimeMs = result.birthtimeMs; - - this.atime = new Date(result.atimeMs); - this.mtime = new Date(result.mtimeMs); - this.ctime = new Date(result.ctimeMs); - this.birthtime = new Date(result.birthtimeMs); - - this.kind = result.kind; - } - - isFile(): boolean { - const bits = fileTypeBits(this.mode); - return bits === 0 - ? this.kind === FILE_KIND.file - : bits === constants.S_IFREG; - } - - isDirectory(): boolean { - const bits = fileTypeBits(this.mode); - return bits === 0 - ? this.kind === FILE_KIND.directory - : bits === constants.S_IFDIR; - } - - isSymbolicLink(): boolean { - const bits = fileTypeBits(this.mode); - return bits === 0 - ? this.kind === FILE_KIND.symlink - : bits === constants.S_IFLNK; - } - - isBlockDevice(): boolean { - return fileTypeBits(this.mode) === constants.S_IFBLK; - } - - isCharacterDevice(): boolean { - return fileTypeBits(this.mode) === constants.S_IFCHR; - } - - isFIFO(): boolean { - return fileTypeBits(this.mode) === constants.S_IFIFO; - } - - isSocket(): boolean { - return fileTypeBits(this.mode) === constants.S_IFSOCK; - } -} - -/** - * Node's `fs.Dirent`. - * - * `parentPath` is `''` when the caller already held the parent, matching what - * `readdir` with `{withFileTypes: true}` produces there. - */ -export class Dirent { - readonly name: string; - readonly parentPath: string; - readonly path: string; - - private readonly kind: number; - - constructor(result: DirEntryResult) { - this.name = result.name; - this.parentPath = result.parentPath; - // `path` is the older name for the same field, and libraries still read it. - this.path = result.parentPath; - this.kind = result.kind; - } - - isFile(): boolean { - return this.kind === FILE_KIND.file; - } - - isDirectory(): boolean { - return this.kind === FILE_KIND.directory; - } - - isSymbolicLink(): boolean { - return this.kind === FILE_KIND.symlink; - } - - isBlockDevice(): boolean { - return false; - } - - isCharacterDevice(): boolean { - return false; - } - - isFIFO(): boolean { - return false; - } - - isSocket(): boolean { - return false; - } -} diff --git a/vendor/react-native-gpui/modules/fs/src/upload.ts b/vendor/react-native-gpui/modules/fs/src/upload.ts deleted file mode 100644 index 77d76d7cba..0000000000 --- a/vendor/react-native-gpui/modules/fs/src/upload.ts +++ /dev/null @@ -1,97 +0,0 @@ -/** - * `upload`: a file, or a range of one, streamed as an HTTP request body. - * - * The native side reads the file in small blocks while the connection takes - * them, so nothing larger than a block is ever held in memory. - */ - -import NativeFs from './NativeFs'; -import { nodeError, toPath, withContext, type NodeError } from './shared'; - -export interface UploadOptions { - /** `PUT` unless set. */ - method?: string; - headers?: Record; - /** Where in the file the body starts. Zero unless set. */ - offset?: number; - /** How many bytes to send. Everything from `offset` unless set. */ - length?: number; - /** Called while the body is sent. */ - onProgress?: (sent: number, total: number) => void; - /** Aborting rejects with an `AbortError`. */ - signal?: AbortSignal; -} - -export interface UploadResult { - status: number; - /** Response headers, lower-cased; repeated headers are joined with `, `. */ - headers: Record; - /** The first part of the response body. */ - body: string; -} - -let nextId = 1; - -function abortError(): NodeError { - const error = nodeError('ABORT_ERR', 'The upload was aborted'); - error.name = 'AbortError'; - return error; -} - -function toRecord(list: Array<{ name: string; value: string }>) { - const record: Record = {}; - for (const { name, value } of list) { - record[name] = value; - } - return record; -} - -export async function upload( - url: string, - path: string, - options: UploadOptions = {}, -): Promise { - const { signal, onProgress } = options; - if (signal?.aborted) { - throw abortError(); - } - const source = toPath(path); - const id = nextId++; - const subscription = onProgress - ? NativeFs.onUploadProgress(event => { - if (event.id === id) { - onProgress(event.sent, event.total); - } - }) - : null; - const onAbort = () => { - NativeFs.cancelUpload(id); - }; - signal?.addEventListener('abort', onAbort); - - try { - const result = await NativeFs.upload(url, source, { - id, - method: options.method ?? 'PUT', - headers: Object.entries(options.headers ?? {}).map(([name, value]) => ({ - name, - value, - })), - offset: options.offset ?? 0, - length: options.length ?? -1, - }); - return { - status: result.status, - headers: toRecord(result.headers), - body: result.body, - }; - } catch (error) { - if (signal?.aborted || (error as NodeError)?.code === 'ABORT_ERR') { - throw abortError(); - } - throw withContext(error, 'upload', source); - } finally { - signal?.removeEventListener('abort', onAbort); - subscription?.remove(); - } -} diff --git a/vendor/react-native-gpui/modules/fs/src/watch.ts b/vendor/react-native-gpui/modules/fs/src/watch.ts deleted file mode 100644 index 7bc3b5a277..0000000000 --- a/vendor/react-native-gpui/modules/fs/src/watch.ts +++ /dev/null @@ -1,141 +0,0 @@ -/** - * `watch`: the JS half of the typed watcher event. - * - * The native module returns a watcher id; every event it produces carries that - * id, so one shared emitter serves every open watcher and each listener keeps - * only its own. The subscription is taken through the generated typed emitter on - * the module (`NativeFs.onWatchEvent`), which is the same mechanism the fixture's - * `onProgress` uses in `RustTurboModuleFixture.tsx`, rather than through - * `NativeEventEmitter`: the spec declares `onWatchEvent` as a typed - * `CodegenTypes.EventEmitter`, and the bridge installs a listener for exactly - * that; `NativeEventEmitter` would subscribe on the global device-emitter channel - * that only `sendEvent` writes to, so it would never fire. - */ - -import NativeFs, { type WatchEvent } from './NativeFs'; -import { toPath, withContext, type NodeError } from './shared'; - -/** The event names Node uses for the two things a watcher reports. */ -export type WatchEventType = 'rename' | 'change'; - -export interface WatchOptions { - recursive?: boolean; - encoding?: string; -} - -export interface FSWatcher { - close(): Promise; -} - -export type WatchListener = ( - eventType: WatchEventType, - filename: string | null, -) => void; - -/** - * Which of Node's two event types a native kind is. - * - * Node folds everything it sees into `rename` (the entry appeared, vanished or - * moved) and `change` (its contents or metadata changed). The caller's callback - * signature is Node's, so the mapping happens here while the native kind stays - * available to anyone who subscribes to the module directly. - */ -function eventTypeOf(kind: string): WatchEventType { - return kind === 'modify' ? 'change' : 'rename'; -} - -/** The file a path names, relative to the watched root where it is below it. */ -/** - * The filename a listener is given. - * - * The native side already reported it relative to the watch root, and its own - * name for a single-file watch: it canonicalises the root, which is where macOS - * decides between `/var` and `/private/var`, and it strips whichever spelling the - * event actually carries. Stripping a prefix here as well would be a second, - * weaker guess at the same question — a relative root never matches, and Windows - * separates with `\` — so the event path is passed through unchanged. - */ -function fileNameOf(eventPath: string): string { - return eventPath; -} - -/** - * Starts a watcher. - * - * The id arrives asynchronously, but the caller expects a handle it can close - * immediately, so the handle is created first and closing it before the id is - * known sets a flag the resolution honours. That is the one ordering hazard in - * this API, and it is invisible from the outside. - * - * Node reports a failure to start through an `error` event on the watcher. This - * handle has no event surface, so the failure is held and rejected from - * `close()` instead: it can then never become an unhandled rejection, and a - * caller that closes what it opened is guaranteed to see it. - */ -export function watch(path: string, listener: WatchListener): FSWatcher; -export function watch( - path: string, - options: WatchOptions | null, - listener: WatchListener, -): FSWatcher; -export function watch( - path: string, - optionsOrListener: WatchOptions | null | WatchListener, - maybeListener?: WatchListener, -): FSWatcher { - const options = - typeof optionsOrListener === 'function' ? {} : (optionsOrListener ?? {}); - const listener = - typeof optionsOrListener === 'function' ? optionsOrListener : maybeListener; - if (typeof listener !== 'function') { - throw new TypeError('watch requires a listener function'); - } - - const target = toPath(path); - let id: number | null = null; - let closed = false; - let failure: NodeError | null = null; - let subscription: { remove(): void } | null = null; - - const ready = NativeFs.watch(target, options.recursive ?? false) - .then(watcherId => { - id = watcherId; - if (closed) { - // `close()` ran while the id was in flight; stop the native watcher now - // that there is something to stop. - NativeFs.unwatch(watcherId); - return; - } - subscription = NativeFs.onWatchEvent((event: WatchEvent) => { - if (event.id !== id) { - return; - } - // The encoding option only affects how a non-ASCII name is decoded, and - // every name already arrives as a JS string. - listener(eventTypeOf(event.kind), fileNameOf(event.path)); - }); - }) - .catch((error: unknown) => { - failure = withContext(error, 'watch', target); - }); - - return { - async close(): Promise { - closed = true; - subscription?.remove(); - subscription = null; - if (id !== null) { - NativeFs.unwatch(id); - id = null; - } - // Awaiting the start makes `close()` immediately after `watch()` still stop - // the native watcher rather than racing it. - await ready; - if (failure !== null) { - const error = failure; - failure = null; - throw error; - } - }, - }; -} diff --git a/vendor/react-native-gpui/modules/gesture-handler/CHANGELOG.md b/vendor/react-native-gpui/modules/gesture-handler/CHANGELOG.md deleted file mode 100644 index 871189d2ff..0000000000 --- a/vendor/react-native-gpui/modules/gesture-handler/CHANGELOG.md +++ /dev/null @@ -1,12 +0,0 @@ -# Changelog - -All notable changes to `@react-native-gpui/gesture-handler` are listed here. Each version's section becomes the notes of its GitHub release. - -## 3.3.0-alpha.1 - 2026-11-12 - -- A gesture whose callbacks run on the JS thread (`runOnJS(true)`, or a handler from the old API) receives its events. They were sent to its view, where only worklet callbacks listen, so a sheet dragged by such a gesture did not move. - -## 3.3.0-alpha.0 - 2026-11-01 - -- First release, for `react-native-gesture-handler` 3.3.x with Reanimated 4.7.x and Worklets 0.13.x. -- Gesture recognition for mouse, trackpad and touch input on desktop. diff --git a/vendor/react-native-gpui/modules/gesture-handler/LICENSE b/vendor/react-native-gpui/modules/gesture-handler/LICENSE deleted file mode 100644 index 149a0f8321..0000000000 --- a/vendor/react-native-gpui/modules/gesture-handler/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Streetwriters - -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/vendor/react-native-gpui/modules/gesture-handler/README.md b/vendor/react-native-gpui/modules/gesture-handler/README.md deleted file mode 100644 index 088856c9b6..0000000000 --- a/vendor/react-native-gpui/modules/gesture-handler/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# @react-native-gpui/gesture-handler - -Adapter for [`react-native-gesture-handler`](https://github.com/software-mansion/react-native-gesture-handler) (MIT): recognizes gestures from the mouse, trackpad and touch screen. - -Part of [react-native-gpui](https://github.com/streetwriters/react-native-gpui), React Native for macOS, Windows and Linux. - -## Install - -Install it next to `react-native-gesture-handler`: - -```sh -npm install react-native-gesture-handler@3.3.x @react-native-gpui/gesture-handler -``` - -Gesture Handler needs Reanimated 4.7.x and Worklets 0.13.x, with their desktop packages [`@react-native-gpui/reanimated`](https://www.npmjs.com/package/@react-native-gpui/reanimated) and [`@react-native-gpui/worklets`](https://www.npmjs.com/package/@react-native-gpui/worklets). - -Keep using `react-native-gesture-handler` as you do on iOS and Android; its JavaScript API is unchanged. Autolinking builds the desktop side when the app is built. - -## Documentation - -[Supported libraries](https://streetwriters.github.io/react-native-gpui/docs/supported-libraries) - -## License - -MIT. See [LICENSE](LICENSE). diff --git a/vendor/react-native-gpui/modules/gesture-handler/desktop/CMakeLists.txt b/vendor/react-native-gpui/modules/gesture-handler/desktop/CMakeLists.txt deleted file mode 100644 index 5a14af4856..0000000000 --- a/vendor/react-native-gpui/modules/gesture-handler/desktop/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -if(NOT RN_GPUI_PROJECT_ROOT) - message(FATAL_ERROR - "@react-native-gpui/gesture-handler was added by the platform; RN_GPUI_PROJECT_ROOT must be set by its build.rs") -endif() -rn_gpui_find_node_module(react-native-gesture-handler _gesture_root) -if(NOT EXISTS "${_gesture_root}/src/specs/NativeRNGestureHandlerModule.ts") - message(FATAL_ERROR "react-native-gesture-handler 3.3.x was not found at ${_gesture_root}") -endif() - -file(READ "${_gesture_root}/package.json" _gesture_package_json) -string(JSON _gesture_version GET "${_gesture_package_json}" version) -if(NOT _gesture_version MATCHES "^3\\.3\\.") - message(FATAL_ERROR "@react-native-gpui/gesture-handler supports react-native-gesture-handler 3.3.x, found ${_gesture_version}") -endif() - -set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_SOURCES - "${CMAKE_CURRENT_LIST_DIR}/cpp/GPUIGestureHandlerModule.cpp") -set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_INCLUDE_DIRS - "${RN_GPUI_SYS_CPP_DIR}") diff --git a/vendor/react-native-gpui/modules/gesture-handler/desktop/cpp/GPUIGestureHandlerModule.cpp b/vendor/react-native-gpui/modules/gesture-handler/desktop/cpp/GPUIGestureHandlerModule.cpp deleted file mode 100644 index 4923c002c5..0000000000 --- a/vendor/react-native-gpui/modules/gesture-handler/desktop/cpp/GPUIGestureHandlerModule.cpp +++ /dev/null @@ -1,548 +0,0 @@ -#include "GpuiHost.h" -#include "GpuiModules.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { -using facebook::jsi::Runtime; -using facebook::react::TurboModule; -using rngpui::extension::RawPointerEvent; -using rngpui::extension::RecognizedGesture; - -constexpr int32_t kUndetermined = 0; -constexpr int32_t kFailed = 1; -constexpr int32_t kBegan = 2; -constexpr int32_t kCancelled = 3; -constexpr int32_t kActive = 4; -constexpr int32_t kEnd = 5; - -struct Handler { - std::string name; - folly::dynamic config{folly::dynamic::object}; - int32_t viewTag{-1}; - int32_t actionType{0}; - int32_t state{kUndetermined}; - float startX{0}; - float startY{0}; - float lastX{0}; - float lastY{0}; - double startTime{0}; - double lastTime{0}; - bool recognized{false}; - std::vector simultaneousHandlers; - std::vector waitFor; - std::vector blocksHandlers; -}; - -std::mutex handlersMutex; -std::unordered_map handlers; - -// What one pointer event produced. A gesture whose callbacks run on the JS -// thread is told through device events, as GestureDetector listens for them; -// any other through events on its view. -struct Recognized { - std::vector viewEvents; - std::vector> deviceEvents; -}; - -bool runsOnJS(const Handler& handler) { - constexpr int32_t kJSFunctionOldAPI = 3; - constexpr int32_t kJSFunctionNewAPI = 4; - return handler.actionType == kJSFunctionOldAPI || - handler.actionType == kJSFunctionNewAPI; -} - -folly::dynamic configObject(folly::dynamic config) { - return config.isObject() ? std::move(config) : folly::dynamic::object(); -} - -float number(const folly::dynamic& object, const char* key, float fallback) { - if (!object.isObject() || !object.get_ptr(key)) - return fallback; - const auto& value = object[key]; - if (value.isNumber()) - return static_cast(value.asDouble()); - return fallback; -} - -bool enabled(const Handler& handler) { - const auto* value = handler.config.get_ptr("enabled"); - return value == nullptr || !value->isBool() || value->asBool(); -} - -bool isPan(const Handler& handler) { - return handler.name == "Pan" || handler.name == "PanGestureHandler"; -} - -bool isTap(const Handler& handler) { - return handler.name == "Tap" || handler.name == "TapGestureHandler"; -} - -bool isLongPress(const Handler& handler) { - return handler.name == "LongPress" || - handler.name == "LongPressGestureHandler"; -} - -bool gestureTracingEnabled() { - return std::getenv("RN_GPUI_DEBUG_GESTURES") != nullptr; -} - -folly::dynamic payloadFor( - int32_t handlerTag, - const Handler& handler, - int32_t state, - int32_t oldState, - const RawPointerEvent& pointer, - bool stateChange) { - const float dx = pointer.x - handler.startX; - const float dy = pointer.y - handler.startY; - const double elapsed = std::max(1.0, pointer.timestamp - handler.lastTime); - folly::dynamic payload = folly::dynamic::object("handlerTag", handlerTag)( - "state", state)("x", pointer.x - handler.startX)( - "y", pointer.y - handler.startY)("absoluteX", pointer.x)( - "absoluteY", pointer.y)("translationX", dx)("translationY", dy)( - "velocityX", (pointer.x - handler.lastX) * 1000.0 / elapsed)( - "velocityY", (pointer.y - handler.lastY) * 1000.0 / elapsed)( - "numberOfPointers", 1)("pointerType", 2)( - "duration", pointer.timestamp - handler.startTime); - if (stateChange) { - payload["oldState"] = oldState; - } - return payload; -} - -void appendEvent( - Recognized& events, - const Handler& handler, - const char* type, - const folly::dynamic& payload) { - if (runsOnJS(handler)) { - const bool stateChange = - std::string_view(type) == "topGestureHandlerStateChange"; - events.deviceEvents.emplace_back( - stateChange ? "onGestureHandlerStateChange" : "onGestureHandlerEvent", - payload); - return; - } - events.viewEvents.push_back({handler.viewTag, type, folly::toJson(payload)}); -} - -void appendState( - Recognized& events, - int32_t handlerTag, - Handler& handler, - int32_t nextState, - const RawPointerEvent& pointer) { - if (handler.state == nextState) - return; - const auto oldState = handler.state; - handler.state = nextState; - if (nextState == kActive) { - handler.recognized = true; - } - appendEvent( - events, - handler, - "topGestureHandlerStateChange", - payloadFor(handlerTag, handler, nextState, oldState, pointer, true)); -} - -std::vector relationTags( - const folly::dynamic& relations, - const char* key) { - std::vector tags; - const auto* values = relations.get_ptr(key); - if (values == nullptr || !values->isArray()) { - return tags; - } - tags.reserve(values->size()); - for (const auto& value : *values) { - if (value.isInt()) { - tags.push_back(static_cast(value.asInt())); - } - } - return tags; -} - -bool hasTag(const std::vector& tags, int32_t tag) { - return std::find(tags.begin(), tags.end(), tag) != tags.end(); -} - -bool hasRecognizedWaitFor(const Handler& handler) { - for (const auto tag : handler.waitFor) { - const auto dependency = handlers.find(tag); - if (dependency != handlers.end() && dependency->second.recognized) { - return true; - } - } - return false; -} - -bool hasUnresolvedWaitFor(const Handler& handler) { - for (const auto tag : handler.waitFor) { - const auto dependency = handlers.find(tag); - if (dependency != handlers.end() && dependency->second.state == kBegan && - !dependency->second.recognized) { - return true; - } - } - return false; -} - -bool blockedByActiveHandler(int32_t handlerTag) { - for (const auto& [otherTag, other] : handlers) { - if (otherTag != handlerTag && other.state == kActive && - hasTag(other.blocksHandlers, handlerTag)) { - return true; - } - } - return false; -} - -Recognized processPointer(const RawPointerEvent& pointer) { - Recognized events; - std::lock_guard lock(handlersMutex); - if (gestureTracingEnabled() && pointer.phase != 4) { - LOG(INFO) << "[gesture-handler] pointer phase=" << pointer.phase << " at (" - << pointer.x << ',' << pointer.y - << ") chain=" << pointer.targetChain.size() << " tags"; - } - if (pointer.phase == 0) { - for (auto& [_, handler] : handlers) { - if (!enabled(handler) || handler.viewTag < 0 || - std::find( - pointer.targetChain.begin(), - pointer.targetChain.end(), - handler.viewTag) == pointer.targetChain.end()) { - continue; - } - handler.state = kUndetermined; - handler.startX = pointer.x; - handler.startY = pointer.y; - handler.lastX = pointer.x; - handler.lastY = pointer.y; - handler.startTime = pointer.timestamp; - handler.lastTime = pointer.timestamp; - handler.recognized = false; - appendState(events, _, handler, kBegan, pointer); - if (gestureTracingEnabled()) { - LOG(INFO) << "[gesture-handler] began handler=" << _ - << " name=" << handler.name << " view=" << handler.viewTag; - } - } - return events; - } - - if (pointer.phase == 2) { - // Resolve recognizers that cannot succeed on release before testing tap - // handlers that may be waiting for them to fail. - for (auto& [handlerTag, handler] : handlers) { - if (handler.state != kBegan || isTap(handler)) { - continue; - } - const float dx = pointer.x - handler.startX; - const float dy = pointer.y - handler.startY; - if (isLongPress(handler)) { - const auto elapsed = pointer.timestamp - handler.startTime; - const auto minDuration = - number(handler.config, "minDurationMs", 500.0f); - if (elapsed >= minDuration && - std::hypot(dx, dy) <= number(handler.config, "maxDist", 10.0f) && - !hasRecognizedWaitFor(handler) && - !blockedByActiveHandler(handlerTag)) { - appendState(events, handlerTag, handler, kActive, pointer); - } else { - appendState(events, handlerTag, handler, kFailed, pointer); - } - } else { - appendState(events, handlerTag, handler, kFailed, pointer); - } - } - } - - for (auto& [handlerTag, handler] : handlers) { - if (handler.state != kBegan && handler.state != kActive) - continue; - if (pointer.phase == 4) { - const float dx = pointer.x - handler.startX; - const float dy = pointer.y - handler.startY; - const auto elapsed = pointer.timestamp - handler.startTime; - const auto minDuration = number(handler.config, "minDurationMs", 500.0f); - if (gestureTracingEnabled() && handler.state == kBegan && - isLongPress(handler) && elapsed >= minDuration) { - LOG(INFO) << "[gesture-handler] long-press threshold handler=" - << handlerTag << " elapsed=" << elapsed - << " required=" << minDuration - << " distance=" << std::hypot(dx, dy); - } - if (handler.state == kBegan && isLongPress(handler) && - elapsed >= minDuration && - std::hypot(dx, dy) <= number(handler.config, "maxDist", 10.0f)) { - if (hasRecognizedWaitFor(handler) || - blockedByActiveHandler(handlerTag)) { - appendState(events, handlerTag, handler, kFailed, pointer); - } else if (!hasUnresolvedWaitFor(handler)) { - appendState(events, handlerTag, handler, kActive, pointer); - } - } - } else if (pointer.phase == 1) { - const float dx = pointer.x - handler.startX; - const float dy = pointer.y - handler.startY; - if (handler.state == kBegan && isPan(handler) && - std::hypot(dx, dy) >= number(handler.config, "minDist", 3.0f)) { - if (hasRecognizedWaitFor(handler) || - blockedByActiveHandler(handlerTag)) { - appendState(events, handlerTag, handler, kFailed, pointer); - } else if (!hasUnresolvedWaitFor(handler)) { - appendState(events, handlerTag, handler, kActive, pointer); - } - } else if ( - handler.state == kBegan && isLongPress(handler) && - pointer.timestamp - handler.startTime >= - number(handler.config, "minDurationMs", 500.0f) && - std::hypot(dx, dy) <= number(handler.config, "maxDist", 10.0f)) { - if (hasRecognizedWaitFor(handler) || - blockedByActiveHandler(handlerTag)) { - appendState(events, handlerTag, handler, kFailed, pointer); - } else if (!hasUnresolvedWaitFor(handler)) { - appendState(events, handlerTag, handler, kActive, pointer); - } - } - if (handler.state == kActive && - (isPan(handler) || isLongPress(handler))) { - appendEvent( - events, - handler, - "topGestureHandlerEvent", - payloadFor( - handlerTag, - handler, - handler.state, - kUndetermined, - pointer, - false)); - } - } else if (pointer.phase == 2) { - const float dx = pointer.x - handler.startX; - const float dy = pointer.y - handler.startY; - if (isTap(handler) && handler.state == kBegan && - pointer.timestamp - handler.startTime <= - number(handler.config, "maxDurationMs", 500.0f) && - std::hypot(dx, dy) <= number(handler.config, "maxDist", 10.0f)) { - if (hasRecognizedWaitFor(handler) || - blockedByActiveHandler(handlerTag)) { - appendState(events, handlerTag, handler, kFailed, pointer); - } else if (!hasUnresolvedWaitFor(handler)) { - appendState(events, handlerTag, handler, kActive, pointer); - } else { - appendState(events, handlerTag, handler, kFailed, pointer); - } - } else if ( - isLongPress(handler) && handler.state == kBegan && - pointer.timestamp - handler.startTime >= - number(handler.config, "minDurationMs", 500.0f) && - std::hypot(dx, dy) <= number(handler.config, "maxDist", 10.0f)) { - appendState(events, handlerTag, handler, kActive, pointer); - } else if (handler.state == kBegan) { - appendState(events, handlerTag, handler, kFailed, pointer); - } - if (handler.state == kActive) { - if (isTap(handler) || isLongPress(handler)) { - appendEvent( - events, - handler, - "topGestureHandlerEvent", - payloadFor( - handlerTag, - handler, - handler.state, - kUndetermined, - pointer, - false)); - } - appendState(events, handlerTag, handler, kEnd, pointer); - } - handler.lastX = pointer.x; - handler.lastY = pointer.y; - handler.lastTime = pointer.timestamp; - } else if (pointer.phase == 3) { - appendState( - events, - handlerTag, - handler, - handler.state == kActive ? kCancelled : kFailed, - pointer); - } - } - if (gestureTracingEnabled() && - (pointer.phase != 4 || !events.viewEvents.empty() || - !events.deviceEvents.empty())) { - LOG(INFO) << "[gesture-handler] recognized events=" - << events.viewEvents.size() + events.deviceEvents.size(); - } - return events; -} - -class GPUIGestureHandlerModule final - : public facebook::react::NativeRNGestureHandlerModuleSpec< - GPUIGestureHandlerModule> { - public: - explicit GPUIGestureHandlerModule( - std::shared_ptr jsInvoker) - : NativeRNGestureHandlerModuleSpec(std::move(jsInvoker)) {} - - // The JS side queues operations and flushes them in order, so every method - // has to observe the same order the JS thread produced. - static constexpr rngpui::ModuleThread kThread = rngpui::ModuleThread::JS; - - void createGestureHandler( - Runtime&, - std::string handlerName, - double handlerTag, - folly::dynamic config) { - Handler handler; - handler.name = std::move(handlerName); - handler.config = configObject(std::move(config)); - std::lock_guard lock(handlersMutex); - handlers.insert_or_assign( - static_cast(handlerTag), std::move(handler)); - } - - void attachGestureHandler( - Runtime&, - double handlerTag, - double viewTag, - double actionType) { - const auto tag = static_cast(handlerTag); - std::lock_guard lock(handlersMutex); - auto found = handlers.find(tag); - if (found != handlers.end()) { - found->second.viewTag = static_cast(viewTag); - found->second.actionType = static_cast(actionType); - if (gestureTracingEnabled()) { - LOG(INFO) << "[gesture-handler] attached handler=" << tag - << " view=" << found->second.viewTag - << " action=" << found->second.actionType; - } - } - } - - void setGestureHandlerConfig( - Runtime&, - double handlerTag, - folly::dynamic newConfig) { - const auto tag = static_cast(handlerTag); - auto config = configObject(std::move(newConfig)); - std::lock_guard lock(handlersMutex); - auto found = handlers.find(tag); - if (found != handlers.end()) - found->second.config = std::move(config); - } - - void updateGestureHandlerConfig( - Runtime&, - double handlerTag, - folly::dynamic newConfig) { - const auto tag = static_cast(handlerTag); - std::lock_guard lock(handlersMutex); - auto found = handlers.find(tag); - if (found != handlers.end() && newConfig.isObject()) { - for (const auto& [key, value] : newConfig.items()) - found->second.config[key] = value; - } - } - - void - configureRelations(Runtime&, double handlerTag, folly::dynamic relations) { - const auto tag = static_cast(handlerTag); - std::lock_guard lock(handlersMutex); - const auto found = handlers.find(tag); - if (found != handlers.end()) { - found->second.simultaneousHandlers = - relationTags(relations, "simultaneousHandlers"); - found->second.waitFor = relationTags(relations, "waitFor"); - found->second.blocksHandlers = relationTags(relations, "blocksHandlers"); - if (gestureTracingEnabled()) { - auto formatTags = [](const std::vector& tags) { - std::string result; - for (const auto value : tags) { - if (!result.empty()) - result += ","; - result += std::to_string(value); - } - return result; - }; - LOG(INFO) << "[gesture-handler] relations handler=" << tag - << " name=" << found->second.name << " simultaneous=" - << formatTags(found->second.simultaneousHandlers) - << " waitFor=" << formatTags(found->second.waitFor) - << " blocks=" << formatTags(found->second.blocksHandlers); - } - } - } - - void dropGestureHandler(Runtime&, double handlerTag) { - std::lock_guard lock(handlersMutex); - handlers.erase(static_cast(handlerTag)); - } - - void flushOperations(Runtime&) {} - - bool installUIRuntimeBindings(Runtime&) { - return true; - } - - void emit(const std::string& name, folly::dynamic payload) { - emitDeviceEvent( - name, - [payload = std::move(payload)]( - Runtime& runtime, std::vector& args) { - args.emplace_back(facebook::jsi::valueFromDynamic(runtime, payload)); - }); - } -}; - -std::weak_ptr currentModule; -} // namespace - -std::shared_ptr -create_gpui_gesture_handler_module( - const std::string& name, - std::shared_ptr jsInvoker) { - if (name != GPUIGestureHandlerModule::kModuleName) { - return nullptr; - } - rngpui::registerPointerObserver( - [](const rngpui::extension::RawPointerEvent& pointer) { - auto events = processPointer(pointer); - if (auto module = currentModule.lock()) { - for (auto& [name, payload] : events.deviceEvents) { - module->emit(name, std::move(payload)); - } - } - return std::move(events.viewEvents); - }); - if (gestureTracingEnabled()) { - LOG(INFO) << "[gesture-handler] native pointer processor installed"; - } - auto module = - std::make_shared(std::move(jsInvoker)); - currentModule = module; - return module; -} diff --git a/vendor/react-native-gpui/modules/gesture-handler/package.json b/vendor/react-native-gpui/modules/gesture-handler/package.json deleted file mode 100644 index 35f1a12f13..0000000000 --- a/vendor/react-native-gpui/modules/gesture-handler/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "@react-native-gpui/gesture-handler", - "version": "3.3.0-alpha.1", - "description": "Adapter for react-native-gesture-handler (MIT): recognizes gestures from the mouse, trackpad and touch screen", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/streetwriters/react-native-gpui-modules.git", - "directory": "modules/gesture-handler" - }, - "homepage": "https://github.com/streetwriters/react-native-gpui-modules/tree/main/modules/gesture-handler#readme", - "bugs": { - "url": "https://github.com/streetwriters/react-native-gpui-modules/issues" - }, - "files": [ - "desktop", - "react-native.config.js", - "src", - "README.md", - "LICENSE", - "CHANGELOG.md", - "!**/*.test.js", - "!**/*.test.mjs", - "!**/*.test.ts", - "!**/*.test.cjs" - ], - "peerDependencies": { - "react-native": "0.87.x", - "react-native-gesture-handler": "3.3.x", - "react-native-reanimated": "4.7.x", - "react-native-worklets": "0.13.x" - }, - "codegenConfig": { - "name": "GPUIGestureHandlerSpec", - "type": "modules", - "jsSrcsDir": "src" - }, - "publishConfig": { - "access": "public", - "tag": "latest" - } -} diff --git a/vendor/react-native-gpui/modules/gesture-handler/react-native.config.js b/vendor/react-native-gpui/modules/gesture-handler/react-native.config.js deleted file mode 100644 index d5e619bf42..0000000000 --- a/vendor/react-native-gpui/modules/gesture-handler/react-native.config.js +++ /dev/null @@ -1,25 +0,0 @@ -module.exports = { - dependency: { - platforms: { - desktop: { - cmake: 'desktop', - cppProvider: 'create_gpui_gesture_handler_module', - componentCodegenPackage: 'react-native-gesture-handler', - componentDescriptors: [ - 'RNGestureHandlerButtonComponentDescriptor', - 'RNGestureHandlerRootViewComponentDescriptor', - ], - componentHeaders: [ - 'react/renderer/components/rngesturehandler_codegen/ComponentDescriptors.h', - ], - // Metro: replace these files of installed packages for gpui. - sourceOverrides: { - 'react-native-gesture-handler/src/handlers/customDirectEventTypes.ts': - './src/customDirectEventTypes.desktop.ts', - 'react-native-gesture-handler/src/v3/components/GestureButtons.tsx': - './src/GestureButtons.desktop.tsx', - }, - }, - }, - }, -}; diff --git a/vendor/react-native-gpui/modules/gesture-handler/src/GestureButtons.desktop.tsx b/vendor/react-native-gpui/modules/gesture-handler/src/GestureButtons.desktop.tsx deleted file mode 100644 index 61b5db847e..0000000000 --- a/vendor/react-native-gpui/modules/gesture-handler/src/GestureButtons.desktop.tsx +++ /dev/null @@ -1,71 +0,0 @@ -import React from 'react'; -import './customDirectEventTypes.desktop'; -import { - Pressable, - type ColorValue, - type PressableProps, - type StyleProp, - type ViewStyle, -} from 'react-native'; - -type DesktopButtonProps = Omit & { - style?: StyleProp; - activeOpacity?: number; - underlayColor?: ColorValue; - onActiveStateChange?: (active: boolean) => void; - pressedStyle?: ViewStyle; - borderless?: boolean; - rippleColor?: ColorValue | number | null; - rippleRadius?: number | null; - foreground?: boolean; - exclusive?: boolean; - cancelable?: boolean; -}; - -function DesktopButton({ - activeOpacity = 0.75, - onActiveStateChange, - onPressIn, - onPressOut, - pressedStyle, - style, - ...props -}: DesktopButtonProps) { - return ( - [ - style, - pressed ? [{ opacity: activeOpacity }, pressedStyle] : undefined, - ]} - onPressIn={event => { - onActiveStateChange?.(true); - onPressIn?.(event); - }} - onPressOut={event => { - onActiveStateChange?.(false); - onPressOut?.(event); - }} - /> - ); -} - -export const RectButton = ({ underlayColor, ...props }: DesktopButtonProps) => ( - -); - -export const BorderlessButton = (props: DesktopButtonProps) => ( - -); - -export const RawButton = DesktopButton; -export const BaseButton = DesktopButton; -export const LegacyRectButton = RectButton; -export const LegacyBorderlessButton = BorderlessButton; -export const LegacyRawButton = RawButton; -export const LegacyBaseButton = BaseButton; diff --git a/vendor/react-native-gpui/modules/gesture-handler/src/NativeRNGestureHandlerModule.ts b/vendor/react-native-gpui/modules/gesture-handler/src/NativeRNGestureHandlerModule.ts deleted file mode 100644 index c9fe2cd0d0..0000000000 --- a/vendor/react-native-gpui/modules/gesture-handler/src/NativeRNGestureHandlerModule.ts +++ /dev/null @@ -1,32 +0,0 @@ -import type { CodegenTypes, TurboModule } from 'react-native'; -import { TurboModuleRegistry } from 'react-native'; - -export interface Spec extends TurboModule { - createGestureHandler: ( - handlerName: string, - handlerTag: CodegenTypes.Double, - config: Object, - ) => void; - attachGestureHandler: ( - handlerTag: CodegenTypes.Double, - viewTag: CodegenTypes.Double, - actionType: CodegenTypes.Double, - ) => void; - setGestureHandlerConfig: ( - handlerTag: CodegenTypes.Double, - newConfig: Object, - ) => void; - updateGestureHandlerConfig: ( - handlerTag: CodegenTypes.Double, - newConfig: Object, - ) => void; - configureRelations: ( - handlerTag: CodegenTypes.Double, - relations: Object, - ) => void; - dropGestureHandler: (handlerTag: CodegenTypes.Double) => void; - flushOperations: () => void; - installUIRuntimeBindings: () => boolean; -} - -export default TurboModuleRegistry.getEnforcing('RNGestureHandlerModule'); diff --git a/vendor/react-native-gpui/modules/gesture-handler/src/customDirectEventTypes.desktop.ts b/vendor/react-native-gpui/modules/gesture-handler/src/customDirectEventTypes.desktop.ts deleted file mode 100644 index a27aed907e..0000000000 --- a/vendor/react-native-gpui/modules/gesture-handler/src/customDirectEventTypes.desktop.ts +++ /dev/null @@ -1,13 +0,0 @@ -// RNGH's legacy handler path registers only the continuous event in its JS -// module. GPUI dispatches the codegen state-change event directly, so expose -// both direct-event registrations from this platform package. -import { customDirectEventTypes } from 'react-native/Libraries/Renderer/shims/ReactNativeViewConfigRegistry'; - -customDirectEventTypes.topGestureHandlerEvent = { - registrationName: 'onGestureHandlerEvent', -}; -customDirectEventTypes.topGestureHandlerStateChange = { - registrationName: 'onGestureHandlerStateChange', -}; - -export { customDirectEventTypes }; diff --git a/vendor/react-native-gpui/modules/reanimated/CHANGELOG.md b/vendor/react-native-gpui/modules/reanimated/CHANGELOG.md deleted file mode 100644 index b3235d8315..0000000000 --- a/vendor/react-native-gpui/modules/reanimated/CHANGELOG.md +++ /dev/null @@ -1,17 +0,0 @@ -# Changelog - -All notable changes to `@react-native-gpui/reanimated` are listed here. Each version's section becomes the notes of its GitHub release. - -## Unreleased - -- Builds with MSVC 14.51 (Visual Studio 18): the members of the resolvable transform interpolator are defined in the class body, since that compiler cannot match their out-of-line definitions. - -## 4.7.0-alpha.1 - 2026-11-12 - -- CSS transitions and animations now run: the registries' updates are applied after every frame, as the display link does on iOS, where before nothing applied them and a transition or keyframe animation never changed what was painted. Needs a prebuilt runtime built with the change. - -## 4.7.0-alpha.0 - 2026-11-01 - -- First release, for `react-native-reanimated` 4.7.x with Worklets 0.13.x. -- Animations, layout animations and CSS animations on desktop. -- Works with the npm release of `react-native-reanimated`: the C++ fixes it needs for MSVC and Linux are applied to a copy in the build directory. UI props update synchronously on Linux, as on iOS. diff --git a/vendor/react-native-gpui/modules/reanimated/LICENSE b/vendor/react-native-gpui/modules/reanimated/LICENSE deleted file mode 100644 index 149a0f8321..0000000000 --- a/vendor/react-native-gpui/modules/reanimated/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Streetwriters - -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/vendor/react-native-gpui/modules/reanimated/README.md b/vendor/react-native-gpui/modules/reanimated/README.md deleted file mode 100644 index a409a13368..0000000000 --- a/vendor/react-native-gpui/modules/reanimated/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# @react-native-gpui/reanimated - -Adapter for [`react-native-reanimated`](https://github.com/software-mansion/react-native-reanimated) (MIT): runs animations, layout animations and CSS animations on the desktop renderer. - -Part of [react-native-gpui](https://github.com/streetwriters/react-native-gpui), React Native for macOS, Windows and Linux. - -## Install - -Install it next to `react-native-reanimated`: - -```sh -npm install react-native-reanimated@4.7.x @react-native-gpui/reanimated -``` - -Reanimated needs Worklets, so install `react-native-worklets@0.13.x` and [`@react-native-gpui/worklets`](https://www.npmjs.com/package/@react-native-gpui/worklets) too. - -Install the regular npm release of `react-native-reanimated`. Its C++ needs small fixes to build with MSVC and on Linux; this package applies them to a copy in the desktop build directory and never changes `node_modules`. - -Keep using `react-native-reanimated` as you do on iOS and Android; its JavaScript API is unchanged. Autolinking builds the desktop side when the app is built. - -## Documentation - -[Supported libraries](https://streetwriters.github.io/react-native-gpui/docs/supported-libraries) - -## License - -MIT. See [LICENSE](LICENSE). diff --git a/vendor/react-native-gpui/modules/reanimated/desktop/CMakeLists.txt b/vendor/react-native-gpui/modules/reanimated/desktop/CMakeLists.txt deleted file mode 100644 index 427df8fd59..0000000000 --- a/vendor/react-native-gpui/modules/reanimated/desktop/CMakeLists.txt +++ /dev/null @@ -1,116 +0,0 @@ -if(NOT RN_GPUI_PROJECT_ROOT) - message(FATAL_ERROR - "@react-native-gpui/reanimated was added by the platform; RN_GPUI_PROJECT_ROOT must be set by its build.rs") -endif() -set(_gpui_app_root "${RN_GPUI_PROJECT_ROOT}") -find_program(_gpui_node node REQUIRED) -execute_process( - COMMAND "${_gpui_node}" -e "process.stdout.write(require.resolve('react-native-reanimated/package.json', {paths: [process.argv[1]]}))" "${_gpui_app_root}" - RESULT_VARIABLE _reanimated_resolve_result - OUTPUT_VARIABLE _reanimated_package_json - OUTPUT_STRIP_TRAILING_WHITESPACE) -if(NOT _reanimated_resolve_result EQUAL 0 OR NOT EXISTS "${_reanimated_package_json}") - message(FATAL_ERROR "react-native-reanimated could not be resolved from ${_gpui_app_root}") -endif() -get_filename_component(_reanimated_root "${_reanimated_package_json}" DIRECTORY) -execute_process( - COMMAND "${_gpui_node}" -e "process.stdout.write(require.resolve('react-native/package.json', {paths: [process.argv[1]]}))" "${_gpui_app_root}" - RESULT_VARIABLE _react_native_resolve_result - OUTPUT_VARIABLE _react_native_package_json - OUTPUT_STRIP_TRAILING_WHITESPACE) -if(NOT _react_native_resolve_result EQUAL 0 OR NOT EXISTS "${_react_native_package_json}") - message(FATAL_ERROR "react-native could not be resolved from ${_gpui_app_root}") -endif() -get_filename_component(_react_native_root "${_react_native_package_json}" DIRECTORY) -execute_process( - COMMAND "${_gpui_node}" -e "process.stdout.write(require.resolve('react-native-worklets/package.json', {paths: [process.argv[1]]}))" "${_gpui_app_root}" - RESULT_VARIABLE _worklets_resolve_result - OUTPUT_VARIABLE _worklets_package_json - OUTPUT_STRIP_TRAILING_WHITESPACE) -if(NOT _worklets_resolve_result EQUAL 0 OR NOT EXISTS "${_worklets_package_json}") - message(FATAL_ERROR "react-native-worklets could not be resolved from ${_gpui_app_root}") -endif() -get_filename_component(_worklets_root "${_worklets_package_json}" DIRECTORY) -set(_reanimated_common "${_reanimated_root}/Common/cpp") -set(_worklets_common "${_worklets_root}/Common/cpp") -if(NOT EXISTS "${_reanimated_common}/reanimated/NativeModules/ReanimatedModuleProxy.h") - message(FATAL_ERROR "react-native-reanimated 4.7.x was not found in ${_gpui_app_root} or any ancestor node_modules directory") -endif() -execute_process( - COMMAND "${_gpui_node}" -e "process.stdout.write(require.resolve('@react-native-gpui/worklets/package.json', {paths: [process.argv[1]]}))" "${_gpui_app_root}" - RESULT_VARIABLE _gpui_worklets_resolve_result - OUTPUT_VARIABLE _gpui_worklets_package_json - OUTPUT_STRIP_TRAILING_WHITESPACE) -if(NOT _gpui_worklets_resolve_result EQUAL 0 OR NOT EXISTS "${_gpui_worklets_package_json}") - message(FATAL_ERROR "@react-native-gpui/worklets could not be resolved from ${_gpui_app_root}") -endif() -get_filename_component(_gpui_worklets_root "${_gpui_worklets_package_json}" DIRECTORY) -if(NOT EXISTS "${_worklets_common}/worklets/Compat/StableApi.h") - message(FATAL_ERROR "react-native-worklets 0.13.x is required by GPUI Reanimated") -endif() - -# Upstream's C++ does not build with MSVC or on Linux as published; compile -# patched copies in the build tree and leave node_modules untouched. Worklets -# is patched here too because Reanimated includes its headers. -set(_reanimated_patch "${CMAKE_CURRENT_LIST_DIR}/patches/react-native-reanimated-4.7.1.patch") -set(_worklets_patch "${_gpui_worklets_root}/desktop/patches/react-native-worklets-0.13.0.patch") -foreach(_patched reanimated worklets) - execute_process( - COMMAND "${_gpui_node}" "${_gpui_worklets_root}/desktop/patch-sources.mjs" - "${_${_patched}_root}" "${_${_patched}_patch}" - "${CMAKE_BINARY_DIR}/rn-gpui-patched/react-native-${_patched}" - RESULT_VARIABLE _patch_result - OUTPUT_VARIABLE _${_patched}_common - ERROR_VARIABLE _patch_error - OUTPUT_STRIP_TRAILING_WHITESPACE) - if(NOT _patch_result EQUAL 0) - message(FATAL_ERROR "${_patch_error}") - endif() -endforeach() -set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS - "${_reanimated_patch}" "${_worklets_patch}" - "${_reanimated_package_json}" "${_worklets_package_json}") - -# Match the static feature-flag definition normally supplied by Reanimated's -# CocoaPods/Gradle builds. Without this, FeatureFlags.h silently treats every -# flag as false, including defaults which change how animated props are -# committed through Fabric. -execute_process( - COMMAND "${_gpui_node}" -e - "const fs=require('fs'); const flags=JSON.parse(fs.readFileSync(process.argv[1],'utf8')); const app=JSON.parse(fs.readFileSync(process.argv[2],'utf8')); Object.assign(flags, app.reanimated?.staticFeatureFlags ?? {}); if(process.platform==='darwin' && !Object.hasOwn(app.reanimated?.staticFeatureFlags ?? {}, 'IOS_SYNCHRONOUSLY_UPDATE_UI_PROPS')) flags.IOS_SYNCHRONOUSLY_UPDATE_UI_PROPS=true; if(process.platform==='linux' && !Object.hasOwn(app.reanimated?.staticFeatureFlags ?? {}, 'LINUX_SYNCHRONOUSLY_UPDATE_UI_PROPS')) flags.LINUX_SYNCHRONOUSLY_UPDATE_UI_PROPS=true; process.stdout.write(Object.entries(flags).map(([key,value])=>'['+key+':'+value+']').join(''));" - "${_reanimated_root}/src/featureFlags/staticFlags.json" - "${_gpui_app_root}/package.json" - RESULT_VARIABLE _reanimated_flags_result - OUTPUT_VARIABLE _reanimated_feature_flags - OUTPUT_STRIP_TRAILING_WHITESPACE -) -if(NOT _reanimated_flags_result EQUAL 0 OR _reanimated_feature_flags STREQUAL "") - message(FATAL_ERROR "Failed to load Reanimated static feature flags for GPUI") -endif() - -execute_process( - COMMAND "${_gpui_node}" "${_react_native_root}/scripts/generate-codegen-artifacts.js" - --path "${_gpui_app_root}" - --targetPlatform ios - --outputPath "${_gpui_app_root}/desktop/build/codegen" - --source app - RESULT_VARIABLE _reanimated_codegen_result -) -if(NOT _reanimated_codegen_result EQUAL 0) - message(FATAL_ERROR "React Native codegen failed while configuring GPUI Reanimated") -endif() -set(_rn_codegen "${_gpui_app_root}/desktop/build/codegen/build/generated/ios/ReactCodegen") - -file(GLOB_RECURSE _reanimated_sources CONFIGURE_DEPENDS "${_reanimated_common}/reanimated/*.cpp") -set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_SOURCES - ${_reanimated_sources} - "${CMAKE_CURRENT_LIST_DIR}/cpp/GPUIReanimatedModule.cpp") -set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_INCLUDE_DIRS - "${_reanimated_common}" - "${_reanimated_root}" - "${_worklets_common}" - "${_rn_codegen}" - "${_gpui_worklets_root}/desktop/cpp") -set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_DEFINITIONS - "REANIMATED_VERSION=4.7.1" - "REANIMATED_FEATURE_FLAGS=\"${_reanimated_feature_flags}\"") diff --git a/vendor/react-native-gpui/modules/reanimated/desktop/cpp/GPUIReanimatedModule.cpp b/vendor/react-native-gpui/modules/reanimated/desktop/cpp/GPUIReanimatedModule.cpp deleted file mode 100644 index 0cc7638504..0000000000 --- a/vendor/react-native-gpui/modules/reanimated/desktop/cpp/GPUIReanimatedModule.cpp +++ /dev/null @@ -1,169 +0,0 @@ -#include "GPUIWorkletsModule.h" -#include "GpuiHost.h" - -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include - -namespace { -bool animationTracingEnabled() { - static const bool enabled = std::getenv("RN_GPUI_DEBUG_ANIMATION") != nullptr; - return enabled; -} - -using facebook::jsi::Runtime; -using reanimated::PlatformDepMethodsHolder; -using reanimated::ReanimatedModuleProxy; - -PlatformDepMethodsHolder platformMethods( - const std::shared_ptr>& proxyHolder) { - PlatformDepMethodsHolder methods; - methods.requestRender = [](std::function callback) { - static std::atomic requests{0}; - const auto count = ++requests; - if (animationTracingEnabled() && (count <= 5 || count % 60 == 0)) { - LOG(INFO) << "[gpui-reanimated] requestRender count=" << count; - } - auto module = gpui_worklets::currentModule(); - if (module) - module->requestAnimationFrame(std::move(callback)); - }; - methods.synchronouslyUpdateUIPropsFunction = [](const int tag, - const folly::dynamic& props) { - rngpui::gpui_synchronously_update_props(tag, props); - }; - methods.getAnimationTimestamp = [] { - return std::chrono::duration( - std::chrono::steady_clock::now().time_since_epoch()) - .count(); - }; - methods.registerSensor = - [](int, int, int, std::function) { return 0; }; - methods.unregisterSensor = [](int) {}; - methods.setGestureStateFunction = [](int, int) {}; - methods.maybeFlushUIUpdatesQueueFunction = [proxyHolder] { - if (auto proxy = proxyHolder->lock()) { - proxy->performOperations(); - } - }; - methods.attachPseudoSelector = [](facebook::react::Tag, - reanimated::PseudoSelector, - std::function callback) { - if (callback) - callback(false); - }; - methods.detachPseudoSelector = [](facebook::react::Tag, - reanimated::PseudoSelector) {}; -#if defined(__APPLE__) - methods.forceScreenSnapshotFunction = [](facebook::react::Tag) { - return false; - }; - methods.readMountedViewPropsFunction = - [](facebook::react::Tag) -> facebook::react::Props::Shared { - return nullptr; - }; -#endif - return methods; -} - -class Module final - : public facebook::react::NativeReanimatedModuleSpec { - public: - explicit Module(std::shared_ptr jsInvoker) - : NativeReanimatedModuleSpec(std::move(jsInvoker)) {} - - bool installTurboModule(Runtime& runtime) { - if (proxy_) - return true; - auto worklets = gpui_worklets::currentModule(); - auto uiManager = rngpui::get_gpui_ui_manager(); - if (!worklets || !worklets->uiRuntime() || !worklets->uiScheduler() || - !uiManager) { - throw facebook::jsi::JSError( - runtime, "GPUI Reanimated requires initialized Worklets and Fabric"); - } - - // The platform flush callback is constructed before the proxy exists. - // Retain only a weak reference so the decorated UI runtime cannot keep - // the module alive after React Native tears it down. - auto proxyHolder = std::make_shared>(); - auto methods = platformMethods(proxyHolder); - proxy_ = std::make_shared( - worklets->uiRuntime(), - worklets->uiScheduler(), - runtime, - jsInvoker_, - methods, - false); - *proxyHolder = proxy_; - // The platform runs the registries' pending updates after each frame's - // animation callbacks, which is what applies a CSS transition or animation. - worklets->setAfterFrame( - [weak = std::weak_ptr(proxy_)] { - if (auto proxy = weak.lock()) { - proxy->performOperations(); - } - }); - proxy_->init(methods); - proxy_->initializeFabric(uiManager); - LOG(INFO) << "[gpui-reanimated] module proxy initialized"; - auto& uiRuntime = - worklets::getJSIRuntimeFromWorkletRuntime(worklets->uiRuntime()); - reanimated::RNRuntimeDecorator::decorate(runtime, uiRuntime, proxy_); - std::weak_ptr weakProxy = proxy_; - eventListener_ = std::make_shared( - [weakProxy](const facebook::react::RawEvent& event) { - auto proxy = weakProxy.lock(); - if (!proxy) - return false; - const auto timestamp = - std::chrono::duration( - std::chrono::steady_clock::now().time_since_epoch()) - .count(); - static std::atomic events{0}; - const auto count = ++events; - if (animationTracingEnabled() && - event.type.find("GestureHandler") != std::string::npos) { - const auto* target = event.eventTarget.get(); - const auto tag = target ? target->getTag() : -1; - auto eventName = event.type; - if (eventName.rfind("top", 0) == 0) { - eventName = "on" + eventName.substr(3); - } - LOG(INFO) << "[gpui-reanimated] gesture lookup type=" << eventName - << " tag=" << tag << " waiting=" - << proxy->isAnyHandlerWaitingForEvent(eventName, tag); - } - if (animationTracingEnabled() && - (count <= 10 || - event.type.find("GestureHandler") != std::string::npos)) { - LOG(INFO) << "[gpui-reanimated] raw event count=" << count - << " type=" << event.type; - } - return proxy->handleRawEvent(event, timestamp); - }); - rngpui::register_gpui_event_listener(eventListener_); - return true; - } - - std::shared_ptr proxy_; - std::shared_ptr eventListener_; -}; -} // namespace - -std::shared_ptr create_gpui_reanimated_module( - const std::string& name, - std::shared_ptr jsInvoker) { - return rngpui::provideTurboModule(name, std::move(jsInvoker)); -} diff --git a/vendor/react-native-gpui/modules/reanimated/desktop/patches/react-native-reanimated-4.7.1.patch b/vendor/react-native-gpui/modules/reanimated/desktop/patches/react-native-reanimated-4.7.1.patch deleted file mode 100644 index 20c0cc45b2..0000000000 --- a/vendor/react-native-gpui/modules/reanimated/desktop/patches/react-native-reanimated-4.7.1.patch +++ /dev/null @@ -1,530 +0,0 @@ ---- a/reanimated/CSS/common/filters/FilterOp.cpp -+++ b/reanimated/CSS/common/filters/FilterOp.cpp -@@ -1,6 +1,7 @@ - #include - - #include -+#include - #include - #include - ---- a/reanimated/CSS/common/transforms/TransformMatrix2D.cpp -+++ b/reanimated/CSS/common/transforms/TransformMatrix2D.cpp -@@ -1,6 +1,7 @@ - #include - - #include -+#include - - namespace reanimated::css { - ---- a/reanimated/CSS/common/transforms/TransformMatrix3D.cpp -+++ b/reanimated/CSS/common/transforms/TransformMatrix3D.cpp -@@ -1,6 +1,8 @@ - #include - #include - -+#include -+#include - #include - - namespace reanimated::css { ---- a/reanimated/CSS/common/transforms/TransformOp.cpp -+++ b/reanimated/CSS/common/transforms/TransformOp.cpp -@@ -1,6 +1,7 @@ - #include - - #include -+#include - #include - #include - ---- a/reanimated/CSS/common/transforms/vectors.cpp -+++ b/reanimated/CSS/common/transforms/vectors.cpp -@@ -1,4 +1,5 @@ - #include -+#include - - namespace reanimated::css { - ---- a/reanimated/CSS/common/values/CSSAngle.cpp -+++ b/reanimated/CSS/common/values/CSSAngle.cpp -@@ -2,6 +2,7 @@ - - #include - #include -+#include - #include - #include - ---- a/reanimated/CSS/common/values/CSSColor.cpp -+++ b/reanimated/CSS/common/values/CSSColor.cpp -@@ -4,6 +4,7 @@ - - #include - -+#include - #include - - namespace reanimated::css { ---- a/reanimated/CSS/common/values/CSSLength.cpp -+++ b/reanimated/CSS/common/values/CSSLength.cpp -@@ -1,6 +1,7 @@ - #include - #include - -+#include - #include - - namespace reanimated::css { ---- a/reanimated/CSS/common/values/CSSValueVariant.cpp -+++ b/reanimated/CSS/common/values/CSSValueVariant.cpp -@@ -14,6 +14,7 @@ - #include - #include - -+#include - #include - #include - #include ---- a/reanimated/CSS/configs/CSSAnimationConfig.cpp -+++ b/reanimated/CSS/configs/CSSAnimationConfig.cpp -@@ -1,6 +1,7 @@ - #include - - #include -+#include - #include - #include - #include ---- a/reanimated/CSS/easing/EasingFunctions.cpp -+++ b/reanimated/CSS/easing/EasingFunctions.cpp -@@ -1,5 +1,6 @@ - #include - -+#include - #include - #include - #include ---- a/reanimated/CSS/interpolation/InterpolatorFactory.cpp -+++ b/reanimated/CSS/interpolation/InterpolatorFactory.cpp -@@ -27,7 +27,7 @@ class RecordInterpolatorFactory : public PropertyInterpolatorFactory { - // Helper private type just for a default value - struct EmptyObjectValue : public CSSValue { - folly::dynamic toDynamic() const override { -- return folly::dynamic::object; -+ return folly::dynamic::object(); - } - - std::string toString() const override { -@@ -53,7 +53,7 @@ class ArrayLikeInterpolatorFactory : public PropertyInterpolatorFactory { - // Helper private type just for a default value - struct EmptyArrayValue : public CSSValue { - folly::dynamic toDynamic() const override { -- return folly::dynamic::array; -+ return folly::dynamic::array(); - } - - std::string toString() const override { ---- a/reanimated/CSS/interpolation/InterpolatorFactory.h -+++ b/reanimated/CSS/interpolation/InterpolatorFactory.h -@@ -14,6 +14,7 @@ - #include - - #include -+#include - #include - #include - #include ---- a/reanimated/CSS/interpolation/PropertyInterpolator.cpp -+++ b/reanimated/CSS/interpolation/PropertyInterpolator.cpp -@@ -2,6 +2,7 @@ - #include - - #include -+#include - #include - #include - #include ---- a/reanimated/CSS/interpolation/filters/FilterOperation.cpp -+++ b/reanimated/CSS/interpolation/filters/FilterOperation.cpp -@@ -15,6 +15,7 @@ - #include - #include - -+#include - #include - - namespace reanimated::css { ---- a/reanimated/CSS/interpolation/transforms/TransformOperation.cpp -+++ b/reanimated/CSS/interpolation/transforms/TransformOperation.cpp -@@ -13,6 +13,7 @@ - #include - #include - -+#include - #include - - namespace reanimated::css { ---- a/reanimated/CSS/interpolation/transforms/TransformOperationInterpolator.cpp -+++ b/reanimated/CSS/interpolation/transforms/TransformOperationInterpolator.cpp -@@ -7,22 +7,11 @@ - - #include - #include -+#include - #include - - namespace reanimated::css { - --// Base implementation for simple operations --template --std::unique_ptr TransformOperationInterpolator::interpolate( -- double progress, -- const std::shared_ptr &from, -- const std::shared_ptr &to, -- const StyleOperationsInterpolationContext & /* context */) const { -- const auto &fromOp = *std::static_pointer_cast(from); -- const auto &toOp = *std::static_pointer_cast(to); -- return std::make_unique(fromOp.value.interpolate(progress, toOp.value)); --} -- - // Specialization for PerspectiveOperation - TransformOperationInterpolator::TransformOperationInterpolator( - const std::shared_ptr &defaultOperation) -@@ -148,52 +137,6 @@ template TransformMatrix3D TransformOperationInterpolator::inte - const TransformMatrix::Shared &, - const TransformMatrix::Shared &) const; - --// Specialization for resolvable operations --template --TransformOperationInterpolator::TransformOperationInterpolator( -- const std::shared_ptr &defaultOperation, -- ResolvableValueInterpolatorConfig config) -- : StyleOperationInterpolator(defaultOperation), config_(std::move(config)) {} -- --template --std::unique_ptr TransformOperationInterpolator::interpolate( -- double progress, -- const std::shared_ptr &from, -- const std::shared_ptr &to, -- const StyleOperationsInterpolationContext &context) const { -- const auto &fromOp = *std::static_pointer_cast(from); -- const auto &toOp = *std::static_pointer_cast(to); -- -- return std::make_unique(fromOp.value.interpolate(progress, toOp.value, getRelativeValueContext(context))); --} -- --template --std::shared_ptr TransformOperationInterpolator::resolveOperation( -- const std::shared_ptr &operation, -- const StyleOperationsInterpolationContext &context) const { -- const auto &resolvableOp = std::static_pointer_cast(operation); -- const auto &resolved = resolvableOp->value.resolve(getRelativeValueContext(context)); -- -- if (!resolved.has_value()) { -- throw std::invalid_argument( -- "[Reanimated] Cannot resolve resolvable operation: " + operation->getOperationName() + -- " for node with tag: " + std::to_string(context.node->getTag())); -- } -- -- return std::make_shared(resolved.value()); --} -- --template --RelativeValueInterpolationContext TransformOperationInterpolator::getRelativeValueContext( -- const StyleOperationsInterpolationContext &context) const { -- return RelativeValueInterpolationContext{ -- .node = context.node, -- .fallbackInterpolateThreshold = context.fallbackInterpolateThreshold, -- .viewStylesRepository = context.viewStylesRepository, -- .relativeProperty = config_.relativeProperty, -- .relativeTo = config_.relativeTo}; --} -- - // Rotate operations - template class TransformOperationInterpolator; - template class TransformOperationInterpolator; ---- a/reanimated/CSS/interpolation/transforms/TransformOperationInterpolator.h -+++ b/reanimated/CSS/interpolation/transforms/TransformOperationInterpolator.h -@@ -6,6 +6,9 @@ - #include - - #include -+#include -+#include -+#include - - namespace reanimated::css { - -@@ -15,11 +18,18 @@ class TransformOperationInterpolator : public StyleOperationInterpolator { - public: - using StyleOperationInterpolator::StyleOperationInterpolator; - -+ // Defined in the class body: MSVC rejects an out-of-line definition of the -+ // primary template member next to the constrained partial specialization -+ // below (C3855). - std::unique_ptr interpolate( - double progress, - const std::shared_ptr &from, - const std::shared_ptr &to, -- const StyleOperationsInterpolationContext &context) const override; -+ const StyleOperationsInterpolationContext & /* context */) const override { -+ const auto &fromOp = *std::static_pointer_cast(from); -+ const auto &toOp = *std::static_pointer_cast(to); -+ return std::make_unique(fromOp.value.interpolate(progress, toOp.value)); -+ } - }; - - // Specialization for PerspectiveOperation -@@ -59,27 +69,54 @@ class TransformOperationInterpolator : public StyleOperationInt - }; - - // Specialization for resolvable operations -+// Members are defined in the class body: MSVC 14.51 cannot match out-of-line -+// definitions of a constrained partial specialization's members (C2244, C3855). - template - class TransformOperationInterpolator : public StyleOperationInterpolator { - public: - TransformOperationInterpolator( - const std::shared_ptr &defaultOperation, -- ResolvableValueInterpolatorConfig config); -+ ResolvableValueInterpolatorConfig config) -+ : StyleOperationInterpolator(defaultOperation), config_(std::move(config)) {} - - std::unique_ptr interpolate( - double progress, - const std::shared_ptr &from, - const std::shared_ptr &to, -- const StyleOperationsInterpolationContext &context) const override; -+ const StyleOperationsInterpolationContext &context) const override { -+ const auto &fromOp = *std::static_pointer_cast(from); -+ const auto &toOp = *std::static_pointer_cast(to); -+ -+ return std::make_unique( -+ fromOp.value.interpolate(progress, toOp.value, getRelativeValueContext(context))); -+ } - - std::shared_ptr resolveOperation( - const std::shared_ptr &operation, -- const StyleOperationsInterpolationContext &context) const override; -+ const StyleOperationsInterpolationContext &context) const override { -+ const auto &resolvableOp = std::static_pointer_cast(operation); -+ const auto &resolved = resolvableOp->value.resolve(getRelativeValueContext(context)); -+ -+ if (!resolved.has_value()) { -+ throw std::invalid_argument( -+ "[Reanimated] Cannot resolve resolvable operation: " + operation->getOperationName() + -+ " for node with tag: " + std::to_string(context.node->getTag())); -+ } -+ -+ return std::make_shared(resolved.value()); -+ } - - protected: - const ResolvableValueInterpolatorConfig config_; - -- RelativeValueInterpolationContext getRelativeValueContext(const StyleOperationsInterpolationContext &context) const; -+ RelativeValueInterpolationContext getRelativeValueContext(const StyleOperationsInterpolationContext &context) const { -+ return RelativeValueInterpolationContext{ -+ .node = context.node, -+ .fallbackInterpolateThreshold = context.fallbackInterpolateThreshold, -+ .viewStylesRepository = context.viewStylesRepository, -+ .relativeProperty = config_.relativeProperty, -+ .relativeTo = config_.relativeTo}; -+ } - }; - - } // namespace reanimated::css ---- a/reanimated/CSS/interpolation/transforms/operations/matrix.cpp -+++ b/reanimated/CSS/interpolation/transforms/operations/matrix.cpp -@@ -3,6 +3,7 @@ - - #include - #include -+#include - #include - - namespace reanimated::css { ---- a/reanimated/CSS/interpolation/transforms/operations/translate.cpp -+++ b/reanimated/CSS/interpolation/transforms/operations/translate.cpp -@@ -3,6 +3,7 @@ - #include - - #include -+#include - #include - - namespace reanimated::css { ---- a/reanimated/CSS/interpolation/values/SimpleValueInterpolator.cpp -+++ b/reanimated/CSS/interpolation/values/SimpleValueInterpolator.cpp -@@ -18,6 +18,7 @@ - #include - - #include -+#include - - namespace reanimated::css { - ---- a/reanimated/CSS/misc/ViewStylesRepository.cpp -+++ b/reanimated/CSS/misc/ViewStylesRepository.cpp -@@ -2,6 +2,7 @@ - #include - - #include -+#include - #include - #include - ---- a/reanimated/CSS/registries/CSSAnimationsRegistry.cpp -+++ b/reanimated/CSS/registries/CSSAnimationsRegistry.cpp -@@ -4,6 +4,7 @@ - #include - - #include -+#include - #include - #include - #include ---- a/reanimated/CSS/svg/values/SVGPath.cpp -+++ b/reanimated/CSS/svg/values/SVGPath.cpp -@@ -7,6 +7,7 @@ - #include - #include - #include -+#include - #include - - namespace reanimated::css { ---- a/reanimated/CSS/svg/values/SVGStops.cpp -+++ b/reanimated/CSS/svg/values/SVGStops.cpp -@@ -2,6 +2,7 @@ - #include - - #include -+#include - #include - #include - #include ---- a/reanimated/CSS/utils/interpolators.cpp -+++ b/reanimated/CSS/utils/interpolators.cpp -@@ -1,6 +1,7 @@ - #include - - #include -+#include - #include - - namespace reanimated::css { ---- a/reanimated/Fabric/updates/UpdatesRegistryManager.cpp -+++ b/reanimated/Fabric/updates/UpdatesRegistryManager.cpp -@@ -4,6 +4,7 @@ - #include - - #include -+#include - #include - #include - ---- a/reanimated/LayoutAnimations/LayoutAnimationsManager.cpp -+++ b/reanimated/LayoutAnimations/LayoutAnimationsManager.cpp -@@ -3,6 +3,7 @@ - #include - - #include -+#include - #include - #include - #include ---- a/reanimated/NativeModules/ReanimatedModuleProxy.cpp -+++ b/reanimated/NativeModules/ReanimatedModuleProxy.cpp -@@ -30,6 +30,7 @@ - #include - #include - #include -+#include - #include - #include - #include -@@ -72,6 +73,10 @@ constexpr bool shouldUseSynchronousUpdatesInPerformOperations() { - constexpr bool shouldUseSynchronousUpdatesInPerformOperations() { - return StaticFeatureFlags::getFlag("IOS_SYNCHRONOUSLY_UPDATE_UI_PROPS"); - } -+#elif defined(__linux__) -+constexpr bool shouldUseSynchronousUpdatesInPerformOperations() { -+ return StaticFeatureFlags::getFlag("LINUX_SYNCHRONOUSLY_UPDATE_UI_PROPS"); -+} - #else - constexpr bool shouldUseSynchronousUpdatesInPerformOperations() { - return false; -@@ -1089,11 +1094,11 @@ void ReanimatedModuleProxy::writeSynchronousPropsToViews(const UpdatesBatch &syn - } - #endif // ANDROID - --#if __APPLE__ -+#ifndef ANDROID - for (const auto &[shadowNodeFamily, props] : synchronousUpdatesBatch) { - synchronouslyUpdateUIPropsFunction_(shadowNodeFamily->getTag(), props); - } --#endif // __APPLE__ -+#endif // ANDROID - } - - void ReanimatedModuleProxy::requestFlushRegistry() { ---- a/reanimated/Tools/FeatureFlags.h -+++ b/reanimated/Tools/FeatureFlags.h -@@ -1,5 +1,6 @@ - #pragma once - #include -+#include - #include - #include - ---- a/reanimated/Tools/PlatformDepMethodsHolder.h -+++ b/reanimated/Tools/PlatformDepMethodsHolder.h -@@ -9,7 +9,9 @@ - #include - #include - -+#include - #include -+#include - #include - #include - #include -@@ -32,7 +34,7 @@ using MeasureFunction = std::function)>; - #ifdef ANDROID - using SynchronouslyUpdateUIPropsFunction = std::function &, const std::vector &)>; --#elif __APPLE__ -+#else - using SynchronouslyUpdateUIPropsFunction = std::function; - #endif // ANDROID - using PreserveMountedTagsFunction = std::function>(std::vector &)>; ---- a/reanimated/Tools/SingleInstanceChecker.h -+++ b/reanimated/Tools/SingleInstanceChecker.h -@@ -4,7 +4,9 @@ - - #include - -+#ifndef _MSC_VER - #include -+#endif - - #include - #include -@@ -51,10 +53,14 @@ class SingleInstanceChecker { - - template - SingleInstanceChecker::SingleInstanceChecker() { -+#ifdef _MSC_VER -+ std::string className = typeid(T).name(); -+#else - int status = 0; - char *demangled = __cxxabiv1::__cxa_demangle(typeid(T).name(), nullptr, nullptr, &status); - std::string className = (status == 0 && demangled != nullptr) ? demangled : typeid(T).name(); - std::free(demangled); -+#endif - - // React Native can spawn up to two instances of a Native Module at the same - // time. This happens during a reload when a new instance of React Native is diff --git a/vendor/react-native-gpui/modules/reanimated/package.json b/vendor/react-native-gpui/modules/reanimated/package.json deleted file mode 100644 index d725e8df65..0000000000 --- a/vendor/react-native-gpui/modules/reanimated/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "@react-native-gpui/reanimated", - "version": "4.7.0-alpha.1", - "description": "Adapter for react-native-reanimated (MIT): runs animations, layout animations and CSS animations on the desktop renderer", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/streetwriters/react-native-gpui-modules.git", - "directory": "modules/reanimated" - }, - "homepage": "https://github.com/streetwriters/react-native-gpui-modules/tree/main/modules/reanimated#readme", - "bugs": { - "url": "https://github.com/streetwriters/react-native-gpui-modules/issues" - }, - "files": [ - "desktop", - "react-native.config.js", - "src", - "README.md", - "LICENSE", - "CHANGELOG.md", - "!**/*.test.js", - "!**/*.test.mjs", - "!**/*.test.ts", - "!**/*.test.cjs" - ], - "peerDependencies": { - "react-native": "0.87.x", - "react-native-reanimated": "4.7.x", - "react-native-worklets": "0.13.x", - "@react-native-gpui/worklets": "0.13.0-alpha.1" - }, - "codegenConfig": { - "name": "GPUIReanimatedSpec", - "type": "modules", - "jsSrcsDir": "src" - }, - "publishConfig": { - "access": "public", - "tag": "latest" - } -} diff --git a/vendor/react-native-gpui/modules/reanimated/react-native.config.js b/vendor/react-native-gpui/modules/reanimated/react-native.config.js deleted file mode 100644 index edd87f97d4..0000000000 --- a/vendor/react-native-gpui/modules/reanimated/react-native.config.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = { - dependency: { - platforms: { - desktop: { - cmake: 'desktop', - cppProvider: 'create_gpui_reanimated_module', - }, - }, - }, -}; diff --git a/vendor/react-native-gpui/modules/reanimated/src/NativeReanimatedModule.ts b/vendor/react-native-gpui/modules/reanimated/src/NativeReanimatedModule.ts deleted file mode 100644 index a664c6dca4..0000000000 --- a/vendor/react-native-gpui/modules/reanimated/src/NativeReanimatedModule.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { TurboModule } from 'react-native'; -import { TurboModuleRegistry } from 'react-native'; - -export interface Spec extends TurboModule { - installTurboModule: () => boolean; -} - -export default TurboModuleRegistry.get('ReanimatedModule'); diff --git a/vendor/react-native-gpui/modules/safe-area-context/CHANGELOG.md b/vendor/react-native-gpui/modules/safe-area-context/CHANGELOG.md deleted file mode 100644 index e00be548c6..0000000000 --- a/vendor/react-native-gpui/modules/safe-area-context/CHANGELOG.md +++ /dev/null @@ -1,8 +0,0 @@ -# Changelog - -All notable changes to `@react-native-gpui/safe-area-context` are listed here. Each version's section becomes the notes of its GitHub release. - -## 5.10.0-alpha.0 - 2026-11-01 - -- First release, for `react-native-safe-area-context` 5.10.x. -- Safe area insets for desktop windows, including custom title bars. diff --git a/vendor/react-native-gpui/modules/safe-area-context/LICENSE b/vendor/react-native-gpui/modules/safe-area-context/LICENSE deleted file mode 100644 index 149a0f8321..0000000000 --- a/vendor/react-native-gpui/modules/safe-area-context/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Streetwriters - -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/vendor/react-native-gpui/modules/safe-area-context/README.md b/vendor/react-native-gpui/modules/safe-area-context/README.md deleted file mode 100644 index bf29bcdde1..0000000000 --- a/vendor/react-native-gpui/modules/safe-area-context/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# @react-native-gpui/safe-area-context - -Adapter for [`react-native-safe-area-context`](https://github.com/AppAndFlow/react-native-safe-area-context) (MIT): reports safe area insets for desktop windows, including windows with a custom title bar. - -Part of [react-native-gpui](https://github.com/streetwriters/react-native-gpui), React Native for macOS, Windows and Linux. - -## Install - -Install it next to `react-native-safe-area-context`: - -```sh -npm install react-native-safe-area-context@5.10.x @react-native-gpui/safe-area-context -``` - -Keep using `react-native-safe-area-context` as you do on iOS and Android; its JavaScript API is unchanged. Autolinking builds the desktop side when the app is built. - -## Documentation - -[Supported libraries](https://streetwriters.github.io/react-native-gpui/docs/supported-libraries) - -## License - -MIT. See [LICENSE](LICENSE). diff --git a/vendor/react-native-gpui/modules/safe-area-context/desktop/CMakeLists.txt b/vendor/react-native-gpui/modules/safe-area-context/desktop/CMakeLists.txt deleted file mode 100644 index 5e934c3598..0000000000 --- a/vendor/react-native-gpui/modules/safe-area-context/desktop/CMakeLists.txt +++ /dev/null @@ -1,33 +0,0 @@ -if(NOT RN_GPUI_PROJECT_ROOT) - message(FATAL_ERROR - "@react-native-gpui/safe-area-context was added by the platform; RN_GPUI_PROJECT_ROOT must be set by its build.rs") -endif() -rn_gpui_find_node_module(react-native-safe-area-context _safe_area_root) -set(_safe_area_common "${_safe_area_root}/common/cpp") -set(_safe_area_shadow_node "${_safe_area_common}/react/renderer/components/safeareacontext/RNCSafeAreaViewShadowNode.cpp") -set(_safe_area_package_json "${_safe_area_root}/package.json") - -if(NOT EXISTS "${_safe_area_shadow_node}" OR NOT EXISTS "${_safe_area_package_json}") - message(FATAL_ERROR "react-native-safe-area-context 5.10.x was not found at ${_safe_area_root}") -endif() -file(READ "${_safe_area_package_json}" _safe_area_package_json_contents) -string(JSON _safe_area_version GET "${_safe_area_package_json_contents}" version) -if(NOT _safe_area_version MATCHES "^5\\.10\\.") - message(FATAL_ERROR "@react-native-gpui/safe-area-context supports react-native-safe-area-context 5.10.x, found ${_safe_area_version}") -endif() - -set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_SOURCES - "${_safe_area_shadow_node}" - "${CMAKE_CURRENT_LIST_DIR}/cpp/GPUISafeAreaContextModule.cpp") -set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_INCLUDE_DIRS - "${_safe_area_common}" - "${RN_GPUI_REACT_CXX_PLATFORM_DIR}" - "${CMAKE_CURRENT_LIST_DIR}/cpp") -# Safe-area insets reach the mounting manager through this glue, which the -# platform compiles only because the package is installed. -set_property(GLOBAL APPEND PROPERTY RN_GPUI_PACKAGE_MODULE_SOURCES - "${CMAKE_CURRENT_LIST_DIR}/cpp/GpuiSafeAreaModule.cpp") -set_property(GLOBAL APPEND PROPERTY RN_GPUI_PACKAGE_MODULE_INSTALLERS safe_area) -set_property(GLOBAL APPEND PROPERTY RN_GPUI_PACKAGE_MODULE_INCLUDE_DIRS - "${CMAKE_CURRENT_LIST_DIR}/cpp" - "${RN_GPUI_PROJECT_ROOT}/desktop/autolink/codegen/safeareacontext") diff --git a/vendor/react-native-gpui/modules/safe-area-context/desktop/cpp/GPUISafeAreaContextModule.cpp b/vendor/react-native-gpui/modules/safe-area-context/desktop/cpp/GPUISafeAreaContextModule.cpp deleted file mode 100644 index 670865ad27..0000000000 --- a/vendor/react-native-gpui/modules/safe-area-context/desktop/cpp/GPUISafeAreaContextModule.cpp +++ /dev/null @@ -1,48 +0,0 @@ -#include -#include -#include "GPUISafeAreaInsets.h" - -#include - -namespace { -using facebook::react::TurboModule; - -class SafeAreaContextModule final - : public facebook::react::NativeSafeAreaContextSpec { - public: - explicit SafeAreaContextModule( - std::shared_ptr jsInvoker) - : NativeSafeAreaContextSpec(std::move(jsInvoker)) {} - - facebook::jsi::Object getConstants(facebook::jsi::Runtime& runtime) { - const auto windowSize = facebook::react::DeviceInfoModule::windowSize(); - facebook::jsi::Object insets(runtime); - const auto safeInsets = gpui_safe_area::gpui_safe_area_insets(0); - insets.setProperty(runtime, "top", safeInsets.top); - insets.setProperty(runtime, "right", safeInsets.right); - insets.setProperty(runtime, "bottom", safeInsets.bottom); - insets.setProperty(runtime, "left", safeInsets.left); - - facebook::jsi::Object frame(runtime); - frame.setProperty(runtime, "x", 0.0); - frame.setProperty(runtime, "y", 0.0); - frame.setProperty(runtime, "width", windowSize.width); - frame.setProperty(runtime, "height", windowSize.height); - - facebook::jsi::Object metrics(runtime); - metrics.setProperty(runtime, "insets", std::move(insets)); - metrics.setProperty(runtime, "frame", std::move(frame)); - - facebook::jsi::Object constants(runtime); - constants.setProperty(runtime, "initialWindowMetrics", std::move(metrics)); - return constants; - } -}; -} // namespace - -std::shared_ptr create_gpui_safe_area_context_module( - const std::string& name, - std::shared_ptr jsInvoker) { - return rngpui::provideTurboModule( - name, std::move(jsInvoker)); -} diff --git a/vendor/react-native-gpui/modules/safe-area-context/desktop/cpp/GPUISafeAreaInsets.h b/vendor/react-native-gpui/modules/safe-area-context/desktop/cpp/GPUISafeAreaInsets.h deleted file mode 100644 index cd432b1e7c..0000000000 --- a/vendor/react-native-gpui/modules/safe-area-context/desktop/cpp/GPUISafeAreaInsets.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include -#include - -namespace gpui_safe_area { - -struct Insets { - double top; - double right; - double bottom; - double left; -}; - -inline std::atomic windowTopInset{0.0}; - -inline Insets gpui_safe_area_insets(int32_t /*surfaceId*/) { - return { - .top = windowTopInset.load(), .right = 0.0, .bottom = 0.0, .left = 0.0}; -} - -} // namespace gpui_safe_area diff --git a/vendor/react-native-gpui/modules/safe-area-context/desktop/cpp/GpuiSafeAreaModule.cpp b/vendor/react-native-gpui/modules/safe-area-context/desktop/cpp/GpuiSafeAreaModule.cpp deleted file mode 100644 index 4c84f883c6..0000000000 --- a/vendor/react-native-gpui/modules/safe-area-context/desktop/cpp/GpuiSafeAreaModule.cpp +++ /dev/null @@ -1,143 +0,0 @@ -#include "GPUISafeAreaInsets.h" -#include "GpuiModules.h" - -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace rngpui { -using namespace facebook::react; - -namespace { -struct TrackedView { - std::array frame; - SharedEventEmitter emitter; - std::shared_ptr> state; -}; - -std::mutex trackedMutex; -std::unordered_map tracked; - -std::shared_ptr> safeAreaState( - const ShadowView& view) { - if (std::string_view(view.componentName) != "RNCSafeAreaView") - return nullptr; - return std::dynamic_pointer_cast>( - view.state); -} - -void dispatchInsets( - const SharedEventEmitter& emitter, - const std::array& frame, - float top, - float right, - float bottom, - float left) { - if (!emitter) - return; - emitter->dispatchEvent( - "insetsChange", - folly::dynamic::object( - "insets", - folly::dynamic::object("top", top)("right", right)("bottom", bottom)( - "left", left))( - "frame", - folly::dynamic::object("x", frame[0])("y", frame[1])( - "width", frame[2])("height", frame[3]))); -} - -void applyInsets(float top, float right, float bottom, float left) { - const bool changed = gpui_safe_area::windowTopInset.exchange(top) != top; - std::vector>> - states; - { - std::lock_guard lock(trackedMutex); - for (const auto& [tag, entry] : tracked) { - (void)tag; - if (changed && entry.emitter) - dispatchInsets(entry.emitter, entry.frame, top, right, bottom, left); - if (!entry.state) - continue; - // The tracked state is the one the view had when its frame last changed. - // A state update does not move the frame, so it would stay at the old - // insets, and every batch would send the same update again: one commit - // per batch, for ever. - const auto latest = - std::dynamic_pointer_cast>( - entry.state->getMostRecentState()); - const auto& current = latest ? latest : entry.state; - if (current->getData().insets.top != top) - states.push_back(current); - } - } - for (const auto& state : states) { - auto next = state->getData(); - next.insets.top = top; - state->updateState(std::move(next)); - } -} -} // namespace - -void rn_gpui_install_safe_area_module() { - registerMountObserver(extension::MountObserver{ - .onFrameChanged = - [](SurfaceId surfaceId, const ShadowView& view) { - const auto& frame = view.layoutMetrics.frame; - const std::array nextFrame = { - frame.origin.x, - frame.origin.y, - frame.size.width, - frame.size.height}; - const bool isProvider = - std::string_view(view.componentName) == "RNCSafeAreaProvider"; - if (!isProvider && !safeAreaState(view)) - return; - { - std::lock_guard lock(trackedMutex); - auto& entry = tracked[view.tag]; - if (isProvider && entry.emitter && entry.frame == nextFrame) - return; - entry.frame = nextFrame; - entry.emitter = view.eventEmitter; - entry.state = safeAreaState(view); - } - if (!isProvider) - return; - const auto insets = gpui_safe_area::gpui_safe_area_insets( - static_cast(surfaceId)); - LOG(INFO) << "[gpui-safe-area] onInsetsChange tag=" << view.tag - << " surface=" << surfaceId << " frame=(" - << frame.origin.x << ',' << frame.origin.y << ' ' - << frame.size.width << 'x' << frame.size.height << ')'; - dispatchInsets( - view.eventEmitter, - nextFrame, - insets.top, - insets.right, - insets.bottom, - insets.left); - }, - .onDeleted = - [](Tag tag) { - std::lock_guard lock(trackedMutex); - tracked.erase(tag); - }, - .afterBatch = - [] { - applyInsets( - gpui_safe_area::windowTopInset.load(), 0.0f, 0.0f, 0.0f); - }}); - - registerWindowInsetsObserver( - [](float top, float right, float bottom, float left) { - applyInsets(top, right, bottom, left); - }); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/modules/safe-area-context/package.json b/vendor/react-native-gpui/modules/safe-area-context/package.json deleted file mode 100644 index 370fab8afe..0000000000 --- a/vendor/react-native-gpui/modules/safe-area-context/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@react-native-gpui/safe-area-context", - "version": "5.10.0-alpha.0", - "description": "Adapter for react-native-safe-area-context (MIT): reports safe area insets for desktop windows, including windows with a custom title bar", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/streetwriters/react-native-gpui-modules.git", - "directory": "modules/safe-area-context" - }, - "homepage": "https://github.com/streetwriters/react-native-gpui-modules/tree/main/modules/safe-area-context#readme", - "bugs": { - "url": "https://github.com/streetwriters/react-native-gpui-modules/issues" - }, - "files": [ - "desktop", - "react-native.config.js", - "src", - "README.md", - "LICENSE", - "CHANGELOG.md", - "!**/*.test.js", - "!**/*.test.mjs", - "!**/*.test.ts", - "!**/*.test.cjs" - ], - "peerDependencies": { - "react-native": "0.87.x", - "react-native-safe-area-context": "5.10.x" - }, - "codegenConfig": { - "name": "GPUISafeAreaContextSpec", - "type": "modules", - "jsSrcsDir": "src" - }, - "publishConfig": { - "access": "public", - "tag": "latest" - } -} diff --git a/vendor/react-native-gpui/modules/safe-area-context/react-native.config.js b/vendor/react-native-gpui/modules/safe-area-context/react-native.config.js deleted file mode 100644 index 2ab45e0071..0000000000 --- a/vendor/react-native-gpui/modules/safe-area-context/react-native.config.js +++ /dev/null @@ -1,19 +0,0 @@ -module.exports = { - dependency: { - platforms: { - desktop: { - cmake: 'desktop', - cppProvider: 'create_gpui_safe_area_context_module', - componentCodegenPackage: 'react-native-safe-area-context', - componentDescriptors: [ - 'RNCSafeAreaProviderComponentDescriptor', - 'RNCSafeAreaViewComponentDescriptor', - ], - componentHeaders: [ - 'react/renderer/components/safeareacontext/ComponentDescriptors.h', - 'react/renderer/components/safeareacontext/RNCSafeAreaViewComponentDescriptor.h', - ], - }, - }, - }, -}; diff --git a/vendor/react-native-gpui/modules/safe-area-context/src/NativeSafeAreaContext.ts b/vendor/react-native-gpui/modules/safe-area-context/src/NativeSafeAreaContext.ts deleted file mode 100644 index 282ab56909..0000000000 --- a/vendor/react-native-gpui/modules/safe-area-context/src/NativeSafeAreaContext.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { CodegenTypes, TurboModule } from 'react-native'; -import { TurboModuleRegistry } from 'react-native'; - -export interface Spec extends TurboModule { - getConstants: () => { - initialWindowMetrics?: { - insets: { - top: CodegenTypes.Double; - right: CodegenTypes.Double; - bottom: CodegenTypes.Double; - left: CodegenTypes.Double; - }; - frame: { - x: CodegenTypes.Double; - y: CodegenTypes.Double; - width: CodegenTypes.Double; - height: CodegenTypes.Double; - }; - }; - }; -} - -export default TurboModuleRegistry.get('RNCSafeAreaContext'); diff --git a/vendor/react-native-gpui/modules/screens/CHANGELOG.md b/vendor/react-native-gpui/modules/screens/CHANGELOG.md deleted file mode 100644 index 937e62db35..0000000000 --- a/vendor/react-native-gpui/modules/screens/CHANGELOG.md +++ /dev/null @@ -1,20 +0,0 @@ -# Changelog - -All notable changes to `@react-native-gpui/screens` are listed here. Each version's section becomes the notes of its GitHub release. - -## Unreleased - -- Builds against gpui-fast `1ad3cc3`. - -## 4.28.0-alpha.2 - 2026-11-12 - -- Builds against gpui-fast `5392403`. - -## 4.28.0-alpha.1 - 2026-11-05 - -- Builds against gpui-fast `9e455ae`, which needs Rust 1.98 or newer. - -## 4.28.0-alpha.0 - 2026-11-01 - -- First release, for `react-native-screens` 4.28.x. -- Native stacks and screens on desktop, for React Navigation. diff --git a/vendor/react-native-gpui/modules/screens/LICENSE b/vendor/react-native-gpui/modules/screens/LICENSE deleted file mode 100644 index 149a0f8321..0000000000 --- a/vendor/react-native-gpui/modules/screens/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Streetwriters - -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/vendor/react-native-gpui/modules/screens/README.md b/vendor/react-native-gpui/modules/screens/README.md deleted file mode 100644 index e2f85bd5c2..0000000000 --- a/vendor/react-native-gpui/modules/screens/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# @react-native-gpui/screens - -Adapter for [`react-native-screens`](https://github.com/software-mansion/react-native-screens) (MIT): draws native stacks and screens, as used by React Navigation. - -Part of [react-native-gpui](https://github.com/streetwriters/react-native-gpui), React Native for macOS, Windows and Linux. - -## Install - -Install it next to `react-native-screens`: - -```sh -npm install react-native-screens@4.28.x @react-native-gpui/screens -``` - -Keep using `react-native-screens` as you do on iOS and Android; its JavaScript API is unchanged. Autolinking builds the desktop side when the app is built. - -## Documentation - -[Navigating between screens](docs/navigation.md) - -[Supported libraries](https://streetwriters.github.io/react-native-gpui/docs/supported-libraries) - -## License - -MIT. See [LICENSE](LICENSE). diff --git a/vendor/react-native-gpui/modules/screens/desktop/CMakeLists.txt b/vendor/react-native-gpui/modules/screens/desktop/CMakeLists.txt deleted file mode 100644 index 9b0d721758..0000000000 --- a/vendor/react-native-gpui/modules/screens/desktop/CMakeLists.txt +++ /dev/null @@ -1,30 +0,0 @@ -if(NOT RN_GPUI_PROJECT_ROOT) - message(FATAL_ERROR - "@react-native-gpui/screens was added by the platform; RN_GPUI_PROJECT_ROOT must be set by its build.rs") -endif() -rn_gpui_find_node_module(react-native-screens _screens_root) -set(_screens_common "${_screens_root}/common/cpp") -set(_screens_component_dir "${_screens_common}/react/renderer/components/rnscreens") -set(_screens_package_json "${_screens_root}/package.json") - -if(NOT EXISTS "${_screens_component_dir}/RNSScreenShadowNode.cpp" OR NOT EXISTS "${_screens_package_json}") - message(FATAL_ERROR "react-native-screens 4.28.x was not found at ${_screens_root}") -endif() - -file(READ "${_screens_package_json}" _screens_package_json_contents) -string(JSON _screens_version GET "${_screens_package_json_contents}" version) -if(NOT _screens_version MATCHES "^4\\.28\\.") - message(FATAL_ERROR "@react-native-gpui/screens supports react-native-screens 4.28.x, found ${_screens_version}") -endif() - -file(GLOB _screens_common_sources CONFIGURE_DEPENDS "${_screens_component_dir}/*.cpp") -set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_SOURCES ${_screens_common_sources}) -set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_INCLUDE_DIRS "${_screens_common}") -# The mount pipeline knows nothing about screens: this glue fills the header and -# screen fields of a mount op, and the platform compiles it only because the -# package is installed. -set_property(GLOBAL APPEND PROPERTY RN_GPUI_PACKAGE_MODULE_SOURCES - "${CMAKE_CURRENT_LIST_DIR}/cpp/GpuiScreensModule.cpp") -set_property(GLOBAL APPEND PROPERTY RN_GPUI_PACKAGE_MODULE_INSTALLERS screens) -set_property(GLOBAL APPEND PROPERTY RN_GPUI_PACKAGE_MODULE_INCLUDE_DIRS - "${_screens_common}") diff --git a/vendor/react-native-gpui/modules/screens/desktop/Cargo.toml b/vendor/react-native-gpui/modules/screens/desktop/Cargo.toml deleted file mode 100644 index 41064cdd6c..0000000000 --- a/vendor/react-native-gpui/modules/screens/desktop/Cargo.toml +++ /dev/null @@ -1,54 +0,0 @@ -[package] -name = "rn-gpui-screens" -version = "0.1.0" -edition = "2021" - -[dependencies] -react-native-gpui = "0.1" -rn-gpui-sys = "0.1" -gpui = "0.2" -serde_json = "1" -log = "0.4" - -[dev-dependencies] -# `TestNode` and `TreeView::for_test` are gated behind `test-driver`, and a -# dependency cannot enable another package's feature. It is a dev-dependency -# rather than a normal one so a build of the module never pays for it, and it only -# becomes usable because this crate is its own workspace root below. -react-native-gpui = { version = "0.1", features = ["test-driver"] } - -# Its own workspace root, deliberately. Cargo refuses to test a package that has -# dev-dependencies unless it is a workspace member, and core's workspace cannot -# hold it: a module resolves core by version and must not be a member of the -# checkout's workspace. A root with itself as the only member satisfies the rule -# without making the module part of anything else. -[workspace] - -# The checkout's shared dev profile (see core's `ReactGpui/Cargo.toml`): line tables -# only, no debug info for dependencies, which are optimized. Every workspace root -# builds into the one root `target/`, so a matching profile is also what lets them -# reuse each other's dependency builds instead of storing one copy each. -[profile.dev] -debug = "line-tables-only" -split-debuginfo = "packed" - -[profile.dev.package."*"] -debug = false -opt-level = 3 - -[profile.dev.package.rn-gpui-sys] -opt-level = 0 - -# This block has to live here because Cargo honours `[patch.crates-io]` only at a -# workspace root, and this crate is one. `npm run test:rust` regenerates it from -# core's manifest before running these tests and fails if it changed, so the gpui -# revision is never written down by hand — commit whatever the run rewrites. -[patch.crates-io] -# Managed by @react-native-gpui/cli autolink; do not edit between these markers. -react-native-gpui = { path = "../../../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui" } -rn-gpui-sys = { path = "../../../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-sys" } -rn-gpui-module = { path = "../../../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-module" } -rn-gpui-module-build = { path = "../../../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-module-build" } -gpui = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3" } -gpui_platform = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3" } -# End managed by autolink. diff --git a/vendor/react-native-gpui/modules/screens/desktop/build.rs b/vendor/react-native-gpui/modules/screens/desktop/build.rs deleted file mode 100644 index b40f68662d..0000000000 --- a/vendor/react-native-gpui/modules/screens/desktop/build.rs +++ /dev/null @@ -1,38 +0,0 @@ -//! Puts the C++ runtime's shared libraries on this crate's test binary rpath. -//! -//! `rn-gpui-screens`'s tests build gpui trees, which link `libjsi.dylib` and the -//! rest of the Node-API runtime. Core's `build.rs` emits -//! `cargo:rustc-link-arg=-Wl,-rpath,` for its own binary — the app — and that -//! flag is not inherited by a dependency's test binary, so the test process -//! aborted in dyld with `Library not loaded: @rpath/libjsi.dylib` before running a -//! single test. -//! -//! Core exports the directories it was given as `DEP_RN_GPUI_CORE_RPATHS`, which -//! is the same variable core's own `build.rs` reads. Re-emitting it here scopes -//! the flag to this crate's test binary, since `cargo:rustc-link-arg` without a -//! target suffix applies to the crate's own targets and not to the app that -//! depends on it. - -fn main() { - println!("cargo:rerun-if-env-changed=DEP_RN_GPUI_CORE_RPATHS"); - println!("cargo:rerun-if-changed=build.rs"); - - let Ok(dirs) = std::env::var("DEP_RN_GPUI_CORE_RPATHS") else { - return; - }; - let dirs = dirs - .split('|') - .filter(|dir| !dir.is_empty()) - .collect::>(); - if dirs.is_empty() { - return; - } - // MSVC and MinGW have no rpath, and the flag is rejected outright; Windows - // finds the DLLs through PATH, which the test runner already arranges. - if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { - return; - } - for dir in dirs { - println!("cargo:rustc-link-arg=-Wl,-rpath,{dir}"); - } -} diff --git a/vendor/react-native-gpui/modules/screens/desktop/cpp/GpuiScreensModule.cpp b/vendor/react-native-gpui/modules/screens/desktop/cpp/GpuiScreensModule.cpp deleted file mode 100644 index 31f198b876..0000000000 --- a/vendor/react-native-gpui/modules/screens/desktop/cpp/GpuiScreensModule.cpp +++ /dev/null @@ -1,77 +0,0 @@ - -#include "GpuiModules.h" - -#include -#include - -#include - -namespace rngpui { -namespace { - -using namespace facebook::react; - -std::string screenPropsJson( - const std::string& /*componentName*/, - const ShadowView& view) { - if (!view.props) { - return std::string("{}"); - } - auto props = std::dynamic_pointer_cast(view.props); - if (!props) { - return std::string("{}"); - } - folly::dynamic object = folly::dynamic::object; - object["activityState"] = props->activityState; - object["stackAnimation"] = toString(props->stackAnimation); - object["stackPresentation"] = toString(props->stackPresentation); - return folly::toJson(object); -} - -std::string headerConfigPropsJson( - const std::string& /*componentName*/, - const ShadowView& view) { - if (!view.props) { - return std::string("{}"); - } - auto props = std::dynamic_pointer_cast( - view.props); - if (!props) { - return std::string("{}"); - } - folly::dynamic object = folly::dynamic::object; - object["title"] = props->title; - object["backgroundColor"] = argb(props->backgroundColor); - object["titleColor"] = argb(props->titleColor); - object["tintColor"] = argb(props->color); - object["hidden"] = props->hidden; - object["hideBackButton"] = props->hideBackButton; - return folly::toJson(object); -} - -std::string headerSubviewPropsJson( - const std::string& /*componentName*/, - const ShadowView& view) { - if (!view.props) { - return std::string("{}"); - } - auto props = - std::dynamic_pointer_cast( - view.props); - if (!props) { - return std::string("{}"); - } - folly::dynamic object = folly::dynamic::object; - object["type"] = toString(props->type); - return folly::toJson(object); -} - -} // namespace - -void rn_gpui_install_screens_module() { - registerComponentProps("RNSScreen", screenPropsJson); - registerComponentProps("RNSScreenStackHeaderConfig", headerConfigPropsJson); - registerComponentProps("RNSScreenStackHeaderSubview", headerSubviewPropsJson); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/modules/screens/desktop/src/lib.rs b/vendor/react-native-gpui/modules/screens/desktop/src/lib.rs deleted file mode 100644 index 26209f4b81..0000000000 --- a/vendor/react-native-gpui/modules/screens/desktop/src/lib.rs +++ /dev/null @@ -1,29 +0,0 @@ -//! The screens module. -//! -//! Everything react-native-screens needs lives here: its props extraction in -//! `cpp/`, and its layout, painting and lifecycle in the modules below. Core is -//! told only what any library can say — a component name, a props reader, and a -//! set of generic hooks. -pub mod lifecycle; -pub mod props; -pub mod render; -pub mod stack; -pub mod state; -pub mod transition; -pub mod unsupported; - -/// Registers this module's renderers and observer. -/// -/// Autolink calls this from `ensure_linked()` while `main` starts, before any -/// `gpui::App` exists, so nothing here may touch the app. -pub fn rn_gpui_register() { - react_native_gpui::extensions::register_store_observer(std::sync::Arc::new( - stack::StackObserver, - )); - for (component, build) in render::RENDERED_COMPONENTS { - react_native_gpui::extensions::register_component_renderer( - *component, - std::sync::Arc::from(build()), - ); - } -} diff --git a/vendor/react-native-gpui/modules/screens/desktop/src/lifecycle.rs b/vendor/react-native-gpui/modules/screens/desktop/src/lifecycle.rs deleted file mode 100644 index 887ff23534..0000000000 --- a/vendor/react-native-gpui/modules/screens/desktop/src/lifecycle.rs +++ /dev/null @@ -1,80 +0,0 @@ -//! The lifecycle events a stack sends to its screens as they appear and leave. -//! -//! React Native exposes these as `topWillAppear`, `topAppear`, -//! `topWillDisappear` and `topDisappear`, in that order around a transition. -use gpui::App; -use react_native_gpui::extensions::StoreHandle; - -/// The events an activity-state change produces, in the order they fire. -pub fn lifecycle_events(previous: f32, next: f32) -> &'static [&'static str] { - match (previous < 1.0, previous >= 2.0, next < 1.0, next >= 2.0) { - (true, _, false, true) => &["topWillAppear", "topAppear"], - (true, _, false, false) => &["topWillAppear"], - (_, true, false, false) => &["topWillDisappear"], - (false, false, true, _) => &["topDisappear"], - (false, true, true, _) => &["topWillDisappear", "topDisappear"], - (false, false, false, true) => &["topAppear"], - _ => &[], - } -} - -/// Sends the "will" half of a transition: the outgoing screen then the incoming. -pub fn dispatch_will( - handle: &StoreHandle, - outgoing: Option, - incoming: Option, - cx: &mut App, -) { - for (tag, event) in [ - outgoing.map(|tag| (tag, "topWillDisappear")), - incoming.map(|tag| (tag, "topWillAppear")), - ] - .into_iter() - .flatten() - { - log::info!("[screens] tag={tag} lifecycle={event}"); - handle.dispatch_event(tag, event, &serde_json::json!({}), cx); - } -} - -/// Sends the "did" half: the outgoing screen then the incoming, and wakes -/// Fabric so the callbacks arrive before a later pop unmounts them. -pub fn dispatch_did( - handle: &StoreHandle, - outgoing: Option, - incoming: Option, - cx: &mut App, -) { - for (tag, event) in [ - outgoing.map(|tag| (tag, "topDisappear")), - incoming.map(|tag| (tag, "topAppear")), - ] - .into_iter() - .flatten() - { - log::info!("[screens] tag={tag} lifecycle={event}"); - handle.dispatch_event(tag, event, &serde_json::json!({}), cx); - } - // A timer can complete after the display-frame chain has gone idle, so the - // JavaScript that handles these events needs a render to arrive in. - handle.wake(cx); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn activity_state_edges_emit_lifecycle_in_order() { - assert_eq!(lifecycle_events(0.0, 1.0), &["topWillAppear"]); - assert_eq!(lifecycle_events(1.0, 2.0), &["topAppear"]); - assert_eq!(lifecycle_events(2.0, 1.0), &["topWillDisappear"]); - assert_eq!(lifecycle_events(1.0, 0.0), &["topDisappear"]); - assert_eq!(lifecycle_events(0.0, 2.0), &["topWillAppear", "topAppear"]); - assert_eq!( - lifecycle_events(2.0, 0.0), - &["topWillDisappear", "topDisappear"] - ); - assert!(lifecycle_events(1.0, 1.0).is_empty()); - } -} diff --git a/vendor/react-native-gpui/modules/screens/desktop/src/props.rs b/vendor/react-native-gpui/modules/screens/desktop/src/props.rs deleted file mode 100644 index b8dbf124f4..0000000000 --- a/vendor/react-native-gpui/modules/screens/desktop/src/props.rs +++ /dev/null @@ -1,177 +0,0 @@ -//! Typed readers over the JSON this module's C++ half produced. -//! -//! A missing key reads as today's zero value, so a component that has not been -//! given the prop yet behaves the way it did before it arrived. -use react_native_gpui::extensions::ComponentNode; - -/// A number, or 0 when absent. -fn number(node: &ComponentNode, key: &str) -> f64 { - node.props - .get(key) - .and_then(|value| value.as_f64()) - .unwrap_or(0.0) -} - -/// A number as `f32`, or 0 when absent. -fn number_f32(node: &ComponentNode, key: &str) -> f32 { - number(node, key) as f32 -} - -/// A string, borrowed from the props. -fn string<'a>(node: &'a ComponentNode, key: &str) -> &'a str { - node.props - .get(key) - .and_then(|value| value.as_str()) - .unwrap_or("") -} - -/// A boolean, false when absent. -fn boolean(node: &ComponentNode, key: &str) -> bool { - node.props - .get(key) - .and_then(|value| value.as_bool()) - .unwrap_or(false) -} - -/// A colour as 0xAARRGGBB, 0 when unset. -fn color(node: &ComponentNode, key: &str) -> u32 { - number(node, key) as u32 -} - -/// An `RNSScreen`'s activity state. 0 is detached, 1 is transitioning, 2 is -/// fully on screen. -pub fn activity_state(node: &ComponentNode) -> f32 { - number_f32(node, "activityState") -} - -/// An `RNSScreen`'s `stackAnimation`. -pub fn stack_animation(node: &ComponentNode) -> &str { - string(node, "stackAnimation") -} - -/// An `RNSScreen`'s `stackPresentation`. -pub fn stack_presentation(node: &ComponentNode) -> &str { - string(node, "stackPresentation") -} - -/// Whether a presentation paints its own card over the one underneath. -pub fn is_modal_presentation(node: &ComponentNode) -> bool { - matches!( - stack_presentation(node), - "modal" | "transparentModal" | "containedModal" | "formSheet" - ) -} - -/// Whether that card lets the screen underneath show through. -pub fn is_transparent_presentation(node: &ComponentNode) -> bool { - stack_presentation(node) == "transparentModal" -} - -/// A header config's title. -pub fn header_title(node: &ComponentNode) -> &str { - string(node, "title") -} - -/// A header config's background colour. -pub fn header_background_color(node: &ComponentNode) -> u32 { - color(node, "backgroundColor") -} - -/// A header config's title colour. -pub fn header_title_color(node: &ComponentNode) -> u32 { - color(node, "titleColor") -} - -/// A header config's tint colour, used for the back button. -pub fn header_tint_color(node: &ComponentNode) -> u32 { - color(node, "tintColor") -} - -/// Whether a header config hides the whole bar. -pub fn header_hidden(node: &ComponentNode) -> bool { - boolean(node, "hidden") -} - -/// Whether a header config hides only the back button. -pub fn header_hide_back(node: &ComponentNode) -> bool { - boolean(node, "hideBackButton") -} - -/// A header subview's placement: `left`, `right`, `center`, `title` or a Yoga x. -pub fn subview_type(node: &ComponentNode) -> &str { - string(node, "type") -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::Arc; - - fn node(json: serde_json::Value) -> ComponentNode { - ComponentNode { - component: "RNSScreen".to_string(), - tag: 1, - frame: rn_gpui_sys::ffi::RectF::default(), - scale: (1.0, 1.0), - props: Arc::new(json), - parent: None, - children: Vec::new(), - } - } - - #[test] - fn a_missing_key_reads_as_the_zero_value() { - let empty = node(serde_json::json!({})); - assert_eq!(activity_state(&empty), 0.0); - assert_eq!(stack_animation(&empty), ""); - assert_eq!(stack_presentation(&empty), ""); - assert_eq!(header_title(&empty), ""); - assert_eq!(header_background_color(&empty), 0); - assert!(!header_hidden(&empty)); - assert!(!header_hide_back(&empty)); - assert!(!is_modal_presentation(&empty)); - } - - #[test] - fn reads_the_fields_the_props_half_writes() { - let screen = node(serde_json::json!({ - "activityState": 2, - "stackAnimation": "slide_from_right", - "stackPresentation": "transparentModal", - })); - assert_eq!(activity_state(&screen), 2.0); - assert_eq!(stack_animation(&screen), "slide_from_right"); - assert!(is_modal_presentation(&screen)); - assert!(is_transparent_presentation(&screen)); - - let header = node(serde_json::json!({ - "title": "Home", - "backgroundColor": 0xff112233u32, - "titleColor": 0xffaabbccu32, - "tintColor": 0xff445566u32, - "hidden": true, - "hideBackButton": true, - })); - assert_eq!(header_title(&header), "Home"); - assert_eq!(header_background_color(&header), 0xff112233); - assert_eq!(header_title_color(&header), 0xffaabbcc); - assert_eq!(header_tint_color(&header), 0xff445566); - assert!(header_hidden(&header)); - assert!(header_hide_back(&header)); - - let subview = node(serde_json::json!({"type": "right"})); - assert_eq!(subview_type(&subview), "right"); - } - - #[test] - fn only_the_modal_presentations_count_as_modal() { - for presentation in ["modal", "transparentModal", "containedModal", "formSheet"] { - let node = node(serde_json::json!({"stackPresentation": presentation})); - assert!(is_modal_presentation(&node), "{presentation}"); - } - for presentation in ["push", "card", ""] { - let node = node(serde_json::json!({"stackPresentation": presentation})); - assert!(!is_modal_presentation(&node), "{presentation}"); - } - } -} diff --git a/vendor/react-native-gpui/modules/screens/desktop/src/render.rs b/vendor/react-native-gpui/modules/screens/desktop/src/render.rs deleted file mode 100644 index 0bc0d1b2d8..0000000000 --- a/vendor/react-native-gpui/modules/screens/desktop/src/render.rs +++ /dev/null @@ -1,829 +0,0 @@ -//! Painting react-native-screens through the generic renderer hooks. -//! -//! Core builds a box, a background and an accessibility node for every -//! component. What is screens-specific — which screen is on top, where a header -//! subview sits, whether a card is showing — is decided here, from the props this -//! module's C++ half produced and a read-only view of the tree. -use crate::props; -use crate::stack::{ - CONTENT_WRAPPER, FULL_WINDOW_OVERLAY, HEADER_CONFIG, HEADER_SUBVIEW, MODAL_SCREEN, SCREEN, - STACK, -}; -use gpui::{div, prelude::*, AnyElement, App, MouseButton, SharedString, Window}; -use react_native_gpui::extensions::{ - store_handle, ComponentNode, ComponentRenderer, Decoration, Portal, StoreHandle, TreeView, -}; -use rn_gpui_sys::ffi::RectF; - -/// The header bar's height, which the content wrapper is inset by. -pub const HEADER_HEIGHT: f32 = 56.0; - -/// A screen inside a stack. -pub struct ScreenRenderer; - -impl ComponentRenderer for ScreenRenderer { - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } - - fn children( - &self, - node: &ComponentNode, - children: Vec, - _window: &mut Window, - _cx: &mut App, - ) -> Vec { - if !props::is_modal_presentation(node) { - return children; - } - let material = props::is_transparent_presentation(node); - // The frame is in unscaled coordinates and the element this returns is - // painted scaled, so the sheet has to be scaled to land where the card - // it covers does. The old code did the same with `scale_x`/`scale_y`. - let (scale_x, scale_y) = node.scale; - let width = (node.frame.w - SHEET_MARGIN).clamp(0.0, SHEET_MAX_WIDTH) * scale_x; - let height = (node.frame.h - SHEET_MARGIN).clamp(0.0, SHEET_MAX_HEIGHT) * scale_y; - let left = ((node.frame.w * scale_x - width) * 0.5).max(0.0); - let top = ((node.frame.h * scale_y - height) * 0.5).max(0.0); - let mut layers = Vec::with_capacity(2); - if !material { - layers.push( - div() - .absolute() - .inset_0() - .size_full() - .bg(argb(0x80000000)) - .into_any_element(), - ); - } - layers.push( - div() - .absolute() - .left(gpui::px(left)) - .top(gpui::px(top)) - .w(gpui::px(width)) - .h(gpui::px(height)) - .overflow_hidden() - .bg(argb(if material { 0x00000000 } else { 0xff171923 })) - .children(children) - .into_any_element(), - ); - layers - } - - fn hides_subtree(&self, node: &ComponentNode, tree: &TreeView) -> bool { - if props::activity_state(node) > 0.0 { - return false; - } - if tree - .transition(node.tag) - .is_some_and(|state| state.progress < 1.0) - { - return false; - } - !covered_by_modal_sibling(node, tree) - } - - fn decorate(&self, node: &ComponentNode, tree: &TreeView) -> Decoration { - if props::activity_state(node) > 0.0 { - return Decoration::default(); - } - let transitioning = tree - .transition(node.tag) - .is_some_and(|state| state.progress < 1.0); - let visible_under_modal = covered_by_modal_sibling(node, tree); - if !transitioning && !visible_under_modal { - return Decoration { - display: Some(false), - ..Decoration::default() - }; - } - Decoration::default() - } -} - -/// Whether a later sibling in the same stack is an active modal presentation. -fn covered_by_modal_sibling(node: &ComponentNode, tree: &TreeView) -> bool { - let Some(parent) = node.parent else { - return false; - }; - let siblings = tree.children(parent); - let Some(position) = siblings.iter().position(|tag| *tag == node.tag) else { - return false; - }; - siblings - .into_iter() - .skip(position + 1) - .filter_map(|tag| tree.node(tag)) - .any(|sibling| { - sibling.component == SCREEN - && props::activity_state(&sibling) > 0.0 - && props::is_modal_presentation(&sibling) - }) -} - -/// The stack itself: it clips, and it owns the Escape gesture. -pub struct StackRenderer; - -impl ComponentRenderer for StackRenderer { - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } - - fn decorate(&self, _node: &ComponentNode, _tree: &TreeView) -> Decoration { - Decoration { - clip: true, - ..Decoration::default() - } - } - - fn handles_keys(&self, _node: &ComponentNode) -> bool { - true - } - - fn on_key_down( - &self, - node: &ComponentNode, - key: &str, - tree: &TreeView, - handle: &react_native_gpui::extensions::StoreHandle, - window: &mut Window, - cx: &mut App, - ) -> bool { - if key != "escape" { - return false; - } - if has_screen_ancestor(node, tree) { - return false; - } - let screens: Vec = tree - .children(node.tag) - .into_iter() - .filter(|tag| { - tree.is_live(*tag) && tree.node(*tag).is_some_and(|n| n.component == SCREEN) - }) - .collect(); - let Some(top) = screens.last().copied() else { - return false; - }; - if crate::state::with(|state| state.native_dismiss_pending.is_some()) { - return true; - } - dismiss_top(top, node.tag, tree, handle, window, cx); - true - } -} - -/// Whether any ancestor of `node` is a screen, i.e. this stack is nested. -fn has_screen_ancestor(node: &ComponentNode, tree: &TreeView) -> bool { - tree.ancestors(node.tag) - .into_iter() - .filter_map(|tag| tree.node(tag)) - .any(|ancestor| ancestor.component == SCREEN) -} - -/// The header bar: a background, a title and a back button. -pub struct HeaderConfigRenderer; - -impl ComponentRenderer for HeaderConfigRenderer { - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } - - fn layout_frame(&self, node: &ComponentNode, tree: &TreeView) -> Option { - let mut frame = node.frame; - frame.y += tree.window_top_inset(); - frame.h = if props::header_hidden(node) || !is_top_header(node, tree) { - 0.0 - } else { - HEADER_HEIGHT - }; - Some(frame) - } - - fn hides_subtree(&self, node: &ComponentNode, tree: &TreeView) -> bool { - props::header_hidden(node) || !is_top_header(node, tree) - } - - fn decorate(&self, node: &ComponentNode, tree: &TreeView) -> Decoration { - let top = is_top_header(node, tree); - let shown = should_show_back(node, tree); - crate::state::set_header_facts( - node.tag, - top, - shown, - has_title_subview(node, tree), - node.parent, - ); - if props::header_hidden(node) || !top { - return Decoration { - display: Some(false), - ..Decoration::default() - }; - } - let background = first_nonzero(props::header_background_color(node), 0xff171923); - Decoration { - background: Some(background), - ..Decoration::default() - } - } - - fn depends_on_window_insets(&self) -> bool { - true - } - - fn content( - &self, - node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - if props::header_hidden(node) || !crate::state::header_is_top(node.tag) { - return None; - } - // React Native declares `onHeaderBackButtonClicked` on the screen, so - // the config's parent is the tag that has a listener for it. - let Some(screen_tag) = crate::state::header_screen(node.tag) else { - return None; - }; - let title_color = first_nonzero(props::header_title_color(node), 0xffffffff); - let mut bar = div() - .absolute() - .top_0() - .left_0() - .size_full() - .flex() - .items_center() - .justify_center() - .text_color(argb(title_color)) - .text_size(gpui::px(18.0)); - if !crate::state::header_has_title_subview(node.tag) { - bar = bar.child(SharedString::from(props::header_title(node).to_string())); - } - if crate::state::header_shows_back(node.tag) { - bar = bar.child( - div() - .absolute() - .left_0() - .top_0() - .h(gpui::px(HEADER_HEIGHT)) - .w(gpui::px(HEADER_HEIGHT)) - .flex() - .items_center() - .justify_center() - .text_color(argb(first_nonzero( - props::header_tint_color(node), - 0xffffffff, - ))) - .text_size(gpui::px(30.0)) - .cursor_pointer() - .child("‹") - .on_mouse_down(MouseButton::Left, move |_event, window, cx| { - if let Some(handle) = store_handle(cx) { - handle.dispatch_event( - screen_tag, - "headerBackButtonClicked", - &serde_json::json!({}), - cx, - ); - handle.request_frame(window); - } - cx.stop_propagation(); - }), - ); - } - Some(bar.into_any_element()) - } -} - -/// Escape dismisses the top screen the way a native gesture would. -/// -/// The card runs its exit animation, the screen gets the `will` pair, and only -/// when the animation ends does it get the final progress, the `did` pair and -/// `topDismissed`. `native_dismiss_pending` tells the stack observer that this -/// dismissal already ran its animation, so it must not run a second one. -fn dismiss_top( - top: i32, - stack: i32, - tree: &TreeView, - handle: &StoreHandle, - window: &mut Window, - cx: &mut App, -) { - crate::state::with(|state| state.native_dismiss_pending = Some(top)); - let incoming = previous_screen(top, stack, tree); - crate::lifecycle::dispatch_will(handle, Some(top), incoming, cx); - // The animation belongs to the screen being dismissed, not to the stack: a - // stack carries no `stackAnimation` prop of its own. A dismissal plays the - // entry mirrored, which is what `reverse` is for. - let animation = tree - .node(top) - .map(|node| props::stack_animation(&node).to_string()) - .unwrap_or_default(); - let mode = crate::transition::transition_mode(&animation) - .filter(|_| tree.animations_enabled()) - .map(crate::transition::TransitionMode::reverse); - let duration = mode.map(|mode| mode.duration()); - if let Some(mode) = mode { - let exit = crate::transition::transition(mode, crate::transition::Role::Exit, 1.0); - crate::state::with(|state| { - state.roles.insert(top, (crate::state::Role::Exit, 1.0)); - }); - handle.start_transition(top, exit, cx); - // The card underneath comes back to rest from wherever the push left - // it. Without this it stays offset for the whole dismissal. - if let Some(incoming) = incoming { - handle.clear_transition(incoming, cx); - } - handle.request_frame(window); - } - let finish = move |handle: &StoreHandle, cx: &mut App| { - handle.dispatch_event( - top, - "topTransitionProgress", - &serde_json::json!({"progress": 1, "closing": 1, "goingForward": 0}), - cx, - ); - crate::lifecycle::dispatch_did(handle, Some(top), incoming, cx); - handle.dispatch_event( - top, - "topDismissed", - &serde_json::json!({ "dismissCount": 1 }), - cx, - ); - }; - match duration { - Some(duration) => { - let handle = handle.clone(); - handle.after(duration, cx, move |handle, cx| finish(handle, cx)); - } - None => finish(handle, cx), - } -} - -/// A Fabric colour as GPUI sees it, alpha included. -fn argb(color: u32) -> gpui::Hsla { - let alpha = color >> 24; - gpui::rgba((color << 8) | alpha).into() -} - -fn first_nonzero(value: u32, fallback: u32) -> u32 { - if value == 0 { - fallback - } else { - value - } -} - -/// Whether the screen has a previous live screen in its stack to go back to. -fn should_show_back(node: &ComponentNode, tree: &TreeView) -> bool { - if props::header_hide_back(node) { - return false; - } - let Some(screen) = node.parent else { - return false; - }; - let Some(stack) = stack_of(screen, tree) else { - return false; - }; - let screens: Vec = tree - .children(stack) - .into_iter() - .filter(|tag| tree.is_live(*tag) && tree.node(*tag).is_some_and(|n| n.component == SCREEN)) - .collect(); - screens - .iter() - .position(|tag| *tag == screen) - .is_some_and(|position| position > 0) -} - -/// Whether this header belongs to the screen currently on top of its stack. -fn is_top_header(node: &ComponentNode, tree: &TreeView) -> bool { - let Some(parent) = node.parent else { - return true; - }; - let Some(stack) = stack_of(parent, tree) else { - return true; - }; - let screens: Vec = tree - .children(stack) - .into_iter() - .filter(|tag| tree.node(*tag).is_some_and(|n| n.component == SCREEN)) - .collect(); - let is_last = screens.last().copied() == Some(parent); - // A screen that is leaving keeps its header while its transition runs, so - // the header does not blink out before the card has finished moving. An - // entry transition is never cleared once it ends, so only a running one - // counts: otherwise the first screen ever pushed keeps its header for good. - is_last - || tree - .transition(parent) - .is_some_and(|state| state.progress < 1.0) -} - -/// Whether the header config carries a subview that paints the title. -/// -/// React Navigation puts a custom title in a `title` subview, and a centred one -/// in a `center` subview; either way that subview paints the title, so core must -/// not paint a second copy. -fn has_title_subview(config: &ComponentNode, tree: &TreeView) -> bool { - tree.children(config.tag) - .into_iter() - .filter_map(|tag| tree.node(tag)) - .any(|child| { - child.component == HEADER_SUBVIEW - && matches!(props::subview_type(&child), "title" | "center") - }) -} - -/// The live screen directly below `top` in its stack, if any. -fn previous_screen(top: i32, stack: i32, tree: &TreeView) -> Option { - let screens: Vec = tree - .children(stack) - .into_iter() - .filter(|tag| tree.is_live(*tag) && tree.node(*tag).is_some_and(|n| n.component == SCREEN)) - .collect(); - let index = screens.iter().position(|tag| *tag == top)?; - index.checked_sub(1).and_then(|i| screens.get(i)).copied() -} - -/// The stack a screen sits in, walking up past intermediate containers. -fn stack_of(screen: i32, tree: &TreeView) -> Option { - tree.ancestors(screen) - .into_iter() - .find(|tag| tree.node(*tag).is_some_and(|n| n.component == STACK)) -} - -/// A header subview: positioned by its declared type. -pub struct HeaderSubviewRenderer; - -impl ComponentRenderer for HeaderSubviewRenderer { - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } - - fn layout_frame(&self, node: &ComponentNode, tree: &TreeView) -> Option { - let mut frame = node.frame; - let Some(config) = node.parent else { - return Some(frame); - }; - let container_width = tree - .node(config) - .map(|config| config.frame.w) - .unwrap_or(frame.w); - let tallest = tree - .children(node.tag) - .into_iter() - .filter_map(|tag| tree.node(tag)) - .fold(0.0f32, |height, child| height.max(child.frame.h)); - frame.x = match props::subview_type(node) { - "right" => container_width - frame.w - 12.0, - "center" | "title" => (container_width - frame.w) / 2.0, - "left" => 12.0, - _ => frame.x, - }; - frame.y = ((HEADER_HEIGHT - tallest).max(0.0)) / 2.0; - Some(frame) - } -} - -/// A screen's content area, inset by the header when one is showing. -pub struct ContentWrapperRenderer; - -impl ComponentRenderer for ContentWrapperRenderer { - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } - - fn layout_frame(&self, node: &ComponentNode, tree: &TreeView) -> Option { - let Some(screen) = node.parent else { - return None; - }; - let mut frame = node.frame; - // Only a header that is actually showing takes space. When it is hidden - // the C++ half already gave the wrapper the whole screen, so the Yoga - // frame is the answer and any adjustment here would move it twice. - if !header_hidden(screen, tree) { - frame.y += HEADER_HEIGHT; - frame.h = (frame.h - HEADER_HEIGHT).max(0.0); - } - Some(frame) - } -} - -/// Whether a screen's header config is hidden, whether or not it exists. -fn header_hidden(screen: i32, tree: &TreeView) -> bool { - tree.children(screen) - .into_iter() - .filter_map(|tag| tree.node(tag)) - .find(|node| node.component == HEADER_CONFIG) - .is_some_and(|config| props::header_hidden(&config)) -} - -/// The gap a modal sheet leaves around itself, and the size it is capped at. -const SHEET_MARGIN: f32 = 48.0; -const SHEET_MAX_WIDTH: f32 = 760.0; -const SHEET_MAX_HEIGHT: f32 = 640.0; - -/// A modal presentation. It paints like a screen; the difference is that the -/// card underneath stays visible. -pub struct ModalScreenRenderer; - -impl ComponentRenderer for ModalScreenRenderer { - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } -} - -/// A full-window overlay paints over the whole window, not inside the tree. -pub struct FullWindowOverlayRenderer; - -impl ComponentRenderer for FullWindowOverlayRenderer { - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } - - fn portal(&self, _props: &serde_json::Value) -> Option { - Some(Portal { - visible: true, - close_request_event: None, - }) - } -} - -/// Every component name this module paints, and how to build its renderer. -pub const RENDERED_COMPONENTS: &[(&str, fn() -> Box)] = &[ - (STACK, || Box::new(StackRenderer)), - (SCREEN, || Box::new(ScreenRenderer)), - (MODAL_SCREEN, || Box::new(ModalScreenRenderer)), - (HEADER_CONFIG, || Box::new(HeaderConfigRenderer)), - (HEADER_SUBVIEW, || Box::new(HeaderSubviewRenderer)), - (CONTENT_WRAPPER, || Box::new(ContentWrapperRenderer)), - (FULL_WINDOW_OVERLAY, || Box::new(FullWindowOverlayRenderer)), -]; - -#[cfg(test)] -mod tests { - use super::*; - use crate::state; - use std::sync::Arc; - - /// Builds a node with the props this module's C++ half would have produced. - fn node(component: &str, tag: i32, props: serde_json::Value) -> ComponentNode { - ComponentNode { - component: component.to_string(), - tag, - frame: RectF::default(), - scale: (1.0, 1.0), - props: Arc::new(props), - parent: None, - children: Vec::new(), - } - } - - fn frame(x: f32, y: f32, w: f32, h: f32) -> RectF { - RectF { x, y, w, h } - } - - /// A tree built from plain values, matching what core would hand a hook. - fn tree( - nodes: Vec, - edges: &[(i32, i32)], - top_inset: f32, - ) -> TreeView<'static> { - TreeView::for_test(nodes, edges, top_inset) - } - - fn entry( - tag: i32, - component: &'static str, - frame: RectF, - props: serde_json::Value, - ) -> react_native_gpui::extensions::TestNode { - react_native_gpui::extensions::TestNode { - tag, - component: component.to_string(), - frame, - scale: (1.0, 1.0), - props, - } - } - - /// A stack with one screen, its header config and its content wrapper. - /// - /// `header` is the header config's props and `content_height` the wrapper's - /// Yoga height, which the C++ half computes for the whole screen. - fn stack_with_header( - header: serde_json::Value, - content_height: f32, - ) -> (TreeView<'static>, i32, i32) { - let nodes = vec![ - entry( - 1, - STACK, - frame(0.0, 0.0, 400.0, 600.0), - serde_json::json!({}), - ), - entry( - 2, - SCREEN, - frame(0.0, 0.0, 400.0, 600.0), - serde_json::json!({"activityState": 2, "stackPresentation": "card"}), - ), - entry(3, HEADER_CONFIG, frame(0.0, 0.0, 400.0, 56.0), header), - entry( - 4, - CONTENT_WRAPPER, - frame(0.0, 0.0, 400.0, content_height), - serde_json::json!({}), - ), - ]; - let edges = [(1, 2), (2, 3), (2, 4)]; - (tree(nodes, &edges, 0.0), 3, 4) - } - - #[test] - fn a_visible_header_pushes_the_content_down_by_its_height() { - // Yoga gives the wrapper the whole screen; a visible header takes the - // top 56 px of it, so the content starts below the bar. - let (tree, _, wrapper) = stack_with_header(serde_json::json!({"title": "Home"}), 600.0); - let node = tree.node(wrapper).expect("wrapper is mounted"); - let laid_out = ContentWrapperRenderer - .layout_frame(&node, &tree) - .expect("the wrapper is laid out"); - assert_eq!(laid_out.y, HEADER_HEIGHT); - assert_eq!(laid_out.h, 600.0 - HEADER_HEIGHT); - } - - #[test] - fn a_hidden_header_leaves_the_content_where_yoga_put_it() { - // The C++ half gives a hidden-header screen's wrapper the full height, - // so any adjustment here would move the content a second time: the - // reported bug was content sitting 56 px above the top of the window. - let (tree, _, wrapper) = - stack_with_header(serde_json::json!({"title": "Home", "hidden": true}), 600.0); - let node = tree.node(wrapper).expect("wrapper is mounted"); - let laid_out = ContentWrapperRenderer - .layout_frame(&node, &tree) - .expect("the wrapper is laid out"); - assert_eq!(laid_out.y, 0.0); - assert_eq!(laid_out.h, 600.0); - } - - #[test] - fn the_header_sits_below_the_window_inset_and_is_one_bar_tall() { - let (tree, header, _) = stack_with_header(serde_json::json!({"title": "Home"}), 600.0); - // A window whose title bar takes 28 px: the bar must start below it. - let tree = tree_with_inset(&tree, 28.0); - let node = tree.node(header).expect("header is mounted"); - let laid_out = HeaderConfigRenderer - .layout_frame(&node, &tree) - .expect("the header is laid out"); - assert_eq!(laid_out.y, 28.0); - assert_eq!(laid_out.h, HEADER_HEIGHT); - } - - #[test] - fn a_hidden_header_takes_no_height_and_paints_nothing() { - let (tree, header, _) = - stack_with_header(serde_json::json!({"title": "Home", "hidden": true}), 600.0); - let node = tree.node(header).expect("header is mounted"); - let laid_out = HeaderConfigRenderer - .layout_frame(&node, &tree) - .expect("the header is laid out"); - assert_eq!(laid_out.h, 0.0); - assert!(HeaderConfigRenderer.hides_subtree(&node, &tree)); - assert_eq!( - HeaderConfigRenderer.decorate(&node, &tree).display, - Some(false) - ); - } - - /// A header carrying a `title` or `center` subview must not paint a second - /// title of its own: the subview is the title. - #[test] - fn a_title_subview_suppresses_the_headers_own_title() { - for subview_type in ["title", "center"] { - let nodes = vec![ - entry( - 1, - STACK, - frame(0.0, 0.0, 400.0, 600.0), - serde_json::json!({}), - ), - entry( - 2, - SCREEN, - frame(0.0, 0.0, 400.0, 600.0), - serde_json::json!({"activityState": 2, "stackPresentation": "card"}), - ), - entry( - 3, - HEADER_CONFIG, - frame(0.0, 0.0, 400.0, 56.0), - serde_json::json!({"title": "Details 1"}), - ), - entry( - 4, - HEADER_SUBVIEW, - frame(0.0, 0.0, 80.0, 20.0), - serde_json::json!({ "type": subview_type }), - ), - ]; - let edges = [(1, 2), (2, 3), (3, 4)]; - let tree = tree(nodes, &edges, 0.0); - let config = tree.node(3).expect("header config is mounted"); - assert!( - has_title_subview(&config, &tree), - "a {subview_type} subview paints the title" - ); - } - } - - #[test] - fn a_header_without_a_title_subview_paints_its_title() { - let (tree, header, _) = stack_with_header(serde_json::json!({"title": "Home"}), 600.0); - let node = tree.node(header).expect("header is mounted"); - assert!(!has_title_subview(&node, &tree)); - } - - #[test] - fn the_header_paints_the_colours_react_native_asked_for() { - let (tree, header, _) = stack_with_header( - serde_json::json!({ - "title": "Home", - "backgroundColor": 0xff203040u32, - }), - 600.0, - ); - let node = tree.node(header).expect("header is mounted"); - let decoration = HeaderConfigRenderer.decorate(&node, &tree); - assert_eq!(decoration.background, Some(0xff203040)); - assert_ne!(decoration.display, Some(false)); - } - - #[test] - fn a_header_without_a_background_falls_back_to_the_default() { - let (tree, header, _) = stack_with_header(serde_json::json!({"title": "Home"}), 600.0); - let node = tree.node(header).expect("header is mounted"); - assert_eq!( - HeaderConfigRenderer.decorate(&node, &tree).background, - Some(0xff171923) - ); - } - - /// The same tree as `stack_with_header` but with a window inset. - fn tree_with_inset(source: &TreeView<'_>, inset: f32) -> TreeView<'static> { - let mut nodes: Vec = Vec::new(); - let mut edges = Vec::new(); - for tag in [1, 2, 3, 4] { - let node = source.node(tag).expect("node is mounted"); - nodes.push(react_native_gpui::extensions::TestNode { - tag, - component: node.component, - frame: node.frame, - scale: node.scale, - props: (*node.props).clone(), - }); - if let Some(parent) = node.parent { - edges.push((parent, tag)); - } - } - tree(nodes, &edges, inset) - } -} diff --git a/vendor/react-native-gpui/modules/screens/desktop/src/stack.rs b/vendor/react-native-gpui/modules/screens/desktop/src/stack.rs deleted file mode 100644 index 8e76165ef4..0000000000 --- a/vendor/react-native-gpui/modules/screens/desktop/src/stack.rs +++ /dev/null @@ -1,396 +0,0 @@ -//! The stack observer: everything react-native-screens does between a mount -//! batch and a paint. -//! -//! Core tells an observer about a batch before it applies it, about each insert -//! and removal as it applies them, and about the batch once it is done. All the -//! navigation decisions — which stack is nested, which card is leaving, when a -//! lifecycle event fires, when a card is kept alive for its exit — are made here -//! and remembered in `state`. -use crate::props; -use crate::state::{self, PopPlan, Role}; -use crate::transition::{self, Role as TransitionRole}; -use react_native_gpui::extensions::{ - BatchOpKind, BatchView, ComponentNode, StoreHandle, StoreObserver, TreeView, -}; -use std::collections::HashSet; - -/// The component names this module owns. -pub const STACK: &str = "RNSScreenStack"; -pub const SCREEN: &str = "RNSScreen"; -pub const HEADER_CONFIG: &str = "RNSScreenStackHeaderConfig"; -pub const HEADER_SUBVIEW: &str = "RNSScreenStackHeaderSubview"; -pub const CONTENT_WRAPPER: &str = "RNSScreenContentWrapper"; -pub const MODAL_SCREEN: &str = "RNSModalScreen"; -pub const FULL_WINDOW_OVERLAY: &str = "RNSFullWindowOverlay"; - -/// Watches the batch and drives the stack. -pub struct StackObserver; - -impl StoreObserver for StackObserver { - fn before_batch( - &self, - batch: &BatchView, - tree: &TreeView, - handle: &StoreHandle, - cx: &mut gpui::App, - ) { - let nested = nested_stacks(batch, tree); - if std::env::var_os("RN_GPUI_DEBUG_SCREENS").is_some() && !nested.is_empty() { - log::info!("[screens] nested stack tags={nested:?}"); - } - let plans = pop_plans(batch, tree, &nested, handle, cx); - for (tag, plan) in &plans { - if plan.retain { - handle.retain_subtree(*tag); - } - } - state::with(|state| { - state.nested_stacks = nested; - state.pop_plans = plans; - }); - } - - fn on_mount(&self, node: &ComponentNode, _handle: &StoreHandle, _cx: &mut gpui::App) { - if node.component == FULL_WINDOW_OVERLAY { - log::info!( - "[screens] full window overlay created tag={} frame={}x{}", - node.tag, - node.frame.w, - node.frame.h - ); - } else if crate::unsupported::unsupported_component(&node.component) { - log::error!( - "[screens] component {} is not implemented on gpui", - node.component - ); - } - } - - fn on_insert( - &self, - child: &ComponentNode, - parent: i32, - previous_children: &[i32], - tree: &TreeView, - handle: &StoreHandle, - cx: &mut gpui::App, - ) { - if child.component != SCREEN || !is_outer_stack(parent) { - return; - } - let animation = props::stack_animation(child).to_string(); - let presentation = props::stack_presentation(child).to_string(); - log::info!( - "[screens] screen inserted tag={} animation={} presentation={} reduce_motion={}", - child.tag, - animation, - presentation, - !tree.animations_enabled() - ); - let previous_top = previous_children - .iter() - .rev() - .copied() - .find(|tag| tree.node(*tag).is_some_and(|node| node.component == SCREEN)); - let mode = transition::transition_mode(&animation).filter(|_| tree.animations_enabled()); - if let Some(mode) = mode { - log::info!( - "[screens] push transition incoming={} outgoing={:?} animation={} mode={mode:?}", - child.tag, - previous_top, - animation - ); - if presentation == "push" { - if let Some(previous) = previous_top { - let distance = transition::PARALLAX_DISTANCE; - handle.start_transition( - previous, - transition::transition(mode, TransitionRole::Exit, distance), - cx, - ); - state::with(|state| { - state.roles.insert(previous, (Role::Exit, distance)); - }); - } - } - handle.start_transition( - child.tag, - transition::transition(mode, TransitionRole::Enter, 1.0), - cx, - ); - state::with(|state| { - state.roles.insert(child.tag, (Role::Enter, 1.0)); - }); - } - crate::lifecycle::dispatch_will(handle, previous_top, Some(child.tag), cx); - match mode { - Some(mode) => { - let outgoing = previous_top; - let incoming = Some(child.tag); - let handle = handle.clone(); - handle.after(mode.duration(), cx, move |handle, cx| { - if let Some(outgoing) = outgoing { - handle.clear_transition(outgoing, cx); - } - crate::lifecycle::dispatch_did(handle, outgoing, incoming, cx); - }); - } - None => crate::lifecycle::dispatch_did(handle, previous_top, Some(child.tag), cx), - } - } - - fn on_remove_child( - &self, - child: i32, - parent: i32, - retained: bool, - tree: &TreeView, - handle: &StoreHandle, - cx: &mut gpui::App, - ) { - let Some(node) = tree.node(child) else { - return; - }; - if node.component != SCREEN { - return; - } - let plan = state::with(|state| state.pop_plans.remove(&child)); - let Some(plan) = plan else { - return; - }; - let _ = parent; - if let Some(revealed) = plan.revealed { - handle.clear_transition(revealed, cx); - } - let native_dismiss = state::with(|state| state.native_dismiss_pending == Some(child)); - let mode = transition::transition_mode(&plan.animation) - .filter(|_| tree.animations_enabled()) - .map(transition::TransitionMode::reverse); - let retain = plan.retain && mode.is_some(); - log::info!( - "[screens] pop transition outgoing={} incoming={:?} animation={} retained={retain}", - child, - plan.revealed, - plan.animation - ); - if retain { - if let Some(mode) = mode { - handle.start_transition( - child, - transition::transition(mode, TransitionRole::Exit, 1.0), - cx, - ); - state::with(|state| { - state.roles.insert(child, (Role::Exit, 1.0)); - }); - } - } - if !native_dismiss { - crate::lifecycle::dispatch_will(handle, Some(child), plan.revealed, cx); - } - if retained { - let duration = mode.map(|mode| mode.duration()).unwrap_or_default(); - let revealed = plan.revealed; - let handle = handle.clone(); - handle.after(duration, cx, move |handle, cx| { - handle.release_retained(child, cx); - log::info!("[screens] pop finished outgoing={child}"); - crate::lifecycle::dispatch_did(handle, Some(child), revealed, cx); - }); - } else if !native_dismiss { - crate::lifecycle::dispatch_did(handle, Some(child), plan.revealed, cx); - } - state::with(|state| { - if state.native_dismiss_pending == Some(child) { - state.native_dismiss_pending = None; - } - }); - } - - fn on_remove(&self, tag: i32, _handle: &StoreHandle, _cx: &mut gpui::App) { - state::with(|state| { - state.pop_plans.remove(&tag); - state.roles.remove(&tag); - state.headers.remove(&tag); - }); - } - - fn on_update( - &self, - node: &ComponentNode, - previous: &ComponentNode, - handle: &StoreHandle, - cx: &mut gpui::App, - ) { - if node.component != SCREEN { - return; - } - let before = props::activity_state(previous); - let after = props::activity_state(node); - if before == after { - return; - } - for event in crate::lifecycle::lifecycle_events(before, after) { - log::info!( - "[screens] tag={} activity={}->{} event={event}", - node.tag, - before, - after - ); - handle.dispatch_event(node.tag, event, &serde_json::json!({}), cx); - } - } - - fn after_batch(&self, _tree: &TreeView, _handle: &StoreHandle, _cx: &mut gpui::App) { - state::clear_batch_state(); - } - - fn on_transition_frame( - &self, - tag: i32, - progress: f32, - handle: &StoreHandle, - cx: &mut gpui::App, - ) { - let forward = state::with(|state| { - state - .roles - .get(&tag) - .is_none_or(|(role, distance)| *role == Role::Enter || *distance < 1.0) - }); - handle.dispatch_event( - tag, - "topTransitionProgress", - &serde_json::json!({ - "progress": progress, - "closing": if forward { 0 } else { 1 }, - "goingForward": if forward { 1 } else { 0 } - }), - cx, - ); - } -} - -/// Whether `stack` is the outer stack, the only one that animates. -fn is_outer_stack(stack: i32) -> bool { - !state::with(|state| state.nested_stacks.contains(&stack)) -} - -/// Every stack that sits inside a screen, found from the batch topology before -/// any of it is applied. -fn nested_stacks(batch: &BatchView, tree: &TreeView) -> HashSet { - let stacks: Vec = batch - .ops - .iter() - .filter(|op| op.kind == BatchOpKind::Create && op.component == STACK) - .map(|op| op.tag) - .chain( - batch - .ops - .iter() - .filter(|op| op.kind != BatchOpKind::Create && op.component == STACK) - .map(|op| op.tag), - ) - .collect(); - let mut nested = HashSet::new(); - for stack in stacks { - let mut cursor = Some(stack); - let mut visited = HashSet::new(); - while let Some(tag) = cursor { - if !visited.insert(tag) { - break; - } - let Some(parent) = batch.parent_of(tag).or_else(|| tree.parent(tag)) else { - break; - }; - if batch.component_of(parent, tree).as_deref() == Some(SCREEN) { - nested.insert(stack); - break; - } - cursor = Some(parent); - } - } - nested -} - -/// The cards leaving in this batch that should animate their exit. -fn pop_plans( - batch: &BatchView, - tree: &TreeView, - nested: &HashSet, - handle: &StoreHandle, - cx: &mut gpui::App, -) -> std::collections::HashMap { - let removed: HashSet = batch - .ops - .iter() - .filter(|op| op.kind == BatchOpKind::Remove && op.component == SCREEN) - .map(|op| op.tag) - .collect(); - let mut plans = std::collections::HashMap::new(); - for op in batch - .ops - .iter() - .filter(|op| op.kind == BatchOpKind::Remove && op.component == SCREEN) - { - if nested.contains(&op.parent_tag) { - continue; - } - let Some(stack) = tree.node(op.parent_tag) else { - continue; - }; - if stack.component != STACK { - continue; - } - let live: Vec = tree - .children(op.parent_tag) - .into_iter() - .filter(|tag| { - tree.is_live(*tag) && tree.node(*tag).is_some_and(|node| node.component == SCREEN) - }) - .collect(); - if live.last().copied() != Some(op.tag) { - continue; - } - let revealed = live - .iter() - .rev() - .find(|tag| !removed.contains(tag)) - .copied(); - let Some(screen) = tree.node(op.tag) else { - continue; - }; - let animation = props::stack_animation(&screen).to_string(); - let native_dismiss = state::with(|state| state.native_dismiss_pending == Some(op.tag)); - let mode = transition::transition_mode(&animation).filter(|_| tree.animations_enabled()); - let retain = !native_dismiss && revealed.is_some() && mode.is_some(); - if retain { - log::info!( - "[screens] preserve outgoing={} descendants={}", - op.tag, - descendant_count(op.tag, tree) - ); - } - plans.insert( - op.tag, - PopPlan { - revealed, - animation, - duration: mode.map(|mode| mode.duration()).unwrap_or_default(), - retain, - }, - ); - } - plans -} - -/// How many nodes sit below `tag`, at any depth. -fn descendant_count(tag: i32, tree: &TreeView) -> usize { - let mut total = 0; - let mut stack = tree.children(tag); - while let Some(next) = stack.pop() { - total += 1; - stack.extend(tree.children(next)); - } - total -} diff --git a/vendor/react-native-gpui/modules/screens/desktop/src/state.rs b/vendor/react-native-gpui/modules/screens/desktop/src/state.rs deleted file mode 100644 index 9bf4ce4720..0000000000 --- a/vendor/react-native-gpui/modules/screens/desktop/src/state.rs +++ /dev/null @@ -1,162 +0,0 @@ -//! The module's own state, kept outside core. -//! -//! Core hands an observer facts about a batch and forgets them; everything a -//! stack has to remember between batches — which stacks are nested, which cards -//! are leaving, what a dismissal already animated — is here. -use std::collections::{HashMap, HashSet}; -use std::sync::{Mutex, OnceLock}; -use std::time::Duration; - -/// What `decorate` learned about a header, for `content` to use. -#[derive(Clone, Copy, Debug, Default)] -pub struct HeaderFacts { - pub is_top: bool, - pub shows_back: bool, - pub has_title_subview: bool, - /// The screen this header belongs to, which is where a back-button event - /// has to go: React Native declares `onHeaderBackButtonClicked` on - /// `RNSScreen`, not on the header config. - pub screen: Option, -} - -/// Records what `decorate` learned, so `content` can read it. -pub fn set_header_facts( - tag: i32, - is_top: bool, - shows_back: bool, - has_title_subview: bool, - screen: Option, -) { - with(|state| { - state.headers.insert( - tag, - HeaderFacts { - is_top, - shows_back, - has_title_subview, - screen, - }, - ); - }); -} - -/// Whether this header is the top screen's, as of the last `decorate` call. -pub fn header_is_top(tag: i32) -> bool { - with(|state| state.headers.get(&tag).is_some_and(|facts| facts.is_top)) -} - -/// Whether this header carries a `title` subview, as of the last `decorate` call. -/// -/// When it does, that subview paints the title and core must not paint its own. -pub fn header_has_title_subview(tag: i32) -> bool { - with(|state| { - state - .headers - .get(&tag) - .is_some_and(|facts| facts.has_title_subview) - }) -} - -/// The screen a header belongs to, as of the last `decorate` call. -pub fn header_screen(tag: i32) -> Option { - with(|state| state.headers.get(&tag).and_then(|facts| facts.screen)) -} - -/// Whether this header shows a back button, as of the last `decorate` call. -pub fn header_shows_back(tag: i32) -> bool { - with(|state| { - state - .headers - .get(&tag) - .is_some_and(|facts| facts.shows_back) - }) -} - -/// A card that is leaving, and what should happen when it is gone. -#[derive(Clone, Debug)] -pub struct PopPlan { - /// The screen that becomes top when this one is gone. - pub revealed: Option, - /// The animation name React Native asked for, unparsed. - pub animation: String, - /// How long the exit runs. - pub duration: Duration, - /// Whether the card must stay attached so its exit can paint. - pub retain: bool, -} - -/// Everything the module remembers between batches. -#[derive(Default)] -pub struct State { - /// A native dismissal already ran the exit animation, so the removal must - /// not run a second one and must not send the "will" events again. - pub native_dismiss_pending: Option, - /// Stacks that sit inside a screen, so only the outer stack animates. - pub nested_stacks: HashSet, - /// Cards leaving in this batch, by tag. - pub pop_plans: HashMap, - /// The cards this module started a transition on: whether it is an entry - /// (the screen is arriving) or an exit, and how far it travels. - pub roles: HashMap, - /// The latest facts about each header, written by `decorate`. - pub headers: HashMap, -} - -/// Whether a transition the module started is an arrival or a departure. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Role { - Enter, - Exit, -} - -fn state() -> &'static Mutex { - static STATE: OnceLock> = OnceLock::new(); - STATE.get_or_init(|| Mutex::new(State::default())) -} - -/// Runs `f` with the module state. -pub fn with(f: impl FnOnce(&mut State) -> R) -> R { - let mut state = state() - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - f(&mut state) -} - -/// Forgets the per-batch decisions. Call from `after_batch`. -pub fn clear_batch_state() { - with(|state| { - state.pop_plans.clear(); - }); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn batch_state_is_cleared_but_lifetimes_are_not() { - with(|state| { - state.pop_plans.insert( - 7, - PopPlan { - revealed: Some(3), - animation: "slide_from_right".to_string(), - duration: Duration::from_millis(240), - retain: true, - }, - ); - state.nested_stacks.insert(9); - state.native_dismiss_pending = Some(7); - }); - clear_batch_state(); - with(|state| { - assert!(state.pop_plans.is_empty()); - assert!(state.nested_stacks.contains(&9)); - assert_eq!(state.native_dismiss_pending, Some(7)); - }); - with(|state| { - state.nested_stacks.clear(); - state.native_dismiss_pending = None; - }); - } -} diff --git a/vendor/react-native-gpui/modules/screens/desktop/src/transition.rs b/vendor/react-native-gpui/modules/screens/desktop/src/transition.rs deleted file mode 100644 index e94f7fdd3d..0000000000 --- a/vendor/react-native-gpui/modules/screens/desktop/src/transition.rs +++ /dev/null @@ -1,193 +0,0 @@ -//! The animation modes a stack accepts, and the poses each one corresponds to. -//! -//! Core owns the timing and the paint; this file is the module's own statement -//! of what "slide from the right" and "fade" mean as movement between two -//! poses, so core never learns a navigation name. -use react_native_gpui::extensions::{Pose, Transition}; -use std::time::Duration; - -/// A stack animation, as `stackAnimation` names it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum TransitionMode { - Fade, - SlideFromRight, - SlideFromLeft, -} - -impl TransitionMode { - /// The mode the reverse of this one uses, so a pop plays the entry mirrored. - #[must_use] - pub fn reverse(self) -> Self { - match self { - Self::SlideFromRight => Self::SlideFromLeft, - Self::SlideFromLeft => Self::SlideFromRight, - Self::Fade => Self::Fade, - } - } - - /// How long this mode runs. - pub fn duration(self) -> Duration { - match self { - Self::Fade => Duration::from_millis(150), - _ => Duration::from_millis(240), - } - } -} - -/// The mode a `stackAnimation` string asks for. Unknown values fade, which is -/// what the platform's own default is. -pub fn transition_mode(animation: &str) -> Option { - match animation { - "none" => None, - "slide_from_right" | "simple_push" => Some(TransitionMode::SlideFromRight), - "slide_from_left" => Some(TransitionMode::SlideFromLeft), - "default" | "" | "fade" => Some(TransitionMode::Fade), - _ => Some(TransitionMode::Fade), - } -} - -/// Whether entering or leaving. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Role { - Enter, - Exit, -} - -/// The poses a mode and role correspond to. -/// -/// Entering slides from off-screen to rest; leaving slides from rest to -/// off-screen; a fade keeps the node still while its opacity moves. The offset -/// is a fraction of the node's own width, so `distance` is how far it travels. -pub fn poses(mode: TransitionMode, role: Role, distance: f32) -> (Pose, Pose) { - let rest = Pose { - offset_x: 0.0, - opacity: 1.0, - }; - let transparent = Pose { - offset_x: 0.0, - opacity: 0.0, - }; - let off_screen = |sign: f32| Pose { - offset_x: sign * distance, - opacity: 1.0, - }; - match (mode, role) { - (TransitionMode::Fade, Role::Enter) => (transparent, rest), - (TransitionMode::Fade, Role::Exit) => (rest, transparent), - (TransitionMode::SlideFromRight, Role::Enter) => (off_screen(1.0), rest), - (TransitionMode::SlideFromLeft, Role::Enter) => (off_screen(-1.0), rest), - (TransitionMode::SlideFromRight, Role::Exit) => (rest, off_screen(-1.0)), - (TransitionMode::SlideFromLeft, Role::Exit) => (rest, off_screen(1.0)), - } -} - -/// The transition a mode and role describe. -pub fn transition(mode: TransitionMode, role: Role, distance: f32) -> Transition { - let (from, to) = poses(mode, role, distance); - Transition { - from, - to, - duration: mode.duration(), - } -} - -/// The card underneath a push parallaxes a short way rather than leaving. -pub const PARALLAX_DISTANCE: f32 = 0.12; - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn maps_supported_animations_and_falls_back_to_fade() { - assert_eq!(transition_mode("none"), None); - assert_eq!(transition_mode("fade"), Some(TransitionMode::Fade)); - assert_eq!(transition_mode("default"), Some(TransitionMode::Fade)); - assert_eq!(transition_mode(""), Some(TransitionMode::Fade)); - assert_eq!( - transition_mode("slide_from_right"), - Some(TransitionMode::SlideFromRight) - ); - assert_eq!( - transition_mode("simple_push"), - Some(TransitionMode::SlideFromRight) - ); - assert_eq!( - transition_mode("slide_from_left"), - Some(TransitionMode::SlideFromLeft) - ); - assert_eq!(transition_mode("unsupported"), Some(TransitionMode::Fade)); - } - - #[test] - fn reversing_a_slide_swaps_its_direction() { - assert_eq!( - TransitionMode::SlideFromRight.reverse(), - TransitionMode::SlideFromLeft - ); - assert_eq!( - TransitionMode::SlideFromLeft.reverse(), - TransitionMode::SlideFromRight - ); - assert_eq!(TransitionMode::Fade.reverse(), TransitionMode::Fade); - } - - #[test] - fn the_poses_reproduce_the_original_slide_and_fade_curves() { - for (mode, role, distance, expected) in [ - ( - TransitionMode::SlideFromRight, - Role::Enter, - 1.0, - [1.0, 0.5, 0.0], - ), - ( - TransitionMode::SlideFromLeft, - Role::Enter, - 1.0, - [-1.0, -0.5, 0.0], - ), - ( - TransitionMode::SlideFromRight, - Role::Exit, - 1.0, - [0.0, -0.5, -1.0], - ), - ( - TransitionMode::SlideFromLeft, - Role::Exit, - 1.0, - [0.0, 0.5, 1.0], - ), - ( - TransitionMode::SlideFromRight, - Role::Exit, - PARALLAX_DISTANCE, - [0.0, -0.06, -0.12], - ), - ] { - let transition = transition(mode, role, distance); - for (progress, expected_offset) in - [(0.0, expected[0]), (0.5, expected[1]), (1.0, expected[2])] - { - let pose = transition.pose_at(progress); - assert!( - (pose.offset_x - expected_offset).abs() < 0.001, - "{mode:?} {role:?} at {progress}: {} != {expected_offset}", - pose.offset_x - ); - } - } - } - - #[test] - fn a_fade_moves_opacity_and_nothing_else() { - let transition = transition(TransitionMode::Fade, Role::Enter, 1.0); - for (progress, expected) in [(0.0, 0.0), (0.5, 0.5), (1.0, 1.0)] { - let pose = transition.pose_at(progress); - assert!((pose.opacity - expected).abs() < 0.001); - assert!(pose.offset_x.abs() < 0.001); - } - assert_eq!(transition.duration, Duration::from_millis(150)); - } -} diff --git a/vendor/react-native-gpui/modules/screens/desktop/src/unsupported.rs b/vendor/react-native-gpui/modules/screens/desktop/src/unsupported.rs deleted file mode 100644 index 4222c9ef0a..0000000000 --- a/vendor/react-native-gpui/modules/screens/desktop/src/unsupported.rs +++ /dev/null @@ -1,39 +0,0 @@ -//! Components react-native-screens ships that this platform does not implement. -//! -//! They are named here so the module can say so once, instead of core carrying a -//! list of a library's components. -/// Whether this component is one the platform cannot render. -pub fn unsupported_component(name: &str) -> bool { - matches!( - name, - "RNSSearchBar" - | "RNSBottomTabs" - | "RNSBottomTabsScreen" - | "RNSScreenFooter" - | "RNSSplitView" - | "RNSSplitViewScreen" - ) || name.starts_with("RNSSplitView") -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn identifies_the_components_the_platform_cannot_render() { - for name in [ - "RNSSearchBar", - "RNSBottomTabs", - "RNSBottomTabsScreen", - "RNSScreenFooter", - "RNSSplitView", - "RNSSplitViewScreen", - ] { - assert!(unsupported_component(name), "{name} should be unsupported"); - } - assert!(unsupported_component("RNSSplitViewSomethingElse")); - for name in ["RNSScreen", "RNSScreenStack", "View", "RNSScreenContainer"] { - assert!(!unsupported_component(name), "{name} should be supported"); - } - } -} diff --git a/vendor/react-native-gpui/modules/screens/docs/navigation.md b/vendor/react-native-gpui/modules/screens/docs/navigation.md deleted file mode 100644 index 58823a2f2d..0000000000 --- a/vendor/react-native-gpui/modules/screens/docs/navigation.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -id: navigation -title: Navigating Between Screens ---- - -[React Navigation](https://reactnavigation.org) works on desktop with its native stack. Follow React Native's [navigation guide](https://reactnative.dev/docs/0.87/navigation) and the [React Navigation getting started guide](https://reactnavigation.org/docs/getting-started); this page lists only what is different on desktop. - -## Installation - -Install the desktop packages next to React Navigation's peer dependencies: - -```shell -npm install @react-navigation/native @react-navigation/native-stack -npm install react-native-screens react-native-safe-area-context -npm install @react-native-gpui/screens @react-native-gpui/safe-area-context -``` - -See [Supported libraries](https://streetwriters.github.io/react-native-gpui/docs/supported-libraries) for the versions that the desktop packages support. Autolinking builds the native code, so there is no extra linking step. Run the app with `npx react-native run-desktop`. - -## The native stack - -The `native-stack` navigator is drawn by react-native-gpui through `react-native-screens`, so the same code runs on macOS, Windows and Linux. - -## Mouse back and forward buttons - -The back button fires `BackHandler`'s `hardwareBackPress`, which React Navigation already handles. The forward button moves forward in a stack with `useDesktopForwardNavigation` from `@react-native-gpui/core/navigation`: - -```tsx -import { useDesktopForwardNavigation } from '@react-native-gpui/core/navigation'; - -function App() { - const navigationRef = useNavigationContainerRef(); - useDesktopForwardNavigation(navigationRef); - return ( - {/* ... */} - ); -} -``` diff --git a/vendor/react-native-gpui/modules/screens/package.json b/vendor/react-native-gpui/modules/screens/package.json deleted file mode 100644 index 0d2172ccfe..0000000000 --- a/vendor/react-native-gpui/modules/screens/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "@react-native-gpui/screens", - "version": "4.28.0-alpha.2", - "description": "Adapter for react-native-screens (MIT): draws native stacks and screens, as used by React Navigation", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/streetwriters/react-native-gpui-modules.git", - "directory": "modules/screens" - }, - "homepage": "https://github.com/streetwriters/react-native-gpui-modules/tree/main/modules/screens#readme", - "bugs": { - "url": "https://github.com/streetwriters/react-native-gpui-modules/issues" - }, - "files": [ - "desktop", - "react-native.config.js", - "src", - "README.md", - "LICENSE", - "CHANGELOG.md", - "!**/*.test.js", - "!**/*.test.mjs", - "!**/*.test.ts", - "!**/*.test.cjs" - ], - "peerDependencies": { - "react-native": "0.87.x", - "react-native-screens": "4.28.x" - }, - "publishConfig": { - "access": "public", - "tag": "latest" - } -} diff --git a/vendor/react-native-gpui/modules/screens/react-native.config.js b/vendor/react-native-gpui/modules/screens/react-native.config.js deleted file mode 100644 index 6f949d7fe8..0000000000 --- a/vendor/react-native-gpui/modules/screens/react-native.config.js +++ /dev/null @@ -1,36 +0,0 @@ -module.exports = { - dependency: { - platforms: { - desktop: { - cmake: 'desktop', - crate: 'rn-gpui-screens', - componentCodegenPackage: 'react-native-screens', - componentDescriptors: [ - 'RNSScreenComponentDescriptor', - 'RNSScreenContainerComponentDescriptor', - 'RNSScreenContentWrapperComponentDescriptor', - 'RNSScreenNavigationContainerComponentDescriptor', - 'RNSScreenStackComponentDescriptor', - 'RNSScreenStackHeaderConfigComponentDescriptor', - 'RNSScreenStackHeaderSubviewComponentDescriptor', - 'RNSModalScreenComponentDescriptor', - 'RNSFullWindowOverlayComponentDescriptor', - ], - componentHeaders: [ - 'react/renderer/components/rnscreens/ComponentDescriptors.h', - 'react/renderer/components/rnscreens/RNSScreenComponentDescriptor.h', - 'react/renderer/components/rnscreens/RNSScreenStackHeaderConfigComponentDescriptor.h', - 'react/renderer/components/rnscreens/RNSScreenStackHeaderSubviewComponentDescriptor.h', - 'react/renderer/components/rnscreens/RNSModalScreenComponentDescriptor.h', - 'react/renderer/components/rnscreens/RNSFullWindowOverlayComponentDescriptor.h', - ], - // Metro: replace these files of installed packages for gpui. - sourceOverrides: { - 'react-native-screens/src/core.ts': './src/core.desktop.ts', - 'react-native-screens/src/components/FullWindowOverlay.tsx': - './src/FullWindowOverlay.desktop.tsx', - }, - }, - }, - }, -}; diff --git a/vendor/react-native-gpui/modules/screens/src/FullWindowOverlay.desktop.tsx b/vendor/react-native-gpui/modules/screens/src/FullWindowOverlay.desktop.tsx deleted file mode 100644 index 761bcc383e..0000000000 --- a/vendor/react-native-gpui/modules/screens/src/FullWindowOverlay.desktop.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import React, { type PropsWithChildren } from 'react'; -import { StyleSheet, useWindowDimensions } from 'react-native'; -import FullWindowOverlayNativeComponent from 'react-native-screens/src/fabric/FullWindowOverlayNativeComponent'; -import type { NativeProps } from 'react-native-screens/src/fabric/FullWindowOverlayNativeComponent'; - -export default function FullWindowOverlay({ - children, - ...props -}: PropsWithChildren) { - const { width, height } = useWindowDimensions(); - return ( - - {children} - - ); -} diff --git a/vendor/react-native-gpui/modules/screens/src/core.desktop.ts b/vendor/react-native-gpui/modules/screens/src/core.desktop.ts deleted file mode 100644 index 9a5e1a98e7..0000000000 --- a/vendor/react-native-gpui/modules/screens/src/core.desktop.ts +++ /dev/null @@ -1,28 +0,0 @@ -import './customDirectEventTypes.desktop'; - -// GPUI always ships the native screens implementation. -export const isNativePlatformSupported = true; - -let ENABLE_SCREENS = isNativePlatformSupported; - -export function enableScreens(shouldEnableScreens = true) { - ENABLE_SCREENS = shouldEnableScreens; -} - -let ENABLE_FREEZE = false; - -export function enableFreeze(shouldEnableReactFreeze = true) { - if (!isNativePlatformSupported) { - return; - } - - ENABLE_FREEZE = shouldEnableReactFreeze; -} - -export function screensEnabled() { - return ENABLE_SCREENS; -} - -export function freezeEnabled() { - return ENABLE_FREEZE; -} diff --git a/vendor/react-native-gpui/modules/screens/src/customDirectEventTypes.desktop.ts b/vendor/react-native-gpui/modules/screens/src/customDirectEventTypes.desktop.ts deleted file mode 100644 index 39f81385fd..0000000000 --- a/vendor/react-native-gpui/modules/screens/src/customDirectEventTypes.desktop.ts +++ /dev/null @@ -1,16 +0,0 @@ -// The native stack header dispatches this upstream screen event to notify -// React Navigation that the user requested a native back action. -import { customDirectEventTypes } from 'react-native/Libraries/Renderer/shims/ReactNativeViewConfigRegistry'; - -customDirectEventTypes.topHeaderBackButtonClicked = { - registrationName: 'onHeaderBackButtonClicked', -}; - -customDirectEventTypes.topWillAppear = { registrationName: 'onWillAppear' }; -customDirectEventTypes.topWillDisappear = { - registrationName: 'onWillDisappear', -}; -customDirectEventTypes.topAppear = { registrationName: 'onAppear' }; -customDirectEventTypes.topDisappear = { registrationName: 'onDisappear' }; - -export { customDirectEventTypes }; diff --git a/vendor/react-native-gpui/modules/svg/CHANGELOG.md b/vendor/react-native-gpui/modules/svg/CHANGELOG.md deleted file mode 100644 index c8aab3a243..0000000000 --- a/vendor/react-native-gpui/modules/svg/CHANGELOG.md +++ /dev/null @@ -1,21 +0,0 @@ -# Changelog - -All notable changes to `@react-native-gpui/svg` are listed here. Each version's section becomes the notes of its GitHub release. - -## 15.15.0-alpha.1 - 2026-11-12 - -- A drawing is looked up by a structural hash of its props, children, frame size and scale, so a render that finds it builds no document string. Before, every render built and escaped the whole SVG document just to hash it, even when the raster was cached. -- The rasters are kept in one cache shared by every node, bounded by bytes (64 MB; `RN_GPUI_SVG_CACHE_MB` sets another) and dropping the image used longest ago first. It held weak references before, so an icon that left the screen was rasterised again when it came back, and the same icon in two places was drawn twice. -- A drawing that is not cached is rasterised on a background thread when it is large (over about 48 CSS pixels square at a scale of 2) or has a filter, or when its node already shows an image (a theme switch). The node keeps showing its previous image until the new one is ready, then is built again; a node with nothing to show yet draws nothing until then. A small icon whose node has no image is still drawn at once, so a row that scrolls in has its icon on the first frame. Several nodes asking for the same drawing share one rasterisation. -- The four coverage samples of a drawing are rasterised side by side (a small one, under 128 by 128 pixels, one after the other, because starting a thread costs more than a sample) and combined in a fixed order, so the pixels are the same as when they were drawn one after the other (a test compares them in both ways). A 230 point illustration with drop shadows takes 30 ms to rasterise instead of 120, and now off the main thread. -- `RN_GPUI_SVG_TRACE=1` logs each rasterisation with the time of every sample, and `RN_GPUI_SVG_SYNC=1` draws everything on the main thread, for measuring. -- An SVG is drawn with the same antialiasing as Chrome: once per coverage sample at the window's scale, without antialiasing, with the four sample positions Chrome uses, and averaged. An icon's edge now takes the same five coverage steps (0, 1/4, 1/2, 3/4, 1) at the same pixels, so the Material star at 16 points differs from Chrome in 5 of 1024 pixels instead of 112, and over 80 icons in 124,480 pixels in 1,288 instead of 7,250. Needs `image` and `smallvec` in the crate. -- An SVG is placed at a whole CSS pixel, as Chrome places an inline SVG: a 15 point icon centred in a 20 point button, which lays out at 2.5, is drawn at 3 instead of half a point to the left. That half point was the bulk of the edge pixels that differed from the web app (97 of 1,600 in a toolbar arrow, 2 now). -- An element's `transform` is applied: react-native-svg sends it as a six number `matrix`, which was only read when it had sixteen, so every rotated or scaled shape was drawn untransformed. -- Filters are drawn: `filter` on a shape or group, `` and the `feBlend`, `feColorMatrix`, `feComposite`, `feFlood`, `feGaussianBlur`, `feMerge` and `feOffset` primitives reach the renderer, with `sRGB` colour interpolation. An illustration with rotated cards and drop shadows at 230 points differs from Chrome in 249 of 211,600 pixels by more than 8 levels instead of 14,817. -- Asks core for each node's subtree, which core now hands a component renderer only when it reads it. - -## 15.15.0-alpha.0 - 2026-11-01 - -- First release, for `react-native-svg` 15.15.x. -- Renders SVG elements with the desktop renderer. diff --git a/vendor/react-native-gpui/modules/svg/LICENSE b/vendor/react-native-gpui/modules/svg/LICENSE deleted file mode 100644 index 149a0f8321..0000000000 --- a/vendor/react-native-gpui/modules/svg/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Streetwriters - -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/vendor/react-native-gpui/modules/svg/README.md b/vendor/react-native-gpui/modules/svg/README.md deleted file mode 100644 index 463f0ba306..0000000000 --- a/vendor/react-native-gpui/modules/svg/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# @react-native-gpui/svg - -Adapter for [`react-native-svg`](https://github.com/software-mansion/react-native-svg) (MIT): draws SVG elements with the desktop renderer. - -Part of [react-native-gpui](https://github.com/streetwriters/react-native-gpui), React Native for macOS, Windows and Linux. - -## Install - -Install it next to `react-native-svg`: - -```sh -npm install react-native-svg@15.15.x @react-native-gpui/svg -``` - -Keep using `react-native-svg` as you do on iOS and Android; its JavaScript API is unchanged. Autolinking builds the desktop side when the app is built. - -## What is drawn - -Shapes, paths, text, gradients, masks, clip paths, symbols, patterns and markers, with the transform of each element (react-native-svg sends it as a six number matrix). Filters are drawn too: `filter` on a shape or group and the `feBlend`, `feColorMatrix`, `feComposite`, `feFlood`, `feGaussianBlur`, `feMerge` and `feOffset` primitives, always with sRGB colour interpolation. An icon is drawn with the same antialiasing as Chrome and placed at a whole CSS pixel, as Chrome places an inline SVG. - -Limits: `overflow="visible"` is not honoured (the drawing is clipped to the SVG's frame), the other filter primitives such as `feDropShadow` and `feMorphology` are not passed to the renderer, and a blurred shadow comes out about one level lighter than Chrome's for each shadow that overlaps another. - -## Cost - -A drawing is cached by a hash of what it is made of, so drawing it again costs a hash and a lookup. The cache is shared by every node and holds up to 64 MB of images (`RN_GPUI_SVG_CACHE_MB` changes that). A drawing that is not cached yet is rasterised on a background thread when it is large or filtered, and the node shows its previous image, if it has one, until the new one is ready; a small icon with nothing yet to show is drawn at once. `RN_GPUI_SVG_TRACE=1` logs each rasterisation and `RN_GPUI_SVG_SYNC=1` draws on the main thread, to measure. - -## Documentation - -[Supported libraries](https://streetwriters.github.io/react-native-gpui/docs/supported-libraries) - -## License - -MIT. See [LICENSE](LICENSE). diff --git a/vendor/react-native-gpui/modules/svg/desktop/CMakeLists.txt b/vendor/react-native-gpui/modules/svg/desktop/CMakeLists.txt deleted file mode 100644 index 0eb1aa2dc8..0000000000 --- a/vendor/react-native-gpui/modules/svg/desktop/CMakeLists.txt +++ /dev/null @@ -1,8 +0,0 @@ -# SVG shared Fabric props/shadow-node descriptors are supplied by RN Codegen -# and react-native-svg's published common C++ shadow-node headers. -set(_svg_codegen_dir "${RN_GPUI_PROJECT_ROOT}/desktop/autolink/codegen/rnsvg") -set_property(GLOBAL APPEND PROPERTY RN_GPUI_PACKAGE_MODULE_SOURCES - "${CMAKE_CURRENT_LIST_DIR}/cpp/GpuiSvgModule.cpp") -set_property(GLOBAL APPEND PROPERTY RN_GPUI_PACKAGE_MODULE_INSTALLERS svg) -set_property(GLOBAL APPEND PROPERTY RN_GPUI_PACKAGE_MODULE_INCLUDE_DIRS - "${_svg_codegen_dir}") diff --git a/vendor/react-native-gpui/modules/svg/desktop/Cargo.toml b/vendor/react-native-gpui/modules/svg/desktop/Cargo.toml deleted file mode 100644 index b4af6a186b..0000000000 --- a/vendor/react-native-gpui/modules/svg/desktop/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "rn-gpui-svg" -version = "0.1.0" -edition = "2021" - -[dependencies] -react-native-gpui = { version = "0.1" } -rn-gpui-sys = { version = "0.1" } -gpui = { version = "0.2" } -serde_json = "1" -# The same versions gpui is built with, for the averaged image it draws. -image = { version = "0.25", default-features = false } -smallvec = "1" diff --git a/vendor/react-native-gpui/modules/svg/desktop/build.rs b/vendor/react-native-gpui/modules/svg/desktop/build.rs deleted file mode 100644 index d18a3120d0..0000000000 --- a/vendor/react-native-gpui/modules/svg/desktop/build.rs +++ /dev/null @@ -1,38 +0,0 @@ -//! Puts the C++ runtime's shared libraries on this crate's test binary rpath. -//! -//! `rn-gpui-svg`'s tests build gpui trees, which link `libjsi.dylib` and the rest -//! of the Node-API runtime. Core's `build.rs` emits -//! `cargo:rustc-link-arg=-Wl,-rpath,` for its own binary — the app — and that -//! flag is not inherited by a dependency's test binary, so the test process -//! aborted in dyld with `Library not loaded: @rpath/libjsi.dylib` before running a -//! single test. -//! -//! Core exports the directories it was given as `DEP_RN_GPUI_CORE_RPATHS`, which -//! is the same variable core's own `build.rs` reads. Re-emitting it here scopes -//! the flag to this crate's test binary, since `cargo:rustc-link-arg` without a -//! target suffix applies to the crate's own targets and not to the app that -//! depends on it. - -fn main() { - println!("cargo:rerun-if-env-changed=DEP_RN_GPUI_CORE_RPATHS"); - println!("cargo:rerun-if-changed=build.rs"); - - let Ok(dirs) = std::env::var("DEP_RN_GPUI_CORE_RPATHS") else { - return; - }; - let dirs = dirs - .split('|') - .filter(|dir| !dir.is_empty()) - .collect::>(); - if dirs.is_empty() { - return; - } - // MSVC and MinGW have no rpath, and the flag is rejected outright; Windows - // finds the DLLs through PATH, which the test runner already arranges. - if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { - return; - } - for dir in dirs { - println!("cargo:rustc-link-arg=-Wl,-rpath,{dir}"); - } -} diff --git a/vendor/react-native-gpui/modules/svg/desktop/cpp/GpuiSvgModule.cpp b/vendor/react-native-gpui/modules/svg/desktop/cpp/GpuiSvgModule.cpp deleted file mode 100644 index 4d80bba9ca..0000000000 --- a/vendor/react-native-gpui/modules/svg/desktop/cpp/GpuiSvgModule.cpp +++ /dev/null @@ -1,178 +0,0 @@ -#include "GpuiModules.h" -#include "MountBatchBuilder.h" - -#include - -#include -#include -#include -#include - -namespace rngpui { -using namespace facebook::react; - -namespace { -constexpr const char* kSvgComponents[] = { - "RNSVGSvgView", "RNSVGCircle", "RNSVGEllipse", - "RNSVGLine", "RNSVGPath", "RNSVGRect", - "RNSVGGroup", "RNSVGDefs", "RNSVGClipPath", - "RNSVGLinearGradient", "RNSVGRadialGradient", "RNSVGText", - "RNSVGTSpan", "RNSVGFilter", "RNSVGFeBlend", - "RNSVGFeColorMatrix", "RNSVGFeComposite", "RNSVGFeFlood", - "RNSVGFeGaussianBlur", "RNSVGFeMerge", "RNSVGFeOffset", -}; - -template - requires(!std::is_enum_v) -folly::dynamic svgJsonValue(const T& value) { - return value; -} - -template - requires std::is_enum_v -folly::dynamic svgJsonValue(const T& value) { - return toString(value); -} - -folly::dynamic svgJsonValue(const Float& value) { - return value; -} -folly::dynamic svgJsonValue(const SharedColor& value) { - return value ? folly::dynamic(argb(value)) : folly::dynamic(nullptr); -} -folly::dynamic svgJsonValue(const std::vector& values) { - folly::dynamic result = folly::dynamic::array(); - for (const auto& value : values) - result.push_back(value); - return result; -} -folly::dynamic svgJsonValue(const std::vector& values) { - folly::dynamic result = folly::dynamic::array(); - for (auto value : values) - result.push_back(value); - return result; -} - -template -folly::dynamic svgPropsJson(const T& props) { - folly::dynamic result = folly::dynamic::object(); -#define RN_GPUI_COPY_SVG_PROP(name) \ - if constexpr (requires { props.name; }) \ - result[#name] = svgJsonValue(props.name) - RN_GPUI_COPY_SVG_PROP(name); - RN_GPUI_COPY_SVG_PROP(d); - RN_GPUI_COPY_SVG_PROP(x); - RN_GPUI_COPY_SVG_PROP(y); - RN_GPUI_COPY_SVG_PROP(x1); - RN_GPUI_COPY_SVG_PROP(y1); - RN_GPUI_COPY_SVG_PROP(x2); - RN_GPUI_COPY_SVG_PROP(y2); - RN_GPUI_COPY_SVG_PROP(cx); - RN_GPUI_COPY_SVG_PROP(cy); - RN_GPUI_COPY_SVG_PROP(r); - RN_GPUI_COPY_SVG_PROP(rx); - RN_GPUI_COPY_SVG_PROP(ry); - RN_GPUI_COPY_SVG_PROP(width); - RN_GPUI_COPY_SVG_PROP(height); - RN_GPUI_COPY_SVG_PROP(vbWidth); - RN_GPUI_COPY_SVG_PROP(vbHeight); - RN_GPUI_COPY_SVG_PROP(minX); - RN_GPUI_COPY_SVG_PROP(minY); - RN_GPUI_COPY_SVG_PROP(align); - RN_GPUI_COPY_SVG_PROP(meetOrSlice); - RN_GPUI_COPY_SVG_PROP(opacity); - RN_GPUI_COPY_SVG_PROP(color); - RN_GPUI_COPY_SVG_PROP(propList); - RN_GPUI_COPY_SVG_PROP(fill); - RN_GPUI_COPY_SVG_PROP(fillOpacity); - RN_GPUI_COPY_SVG_PROP(fillRule); - RN_GPUI_COPY_SVG_PROP(stroke); - RN_GPUI_COPY_SVG_PROP(strokeOpacity); - RN_GPUI_COPY_SVG_PROP(strokeWidth); - RN_GPUI_COPY_SVG_PROP(strokeLinecap); - RN_GPUI_COPY_SVG_PROP(strokeLinejoin); - RN_GPUI_COPY_SVG_PROP(strokeDasharray); - RN_GPUI_COPY_SVG_PROP(strokeDashoffset); - RN_GPUI_COPY_SVG_PROP(strokeMiterlimit); - RN_GPUI_COPY_SVG_PROP(matrix); - RN_GPUI_COPY_SVG_PROP(mask); - RN_GPUI_COPY_SVG_PROP(clipPath); - RN_GPUI_COPY_SVG_PROP(offset); - RN_GPUI_COPY_SVG_PROP(stopColor); - RN_GPUI_COPY_SVG_PROP(stopOpacity); - if constexpr (requires { props.filter; }) { - if constexpr (std::is_same_v< - std::remove_cvref_t, - std::string>) - result["filter"] = props.filter; - } - RN_GPUI_COPY_SVG_PROP(filterUnits); - RN_GPUI_COPY_SVG_PROP(primitiveUnits); - RN_GPUI_COPY_SVG_PROP(result); - RN_GPUI_COPY_SVG_PROP(in1); - RN_GPUI_COPY_SVG_PROP(in2); - RN_GPUI_COPY_SVG_PROP(mode); - RN_GPUI_COPY_SVG_PROP(type); - RN_GPUI_COPY_SVG_PROP(values); - RN_GPUI_COPY_SVG_PROP(operator1); - RN_GPUI_COPY_SVG_PROP(k1); - RN_GPUI_COPY_SVG_PROP(k2); - RN_GPUI_COPY_SVG_PROP(k3); - RN_GPUI_COPY_SVG_PROP(k4); - RN_GPUI_COPY_SVG_PROP(dx); - RN_GPUI_COPY_SVG_PROP(dy); - RN_GPUI_COPY_SVG_PROP(edgeMode); - RN_GPUI_COPY_SVG_PROP(floodColor); - RN_GPUI_COPY_SVG_PROP(floodOpacity); - RN_GPUI_COPY_SVG_PROP(stdDeviationX); - RN_GPUI_COPY_SVG_PROP(stdDeviationY); - RN_GPUI_COPY_SVG_PROP(nodes); -#undef RN_GPUI_COPY_SVG_PROP - return result; -} - -folly::dynamic svgPropsJson(const std::string& component, const Props& props) { -#define RN_GPUI_SVG_PROPS(tag, type) \ - if (component == tag) { \ - if (auto typed = dynamic_cast(&props)) \ - return svgPropsJson(*typed); \ - } - RN_GPUI_SVG_PROPS("RNSVGSvgView", RNSVGSvgViewProps) - RN_GPUI_SVG_PROPS("RNSVGCircle", RNSVGCircleProps) - RN_GPUI_SVG_PROPS("RNSVGEllipse", RNSVGEllipseProps) - RN_GPUI_SVG_PROPS("RNSVGLine", RNSVGLineProps) - RN_GPUI_SVG_PROPS("RNSVGPath", RNSVGPathProps) - RN_GPUI_SVG_PROPS("RNSVGRect", RNSVGRectProps) - RN_GPUI_SVG_PROPS("RNSVGGroup", RNSVGGroupProps) - RN_GPUI_SVG_PROPS("RNSVGDefs", RNSVGDefsProps) - RN_GPUI_SVG_PROPS("RNSVGClipPath", RNSVGClipPathProps) - RN_GPUI_SVG_PROPS("RNSVGLinearGradient", RNSVGLinearGradientProps) - RN_GPUI_SVG_PROPS("RNSVGRadialGradient", RNSVGRadialGradientProps) - RN_GPUI_SVG_PROPS("RNSVGText", RNSVGTextProps) - RN_GPUI_SVG_PROPS("RNSVGTSpan", RNSVGTSpanProps) - RN_GPUI_SVG_PROPS("RNSVGFilter", RNSVGFilterProps) - RN_GPUI_SVG_PROPS("RNSVGFeBlend", RNSVGFeBlendProps) - RN_GPUI_SVG_PROPS("RNSVGFeColorMatrix", RNSVGFeColorMatrixProps) - RN_GPUI_SVG_PROPS("RNSVGFeComposite", RNSVGFeCompositeProps) - RN_GPUI_SVG_PROPS("RNSVGFeFlood", RNSVGFeFloodProps) - RN_GPUI_SVG_PROPS("RNSVGFeGaussianBlur", RNSVGFeGaussianBlurProps) - RN_GPUI_SVG_PROPS("RNSVGFeMerge", RNSVGFeMergeProps) - RN_GPUI_SVG_PROPS("RNSVGFeOffset", RNSVGFeOffsetProps) -#undef RN_GPUI_SVG_PROPS - return folly::dynamic::object(); -} - -} // namespace - -void rn_gpui_install_svg_module() { - for (const char* component : kSvgComponents) { - registerComponentProps( - component, [](const std::string& name, const ShadowView& view) { - if (!view.props) - return std::string("{}"); - return folly::toJson(svgPropsJson(name, *view.props)); - }); - } -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/modules/svg/desktop/src/cache.rs b/vendor/react-native-gpui/modules/svg/desktop/src/cache.rs deleted file mode 100644 index ff7fab5fb4..0000000000 --- a/vendor/react-native-gpui/modules/svg/desktop/src/cache.rs +++ /dev/null @@ -1,156 +0,0 @@ -//! The rasters, kept by key in a cache bounded by bytes. -//! -//! One cache for every node, so identical icons share one image. It holds the -//! images strongly: an icon that scrolls off the screen is still here when it -//! comes back. When the total passes the limit the image used longest ago goes -//! first. The limit is 64 MB; `RN_GPUI_SVG_CACHE_MB` sets another. - -use crate::key::Key; -use std::collections::HashMap; -use std::sync::{Arc, Mutex, OnceLock}; - -pub const DEFAULT_LIMIT_BYTES: usize = 64 * 1024 * 1024; - -struct Entry { - image: Arc, - bytes: usize, - used: u64, -} - -pub struct Cache { - limit: usize, - bytes: usize, - clock: u64, - entries: HashMap, -} - -fn size_of(image: &gpui::RenderImage) -> usize { - let size = image.size(0); - size.width.0.max(0) as usize * size.height.0.max(0) as usize * 4 -} - -impl Cache { - pub fn new(limit: usize) -> Self { - Self { - limit, - bytes: 0, - clock: 0, - entries: HashMap::new(), - } - } - - pub fn get(&mut self, key: &Key) -> Option> { - self.clock += 1; - let clock = self.clock; - let entry = self.entries.get_mut(key)?; - entry.used = clock; - Some(entry.image.clone()) - } - - pub fn insert(&mut self, key: Key, image: Arc) { - self.clock += 1; - let bytes = size_of(&image); - if let Some(old) = self.entries.insert( - key, - Entry { - image, - bytes, - used: self.clock, - }, - ) { - self.bytes -= old.bytes; - } - self.bytes += bytes; - // The newest image stays even when it alone is over the limit. - while self.bytes > self.limit && self.entries.len() > 1 { - let Some(oldest) = self - .entries - .iter() - .min_by_key(|(_, entry)| entry.used) - .map(|(key, _)| *key) - else { - break; - }; - if let Some(removed) = self.entries.remove(&oldest) { - self.bytes -= removed.bytes; - } - } - } - - pub fn bytes(&self) -> usize { - self.bytes - } - - pub fn len(&self) -> usize { - self.entries.len() - } -} - -pub fn global() -> &'static Mutex { - static CACHE: OnceLock> = OnceLock::new(); - CACHE.get_or_init(|| { - let limit = std::env::var("RN_GPUI_SVG_CACHE_MB") - .ok() - .and_then(|value| value.parse::().ok()) - .map_or(DEFAULT_LIMIT_BYTES, |megabytes| megabytes * 1024 * 1024); - Mutex::new(Cache::new(limit)) - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn image(side: u32) -> Arc { - let buffer = - image::ImageBuffer::from_raw(side, side, vec![0u8; (side * side * 4) as usize]) - .expect("a buffer"); - Arc::new(gpui::RenderImage::new(smallvec::SmallVec::from_const([ - image::Frame::new(buffer), - ]))) - } - - fn key(n: u64) -> Key { - crate::key::test_key(n) - } - - #[test] - fn it_returns_what_it_was_given_and_counts_bytes() { - let mut cache = Cache::new(1 << 20); - let a = image(10); - cache.insert(key(1), a.clone()); - assert!(Arc::ptr_eq(&cache.get(&key(1)).unwrap(), &a)); - assert!(cache.get(&key(2)).is_none()); - assert_eq!(cache.bytes(), 400); - // Replacing a key does not count its old image twice. - cache.insert(key(1), image(20)); - assert_eq!(cache.bytes(), 1600); - assert_eq!(cache.len(), 1); - } - - #[test] - fn it_stays_within_its_limit_and_drops_the_image_used_longest_ago() { - // Three 10 by 10 images are 1200 bytes; the limit holds two. - let mut cache = Cache::new(900); - cache.insert(key(1), image(10)); - cache.insert(key(2), image(10)); - // Using the first makes the second the oldest. - assert!(cache.get(&key(1)).is_some()); - cache.insert(key(3), image(10)); - assert!(cache.bytes() <= 900); - assert!(cache.get(&key(1)).is_some()); - assert!(cache.get(&key(2)).is_none()); - assert!(cache.get(&key(3)).is_some()); - } - - #[test] - fn one_image_over_the_limit_is_still_kept() { - let mut cache = Cache::new(100); - cache.insert(key(1), image(10)); - assert_eq!(cache.len(), 1); - assert!(cache.get(&key(1)).is_some()); - cache.insert(key(2), image(10)); - assert_eq!(cache.len(), 1); - assert!(cache.get(&key(2)).is_some()); - } -} diff --git a/vendor/react-native-gpui/modules/svg/desktop/src/key.rs b/vendor/react-native-gpui/modules/svg/desktop/src/key.rs deleted file mode 100644 index 551bd439d3..0000000000 --- a/vendor/react-native-gpui/modules/svg/desktop/src/key.rs +++ /dev/null @@ -1,173 +0,0 @@ -//! The cache key of a drawing: what decides its pixels, hashed in place. -//! -//! The document string is the expensive part of a render, so a lookup never -//! builds it: the key is a structural hash of the node, its props and its -//! children (the resolved colours are props), the frame's size and the scale. -//! A position is not part of it, so identical icons at different places share -//! one raster. - -use react_native_gpui::extensions::ComponentNode; -use rn_gpui_sys::ffi::RectF; -use serde_json::Value; -use std::collections::hash_map::DefaultHasher; -use std::hash::Hasher; - -/// Two independent 64 bit hashes of the same input. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct Key(u64, u64); - -struct Pair(DefaultHasher, DefaultHasher); - -impl Hasher for Pair { - fn write(&mut self, bytes: &[u8]) { - self.0.write(bytes); - self.1.write(bytes); - } - - fn finish(&self) -> u64 { - self.0.finish() - } -} - -fn hash_value(input: &Value, hasher: &mut Pair) { - match input { - Value::Null => hasher.write_u8(0), - Value::Bool(flag) => { - hasher.write_u8(1); - hasher.write_u8(u8::from(*flag)); - } - Value::Number(number) => { - hasher.write_u8(2); - hasher.write_u64(number.as_f64().unwrap_or(f64::NAN).to_bits()); - } - Value::String(text) => { - hasher.write_u8(3); - hasher.write_usize(text.len()); - hasher.write(text.as_bytes()); - } - Value::Array(items) => { - hasher.write_u8(4); - hasher.write_usize(items.len()); - for item in items { - hash_value(item, hasher); - } - } - Value::Object(entries) => { - hasher.write_u8(5); - hasher.write_usize(entries.len()); - for (name, entry) in entries { - hasher.write_usize(name.len()); - hasher.write(name.as_bytes()); - hash_value(entry, hasher); - } - } - } -} - -fn node(node: &ComponentNode, hasher: &mut Pair) { - hasher.write_usize(node.component.len()); - hasher.write(node.component.as_bytes()); - hash_value(&node.props, hasher); - hasher.write_usize(node.children.len()); - for child in &node.children { - self::node(child, hasher); - } -} - -pub fn node_key(root: &ComponentNode, frame: RectF, scale: f32) -> Key { - let mut hasher = Pair(DefaultHasher::new(), DefaultHasher::new()); - hasher.1.write_u8(0x5a); - node(root, &mut hasher); - hasher.write_u32(frame.w.to_bits()); - hasher.write_u32(frame.h.to_bits()); - hasher.write_u32(scale.to_bits()); - Key(hasher.0.finish(), hasher.1.finish()) -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - use std::sync::Arc; - - fn shape(props: Value) -> ComponentNode { - ComponentNode { - component: "RNSVGPath".into(), - tag: 1, - frame: RectF { - x: 0.0, - y: 0.0, - w: 10.0, - h: 10.0, - }, - scale: (1.0, 1.0), - props: Arc::new(props), - parent: None, - children: Vec::new(), - } - } - - fn svg(color: u32, d: &str) -> ComponentNode { - let mut root = shape(json!({"color": color, "vbWidth": 24, "vbHeight": 24})); - root.component = "RNSVGSvgView".into(); - root.children.push(shape( - json!({"d": d, "fill": {"type": 0, "payload": color}}), - )); - root - } - - const FRAME: RectF = RectF { - x: 0.0, - y: 0.0, - w: 16.0, - h: 16.0, - }; - - #[test] - fn the_same_drawing_has_the_same_key_wherever_it_is() { - let a = node_key(&svg(0xff112233, "M0 0L1 1"), FRAME, 2.0); - let mut moved = svg(0xff112233, "M0 0L1 1"); - moved.frame.x = 99.0; - moved.tag = 7; - assert_eq!(a, node_key(&moved, RectF { x: 40.0, ..FRAME }, 2.0)); - assert_eq!(a, node_key(&svg(0xff112233, "M0 0L1 1"), FRAME, 2.0)); - } - - #[test] - fn anything_that_changes_the_pixels_changes_the_key() { - let base = node_key(&svg(0xff112233, "M0 0L1 1"), FRAME, 2.0); - // A colour, a path, a child, the size and the scale each make a new key. - assert_ne!(base, node_key(&svg(0xff112234, "M0 0L1 1"), FRAME, 2.0)); - assert_ne!(base, node_key(&svg(0xff112233, "M0 0L1 2"), FRAME, 2.0)); - let mut more = svg(0xff112233, "M0 0L1 1"); - more.children.push(shape(json!({"d": "M1 1"}))); - assert_ne!(base, node_key(&more, FRAME, 2.0)); - assert_ne!( - base, - node_key( - &svg(0xff112233, "M0 0L1 1"), - RectF { w: 17.0, ..FRAME }, - 2.0 - ) - ); - assert_ne!(base, node_key(&svg(0xff112233, "M0 0L1 1"), FRAME, 1.0)); - } - - #[test] - fn values_of_different_kinds_do_not_collide() { - let flag = node_key(&shape(json!({"a": true})), FRAME, 1.0); - let text = node_key(&shape(json!({"a": "true"})), FRAME, 1.0); - let number = node_key(&shape(json!({"a": 1})), FRAME, 1.0); - assert_ne!(flag, text); - assert_ne!(flag, number); - assert_ne!( - node_key(&shape(json!({"ab": "c"})), FRAME, 1.0), - node_key(&shape(json!({"a": "bc"})), FRAME, 1.0) - ); - } -} - -#[cfg(test)] -pub fn test_key(n: u64) -> Key { - Key(n, n) -} diff --git a/vendor/react-native-gpui/modules/svg/desktop/src/lib.rs b/vendor/react-native-gpui/modules/svg/desktop/src/lib.rs deleted file mode 100644 index 1054af4b4e..0000000000 --- a/vendor/react-native-gpui/modules/svg/desktop/src/lib.rs +++ /dev/null @@ -1,609 +0,0 @@ -use gpui::{div, prelude::*, px, AnyElement, App, Window}; -use react_native_gpui::extensions::{ - register_component_renderer, ComponentNode, ComponentRenderer, -}; -use rn_gpui_sys::ffi::RectF; -use std::sync::Arc; - -mod cache; -mod key; -mod raster; - -const COMPONENTS: &[&str] = &[ - "RNSVGSvgView", - "RNSVGCircle", - "RNSVGEllipse", - "RNSVGLine", - "RNSVGPath", - "RNSVGRect", - "RNSVGGroup", - "RNSVGDefs", - "RNSVGClipPath", - "RNSVGLinearGradient", - "RNSVGRadialGradient", - "RNSVGText", - "RNSVGTSpan", - "RNSVGMask", - "RNSVGSymbol", - "RNSVGPattern", - "RNSVGMarker", - "RNSVGTextPath", - "RNSVGUse", - "RNSVGFilter", - "RNSVGFeBlend", - "RNSVGFeColorMatrix", - "RNSVGFeComposite", - "RNSVGFeFlood", - "RNSVGFeGaussianBlur", - "RNSVGFeMerge", - "RNSVGFeOffset", -]; - -struct SvgRenderer; - -impl ComponentRenderer for SvgRenderer { - // The SVG document is drawn from the shapes under its root. - fn reads_children(&self) -> bool { - true - } - - fn render( - &self, - node: &ComponentNode, - window: &mut Window, - cx: &mut App, - ) -> Option { - if node.component != "RNSVGSvgView" { - return Some(div().into_any_element()); - } - // The frame is in unscaled coordinates and this element is painted - // scaled, exactly as `ComponentRenderer::render` documents, so the box - // has to be scaled the same way core scales the element it would have - // built. `size_full()` sized the image to its parent instead: the - // document is rasterized at the window's scale factor, and an image - // carries no intrinsic size, so every SVG stretched to fill whatever - // surrounded it and painted over the text below it. - let frame = node.frame; - let (scale_x, scale_y) = node.scale; - let width = frame.w * scale_x; - let height = frame.h * scale_y; - let scale = window.scale_factor(); - let image = raster::image_for(node, frame, scale, window, cx); - // Chrome paints an inline SVG at a whole CSS pixel: a box laid out at - // 2.5 is drawn at 3. The image is placed the same way, so a 15 point - // icon centred in a 20 point button lands where the web app's does. - Some( - gpui::canvas( - |bounds, _, _| bounds, - move |_, bounds, window, _| { - let snapped = gpui::Bounds::new( - gpui::point( - px((bounds.origin.x.as_f32() + 0.5).floor()), - px((bounds.origin.y.as_f32() + 0.5).floor()), - ), - bounds.size, - ); - if let Some(image) = &image { - let _ = window.paint_image( - snapped, - snapped, - gpui::Corners::default(), - image.clone(), - 0, - false, - ); - } - }, - ) - .w(px(width)) - .h(px(height)) - .into_any_element(), - ) - } -} - -pub fn rn_gpui_register() { - for component in COMPONENTS { - register_component_renderer(*component, Arc::new(SvgRenderer)); - } -} - -/// Where one coverage sample sits, so a shape can be drawn once per sample. -#[derive(Clone, Copy)] -pub(crate) struct Sample { - /// The sample's offset from the pixel centre, in device pixels. - pub(crate) dx: f32, - pub(crate) dy: f32, - /// Device pixels per CSS pixel. - pub(crate) scale: f32, -} - -/// Chrome rasterises with four coverage samples per pixel at these offsets (in -/// pixels from the centre): the standard Direct3D 4x pattern. A pixel is -/// therefore never covered by anything but 0, 1/4, 1/2, 3/4 or all, and the edge -/// of an icon takes the same five steps here. -pub(crate) const SAMPLE_OFFSETS: [(f32, f32); 4] = [ - (-2.0 / 16.0, -6.0 / 16.0), - (6.0 / 16.0, -2.0 / 16.0), - (-6.0 / 16.0, 2.0 / 16.0), - (2.0 / 16.0, 6.0 / 16.0), -]; - -pub(crate) fn svg_document(node: &ComponentNode, frame: RectF, sample: Option) -> String { - let props = &node.props; - let mut attributes = format!( - "xmlns=\"http://www.w3.org/2000/svg\" width=\"{}\" height=\"{}\"", - svg_number(frame.w), - svg_number(frame.h) - ); - if sample.is_some() { - attributes.push_str(" shape-rendering=\"crispEdges\""); - } - for (name, attribute) in [ - ("color", "color"), - ("fill", "fill"), - ("stroke", "stroke"), - ("strokeWidth", "stroke-width"), - ("fillOpacity", "fill-opacity"), - ("strokeOpacity", "stroke-opacity"), - ("opacity", "opacity"), - ] { - if let Some(value) = props.get(name).filter(|value| !value.is_null()) { - if let Some(value) = svg_value(value) { - attributes.push_str(&format!(" {attribute}=\"{}\"", svg_escape(&value))); - } - } - } - if let Some(cap) = props - .get("strokeLinecap") - .and_then(serde_json::Value::as_i64) - { - let cap = ["butt", "round", "square"] - .get(cap as usize) - .copied() - .unwrap_or("butt"); - attributes.push_str(&format!(" stroke-linecap=\"{cap}\"")); - } - if let Some(join) = props - .get("strokeLinejoin") - .and_then(serde_json::Value::as_i64) - { - let join = ["miter", "round", "bevel"] - .get(join as usize) - .copied() - .unwrap_or("miter"); - attributes.push_str(&format!(" stroke-linejoin=\"{join}\"")); - } - let view_box = match ( - props.get("vbWidth").and_then(serde_json::Value::as_f64), - props.get("vbHeight").and_then(serde_json::Value::as_f64), - ) { - (Some(width), Some(height)) if width > 0.0 && height > 0.0 => { - let min_x = props - .get("minX") - .and_then(serde_json::Value::as_f64) - .unwrap_or(0.0); - let min_y = props - .get("minY") - .and_then(serde_json::Value::as_f64) - .unwrap_or(0.0); - let align = props.get("align").and_then(serde_json::Value::as_str); - let mode = match props - .get("meetOrSlice") - .and_then(serde_json::Value::as_i64) - .unwrap_or(0) - { - 1 => "slice", - 2 => "none", - _ => "meet", - }; - Some((min_x, min_y, width, height, align, mode)) - } - _ => None, - }; - match (view_box, sample) { - (Some((min_x, min_y, width, height, align, mode)), sample) => { - // The sample's shift in user units: how many of them one device - // pixel covers depends on how the view box is fitted to the frame. - let (mut min_x, mut min_y) = (min_x, min_y); - if let Some(sample) = sample { - let fit_x = f64::from(frame.w * sample.scale) / width; - let fit_y = f64::from(frame.h * sample.scale) / height; - let (unit_x, unit_y) = match (align, mode) { - (Some("none"), _) | (Some(_), "none") => (fit_x, fit_y), - (_, "slice") => (fit_x.max(fit_y), fit_x.max(fit_y)), - _ => (fit_x.min(fit_y), fit_x.min(fit_y)), - }; - min_x += f64::from(sample.dx) / unit_x; - min_y += f64::from(sample.dy) / unit_y; - } - attributes.push_str(&format!( - " viewBox=\"{} {} {} {}\"", - svg_number(min_x as f32), - svg_number(min_y as f32), - svg_number(width as f32), - svg_number(height as f32) - )); - if let Some(align) = align { - attributes.push_str(&format!( - " preserveAspectRatio=\"{} {}\"", - svg_escape(align), - mode - )); - } - } - (None, Some(sample)) => { - // Without a view box the user unit is the CSS pixel; one is added - // only to carry the shift. - attributes.push_str(&format!( - " viewBox=\"{} {} {} {}\"", - svg_number(sample.dx / sample.scale), - svg_number(sample.dy / sample.scale), - svg_number(frame.w), - svg_number(frame.h) - )); - } - (None, None) => {} - } - let mut document = format!(""); - for child in &node.children { - svg_node(child, &mut document); - } - document.push_str(""); - document -} - -fn svg_node(node: &ComponentNode, output: &mut String) { - let props = &node.props; - let element = match node.component.as_str() { - "RNSVGCircle" => "circle", - "RNSVGEllipse" => "ellipse", - "RNSVGLine" => "line", - "RNSVGPath" => "path", - "RNSVGRect" => "rect", - "RNSVGGroup" => "g", - "RNSVGDefs" => "defs", - "RNSVGClipPath" => "clipPath", - "RNSVGLinearGradient" => "linearGradient", - "RNSVGRadialGradient" => "radialGradient", - "RNSVGMask" => "mask", - "RNSVGSymbol" => "symbol", - "RNSVGPattern" => "pattern", - "RNSVGMarker" => "marker", - "RNSVGText" => "text", - "RNSVGTSpan" => "tspan", - "RNSVGTextPath" => "textPath", - "RNSVGUse" => "use", - "RNSVGFilter" => "filter", - "RNSVGFeBlend" => "feBlend", - "RNSVGFeColorMatrix" => "feColorMatrix", - "RNSVGFeComposite" => "feComposite", - "RNSVGFeFlood" => "feFlood", - "RNSVGFeGaussianBlur" => "feGaussianBlur", - "RNSVGFeMerge" => "feMerge", - "RNSVGFeOffset" => "feOffset", - _ => "", - }; - if element.is_empty() { - for child in &node.children { - svg_node(child, output); - } - return; - } - let mut attributes = String::new(); - for name in [ - "id", - "name", - "href", - "d", - "x", - "y", - "x1", - "y1", - "x2", - "y2", - "cx", - "cy", - "r", - "rx", - "ry", - "width", - "height", - "color", - "fill", - "stroke", - "strokeWidth", - "fillOpacity", - "strokeOpacity", - "strokeDasharray", - "strokeDashoffset", - "strokeMiterlimit", - "opacity", - "fontSize", - "fontWeight", - "fontFamily", - "textLength", - "dominantBaseline", - "offset", - "stopColor", - "stopOpacity", - ] { - if !svg_property_is_set(props, name) { - continue; - } - if let Some(value) = props.get(name) { - let attribute = match name { - "strokeWidth" => "stroke-width", - "fillOpacity" => "fill-opacity", - "strokeOpacity" => "stroke-opacity", - "strokeDasharray" => "stroke-dasharray", - "strokeDashoffset" => "stroke-dashoffset", - "strokeMiterlimit" => "stroke-miterlimit", - "fontSize" => "font-size", - "fontWeight" => "font-weight", - "fontFamily" => "font-family", - "dominantBaseline" => "dominant-baseline", - "stopColor" => "stop-color", - "stopOpacity" => "stop-opacity", - other => other, - }; - let value = if value.is_null() && matches!(name, "fill" | "stroke") { - Some("none".to_owned()) - } else { - svg_value(value) - }; - if let Some(value) = value { - attributes.push_str(&format!(" {attribute}=\"{}\"", svg_escape(&value))); - } - } - } - if let Some(rule) = props - .get("fillRule") - .filter(|_| svg_property_is_set(props, "fillRule")) - .and_then(serde_json::Value::as_i64) - { - attributes.push_str(&format!( - " fill-rule=\"{}\"", - if rule == 0 { "evenodd" } else { "nonzero" } - )); - } - if let Some(cap) = props - .get("strokeLinecap") - .filter(|_| svg_property_is_set(props, "strokeLinecap")) - .and_then(serde_json::Value::as_i64) - { - let cap = ["butt", "round", "square"] - .get(cap as usize) - .copied() - .unwrap_or("butt"); - attributes.push_str(&format!(" stroke-linecap=\"{cap}\"")); - } - if let Some(join) = props - .get("strokeLinejoin") - .filter(|_| svg_property_is_set(props, "strokeLinejoin")) - .and_then(serde_json::Value::as_i64) - { - let join = ["miter", "round", "bevel"] - .get(join as usize) - .copied() - .unwrap_or("miter"); - attributes.push_str(&format!(" stroke-linejoin=\"{join}\"")); - } - if let Some(matrix) = props.get("matrix").and_then(serde_json::Value::as_array) { - let component = |index: usize| matrix.get(index).and_then(serde_json::Value::as_f64); - let values = match matrix.len() { - 6 => [0, 1, 2, 3, 4, 5], - 16.. => [0, 1, 4, 5, 12, 13], - _ => [usize::MAX; 6], - } - .map(component); - if let [Some(a), Some(b), Some(c), Some(d), Some(e), Some(f)] = values { - attributes.push_str(&format!(" transform=\"matrix({a} {b} {c} {d} {e} {f})\"")); - } - } - if let Some(id) = props - .get("name") - .and_then(serde_json::Value::as_str) - .filter(|id| !id.is_empty()) - { - attributes.push_str(&format!(" id=\"{}\"", svg_escape(id))); - } - if let Some(filter) = props - .get("filter") - .and_then(serde_json::Value::as_str) - .filter(|filter| !filter.is_empty()) - { - attributes.push_str(&format!(" filter=\"url(#{})\"", svg_escape(filter))); - } - if element == "filter" { - attributes.push_str(" color-interpolation-filters=\"sRGB\""); - } - if element.starts_with("fe") || element == "filter" { - attributes.push_str(&filter_primitive_attributes(props)); - } - output.push('<'); - output.push_str(element); - output.push_str(&attributes); - output.push('>'); - if element == "feMerge" { - for id in props - .get("nodes") - .and_then(serde_json::Value::as_array) - .into_iter() - .flatten() - .filter_map(serde_json::Value::as_str) - { - output.push_str(&format!("", svg_escape(id))); - } - } - for child in &node.children { - svg_node(child, output); - } - output.push_str("'); -} - -fn filter_primitive_attributes(props: &serde_json::Value) -> String { - let mut attributes = String::new(); - let text = |name: &str| match props.get(name) { - Some(serde_json::Value::String(value)) if !value.is_empty() => Some(value.clone()), - Some(value) if value.is_array() || value.is_number() => svg_value(value), - _ => None, - }; - for (name, attribute) in [ - ("in1", "in"), - ("in2", "in2"), - ("result", "result"), - ("mode", "mode"), - ("type", "type"), - ("values", "values"), - ("operator1", "operator"), - ("k1", "k1"), - ("k2", "k2"), - ("k3", "k3"), - ("k4", "k4"), - ("dx", "dx"), - ("dy", "dy"), - ("edgeMode", "edgeMode"), - ("floodOpacity", "flood-opacity"), - ("filterUnits", "filterUnits"), - ("primitiveUnits", "primitiveUnits"), - ] { - if let Some(value) = text(name) { - attributes.push_str(&format!(" {attribute}=\"{}\"", svg_escape(&value))); - } - } - if let Some(color) = props.get("floodColor").and_then(svg_value) { - attributes.push_str(&format!(" flood-color=\"{}\"", svg_escape(&color))); - } - let deviation = |name: &str| props.get(name).and_then(serde_json::Value::as_f64); - if let Some(x) = deviation("stdDeviationX") { - let y = deviation("stdDeviationY").unwrap_or(x); - attributes.push_str(&format!(" stdDeviation=\"{x} {y}\"")); - } - attributes -} - -fn svg_property_is_set(props: &serde_json::Value, name: &str) -> bool { - if !matches!( - name, - "fill" - | "fillOpacity" - | "fillRule" - | "stroke" - | "strokeWidth" - | "strokeOpacity" - | "strokeLinecap" - | "strokeLinejoin" - | "strokeDasharray" - | "strokeDashoffset" - | "strokeMiterlimit" - ) { - return true; - } - props - .get("propList") - .and_then(serde_json::Value::as_array) - .is_none_or(|properties| { - properties - .iter() - .any(|property| property.as_str() == Some(name)) - }) -} - -fn svg_value(value: &serde_json::Value) -> Option { - match value.get("type").and_then(serde_json::Value::as_i64) { - Some(1) => { - return value - .get("brushRef") - .and_then(serde_json::Value::as_str) - .map(|id| format!("url(#{id})")) - } - Some(2) => return Some("currentColor".to_owned()), - Some(3) => return Some("context-fill".to_owned()), - Some(4) => return Some("context-stroke".to_owned()), - _ => {} - } - - if let Some(number) = value.as_f64() { - if number < 0.0 && number.fract() == 0.0 { - return Some(format!("#{:06x}", (number as i64 as u32) & 0x00ff_ffff)); - } - if (0x0100_0000..=0xffff_ffff).contains(&(number as u64)) { - let argb = number as u32; - return Some(format!( - "rgba({}, {}, {}, {})", - (argb >> 16) & 0xff, - (argb >> 8) & 0xff, - argb & 0xff, - ((argb >> 24) & 0xff) as f32 / 255.0 - )); - } - return Some(svg_number(number as f32)); - } - if let Some(value) = value.as_str() { - return Some(value.to_owned()); - } - if let Some(value) = value.as_array() { - return Some( - value - .iter() - .filter_map(svg_value) - .collect::>() - .join(" "), - ); - } - value - .get("payload") - .and_then(svg_value) - .or_else(|| value.get("value").and_then(svg_value)) -} - -fn svg_escape(value: &str) -> String { - value - .replace('&', "&") - .replace('"', """) - .replace('<', "<") - .replace('>', ">") -} - -fn svg_number(value: f32) -> String { - if value.fract() == 0.0 { - format!("{value:.0}") - } else { - value.to_string() - } -} - -#[cfg(test)] -mod svg_paint_tests { - use super::{svg_property_is_set, svg_value}; - use serde_json::json; - - #[test] - fn brushes_keep_current_color_and_reference_semantics() { - assert_eq!( - svg_value(&json!({"type": 2})).as_deref(), - Some("currentColor") - ); - assert_eq!( - svg_value(&json!({"type": 1, "brushRef": "gradient"})).as_deref(), - Some("url(#gradient)") - ); - assert_eq!( - svg_value(&json!({"type": 0, "payload": 0xff64d2ff_u32})).as_deref(), - Some("rgba(100, 210, 255, 1)") - ); - } - - #[test] - fn default_black_fill_does_not_override_inherited_none() { - let child = json!({"fill": {"type": 0, "payload": 0xff000000_u32}, "strokeLinecap": 0, "propList": []}); - assert!(!svg_property_is_set(&child, "fill")); - assert!(!svg_property_is_set(&child, "strokeLinecap")); - let group = json!({"fill": null, "stroke": {"type": 2}, "propList": ["fill", "stroke"]}); - assert!(svg_property_is_set(&group, "fill")); - assert!(svg_property_is_set(&group, "stroke")); - } -} diff --git a/vendor/react-native-gpui/modules/svg/desktop/src/raster.rs b/vendor/react-native-gpui/modules/svg/desktop/src/raster.rs deleted file mode 100644 index 87a332359f..0000000000 --- a/vendor/react-native-gpui/modules/svg/desktop/src/raster.rs +++ /dev/null @@ -1,477 +0,0 @@ -//! Turning a node into the image it is drawn as, and when to do it. -//! -//! A drawing is found by its [`Key`] in the shared cache, which builds no -//! document. Only a miss builds the four documents (one per coverage sample) and -//! rasterises them. A small image with nothing already on screen for its node is -//! drawn right away, so a row that scrolls in has its icon on the first frame. -//! Anything else is drawn on a background thread while the node keeps showing -//! its previous image, if it has one, and is built again when the new one is -//! ready. - -use crate::cache::{self, Cache}; -use crate::key::{node_key, Key}; -use crate::{svg_document, Sample, SAMPLE_OFFSETS}; -use gpui::{App, Window}; -use react_native_gpui::extensions::{rendering_node, ComponentNode, NodeHandle}; -use rn_gpui_sys::ffi::RectF; -use std::collections::{HashMap, HashSet}; -use std::sync::{Arc, Mutex, OnceLock}; -use std::time::Instant; - -/// Images up to this many device pixels are drawn on the main thread when their -/// node has nothing to show yet: about 48 CSS pixels square at a scale of 2. -const SYNC_MAX_PIXELS: i64 = 96 * 96; - -/// Below this many device pixels the four samples are drawn one after the other: -/// each takes less time than starting a thread for it. -const PARALLEL_MIN_PIXELS: i64 = 128 * 128; - -/// `RN_GPUI_SVG_TRACE=1` logs every drawing that is rasterised: its size, how -/// long each coverage sample took and how long they took together. With -/// `RN_GPUI_SVG_SYNC=1` every drawing is rasterised on the main thread. -fn setting(name: &str) -> bool { - std::env::var(name).is_ok_and(|value| value == "1") -} - -fn trace() -> bool { - static TRACE: OnceLock = OnceLock::new(); - *TRACE.get_or_init(|| setting("RN_GPUI_SVG_TRACE")) -} - -fn force_sync() -> bool { - static SYNC: OnceLock = OnceLock::new(); - *SYNC.get_or_init(|| setting("RN_GPUI_SVG_SYNC")) -} - -/// The image each node showed last, so a node whose drawing changes keeps -/// showing it until the new one is ready. -fn shown() -> &'static Mutex>> { - static SHOWN: OnceLock>>> = OnceLock::new(); - SHOWN.get_or_init(|| Mutex::new(HashMap::new())) -} - -/// Drawings being rasterised, with the nodes waiting for each. -fn pending() -> &'static Mutex>> { - static PENDING: OnceLock>>> = OnceLock::new(); - PENDING.get_or_init(|| Mutex::new(HashMap::new())) -} - -/// Drawings the renderer could not rasterise, which are not tried again. -fn failed() -> &'static Mutex> { - static FAILED: OnceLock>> = OnceLock::new(); - FAILED.get_or_init(|| Mutex::new(HashSet::new())) -} - -fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { - mutex - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) -} - -fn has_filter(node: &ComponentNode) -> bool { - node.component == "RNSVGFilter" || node.children.iter().any(has_filter) -} - -/// The image in the cache for `key`, or the result of `make`, which is stored. -pub fn get_or_make( - cache: &Mutex, - key: Key, - make: impl FnOnce() -> Option>, -) -> Option> { - if let Some(image) = lock(cache).get(&key) { - return Some(image); - } - let image = make()?; - lock(cache).insert(key, image.clone()); - Some(image) -} - -/// The image `node` is drawn as now, or what it shows meanwhile. -pub fn image_for( - node: &ComponentNode, - frame: RectF, - scale: f32, - window: &mut Window, - cx: &mut App, -) -> Option> { - let key = node_key(node, frame, scale); - let remember = |image: &Arc| { - lock(shown()).insert(node.tag, image.clone()); - }; - if let Some(image) = lock(cache::global()).get(&key) { - remember(&image); - return Some(image); - } - let previous = lock(shown()).get(&node.tag).cloned(); - if lock(failed()).contains(&key) { - return previous; - } - let pixels = (frame.w * scale).round() as i64 * (frame.h * scale).round() as i64; - let small = pixels <= SYNC_MAX_PIXELS && !has_filter(node); - if force_sync() || (previous.is_none() && small) { - let renderer = cx.svg_renderer(); - let image = get_or_make(cache::global(), key, || { - sampled_image(&renderer, node, frame, scale) - }); - match &image { - Some(image) => remember(image), - None => { - lock(failed()).insert(key); - } - } - return image; - } - request(key, node.clone(), frame, scale, window, cx); - previous -} - -/// Rasterises `node` on a background thread, once for every node that asks for -/// the same drawing, and builds the nodes again when it is done. -fn request( - key: Key, - node: ComponentNode, - frame: RectF, - scale: f32, - window: &mut Window, - cx: &mut App, -) { - let Some(handle) = rendering_node() else { - return; - }; - { - let mut pending = lock(pending()); - if let Some(waiting) = pending.get_mut(&key) { - waiting.push(handle); - return; - } - pending.insert(key, vec![handle]); - } - let renderer = cx.svg_renderer(); - let work = cx - .background_executor() - .spawn(async move { sampled_image(&renderer, &node, frame, scale) }); - window - .spawn(cx, async move |cx| { - let image = work.await; - match &image { - Some(image) => lock(cache::global()).insert(key, image.clone()), - None => { - lock(failed()).insert(key); - } - } - let waiting = lock(pending()).remove(&key).unwrap_or_default(); - let _ = cx.update(|_, cx| { - for handle in &waiting { - handle.notify(cx); - } - }); - }) - .detach(); -} - -/// Draws the document at the window's scale, once per coverage sample without -/// antialiasing, and averages the samples. The samples are rasterised side by -/// side and combined in a fixed order, so the pixels do not depend on timing. -pub fn sampled_image( - renderer: &gpui::SvgRenderer, - node: &ComponentNode, - frame: RectF, - scale: f32, -) -> Option> { - let width = (frame.w * scale).round() as i32; - let height = (frame.h * scale).round() as i32; - if width < 1 || height < 1 { - return None; - } - let size = gpui::size(gpui::DevicePixels(width), gpui::DevicePixels(height)); - let started = Instant::now(); - let render = |(dx, dy): (f32, f32)| -> Option<(Vec, f64)> { - let sample_started = Instant::now(); - let document = svg_document(node, frame, Some(Sample { dx, dy, scale })); - let parsed = renderer.parse_svg(document.as_bytes()).ok()?; - let rendered = renderer - .render_parsed(&parsed, gpui::SvgSize::ExactSize(size)) - .ok()?; - rendered.as_bytes(0).map(|bytes| { - ( - bytes.to_vec(), - sample_started.elapsed().as_secs_f64() * 1000.0, - ) - }) - }; - let samples: Vec, f64)>> = - if i64::from(width) * i64::from(height) < PARALLEL_MIN_PIXELS { - SAMPLE_OFFSETS - .iter() - .map(|offset| render(*offset)) - .collect() - } else { - std::thread::scope(|scope| { - let workers: Vec<_> = SAMPLE_OFFSETS - .iter() - .map(|offset| scope.spawn(move || render(*offset))) - .collect(); - workers - .into_iter() - .map(|worker| worker.join().ok().flatten()) - .collect() - }) - }; - if trace() { - let times: Vec = samples - .iter() - .map(|sample| { - sample - .as_ref() - .map_or("failed".into(), |(_, ms)| format!("{ms:.1}")) - }) - .collect(); - eprintln!( - "[svg] {width}x{height} samples_ms=[{}] wall_ms={:.1}", - times.join(", "), - started.elapsed().as_secs_f64() * 1000.0 - ); - } - let samples: Vec>> = samples - .into_iter() - .map(|sample| sample.map(|(bytes, _)| bytes)) - .collect(); - average(&samples, width as u32, height as u32) -} - -/// Averages the samples: BGRA with straight alpha, colour weighted by alpha. -fn average(samples: &[Option>], width: u32, height: u32) -> Option> { - let length = width as usize * height as usize * 4; - let mut sum = vec![0f32; length]; - for bytes in samples { - let bytes = bytes.as_ref()?; - if bytes.len() != length { - return None; - } - for (total, pixel) in sum.chunks_exact_mut(4).zip(bytes.chunks_exact(4)) { - let alpha = f32::from(pixel[3]); - total[0] += f32::from(pixel[0]) * alpha; - total[1] += f32::from(pixel[1]) * alpha; - total[2] += f32::from(pixel[2]) * alpha; - total[3] += alpha; - } - } - let count = samples.len() as f32; - let mut out = Vec::with_capacity(sum.len()); - for total in sum.chunks_exact(4) { - if total[3] <= 0.0 { - out.extend_from_slice(&[0, 0, 0, 0]); - continue; - } - let blue = (total[0] / total[3]).round().clamp(0.0, 255.0); - let green = (total[1] / total[3]).round().clamp(0.0, 255.0); - let red = (total[2] / total[3]).round().clamp(0.0, 255.0); - // Half coverage is 127.5 of 255, which the alpha channel cannot hold. - // Chrome blends the exact half, and the result then rounds away from - // the ink's own side: toward light under dark ink and toward dark - // under light ink, so the alpha rounds the other way to match. - let alpha = total[3] / count; - let alpha = if (alpha.fract() - 0.5).abs() < 1e-3 { - let luma = 0.299 * red + 0.587 * green + 0.114 * blue; - if luma < 128.0 { - alpha.floor() - } else { - alpha.ceil() - } - } else { - alpha.round() - }; - out.extend_from_slice(&[ - blue as u8, - green as u8, - red as u8, - alpha.clamp(0.0, 255.0) as u8, - ]); - } - let buffer = image::ImageBuffer::from_raw(width, height, out)?; - Some(Arc::new(gpui::RenderImage::new( - smallvec::SmallVec::from_const([image::Frame::new(buffer)]), - ))) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; - - fn image() -> Arc { - let buffer = image::ImageBuffer::from_raw(2, 2, vec![0u8; 16]).expect("a buffer"); - Arc::new(gpui::RenderImage::new(smallvec::SmallVec::from_const([ - image::Frame::new(buffer), - ]))) - } - - #[test] - fn a_hit_makes_nothing_and_a_miss_makes_once() { - let cache = Mutex::new(Cache::new(1 << 20)); - let made = AtomicUsize::new(0); - let make = || { - made.fetch_add(1, Ordering::SeqCst); - Some(image()) - }; - let key = crate::key::test_key(1); - let first = get_or_make(&cache, key, make).unwrap(); - assert_eq!(made.load(Ordering::SeqCst), 1); - // The second lookup is a hit: the closure, which is where a document - // string would be built, is not called. - let second = get_or_make(&cache, key, || panic!("a hit must not build anything")).unwrap(); - assert!(Arc::ptr_eq(&first, &second)); - assert_eq!(made.load(Ordering::SeqCst), 1); - } - - #[test] - fn a_drawing_that_cannot_be_made_is_not_cached() { - let cache = Mutex::new(Cache::new(1 << 20)); - let key = crate::key::test_key(2); - assert!(get_or_make(&cache, key, || None).is_none()); - assert_eq!(lock(&cache).len(), 0); - } - - #[test] - fn averaging_four_equal_samples_gives_the_sample() { - let pixels = vec![10u8, 20, 30, 255, 0, 0, 0, 0]; - let samples = vec![ - Some(pixels.clone()), - Some(pixels.clone()), - Some(pixels.clone()), - Some(pixels), - ]; - let averaged = average(&samples, 2, 1).unwrap(); - assert_eq!( - averaged.as_bytes(0).unwrap(), - &[10, 20, 30, 255, 0, 0, 0, 0] - ); - } - - #[test] - fn a_missing_sample_gives_no_image() { - assert!(average(&[Some(vec![0; 4]), None], 1, 1).is_none()); - } - - fn node( - component: &str, - props: serde_json::Value, - children: Vec, - ) -> ComponentNode { - ComponentNode { - component: component.into(), - tag: 1, - frame: RectF { - x: 0.0, - y: 0.0, - w: 24.0, - h: 24.0, - }, - scale: (1.0, 1.0), - props: Arc::new(props), - parent: None, - children, - } - } - - fn drawings() -> Vec { - use serde_json::json; - let fill = json!({"type": 0, "payload": 0xff336699_u32}); - let shape = |component: &str, props: serde_json::Value| { - let mut full = json!({"fill": fill, "propList": ["fill"]}); - full.as_object_mut() - .unwrap() - .extend(props.as_object().unwrap().clone()); - node(component, full, vec![]) - }; - let root = |children| { - node( - "RNSVGSvgView", - json!({"vbWidth": 24, "vbHeight": 24, "align": "xMidYMid", "meetOrSlice": 0}), - children, - ) - }; - let blurred = node( - "RNSVGGroup", - json!({"filter": "f", "propList": []}), - vec![shape( - "RNSVGRect", - json!({"x": 6, "y": 6, "width": 12, "height": 12}), - )], - ); - let filter = node( - "RNSVGDefs", - json!({}), - vec![node( - "RNSVGFilter", - json!({"name": "f", "x": 0, "y": 0, "width": 24, "height": 24, "filterUnits": "userSpaceOnUse", "primitiveUnits": "userSpaceOnUse"}), - vec![node( - "RNSVGFeGaussianBlur", - json!({"stdDeviationX": 2, "stdDeviationY": 2}), - vec![], - )], - )], - ); - vec![ - root(vec![shape("RNSVGPath", json!({"d": "M2 2L22 2L12 22Z"}))]), - root(vec![shape( - "RNSVGCircle", - json!({"cx": 12, "cy": 12, "r": 7.3}), - )]), - root(vec![shape( - "RNSVGRect", - json!({"x": 3.3, "y": 4.1, "width": 15, "height": 9, "rx": 3, "matrix": [0.94, -0.34, 0.34, 0.94, 0, 0]}), - )]), - root(vec![filter, blurred]), - ] - } - - /// The four samples one after the other, as the module drew them before. - fn sequential( - renderer: &gpui::SvgRenderer, - node: &ComponentNode, - frame: RectF, - scale: f32, - ) -> Option> { - let width = (frame.w * scale).round() as i32; - let height = (frame.h * scale).round() as i32; - let size = gpui::size(gpui::DevicePixels(width), gpui::DevicePixels(height)); - let samples: Vec>> = SAMPLE_OFFSETS - .iter() - .map(|&(dx, dy)| { - let document = svg_document(node, frame, Some(Sample { dx, dy, scale })); - let parsed = renderer.parse_svg(document.as_bytes()).ok()?; - let rendered = renderer - .render_parsed(&parsed, gpui::SvgSize::ExactSize(size)) - .ok()?; - rendered.as_bytes(0).map(<[u8]>::to_vec) - }) - .collect(); - average(&samples, width as u32, height as u32) - } - - #[test] - fn rasterising_the_samples_side_by_side_gives_the_same_pixels() { - let renderer = gpui::SvgRenderer::new(Arc::new(())); - // 24 and 48 point frames are drawn in turn, and 80 at a scale of 2 is - // large enough to be drawn in parallel. - for (index, drawing) in drawings().iter().enumerate() { - for (side, scale) in [(24.0, 1.0), (24.0, 2.0), (80.0, 2.0)] { - let frame = RectF { - x: 0.0, - y: 0.0, - w: side, - h: side, - }; - let together = sampled_image(&renderer, drawing, frame, scale).expect("drawn"); - let apart = sequential(&renderer, drawing, frame, scale).expect("drawn"); - assert_eq!( - together.as_bytes(0).unwrap(), - apart.as_bytes(0).unwrap(), - "drawing {index} at scale {scale}" - ); - assert!(together.as_bytes(0).unwrap().iter().any(|byte| *byte != 0)); - } - } - } -} diff --git a/vendor/react-native-gpui/modules/svg/package.json b/vendor/react-native-gpui/modules/svg/package.json deleted file mode 100644 index 4443fc0343..0000000000 --- a/vendor/react-native-gpui/modules/svg/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "@react-native-gpui/svg", - "version": "15.15.0-alpha.1", - "description": "Adapter for react-native-svg (MIT): draws SVG elements with the desktop renderer", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/streetwriters/react-native-gpui-modules.git", - "directory": "modules/svg" - }, - "homepage": "https://github.com/streetwriters/react-native-gpui-modules/tree/main/modules/svg#readme", - "bugs": { - "url": "https://github.com/streetwriters/react-native-gpui-modules/issues" - }, - "files": [ - "desktop", - "react-native.config.js", - "README.md", - "LICENSE", - "CHANGELOG.md", - "!**/*.test.js", - "!**/*.test.mjs", - "!**/*.test.ts", - "!**/*.test.cjs" - ], - "peerDependencies": { - "react-native": "0.87.x", - "react-native-svg": "15.15.x" - }, - "publishConfig": { - "access": "public", - "tag": "latest" - } -} diff --git a/vendor/react-native-gpui/modules/svg/react-native.config.js b/vendor/react-native-gpui/modules/svg/react-native.config.js deleted file mode 100644 index 88a9d4d06e..0000000000 --- a/vendor/react-native-gpui/modules/svg/react-native.config.js +++ /dev/null @@ -1,51 +0,0 @@ -module.exports = { - dependency: { - platforms: { - desktop: { - cmake: 'desktop', - crate: 'rn-gpui-svg', - componentCodegenPackage: 'react-native-svg', - componentSourcePackage: 'react-native-svg', - componentDescriptors: [ - 'RNSVGCircleComponentDescriptor', - 'RNSVGClipPathComponentDescriptor', - 'RNSVGDefsComponentDescriptor', - 'RNSVGFeBlendComponentDescriptor', - 'RNSVGFeColorMatrixComponentDescriptor', - 'RNSVGFeCompositeComponentDescriptor', - 'RNSVGFeFloodComponentDescriptor', - 'RNSVGFeGaussianBlurComponentDescriptor', - 'RNSVGFeMergeComponentDescriptor', - 'RNSVGFeOffsetComponentDescriptor', - 'RNSVGFilterComponentDescriptor', - 'RNSVGEllipseComponentDescriptor', - 'RNSVGForeignObjectComponentDescriptor', - 'RNSVGGroupComponentDescriptor', - 'RNSVGLinearGradientComponentDescriptor', - 'RNSVGLineComponentDescriptor', - 'RNSVGMarkerComponentDescriptor', - 'RNSVGMaskComponentDescriptor', - 'RNSVGPathComponentDescriptor', - 'RNSVGPatternComponentDescriptor', - 'RNSVGRadialGradientComponentDescriptor', - 'RNSVGRectComponentDescriptor', - 'RNSVGSymbolComponentDescriptor', - 'RNSVGTextComponentDescriptor', - 'RNSVGTextPathComponentDescriptor', - 'RNSVGTSpanComponentDescriptor', - 'RNSVGUseComponentDescriptor', - 'RNSVGSvgViewComponentDescriptor', - ], - componentHeaders: [ - 'react/renderer/components/rnsvg/ComponentDescriptors.h', - 'react/renderer/components/rnsvg/RNSVGComponentDescriptors.h', - ], - componentIncludeDirs: ['common/cpp'], - componentSources: [ - 'common/cpp/react/renderer/components/rnsvg/RNSVGShadowNodes.cpp', - 'common/cpp/react/renderer/components/rnsvg/RNSVGLayoutableShadowNode.cpp', - ], - }, - }, - }, -}; diff --git a/vendor/react-native-gpui/modules/worklets/CHANGELOG.md b/vendor/react-native-gpui/modules/worklets/CHANGELOG.md deleted file mode 100644 index 6456f737fe..0000000000 --- a/vendor/react-native-gpui/modules/worklets/CHANGELOG.md +++ /dev/null @@ -1,13 +0,0 @@ -# Changelog - -All notable changes to `@react-native-gpui/worklets` are listed here. Each version's section becomes the notes of its GitHub release. - -## 0.13.0-alpha.1 - 2026-11-12 - -- Added a hook that runs after each frame's animation callbacks, which Reanimated uses to apply its pending updates. - -## 0.13.0-alpha.0 - 2026-11-01 - -- First release, for `react-native-worklets` 0.13.x. -- Runs worklets on desktop, driven by the renderer's frame clock. -- Works with the npm release of `react-native-worklets`: the C++ fixes it needs for MSVC and Linux are applied to a copy in the build directory. diff --git a/vendor/react-native-gpui/modules/worklets/LICENSE b/vendor/react-native-gpui/modules/worklets/LICENSE deleted file mode 100644 index 149a0f8321..0000000000 --- a/vendor/react-native-gpui/modules/worklets/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Streetwriters - -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/vendor/react-native-gpui/modules/worklets/README.md b/vendor/react-native-gpui/modules/worklets/README.md deleted file mode 100644 index 76801618d4..0000000000 --- a/vendor/react-native-gpui/modules/worklets/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# @react-native-gpui/worklets - -Adapter for [`react-native-worklets`](https://github.com/software-mansion/react-native-reanimated/tree/main/packages/react-native-worklets) (MIT): runs worklets on desktop, driven by the renderer's frame clock. - -Part of [react-native-gpui](https://github.com/streetwriters/react-native-gpui), React Native for macOS, Windows and Linux. - -## Install - -Install it next to `react-native-worklets`: - -```sh -npm install react-native-worklets@0.13.x @react-native-gpui/worklets -``` - -Install the regular npm release of `react-native-worklets`. Its C++ needs small fixes to build with MSVC and on Linux; this package applies them to a copy in the desktop build directory and never changes `node_modules`. - -Keep using `react-native-worklets` as you do on iOS and Android; its JavaScript API is unchanged. Autolinking builds the desktop side when the app is built. - -## Documentation - -[Supported libraries](https://streetwriters.github.io/react-native-gpui/docs/supported-libraries) - -## License - -MIT. See [LICENSE](LICENSE). diff --git a/vendor/react-native-gpui/modules/worklets/desktop/CMakeLists.txt b/vendor/react-native-gpui/modules/worklets/desktop/CMakeLists.txt deleted file mode 100644 index 92ca4b53d9..0000000000 --- a/vendor/react-native-gpui/modules/worklets/desktop/CMakeLists.txt +++ /dev/null @@ -1,52 +0,0 @@ -if(NOT RN_GPUI_PROJECT_ROOT) - message(FATAL_ERROR - "@react-native-gpui/worklets was added by the platform; RN_GPUI_PROJECT_ROOT must be set by its build.rs") -endif() -set(_gpui_app_root "${RN_GPUI_PROJECT_ROOT}") -find_program(_gpui_node node REQUIRED) -execute_process( - COMMAND "${_gpui_node}" -e "process.stdout.write(require.resolve('react-native-worklets/package.json', {paths: [process.argv[1]]}))" "${_gpui_app_root}" - RESULT_VARIABLE _worklets_resolve_result - OUTPUT_VARIABLE _worklets_package_json - OUTPUT_STRIP_TRAILING_WHITESPACE) -if(NOT _worklets_resolve_result EQUAL 0 OR NOT EXISTS "${_worklets_package_json}") - message(FATAL_ERROR "react-native-worklets could not be resolved from ${_gpui_app_root}") -endif() -get_filename_component(_worklets_root "${_worklets_package_json}" DIRECTORY) -set(_worklets_common "${_worklets_root}/Common/cpp") -if(NOT EXISTS "${_worklets_common}/worklets/NativeModules/WorkletsModuleProxy.h") - message(FATAL_ERROR "react-native-worklets 0.13.x was not found in ${_gpui_app_root} or any ancestor node_modules directory") -endif() - -# Upstream's C++ does not build with MSVC or on Linux as published; compile a -# patched copy in the build tree and leave node_modules untouched. -set(_worklets_patch "${CMAKE_CURRENT_LIST_DIR}/patches/react-native-worklets-0.13.0.patch") -execute_process( - COMMAND "${_gpui_node}" "${CMAKE_CURRENT_LIST_DIR}/patch-sources.mjs" - "${_worklets_root}" "${_worklets_patch}" - "${CMAKE_BINARY_DIR}/rn-gpui-patched/react-native-worklets" - RESULT_VARIABLE _worklets_patch_result - OUTPUT_VARIABLE _worklets_common - ERROR_VARIABLE _worklets_patch_error - OUTPUT_STRIP_TRAILING_WHITESPACE) -if(NOT _worklets_patch_result EQUAL 0) - message(FATAL_ERROR "${_worklets_patch_error}") -endif() -set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS - "${_worklets_patch}" "${_worklets_package_json}") - -file(GLOB_RECURSE _worklets_sources CONFIGURE_DEPENDS "${_worklets_common}/worklets/*.cpp") -set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_SOURCES - ${_worklets_sources} - "${CMAKE_CURRENT_LIST_DIR}/cpp/GPUIWorkletsModule.cpp" - "${CMAKE_CURRENT_LIST_DIR}/cpp/GPUIPlatformLogger.cpp") -set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_INCLUDE_DIRS - "${_worklets_common}" - "${_worklets_root}") -set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_DEFINITIONS - "WORKLETS_VERSION=0.13.0") -# The frame hook is how worklets see every frame; the platform compiles this -# glue only because the package is installed. -set_property(GLOBAL APPEND PROPERTY RN_GPUI_PACKAGE_MODULE_SOURCES - "${CMAKE_CURRENT_LIST_DIR}/cpp/GpuiWorkletsFrameModule.cpp") -set_property(GLOBAL APPEND PROPERTY RN_GPUI_PACKAGE_MODULE_INSTALLERS worklets) diff --git a/vendor/react-native-gpui/modules/worklets/desktop/cpp/GPUIPlatformLogger.cpp b/vendor/react-native-gpui/modules/worklets/desktop/cpp/GPUIPlatformLogger.cpp deleted file mode 100644 index 72c3bd8797..0000000000 --- a/vendor/react-native-gpui/modules/worklets/desktop/cpp/GPUIPlatformLogger.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include - -#include - -namespace worklets { - -void PlatformLogger::log(const char* str) { - LOG(INFO) << str; -} - -void PlatformLogger::log(const std::string& str) { - LOG(INFO) << str; -} - -void PlatformLogger::log(const double value) { - LOG(INFO) << value; -} - -void PlatformLogger::log(const int value) { - LOG(INFO) << value; -} - -void PlatformLogger::log(const bool value) { - LOG(INFO) << (value ? "true" : "false"); -} - -} // namespace worklets diff --git a/vendor/react-native-gpui/modules/worklets/desktop/cpp/GPUIWorkletsModule.cpp b/vendor/react-native-gpui/modules/worklets/desktop/cpp/GPUIWorkletsModule.cpp deleted file mode 100644 index bbff8fb03d..0000000000 --- a/vendor/react-native-gpui/modules/worklets/desktop/cpp/GPUIWorkletsModule.cpp +++ /dev/null @@ -1,353 +0,0 @@ -#include "GPUIWorkletsModule.h" - -#include "rn-gpui-sys/src/lib.rs.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "GpuiModules.h" - -namespace { -bool animationTracingEnabled() { - static const bool enabled = std::getenv("RN_GPUI_DEBUG_ANIMATION") != nullptr; - return enabled; -} - -std::mutex moduleMutex; -std::weak_ptr moduleInstance; -std::atomic workletFrames{0}; -std::atomic workletRafRequests{0}; - -class GPUIScheduler final : public worklets::UIScheduler { - protected: - bool queryIsOnUIThread() const override { - return gpui_worklets::isOnMainThread(); - } - - public: - void scheduleOnUI(std::function job) override { - static std::atomic scheduled{0}; - const auto count = ++scheduled; - if (animationTracingEnabled() && count <= 5) { - LOG(INFO) << "[gpui-worklets] scheduleOnUI count=" << count - << " onUI=" << isOnUIThread(); - } - if (isOnUIThread()) { - job(); - return; - } - UIScheduler::scheduleOnUI(std::move(job)); - rngpui::requestFrames("worklets", true); - } -}; - -worklets::RuntimeBindings::NativeLoggingHook nativeLoggingHook() { - return [](facebook::jsi::Runtime& runtime, - const facebook::jsi::Value&, - const facebook::jsi::Value* args, - size_t count) -> facebook::jsi::Value { - if (count != 2) { - throw std::invalid_argument("nativeLoggingHook takes 2 arguments"); - } - const auto message = args[0].asString(runtime).utf8(runtime); - LOG(INFO) << "[worklet] " << message; - return facebook::jsi::Value::undefined(); - }; -} -} // namespace - -namespace gpui_worklets { -namespace { -std::mutex uiThreadMutex; -std::thread::id uiThreadId; -} // namespace - -bool isOnMainThread() { - // The runtime records the main thread before its loop runs. `onFrame` only - // notes it once a frame arrives, and `UIScheduler::isOnUIThread` caches the - // first answer per thread: a query that comes first, such as a layout - // animation flush, would pin "not the UI thread" on the main thread for good. - if (rngpui::rn_gpui_is_main_thread()) { - return true; - } - std::lock_guard lock(uiThreadMutex); - return uiThreadId != std::thread::id{} && - uiThreadId == std::this_thread::get_id(); -} - -void noteMainThread() { - std::lock_guard lock(uiThreadMutex); - if (uiThreadId == std::thread::id{}) { - uiThreadId = std::this_thread::get_id(); - } -} - -Module::Module(std::shared_ptr jsInvoker) - : NativeWorkletsModuleSpec(std::move(jsInvoker)) {} - -Module::~Module() { - rngpui::reportPendingWork("worklets", 0); - rngpui::requestFrames("worklets", false); - if (initializer_) { - initializer_->invalidate(); - } - std::lock_guard lock(moduleMutex); - if (moduleInstance.lock().get() == this) { - moduleInstance.reset(); - } -} - -void Module::initialize(facebook::jsi::Runtime& runtime) { - if (initializer_) - return; - uiScheduler_ = std::make_shared(); - runtimeStatus_ = std::make_shared(); - jsScheduler_ = std::make_shared( - runtime, jsInvoker_, [] { return true; }); - std::weak_ptr weakModule = shared_from_this(); - auto runtimeBindings = - std::make_shared(worklets::RuntimeBindings{ - .requestAnimationFrame = - [weakModule](std::function callback) { - if (auto module = weakModule.lock()) { - module->requestAnimationFrame(std::move(callback)); - } - }, - .nativeLoggingHook = nativeLoggingHook(), - .networkingBackend = nullptr, - }); - initializer_ = std::make_shared( - jsScheduler_, uiScheduler_, runtimeBindings, runtimeStatus_); - LOG(INFO) << "[gpui-worklets] initialized runtime bindings"; - auto initializer = initializer_; - std::thread([initializer] { initializer->prepareProxy(); }).detach(); -} - -bool Module::installTurboModule( - facebook::jsi::Runtime& runtime, - bool bundleModeEnabled) { - initialize(runtime); - if (bundleModeEnabled) { - throw facebook::jsi::JSError( - runtime, "GPUI Worklets does not support Bundle Mode yet"); - } - proxy_ = initializer_->finalize(runtime, false, {}); - LOG(INFO) << "[gpui-worklets] WorkletsModule installed"; - return true; -} - -bool Module::prepareBundleMode(facebook::jsi::Runtime& runtime) { - throw facebook::jsi::JSError( - runtime, "GPUI Worklets does not support Bundle Mode yet"); -} - -bool Module::start(facebook::jsi::Runtime& runtime) { - if (!proxy_) - throw facebook::jsi::JSError( - runtime, "WorkletsModule.installTurboModule must run before start"); - proxy_->start(); - LOG(INFO) << "[gpui-worklets] UI runtime started"; - return true; -} - -bool Module::toggleSlowAnimationsOnUIRuntime(facebook::jsi::Runtime&) { - return false; -} - -void Module::requestAnimationFrame(std::function callback) { - const auto count = ++workletRafRequests; - if (animationTracingEnabled() && count <= 5) { - LOG(INFO) << "[gpui-worklets] requestAnimationFrame count=" << count; - } - { - std::lock_guard lock(callbacksMutex_); - frameCallbacks_.push_back(std::move(callback)); - } - rngpui::requestFrames("worklets", true); -} - -void Module::setAfterFrame(std::function afterFrame) { - std::lock_guard lock(callbacksMutex_); - afterFrame_ = std::move(afterFrame); -} - -void Module::onFrame(double timestampMs) { - const auto count = ++workletFrames; - if (animationTracingEnabled()) { - static double windowStartMs = timestampMs; - static double previousFrameMs = timestampMs; - static double maximumGapMs = 0; - maximumGapMs = std::max(maximumGapMs, timestampMs - previousFrameMs); - previousFrameMs = timestampMs; - if (count % 60 == 0) { - LOG(INFO) << "[gpui-worklets] native frame cadence frames=60 elapsed_ms=" - << timestampMs - windowStartMs - << " max_frame_gap_ms=" << maximumGapMs; - windowStartMs = timestampMs; - maximumGapMs = 0; - } - } - if (animationTracingEnabled() && (count <= 5 || count % 600 == 0)) { - LOG(INFO) << "[gpui-worklets] GPUI frame count=" << count; - } - // Frame callbacks are platform entry points, outside Worklets' guarded - // invocation paths. Report JS exceptions on RN rather than unwinding across - // the CXX boundary and terminating the desktop process. - const auto reportError = [this](const facebook::jsi::JSError& error) { - LOG(ERROR) << "[gpui-worklets] " << error.what(); - worklets::JSLogger::reportFatalErrorOnJS( - jsScheduler_, - {.message = error.getMessage(), - .stack = error.getStack(), - .name = "WorkletsError"}); - }; - try { - if (uiScheduler_) - uiScheduler_->triggerUI(); - } catch (const facebook::jsi::JSError& error) { - reportError(error); - } - // Worklets has a perpetual native heartbeat even when its JS RAF queue is - // empty. Test synchronization observes application callbacks, not that beat. - if (std::getenv("RN_GPUI_TEST_DRIVER")) { - if (auto runtime = uiRuntime()) { - runtime->runSync([](facebook::jsi::Runtime& rt) { - auto global = rt.global(); - if (!global.hasProperty(rt, "requestAnimationFrame") || - (global.hasProperty(rt, "__gpuiTestRaf") && - facebook::jsi::Value::strictEquals( - rt, - global.getProperty(rt, "requestAnimationFrame"), - global.getProperty(rt, "__gpuiTestRaf")))) - return; - global.setProperty( - rt, - "__gpuiReportPendingRaf", - facebook::jsi::Function::createFromHostFunction( - rt, - facebook::jsi::PropNameID::forAscii( - rt, "__gpuiReportPendingRaf"), - 1, - [](facebook::jsi::Runtime&, - const facebook::jsi::Value&, - const facebook::jsi::Value* args, - size_t count) { - if (count == 1 && args[0].isNumber()) - rngpui::reportPendingWork( - "worklets", static_cast(args[0].getNumber())); - return facebook::jsi::Value::undefined(); - })); - rt.evaluateJavaScript( - std::make_shared(R"JS( - (() => { - const raf = globalThis.requestAnimationFrame; - const cancel = globalThis.cancelAnimationFrame; - const pending = new Set(); - const report = () => globalThis.__gpuiReportPendingRaf(pending.size); - globalThis.requestAnimationFrame = callback => { - let id; - id = raf(timestamp => { - pending.delete(id); report(); callback(timestamp); - }); - pending.add(id); report(); return id; - }; - globalThis.cancelAnimationFrame = id => { - pending.delete(id); report(); cancel(id); - }; - globalThis.__gpuiTestRaf = globalThis.requestAnimationFrame; - report(); - })(); - )JS"), - "gpui-test-raf.js"); - }); - } - } - std::vector> callbacks; - { - std::lock_guard lock(callbacksMutex_); - callbacks.swap(frameCallbacks_); - } - if (animationTracingEnabled() && !callbacks.empty() && - (count <= 5 || count % 60 == 0)) { - LOG(INFO) << "[gpui-worklets] callbacks on frame=" << callbacks.size(); - } - for (auto& callback : callbacks) { - try { - callback(timestampMs); - } catch (const facebook::jsi::JSError& error) { - reportError(error); - } - } - std::function afterFrame; - { - std::lock_guard lock(callbacksMutex_); - afterFrame = afterFrame_; - } - if (afterFrame) { - try { - afterFrame(); - } catch (const facebook::jsi::JSError& error) { - reportError(error); - } - } - { - std::lock_guard lock(callbacksMutex_); - if (frameCallbacks_.empty()) { - rngpui::requestFrames("worklets", false); - } - } -} - -std::shared_ptr Module::uiRuntime() const { - return proxy_ ? proxy_->getUIWorkletRuntime() : nullptr; -} - -std::shared_ptr Module::uiScheduler() const { - return uiScheduler_; -} - -void onFrame(double timestampMs) { - noteMainThread(); - std::shared_ptr module; - { - std::lock_guard lock(moduleMutex); - module = moduleInstance.lock(); - } - if (module) - module->onFrame(timestampMs); -} - -std::shared_ptr currentModule() { - std::lock_guard lock(moduleMutex); - return moduleInstance.lock(); -} - -std::shared_ptr createModule( - const std::string& name, - std::shared_ptr jsInvoker) { - if (name != Module::kModuleName) - return nullptr; - auto module = std::make_shared(std::move(jsInvoker)); - { - std::lock_guard lock(moduleMutex); - moduleInstance = module; - } - return module; -} -} // namespace gpui_worklets - -std::shared_ptr create_gpui_worklets_module( - const std::string& name, - std::shared_ptr jsInvoker) { - return gpui_worklets::createModule(name, std::move(jsInvoker)); -} diff --git a/vendor/react-native-gpui/modules/worklets/desktop/cpp/GPUIWorkletsModule.h b/vendor/react-native-gpui/modules/worklets/desktop/cpp/GPUIWorkletsModule.h deleted file mode 100644 index a97f9817c1..0000000000 --- a/vendor/react-native-gpui/modules/worklets/desktop/cpp/GPUIWorkletsModule.h +++ /dev/null @@ -1,64 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace gpui_worklets { -bool isOnMainThread(); -void noteMainThread(); - -class Module final : public facebook::react::NativeWorkletsModuleSpec { - public: - explicit Module(std::shared_ptr jsInvoker); - ~Module() override; - - void onFrame(double timestampMs); - void requestAnimationFrame(std::function callback); - /// Runs after every frame's animation callbacks, as the display link's - /// handler does on iOS. - void setAfterFrame(std::function afterFrame); - std::shared_ptr uiRuntime() const; - std::shared_ptr uiScheduler() const; - - bool installTurboModule( - facebook::jsi::Runtime& runtime, - bool bundleModeEnabled); - bool prepareBundleMode(facebook::jsi::Runtime& runtime); - bool start(facebook::jsi::Runtime& runtime); - bool toggleSlowAnimationsOnUIRuntime(facebook::jsi::Runtime& runtime); - - private: - void initialize(facebook::jsi::Runtime& runtime); - - std::shared_ptr uiScheduler_; - std::shared_ptr jsScheduler_; - std::shared_ptr runtimeStatus_; - std::shared_ptr initializer_; - std::shared_ptr proxy_; - std::mutex callbacksMutex_; - std::vector> frameCallbacks_; - std::function afterFrame_; -}; - -void onFrame(double timestampMs); -std::shared_ptr currentModule(); -std::shared_ptr createModule( - const std::string& name, - std::shared_ptr jsInvoker); - -} // namespace gpui_worklets - -std::shared_ptr create_gpui_worklets_module( - const std::string& name, - std::shared_ptr jsInvoker); diff --git a/vendor/react-native-gpui/modules/worklets/desktop/cpp/GpuiWorkletsFrameModule.cpp b/vendor/react-native-gpui/modules/worklets/desktop/cpp/GpuiWorkletsFrameModule.cpp deleted file mode 100644 index a3ff29a3e5..0000000000 --- a/vendor/react-native-gpui/modules/worklets/desktop/cpp/GpuiWorkletsFrameModule.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include "GpuiModules.h" - -namespace gpui_worklets { -void onFrame(double timestampMs); -} - -namespace rngpui { -void rn_gpui_install_worklets_module() { - registerFrameCallback( - [](double timestampMs) { gpui_worklets::onFrame(timestampMs); }); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/modules/worklets/desktop/patch-sources.mjs b/vendor/react-native-gpui/modules/worklets/desktop/patch-sources.mjs deleted file mode 100644 index cae6408194..0000000000 --- a/vendor/react-native-gpui/modules/worklets/desktop/patch-sources.mjs +++ /dev/null @@ -1,149 +0,0 @@ -#!/usr/bin/env node -// Copies an upstream package's `Common/cpp` into a build directory and applies a -// unified diff to the copy, so the app's node_modules is never modified. -// -// node patch-sources.mjs -// -// Prints the patched `Common/cpp` directory. The copy is reused while the -// package version and the patch are unchanged. -import { createHash } from 'node:crypto'; -import fs from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; - -/** Parses a unified diff into files, each with its hunks. */ -export function parsePatch(text) { - const files = []; - let file = null; - let hunk = null; - // Lines still expected in the current hunk, from its header counts. - let oldLeft = 0; - let newLeft = 0; - for (const line of text.replace(/\r\n/gu, '\n').split('\n')) { - if (hunk !== null && (oldLeft > 0 || newLeft > 0)) { - const kind = line.length === 0 ? ' ' : line[0]; - const body = line.slice(1); - if (kind === ' ' || kind === '-') { - hunk.old.push(body); - oldLeft--; - } - if (kind === ' ' || kind === '+') { - hunk.new.push(body); - newLeft--; - } - if (kind === '\\') continue; - } else if (line.startsWith('--- ')) { - file = { path: null, hunks: [] }; - files.push(file); - hunk = null; - } else if (line.startsWith('+++ ') && file !== null) { - file.path = line.slice(4).split('\t')[0].replace(/^b\//u, ''); - } else if (line.startsWith('@@ ') && file !== null) { - const match = /^@@ -(\d+)(?:,(\d+))? \+\d+(?:,(\d+))? @@/u.exec(line); - if (match === null) throw new Error(`bad hunk header: ${line}`); - hunk = { start: Number(match[1]), old: [], new: [] }; - oldLeft = match[2] === undefined ? 1 : Number(match[2]); - newLeft = match[3] === undefined ? 1 : Number(match[3]); - file.hunks.push(hunk); - } - } - return files; -} - -function matchesAt(lines, block, at) { - if (at < 0 || at + block.length > lines.length) return false; - return block.every((line, i) => lines[at + i] === line); -} - -/** The line nearest `expected` where `block` starts, or -1. */ -function find(lines, block, expected) { - for (let delta = 0; delta <= lines.length; delta++) { - if (matchesAt(lines, block, expected - delta)) return expected - delta; - if (matchesAt(lines, block, expected + delta)) return expected + delta; - } - return -1; -} - -/** - * Applies one file's hunks to its text, keeping its line endings. A hunk whose - * result is already present - * is skipped, so sources that carry the fix upstream still build; any other - * mismatch throws. - */ -export function applyHunks(text, hunks, name) { - const crlf = text.includes('\r\n'); - const lines = text.replace(/\r\n/gu, '\n').split('\n'); - let offset = 0; - for (const hunk of hunks) { - const expected = Math.max(hunk.start - 1, 0) + offset; - const at = find(lines, hunk.old, expected); - if (at !== -1) { - lines.splice(at, hunk.old.length, ...hunk.new); - offset = at - (hunk.start - 1) + hunk.new.length - hunk.old.length; - continue; - } - const applied = find(lines, hunk.new, expected); - if (applied === -1) { - throw new Error(`${name}: hunk at line ${hunk.start} does not apply`); - } - offset = applied - (hunk.start - 1); - } - return lines.join(crlf ? '\r\n' : '\n'); -} - -function main([packageRoot, patchFile, outputDir]) { - if (!packageRoot || !patchFile || !outputDir) { - throw new Error( - 'usage: patch-sources.mjs ', - ); - } - const manifest = JSON.parse( - fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'), - ); - const patch = fs.readFileSync(patchFile, 'utf8'); - const stamp = createHash('sha256') - .update(`${manifest.name}@${manifest.version}\n`) - .update(patch) - .digest('hex'); - const target = path.join(outputDir, 'Common', 'cpp'); - const stampFile = path.join(outputDir, '.patched'); - const current = fs.existsSync(stampFile) - ? fs.readFileSync(stampFile, 'utf8') - : ''; - if (current !== stamp) { - fs.rmSync(outputDir, { recursive: true, force: true }); - fs.cpSync(path.join(packageRoot, 'Common', 'cpp'), target, { - recursive: true, - }); - for (const file of parsePatch(patch)) { - const full = path.join(target, file.path); - const original = fs.existsSync(full) ? fs.readFileSync(full, 'utf8') : ''; - let patched; - try { - patched = applyHunks(original, file.hunks, file.path); - } catch (error) { - fs.rmSync(outputDir, { recursive: true, force: true }); - throw new Error( - `${path.basename(patchFile)} does not apply to ${manifest.name}@${manifest.version}: ${error.message}`, - ); - } - fs.mkdirSync(path.dirname(full), { recursive: true }); - fs.writeFileSync(full, patched); - } - fs.writeFileSync(stampFile, stamp); - } - // CMake reads backslashes as escapes. - process.stdout.write(target.split(path.sep).join('/')); -} - -if ( - process.argv[1] && - path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) -) { - try { - main(process.argv.slice(2)); - } catch (error) { - process.stderr.write(`${error.message}\n`); - process.exit(1); - } -} diff --git a/vendor/react-native-gpui/modules/worklets/desktop/patch-sources.test.mjs b/vendor/react-native-gpui/modules/worklets/desktop/patch-sources.test.mjs deleted file mode 100644 index 9e191ba24e..0000000000 --- a/vendor/react-native-gpui/modules/worklets/desktop/patch-sources.test.mjs +++ /dev/null @@ -1,79 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { describe, expect, test } from 'vitest'; -import { applyHunks, parsePatch } from './patch-sources.mjs'; - -const PATCH = `--- a/lib/a.cpp -+++ b/lib/a.cpp -@@ -1,3 +1,4 @@ - #include -+#include - - int main() {} -`; - -describe('parsePatch', () => { - test('reads each file and its hunks, including blank context lines', () => { - const [file] = parsePatch(PATCH); - expect(file.path).toBe('lib/a.cpp'); - expect(file.hunks).toEqual([ - { - start: 1, - old: ['#include ', '', 'int main() {}'], - new: ['#include ', '#include ', '', 'int main() {}'], - }, - ]); - }); -}); - -describe('applyHunks', () => { - const [{ hunks }] = parsePatch(PATCH); - - test('applies a hunk', () => { - expect(applyHunks('#include \n\nint main() {}\n', hunks, 'a')).toBe( - '#include \n#include \n\nint main() {}\n', - ); - }); - - test('finds a hunk that moved', () => { - expect( - applyHunks('// x\n// y\n#include \n\nint main() {}\n', hunks, 'a'), - ).toBe('// x\n// y\n#include \n#include \n\nint main() {}\n'); - }); - - test('leaves sources that already carry the change alone', () => { - const patched = '#include \n#include \n\nint main() {}\n'; - expect(applyHunks(patched, hunks, 'a')).toBe(patched); - }); - - test('ignores CRLF in the patch and keeps CRLF in the source', () => { - const [{ hunks: crlfHunks }] = parsePatch(PATCH.replace(/\n/gu, '\r\n')); - expect( - applyHunks('#include \r\n\r\nint main() {}\r\n', crlfHunks, 'a'), - ).toBe('#include \r\n#include \r\n\r\nint main() {}\r\n'); - }); - - test('rejects sources it does not match', () => { - expect(() => applyHunks('int main() { return 1; }\n', hunks, 'a')).toThrow( - 'a: hunk at line 1 does not apply', - ); - }); -}); - -describe('the shipped patches', () => { - const root = path.resolve(import.meta.dirname, '../../..'); - - test.each([ - ['react-native-worklets', 'modules/worklets/desktop/patches'], - ['react-native-reanimated', 'modules/reanimated/desktop/patches'], - ])('apply to the installed %s', (name, patches) => { - const source = path.join(root, 'node_modules', name, 'Common', 'cpp'); - for (const patchFile of fs.readdirSync(path.join(root, patches))) { - const text = fs.readFileSync(path.join(root, patches, patchFile), 'utf8'); - for (const file of parsePatch(text)) { - const original = fs.readFileSync(path.join(source, file.path), 'utf8'); - expect(() => applyHunks(original, file.hunks, file.path)).not.toThrow(); - } - } - }); -}); diff --git a/vendor/react-native-gpui/modules/worklets/desktop/patches/react-native-worklets-0.13.0.patch b/vendor/react-native-gpui/modules/worklets/desktop/patches/react-native-worklets-0.13.0.patch deleted file mode 100644 index 79731e710c..0000000000 --- a/vendor/react-native-gpui/modules/worklets/desktop/patches/react-native-worklets-0.13.0.patch +++ /dev/null @@ -1,107 +0,0 @@ ---- a/worklets/RunLoop/AsyncQueueImpl.cpp -+++ b/worklets/RunLoop/AsyncQueueImpl.cpp -@@ -4,6 +4,10 @@ - #include - #endif // ANDROID - -+#if defined(__APPLE__) || defined(__linux__) -+#include -+#endif -+ - #include - #include - #include -@@ -69,7 +73,11 @@ - pthread_setname_np(pthread_self(), name.c_str()); - jni::ThreadScope::WithClassLoader([state]() { AsyncQueueImpl::runLoop(state); }); - #else -+#if defined(__APPLE__) - pthread_setname_np(name.c_str()); -+#elif defined(__linux__) -+ pthread_setname_np(pthread_self(), name.substr(0, 15).c_str()); -+#endif - AsyncQueueImpl::runLoop(state); - #endif // ANDROID - }); ---- a/worklets/RunLoop/EventLoop.cpp -+++ b/worklets/RunLoop/EventLoop.cpp -@@ -1,5 +1,6 @@ - #include - -+#include - #include - #include - #include ---- a/worklets/Tools/JSISerializer.cpp -+++ b/worklets/Tools/JSISerializer.cpp -@@ -1,7 +1,10 @@ - #include - -+#ifndef _MSC_VER - #include -+#endif - -+#include - #include - #include - #include -@@ -116,15 +119,20 @@ - } - - std::string JSISerializer::stringifyHostObject(jsi::HostObject &hostObject) { -+#ifdef _MSC_VER -+ const char *hostObjClassName = typeid(hostObject).name(); -+#else - int status = -1; -- std::unique_ptr hostObjClassName( -+ std::unique_ptr demangled( - abi::__cxa_demangle(typeid(hostObject).name(), nullptr, nullptr, &status), std::free); - if (status != 0) { - return "[jsi::HostObject]"; - } -+ const char *hostObjClassName = demangled.get(); -+#endif - - std::stringstream ss; -- ss << "[jsi::HostObject(" << hostObjClassName.get() << ")"; -+ ss << "[jsi::HostObject(" << hostObjClassName << ")"; - - auto props = hostObject.getPropertyNames(rt_); - auto propsCount = props.size(); ---- a/worklets/Tools/SingleInstanceChecker.h -+++ b/worklets/Tools/SingleInstanceChecker.h -@@ -4,7 +4,9 @@ - - #include - -+#ifndef _MSC_VER - #include -+#endif - - #include - #include -@@ -50,10 +52,14 @@ - - template - SingleInstanceChecker::SingleInstanceChecker() { -+#ifdef _MSC_VER -+ std::string className = typeid(T).name(); -+#else - int status = 0; - char *demangled = __cxxabiv1::__cxa_demangle(typeid(T).name(), nullptr, nullptr, &status); - std::string className = (status == 0 && demangled != nullptr) ? demangled : typeid(T).name(); - std::free(demangled); -+#endif - - // React Native can spawn up to two instances of a Native Module at the same - // time. This happens during a reload when a new instance of React Native is ---- a/worklets/Tools/WorkletsJSIUtils.cpp -+++ b/worklets/Tools/WorkletsJSIUtils.cpp -@@ -2,6 +2,7 @@ - - #include - -+#include - #include - #include - #include diff --git a/vendor/react-native-gpui/modules/worklets/package.json b/vendor/react-native-gpui/modules/worklets/package.json deleted file mode 100644 index c3b597c8c2..0000000000 --- a/vendor/react-native-gpui/modules/worklets/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@react-native-gpui/worklets", - "version": "0.13.0-alpha.1", - "description": "Adapter for react-native-worklets (MIT): runs worklets on desktop, driven by the renderer's frame clock", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/streetwriters/react-native-gpui-modules.git", - "directory": "modules/worklets" - }, - "homepage": "https://github.com/streetwriters/react-native-gpui-modules/tree/main/modules/worklets#readme", - "bugs": { - "url": "https://github.com/streetwriters/react-native-gpui-modules/issues" - }, - "files": [ - "desktop", - "react-native.config.js", - "src", - "README.md", - "LICENSE", - "CHANGELOG.md", - "!**/*.test.js", - "!**/*.test.mjs", - "!**/*.test.ts", - "!**/*.test.cjs" - ], - "peerDependencies": { - "react-native": "0.87.x", - "react-native-worklets": "0.13.x" - }, - "codegenConfig": { - "name": "GPUIWorkletsSpec", - "type": "modules", - "jsSrcsDir": "src" - }, - "publishConfig": { - "access": "public", - "tag": "latest" - } -} diff --git a/vendor/react-native-gpui/modules/worklets/react-native.config.js b/vendor/react-native-gpui/modules/worklets/react-native.config.js deleted file mode 100644 index 6c33f0cfda..0000000000 --- a/vendor/react-native-gpui/modules/worklets/react-native.config.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = { - dependency: { - platforms: { - desktop: { - cmake: 'desktop', - cppProvider: 'create_gpui_worklets_module', - }, - }, - }, -}; diff --git a/vendor/react-native-gpui/modules/worklets/src/NativeWorkletsModule.ts b/vendor/react-native-gpui/modules/worklets/src/NativeWorkletsModule.ts deleted file mode 100644 index a10c343352..0000000000 --- a/vendor/react-native-gpui/modules/worklets/src/NativeWorkletsModule.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { TurboModuleRegistry, type TurboModule } from 'react-native'; - -export interface Spec extends TurboModule { - installTurboModule(bundleModeEnabled: boolean): boolean; - prepareBundleMode(): boolean; - toggleSlowAnimationsOnUIRuntime(): boolean; - start(): boolean; -} - -export default TurboModuleRegistry.get('WorkletsModule'); diff --git a/vendor/react-native-gpui/packages/cli/CHANGELOG.md b/vendor/react-native-gpui/packages/cli/CHANGELOG.md deleted file mode 100644 index 2db0df5728..0000000000 --- a/vendor/react-native-gpui/packages/cli/CHANGELOG.md +++ /dev/null @@ -1,59 +0,0 @@ -# Changelog - -All notable changes to `@react-native-gpui/cli` are listed here. Each version's section becomes the notes of its GitHub release. - -## 0.87.0-alpha.5 - 2026-11-26 - -- With the Loom renderer, the build downloads the Loom prebuilt runtime before Cargo runs, as it does for Fabric, and `project.desktop.prebuilt` `always` no longer fails for Loom. `package-desktop` finds the shared libraries of a Loom build, whose CMake folder is named `-loom` or `-loom-prebuilt`. -- `--js-thread` and `jsThread` choose where JavaScript runs with Loom for the build; the app no longer reads `RN_GPUI_JS_THREAD` at launch. -- `doctor` requires Rust and Cargo 1.98 or newer instead of only checking that they are installed, so an older toolchain, such as a Homebrew Rust ahead of rustup on `PATH`, is reported before the build fails. -- The app template's `desktop/build.rs` no longer warns about an unused `mut` on the first build. -- `desktop.json` takes `renderer` (`fabric` or `loom`) and `jsThread` (`background` or `main`, Loom only), documented in `desktop.schema.json`, and `run-desktop` takes `--renderer` and `--js-thread` for one run. `autolink` records the choice and the React Native tree it selects in `autolink.json`, and the app's build follows it. - -## 0.87.0-alpha.4 - 2026-11-16 - -- `platforms.desktop.hostComponents` entries take `maskChildren: true` for a component whose first child masks the others. It cannot also be `measured` or `cpp`, and needs no Rust registration. -- `platforms.desktop.hostComponents` entries take `cpp: true` for a component implemented in C++. Such an entry needs no Rust crate or codegen spec, cannot also be `measured` or a `container`, and is declared in the generated `CppTurboModules.generated.cpp`, which then runs the init functions modules add to `RN_GPUI_APP_CPP_INIT_FUNCTIONS`. - -## 0.87.0-alpha.3 - 2026-11-12 - -- On macOS, the Xcode command line tools are enough to build an app. `autolink` declares a `runtime-shaders` feature in the app manifest, and `run-desktop` and `package-desktop` turn it on when there is no Metal shader compiler (it ships only with full Xcode), so the shaders are compiled when the app starts. With full Xcode and its Metal toolchain, the shaders are still compiled at build time. `doctor` no longer requires Xcode or the Metal compiler; it checks for the command line tools, and for the Xcode license only when full Xcode is selected. - -## 0.87.0-alpha.2 - 2026-11-12 - -- `autolink` writes the GPUI Kit compat patches itself: when a linked module crate depends on `gpui-base`, `gpui-component`, a `gpui-kit*` or a `gpui-pre*` crate, the managed `[patch.crates-io]` block also has `gpui-pre`, `gpui-pre-macros` and `gpui-pre-sum-tree` (and `gpui-pre-platform`, `gpui-pre-web` and `gpui-pre-reqwest-client` when a module or the app's `Cargo.lock` names them), each at the gpui-fast git and rev of core's pin. Apps without such a module get none of them. A hand-written line for a managed crate in `[patch.crates-io]` is refused even when it sits beside an existing managed block; remove those lines. - -- `run-desktop --features test-driver --no-launch` also writes the JavaScript bundle the test driver loads, so a debug build can be tested without Metro or a separate `react-native bundle` step. -- `run-desktop` takes `--sign-identity ` (default `$APPLE_SIGNING_IDENTITY`) and signs the binary with `--no-launch` too, instead of only before a launch. -- `autolink` adds `rn-gpui-module` and `rn-gpui-module-build` to an app manifest that already has the managed patch block, which it skipped because the block names the same crates. It also rewrites an existing path to either crate to the real path, so a `file:`-linked core no longer makes Cargo report two different packages. -- `platforms.desktop.bundleHook` names a module of a package that `run-desktop --release` and `package-desktop` run after the app's bundle is built, to build more of what the release ships (react-native-workers bundles each worker this way). What it returns is copied beside the bundle and packaged as resources. -- `platforms.desktop.cppSpecs` lists the specification files a package's C++ provider serves when the package also has a Rust crate, so the provider is no longer asked for the crate's modules and the crate no longer lists the C++ ones. -- `run-desktop --release` and `package-desktop` collect the Node addons the release bundle loads into `desktop/build/node-addons` without a separate `collect-node-addons` step. A release run copies them beside the executable, and a packaged macOS app ships them as `Resources/node-addons`, with each shared library beside its addon. When `APPLE_SIGNING_IDENTITY` is set on macOS, the collected `.node` and `.dylib` files are signed with it, as the app is. A debug build collects nothing. -- `desktop.json` accepts `window.visible`, which starts the main window hidden until the app shows it. -- Autolink records the window options and flags of `desktop/desktop.json`, merged with the per-OS file, in the generated autolink crate, and `ensure_linked()` hands them to the runtime, so `window.titleBar`, `window.trafficLightPosition` and the other window keys apply to a hand-written `main.rs` without running `init-desktop` again. -- `package-desktop` tells the engine which build it packages, so a release app ships the Hermes VM without the debugger. -- `run-desktop` on macOS signs the app with `APPLE_SIGNING_IDENTITY` when it is set, so the keychain keeps the access it granted across rebuilds instead of asking for every item again. - -## 0.87.0-alpha.1 - 2026-11-05 - -- `package-desktop` tries `cargo packager` again, up to four times with a growing pause, when it fails because `hdiutil` reports `create failed - Resource busy` while building a disk image, or because a download it needs answers with a 5xx status or times out. Packaging failed at random on these. -- `desktop.json` accepts `tray.popoverAnchor` and `tray.popoverOffset`, the corner and offset of a tray popover on Linux with Wayland. -- `desktop.json` accepts `window.cornerRadius`, the corner radius of a client-decorated window on Linux where the desktop's cannot be measured. -- `desktop.json` accepts `window.windowControlsPosition` (`"left"` or `"right"`), the side the window controls use on Linux when the desktop gives none. -- `desktop.json` accepts `accessory`. -- `desktop.json` accepts `window.titleBar: "none"`. -- `desktop.json` accepts `window.windowButtons` and `window.shadow`. -- `desktop.json` accepts `window.background`: `opaque`, `transparent`, `blurred` or `mica`. -- `init` keeps React Native's own `App.tsx` and its new app screen instead of replacing it. -- `init` and `init-desktop` add `@react-native-gpui/safe-area-context` to an app that uses `react-native-safe-area-context`, and pin that library to the version the module supports. -- `run-desktop` downloads the prebuilt runtime before building, so its progress shows in the terminal instead of Cargo looking stuck. -- `init` and `init-desktop` add a `desktop` script to `package.json`, so `npm run desktop` starts the app. - -## 0.87.0-alpha.0 - 2026-11-01 - -- First release. -- `init` creates an app with a `desktop/` target; `init-desktop` adds one to an existing React Native app. -- `run-desktop` builds and runs the app, in debug against Metro or with `--release`. -- `package-desktop` builds `.app` and `.dmg` on macOS, an NSIS installer on Windows, and `.deb` and `.AppImage` on Linux. -- `doctor` checks the toolchain on each operating system. -- Autolinks desktop modules from their `react-native.config.js`, and prunes stale build output after a day. diff --git a/vendor/react-native-gpui/packages/cli/LICENSE b/vendor/react-native-gpui/packages/cli/LICENSE deleted file mode 100644 index 149a0f8321..0000000000 --- a/vendor/react-native-gpui/packages/cli/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Streetwriters - -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/vendor/react-native-gpui/packages/cli/README.md b/vendor/react-native-gpui/packages/cli/README.md deleted file mode 100644 index 095006ebf7..0000000000 --- a/vendor/react-native-gpui/packages/cli/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# @react-native-gpui/cli - -Command-line tools for React Native desktop apps: create, run, test and package them. - -Part of [react-native-gpui](https://github.com/streetwriters/react-native-gpui), React Native for macOS, Windows and Linux. - -## Commands - -| Command | Description | -| ---------------------------------------- | ------------------------------------------------------------- | -| `npx @react-native-gpui/cli init MyApp` | Creates an app with a `desktop/` target. | -| `npx react-native init-desktop` | Adds a `desktop/` target to an existing app. | -| `npx react-native doctor-desktop` | Checks the toolchain for this operating system. | -| `npx react-native run-desktop` | Builds and runs the app. Add `--release` for a release build. | -| `npx react-native package-desktop` | Builds installers: `.app`/`.dmg`, NSIS, `.deb`/`.AppImage`. | -| `npx react-native create-library ` | Creates a native module library in Rust or C++. | - -## Documentation - -[CLI](https://streetwriters.github.io/react-native-gpui/docs/cli) - -## License - -MIT. See [LICENSE](LICENSE). diff --git a/vendor/react-native-gpui/packages/cli/assets/default-icon.png b/vendor/react-native-gpui/packages/cli/assets/default-icon.png deleted file mode 100644 index 576f7080ed..0000000000 Binary files a/vendor/react-native-gpui/packages/cli/assets/default-icon.png and /dev/null differ diff --git a/vendor/react-native-gpui/packages/cli/bin/react-native-gpui.js b/vendor/react-native-gpui/packages/cli/bin/react-native-gpui.js deleted file mode 100755 index 76e622ecc8..0000000000 --- a/vendor/react-native-gpui/packages/cli/bin/react-native-gpui.js +++ /dev/null @@ -1,177 +0,0 @@ -#!/usr/bin/env node -import fs from 'node:fs'; -import path from 'node:path'; -import { execFileSync, spawnSync } from 'node:child_process'; -import { createRequire } from 'node:module'; -import { - collectNodeAddons, - createLibrary, - initDesktop, - initProject, - runDesktop, -} from '../src/commands.js'; -import { autolink } from '../src/autolink.js'; -import { doctor } from '../src/doctor.cjs'; -const requestedCommand = process.argv[2]; -const command = requestedCommand === 'run-desktop' ? 'run' : requestedCommand; -const option = name => { - const index = process.argv.indexOf(name); - return index < 0 ? undefined : process.argv[index + 1]; -}; -const hasFlag = name => process.argv.includes(name); -const projectRoot = path.resolve(option('--project-root') ?? process.cwd()); -const desktopRoot = path.join(projectRoot, 'desktop'); -const run = (bin, args) => - execFileSync(bin, args, { cwd: projectRoot, stdio: 'inherit' }); - -if (hasFlag('--help') || hasFlag('-h')) { - console.log( - 'usage: npx react-native run-desktop [--project-root path] [--port 8082] [--release] [--features feature,...] [--no-launch] [--sign-identity identity] [--renderer fabric|loom] [--js-thread background|main]', - ); - process.exit(0); -} - -if (command === 'doctor' || command === 'doctor-desktop') { - process.exit(doctor()); -} - -if (command === 'init-desktop') { - initDesktop({ projectRoot, skipInstall: hasFlag('--skip-install') }); - process.exit(0); -} - -if (command === 'create-library') { - createLibrary({ - libraryName: process.argv[3], - type: option('--type') ?? 'rust', - destination: option('--directory'), - moduleName: option('--module-name'), - packageName: option('--package-name'), - }); - process.exit(0); -} - -if (command === 'init') { - const appName = process.argv[3]; - if (!appName || !/^[A-Za-z][A-Za-z0-9_-]*$/u.test(appName)) { - console.error('usage: react-native-gpui init [--directory path]'); - process.exit(2); - } - const destination = path.resolve(option('--directory') ?? appName); - const initArgs = process.argv.slice(4); - for (let index = 0; index < initArgs.length; index += 1) { - if ( - initArgs[index] === '--directory' || - initArgs[index] === '--project-root' - ) { - initArgs.splice(index, 2); - index -= 1; - } - } - initProject({ appName, destination, initArgs }); - process.exit(0); -} - -if ( - !['autolink', 'bundle', 'collect-node-addons', 'prebuilt', 'run'].includes( - command, - ) -) { - console.error( - 'usage: react-native-gpui [options]', - ); - process.exit(2); -} - -if (command === 'collect-node-addons') { - collectNodeAddons({ - bundle: option('--bundle'), - out: option('--out'), - platform: option('--platform'), - }); - process.exit(0); -} - -if (option('--renderer')) process.env.RN_GPUI_RENDERER = option('--renderer'); -if (option('--js-thread')) - process.env.RN_GPUI_JS_THREAD = option('--js-thread'); - -if (command === 'run') { - await runDesktop({ - projectRoot, - entryFile: option('--entry-file'), - bundle: option('--bundle'), - config: option('--config'), - release: hasFlag('--release'), - features: option('--features'), - noLaunch: hasFlag('--no-launch'), - signIdentity: option('--sign-identity'), - port: option('--port'), - host: option('--host'), - }); - process.exit(0); -} - -if (command === 'bundle') { - const entryFile = option('--entry-file') ?? 'index.js'; - const bundlePath = path.resolve( - option('--bundle') ?? path.join(desktopRoot, 'build/index.bundle'), - ); - fs.mkdirSync(path.dirname(bundlePath), { recursive: true }); - const bundleArgs = [ - 'react-native', - 'bundle', - '--platform', - 'desktop', - '--entry-file', - entryFile, - '--bundle-output', - bundlePath, - '--assets-dest', - path.join(path.dirname(bundlePath), 'assets'), - '--dev', - 'false', - ]; - const metroConfig = - option('--config') ?? path.join(desktopRoot, 'metro.config.js'); - if (fs.existsSync(metroConfig)) bundleArgs.push('--config', metroConfig); - process.exit(0); -} - -if (command === 'autolink') { - autolink({ projectRoot, configFile: option('--config-json') }); - process.exit(0); -} - -if (command === 'prebuilt') { - const appRequire = createRequire(path.join(projectRoot, 'package.json')); - let gpuiPackageJson; - try { - gpuiPackageJson = appRequire.resolve( - '@react-native-gpui/core/package.json', - ); - } catch { - console.error( - '@react-native-gpui/core is not installed in this project; run `npm install @react-native-gpui/core`.', - ); - process.exit(1); - } - const script = path.join( - path.dirname(gpuiPackageJson), - 'scripts', - 'prebuilt-binaries.mjs', - ); - const subcommand = process.argv[3]; - const allowed = ['fetch', 'path', 'verify', 'clean']; - if (!allowed.includes(subcommand)) { - console.error( - `usage: react-native-gpui prebuilt <${allowed.join('|')}> [--triple ] [dir]`, - ); - process.exit(1); - } - const forwarded = process.argv.slice(3); - const result = spawnSync(process.execPath, [script, ...forwarded], { - stdio: 'inherit', - }); - process.exit(result.status ?? 1); -} diff --git a/vendor/react-native-gpui/packages/cli/desktop.schema.json b/vendor/react-native-gpui/packages/cli/desktop.schema.json deleted file mode 100644 index 4fd2b704c6..0000000000 --- a/vendor/react-native-gpui/packages/cli/desktop.schema.json +++ /dev/null @@ -1,325 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/streetwriters/react-native-gpui/packages/cli/desktop.schema.json", - "title": "React Native GPUI desktop app configuration", - "description": "The desktop/desktop.json file of a React Native GPUI app. Every field is optional: an app with no desktop.json runs and packages with the defaults.", - "type": "object", - "additionalProperties": false, - "properties": { - "$schema": { - "description": "Path to this schema, for editor completion.", - "type": "string" - }, - "productName": { - "description": "The name a person sees: window title bar, Dock, menu bar, installers. Defaults to the app's displayName, else its name.", - "type": "string", - "minLength": 1 - }, - "identifier": { - "description": "The reverse-DNS bundle id, e.g. com.example.myapp. Defaults to an id derived from the app name.", - "type": "string", - "minLength": 1, - "pattern": "^[A-Za-z0-9][A-Za-z0-9.-]*$" - }, - "version": { - "description": "The app version. Defaults to the version in package.json.", - "type": "string", - "minLength": 1 - }, - "renderer": { - "description": "The renderer that mounts React's output. 'fabric' is React Native's renderer and the default. 'loom' is Loom, an alternative renderer pinned by @react-native-gpui/core; it builds the native runtime from source and does not support Reanimated. The RN_GPUI_RENDERER environment variable overrides this.", - "enum": ["fabric", "loom"] - }, - "jsThread": { - "description": "Where JavaScript runs with the 'loom' renderer. 'background' runs it on its own thread and is the default. 'main' runs it on the UI thread, so commits apply without a thread hop and a long task blocks painting. Only valid with \"renderer\": \"loom\". Fixed when the app is built; changing it rebuilds the Rust part of the runtime. The RN_GPUI_JS_THREAD environment variable overrides this for a build.", - "enum": ["background", "main"] - }, - "icon": { - "description": "One square PNG, recommended 1024x1024, relative to desktop/. Per-OS icon formats are generated from it. When this is unset the CLI uses its own placeholder, so every packaging format can be built.", - "type": "string", - "minLength": 1 - }, - "window": { - "description": "The main window.", - "type": "object", - "additionalProperties": false, - "properties": { - "title": { - "description": "The title bar text. Defaults to productName.", - "type": "string" - }, - "width": { - "description": "The window width in points. Defaults to 1024.", - "type": "number", - "exclusiveMinimum": 0 - }, - "height": { - "description": "The window height in points. Defaults to 768.", - "type": "number", - "exclusiveMinimum": 0 - }, - "position": { - "description": "Where the window opens. Omit to let the platform place it.", - "type": "object", - "additionalProperties": false, - "required": ["x", "y"], - "properties": { - "x": { - "type": "number" - }, - "y": { - "type": "number" - } - } - }, - "resizable": { - "description": "Whether the window can be resized. Defaults to true.", - "type": "boolean" - }, - "visible": { - "description": "Whether the window is shown when the app starts. When false the window is created and the app runs and renders in it, but nothing is shown and no focus is taken until the app calls DesktopWindow.show(). Defaults to true.", - "type": "boolean" - }, - "restoreState": { - "description": "Whether the window remembers its size and position between launches. Defaults to true.", - "type": "boolean" - }, - "titleBar": { - "description": "How the window's title bar is drawn. 'default' keeps the platform's; 'transparent' keeps the window's chrome but lets the app draw under it, which on macOS leaves the traffic lights over the app's own bar; 'hidden' removes it entirely, and the app must draw and move its own bar; 'none' removes all system chrome, which on macOS means a borderless window with no border line or system corners. On Linux 'transparent' and 'hidden' both ask the compositor for client-side decorations, and a window manager that refuses leaves the native title bar in place. Defaults to 'default'.", - "default": "default", - "oneOf": [ - { - "type": "string", - "enum": ["default"] - }, - { - "type": "string", - "enum": ["transparent"] - }, - { - "type": "string", - "enum": ["hidden"] - }, - { - "type": "string", - "enum": ["none"] - } - ] - }, - "background": { - "description": "What shows through the window where the app draws nothing opaque. 'transparent' is plain alpha transparency, so the app's own colors decide how much of the desktop shows; 'blurred' blurs what is behind the window; 'mica' is the Windows 11 material and leaves the window opaque elsewhere. The root view of the app has to be transparent too. Defaults to 'opaque'.", - "default": "opaque", - "enum": ["opaque", "transparent", "blurred", "mica"] - }, - "windowButtons": { - "description": "Whether macOS draws the traffic lights. Set it to false for a window the app styles entirely. Windows and Linux ignore it. Defaults to true.", - "type": "boolean" - }, - "shadow": { - "description": "Whether the window has a shadow: the system's on macOS, and the one a client-decorated window draws around itself on Linux. Defaults to true.", - "type": "boolean" - }, - "trafficLightPosition": { - "description": "Where the macOS traffic lights sit inside a transparent or hidden title bar, in points from the window's top-left corner. Ignored on Windows and Linux, which have no traffic lights. Defaults to the platform's own position.", - "type": "object", - "additionalProperties": false, - "required": ["x", "y"], - "properties": { - "x": { - "type": "number", - "minimum": 0 - }, - "y": { - "type": "number", - "minimum": 0 - } - } - }, - "cornerRadius": { - "description": "The corner radius, in points, of a client-decorated window on Linux when the desktop's own cannot be measured. Ignored on Windows and macOS.", - "type": "number", - "minimum": 0 - }, - "windowControlsPosition": { - "description": "The side of the title bar the window controls (minimize, maximize, close) use on Linux when the desktop does not say where its own go. Defaults to right. Ignored on Windows and macOS.", - "enum": ["left", "right"] - }, - "menuBar": { - "description": "Whether the main window shows a menu bar. Windows and Linux draw one inside the window; on macOS this does nothing, because the bar belongs to the system. Defaults to true.", - "type": "boolean" - } - } - }, - "urlSchemes": { - "description": "URL schemes that open this app, e.g. [\"myapp\"]. Packaging registers them with the operating system, and Linking delivers the opened URL as getInitialURL() or a url event.", - "type": "array", - "uniqueItems": true, - "items": { - "type": "string", - "pattern": "^[a-z][a-z0-9+.-]*$" - } - }, - "singleInstance": { - "description": "Whether launching the app again hands its URL to the running copy and exits, instead of starting a second one. Defaults to true when urlSchemes is set.", - "type": "boolean" - }, - "accessory": { - "description": "Whether the app runs with no Dock icon (macOS), as a launcher or a menu bar app does. Only an accessory app's windows can show over another app's full-screen Space. The tray block's accessory sets this too. Defaults to false.", - "type": "boolean" - }, - "devMenu": { - "description": "Whether the development menu is available. Defaults to true in development builds.", - "type": "boolean" - }, - "tray": { - "description": "A menu-bar or notification-area icon for the app.", - "type": "object", - "additionalProperties": false, - "properties": { - "component": { - "description": "The React component to render as the tray popover.", - "type": "string", - "minLength": 1 - }, - "tooltip": { - "description": "The tooltip text.", - "type": "string" - }, - "icon": { - "description": "The tray icon, a PNG or JPEG path relative to desktop/. Without one the tray shows a built-in glyph.", - "type": "string", - "minLength": 1 - }, - "iconTemplate": { - "description": "macOS: draw the icon as a template the menu bar tints for light and dark mode. Use it for a monochrome glyph. Defaults to false.", - "type": "boolean" - }, - "accessory": { - "description": "Whether the app runs as an accessory, with no Dock icon. Defaults to true.", - "type": "boolean" - }, - "popoverAnchor": { - "description": "Linux on Wayland: the corner of the screen's work area the popover is drawn in. 'auto' puts it at the end of the panel's edge, or centred on the click when the panel reports one. Ignored where the popover opens at the icon. Defaults to 'auto'.", - "enum": [ - "auto", - "top-left", - "top-right", - "bottom-left", - "bottom-right", - "center" - ] - }, - "popoverOffset": { - "description": "Linux on Wayland: moves the popover from its corner, in points.", - "type": "object", - "additionalProperties": false, - "required": ["x", "y"], - "properties": { - "x": { "type": "number" }, - "y": { "type": "number" } - } - } - } - }, - "bundle": { - "description": "How the app is packaged.", - "type": "object", - "additionalProperties": false, - "properties": { - "targets": { - "description": "The formats to build. 'all' means every alpha format for the current OS.", - "oneOf": [ - { - "type": "string", - "enum": ["all"] - }, - { - "type": "array", - "minItems": 1, - "items": { - "type": "string", - "enum": ["app", "dmg", "nsis", "deb", "appimage"] - } - } - ] - }, - "resources": { - "description": "Extra files to ship, relative to desktop/.", - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "copyright": { - "description": "The copyright line shown by installers.", - "type": "string" - }, - "category": { - "description": "The app category, for the Linux desktop entry.", - "type": "string" - }, - "macos": { - "type": "object", - "additionalProperties": false, - "properties": { - "minimumSystemVersion": { - "description": "The oldest macOS the app supports. Defaults to 13.0.", - "type": "string" - }, - "entitlements": { - "description": "A path to an entitlements plist, relative to desktop/.", - "type": ["string", "null"] - }, - "infoPlist": { - "description": "Extra keys merged into the generated Info.plist.", - "type": "object" - } - } - }, - "windows": { - "type": "object", - "additionalProperties": false, - "properties": { - "nsis": { - "type": "object", - "additionalProperties": false, - "properties": { - "installMode": { - "description": "Whether the installer installs for the current user or for everyone.", - "type": "string", - "enum": ["currentUser", "perMachine", "both"] - } - } - } - } - }, - "linux": { - "type": "object", - "additionalProperties": false, - "properties": { - "deb": { - "type": "object", - "additionalProperties": false, - "properties": { - "depends": { - "description": "Extra Debian package dependencies.", - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - } - } - }, - "appimage": { - "type": "object", - "additionalProperties": false, - "properties": {} - } - } - } - } - } - } -} diff --git a/vendor/react-native-gpui/packages/cli/package.json b/vendor/react-native-gpui/packages/cli/package.json deleted file mode 100644 index add249d56b..0000000000 --- a/vendor/react-native-gpui/packages/cli/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "@react-native-gpui/cli", - "version": "0.87.0-alpha.5", - "description": "React Native CLI integration and project scaffolding for the React Native desktop platform.", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/streetwriters/react-native-gpui.git", - "directory": "packages/cli" - }, - "homepage": "https://streetwriters.github.io/react-native-gpui/", - "bugs": { - "url": "https://github.com/streetwriters/react-native-gpui/issues" - }, - "files": [ - "bin", - "src", - "templates", - "assets", - "react-native.config.cjs", - "desktop.schema.json", - "CHANGELOG.md", - "!**/*.test.js", - "!**/*.test.mjs", - "!**/*.test.ts", - "!**/*.test.cjs" - ], - "bin": { - "react-native-gpui": "bin/react-native-gpui.js" - }, - "type": "module", - "dependencies": {}, - "publishConfig": { - "access": "public", - "tag": "latest" - } -} diff --git a/vendor/react-native-gpui/packages/cli/react-native.config.cjs b/vendor/react-native-gpui/packages/cli/react-native.config.cjs deleted file mode 100644 index 9274348408..0000000000 --- a/vendor/react-native-gpui/packages/cli/react-native.config.cjs +++ /dev/null @@ -1,246 +0,0 @@ -const { doctor, reactNativeHealthChecks } = require('./src/doctor.cjs'); - -module.exports = { - healthChecks: reactNativeHealthChecks(), - commands: [ - { - name: 'doctor-desktop', - description: - 'Check that the tools needed to build a desktop app are installed', - func: async () => { - process.exitCode = doctor(); - }, - examples: [ - { - desc: 'Check this machine', - cmd: 'npx react-native doctor-desktop', - }, - ], - }, - { - name: 'run-desktop', - description: 'Run the desktop app with Metro or as a release build', - func: async (_argv, _config, options) => { - const { runDesktop } = await import('./src/commands.js'); - if (options.renderer) process.env.RN_GPUI_RENDERER = options.renderer; - if (options.jsThread) process.env.RN_GPUI_JS_THREAD = options.jsThread; - await runDesktop({ - projectRoot: options.projectRoot, - entryFile: options.entryFile, - bundle: options.bundle, - config: options.config, - release: options.release, - port: options.port, - host: options.host, - features: options.features, - noLaunch: options.noLaunch === true || options.launch === false, - signIdentity: options.signIdentity, - packager: options.packager !== false && options.noPackager !== true, - packagerLog: options.packagerLog === true, - terminal: options.terminal, - }); - }, - options: [ - { name: '--entry-file ', description: 'Application entry file' }, - { - name: '--release', - description: 'Bundle JavaScript and build the optimized app', - }, - { - name: '--port ', - description: 'Metro server port (default: 8081)', - }, - { - name: '--host ', - description: 'Metro server host (default: localhost)', - }, - { name: '--config ', description: 'Metro configuration file' }, - { name: '--bundle ', description: 'Bundle output path' }, - { - name: '--features ', - description: 'Comma-separated Cargo features for the desktop app', - }, - { - name: '--no-launch', - description: - 'Build the desktop app without launching it. With the test-driver feature it also writes the JavaScript bundle the test driver loads', - }, - { - name: '--sign-identity ', - description: - 'macOS code signing identity for the built binary (default: $APPLE_SIGNING_IDENTITY). Applies to --no-launch builds too', - }, - { - name: '--no-packager', - description: 'Do not start Metro if it is not already running', - }, - { - name: '--terminal ', - description: - 'Terminal app Metro opens in (default: $REACT_TERMINAL, then the platform default)', - }, - { - name: '--packager-log', - description: - 'Run Metro in the background, logging to desktop/build/metro.log', - }, - { - name: '--renderer ', - description: - 'fabric or loom, overriding "renderer" in desktop/desktop.json. loom builds the native runtime from source', - }, - { - name: '--js-thread ', - description: - 'background or main, overriding "jsThread" in desktop/desktop.json. Only with the loom renderer. Rebuilds the Rust part of the runtime', - }, - ], - examples: [ - { - desc: 'Run with Metro and Fast Refresh', - cmd: 'npx react-native run-desktop', - }, - { - desc: 'Build a bundled release', - cmd: 'npx react-native run-desktop --release', - }, - { - desc: 'Run with the Loom renderer and JavaScript on the main thread', - cmd: 'npx react-native run-desktop --renderer loom --js-thread main', - }, - ], - }, - { - name: 'package-desktop', - description: - 'Build installable packages for this OS from desktop/desktop.json', - func: async (_argv, _config, options) => { - const { packageDesktop } = await import('./src/commands.js'); - await packageDesktop({ - projectRoot: options.projectRoot, - targets: options.target, - outDir: options.out, - }); - }, - options: [ - { - name: '--target ', - description: - 'Comma-separated formats: app, dmg, nsis, deb, appimage (default: all for this OS)', - }, - { - name: '--project-root ', - description: 'React Native project directory', - }, - { name: '--out ', description: 'Output directory' }, - ], - examples: [ - { - desc: 'Build every format this OS can produce', - cmd: 'npx react-native package-desktop', - }, - { - desc: 'Build only a dmg', - cmd: 'npx react-native package-desktop --target dmg', - }, - ], - }, - { - name: 'init-desktop', - description: 'Add desktop support to an existing React Native app', - func: async (_argv, _config, options) => { - const { initDesktop } = await import('./src/commands.js'); - initDesktop({ - projectRoot: options.projectRoot, - skipInstall: options.skipInstall, - }); - }, - options: [ - { - name: '--project-root ', - description: 'React Native project directory', - }, - { - name: '--skip-install', - description: 'Write the scaffold without installing packages', - }, - ], - examples: [ - { - desc: 'Add desktop support to this app', - cmd: 'npx react-native init-desktop', - }, - ], - }, - { - name: 'create-library ', - description: 'Create a desktop TurboModule library in a new directory', - func: async (argv, _config, options) => { - const { createLibrary } = await import('./src/commands.js'); - createLibrary({ - libraryName: argv[0], - type: options.type, - destination: options.directory, - moduleName: options.moduleName, - packageName: options.packageName, - }); - }, - options: [ - { - name: '--type ', - description: 'Native implementation language (default: rust)', - }, - { name: '--directory ', description: 'Output directory' }, - { - name: '--module-name ', - description: 'Native TurboModule name', - }, - { name: '--package-name ', description: 'npm package name' }, - ], - examples: [ - { - desc: 'Create a Rust TurboModule package', - cmd: 'npx react-native create-library AwesomeStorage', - }, - { - desc: 'Create a C++ TurboModule package', - cmd: 'npx react-native create-library AwesomeStorage --type cpp', - }, - ], - }, - { - name: 'collect-node-addons', - description: - 'Copy the Node addons a bundle loads next to a packaged app executable', - func: async (_argv, _config, options) => { - const { collectNodeAddons } = await import('./src/commands.js'); - collectNodeAddons({ - bundle: options.bundle, - out: options.out, - platform: options.platform, - }); - }, - options: [ - { - name: '--bundle ', - description: 'The bundle file to scan for _requireNodeLibrary calls', - }, - { - name: '--out ', - description: 'Directory to copy the addons into', - }, - { - name: '--platform ', - description: - 'Target platform for shared-library matching (default: the host)', - }, - ], - examples: [ - { - desc: 'Collect the addons a release bundle loads', - cmd: 'npx react-native collect-node-addons --bundle build/index.bundle --out build/node-addons', - }, - ], - }, - ], -}; diff --git a/vendor/react-native-gpui/packages/cli/src/autolink.js b/vendor/react-native-gpui/packages/cli/src/autolink.js deleted file mode 100644 index 02ea7fccf9..0000000000 --- a/vendor/react-native-gpui/packages/cli/src/autolink.js +++ /dev/null @@ -1,1702 +0,0 @@ -import { Buffer } from 'node:buffer'; -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { execFileSync } from 'node:child_process'; -import { createRequire } from 'node:module'; -import { loadDesktopConfig } from './desktop-config.js'; - -// npm ships npx as a .cmd shim on Windows, where child_process cannot resolve a -// command without its extension, and Node refuses to spawn .cmd/.bat files -// without a shell (the CVE-2024-27980 fix), so npx runs through the shell -// there. A shell joins the arguments into one command line, so arguments with -// spaces are quoted here first. -export const npxCommand = process.platform === 'win32' ? 'npx.cmd' : 'npx'; -export const npxShell = process.platform === 'win32'; -export const npxArgs = args => - npxShell ? args.map(arg => (/\s/u.test(arg) ? `"${arg}"` : arg)) : args; - -/** - * Write a generated file only when its content differs. Cargo and CMake go by - * modification time, so rewriting an identical file makes every launch rebuild - * the C++ bridge and each crate that depends on it. - */ -function writeIfChanged(file, contents) { - try { - if (fs.readFileSync(file, 'utf8') === contents) return; - } catch {} - fs.writeFileSync(file, contents); -} - -const findCppSources = directory => { - if (!directory || !fs.existsSync(directory)) return []; - return fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => { - const entryPath = path.join(directory, entry.name); - if (entry.isDirectory()) return findCppSources(entryPath); - return /\.(?:cc|cpp|cxx)$/u.test(entry.name) ? [entryPath] : []; - }); -}; - -/// Crates a module crate must depend on by version, never by path or git. -/// -/// They live under `@react-native-gpui/core` at a path that only exists inside -/// this repository. A published module crate resolves relative paths from -/// `node_modules/@react-native-gpui//desktop`, where `../../../packages` -/// is nowhere. So the crate names a crates.io version and autolink patches it, -/// in the app's root manifest, to the core that is actually installed. -const MANAGED_CRATES = [ - 'react-native-gpui', - 'rn-gpui-sys', - 'rn-gpui-module', - 'rn-gpui-module-build', - 'gpui', - 'gpui_platform', -]; - -/// The version each managed crate is patched to, when it is a path dependency. -const CORE_CRATE_VERSION = '0.1'; - -/// The crates GPUI Kit (published on crates.io against `gpui-pre`) names, which -/// autolink redirects to the gpui-fast compat crates of core's pin, so the kit -/// runs on the same GPUI as core. The first three are patched whenever a linked -/// module crate depends on the kit; the others only when something names them, -/// because Cargo warns about a patch the crate graph does not use. -const GPUI_KIT_PATCHES = ['gpui-pre', 'gpui-pre-macros', 'gpui-pre-sum-tree']; -const GPUI_KIT_OPTIONAL_PATCHES = [ - 'gpui-pre-platform', - 'gpui-pre-web', - 'gpui-pre-reqwest-client', -]; -const GPUI_KIT_DEPENDENCY = - /^(?:gpui-base|gpui-component|gpui-kit(?:-[a-z0-9-]+)?|gpui-pre(?:-[a-z0-9-]+)?)$/u; - -const PATCH_BEGIN = - '# Managed by @react-native-gpui/cli autolink; do not edit between these markers.'; -const PATCH_END = '# End managed by autolink.'; - -/** - * The gpui pin, read from core's manifest. - * - * Core owns the revision (`GPUI_PIN.md` says so), and a module that copied it - * would drift the moment the pin moved. The npm package ships `ReactGpui`, so - * the manifest is always beside the installed crate. - */ -function gpuiPin(platformRoot) { - const manifest = path.join(platformRoot, 'ReactGpui/Cargo.toml'); - let text; - try { - // Normalised for consistency with the lockfile read below. This pattern - // happens to survive CRLF on its own, because `\s*$` treats `\r` as - // whitespace, but relying on that is a trap for the next edit. - text = fs.readFileSync(manifest, 'utf8').replace(/\r\n/gu, '\n'); - } catch (error) { - throw new Error( - `could not read the gpui pin from ${manifest}: ${error.message}`, - ); - } - const workspace = /^\[workspace\.dependencies\]\s*$/mu.exec(text); - if (workspace === null) { - throw new Error(`${manifest} has no [workspace.dependencies] table`); - } - const start = workspace.index; - const nextTable = text.indexOf('\n[', start + 1); - const table = text.slice(start, nextTable < 0 ? text.length : nextTable); - const pin = name => { - const line = new RegExp(`^${name}\\s*=\\s*\\{([^}]*)\\}`, 'mu').exec(table); - if (line === null) { - throw new Error( - `${manifest} declares no ${name} in [workspace.dependencies]`, - ); - } - const git = /git\s*=\s*"([^"]+)"/u.exec(line[1]); - const rev = /rev\s*=\s*"([^"]+)"/u.exec(line[1]); - if (git === null || rev === null) { - throw new Error( - `${manifest}: ${name} is not a git dependency with a rev`, - ); - } - return { git: git[1], rev: rev[1] }; - }; - return { gpui: pin('gpui'), gpuiPlatform: pin('gpui_platform') }; -} - -/** - * The managed `[patch.crates-io]` block, or the text to append. - * - * `[patch]` only takes effect in the root manifest, which is why this is written - * into the app rather than into each module crate. - */ -function patchBlock(entries) { - return [ - PATCH_BEGIN, - ...entries.map(([name, spec]) => `${name} = ${spec}`), - PATCH_END, - ].join('\n'); -} - -/** - * A TOML string literal for a value. - * - * JSON's string syntax is a subset of TOML's for the characters paths contain, so - * quoting through it keeps a Windows path's backslashes escaped correctly. - */ -function rustRawString(text) { - let hashes = '#'; - while (text.includes(`"${hashes}`)) hashes += '#'; - return `r${hashes}"${text}"${hashes}`; -} - -function escapeToml(value) { - return JSON.stringify(value); -} - -/** - * The `[patch.crates-io]` entries that point every managed crate at core. - * - * Exported because a second root manifest needs the same table: a module crate - * that declares `[workspace]` to become testable is its own root, and Cargo - * honours `[patch]` only there. Copying the block by hand reintroduces exactly - * the drift these entries exist to prevent — the gpui revision is read from - * core's manifest here, not written down anywhere. - * - * `platformRoot` is the installed core package, whose gated gpui pin is the - * authority; `base` is the directory the paths are written relative to, which - * for an app manifest is its `desktop/` directory. - */ -/** - * The spec files a package hands to one side. A package with both a C++ - * provider and a Rust crate lists the C++ ones in `cppSpecs`: the provider - * serves those and the crate the rest. Without `cppSpecs` both get every spec. - */ -export function specFilesFor(files, cppSpecs, side) { - if (cppSpecs === undefined) return files; - if ( - !Array.isArray(cppSpecs) || - cppSpecs.some(name => typeof name !== 'string') - ) { - throw new Error( - 'platforms.desktop.cppSpecs must be an array of file names', - ); - } - const missing = cppSpecs.filter(name => !files.includes(name)); - if (missing.length > 0) { - throw new Error( - `platforms.desktop.cppSpecs names ${missing.join(', ')}, which is not a specification of the package`, - ); - } - return files.filter(file => cppSpecs.includes(file) === (side === 'cpp')); -} - -/** - * The crate names a manifest depends on, in any dependency section (also the - * target-specific, dev and build ones), with a renamed dependency under the - * name of the package it points at. - */ -export function manifestDependencyNames(manifest) { - const names = []; - const lines = manifest.replace(/\r\n/gu, '\n').split('\n'); - let section = ''; - let tableName = null; - for (const line of lines) { - const table = /^\[([^\]]+)\]\s*$/u.exec(line); - if (table !== null) { - if (tableName !== null) names.push(tableName.name); - tableName = null; - section = table[1].trim(); - const single = - /^(?:target\..+\.)?(?:dev-|build-)?dependencies\.([A-Za-z0-9_-]+)$/u.exec( - section, - ); - if (single !== null) tableName = { name: single[1] }; - continue; - } - if (tableName !== null) { - const renamed = /^package\s*=\s*"([^"]+)"/u.exec(line.trim()); - if (renamed !== null) tableName.name = renamed[1]; - continue; - } - if (!/^(?:target\..+\.)?(?:dev-|build-)?dependencies$/u.test(section)) { - continue; - } - const entry = /^([A-Za-z0-9_-]+)\s*=\s*(.+?)\s*(?:#.*)?$/u.exec(line); - if (entry === null) continue; - names.push(/package\s*=\s*"([^"]+)"/u.exec(entry[2])?.[1] ?? entry[1]); - } - if (tableName !== null) names.push(tableName.name); - return names; -} - -/** - * The GPUI Kit crates to patch for the linked module crates' manifests, and - * the app's lockfile when it has one: none when no module depends on the kit. - */ -export function gpuiKitPatchNames(moduleManifests, appLockfile = '') { - const named = moduleManifests.flatMap(manifestDependencyNames); - if (!named.some(name => GPUI_KIT_DEPENDENCY.test(name))) return []; - const locked = [...appLockfile.matchAll(/^name = "([^"]+)"$/gmu)].map( - match => match[1], - ); - return [ - ...GPUI_KIT_PATCHES, - ...GPUI_KIT_OPTIONAL_PATCHES.filter( - name => named.includes(name) || locked.includes(name), - ), - ]; -} - -export function managedPatchEntries(platformRoot, base, kitCrates = []) { - const runtimeCrate = path.join(platformRoot, 'ReactGpui/rn-gpui'); - const pin = gpuiPin(platformRoot); - const relative = target => - escapeToml(path.relative(base, target).split(path.sep).join('/')); - return [ - ...MANAGED_CRATES.filter( - crate => crate !== 'gpui' && crate !== 'gpui_platform', - ).map(crate => [ - crate, - // The directory is not always the crate name: `react-native-gpui` lives - // in `rn-gpui`, so the path is built from the directory, not the key. - `{ path = ${relative( - crate === 'react-native-gpui' - ? runtimeCrate - : path.join(path.dirname(runtimeCrate), crate), - )} }`, - ]), - ['gpui', `{ git = "${pin.gpui.git}", rev = "${pin.gpui.rev}" }`], - [ - 'gpui_platform', - `{ git = "${pin.gpuiPlatform.git}", rev = "${pin.gpuiPlatform.rev}" }`, - ], - ...kitCrates.map(crate => [ - crate, - `{ git = "${pin.gpui.git}", rev = "${pin.gpui.rev}" }`, - ]), - ]; -} - -/** - * Whether `section` of a manifest declares `name`, inline or as its own - * `[section.name]` table. The managed `[patch.crates-io]` block names the same - * crates, so a search of the whole file finds them there and wrongly concludes - * the dependency exists. - */ -function declaresDependency(manifest, section, name) { - const header = new RegExp(`^\\[${section}\\]\\s*$`, 'mu').exec(manifest); - if (header !== null) { - const start = header.index + header[0].length; - const next = manifest.indexOf('\n[', start); - const body = manifest.slice(start, next < 0 ? manifest.length : next); - if (new RegExp(`^${name}\\s*=`, 'mu').test(body)) return true; - } - return new RegExp(`^\\[${section}\\.${name}\\]\\s*$`, 'mu').test(manifest); -} - -/** - * Points an app dependency on a core crate at its canonical path. A dependency - * written as a version is left alone, because the managed patch block already - * redirects it. A path that goes through a symlink (a `file:`-linked core) is - * replaced: Cargo treats the linked and the real path as two different crates - * and refuses the lockfile. - */ -function ensurePathDependency(manifest, section, name, tomlPath) { - const entry = `${name} = { path = ${tomlPath} }`; - if (!declaresDependency(manifest, section, name)) { - const header = new RegExp(`^\\[${section}\\]\\s*$`, 'mu'); - return header.test(manifest) - ? manifest.replace(header, line => `${line}\n${entry}`) - : `${manifest}\n[${section}]\n${entry}\n`; - } - const header = new RegExp(`^\\[${section}\\]\\s*$`, 'mu').exec(manifest); - const start = header.index + header[0].length; - const next = manifest.indexOf('\n[', start); - const end = next < 0 ? manifest.length : next; - const inline = new RegExp(`^(${name}\\s*=\\s*)\\{([^\\n]*)\\}$`, 'mu'); - const body = manifest - .slice(start, end) - .replace(inline, (line, prefix, properties) => { - if (!/(?:^|,)\s*path\s*=/u.test(properties)) return line; - const rest = properties - .replace(/(?:^|,)\s*path\s*=\s*"[^"]*"\s*/gu, '') - .trim() - .replace(/^,\s*|\s*,\s*$/gu, ''); - return `${prefix}{ path = ${tomlPath}${rest ? `, ${rest}` : ''} }`; - }); - return `${manifest.slice(0, start)}${body}${manifest.slice(end)}`; -} - -/** - * Insert or replace the managed block in an app manifest. - * - * Idempotent: a second run must produce the same bytes, because `writeIfChanged` - * depends on it and a rewritten manifest makes Cargo rebuild everything. - */ -export function applyPatchBlock(manifest, manifestPath, entries) { - const block = patchBlock(entries); - const managed = new RegExp( - `${PATCH_BEGIN.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')}[\\s\\S]*?${PATCH_END.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')}`, - 'u', - ); - if (managed.test(manifest)) { - const outside = manifest.replace(managed, ''); - const table = /^\[patch\.crates-io\]\s*$/mu.exec(outside); - if (table !== null) { - const next = outside.indexOf('\n[', table.index + 1); - const body = outside.slice(table.index, next < 0 ? outside.length : next); - for (const [name] of entries) { - if (new RegExp(`^${name}\\s*=`, 'mu').test(body)) { - throw new Error( - `${manifestPath}: [patch.crates-io] already sets ${name}, which autolink owns; remove that line so it can be managed`, - ); - } - } - } - return manifest.replace(managed, block); - } - - const header = /^\[patch\.crates-io\]\s*$/mu.exec(manifest); - if (header !== null) { - // A table the user wrote. Cargo rejects a second header, so the block goes - // inside theirs — but a duplicate key would make the manifest invalid, and - // silently overwriting their line would be worse, so that is an error. - const start = header.index; - const nextTable = manifest.indexOf('\n[', start + 1); - const end = nextTable < 0 ? manifest.length : nextTable; - const body = manifest.slice(start, end); - for (const [name] of entries) { - if (new RegExp(`^${name}\\s*=`, 'mu').test(body)) { - throw new Error( - `${manifestPath}: [patch.crates-io] already sets ${name}, which autolink owns; remove that line so it can be managed`, - ); - } - } - const headerEnd = start + header[0].length; - return `${manifest.slice(0, headerEnd)}\n${block}${manifest.slice(headerEnd)}`; - } - - const separator = manifest.endsWith('\n') ? '' : '\n'; - return `${manifest}${separator}\n[patch.crates-io]\n${block}\n`; -} - -/// Every `[dependencies]`-style entry for a managed crate, with its raw value. -function managedDependencyEntries(manifest) { - const found = []; - let section = ''; - const lines = manifest.split('\n'); - for (let index = 0; index < lines.length; index += 1) { - const line = lines[index]; - const table = /^\[([^\]]+)\]\s*$/u.exec(line); - if (table !== null) { - section = table[1]; - // The table form puts one crate's keys on following lines: - // `[dependencies.gpui]` then `git = "…"`. Rare, but legal, and skipping it - // would leave a way past the check this function exists for. - const tableForm = /^dependencies\.([A-Za-z0-9_-]+)$/u.exec(section); - if (tableForm !== null && MANAGED_CRATES.includes(tableForm[1])) { - const keys = []; - for (let inner = index + 1; inner < lines.length; inner += 1) { - if (/^\[/u.test(lines[inner])) break; - keys.push(lines[inner]); - } - found.push({ crate: tableForm[1], value: keys.join('\n') }); - } - continue; - } - if (!/(?:^|[-.])dependencies$/u.test(section)) continue; - const entry = /^([A-Za-z0-9_-]+)\s*=\s*(.+?)\s*(?:#.*)?$/u.exec(line); - if (entry === null) continue; - const renamed = /package\s*=\s*"([^"]+)"/u.exec(entry[2]); - const crate = renamed === null ? entry[1] : renamed[1]; - if (!MANAGED_CRATES.includes(crate)) continue; - found.push({ crate, value: entry[2] }); - } - return found; -} - -/** - * Whether a version requirement accepts `version`, for the forms the ecosystem - * actually writes. Anything else is rejected rather than guessed at, because the - * failure mode is silent: a requirement the patch does not satisfy makes Cargo - * print one warning and resolve the real crates.io crate instead. - */ -function versionSatisfies(requirement, version) { - const text = requirement.trim(); - const parse = value => { - const parts = value.split('.').map(Number); - if (parts.some(Number.isNaN)) return undefined; - return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0]; - }; - const compare = (a, b) => { - for (let index = 0; index < 3; index += 1) { - if (a[index] !== b[index]) return a[index] - b[index]; - } - return 0; - }; - const exact = /^=\s*(\d+(?:\.\d+){0,2})$/u.exec(text); - if (exact !== null) return compare(parse(exact[1]), parse(version)) === 0; - const tilde = /^~\s*(\d+(?:\.\d+){0,2})$/u.exec(text); - if (tilde !== null) { - const [major, minor] = parse(tilde[1]); - const actual = parse(version); - return ( - actual[0] === major && - actual[1] === minor && - compare(actual, [major, minor, 0]) >= 0 - ); - } - const plain = /^\^?\s*(\d+(?:\.\d+){0,2})$/u.exec(text); - if (plain !== null) { - const parts = parse(plain[1]); - const actual = parse(version); - // Caret semantics: the leftmost non-zero component may not change. - if (parts[0] > 0) - return actual[0] === parts[0] && compare(actual, parts) >= 0; - if (parts[1] > 0) - return ( - actual[0] === 0 && actual[1] === parts[1] && compare(actual, parts) >= 0 - ); - return compare(actual, parts) === 0; - } - throw new Error(`unsupported version requirement "${text}"`); -} - -/** - * Reject a module crate that names a managed crate by path or git. - * - * `[patch]` cannot redirect a `path` dependency, and a git dependency of the - * same repository at another rev is rejected by Cargo. Either would fail for - * someone installing the package, a long way from the cause, so it is refused - * here with the fix in the message. A version requirement that the patch does - * not satisfy is worse than a failure: Cargo warns once and quietly resolves the - * real crates.io crate, so `gpui = "0.3"` would build against Zed's gpui. - */ -export function validateModuleManifest( - dependencyName, - cargoPath, - platformRoot, -) { - const manifestPath = path.join(cargoPath, 'Cargo.toml'); - let manifest; - try { - manifest = fs.readFileSync(manifestPath, 'utf8'); - } catch (error) { - throw new Error( - `${dependencyName}: could not read ${manifestPath}: ${error.message}`, - ); - } - const patchedVersions = patchedCrateVersions(platformRoot); - for (const { crate, value } of managedDependencyEntries(manifest)) { - const expected = - crate === 'gpui' || crate === 'gpui_platform' - ? `{ version = "${patchedVersions[crate]}", features = [...] }` - : `${crate} = "${CORE_CRATE_VERSION}"`; - if (/\bpath\s*=/u.test(value) || /\bgit\s*=/u.test(value)) { - throw new Error( - `${dependencyName}: ${crate} must be a version requirement (e.g. ${expected}), not a path or git dependency; autolink points it at the installed @react-native-gpui/core`, - ); - } - // A bare form is `crate = "0.1"`, where the value is the requirement with its - // quotes still on; an inline table is `crate = { version = "0.1" }`. - const bare = /^"([^"]*)"$/u.exec(value.trim())?.[1]; - const requirement = - /\bversion\s*=\s*"([^"]+)"/u.exec(value)?.[1] ?? bare ?? value; - const version = patchedVersions[crate]; - if (!versionSatisfies(requirement, version)) { - throw new Error( - `${dependencyName}: ${crate} requires "${requirement}", which does not match the ${version} that autolink patches to; Cargo would resolve the crates.io crate instead`, - ); - } - } -} - -/** - * The version each managed crate resolves to once patched. - * - * Core crates are `0.1.0`. The gpui crates come from the git pin, so their - * versions are read from the lockfile that describes that revision — the - * numbers cannot be assumed, and `gpui`'s crates.io crate is also `0.2.2`, which - * is exactly the collision the version check exists to catch. - */ -function patchedCrateVersions(platformRoot) { - const versions = {}; - for (const crate of [ - 'react-native-gpui', - 'rn-gpui-sys', - 'rn-gpui-module', - 'rn-gpui-module-build', - ]) { - versions[crate] = CORE_CRATE_VERSION; - } - const lockPath = path.join(platformRoot, 'ReactGpui/Cargo.lock'); - let lock; - try { - // Same reason as the manifest above: the pattern is line-anchored. - lock = fs.readFileSync(lockPath, 'utf8').replace(/\r\n/gu, '\n'); - } catch (error) { - throw new Error(`could not read ${lockPath}: ${error.message}`); - } - for (const crate of ['gpui', 'gpui_platform']) { - const block = new RegExp( - `\\[\\[package\\]\\]\\nname = "${crate}"\\nversion = "([^"]+)"\\nsource = "git\\+https://github\\.com/streetwriters/gpui-fast[^"]*"`, - 'u', - ).exec(lock); - if (block === null) { - throw new Error( - `${lockPath} has no ${crate} from the gpui-fast git source`, - ); - } - versions[crate] = block[1]; - } - return versions; -} - -const cppIdentifier = /^[A-Za-z_][A-Za-z0-9_]*$/u; -const includePath = /^[A-Za-z0-9_./+-]+$/u; -const jsEngineName = /^[a-z][a-z0-9-]*$/u; -const prebuiltModes = ['auto', 'always', 'never']; - -/** A dependency's `platforms.desktop` entry. */ -function desktopPlatformFor(dependency) { - return dependency.platforms?.desktop; -} - -/** The app's `project.desktop` entry. */ -function desktopProjectFor(config) { - return config.project?.desktop; -} - -/** - * Reads the app's `project.desktop.prebuilt` option: `auto` uses the pinned - * prebuilt C++ runtime when it matches and builds from source otherwise, - * `always` fails the build instead of falling back, `never` builds from source. - */ -function prebuiltModeFor(project) { - const prebuilt = project?.prebuilt ?? 'auto'; - if (!prebuiltModes.includes(prebuilt)) { - throw new Error( - `project.desktop.prebuilt must be one of ${prebuiltModes.map(mode => `'${mode}'`).join(', ')}`, - ); - } - return prebuilt; -} - -/** - * Validates a dependency's `platforms.desktop.jsEngine` entry. Installing a - * package that declares one is how an app opts into an engine; the entry names - * the C registration symbol core calls at startup and the optional JS tooling - * hooks the CLI uses. - */ -function jsEngineConfigFor(dependencyName, packageRoot, jsEngine) { - if ( - typeof jsEngine !== 'object' || - jsEngine === null || - Array.isArray(jsEngine) - ) { - throw new Error( - `${dependencyName}: platforms.desktop.jsEngine must be an object`, - ); - } - const { - name, - register, - bundle, - runtimeFiles, - nodeApiExports, - nodeApiLibrary, - } = jsEngine; - if (typeof name !== 'string' || !jsEngineName.test(name)) { - throw new Error( - `${dependencyName}: platforms.desktop.jsEngine.name must be a lowercase engine name (${jsEngineName})`, - ); - } - if (typeof register !== 'string' || !cppIdentifier.test(register)) { - throw new Error( - `${dependencyName}: platforms.desktop.jsEngine.register must be a C identifier`, - ); - } - const resolveHook = (key, value) => { - if (value === undefined) return undefined; - if (typeof value !== 'string' || value.length === 0) { - throw new Error( - `${dependencyName}: platforms.desktop.jsEngine.${key} must be a path`, - ); - } - const resolved = path.resolve(packageRoot, value); - if (!fs.existsSync(resolved)) { - throw new Error( - `${dependencyName}: platforms.desktop.jsEngine.${key} does not exist: ${resolved}`, - ); - } - return resolved; - }; - // The Node-API export list is what the app's executable re-exports on Windows, - // so the name has to be a plain library name: it becomes the DLL half of each - // forwarded export (`napi_x = hermesvm.napi_x`). - if ( - nodeApiExports !== undefined && - (typeof nodeApiLibrary !== 'string' || - !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(nodeApiLibrary)) - ) { - throw new Error( - `${dependencyName}: platforms.desktop.jsEngine.nodeApiLibrary must be a library name when nodeApiExports is set`, - ); - } - return { - dependencyName, - name, - register, - bundle: resolveHook('bundle', bundle), - runtimeFiles: resolveHook('runtimeFiles', runtimeFiles), - nodeApiExports: resolveHook('nodeApiExports', nodeApiExports), - nodeApiLibrary: nodeApiExports === undefined ? undefined : nodeApiLibrary, - }; -} - -function componentConfigFor(dependencyName, gpui) { - const descriptors = gpui.componentDescriptors ?? []; - const headers = gpui.componentHeaders ?? []; - const sources = gpui.componentSources ?? []; - const includeDirs = gpui.componentIncludeDirs ?? []; - const sourcePackage = gpui.componentSourcePackage; - if ( - !Array.isArray(descriptors) || - !descriptors.every( - value => typeof value === 'string' && cppIdentifier.test(value), - ) - ) { - throw new Error( - `${dependencyName}: platforms.desktop.componentDescriptors must be an array of C++ identifiers`, - ); - } - if ( - !Array.isArray(headers) || - !headers.every( - value => - typeof value === 'string' && - includePath.test(value) && - value.endsWith('.h'), - ) - ) { - throw new Error( - `${dependencyName}: platforms.desktop.componentHeaders must be an array of C++ header paths`, - ); - } - if (headers.some(value => value.split('/').includes('..'))) { - throw new Error( - `${dependencyName}: componentHeaders must not escape the include search path`, - ); - } - if (descriptors.length > 0 && headers.length === 0) { - throw new Error( - `${dependencyName}: componentHeaders is required when componentDescriptors are declared`, - ); - } - if ( - !Array.isArray(sources) || - !sources.every(value => typeof value === 'string') - ) { - throw new Error( - `${dependencyName}: platforms.desktop.componentSources must be an array of source paths`, - ); - } - if ( - !Array.isArray(includeDirs) || - !includeDirs.every(value => typeof value === 'string') - ) { - throw new Error( - `${dependencyName}: platforms.desktop.componentIncludeDirs must be an array of paths`, - ); - } - if ( - sourcePackage !== undefined && - (typeof sourcePackage !== 'string' || - !/^(?:@[A-Za-z0-9._-]+\/)?[A-Za-z0-9._-]+$/u.test(sourcePackage)) - ) { - throw new Error( - `${dependencyName}: platforms.desktop.componentSourcePackage must be a package name`, - ); - } - return { - descriptors, - headers, - sources, - includeDirs, - sourcePackage, - hostComponents: hostComponentsFor(dependencyName, gpui), - }; -} - -/** - * The host components a package registers, from - * `platforms.desktop.hostComponents`. - */ -function hostComponentsFor(dependencyName, gpui) { - const hostComponents = gpui.hostComponents ?? []; - if (!Array.isArray(hostComponents)) { - throw new Error( - `${dependencyName}: platforms.desktop.hostComponents must be an array`, - ); - } - return hostComponents.map(entry => { - if ( - entry === null || - typeof entry !== 'object' || - typeof entry.name !== 'string' || - !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(entry.name) - ) { - throw new Error( - `${dependencyName}: each platforms.desktop.hostComponents entry needs a "name" that is a component identifier`, - ); - } - if (entry.measured !== undefined && typeof entry.measured !== 'boolean') { - throw new Error( - `${dependencyName}: hostComponents "${entry.name}" has a non-boolean "measured"`, - ); - } - if ( - entry.nativeSurface !== undefined && - typeof entry.nativeSurface !== 'boolean' - ) { - throw new Error( - `${dependencyName}: hostComponents "${entry.name}" has a non-boolean "nativeSurface"`, - ); - } - if (entry.container !== undefined && typeof entry.container !== 'boolean') { - throw new Error( - `${dependencyName}: hostComponents "${entry.name}" has a non-boolean "container"`, - ); - } - if ( - entry.maskChildren !== undefined && - typeof entry.maskChildren !== 'boolean' - ) { - throw new Error( - `${dependencyName}: hostComponents "${entry.name}" has a non-boolean "maskChildren"`, - ); - } - if (entry.cpp !== undefined && typeof entry.cpp !== 'boolean') { - throw new Error( - `${dependencyName}: hostComponents "${entry.name}" has a non-boolean "cpp"`, - ); - } - if ( - entry.cpp === true && - (entry.measured === true || entry.container === true) - ) { - throw new Error( - `${dependencyName}: hostComponents "${entry.name}" cannot be "cpp" and also "measured" or a "container"; a C++ host component implements neither`, - ); - } - if ( - entry.maskChildren === true && - (entry.measured === true || entry.cpp === true) - ) { - throw new Error( - `${dependencyName}: hostComponents "${entry.name}" cannot be "maskChildren" and also "measured" or "cpp"; a masking component is a view that holds children`, - ); - } - if (entry.measured === true && entry.container === true) { - throw new Error( - `${dependencyName}: hostComponents "${entry.name}" cannot be both "measured" and a "container"; a measured component is a leaf, and a leaf cannot hold children`, - ); - } - return { - name: entry.name, - measured: entry.measured === true, - nativeSurface: entry.nativeSurface === true, - container: entry.container === true, - cpp: entry.cpp === true, - maskChildren: entry.maskChildren === true, - }; - }); -} - -function generateComponentCodegen({ - appRequire, - packageJson, - packageRoot, - dependencyName, - gpui, - generatedRoot, - hostComponents = [], -}) { - const componentCodegenPackage = gpui.componentCodegenPackage; - let codegenPackageRoot = packageRoot; - let codegenPackageJson = packageJson; - if (componentCodegenPackage !== undefined) { - if ( - typeof componentCodegenPackage !== 'string' || - !/^(?:@[A-Za-z0-9._-]+\/)?[A-Za-z0-9._-]+$/u.test(componentCodegenPackage) - ) { - throw new Error( - `${dependencyName}: platforms.desktop.componentCodegenPackage must be a package name`, - ); - } - const packageJsonPath = appRequire.resolve( - `${componentCodegenPackage}/package.json`, - ); - codegenPackageRoot = path.dirname(packageJsonPath); - codegenPackageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); - } - const codegenConfig = codegenPackageJson.codegenConfig; - if (!codegenConfig || !['components', 'all'].includes(codegenConfig.type)) - return { sources: [], libraryName: undefined }; - const jsSrcsDir = path.resolve( - codegenPackageRoot, - codegenConfig.jsSrcsDir ?? '', - ); - if (!fs.existsSync(jsSrcsDir)) { - throw new Error( - `${dependencyName}: Codegen source directory does not exist: ${jsSrcsDir}`, - ); - } - const specs = []; - const visit = directory => { - for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { - const entryPath = path.join(directory, entry.name); - if (entry.isDirectory()) visit(entryPath); - else if (/\.(?:js|jsx|ts|tsx)$/u.test(entry.name)) specs.push(entryPath); - } - }; - visit(jsSrcsDir); - const schema = appRequire( - '@react-native/codegen/lib/cli/combine/combine-js-to-schema', - ).combineSchemasInFileList(specs, 'desktop', null, codegenConfig.name); - if ( - !Object.values(schema.modules ?? {}).some( - module => module.type === 'Component', - ) - ) - return { sources: [], libraryName: undefined }; - const libraryName = codegenConfig.name; - if ( - typeof libraryName !== 'string' || - !/^[A-Za-z][A-Za-z0-9_]*$/u.test(libraryName) - ) { - throw new Error( - `${dependencyName}: codegenConfig.name must be a C++ identifier for Fabric component codegen`, - ); - } - const codegenPackage = appRequire.resolve( - '@react-native/codegen/package.json', - ); - const codegenRoot = path.dirname(codegenPackage); - const rnCodegen = appRequire( - path.join(codegenRoot, 'lib/generators/RNCodegen.js'), - ); - const outputDirectory = path.join( - generatedRoot, - libraryName, - 'react/renderer/components', - libraryName, - ); - // Generate into a staging directory and copy only what changed, as the - // TurboModule path below does: Codegen rewrites every file, and a fresh - // mtime on these headers reruns rn-gpui-sys's build script on every launch. - const stagingDirectory = fs.mkdtempSync( - path.join(os.tmpdir(), 'rn-gpui-codegen-'), - ); - try { - const generated = rnCodegen.generate( - { - libraryName, - schema, - outputDirectory: stagingDirectory, - packageName: packageJson.name, - assumeNonnull: false, - }, - { - generators: [ - 'descriptors', - 'events', - 'props', - 'states', - 'shadow-nodes', - ], - }, - ); - if (generated !== true) { - throw new Error( - `${dependencyName}: React Native Codegen failed for Fabric components`, - ); - } - for (const file of findGeneratedFiles(stagingDirectory)) { - const target = path.join( - outputDirectory, - path.relative(stagingDirectory, file), - ); - fs.mkdirSync(path.dirname(target), { recursive: true }); - writeIfChanged(target, fs.readFileSync(file, 'utf8')); - } - } finally { - fs.rmSync(stagingDirectory, { recursive: true, force: true }); - } - let hostComponentLibrary; - if (hostComponents.length > 0) { - const specPaths = specs.filter(file => - /export\s+default\s+\(?codegenNativeComponent [ - component.name, - component.maskChildren ? { ...component, container: true } : component, - ]), - ); - const { generateHostComponentCpp } = appRequire( - '@react-native-gpui/codegen/generate-host-component-cpp', - ); - const generatedCpp = generateHostComponentCpp({ - specPaths, - libraryName, - components, - }); - writeIfChanged( - path.join(outputDirectory, 'GpuiHostComponents.generated.cpp'), - generatedCpp, - ); - hostComponentLibrary = libraryName; - } - const sources = findCppSources(outputDirectory); - return { sources, libraryName, hostComponentLibrary }; -} - -const findGeneratedFiles = directory => { - if (!fs.existsSync(directory)) return []; - return fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => { - const entryPath = path.join(directory, entry.name); - if (entry.isDirectory()) return findGeneratedFiles(entryPath); - return [entryPath]; - }); -}; - -/** - * Generates the C++ TurboModule specs for one package: our own spec class in - * `.h` and React Native's `JSI.h`, which carries the - * struct helpers for named object types. - * - * Codegen rewrites every file it is handed, and CMake compiles the headers' - * dependents whenever they change, so its output is staged in a temporary - * directory and only the files whose content differs are copied over. - */ -function generateModuleCodegen({ - appRequire, - platformRequire, - packageJson, - dependencyName, - specPaths, - generatedRoot, - generatedLibraries, -}) { - const libraryName = packageJson.codegenConfig?.name; - if (typeof libraryName !== 'string' || !cppIdentifier.test(libraryName)) { - throw new Error( - `${dependencyName}: codegenConfig.name is required for a C++ TurboModule`, - ); - } - // Two packages cannot share one codegen directory: the second would overwrite - // the first's header. - if (generatedLibraries.has(libraryName)) { - throw new Error( - `${dependencyName}: codegenConfig.name ${libraryName} is already used by ${generatedLibraries.get(libraryName)}`, - ); - } - generatedLibraries.set(libraryName, dependencyName); - const schema = appRequire( - '@react-native/codegen/lib/cli/combine/combine-js-to-schema', - ).combineSchemasInFileList(specPaths, 'desktop', null, libraryName); - for (const name of Object.keys(schema.modules ?? {})) { - if (schema.modules[name].type !== 'NativeModule') { - delete schema.modules[name]; - } - } - const codegenPackage = appRequire.resolve( - '@react-native/codegen/package.json', - ); - const codegenRoot = path.dirname(codegenPackage); - const rnCodegen = appRequire( - path.join(codegenRoot, 'lib/generators/RNCodegen.js'), - ); - const outputDirectory = path.join(generatedRoot, libraryName); - const stagingDirectory = fs.mkdtempSync( - path.join(os.tmpdir(), 'rn-gpui-codegen-'), - ); - try { - const generated = rnCodegen.generate( - { - libraryName, - schema, - outputDirectory: stagingDirectory, - packageName: packageJson.name, - assumeNonnull: false, - }, - { generators: ['modulesCxx'] }, - ); - if (generated !== true) { - throw new Error( - `${dependencyName}: React Native Codegen failed for the C++ TurboModule spec`, - ); - } - for (const file of findGeneratedFiles(stagingDirectory)) { - const target = path.join( - outputDirectory, - path.relative(stagingDirectory, file), - ); - fs.mkdirSync(path.dirname(target), { recursive: true }); - writeIfChanged(target, fs.readFileSync(file, 'utf8')); - } - } finally { - fs.rmSync(stagingDirectory, { recursive: true, force: true }); - } - const specPathByModule = new Map( - specPaths.map(specPath => [ - path.basename(specPath).replace(/\.[^.]+$/u, ''), - specPath, - ]), - ); - const { generateCxxSpec } = platformRequire( - '@react-native-gpui/codegen/generate-cxx-spec', - ); - writeIfChanged( - path.join(outputDirectory, `${libraryName}.h`), - generateCxxSpec({ - libraryName, - schema, - specPaths: Object.fromEntries(specPathByModule), - }), - ); - return outputDirectory; -} - -export function autolink({ projectRoot = process.cwd(), configFile } = {}) { - projectRoot = path.resolve(projectRoot); - const desktopRoot = path.join(projectRoot, 'desktop'); - const autolinkRoot = path.join(desktopRoot, 'autolink'); - const config = JSON.parse( - configFile - ? fs.readFileSync(path.resolve(configFile), 'utf8') - : execFileSync(npxCommand, npxArgs(['react-native', 'config']), { - cwd: projectRoot, - encoding: 'utf8', - shell: npxShell, - }), - ); - const prebuilt = prebuiltModeFor(desktopProjectFor(config)); - const appRequire = createRequire(path.join(projectRoot, 'package.json')); - let platformPackageJson; - try { - platformPackageJson = appRequire.resolve( - '@react-native-gpui/core/package.json', - ); - } catch (error) { - throw new Error( - `could not resolve @react-native-gpui/core from ${projectRoot}: ${error.message}`, - ); - } - const platformRoot = fs.realpathSync(path.dirname(platformPackageJson)); - // The spec generator ships with the platform package, so resolve it from - // there rather than from the app. - const platformRequire = createRequire(platformPackageJson); - // The renderer decides which React Native tree the C++ and the codegen read. - const rendererSelection = - platformRequire('./renderer.js').resolveRenderer(projectRoot); - const { TypeScriptParser } = appRequire( - '@react-native/codegen/lib/parsers/typescript/parser', - ); - const typescriptParser = new TypeScriptParser(); - const findSpecFiles = directory => - fs - .readdirSync(directory) - .filter(entry => - /^(?:Native.*|RN.*ModuleSpec)(?:\.d)?\.ts$/u.test(entry), - ); - const moduleNameForSpec = specPath => { - const schema = typescriptParser.parseFile(specPath); - const modules = Object.values(schema.modules ?? {}); - if (modules.length !== 1 || modules[0].type !== 'NativeModule') { - throw new Error(`${specPath} must define exactly one TurboModule`); - } - return modules[0].moduleName; - }; - const runtimeCrate = path.join(platformRoot, 'ReactGpui/rn-gpui'); - if (!fs.existsSync(path.join(runtimeCrate, 'Cargo.toml'))) { - throw new Error( - `@react-native-gpui/core has no Rust crate at ${runtimeCrate}`, - ); - } - // Core owns the gpui revision; a module that copied it would drift as soon as - // the pin moved, and the copies already had. - const pin = gpuiPin(platformRoot); - const rustCrates = []; - const turboModuleSpecs = []; - const cmakeProjects = []; - const cppTurboModules = []; - const appComponentDescriptors = []; - const appComponentHeaders = []; - const appComponentSources = []; - const appComponentIncludeDirs = []; - const componentNames = new Map(); - const hostComponentNames = new Map(); - const hostComponents = []; - const hostComponentLibraries = new Set(); - const jsEngines = []; - const bundleHooks = []; - const codegenRoot = path.join(autolinkRoot, 'codegen'); - const generatedLibraries = new Map(); - for (const [dependencyName, dependency] of Object.entries( - config.dependencies ?? {}, - )) { - const root = fs.realpathSync( - path.resolve( - dependency.root ?? - path.join(projectRoot, 'node_modules', dependencyName), - ), - ); - const packageJson = JSON.parse( - fs.readFileSync(path.join(root, 'package.json'), 'utf8'), - ); - const gpui = desktopPlatformFor(dependency); - if (!gpui) continue; - if (gpui.jsEngine !== undefined) { - jsEngines.push(jsEngineConfigFor(dependencyName, root, gpui.jsEngine)); - } - if (gpui.bundleHook !== undefined) { - if (typeof gpui.bundleHook !== 'string') { - throw new Error( - `${dependencyName}: platforms.desktop.bundleHook must be a path to a module`, - ); - } - const hookPath = path.resolve(root, gpui.bundleHook); - if (!fs.existsSync(hookPath)) { - throw new Error(`${dependencyName}: no bundleHook at ${hookPath}`); - } - bundleHooks.push({ dependencyName, module: hookPath }); - } - const componentConfig = componentConfigFor(dependencyName, gpui); - const componentSourceRoot = componentConfig.sourcePackage - ? path.dirname( - appRequire.resolve(`${componentConfig.sourcePackage}/package.json`), - ) - : root; - for (const descriptor of componentConfig.descriptors) { - const previousDependency = componentNames.get(descriptor); - if (previousDependency) { - throw new Error( - `${dependencyName}: component descriptor ${descriptor} is already declared by ${previousDependency}`, - ); - } - componentNames.set(descriptor, dependencyName); - } - appComponentDescriptors.push(...componentConfig.descriptors); - appComponentHeaders.push(...componentConfig.headers); - for (const hostComponent of componentConfig.hostComponents) { - const previousDependency = hostComponentNames.get(hostComponent.name); - if (previousDependency) { - throw new Error( - `${dependencyName}: host component ${hostComponent.name} is already declared by ${previousDependency}`, - ); - } - hostComponentNames.set(hostComponent.name, dependencyName); - hostComponents.push({ - ...hostComponent, - index: hostComponents.length, - dependencyName, - }); - } - const generatedCodegen = generateComponentCodegen({ - appRequire, - packageJson, - packageRoot: root, - dependencyName, - gpui, - generatedRoot: codegenRoot, - hostComponents: hostComponents.filter( - component => - component.dependencyName === dependencyName && !component.cpp, - ), - }); - const declaresHostComponents = - Array.isArray(gpui.hostComponents) && gpui.hostComponents.length > 0; - if ( - generatedCodegen.sources.length > 0 && - componentConfig.descriptors.length === 0 && - !declaresHostComponents - ) { - throw new Error( - `${dependencyName}: component Codegen is enabled, but platforms.desktop.componentDescriptors is empty`, - ); - } - if (generatedCodegen.hostComponentLibrary) { - hostComponentLibraries.add(generatedCodegen.hostComponentLibrary); - } - appComponentSources.push( - ...generatedCodegen.sources, - ...componentConfig.sources.map(source => - path.resolve(componentSourceRoot, source), - ), - ); - if (generatedCodegen.sources.length > 0 && generatedCodegen.libraryName) { - appComponentIncludeDirs.push( - path.join(codegenRoot, generatedCodegen.libraryName), - ); - } - appComponentIncludeDirs.push( - ...componentConfig.includeDirs.map(directory => - path.resolve(componentSourceRoot, directory), - ), - ); - const specDirectory = - packageJson.codegenConfig?.jsSrcsDir ?? gpui.specs ?? 'src'; - if (gpui.cppProvider) { - if ( - typeof gpui.cppProvider !== 'string' || - !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(gpui.cppProvider) - ) { - throw new Error( - `${dependencyName}: platforms.desktop.cppProvider must be a C++ function name`, - ); - } - const specDir = path.join(root, specDirectory); - const cppSpecPaths = []; - for (const file of specFilesFor( - findSpecFiles(specDir), - gpui.cppSpecs, - 'cpp', - )) { - const specPath = path.join(specDir, file); - const moduleName = moduleNameForSpec(specPath); - cppSpecPaths.push(specPath); - cppTurboModules.push({ - dependencyName, - moduleName, - provider: gpui.cppProvider, - hasCmake: Boolean(gpui.cmake), - sources: gpui.cppSources - ? gpui.cppSources.map(source => path.resolve(root, source)) - : gpui.cmake - ? findCppSources(path.resolve(root, gpui.cmake)) - : [], - }); - turboModuleSpecs.push(specPath); - } - if (cppSpecPaths.length > 0) { - const moduleCodegenDirectory = generateModuleCodegen({ - appRequire, - platformRequire, - packageJson, - dependencyName, - specPaths: cppSpecPaths, - generatedRoot: codegenRoot, - generatedLibraries, - }); - appComponentIncludeDirs.push(moduleCodegenDirectory); - for (const entry of cppTurboModules) { - if ( - entry.dependencyName === dependencyName && - entry.specs === undefined - ) { - entry.specs = cppSpecPaths; - entry.headers = findGeneratedFiles(moduleCodegenDirectory).filter( - file => file.endsWith('.h'), - ); - } - } - } - } - if (!gpui.crate) { - if (gpui.cmake) cmakeProjects.push(path.resolve(root, gpui.cmake)); - continue; - } - const crateName = gpui.crate; - if (typeof crateName !== 'string' || !/^[A-Za-z0-9_-]+$/u.test(crateName)) { - throw new Error( - `${dependencyName}: platforms.desktop.crate must be a Cargo crate name`, - ); - } - const defaultCargoPath = fs.existsSync( - path.join(root, 'desktop/Cargo.toml'), - ) - ? 'desktop' - : '.'; - const cargoPath = path.resolve(root, gpui.path ?? defaultCargoPath); - if (!fs.existsSync(path.join(cargoPath, 'Cargo.toml'))) { - throw new Error(`${dependencyName}: no Cargo.toml at ${cargoPath}`); - } - const alias = crateName.replaceAll('-', '_'); - const moduleTypes = []; - const specDir = path.join(root, specDirectory); - if (fs.existsSync(specDir)) { - for (const file of specFilesFor( - findSpecFiles(specDir), - gpui.cppSpecs, - 'rust', - )) { - const specPath = path.join(specDir, file); - const moduleName = moduleNameForSpec(specPath); - moduleTypes.push(moduleName); - turboModuleSpecs.push(specPath); - } - } - validateModuleManifest(dependencyName, cargoPath, platformRoot); - rustCrates.push({ - dependencyName, - packageName: packageJson.name, - crateName, - alias, - cargoPath, - moduleTypes, - }); - if (gpui.cmake) cmakeProjects.push(path.resolve(root, gpui.cmake)); - } - - // Node addons are loaded from the stock `.node` files a package ships, at - // the absolute path the Babel plugin embeds (see - // @react-native-gpui/core/babel-plugin-node-addons.js). Nothing is staged here any - // more, but an app directory from an earlier run may still hold the old - // staging tree, so remove it. - fs.rmSync(path.join(autolinkRoot, 'node-api'), { - recursive: true, - force: true, - }); - - const localDesktopSource = path.join(projectRoot, 'desktop/src'); - if (fs.existsSync(localDesktopSource)) { - for (const file of findSpecFiles(localDesktopSource)) { - const specPath = path.join(localDesktopSource, file); - moduleNameForSpec(specPath); - turboModuleSpecs.push(specPath); - } - } - - const engineNames = new Map(); - for (const engine of jsEngines) { - const previousDependency = engineNames.get(engine.name); - if (previousDependency) { - throw new Error( - `${engine.dependencyName}: JS engine '${engine.name}' is already declared by ${previousDependency}`, - ); - } - engineNames.set(engine.name, engine.dependencyName); - } - if (jsEngines.length === 0) { - throw new Error( - 'no JS engine installed; add @react-native-gpui/hermes (or another engine package) to the app dependencies', - ); - } - - const generatedDir = autolinkRoot; - fs.mkdirSync(generatedDir, { recursive: true }); - const manifest = { - prebuilt, - renderer: { - name: rendererSelection.renderer, - ...(rendererSelection.jsThread === undefined - ? {} - : { jsThread: rendererSelection.jsThread }), - reactNativeDir: rendererSelection.reactNativeDir, - }, - rustCrates, - turboModuleSpecs, - cppTurboModules, - cmakeProjects, - appComponentDescriptors, - hostComponents, - appComponentHeaders: [...new Set(appComponentHeaders)], - appComponentSources: [...new Set(appComponentSources)], - appComponentIncludeDirs: [...new Set(appComponentIncludeDirs)], - jsEngines, - bundleHooks, - }; - writeIfChanged( - path.join(generatedDir, 'autolink.json'), - `${JSON.stringify(manifest, null, 2)}\n`, - ); - - const autolinkCrate = generatedDir; - fs.mkdirSync(path.join(autolinkCrate, 'src'), { recursive: true }); - const generatedDeps = rustCrates - .map(({ alias, crateName, cargoPath }) => { - const relativePath = path - .relative(autolinkCrate, cargoPath) - .split(path.sep) - .join('/'); - return `${alias} = { package = ${escapeToml(crateName)}, path = ${escapeToml(relativePath)} }`; - }) - .join('\n'); - writeIfChanged( - path.join(autolinkCrate, 'Cargo.toml'), - `[package]\nname = "rn-gpui-autolink"\nversion = "0.1.0"\nedition = "2021"\n\n[dependencies]\nreact-native-gpui = { path = ${escapeToml( - path.relative(autolinkCrate, runtimeCrate).split(path.sep).join('/'), - )} }\n${generatedDeps}`, - ); - const ensureLinked = rustCrates.map( - ({ alias }) => ` ${alias}::rn_gpui_register();`, - ); - const desktopConfig = loadDesktopConfig(path.dirname(desktopRoot)); - const desktopDefaults = JSON.stringify({ - window: desktopConfig.window, - ...(desktopConfig.accessory === undefined - ? {} - : { accessory: desktopConfig.accessory }), - }); - const generatedEnsureLinked = [ - 'pub fn ensure_linked() {', - ' react_native_gpui::set_desktop_defaults(DESKTOP_JSON);', - ' unsafe {', - ' rn_gpui_initialize_app_turbo_modules();', - ' }', - ' declare_host_components();', - ...ensureLinked, - ' ensure_host_components();', - '}', - ].join('\n'); - const hostComponentDeclarations = hostComponents - .map( - ({ - index, - name, - measured, - nativeSurface, - container, - cpp, - maskChildren, - }) => - ` react_native_gpui::host_component::declare_host_component(${index}, ${JSON.stringify(name)}, react_native_gpui::host_component::HostComponentOptions { measured: ${measured}, native_surface: ${nativeSurface}, container: ${container}, cpp: ${cpp}, mask_children: ${maskChildren} });`, - ) - .join('\n'); - const hostComponentChecks = hostComponents - .filter(({ cpp, maskChildren }) => !cpp && !maskChildren) - .map( - ({ index, name }) => - ` expect_host_component(${index}, ${JSON.stringify(name)});`, - ) - .join('\n'); - const generatedEnsureHostComponents = [ - 'fn declare_host_components() {', - hostComponentDeclarations || ' // No package declares a host component.', - '}', - '', - 'fn expect_host_component(index: u32, name: &str) {', - ' assert!(', - ' react_native_gpui::host_component::is_registered(index),', - ' "{name}: declared under platforms.desktop.hostComponents but no rn_gpui_register() registered it; call react_native_gpui::host_component::register_component from the crate that owns the component.",', - ' );', - '}', - '', - 'pub fn ensure_host_components() {', - hostComponentChecks || ' // No package declares a host component.', - '}', - ].join('\n'); - writeIfChanged( - path.join(autolinkCrate, 'src/lib.rs'), - `// Generated by @react-native-gpui/cli autolink; do not edit.\n/// The window options and flags of \`desktop/desktop.json\` for this build.\npub const DESKTOP_JSON: &str = ${rustRawString(desktopDefaults)};\nextern "C" {\n fn rn_gpui_initialize_app_turbo_modules();\n}\n${generatedEnsureLinked}\n\n${generatedEnsureHostComponents}\n`, - ); - - const appCargoManifest = path.join(desktopRoot, 'Cargo.toml'); - if (!fs.existsSync(appCargoManifest)) { - throw new Error(`missing desktop Cargo manifest: ${appCargoManifest}`); - } - let appCargo = fs.readFileSync(appCargoManifest, 'utf8'); - const runtimeCrateRelativePath = path - .relative(desktopRoot, runtimeCrate) - .split(path.sep) - .join('/'); - const runtimeCrateTomlPath = escapeToml(runtimeCrateRelativePath); - const runtimeDependencyPattern = /^(react-native-gpui\s*=\s*)\{([^\n]*)\}$/mu; - if (declaresDependency(appCargo, 'dependencies', 'react-native-gpui')) { - appCargo = appCargo.replace( - runtimeDependencyPattern, - (_line, prefix, properties) => { - const withoutOldPath = properties - .replace(/(?:^|,)\s*path\s*=\s*"[^"]*"\s*/gu, '') - .trim() - .replace(/^,\s*|\s*,\s*$/gu, ''); - return `${prefix}{ path = ${runtimeCrateTomlPath}${withoutOldPath ? `, ${withoutOldPath}` : ''} }`; - }, - ); - } else { - appCargo = appCargo.replace( - /^\[dependencies\]\s*$/mu, - section => - `${section}\nreact-native-gpui = { path = ${runtimeCrateTomlPath} }`, - ); - } - if (!/^react-native-gpui\s*=/mu.test(appCargo)) { - throw new Error(`could not add react-native-gpui to ${appCargoManifest}`); - } - if (!declaresDependency(appCargo, 'dependencies', 'rn-gpui-autolink')) { - appCargo = appCargo.replace( - /^\[dependencies\]\s*$/mu, - section => `${section}\nrn-gpui-autolink = { path = "autolink" }`, - ); - if (!/^rn-gpui-autolink\s*=/mu.test(appCargo)) { - appCargo += `\n[dependencies]\nrn-gpui-autolink = { path = "autolink" }\n`; - } - } - // The app's own Rust TurboModules: its build script generates the glue, and - // main.rs registers the modules it declares. - const moduleCrate = path - .relative( - desktopRoot, - path.join(path.dirname(runtimeCrate), 'rn-gpui-module'), - ) - .split(path.sep) - .join('/'); - const moduleBuildCrate = path - .relative( - desktopRoot, - path.join(path.dirname(runtimeCrate), 'rn-gpui-module-build'), - ) - .split(path.sep) - .join('/'); - appCargo = ensurePathDependency( - appCargo, - 'dependencies', - 'rn-gpui-module', - escapeToml(moduleCrate), - ); - appCargo = ensurePathDependency( - appCargo, - 'build-dependencies', - 'rn-gpui-module-build', - escapeToml(moduleBuildCrate), - ); - if (!/^\[features\]\s*$/mu.test(appCargo)) { - appCargo = appCargo.replace( - /^\[dependencies\]\s*$/mu, - '[features]\nruntime-shaders = ["react-native-gpui/runtime-shaders"]\nvisual-capture = ["react-native-gpui/visual-capture"]\ntest-driver = ["react-native-gpui/test-driver"]\n\n[dependencies]', - ); - } else { - const tableStart = appCargo.indexOf('[features]'); - const suffixStart = appCargo.indexOf( - '\n[', - tableStart + '[features]'.length, - ); - const tableEnd = suffixStart < 0 ? appCargo.length : suffixStart; - const featureLines = appCargo - .slice(tableStart + '[features]'.length, tableEnd) - .split('\n'); - const declares = name => - featureLines.some(line => new RegExp(`^${name}\\s*=`, 'u').test(line)); - const added = []; - if (!declares('visual-capture')) - added.push('visual-capture = ["react-native-gpui/visual-capture"]'); - if (!declares('test-driver')) - added.push('test-driver = ["react-native-gpui/test-driver"]'); - if (!declares('runtime-shaders')) - added.push('runtime-shaders = ["react-native-gpui/runtime-shaders"]'); - let lastEntry = 0; - featureLines.forEach((line, index) => { - if (/^[\w-]+\s*=/u.test(line)) lastEntry = index; - }); - featureLines.splice(lastEntry + 1, 0, ...added); - appCargo = `${appCargo.slice(0, tableStart)}[features]${featureLines.join('\n')}${appCargo.slice(tableEnd)}`; - } - // `[patch]` is only honoured in the root manifest, so the redirection lives in - // the app's rather than in each module crate. - const moduleManifests = rustCrates.map(({ cargoPath }) => - fs.readFileSync(path.join(cargoPath, 'Cargo.toml'), 'utf8'), - ); - const appLockfile = path.join(desktopRoot, 'Cargo.lock'); - appCargo = applyPatchBlock( - appCargo, - appCargoManifest, - managedPatchEntries( - platformRoot, - desktopRoot, - gpuiKitPatchNames( - moduleManifests, - fs.existsSync(appLockfile) ? fs.readFileSync(appLockfile, 'utf8') : '', - ), - ), - ); - writeIfChanged(appCargoManifest, appCargo); - const appMain = path.join(desktopRoot, 'src/main.rs'); - if (fs.existsSync(appMain)) { - let source = fs.readFileSync(appMain, 'utf8'); - if (!source.includes('rn_gpui_autolink::ensure_linked()')) { - if (!/fn main\s*\(\s*\)\s*\{/u.test(source)) { - throw new Error( - `${appMain} must define fn main() for desktop autolinking`, - ); - } - source = source.replace( - /(fn main\s*\(\s*\)\s*\{)/u, - '$1\n rn_gpui_autolink::ensure_linked();', - ); - writeIfChanged(appMain, source); - } - } - const cppProviderPath = path.join( - generatedDir, - 'CppTurboModules.generated.cpp', - ); - const cppProviderCases = cppTurboModules - .map( - ({ moduleName, provider }) => - ` if (name == ${JSON.stringify(moduleName)}) return ::${provider}(name, jsInvoker);`, - ) - .join('\n'); - const hostComponentRegistrationDeclarations = [...hostComponentLibraries] - .map( - library => - `extern "C" void rn_gpui_register_host_components_${library}();`, - ) - .join('\n'); - const hostComponentRegistrationCalls = [...hostComponentLibraries] - .map(library => ` rn_gpui_register_host_components_${library}();`) - .join('\n'); - const cppHostComponentDeclarations = hostComponents - .filter(({ cpp }) => cpp) - .map( - ({ index, name, nativeSurface }) => - ` rngpui::extension::declareCppHostComponent(${index}, ${JSON.stringify(name)}, ${nativeSurface});`, - ) - .join('\n'); - const componentHeaders = [...new Set(appComponentHeaders)] - .map(header => `#include <${header}>`) - .join('\n'); - const componentRegistration = appComponentDescriptors - .map( - descriptor => - ` addComponent(facebook::react::concreteComponentDescriptorProvider());`, - ) - .join('\n'); - writeIfChanged( - cppProviderPath, - `// Generated by @react-native-gpui/cli autolink; do not edit.\n#include \n#include \n#include "GpuiCppHostComponent.h"\n#include \n#include \n#include \n#include \n${componentHeaders}\n${hostComponentRegistrationDeclarations}\n${[...new Set(cppTurboModules.map(({ provider }) => `extern std::shared_ptr ${provider}(const std::string&, std::shared_ptr);`))].join('\n')}\nextern "C" void rn_gpui_set_app_cpp_turbo_module_provider(std::shared_ptr (*)(const std::string&, std::shared_ptr));\nextern "C" void rn_gpui_run_app_cpp_init_functions();\nextern "C" void rn_gpui_initialize_app_turbo_modules() {\n${hostComponentRegistrationCalls}\n${cppHostComponentDeclarations}\n rn_gpui_run_app_cpp_init_functions();\n rn_gpui_set_app_cpp_turbo_module_provider(+[](const std::string& name, std::shared_ptr jsInvoker) -> std::shared_ptr {\n${cppProviderCases}\n return nullptr;\n });\n}\nnamespace rngpui {\nvoid rn_gpui_register_app_components(facebook::react::ComponentDescriptorProviderRegistry& registry) {\n static const std::unordered_set builtins = {"View", "Paragraph", "Text", "RawText", "Image", "ScrollView", "TextInput", "ModalHostView"};\n std::unordered_set registered;\n auto addComponent = [®istry, ®istered](const facebook::react::ComponentDescriptorProvider& provider) {\n const std::string name(provider.name);\n if (builtins.contains(name) || !registered.insert(name).second) {\n std::cerr << "[rn-gpui] duplicate app Fabric component descriptor ignored: " << name << std::endl;\n return;\n }\n registry.add(provider);\n };\n${componentRegistration}\n}\n} // namespace rngpui\n`, - ); - const cppSources = [ - ...new Set([ - ...cppTurboModules - .filter(({ hasCmake }) => !hasCmake) - .flatMap(({ sources }) => sources), - ...appComponentSources, - ]), - ]; - const cmakePath = value => value.replaceAll('\\', '/').replaceAll('"', '\\"'); - const cmake = [ - ...cmakeProjects.map( - (directory, index) => - `add_subdirectory("${cmakePath(directory)}" "${cmakePath(path.join('${CMAKE_BINARY_DIR}', `rn_gpui_autolink_${index}`))}")`, - ), - `set(RN_GPUI_APP_CPP_PROVIDER_SOURCE "${cmakePath(cppProviderPath)}")`, - `set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_SOURCES ${cppSources.map(source => `"${cmakePath(source)}"`).join(' ')})`, - `set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_INCLUDE_DIRS ${appComponentIncludeDirs.map(directory => `"${cmakePath(directory)}"`).join(' ')})`, - // Core calls each registration symbol from the generated - // rn_gpui_install_modules(), so the engine registry is populated before - // the host selects an engine. - ...jsEngines.map( - engine => - `set_property(GLOBAL APPEND PROPERTY RN_GPUI_JS_ENGINE_REGISTRATIONS "${engine.register}")`, - ), - ].join('\n'); - writeIfChanged( - path.join(generatedDir, 'autolink.cmake'), - `# Generated by @react-native-gpui/cli autolink.\n${cmake}\n`, - ); - console.log( - `Autolinked ${rustCrates.length} Rust crate(s), ${cppTurboModules.length} C++ TurboModule(s), ${cmakeProjects.length} CMake project(s), and ${jsEngines.length} JS engine(s) [${jsEngines.map(({ name }) => name).join(', ')}].`, - ); - return config; -} diff --git a/vendor/react-native-gpui/packages/cli/src/autolink.test.js b/vendor/react-native-gpui/packages/cli/src/autolink.test.js deleted file mode 100644 index 544886e699..0000000000 --- a/vendor/react-native-gpui/packages/cli/src/autolink.test.js +++ /dev/null @@ -1,892 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { afterAll, expect, test } from 'vitest'; -import { - applyPatchBlock, - autolink, - gpuiKitPatchNames, - manifestDependencyNames, - specFilesFor, -} from './autolink.js'; - -// The repository root by lookup, not by counting parents: this file sits at a -// different depth before and after a folder move. -const repoRoot = (() => { - let dir = path.dirname(fileURLToPath(import.meta.url)); - for (;;) { - const manifest = path.join(dir, 'package.json'); - if (fs.existsSync(manifest)) { - try { - if (JSON.parse(fs.readFileSync(manifest, 'utf8')).workspaces) - return dir; - } catch {} - } - const parent = path.dirname(dir); - if (parent === dir) throw new Error('no workspace root above the test'); - dir = parent; - } -})(); -const temporaryRoots = []; - -const spec = `import { TurboModuleRegistry, type TurboModule } from 'react-native'; - -export interface Spec extends TurboModule { - greet(name: string): string; - loadLater(name: string): Promise; -} - -export default TurboModuleRegistry.getEnforcing('Fake'); -`; - -/** - * A project small enough for autolink to run end to end: a manifest to resolve - * from, a desktop Cargo manifest, one JS engine, and one C++ TurboModule - * package. It lives under the repo so Node resolves the workspace packages. - */ -function createProject({ - withCodegenConfig = true, - duplicateLibrary = false, - project, -} = {}) { - const projectRoot = fs.mkdtempSync(path.join(repoRoot, '.local/autolink-')); - temporaryRoots.push(projectRoot); - const write = (relative, contents) => { - const target = path.join(projectRoot, relative); - fs.mkdirSync(path.dirname(target), { recursive: true }); - fs.writeFileSync(target, contents); - }; - write( - 'package.json', - `${JSON.stringify({ name: 'autolink-test-app', version: '0.0.1' }, null, 2)}\n`, - ); - write( - 'desktop/Cargo.toml', - '[package]\nname = "autolink-test-app"\nversion = "0.0.1"\nedition = "2021"\n\n[dependencies]\n', - ); - write( - 'node_modules/fake-engine/package.json', - `${JSON.stringify({ name: 'fake-engine', version: '0.0.1' }, null, 2)}\n`, - ); - const moduleManifest = { - name: 'fake-module', - version: '0.0.1', - ...(withCodegenConfig - ? { - codegenConfig: { - name: 'FakeSpec', - type: 'modules', - jsSrcsDir: 'src', - }, - } - : {}), - }; - write( - 'node_modules/fake-module/package.json', - `${JSON.stringify(moduleManifest, null, 2)}\n`, - ); - write('node_modules/fake-module/src/NativeFake.ts', spec); - write( - 'node_modules/fake-module/desktop/CMakeLists.txt', - 'set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_SOURCES "${CMAKE_CURRENT_LIST_DIR}/cpp/FakeModule.cpp")\n', - ); - write('node_modules/fake-module/cpp/FakeModule.cpp', '// fake module\n'); - write( - 'node_modules/fake-module/react-native.config.js', - "module.exports = {dependency: {platforms: {desktop: {cmake: 'desktop', cppProvider: 'create_fake_module'}}}};\n", - ); - if (duplicateLibrary) { - write( - 'node_modules/fake-module-two/package.json', - `${JSON.stringify( - { - name: 'fake-module-two', - version: '0.0.1', - codegenConfig: { - name: 'FakeSpec', - type: 'modules', - jsSrcsDir: 'src', - }, - }, - null, - 2, - )}\n`, - ); - write('node_modules/fake-module-two/src/NativeFakeTwo.ts', spec); - write( - 'node_modules/fake-module-two/react-native.config.js', - "module.exports = {dependency: {platforms: {desktop: {cppProvider: 'create_fake_two_module'}}}};\n", - ); - } - const configPath = path.join(projectRoot, 'rn-config.json'); - fs.writeFileSync( - configPath, - `${JSON.stringify( - { - ...(project ? { project: { desktop: project } } : {}), - dependencies: { - 'fake-engine': { - root: path.join(projectRoot, 'node_modules/fake-engine'), - platforms: { - desktop: { - jsEngine: { - name: 'hermes', - register: 'rn_gpui_register_js_engine_hermes', - }, - }, - }, - }, - 'fake-module': { - root: path.join(projectRoot, 'node_modules/fake-module'), - platforms: { - desktop: { cmake: 'desktop', cppProvider: 'create_fake_module' }, - }, - }, - ...(duplicateLibrary - ? { - 'fake-module-two': { - root: path.join(projectRoot, 'node_modules/fake-module-two'), - platforms: { - desktop: { cppProvider: 'create_fake_two_module' }, - }, - }, - } - : {}), - }, - }, - null, - 2, - )}\n`, - ); - return { projectRoot, configPath }; -} - -afterAll(() => { - for (const root of temporaryRoots) { - fs.rmSync(root, { recursive: true, force: true }); - } -}); - -test('generates both spec headers for a C++ TurboModule package', () => { - const { projectRoot, configPath } = createProject(); - autolink({ projectRoot, configFile: configPath }); - const codegenDirectory = path.join( - projectRoot, - 'desktop/autolink/codegen/FakeSpec', - ); - const ours = fs.readFileSync( - path.join(codegenDirectory, 'FakeSpec.h'), - 'utf8', - ); - const reactNative = fs.readFileSync( - path.join(codegenDirectory, 'FakeSpecJSI.h'), - 'utf8', - ); - expect(ours).toContain('#include '); - expect(ours).toContain( - 'class NativeFakeSpec : public rngpui::TurboModuleBase', - ); - expect(ours).toContain('kModuleName = "Fake"'); - expect(ours).toContain('this->template valueMethod<&T::greet>("greet");'); - expect(ours).toContain( - 'this->template promiseMethod<&T::loadLater>("loadLater");', - ); - expect(reactNative).toContain('NativeFakeCxxSpec'); - expect(reactNative).toContain('"Fake"'); - const cmake = fs.readFileSync( - path.join(projectRoot, 'desktop/autolink/autolink.cmake'), - 'utf8', - ); - const includeDirs = cmake - .split('\n') - .find(line => line.includes('RN_GPUI_APP_CPP_INCLUDE_DIRS')); - // The generated CMake normalises every path to `/`, which is what CMake - // accepts on every platform (a Windows `\` is an escape in a CMake string). - expect(includeDirs).toContain(codegenDirectory.replaceAll('\\', '/')); -}); - -const manifestOf = projectRoot => - JSON.parse( - fs.readFileSync( - path.join(projectRoot, 'desktop/autolink/autolink.json'), - 'utf8', - ), - ); - -test('writes the prebuilt mode into the manifest, defaulting to auto', () => { - const defaults = createProject(); - autolink({ - projectRoot: defaults.projectRoot, - configFile: defaults.configPath, - }); - expect(manifestOf(defaults.projectRoot).prebuilt).toBe('auto'); - - const always = createProject({ project: { prebuilt: 'always' } }); - autolink({ projectRoot: always.projectRoot, configFile: always.configPath }); - expect(manifestOf(always.projectRoot).prebuilt).toBe('always'); -}); - -test('throws on an unknown prebuilt mode', () => { - const { projectRoot, configPath } = createProject({ - project: { prebuilt: true }, - }); - expect(() => autolink({ projectRoot, configFile: configPath })).toThrow( - "project.desktop.prebuilt must be one of 'auto', 'always', 'never'", - ); -}); - -test('reads project.desktop without complaint', () => { - const { projectRoot, configPath } = createProject({ - project: { prebuilt: 'never' }, - }); - autolink({ projectRoot, configFile: configPath }); - expect(manifestOf(projectRoot).prebuilt).toBe('never'); -}); - -test('throws when a C++ TurboModule package has no codegenConfig.name', () => { - const { projectRoot, configPath } = createProject({ - withCodegenConfig: false, - }); - expect(() => autolink({ projectRoot, configFile: configPath })).toThrow( - 'fake-module: codegenConfig.name is required for a C++ TurboModule', - ); -}); - -test('throws when two packages share one codegenConfig.name', () => { - const { projectRoot, configPath } = createProject({ duplicateLibrary: true }); - expect(() => autolink({ projectRoot, configFile: configPath })).toThrow( - 'fake-module-two: codegenConfig.name FakeSpec is already used by fake-module', - ); -}); - -test('leaves both headers untouched when nothing changed', () => { - const { projectRoot, configPath } = createProject(); - autolink({ projectRoot, configFile: configPath }); - const codegenDirectory = path.join( - projectRoot, - 'desktop/autolink/codegen/FakeSpec', - ); - const headers = ['FakeSpec.h', 'FakeSpecJSI.h'].map(name => - path.join(codegenDirectory, name), - ); - const before = headers.map(header => fs.statSync(header).mtimeMs); - autolink({ projectRoot, configFile: configPath }); - const after = headers.map(header => fs.statSync(header).mtimeMs); - expect(after).toEqual(before); -}); - -test('registers a crate that has no TurboModule specs', () => { - const { projectRoot, configPath } = createProject(); - const crateRoot = path.join(projectRoot, 'node_modules/fake-paint'); - fs.mkdirSync(path.join(crateRoot, 'desktop/src'), { recursive: true }); - fs.writeFileSync( - path.join(crateRoot, 'package.json'), - `${JSON.stringify({ name: 'fake-paint', version: '0.0.1' }, null, 2)}\n`, - ); - fs.writeFileSync( - path.join(crateRoot, 'desktop/Cargo.toml'), - '[package]\nname = "fake-paint"\nversion = "0.0.1"\nedition = "2021"\n\n[dependencies]\n', - ); - fs.writeFileSync( - path.join(crateRoot, 'react-native.config.js'), - "module.exports = {dependency: {platforms: {desktop: {crate: 'fake-paint'}}}};\n", - ); - const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); - config.dependencies['fake-paint'] = { - root: crateRoot, - platforms: { desktop: { crate: 'fake-paint' } }, - }; - fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`); - - autolink({ projectRoot, configFile: configPath }); - const generated = fs.readFileSync( - path.join(projectRoot, 'desktop/autolink/src/lib.rs'), - 'utf8', - ); - expect(generated).toContain('fake_paint::rn_gpui_register();'); -}); - -test('hands desktop.json to the app so its window options need no main.rs change', () => { - const { projectRoot, configPath } = createProject(); - fs.writeFileSync( - path.join(projectRoot, 'desktop/desktop.json'), - JSON.stringify({ - window: { titleBar: 'hidden', trafficLightPosition: { x: 10, y: 14 } }, - }), - ); - autolink({ projectRoot, configFile: configPath }); - const generated = fs.readFileSync( - path.join(projectRoot, 'desktop/autolink/src/lib.rs'), - 'utf8', - ); - expect(generated).toContain( - 'react_native_gpui::set_desktop_defaults(DESKTOP_JSON);', - ); - expect(generated).toContain('"titleBar":"hidden"'); - expect(generated).toContain('"trafficLightPosition":{"x":10,"y":14}'); -}); - -/** - * A project with one Rust module crate, so the manifest checks have something to - * read. The crate's manifest is the argument: the tests below vary only that. - */ -function projectWithRustCrate(manifest) { - // No codegen config: `fake-module` declares a `cppProvider`, and a C++ - // TurboModule without a `codegenConfig.name` is refused before the manifest - // checks this fixture is about would run. - const { projectRoot, configPath } = createProject({ - withCodegenConfig: false, - }); - const config0 = JSON.parse(fs.readFileSync(configPath, 'utf8')); - delete config0.dependencies['fake-module']; - fs.writeFileSync(configPath, `${JSON.stringify(config0, null, 2)}\n`); - const crateRoot = path.join(projectRoot, 'node_modules/fake-rust'); - fs.mkdirSync(path.join(crateRoot, 'desktop'), { recursive: true }); - fs.writeFileSync( - path.join(crateRoot, 'package.json'), - `${JSON.stringify({ name: 'fake-rust', version: '0.0.1' }, null, 2)}\n`, - ); - fs.writeFileSync(path.join(crateRoot, 'desktop/Cargo.toml'), manifest); - fs.writeFileSync( - path.join(crateRoot, 'react-native.config.js'), - "module.exports = {dependency: {platforms: {desktop: {crate: 'fake-rust'}}}};\n", - ); - const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); - config.dependencies['fake-rust'] = { - root: crateRoot, - platforms: { desktop: { crate: 'fake-rust' } }, - }; - fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`); - return { projectRoot, configPath, crateRoot }; -} - -const CARGO_HEADER = - '[package]\nname = "fake-rust"\nversion = "0.0.1"\nedition = "2021"\n\n[dependencies]\n'; - -test('the app manifest gets a managed patch block pointing at core', () => { - const { projectRoot, configPath } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = "0.1"\n`, - ); - autolink({ projectRoot, configFile: configPath }); - const appCargo = fs.readFileSync( - path.join(projectRoot, 'desktop/Cargo.toml'), - 'utf8', - ); - expect(appCargo).toContain('[patch.crates-io]'); - expect(appCargo).toContain( - '# Managed by @react-native-gpui/cli autolink; do not edit between these markers.', - ); - expect(appCargo).toMatch( - /^rn-gpui-module = \{ path = "[^"]+rn-gpui-module" \}$/mu, - ); - expect(appCargo).toMatch( - /^react-native-gpui = \{ path = "[^"]+rn-gpui" \}$/mu, - ); - // The rev must be core's, read from core's own manifest, not a copy. - const coreManifest = fs.readFileSync( - path.join(repoRoot, 'packages/core/ReactGpui/Cargo.toml'), - 'utf8', - ); - const rev = /^gpui = \{[^}]*rev = "([^"]+)"/mu.exec(coreManifest)?.[1]; - expect(rev).toBeDefined(); - expect(appCargo).toContain( - `gpui = { git = "https://github.com/streetwriters/gpui-fast", rev = "${rev}" }`, - ); -}); - -test('the app manifest gets the module crates in their own sections', () => { - const { projectRoot, configPath } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = "0.1"\n`, - ); - const appManifest = path.join(projectRoot, 'desktop/Cargo.toml'); - fs.writeFileSync( - appManifest, - '[package]\nname = "app"\nversion = "0.0.1"\nedition = "2021"\n\n[build-dependencies]\nserde_json = "1"\n\n[dependencies]\n', - ); - autolink({ projectRoot, configFile: configPath }); - autolink({ projectRoot, configFile: configPath }); - const appCargo = fs.readFileSync(appManifest, 'utf8'); - const dependencies = appCargo.slice( - appCargo.indexOf('[dependencies]'), - appCargo.indexOf('[patch.crates-io]'), - ); - const buildDependencies = appCargo.slice( - appCargo.indexOf('[build-dependencies]'), - appCargo.indexOf('[features]'), - ); - expect(dependencies).toMatch(/^rn-gpui-module = \{ path = "[^"]+" \}$/mu); - expect(buildDependencies).toMatch( - /^rn-gpui-module-build = \{ path = "[^"]+" \}$/mu, - ); - expect(appCargo.match(/^rn-gpui-module = /gmu)).toHaveLength(2); -}); - -test('a path to a crate of core through a symlink becomes the real path', () => { - const { projectRoot, configPath } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = "0.1"\n`, - ); - const appManifest = path.join(projectRoot, 'desktop/Cargo.toml'); - fs.writeFileSync( - appManifest, - '[package]\nname = "app"\nversion = "0.0.1"\nedition = "2021"\n\n[build-dependencies]\nrn-gpui-module-build = { path = "../node_modules/core/rn-gpui-module-build" }\n\n[dependencies]\nrn-gpui-module = { path = "../node_modules/core/rn-gpui-module" }\n', - ); - autolink({ projectRoot, configFile: configPath }); - const appCargo = fs.readFileSync(appManifest, 'utf8'); - expect(appCargo).not.toContain('node_modules/core'); - expect(appCargo).toMatch( - /^rn-gpui-module = \{ path = "[^"]+ReactGpui\/rn-gpui-module" \}$/gmu, - ); -}); - -test('a second autolink leaves the app manifest byte-identical', () => { - const { projectRoot, configPath } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = "0.1"\n`, - ); - autolink({ projectRoot, configFile: configPath }); - const manifest = path.join(projectRoot, 'desktop/Cargo.toml'); - const once = fs.readFileSync(manifest, 'utf8'); - autolink({ projectRoot, configFile: configPath }); - expect(fs.readFileSync(manifest, 'utf8')).toBe(once); -}); - -test('an unrelated user patch table is kept, with one header', () => { - const { projectRoot, configPath } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = "0.1"\n`, - ); - const manifest = path.join(projectRoot, 'desktop/Cargo.toml'); - const original = fs.readFileSync(manifest, 'utf8'); - fs.writeFileSync( - manifest, - `${original}\n[patch.crates-io]\nserde = { path = "vendor/serde" }\n`, - ); - autolink({ projectRoot, configFile: configPath }); - const patched = fs.readFileSync(manifest, 'utf8'); - expect(patched).toContain('serde = { path = "vendor/serde" }'); - expect(patched.match(/^\[patch\.crates-io\]$/gmu)).toHaveLength(1); - expect(patched).toContain('rn-gpui-module = { path ='); -}); - -test('a user patch table that claims a managed key is refused', () => { - const { projectRoot, configPath } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = "0.1"\n`, - ); - const manifest = path.join(projectRoot, 'desktop/Cargo.toml'); - const original = fs.readFileSync(manifest, 'utf8'); - fs.writeFileSync( - manifest, - `${original}\n[patch.crates-io]\ngpui = { path = "my-gpui" }\n`, - ); - expect(() => autolink({ projectRoot, configFile: configPath })).toThrow( - /already sets gpui/u, - ); -}); - -test('a module crate may not name core by path', () => { - const { projectRoot, configPath } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = { path = "../../core/ReactGpui/rn-gpui-module" }\n`, - ); - expect(() => autolink({ projectRoot, configFile: configPath })).toThrow( - /must be a version requirement/u, - ); -}); - -test('a module crate may not pin gpui by git', () => { - const { projectRoot, configPath } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = "0.1"\ngpui = { git = "https://github.com/streetwriters/gpui-fast", rev = "c380367" }\n`, - ); - expect(() => autolink({ projectRoot, configFile: configPath })).toThrow( - /must be a version requirement/u, - ); -}); - -test('a gpui requirement the patch does not satisfy is refused', () => { - // 0.3 would resolve to the crates.io crate instead, and the only sign would be - // one warning Cargo prints and nobody reads. - const { projectRoot, configPath } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = "0.1"\ngpui = "0.3"\n`, - ); - expect(() => autolink({ projectRoot, configFile: configPath })).toThrow( - /does not match the 0\.2\.2/u, - ); -}); - -test('a managed crate in table form is checked too', () => { - // `[dependencies.gpui]` with its keys on the following lines is legal TOML, so - // it must not be a way past the path check. - const { projectRoot, configPath } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = "0.1"\n\n[dependencies.gpui]\ngit = "https://github.com/streetwriters/gpui-fast"\nrev = "c380367"\n`, - ); - expect(() => autolink({ projectRoot, configFile: configPath })).toThrow( - /must be a version requirement/u, - ); -}); - -test('a CRLF lockfile still yields the managed block', () => { - // A Windows checkout with core.autocrlf gives these files CRLF endings. The - // lockfile pattern anchors on `\n`, so without normalising the read it finds no - // gpui entry and autolink throws on every Windows run. The manifest pattern - // survives CRLF on its own, because `\s*$` treats `\r` as whitespace. - const { projectRoot, configPath } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = "0.1"\n`, - ); - const coreLock = path.join(repoRoot, 'packages/core/ReactGpui/Cargo.lock'); - const original = fs.readFileSync(coreLock, 'utf8'); - fs.writeFileSync(coreLock, original.replace(/\n/gu, '\r\n')); - try { - autolink({ projectRoot, configFile: configPath }); - const rev = /^gpui = \{[^}]*rev = "([^"]+)"/mu.exec( - fs.readFileSync( - path.join(repoRoot, 'packages/core/ReactGpui/Cargo.toml'), - 'utf8', - ), - )?.[1]; - expect( - fs.readFileSync(path.join(projectRoot, 'desktop/Cargo.toml'), 'utf8'), - ).toContain(`rev = "${rev}"`); - } finally { - fs.writeFileSync(coreLock, original); - } -}); - -/** - * Adds a package that declares host components: a codegen spec for each, a Rust - * crate, and `hostComponents` entries in the platform config. - */ -function addHostComponentPackage( - { projectRoot, configPath }, - { - name = 'fake-host', - library = 'FakeHostSpec', - components, - interfaceOnly = true, - }, -) { - const root = path.join(projectRoot, 'node_modules', name); - const write = (relative, contents) => { - const target = path.join(root, relative); - fs.mkdirSync(path.dirname(target), { recursive: true }); - fs.writeFileSync(target, contents); - }; - write( - 'package.json', - `${JSON.stringify( - { - name, - version: '0.0.1', - codegenConfig: { name: library, type: 'components', jsSrcsDir: 'src' }, - }, - null, - 2, - )}\n`, - ); - write( - 'desktop/Cargo.toml', - `[package]\nname = "${name}"\nversion = "0.0.1"\nedition = "2021"\n\n[dependencies]\n`, - ); - for (const component of components) { - write( - `src/${component.name}NativeComponent.ts`, - `import { codegenNativeComponent, type ViewProps } from 'react-native'; - -export interface NativeProps extends ViewProps { - title?: string; - count?: Int32; -} - -export default codegenNativeComponent('${component.name}'${ - interfaceOnly ? ', { interfaceOnly: true }' : '' - }); -`, - ); - } - const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); - config.dependencies[name] = { - root, - platforms: { - desktop: { - crate: name, - hostComponents: components, - }, - }, - }; - fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`); - return root; -} - -const generatedLib = projectRoot => - fs.readFileSync( - path.join(projectRoot, 'desktop/autolink/src/lib.rs'), - 'utf8', - ); - -const generatedProvider = projectRoot => - fs.readFileSync( - path.join(projectRoot, 'desktop/autolink/CppTurboModules.generated.cpp'), - 'utf8', - ); - -test('declares each host component with its index and layout flags', () => { - const project = createProject(); - addHostComponentPackage(project, { - components: [ - { name: 'FakeChart' }, - { name: 'FakeLabel', measured: true }, - { name: 'FakeCard', container: true, nativeSurface: true }, - ], - }); - autolink({ - projectRoot: project.projectRoot, - configFile: project.configPath, - }); - const lib = generatedLib(project.projectRoot); - expect(lib).toContain( - 'declare_host_component(0, "FakeChart", react_native_gpui::host_component::HostComponentOptions { measured: false, native_surface: false, container: false, cpp: false, mask_children: false });', - ); - expect(lib).toContain( - 'declare_host_component(1, "FakeLabel", react_native_gpui::host_component::HostComponentOptions { measured: true, native_surface: false, container: false, cpp: false, mask_children: false });', - ); - expect(lib).toContain( - 'declare_host_component(2, "FakeCard", react_native_gpui::host_component::HostComponentOptions { measured: false, native_surface: true, container: true, cpp: false, mask_children: false });', - ); - // Declared before any package registers, then checked for code afterwards. - expect(lib.indexOf('declare_host_components();')).toBeLessThan( - lib.indexOf('fake_host::rn_gpui_register();'), - ); - expect(lib.indexOf('fake_host::rn_gpui_register();')).toBeLessThan( - lib.indexOf('ensure_host_components();'), - ); - expect(lib).toContain('expect_host_component(2, "FakeCard");'); -}); - -test('generates the C++ that registers a host component library and calls it at startup', () => { - const project = createProject(); - addHostComponentPackage(project, { - components: [{ name: 'FakeChart' }, { name: 'FakeCard', container: true }], - }); - autolink({ - projectRoot: project.projectRoot, - configFile: project.configPath, - }); - const generated = path.join( - project.projectRoot, - 'desktop/autolink/codegen/FakeHostSpec/react/renderer/components/FakeHostSpec/GpuiHostComponents.generated.cpp', - ); - const cpp = fs.readFileSync(generated, 'utf8'); - expect(cpp).toContain('entry.index = 0;'); - expect(cpp).toContain('entry.index = 1;'); - expect(cpp).toContain('entry.container = true;'); - expect(cpp).toContain( - 'extern "C" void rn_gpui_register_host_components_FakeHostSpec() {', - ); - // The app calls it explicitly: a static library member nothing references is - // dropped by the linker, and its static initialiser with it. - const provider = generatedProvider(project.projectRoot); - expect(provider).toContain( - 'extern "C" void rn_gpui_register_host_components_FakeHostSpec();', - ); - expect(provider).toContain( - ' rn_gpui_register_host_components_FakeHostSpec();', - ); - // The generated file is compiled with React Native's own output for the spec. - const cmake = fs.readFileSync( - path.join(project.projectRoot, 'desktop/autolink/autolink.cmake'), - 'utf8', - ); - expect(cmake).toContain('GpuiHostComponents.generated.cpp'); - expect(cmake).toContain('Props.cpp'); -}); - -test('numbers host components across packages in one global order', () => { - const project = createProject(); - addHostComponentPackage(project, { - name: 'fake-host', - library: 'FakeHostSpec', - components: [{ name: 'FakeChart' }], - }); - addHostComponentPackage(project, { - name: 'fake-host-two', - library: 'FakeHostTwoSpec', - components: [{ name: 'FakeOther' }], - }); - autolink({ - projectRoot: project.projectRoot, - configFile: project.configPath, - }); - const lib = generatedLib(project.projectRoot); - expect(lib).toContain('declare_host_component(0, "FakeChart"'); - expect(lib).toContain('declare_host_component(1, "FakeOther"'); -}); - -test('refuses a host component that is both measured and a container', () => { - const project = createProject(); - addHostComponentPackage(project, { - components: [{ name: 'FakeBoth', measured: true, container: true }], - }); - expect(() => - autolink({ - projectRoot: project.projectRoot, - configFile: project.configPath, - }), - ).toThrow(/cannot be both "measured" and a "container"/u); -}); - -test('refuses a host component whose spec is not interfaceOnly', () => { - const project = createProject(); - addHostComponentPackage(project, { - interfaceOnly: false, - components: [{ name: 'FakeChart' }], - }); - expect(() => - autolink({ - projectRoot: project.projectRoot, - configFile: project.configPath, - }), - ).toThrow( - /must be created with codegenNativeComponent\(\.\.\., \{ interfaceOnly: true \}\)/u, - ); -}); - -test('refuses a duplicate host component name across packages', () => { - const project = createProject(); - addHostComponentPackage(project, { - name: 'fake-host', - library: 'FakeHostSpec', - components: [{ name: 'FakeChart' }], - }); - addHostComponentPackage(project, { - name: 'fake-host-two', - library: 'FakeHostTwoSpec', - components: [{ name: 'FakeChart' }], - }); - expect(() => - autolink({ - projectRoot: project.projectRoot, - configFile: project.configPath, - }), - ).toThrow(/host component FakeChart is already declared by fake-host/u); -}); - -test('splits the specifications of a package between its C++ provider and its crate', () => { - const files = ['NativeCrypto.ts', 'NativeSubtle.ts']; - expect(specFilesFor(files, undefined, 'cpp')).toEqual(files); - expect(specFilesFor(files, undefined, 'rust')).toEqual(files); - expect(specFilesFor(files, ['NativeCrypto.ts'], 'cpp')).toEqual([ - 'NativeCrypto.ts', - ]); - expect(specFilesFor(files, ['NativeCrypto.ts'], 'rust')).toEqual([ - 'NativeSubtle.ts', - ]); - expect(() => specFilesFor(files, ['NativeMissing.ts'], 'cpp')).toThrow( - /NativeMissing.ts/u, - ); - expect(() => specFilesFor(files, 'NativeCrypto.ts', 'cpp')).toThrow(/array/u); -}); - -const coreRev = () => { - const coreManifest = fs.readFileSync( - path.join(repoRoot, 'packages/core/ReactGpui/Cargo.toml'), - 'utf8', - ); - return /^gpui = \{[^}]*rev = "([^"]+)"/mu.exec(coreManifest)?.[1]; -}; - -const KIT_NAMES = ['gpui-pre', 'gpui-pre-macros', 'gpui-pre-sum-tree']; - -test('a module crate that depends on GPUI Kit gets the gpui-pre crates patched to the pin of core', () => { - const { projectRoot, configPath } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = "0.1"\ngpui-component = "=0.9.1"\n`, - ); - autolink({ projectRoot, configFile: configPath }); - const appCargo = fs.readFileSync( - path.join(projectRoot, 'desktop/Cargo.toml'), - 'utf8', - ); - const block = appCargo.slice( - appCargo.indexOf('# Managed by'), - appCargo.indexOf('# End managed'), - ); - for (const name of KIT_NAMES) { - expect(block).toContain( - `${name} = { git = "https://github.com/streetwriters/gpui-fast", rev = "${coreRev()}" }`, - ); - } - expect(block).not.toContain('gpui-pre-platform'); - expect(block).not.toContain('gpui-pre-web'); - expect(block).not.toContain('gpui-pre-reqwest-client'); -}); - -test('an app without a GPUI Kit module gets no gpui-pre patches', () => { - const { projectRoot, configPath } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = "0.1"\n`, - ); - autolink({ projectRoot, configFile: configPath }); - const appCargo = fs.readFileSync( - path.join(projectRoot, 'desktop/Cargo.toml'), - 'utf8', - ); - expect(appCargo).not.toContain('gpui-pre'); -}); - -test('the gpui-pre patches follow the modules: they go when the kit does', () => { - const { projectRoot, configPath, crateRoot } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = "0.1"\ngpui-base = "=0.9.1"\n`, - ); - autolink({ projectRoot, configFile: configPath }); - const manifest = path.join(projectRoot, 'desktop/Cargo.toml'); - expect(fs.readFileSync(manifest, 'utf8')).toContain('gpui-pre-macros'); - fs.writeFileSync( - path.join(crateRoot, 'desktop/Cargo.toml'), - `${CARGO_HEADER}rn-gpui-module = "0.1"\n`, - ); - autolink({ projectRoot, configFile: configPath }); - expect(fs.readFileSync(manifest, 'utf8')).not.toContain('gpui-pre'); -}); - -test('a hand-written gpui-pre line beside the managed block is refused with the fix', () => { - const { projectRoot, configPath } = projectWithRustCrate( - `${CARGO_HEADER}rn-gpui-module = "0.1"\ngpui-component = "=0.9.1"\n`, - ); - autolink({ projectRoot, configFile: configPath }); - const manifest = path.join(projectRoot, 'desktop/Cargo.toml'); - fs.writeFileSync( - manifest, - `${fs.readFileSync(manifest, 'utf8')}gpui-pre = { git = "https://github.com/streetwriters/gpui-fast", rev = "abc" }\n`, - ); - expect(() => autolink({ projectRoot, configFile: configPath })).toThrow( - /already sets gpui-pre, which autolink owns; remove that line/u, - ); -}); - -test('the optional gpui-pre crates are patched when a module names them or the lockfile has them', () => { - expect( - gpuiKitPatchNames([ - '[dependencies]\ngpui-component = "=0.9.1"\ngpui-pre-web = "0.3"\n', - ]), - ).toEqual([...KIT_NAMES, 'gpui-pre-web']); - expect( - gpuiKitPatchNames( - ['[dependencies]\ngpui-component = "=0.9.1"\n'], - '[[package]]\nname = "gpui-pre-platform"\nversion = "0.3.12"\n', - ), - ).toEqual([...KIT_NAMES, 'gpui-pre-platform']); - expect(gpuiKitPatchNames(['[dependencies]\nserde = "1"\n'])).toEqual([]); -}); - -test('GPUI Kit is found by dependency name in any section and under a rename', () => { - expect( - manifestDependencyNames( - '[dependencies]\na = "1"\nkit = { package = "gpui-component", version = "1" }\n[target.\'cfg(unix)\'.dependencies]\nb = "1"\n[build-dependencies]\nc = "1"\n[dependencies.gpui-kit-assets]\nversion = "1"\n[dependencies.other]\npackage = "gpui-base"\n[features]\nd = []\n', - ), - ).toEqual(['a', 'gpui-component', 'b', 'c', 'gpui-kit-assets', 'gpui-base']); - expect( - gpuiKitPatchNames(['[dependencies.other]\npackage = "gpui-base"\n']), - ).toEqual(KIT_NAMES); -}); - -test('entries added to the managed block are refused if the user table sets them', () => { - const manifest = - '[package]\nname = "a"\n\n[patch.crates-io]\nfoo = { path = "x" }\n'; - expect(() => - applyPatchBlock(manifest, 'Cargo.toml', [['foo', '{ path = "y" }']]), - ).toThrow(/already sets foo/u); -}); diff --git a/vendor/react-native-gpui/packages/cli/src/commands.js b/vendor/react-native-gpui/packages/cli/src/commands.js deleted file mode 100644 index db3f0e57d9..0000000000 --- a/vendor/react-native-gpui/packages/cli/src/commands.js +++ /dev/null @@ -1,2128 +0,0 @@ -import { Buffer } from 'node:buffer'; -import fs from 'node:fs'; -import path from 'node:path'; -import { execFileSync, spawn, spawnSync } from 'node:child_process'; -import { LINUX_LIBRARIES, installCommands } from './doctor.cjs'; -import { createRequire } from 'node:module'; -import { fileURLToPath } from 'node:url'; -import { autolink, npxArgs, npxCommand, npxShell } from './autolink.js'; -import { desktopOs, loadDesktopConfig, targetsFor } from './desktop-config.js'; -import { - CARGO_PACKAGER_VERSION, - runtimeLibraries, - targetProfileDir, - toPackagerConfig, -} from './package-desktop.js'; -import { - cargoBuildRecording, - cargoTargetDirectory, - pruneTarget, - targetGcEnabled, - targetGcMaxAgeDays, -} from './target-gc.js'; - -const cliDir = path.dirname(fileURLToPath(import.meta.url)); -const templatesDir = path.resolve(cliDir, '../templates'); - -/** - * The app links the system xkbcommon and xcb libraries, and a missing one only - * surfaces at the end of a long build as a linker error, so check up front. - * A non-system pkg-config first on PATH (Linuxbrew, Nix) cannot see the system - * packages. Pure so it can be unit tested: `runPkgConfig` - * returns true, false, or 'missing-pkg-config'; `systemPkgConfigPath` returns - * the system pkg-config search path, or null when it cannot be determined. - * - * The message stays distribution-neutral: it names the pkg-config module and - * gives one install command per common package manager, and the path hint uses - * whatever this machine's system pkg-config reports rather than a hard-coded - * x86_64 Debian path. - */ -export function linuxBuildDependencyProblem( - platform, - runPkgConfig, - systemPkgConfigPath = () => null, -) { - if (platform !== 'linux') return null; - for (const { pc, packages } of LINUX_LIBRARIES) { - const result = runPkgConfig(pc); - if (result === 'missing-pkg-config') { - return ( - 'pkg-config is required to build the desktop app on Linux. ' + - "Install your distribution's pkg-config package " + - '(Debian/Ubuntu: `sudo apt install pkg-config`, ' + - 'Fedora: `sudo dnf install pkgconf-pkg-config`, ' + - 'Arch: `sudo pacman -S pkgconf`), then re-run.' - ); - } - if (!result) { - const systemPath = systemPkgConfigPath(); - const hint = systemPath - ? `set PKG_CONFIG_PATH=${systemPath} and re-run.` - : 'point PKG_CONFIG_PATH at your system pkgconfig directories and re-run.'; - return ( - `Linux build dependency ${pc} was not found. ` + - `Install your distribution's development package for it ` + - `(${installCommands(packages)}). ` + - `If pkg-config cannot see the system packages (Linuxbrew or Nix ` + - `pkg-config first on PATH does this), ${hint}` - ); - } - } - return null; -} - -/** - * The system pkg-config search path, for the preflight hint. Uses - * `/usr/bin/pkg-config` explicitly: a Linuxbrew or Nix `pkg-config` first on - * PATH is exactly the situation the hint is about, and it reports its own - * prefix, not the system one. Returns null when the binary is missing or the - * query fails. - */ -function readSystemPkgConfigPath() { - const pkgConfig = '/usr/bin/pkg-config'; - if (!fs.existsSync(pkgConfig)) return null; - try { - const output = execFileSync( - pkgConfig, - ['--variable', 'pc_path', 'pkg-config'], - { encoding: 'utf8' }, - ).trim(); - return output || null; - } catch { - return null; - } -} - -const run = (bin, args, options = {}) => - execFileSync(bin, args, { - cwd: options.cwd ?? process.cwd(), - stdio: 'inherit', - env: options.env ?? process.env, - shell: options.shell ?? false, - }); - -/** - * Downloads the prebuilt runtime before Cargo runs, so the progress reaches the - * terminal: Cargo hides a build script's output until the script finishes. A - * failure is left to the build script, which falls back to building from source. - */ -function hasMetalCompiler() { - return ( - spawnSync('xcrun', ['-sdk', 'macosx', 'metal', '--version'], { - stdio: 'ignore', - }).status === 0 - ); -} - -function fetchPrebuiltRuntime(projectRoot, autolinkManifest) { - if ( - process.env.RN_GPUI_BUILD_FROM_SOURCE || - process.env.RN_GPUI_PREBUILT_DIR - ) { - return; - } - try { - const manifest = JSON.parse(fs.readFileSync(autolinkManifest, 'utf8')); - if (manifest.prebuilt === 'never') { - return; - } - const appRequire = createRequire(path.join(projectRoot, 'package.json')); - const script = path.join( - path.dirname(appRequire.resolve('@react-native-gpui/core/package.json')), - 'scripts/prebuilt-binaries.mjs', - ); - spawnSync( - process.execPath, - [ - script, - 'ensure', - '--renderer', - manifest.renderer?.name === 'loom' ? 'loom' : 'fabric', - ], - { stdio: ['ignore', 'ignore', 'inherit'] }, - ); - } catch {} -} - -function loadEngineBundle(projectRoot) { - const appRequire = createRequire(path.join(projectRoot, 'package.json')); - let platformPackageJson; - try { - platformPackageJson = appRequire.resolve( - '@react-native-gpui/core/package.json', - ); - } catch { - return null; - } - const { activeJsEngineBundle } = appRequire( - path.join(path.dirname(platformPackageJson), 'js-engine.js'), - ); - return activeJsEngineBundle(projectRoot); -} - -function activeEngineName(projectRoot) { - const appRequire = createRequire(path.join(projectRoot, 'package.json')); - try { - const { activeJsEngine } = appRequire( - path.join( - path.dirname( - appRequire.resolve('@react-native-gpui/core/package.json'), - ), - 'js-engine.js', - ), - ); - return activeJsEngine(projectRoot)?.name ?? null; - } catch { - return null; - } -} - -function copyFontAssets(projectRoot, bundlePath, config) { - const destination = path.join( - path.dirname(bundlePath), - 'assets', - 'assets', - 'fonts', - ); - fs.rmSync(destination, { recursive: true, force: true }); - const sources = []; - const appFonts = path.join(projectRoot, 'desktop/assets/fonts'); - if (fs.existsSync(appFonts)) sources.push({ root: appFonts, prefix: 'app' }); - for (const [name, dependency] of Object.entries(config.dependencies ?? {})) { - const root = - dependency.root ?? path.join(projectRoot, 'node_modules', name); - for (const assets of dependency.assets ?? []) { - sources.push({ - root: path.resolve(root, assets), - prefix: name.replaceAll('/', '-'), - }); - } - } - let copied = 0; - const copyDirectory = (sourceRoot, directory, prefix) => { - if (!fs.existsSync(directory)) return; - for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { - const source = path.join(directory, entry.name); - if (entry.isDirectory()) { - copyDirectory(sourceRoot, source, prefix); - } else if (/\.(?:ttf|otf)$/iu.test(entry.name)) { - const relative = path.relative(sourceRoot, source); - const target = path.join(destination, prefix, relative); - fs.mkdirSync(path.dirname(target), { recursive: true }); - fs.copyFileSync(source, target); - copied += 1; - } - } - }; - for (const source of sources) - copyDirectory(source.root, source.root, source.prefix); - console.log(`Prepared ${copied} desktop font asset(s) in ${destination}`); -} - -function cargoConfigSetsTargetDir(projectRoot) { - let directory = path.resolve(projectRoot); - while (true) { - for (const fileName of ['config.toml', 'config']) { - const configPath = path.join(directory, '.cargo', fileName); - if (!fs.existsSync(configPath)) continue; - const lines = fs.readFileSync(configPath, 'utf8').split(/\r?\n/u); - let inBuildTable = false; - for (const line of lines) { - const table = line.match(/^\s*\[([^\]]+)\]/u); - if (table) { - inBuildTable = table[1].trim() === 'build'; - } else if (inBuildTable && /^\s*target-dir\s*=/u.test(line)) { - return true; - } - } - } - const parent = path.dirname(directory); - if (parent === directory) return false; - directory = parent; - } -} - -/** - * The project the Metro on `host:port` serves: its root, `null` for a Metro - * that does not say (older versions), or `undefined` when none answers. - */ -export async function metroProjectRoot(host, port) { - try { - const response = await fetch(`http://${host}:${port}/status`, { - signal: AbortSignal.timeout(1000), - }); - if ( - !response.ok || - !(await response.text()).includes('packager-status:running') - ) - return undefined; - return response.headers.get('x-react-native-project-root'); - } catch { - return undefined; - } -} - -const samePath = (a, b) => { - const real = target => { - try { - return fs.realpathSync(target); - } catch { - return path.resolve(target); - } - }; - return real(a) === real(b); -}; - -/** - * The terminal Metro opens in: `--terminal`, then `$REACT_TERMINAL` (the - * variable React Native's own `run-ios`/`run-android` read), then the - * platform's default. - */ -export function metroTerminal( - terminal, - { - platform = process.platform, - env = process.env, - exists = command => { - try { - execFileSync('which', [command], { stdio: 'ignore' }); - return true; - } catch { - return false; - } - }, - } = {}, -) { - const requested = terminal ?? env.REACT_TERMINAL; - if (requested) return requested; - if (platform === 'darwin') { - if (env.TERM_PROGRAM === 'iTerm.app') return 'iTerm'; - return 'Terminal'; - } - if (platform === 'win32') return 'cmd.exe'; - return [ - 'x-terminal-emulator', - 'gnome-terminal', - 'konsole', - 'xfce4-terminal', - 'kitty', - 'alacritty', - 'xterm', - ].find(exists); -} - -const shellQuote = value => `'${String(value).replaceAll("'", "'\\''")}'`; - -/** - * Opens Metro in a terminal window of its own, where its keys (`r`, `d`, `j`) - * work, the way `run-ios` and `run-android` do. Returns false when no window - * could be opened. - */ -function startMetroInTerminal({ projectRoot, desktopRoot, args, terminal }) { - const require = createRequire(path.join(projectRoot, 'package.json')); - let cli; - try { - // `cli.js` is not in react-native's `exports`; `package.json` is. - cli = path.join( - path.dirname(require.resolve('react-native/package.json')), - 'cli.js', - ); - } catch { - return false; - } - if (!fs.existsSync(cli)) return false; - const scriptDir = path.join(desktopRoot, 'build'); - fs.mkdirSync(scriptDir, { recursive: true }); - try { - if (process.platform === 'win32') { - const script = path.join(scriptDir, 'metro.bat'); - const quoted = [process.execPath, cli, ...args].map(arg => `"${arg}"`); - fs.writeFileSync( - script, - `@echo off\r\ntitle Metro\r\ncd /d "${projectRoot}"\r\n${quoted.join(' ')}\r\npause\r\n`, - ); - // A detached child on Windows gets a console window of its own. - spawn('cmd.exe', ['/c', script], { - detached: true, - stdio: 'ignore', - windowsHide: false, - }).unref(); - return true; - } - const script = path.join( - scriptDir, - process.platform === 'darwin' ? 'metro.command' : 'metro.sh', - ); - fs.writeFileSync( - script, - [ - '#!/bin/sh', - `cd ${shellQuote(projectRoot)} || exit 1`, - `exec ${[process.execPath, cli, ...args].map(shellQuote).join(' ')}`, - '', - ].join('\n'), - { mode: 0o755 }, - ); - fs.chmodSync(script, 0o755); - if (process.platform === 'darwin') { - execFileSync('open', ['-a', terminal, script], { stdio: 'ignore' }); - return true; - } - // gnome-terminal takes the command after `--`; the others after `-e`. - const terminalArgs = /gnome-terminal$/u.test(terminal) - ? ['--', script] - : ['-e', script]; - const child = spawn(terminal, terminalArgs, { - detached: true, - stdio: 'ignore', - }); - child.on('error', () => {}); - child.unref(); - return true; - } catch { - return false; - } -} - -/** The previous behaviour: Metro in the background, logging to a file. */ -function startMetroInBackground({ projectRoot, desktopRoot, args }) { - const logPath = path.join(desktopRoot, 'build/metro.log'); - fs.mkdirSync(path.dirname(logPath), { recursive: true }); - const logFd = fs.openSync(logPath, 'a'); - const server = spawn( - npxCommand, - npxArgs(['react-native', ...args, '--no-interactive']), - { - cwd: projectRoot, - detached: true, - stdio: ['ignore', logFd, logFd], - shell: npxShell, - }, - ); - fs.closeSync(logFd); - server.unref(); - const state = { error: undefined, server, logPath }; - server.once('error', error => { - state.error = error; - }); - return state; -} - -async function ensureMetro({ - projectRoot, - desktopRoot, - host, - port, - config, - packager = true, - packagerLog = false, - terminal, -}) { - const runningFor = await metroProjectRoot(host, port); - if (runningFor !== undefined) { - if (runningFor !== null && !samePath(runningFor, projectRoot)) { - throw new Error( - `Metro at http://${host}:${port} is serving another project (${runningFor}). ` + - `Stop it, or run on another port with --port.`, - ); - } - console.log(`Reusing Metro at http://${host}:${port}`); - return; - } - if (!packager) { - console.log( - `Metro is not running at http://${host}:${port}; start it with npx react-native start --port ${port}.`, - ); - return; - } - - const args = ['start', '--host', host, '--port', String(port)]; - if (config) args.push('--config', config); - const interactive = process.stdin.isTTY && !process.env.CI; - const window = - !packagerLog && interactive ? metroTerminal(terminal) : undefined; - let background; - if ( - window && - startMetroInTerminal({ projectRoot, desktopRoot, args, terminal: window }) - ) { - console.log(`Starting Metro in a new ${window} window`); - } else { - background = startMetroInBackground({ projectRoot, desktopRoot, args }); - } - - for (let attempt = 0; attempt < 120; attempt += 1) { - if ((await metroProjectRoot(host, port)) !== undefined) { - console.log( - background - ? `Started Metro at http://${host}:${port} (log: ${background.logPath})` - : `Started Metro at http://${host}:${port}`, - ); - return; - } - if (background?.error) throw background.error; - if (background && background.server.exitCode !== null) break; - await new Promise(resolve => setTimeout(resolve, 500)); - } - throw new Error( - background - ? `Metro did not start at http://${host}:${port}. Check ${background.logPath} or run npx react-native start --port ${port}.` - : `Metro did not start at http://${host}:${port}. Check the Metro window or run npx react-native start --port ${port}.`, - ); -} - -export async function runDesktop({ - projectRoot = process.cwd(), - entryFile, - bundle, - config, - release = false, - port = 8081, - host = 'localhost', - packager = true, - packagerLog = false, - terminal, - features, - noLaunch = false, - packaging = false, - signIdentity, -}) { - projectRoot = path.resolve(projectRoot); - const dependencyProblem = linuxBuildDependencyProblem( - process.platform, - pc => { - try { - execFileSync('pkg-config', ['--exists', pc], { stdio: 'ignore' }); - return true; - } catch (error) { - return error?.code === 'ENOENT' ? 'missing-pkg-config' : false; - } - }, - readSystemPkgConfigPath, - ); - if (dependencyProblem) throw new Error(dependencyProblem); - const desktopRoot = path.join(projectRoot, 'desktop'); - entryFile ??= - ['index.js', 'index.ts', 'index.tsx'].find(file => - fs.existsSync(path.join(projectRoot, file)), - ) ?? 'index.js'; - const bundlePath = path.resolve( - projectRoot, - bundle ?? path.join(desktopRoot, 'build/index.bundle'), - ); - const metroConfig = path.resolve( - projectRoot, - config ?? path.join(desktopRoot, 'metro.config.js'), - ); - - // Autolink first: the manifest it writes tells the bundle path which engine is - // active, and therefore which Metro transform and shipping format to use. - const rnConfig = autolink({ projectRoot }); - const engineBundle = loadEngineBundle(projectRoot); - - // What the runtime loads: the plain Metro bundle, or the engine's compiled - // format (`.hbc` bytecode, for example). - let runtimeBundlePath = bundlePath; - let extraResources = []; - // The addons a release bundle loads, collected next to it. - let nodeAddonsDir; - - // A debug build normally loads its JavaScript from Metro. The test driver has - // no Metro, so a build made for it also writes the bundle it will load. - const emitDevBundle = - !release && - noLaunch && - (features ?? '') - .split(',') - .some(feature => feature.trim() === 'test-driver'); - - if (release || emitDevBundle) { - fs.mkdirSync(path.dirname(bundlePath), { recursive: true }); - const bundleArgs = [ - 'react-native', - 'bundle', - '--platform', - 'desktop', - '--entry-file', - entryFile, - '--bundle-output', - bundlePath, - '--assets-dest', - path.join(path.dirname(bundlePath), 'assets'), - '--dev', - release ? 'false' : 'true', - ]; - if (fs.existsSync(metroConfig)) bundleArgs.push('--config', metroConfig); - run(npxCommand, npxArgs(bundleArgs), { cwd: projectRoot, shell: npxShell }); - - if (release) { - nodeAddonsDir = path.join(path.dirname(bundlePath), 'node-addons'); - const collected = collectNodeAddons({ - bundle: bundlePath, - out: nodeAddonsDir, - }); - if (collected.copied.length === 0) nodeAddonsDir = undefined; - else { - signCollectedNodeAddons({ - directory: nodeAddonsDir, - identity: process.env.APPLE_SIGNING_IDENTITY, - }); - } - } - - if (release && engineBundle && typeof engineBundle.compile === 'function') { - const extension = - typeof engineBundle.bundleExtension === 'string' - ? engineBundle.bundleExtension - : '.js'; - const compiledPath = `${bundlePath.replace(/\.[^./\\]+$/u, '')}${extension}`; - const compiled = engineBundle.compile({ - input: bundlePath, - output: compiledPath, - dev: false, - }); - runtimeBundlePath = path.resolve( - projectRoot, - compiled?.output ?? compiledPath, - ); - } - extraResources = await runBundleHooks({ - projectRoot, - desktopRoot, - bundleDir: path.dirname(bundlePath), - entryFile, - metroConfig: fs.existsSync(metroConfig) ? metroConfig : undefined, - engine: engineBundle, - }); - } else { - const numericPort = Number(port); - if ( - !Number.isInteger(numericPort) || - numericPort < 1 || - numericPort > 65535 - ) { - throw new Error(`--port must be an integer between 1 and 65535`); - } - await ensureMetro({ - projectRoot, - desktopRoot, - host, - port: numericPort, - config: fs.existsSync(metroConfig) ? metroConfig : undefined, - packager, - packagerLog, - terminal, - }); - } - copyFontAssets(projectRoot, bundlePath, rnConfig); - - const appCargoManifest = path.join(desktopRoot, 'Cargo.toml'); - if (!fs.existsSync(appCargoManifest)) { - throw new Error(`missing desktop Cargo manifest: ${appCargoManifest}`); - } - fetchPrebuiltRuntime( - projectRoot, - path.join(desktopRoot, 'autolink/autolink.json'), - ); - // Each build of an ad-hoc signed binary is a new app to the keychain, which - // then asks again for every item the app stored. Signed with a certificate - // under the app's identifier, every build is the same app. - const signingIdentity = - process.platform === 'darwin' && !packaging - ? (signIdentity ?? process.env.APPLE_SIGNING_IDENTITY) - : undefined; - const cargoArgs = [noLaunch || signingIdentity ? 'build' : 'run']; - if (release) cargoArgs.push('--release'); - const cargoFeatures = (features ?? '') - .split(',') - .map(feature => feature.trim()) - .filter(Boolean); - if (cargoFeatures.some(feature => !/^[A-Za-z0-9_/-]+$/u.test(feature))) { - throw new Error( - '--features must be a comma-separated list of Cargo features', - ); - } - if ( - process.platform === 'darwin' && - !cargoFeatures.includes('runtime-shaders') && - /^runtime-shaders\s*=/mu.test(fs.readFileSync(appCargoManifest, 'utf8')) && - !hasMetalCompiler() - ) { - console.log( - 'No Metal shader compiler (it ships with Xcode): the shaders are compiled when the app starts.', - ); - cargoFeatures.push('runtime-shaders'); - } - if (cargoFeatures.length > 0) - cargoArgs.push('--features', cargoFeatures.join(',')); - cargoArgs.push('--manifest-path', appCargoManifest); - const cargoEnv = { - ...process.env, - RN_GPUI_BUNDLE: runtimeBundlePath, - RN_GPUI_ASSETS_DIR: path.join(path.dirname(bundlePath), 'assets', 'assets'), - RN_GPUI_SOURCE_URL: entryFile.replace(/\.[^.]+$/u, ''), - RN_GPUI_DEV_HOST: host, - RN_GPUI_DEV_PORT: String(port), - RN_GPUI_AUTOLINK_MANIFEST: path.join(desktopRoot, 'autolink/autolink.json'), - RN_GPUI_AUTOLINK_CMAKE: path.join(desktopRoot, 'autolink/autolink.cmake'), - }; - // An unbundled run has no Info.plist to name its icon, so the app is told - // where it is and sets its Dock icon itself. - if (!packaging) cargoEnv.RN_GPUI_APP_ICON = appIconPath(projectRoot); - // `package-desktop` sets this: the binary is about to be installed elsewhere, - // so `build.rs` emits only relative rpaths. A plain release build keeps the - // absolute ones, because it is run from this tree. - if (packaging) cargoEnv.RN_GPUI_PACKAGING = '1'; - if ( - process.env.CARGO_TARGET_DIR === undefined && - !cargoConfigSetsTargetDir(projectRoot) - ) { - cargoEnv.CARGO_TARGET_DIR = path.join(desktopRoot, 'build/target'); - } - if (targetGcEnabled()) { - // Cargo never cleans a target directory, so every build first drops the - // units no build has used for a week, then builds while recording what it - // used. The build is separate from the launch so its JSON messages are not - // mixed with the app's own output; `cargo run` then finds it all fresh. - const targetDir = cargoTargetDirectory(appCargoManifest, { - cwd: projectRoot, - env: cargoEnv, - }); - if (targetDir) pruneTarget(targetDir, { maxAgeDays: targetGcMaxAgeDays() }); - await cargoBuildRecording(['build', ...cargoArgs.slice(1)], { - cwd: projectRoot, - env: cargoEnv, - targetDir, - }); - if (!noLaunch && !signingIdentity) { - run('cargo', cargoArgs, { cwd: projectRoot, env: cargoEnv }); - } - } else { - run('cargo', cargoArgs, { - cwd: projectRoot, - env: cargoEnv, - }); - } - if (signingIdentity) { - const targetDir = cargoTargetDirectory(appCargoManifest, { - cwd: projectRoot, - env: cargoEnv, - }); - if (!targetDir) - throw new Error('cargo did not report its target directory'); - const binary = path.join( - targetDir, - release ? 'release' : 'debug', - desktopCrateName(desktopRoot), - ); - const { identifier } = loadDesktopConfig(projectRoot, process.platform); - run('codesign', [ - '--force', - '--sign', - signingIdentity, - '--identifier', - identifier, - binary, - ]); - if (!noLaunch) run(binary, [], { cwd: projectRoot, env: cargoEnv }); - } - - // A release run finds its addons next to the executable. A packaged app gets - // them from the packager as `Resources/node-addons`. - if (release && !packaging && nodeAddonsDir !== undefined) { - const targetDir = cargoTargetDirectory(appCargoManifest, { - cwd: projectRoot, - env: cargoEnv, - }); - if (targetDir) { - const beside = path.join(targetDir, 'release', 'node-addons'); - fs.rmSync(beside, { recursive: true, force: true }); - fs.cpSync(nodeAddonsDir, beside, { recursive: true }); - } - } - - // The file the runtime was told to load: the engine's compiled output in a - // release build, the Metro bundle otherwise. `package-desktop` stages it. - return { runtimeBundlePath, bundlePath, extraResources, nodeAddonsDir }; -} - -const appPackageName = (projectRoot, packageJson) => - `react-native-gpui-${(packageJson.name ?? path.basename(projectRoot)) - .toLowerCase() - .replaceAll(/[^a-z0-9-]/gu, '-')}`; - -function snapshotTree(root, track, rememberDirectory, existingDirectories) { - if (!fs.existsSync(root)) { - rememberDirectory(root); - return; - } - existingDirectories.add(root); - for (const entry of fs.readdirSync(root, { withFileTypes: true })) { - const target = path.join(root, entry.name); - if (entry.isDirectory()) { - snapshotTree(target, track, rememberDirectory, existingDirectories); - } else track(target); - } -} - -function removeNewFiles(root, snapshots, existingDirectories) { - if (!fs.existsSync(root)) return; - for (const entry of fs.readdirSync(root, { withFileTypes: true })) { - const target = path.join(root, entry.name); - if (entry.isDirectory()) - removeNewFiles(target, snapshots, existingDirectories); - else if (!snapshots.has(target)) { - fs.rmSync(target, { force: true, recursive: true }); - } - } - if (!existingDirectories.has(root)) { - try { - fs.rmdirSync(root); - } catch {} - } -} - -const desktopFiles = directory => - fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => { - const fullPath = path.join(directory, entry.name); - return entry.isDirectory() - ? desktopFiles(fullPath) - : [path.relative(path.join(templatesDir, 'app'), fullPath)]; - }); - -/// A number as a Rust float literal. -function asFloat(value) { - return Number.isInteger(value) ? `${value}.0` : String(value); -} - -/** - * The `main.rs` an app's `desktop.json` describes. - * - * The window, dev-menu and tray chain is unchanged from when these options - * lived in `app.json`; only where they are read from moved. - */ -export function desktopLaunchConfig(config, configPath) { - const settings = config.window ?? {}; - const title = - settings.title === undefined - ? 'env!("RN_GPUI_APP_NAME")' - : JSON.stringify(settings.title); - const width = settings.width; - const height = settings.height; - - // `window_size` takes `f32`: a JSON number reaches Rust as `1024`, which is - // an integer literal and does not coerce. - const chain = [ - ` .window_title(${title})`, - ` .window_size(${asFloat(width)}, ${asFloat(height)})`, - ]; - if (settings.position !== undefined) { - const { x, y } = settings.position; - if (x === undefined || y === undefined) { - throw new Error( - `desktop/desktop.json window.position needs x and y: ${configPath}`, - ); - } - chain.push(` .window_position(${asFloat(x)}, ${asFloat(y)})`); - } - if (settings.restoreState === false) { - chain.push(' .restore_window_state(false)'); - } - if (settings.menuBar === false) { - // Only meaningful where the bar is drawn inside the window; macOS ignores it, - // and the `menuBarInWindow` capability says so. - chain.push(' .menu_bar(false)'); - } - if (settings.cornerRadius !== undefined) { - chain.push(` .corner_radius(${asFloat(settings.cornerRadius)})`); - } - if (settings.windowControlsPosition === 'left') { - // Right is the default, and only consulted on Linux where the desktop gives - // no layout of its own. - chain.push(' .window_controls_position("left")'); - } - if (settings.titleBar !== undefined && settings.titleBar !== 'default') { - // The default is the platform's own bar, so only the two custom kinds are - // emitted. The enum is spelled out in full because the generated file has no - // `use` lines to import it with. - const variant = - { hidden: 'Hidden', none: 'Borderless' }[settings.titleBar] ?? - 'Transparent'; - chain.push(` .title_bar(react_native_gpui::WindowTitleBar::${variant})`); - } - if (settings.background !== undefined && settings.background !== 'opaque') { - const variant = { - transparent: 'Transparent', - blurred: 'Blurred', - mica: 'Mica', - }[settings.background]; - if (variant === undefined) { - throw new Error( - `desktop/desktop.json window.background must be opaque, transparent, blurred or mica: ${configPath}`, - ); - } - chain.push( - ` .background(react_native_gpui::WindowBackground::${variant})`, - ); - } - if (settings.windowButtons === false) { - chain.push(' .window_buttons(false)'); - } - if (settings.shadow === false) { - chain.push(' .shadow(false)'); - } - if (settings.trafficLightPosition !== undefined) { - const { x, y } = settings.trafficLightPosition; - if (x === undefined || y === undefined) { - throw new Error( - `desktop/desktop.json window.trafficLightPosition needs x and y: ${configPath}`, - ); - } - chain.push(` .traffic_light_position(${asFloat(x)}, ${asFloat(y)})`); - } - if (config.accessory === true) { - chain.push(' .accessory(true)'); - } - chain.push(` .dev_menu(${config.devMenu})`); - if ((config.urlSchemes ?? []).length > 0) { - const schemes = config.urlSchemes.map(scheme => JSON.stringify(scheme)); - chain.push(` .url_schemes(&[${schemes.join(', ')}])`); - chain.push(` .single_instance(${config.singleInstance !== false})`); - } - if (config.tray !== undefined) { - const tray = config.tray; - let trayChain = 'TrayConfig::default()'; - if (tray.component !== undefined) { - trayChain += `.component(${JSON.stringify(tray.component)})`; - } - if (tray.tooltip !== undefined) { - trayChain += `.tooltip(${JSON.stringify(tray.tooltip)})`; - } - if (tray.icon !== undefined) { - // Embedded, so a packaged app needs no file beside it. - const iconPath = JSON.stringify(`/${tray.icon.replaceAll('\\', '/')}`); - trayChain += `.icon_bytes(include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), ${iconPath})))`; - trayChain += `.icon_template(${tray.iconTemplate === true})`; - } - if (tray.popoverAnchor !== undefined && tray.popoverAnchor !== 'auto') { - trayChain += `.popover_anchor_name(${JSON.stringify(tray.popoverAnchor)})`; - } - if (tray.popoverOffset !== undefined) { - const { x, y } = tray.popoverOffset; - if (x === undefined || y === undefined) { - throw new Error( - `desktop/desktop.json tray.popoverOffset needs x and y: ${configPath}`, - ); - } - trayChain += `.popover_offset(${asFloat(x)}, ${asFloat(y)})`; - } - if (tray.accessory === false) { - trayChain += '.accessory(false)'; - } - chain.push(` .tray(${trayChain})`); - } - chain.push(` .configure_window(|options| { - // GPUI window options are public: titlebar, resizability, display, - // decorations, min size, and other native window behavior. - options.is_resizable = ${settings.resizable === false ? 'false' : 'true'}; - })`); - - return `//! Project-owned desktop launch configuration. -//! -//! Generated by \`init-desktop\` from \`desktop/desktop.json\`; edit that file and -//! re-run \`npx react-native init-desktop\`, or this file directly. See -//! \`desktop/README.md\` for the full set of options. -//! -//! Add \`mod my_turbo_module;\` here for local Rust TurboModules. Put matching -//! \`Native*.ts\` specs beside this file; \`run-desktop\` discovers and codegens -//! those specs automatically. - -fn main() { - // A debug build knows where its own bundle is; a release build does not, and - // must not: the path would name the machine that built it. A packaged release - // app resolves the bundle beside its executable instead. - #[cfg(debug_assertions)] - if std::env::var_os("RN_GPUI_BUNDLE").is_none() { - std::env::set_var("RN_GPUI_BUNDLE", env!("RN_GPUI_DEFAULT_BUNDLE")); - } - let config = react_native_gpui::DesktopAppConfig::from_env_with_defaults( - env!("RN_GPUI_APP_NAME"), - env!("RN_GPUI_APP_ID"), - ) -${chain.join('\n')}; - - react_native_gpui::run_with(config); -} -`; -} - -/// The file that pulls the published type augmentation into an app's build. -const ENV_TYPES_FILE = 'react-native-gpui-env.d.ts'; -const ENV_TYPES_CONTENT = `/// -// Added by react-native-gpui. Do not edit: it is regenerated. -`; - -/** The minor of a React Native version or range such as `0.87.1` or `^0.87.0`. */ -export function reactNativeMinor(spec) { - const match = /(?:^|[^\d.])0\.(\d+)\.\d+/u.exec(String(spec ?? '')); - return match === null ? undefined : Number(match[1]); -} - -/** - * The range of our packages that supports the app's React Native minor. - * - * Our packages are versioned `0..`, so React Native - * 0.87 takes `0.87.x`. The prerelease floor lets the alphas satisfy it. - */ -export function gpuiVersionRange(projectRoot, packageJson) { - let minor = reactNativeMinor( - packageJson.dependencies?.['react-native'] ?? - packageJson.devDependencies?.['react-native'], - ); - if (minor === undefined) { - try { - const installed = JSON.parse( - fs.readFileSync( - path.join(projectRoot, 'node_modules/react-native/package.json'), - 'utf8', - ), - ); - minor = reactNativeMinor(installed.version); - } catch { - // Not installed yet. - } - } - if (minor === undefined) { - throw new Error( - 'Cannot tell which React Native version this app uses. Pin react-native to an exact version such as 0.87.1 in package.json.', - ); - } - return `~0.${minor}.0-alpha.0`; -} - -/** - * Fails with a readable message when the registry has no release of the core - * package for the app's React Native minor. A registry that cannot be reached is - * not a failure here: the install that follows reports it. - */ -export function assertReleaseExists(range, { registryView = npmView } = {}) { - const result = registryView(`@react-native-gpui/core@${range}`); - if (result.status !== 0) { - if (/E404|404 Not Found/u.test(result.stderr ?? '')) { - throw new Error( - `@react-native-gpui/core is not published on the registry (looked for ${range}).`, - ); - } - return; - } - if (String(result.stdout ?? '').trim() === '') { - const minor = /^~0\.(\d+)\./u.exec(range)?.[1]; - throw new Error( - `No @react-native-gpui/core release supports React Native 0.${minor}. Use a React Native version that has one (the packages follow it: 0.${minor}.x).`, - ); - } -} - -function npmView(spec) { - return spawnSync( - process.platform === 'win32' ? 'npm.cmd' : 'npm', - ['view', spec, 'version', '--json'], - { encoding: 'utf8', shell: process.platform === 'win32' }, - ); -} - -/// Libraries whose desktop side is a separate package, and the library -/// `.` that package supports. -const desktopLibraryModules = { - 'react-native-safe-area-context': { - module: '@react-native-gpui/safe-area-context', - version: '5.10', - }, -}; - -export function scaffoldDesktop( - projectRoot, - packageJson, - { preserveExisting = false, beforeWrite = () => {} } = {}, -) { - const desktopTemplate = path.join(templatesDir, 'app/desktop'); - for (const relativePath of desktopFiles(desktopTemplate)) { - const targetRelativePath = - relativePath === 'desktop/gitignore' - ? 'desktop/.gitignore' - : relativePath; - const target = path.join(projectRoot, targetRelativePath); - if (preserveExisting && fs.existsSync(target)) continue; - beforeWrite(target); - fs.mkdirSync(path.dirname(target), { recursive: true }); - fs.copyFileSync(path.join(templatesDir, 'app', relativePath), target); - } - - const cargoPath = path.join(projectRoot, 'desktop/Cargo.toml'); - if (!preserveExisting || !fs.existsSync(cargoPath)) { - beforeWrite(cargoPath); - fs.writeFileSync( - cargoPath, - `[package]\nname = ${JSON.stringify(appPackageName(projectRoot, packageJson))}\nversion = "0.1.0"\nedition = "2021"\n\n# Set CARGO_PROFILE_DEV_DEBUG=full to opt into full debug information.\n[profile.dev]\ndebug = "line-tables-only"\nsplit-debuginfo = "packed"\n\n# Dependencies are optimized even in a dev build: GPUI rebuilds and paints the\n# element tree on every frame, and they are only compiled once.\n[profile.dev.package."*"]\ndebug = false\nopt-level = 3\n\n# The C++ bridge picks its CMake build type from this crate's opt-level, and a\n# Release build of React Native has no dev server, inspector or Fast Refresh.\n[profile.dev.package.rn-gpui-sys]\nopt-level = 0\n\n[profile.release]\ndebug = "line-tables-only"\n# Cargo strips inside the linker, before dsymutil, so package-desktop preserves the\n# Cargo dSYM and then strips. Full LTO: 2 MB smaller for 1.4x the build time.\nstrip = "none"\nsplit-debuginfo = "packed"\nlto = "fat"\ncodegen-units = 1\n\n[build-dependencies]\nserde_json = "1"\n\n[dependencies]\n`, - ); - } - - // The type augmentation for the desktop View props is global, and a TypeScript - // augmentation only applies when the file declaring it is compiled. This - // reference is what puts it in the app's compilation, the way Next.js and Vite - // write theirs, so `desktopDragRegion` and `onContextMenu` type-check without an - // import of the desktop entry point. - const envPath = path.join(projectRoot, ENV_TYPES_FILE); - if (!preserveExisting || !fs.existsSync(envPath)) { - beforeWrite(envPath); - fs.writeFileSync(envPath, ENV_TYPES_CONTENT); - } - - const appConfigPath = path.join(projectRoot, 'app.json'); - if (!fs.existsSync(appConfigPath)) { - throw new Error(`missing React Native app config: ${appConfigPath}`); - } - const appConfig = JSON.parse(fs.readFileSync(appConfigPath, 'utf8')); - if (typeof appConfig.name !== 'string' || appConfig.name.length === 0) { - throw new Error(`app.json must define a nonempty name: ${appConfigPath}`); - } - // Every launch setting comes from `desktop/desktop.json`. - const launchConfig = desktopLaunchConfig( - loadDesktopConfig(projectRoot, process.platform), - path.join(projectRoot, 'desktop/desktop.json'), - ); - if (launchConfig !== null) { - const mainPath = path.join(projectRoot, 'desktop/src/main.rs'); - if (!preserveExisting || !fs.existsSync(mainPath)) { - beforeWrite(mainPath); - fs.writeFileSync(mainPath, launchConfig); - } - } - - const range = gpuiVersionRange(projectRoot, packageJson); - const updatedPackageJson = { - ...packageJson, - dependencies: { - ...packageJson.dependencies, - '@react-native-gpui/core': - packageJson.dependencies?.['@react-native-gpui/core'] ?? range, - '@react-native-gpui/hermes': - packageJson.dependencies?.['@react-native-gpui/hermes'] ?? range, - // `rn-gpui-module-build` resolves its spec generator from the app - // (`require.resolve('@react-native-gpui/codegen/generate-rust-spec')` with - // the crate directory as the search path), so the app must depend on it - // directly. Inside this repository the workspace hoists it and a missing - // entry goes unnoticed; an app installed from the registry fails with - // "Cannot find module '@react-native-gpui/codegen/generate-rust-spec'". - '@react-native-gpui/codegen': - packageJson.dependencies?.['@react-native-gpui/codegen'] ?? range, - }, - scripts: { - ...packageJson.scripts, - desktop: packageJson.scripts?.desktop ?? 'react-native run-desktop', - 'test:e2e': - packageJson.scripts?.['test:e2e'] ?? - 'vitest run --config desktop/vitest.e2e.config.ts', - }, - devDependencies: { - ...packageJson.devDependencies, - vitest: packageJson.devDependencies?.vitest ?? '^3.2.4', - '@react-native-gpui/testing': - packageJson.devDependencies?.['@react-native-gpui/testing'] ?? range, - '@react-native-gpui/cli': - packageJson.devDependencies?.['@react-native-gpui/cli'] ?? range, - }, - }; - for (const [library, { module, version }] of Object.entries( - desktopLibraryModules, - )) { - const declared = updatedPackageJson.dependencies[library]; - if (declared === undefined) continue; - // The module's peer is the library's own `.`. - if (!new RegExp(`^[~^]?${version.replace('.', '\\.')}\\b`).test(declared)) { - updatedPackageJson.dependencies[library] = `~${version}.0`; - } - updatedPackageJson.dependencies[module] ??= `~${version}.0-alpha.0`; - } - return updatedPackageJson; -} - -export function initDesktop({ - projectRoot = process.cwd(), - skipInstall = false, -}) { - projectRoot = path.resolve(projectRoot); - const snapshots = new Map(); - const createdDirectories = new Set(); - const existingDirectories = new Set(); - const track = file => { - if (!snapshots.has(file)) { - snapshots.set(file, fs.existsSync(file) ? fs.readFileSync(file) : null); - } - }; - try { - const packagePath = path.join(projectRoot, 'package.json'); - if (!fs.existsSync(packagePath)) { - throw new Error(`no package.json found in ${projectRoot}`); - } - const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8')); - if ( - !packageJson.dependencies?.['react-native'] && - !packageJson.devDependencies?.['react-native'] - ) { - throw new Error('package.json does not declare react-native'); - } - - const updatedPackageJson = scaffoldDesktop(projectRoot, packageJson, { - preserveExisting: true, - beforeWrite(file) { - track(file); - let directory = path.dirname(file); - const missingDirectories = []; - while (directory.startsWith(projectRoot) && !fs.existsSync(directory)) { - missingDirectories.push(directory); - directory = path.dirname(directory); - } - missingDirectories.forEach(item => createdDirectories.add(item)); - }, - }); - track(packagePath); - fs.writeFileSync( - packagePath, - `${JSON.stringify(updatedPackageJson, null, 2)}\n`, - ); - - if (!skipInstall) { - assertReleaseExists(gpuiVersionRange(projectRoot, packageJson)); - const manager = fs.existsSync(path.join(projectRoot, 'pnpm-lock.yaml')) - ? 'pnpm' - : fs.existsSync(path.join(projectRoot, 'yarn.lock')) - ? 'yarn' - : fs.existsSync(path.join(projectRoot, 'bun.lockb')) || - fs.existsSync(path.join(projectRoot, 'bun.lock')) - ? 'bun' - : 'npm'; - for (const lock of [ - 'package-lock.json', - 'npm-shrinkwrap.json', - 'yarn.lock', - 'pnpm-lock.yaml', - 'bun.lock', - 'bun.lockb', - ]) { - const file = path.join(projectRoot, lock); - track(file); - } - run(manager, ['install'], { cwd: projectRoot }); - } - - const desktopRoot = path.join(projectRoot, 'desktop'); - const autolinkRoot = path.join(desktopRoot, 'autolink'); - const buildRoot = path.join(desktopRoot, 'build'); - const rememberDirectory = directory => { - for ( - let current = directory; - current.startsWith(projectRoot) && !fs.existsSync(current); - current = path.dirname(current) - ) { - createdDirectories.add(current); - } - }; - snapshotTree(autolinkRoot, track, rememberDirectory, existingDirectories); - const assetsRoot = path.join(buildRoot, 'assets'); - snapshotTree(assetsRoot, track, rememberDirectory, existingDirectories); - const bundlePath = path.join(buildRoot, 'index.bundle'); - track(bundlePath); - track(path.join(desktopRoot, 'Cargo.toml')); - track(path.join(desktopRoot, 'src/main.rs')); - autolink({ projectRoot }); - - if (!fs.existsSync(bundlePath)) { - rememberDirectory(assetsRoot); - run( - npxCommand, - npxArgs([ - 'react-native', - 'bundle', - '--platform', - 'desktop', - '--entry-file', - ['index.js', 'index.ts', 'index.tsx'].find(file => - fs.existsSync(path.join(projectRoot, file)), - ) ?? 'index.js', - '--bundle-output', - bundlePath, - '--assets-dest', - assetsRoot, - '--config', - path.join(desktopRoot, 'metro.config.js'), - '--dev', - 'false', - ]), - { cwd: projectRoot, shell: npxShell }, - ); - } - console.log( - `Added desktop support to ${projectRoot}. Run npx react-native run-desktop.`, - ); - } catch (error) { - removeNewFiles( - path.join(projectRoot, 'desktop/autolink'), - snapshots, - existingDirectories, - ); - removeNewFiles( - path.join(projectRoot, 'desktop/build/assets'), - snapshots, - existingDirectories, - ); - const bundlePath = path.join(projectRoot, 'desktop/build/index.bundle'); - if (snapshots.get(bundlePath) === null) { - fs.rmSync(bundlePath, { force: true }); - } - for (const [file, contents] of [...snapshots.entries()].reverse()) { - if (contents === null) fs.rmSync(file, { force: true }); - else fs.writeFileSync(file, contents); - } - for (const directory of [...createdDirectories].sort( - (left, right) => right.length - left.length, - )) { - try { - fs.rmdirSync(directory); - } catch {} - } - console.error( - `init-desktop failed and restored its file changes: ${error.message}`, - ); - console.error('Manual steps to add desktop support:'); - for (const step of [ - 'Install @react-native-gpui/core and @react-native-gpui/cli in the app.', - 'Copy the desktop/ scaffold from @react-native-gpui/cli/templates/app/desktop.', - 'Add react-native-gpui-env.d.ts to the app root: /// ', - 'Run npm install (or your package manager), then npx react-native run-desktop.', - ]) { - console.error(` - ${step}`); - } - throw error; - } -} - -export function initProject({ appName, destination, initArgs = [] }) { - destination = path.resolve(destination); - const destinationExisted = fs.existsSync(destination); - if (destinationExisted && fs.readdirSync(destination).length) { - throw new Error(`destination is not empty: ${destination}`); - } - fs.mkdirSync(path.dirname(destination), { recursive: true }); - try { - run( - npxCommand, - npxArgs([ - '--yes', - '@react-native-community/cli@^20.2.0', - 'init', - appName, - '--version', - '0.87.1', - '--skip-install', - '--directory', - destination, - ...initArgs, - ]), - { shell: npxShell }, - ); - const packagePath = path.join(destination, 'package.json'); - const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8')); - fs.writeFileSync( - packagePath, - `${JSON.stringify(scaffoldDesktop(destination, packageJson), null, 2)}\n`, - ); - console.log( - `Created standard React Native project ${appName} (iOS, Android and desktop) in ${destination}. Run npm install, then npx react-native run-desktop.`, - ); - } catch (error) { - fs.rmSync(destination, { recursive: true, force: true }); - if (destinationExisted) fs.mkdirSync(destination, { recursive: true }); - throw error; - } -} - -export function createLibrary({ - libraryName, - type = 'rust', - destination, - moduleName: requestedModuleName, - packageName: requestedPackageName, -}) { - if ( - !libraryName || - !/^[A-Za-z][A-Za-z0-9_-]*$/u.test(libraryName) || - !['rust', 'cpp'].includes(type) - ) { - throw new Error( - 'create-library requires a valid name and rust or cpp type', - ); - } - destination = path.resolve(destination ?? libraryName); - if (fs.existsSync(destination) && fs.readdirSync(destination).length) { - throw new Error(`destination is not empty: ${destination}`); - } - const slug = libraryName - .replaceAll(/([a-z0-9])([A-Z])/gu, '$1-$2') - .toLowerCase() - .replaceAll(/[^a-z0-9-]/gu, '-'); - const snakeCase = value => - value - .replaceAll(/([a-z0-9])([A-Z])/gu, '$1_$2') - .replaceAll(/([A-Z]+)([A-Z][a-z])/gu, '$1_$2') - .toLowerCase(); - const words = libraryName.match(/[A-Z]?[a-z0-9]+|[A-Z]+/gu) ?? [libraryName]; - const moduleStem = words - .map(word => word[0].toUpperCase() + word.slice(1).toLowerCase()) - .join(''); - const moduleName = requestedModuleName ?? `RN${moduleStem}Module`; - if (!/^[A-Za-z][A-Za-z0-9]*$/u.test(moduleName)) { - throw new Error('--module-name must be a PascalCase identifier'); - } - const specName = `Native${moduleStem}`; - const cppProvider = `create_${slug.replaceAll('-', '_')}_module`; - const packageName = requestedPackageName ?? `react-native-${slug}`; - // Two names have to line up: `JSI.h` is the generated header, and - // the spec class is named after the spec file (`src/${specName}.ts`). The C++ - // template writes `RNModuleSpec` and `NativeModuleCxxSpec`, which the - // replacements below turn into exactly these two names. - const codegenName = `${moduleName}Spec`; - const templateRoot = path.join(templatesDir, `modules/${type}`); - fs.mkdirSync(destination, { recursive: true }); - const moduleFiles = - type === 'rust' - ? { - [`src/${specName}.ts`]: 'NativeModule.ts', - 'src/index.ts': 'index.ts', - 'desktop/build.rs': 'build.rs', - 'desktop/src/lib.rs': 'lib.rs', - } - : { - [`src/${specName}.ts`]: 'NativeModule.ts', - 'src/index.ts': 'index.ts', - [`desktop/cpp/${moduleName}.hpp`]: 'RNModule.hpp', - [`desktop/cpp/${moduleName}.cpp`]: 'RNModule.cpp', - 'desktop/CMakeLists.txt': 'CMakeLists.txt', - }; - for (const [target, source] of Object.entries(moduleFiles)) { - const targetPath = path.join(destination, target); - fs.mkdirSync(path.dirname(targetPath), { recursive: true }); - const contents = fs - .readFileSync(path.join(templateRoot, source), 'utf8') - .replaceAll('RNMODULESNAKE', snakeCase(moduleStem)) - .replaceAll('NativeModule', specName) - .replaceAll('RNMODULE', moduleName.toUpperCase()) - .replaceAll('RNModule', moduleName) - .replaceAll('create_rn_module', cppProvider); - fs.writeFileSync(targetPath, contents); - } - - const platformConfig = - type === 'rust' - ? { crate: `rn-gpui-${slug}` } - : { cmake: 'desktop', cppProvider }; - const packageJson = { - name: packageName, - version: '0.1.0', - main: 'src/index.ts', - files: ['src', 'desktop', 'react-native.config.js', 'README.md'], - codegenConfig: { - name: codegenName, - type: 'modules', - jsSrcsDir: 'src', - }, - peerDependencies: { 'react-native': '>=0.76' }, - }; - fs.writeFileSync( - path.join(destination, 'package.json'), - `${JSON.stringify(packageJson, null, 2)}\n`, - ); - fs.writeFileSync( - path.join(destination, 'react-native.config.js'), - [ - 'module.exports = {', - ' dependency: {', - ' platforms: {', - ' desktop: {', - ...Object.entries(platformConfig).map( - ([key, value]) => ` ${key}: ${JSON.stringify(value)},`, - ), - ' },', - ' },', - ' },', - '};', - '', - ].join('\n'), - ); - if (type === 'rust') { - // Version requirements, not paths: `[patch.crates-io]` cannot redirect a - // `path` dependency, and a module installed from npm has no - // `../../../packages` above it. Autolink patches these to the core the app - // actually installed. - fs.writeFileSync( - path.join(destination, 'desktop/Cargo.toml'), - `[package]\nname = ${JSON.stringify(`rn-gpui-${slug}`)}\nversion = "0.1.0"\nedition = "2021"\n\n[dependencies]\nrn-gpui-module = "0.1"\n\n[build-dependencies]\nrn-gpui-module-build = "0.1"\n`, - ); - } - const exampleRoot = path.join(destination, 'example'); - fs.mkdirSync(exampleRoot, { recursive: true }); - fs.writeFileSync( - path.join(exampleRoot, 'app.json'), - `${JSON.stringify({ name: `${moduleStem}Example`, displayName: `${moduleStem} Example` }, null, 2)}\n`, - ); - const examplePackage = scaffoldDesktop(exampleRoot, { - name: `${slug}-example`, - version: '0.0.1', - private: true, - dependencies: { - react: '19.2.3', - 'react-native': '0.87.1', - [packageName]: 'file:..', - }, - devDependencies: { - '@react-native-community/cli': '^20.2.0', - '@react-native/babel-preset': '0.87.1', - '@react-native/metro-config': '0.87.1', - vitest: '^3.2.4', - }, - }); - fs.writeFileSync( - path.join(exampleRoot, 'package.json'), - `${JSON.stringify(examplePackage, null, 2)}\n`, - ); - fs.writeFileSync( - path.join(exampleRoot, 'babel.config.cjs'), - "module.exports = {presets: ['module:@react-native/babel-preset']};\n", - ); - fs.writeFileSync( - path.join(exampleRoot, 'index.ts'), - "import {AppRegistry} from 'react-native';\nimport App from './App';\nimport {name} from './app.json';\nAppRegistry.registerComponent(name, () => App);\n", - ); - fs.writeFileSync( - path.join(exampleRoot, 'App.tsx'), - `import React from 'react';\nimport {Text, View} from 'react-native';\nimport Module from ${JSON.stringify(packageName)};\nexport default function App() {\n return {Module.greet('Desktop')};\n}\n`, - ); - fs.writeFileSync( - path.join(exampleRoot, 'desktop/e2e/library.e2e.ts'), - "import {launchApp, expect as desktopExpect} from '@react-native-gpui/testing';\ntest('calls the native library', async () => {\n const app = await launchApp({disableAnimations: true});\n await desktopExpect(app.getByTestId('library-result')).toContainText('Desktop');\n});\n", - ); - - const language = type === 'rust' ? 'Rust' : 'C++'; - const implementation = - type === 'rust' ? 'desktop/src/lib.rs' : `desktop/cpp/${moduleName}.cpp`; - const description = - type === 'rust' - ? 'call its typed greet(name) method.' - : 'implement methods defined by its generated spec.'; - fs.writeFileSync( - path.join(destination, 'README.md'), - `# ${libraryName}\n\n${language} TurboModule library for React Native on desktop. The spec is in src/${specName}.ts and uses React Native's public TurboModuleRegistry API. The implementation is in ${implementation} and is discovered through package metadata. Import the default export from ${packageName} and ${description}\n`, - ); - console.log( - `Created ${type} TurboModule library ${packageName} in ${destination}. Install/link it in a React Native app, then run npx react-native run-desktop.`, - ); -} - -/** - * The `_requireNodeLibrary(key, path)` calls the Babel plugin emits, as they - * appear in a bundle. Babel's output quotes both arguments with double quotes - * and escapes anything unusual, so this matches the compact and pretty forms - * alike. The key never contains a quote or a backslash (see the plugin's - * `addonKey`), which is what keeps the pattern simple. - */ -const requireNodeLibraryCallPattern = - /_requireNodeLibrary\(\s*"([^"\\]+)"\s*,\s*"((?:[^"\\]|\\.)+)"\s*\)/gu; - -/** - * The Node addon entries a bundle asks for: `{ key, path }`, in the order the - * calls appear, with the escapes Babel produced removed from the path. - * - * Exported for the unit test: scanning is the part worth testing without - * touching the filesystem. - */ -export function scanNodeAddonCalls(bundleText) { - const found = []; - const seen = new Set(); - for (const match of bundleText.matchAll(requireNodeLibraryCallPattern)) { - const key = match[1]; - // The path was emitted by `t.stringLiteral`, so it is escaped the way a JS - // string literal is. `JSON.parse` undoes exactly that. - let filePath; - try { - filePath = JSON.parse(`"${match[2]}"`); - } catch { - continue; - } - if (seen.has(key)) continue; - seen.add(key); - found.push({ key, path: filePath }); - } - return found; -} - -/** Sibling shared libraries a `$ORIGIN` / `@loader_path` lookup may need. */ -function isSiblingSharedLibrary(name, platform) { - if (platform === 'darwin') return name.endsWith('.dylib'); - if (platform === 'win32') return name.endsWith('.dll'); - // Linux: `libfoo.so` and its versioned forms `libfoo.so.1`, `libfoo.so.1.2`. - return /\.so(?:\.\d+)*$/u.test(name); -} - -/** - * `react-native-gpui collect-node-addons --bundle --out ` - * - * A development build loads an addon from the absolute path the Babel plugin - * embedded. A packaged app has no such path, so it copies each addon to - * `/` — which is what `_requireNodeLibrary` looks for relative to the - * executable — together with any sibling shared libraries, since some addons - * load those through `$ORIGIN` / `@loader_path`. - * - * Fails loudly when an embedded path no longer exists: a bundle built against a - * stale tree would otherwise ship without the addon and fail at run time. - */ -export function collectNodeAddons({ - bundle, - out, - platform = process.platform, -} = {}) { - if (!bundle) throw new Error('collect-node-addons requires --bundle '); - if (!out) throw new Error('collect-node-addons requires --out '); - const bundlePath = path.resolve(bundle); - const outDirectory = path.resolve(out); - const bundleText = fs.readFileSync(bundlePath, 'utf8'); - const addons = scanNodeAddonCalls(bundleText); - if (addons.length === 0) { - // A bundle with no addons removes a stale directory rather than leaving one - // from an earlier build behind. - fs.rmSync(outDirectory, { recursive: true, force: true }); - console.log(`No Node addons in ${bundlePath}; removed ${outDirectory}.`); - return { copied: [], out: outDirectory }; - } - - const missing = addons.filter(addon => !fs.existsSync(addon.path)); - if (missing.length > 0) { - throw new Error( - `collect-node-addons: the bundle names ${missing.length} addon file(s) ` + - 'that no longer exist. Rebuild the bundle before packaging:\n' + - missing.map(addon => ` ${addon.key} -> ${addon.path}`).join('\n'), - ); - } - - // Rebuilt from scratch so an addon that disappeared is not shipped. - fs.rmSync(outDirectory, { recursive: true, force: true }); - const copied = []; - for (const addon of addons) { - const target = path.join(outDirectory, addon.key); - if (!target.startsWith(outDirectory + path.sep)) { - throw new Error( - `collect-node-addons: key '${addon.key}' escapes ${outDirectory}`, - ); - } - fs.mkdirSync(path.dirname(target), { recursive: true }); - fs.copyFileSync(addon.path, target); - copied.push({ key: addon.key, path: addon.path, target }); - - // Sibling shared libraries of the same directory, copied once per - // directory so two addons in one folder do not copy them twice. - for (const sibling of fs.readdirSync(path.dirname(addon.path))) { - if (sibling === path.basename(addon.path)) continue; - if (!isSiblingSharedLibrary(sibling, platform)) continue; - const source = path.join(path.dirname(addon.path), sibling); - if (!fs.statSync(source).isFile()) continue; - const siblingKey = path.join(path.dirname(addon.key), sibling); - const siblingTarget = path.join(outDirectory, siblingKey); - if (!siblingTarget.startsWith(outDirectory + path.sep)) continue; - if (fs.existsSync(siblingTarget)) continue; - fs.mkdirSync(path.dirname(siblingTarget), { recursive: true }); - fs.copyFileSync(source, siblingTarget); - copied.push({ key: siblingKey, path: source, target: siblingTarget }); - } - } - - for (const entry of copied) { - console.log(` ${entry.key} <- ${entry.path}`); - } - console.log( - `Copied ${addons.length} Node addon(s) and ${copied.length - addons.length} sibling librar(ies) to ${outDirectory}.`, - ); - return { copied, out: outDirectory }; -} - -/** - * Signs the collected addons and the libraries beside them with the identity the - * CLI signs the app binary with, because the hardened runtime refuses to load an - * unsigned library. Nothing happens off macOS or without an identity: an - * unsigned release is still built, and an ad-hoc signed one needs no change. - */ -export function signCollectedNodeAddons({ - directory, - identity, - platform = process.platform, - exec = execFileSync, -}) { - if (platform !== 'darwin' || !identity || !fs.existsSync(directory)) { - return []; - } - const files = []; - const walk = current => { - for (const entry of fs.readdirSync(current, { withFileTypes: true })) { - const file = path.join(current, entry.name); - if (entry.isDirectory()) walk(file); - else if (/\.(node|dylib)$/u.test(entry.name)) files.push(file); - } - }; - walk(directory); - for (const file of files) { - exec('codesign', ['--force', '--sign', identity, file], { - stdio: 'inherit', - }); - } - return files; -} - -/** - * Strip the symbol table from the release binary, once its debug info is safe. - * - * Cargo's own `strip = "symbols"` runs inside the linker, before `dsymutil`, so - * it leaves an empty dSYM. Stripping here instead — after the dSYM is written and - * before the packager copies the binary — gets both: a 10 MB smaller binary and - * a debug file that can symbolize a crash. - */ -function stripReleaseBinary({ crateDir, binaryName }) { - const binary = path.join(targetProfileDir(crateDir, 'release'), binaryName); - if (!fs.existsSync(binary)) return; - try { - if (process.platform === 'win32') return; // The linker already omits it. - // `-x` removes every symbol that is not exported, which is the 10 MB the - // symbol table costs. `-S` only removes debug info and leaves the table. - execFileSync('strip', ['-x', binary], { stdio: 'inherit' }); - console.log(`stripped symbols from ${path.basename(binary)}`); - } catch { - console.log( - `could not strip ${path.basename(binary)}; the package will be larger`, - ); - } -} - -/** - * Runs the `bundleHook` of every autolinked package: a module that builds more - * of what the release ships, beside the app's bundle, for a library that needs - * its own script files (react-native-workers bundles each worker). A hook is - * called with `{ projectRoot, desktopRoot, bundleDir, entryFile, metroConfig, - * engine }` and returns the files or folders, as absolute paths, that go in the - * app's resource directory. Returns all of them. - */ -export async function runBundleHooks(context) { - const manifestPath = path.join( - context.desktopRoot, - 'autolink', - 'autolink.json', - ); - if (!fs.existsSync(manifestPath)) return []; - const { bundleHooks = [] } = JSON.parse( - fs.readFileSync(manifestPath, 'utf8'), - ); - const resources = []; - for (const hook of bundleHooks) { - const result = await createRequire(import.meta.url)(hook.module)(context); - for (const resource of result ?? []) { - resources.push(path.resolve(resource)); - } - } - return resources; -} - -/** - * Copy the bundle a release should ship to `desktop/build/package/index.bundle`. - * - * One name, one file, and the content is whatever the engine produced. A - * compiling engine ships its bytecode; a JavaScript-only engine ships JavaScript - * under the same name, with one line saying so. The name never varies, so the runtime - * has nothing to guess and `Resources/` holds exactly one bundle. - */ -export function stageBundle({ - projectRoot, - build, - engine = loadEngineBundle(projectRoot), - engineName = activeEngineName(projectRoot), -}) { - const packageDir = path.join(projectRoot, 'desktop', 'build', 'package'); - fs.mkdirSync(packageDir, { recursive: true }); - const staged = path.join(packageDir, 'index.bundle'); - const source = build?.runtimeBundlePath; - if (typeof source !== 'string' || !fs.existsSync(source)) { - throw new Error( - `the release bundle was not produced: expected ${source ?? '(no path)'}`, - ); - } - fs.copyFileSync(source, staged); - // What the packages' bundle hooks produced ships beside the bundle. - for (const resource of build?.extraResources ?? []) { - fs.cpSync(resource, path.join(packageDir, path.basename(resource)), { - recursive: true, - }); - } - - if (!engine || typeof engine.compile !== 'function') { - console.log( - 'packaging a JavaScript bundle: the active engine has no compiler', - ); - return staged; - } - - // The engine declares how its output is recognised; without a declaration the - // output of `compile()` is trusted. - const magic = engine.bytecodeMagic; - if (!Buffer.isBuffer(magic) || magic.length === 0) return staged; - - const head = Buffer.alloc(magic.length); - const fd = fs.openSync(staged, 'r'); - try { - fs.readSync(fd, head, 0, magic.length, 0); - } finally { - fs.closeSync(fd); - } - if (!head.equals(magic)) { - throw new Error( - `the ${engineName ?? 'JS'} engine did not produce bytecode: ${source} starts with ` + - `${JSON.stringify(head.toString('latin1'))}, not the engine's bytecode magic`, - ); - } - return staged; -} - -/// The `name` a desktop crate declares in its Cargo.toml. -function desktopCrateName(crateDir) { - const manifest = fs.readFileSync(path.join(crateDir, 'Cargo.toml'), 'utf8'); - const match = manifest.match(/^name\s*=\s*"([^"]+)"/mu); - if (!match) { - throw new Error(`no package name in ${path.join(crateDir, 'Cargo.toml')}`); - } - return match[1]; -} - -/** - * `package-desktop`: turn the app into installable packages for this OS. - * - * Always a release build. The steps are: load the config, produce the release - * bundle and binary the way `run-desktop --release` does, translate the config - * into cargo-packager's, and run it. cargo-packager is an implementation - * detail — nothing here writes its format by hand. - */ -export async function packageDesktop({ - projectRoot = process.cwd(), - targets, - outDir, -} = {}) { - projectRoot = path.resolve(projectRoot); - const config = loadDesktopConfig(projectRoot, process.platform); - // `--target` reaches the command as the string after the flag. - const requested = - targets === undefined || targets === true - ? config - : { - ...config, - bundle: { - ...config.bundle, - targets: String(targets) - .split(',') - .map(format => format.trim()) - .filter(Boolean), - }, - }; - const formats = targetsFor(requested, process.platform); - - // 1. The release bundle and binary. `packaging` makes build.rs emit only - // relative rpaths, so the result carries no path into this build tree. - const build = await runDesktop({ - projectRoot, - release: true, - noLaunch: true, - packaging: true, - }); - // What the release ships: one bundle, always named `index.bundle`, holding - // whatever the engine compiled the JavaScript into. - const shippedBundle = stageBundle({ projectRoot, build }); - const nodeAddonsDir = build.nodeAddonsDir; - - const crateDir = path.join(projectRoot, 'desktop'); - // The executable is the crate's name, which is what `scaffoldDesktop` writes - // into Cargo.toml and what `cargo build` produces. - const binaryName = desktopCrateName(crateDir); - const buildDir = path.join(crateDir, 'build'); - - // Cargo owns the packed debug output and its symlink in the profile directory. - // Replacing that symlink with a directory makes the next Cargo build fail. - // Keep its output intact and copy the symbols after packaging. - stripReleaseBinary({ crateDir, binaryName }); - - // 2. Icons, from the one PNG the config names. - const icons = generateIcons(config, { crateDir, projectRoot }); - - // 3. The libraries that have to travel with the app. - const libraries = runtimeLibraries(projectRoot, { - os: process.platform, - arch: process.arch, - release: true, - }); - // Named, because a library left out of the package is otherwise invisible until - // the installer or the AppImage step fails with a message that does not say - // which file it was looking for. - for (const library of libraries) { - console.log(`shipping library ${path.basename(library)}`); - } - - // 4. Translate, then run cargo-packager. - // The rpath `build.rs` emits names the app, not the crate: it is - // `RN_GPUI_APP_NAME`, which comes from `app.json`. The deb has to install its - // libraries into that same directory or the binary cannot find them. - const appJson = JSON.parse( - fs.readFileSync(path.join(projectRoot, 'app.json'), 'utf8'), - ); - const packagerConfig = toPackagerConfig(config, { - crateDir, - binaryName, - rpathDir: appJson.name, - os: desktopOs(process.platform), - bundleDir: path.dirname(shippedBundle), - assetsDir: path.join(buildDir, 'assets'), - extraResources: (build.extraResources ?? []).map(resource => - path.join(path.dirname(shippedBundle), path.basename(resource)), - ), - nodeAddonsDir, - icons, - libraries, - formats, - ...(outDir === undefined ? {} : { outDir: path.resolve(outDir) }), - }); - // The config is written at the crate root, not in `build/`: cargo-packager - // resolves every path in it — the binary, the resources, the frameworks — - // relative to the config file's own directory, so a config one level down - // would look for `build/build/index.bundle`. - const configPath = path.join(crateDir, 'packager.json'); - fs.mkdirSync(buildDir, { recursive: true }); - fs.writeFileSync(configPath, `${JSON.stringify(packagerConfig, null, 2)}\n`); - - ensureCargoPackager(); - await runPackager( - ['packager', '--config', 'packager.json', '--formats', formats.join(',')], - { cwd: crateDir }, - ); - - fs.rmSync(configPath, { force: true }); - const produced = listPackages(packagerConfig.outDir); - // After the packages, not before: cargo-packager writes `dist` itself and would - // remove anything already there. - copyDebugSymbols({ crateDir, binaryName, outDir: packagerConfig.outDir }); - for (const file of produced) console.log(file); - return produced; -} - -/** - * Failures of cargo-packager that a second try gets past: `hdiutil`, which it - * runs for a dmg, reports "Resource busy" while macOS still holds the volume it - * just wrote, and the installers it downloads (NSIS and its plugins, the - * AppImage tools) come from servers that answer 5xx or time out now and then. - */ -export function isTransientPackagerFailure(output) { - return ( - /hdiutil: create failed - Resource busy/u.test(output) || - /status code (5\d\d|429)\b/u.test(output) || - /(timed out|connection (reset|refused|closed|failed))/iu.test(output) - ); -} - -/** - * Runs cargo-packager and runs it again, up to `attempts` times with a growing - * pause, when it failed in a way `isTransientPackagerFailure` names. Its error - * stream is shown as it arrives. - */ -export async function runPackager( - args, - { cwd, attempts = 4, wait = defaultWait } = {}, -) { - for (let attempt = 1; ; attempt += 1) { - const { status, stderr } = await new Promise((resolve, reject) => { - const child = spawn('cargo', args, { - cwd, - stdio: ['inherit', 'inherit', 'pipe'], - }); - let text = ''; - child.stderr.on('data', chunk => { - process.stderr.write(chunk); - text += chunk.toString(); - }); - child.on('error', reject); - child.on('close', code => resolve({ status: code, stderr: text })); - }); - if (status === 0) return; - if (attempt < attempts && isTransientPackagerFailure(stderr)) { - console.log( - `cargo packager hit a passing failure; trying again in ${attempt * 5} s`, - ); - await wait(attempt * 5000); - continue; - } - throw new Error(`Command failed: cargo ${args.join(' ')}`); - } -} - -function defaultWait(ms) { - return new Promise(resolve => setTimeout(resolve, ms)); -} - -/** - * Installs cargo-packager when the pinned version is not the one on PATH. - * - * One line saying so: the install takes a few minutes and happens once. - */ -export function ensureCargoPackager() { - let installed; - try { - installed = execFileSync('cargo', ['packager', '--version'], { - encoding: 'utf8', - }).trim(); - } catch { - installed = ''; - } - if (installed.includes(CARGO_PACKAGER_VERSION)) return; - console.log( - `installing cargo-packager ${CARGO_PACKAGER_VERSION} (once, a few minutes)`, - ); - run( - 'cargo', - [ - 'install', - 'cargo-packager', - '--locked', - '--version', - CARGO_PACKAGER_VERSION, - ], - {}, - ); -} - -/// Whether `file` is a directory with no files anywhere below it. -function isEmptyDirectory(file) { - const stat = fs.statSync(file); - if (!stat.isDirectory()) return false; - const stack = [file]; - while (stack.length > 0) { - const directory = stack.pop(); - for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { - if (entry.isFile()) return false; - if (entry.isDirectory()) stack.push(path.join(directory, entry.name)); - } - } - return true; -} - -/** - * Put the release debug file beside the package, and not inside it. - * - * The binary is stripped of its symbol table, so a crash report is addresses and - * nothing else. The dSYM (or `.dwp`, or `.pdb`) is what turns those back into - * function names, and it must not ship: it is larger than the binary and useless - * to anyone who is not symbolizing. - */ -export function copyDebugSymbols({ crateDir, binaryName, outDir }) { - const profileDir = targetProfileDir(crateDir, 'release'); - // `split-debuginfo = "packed"` gives a dSYM on macOS, a `.dwp` on Linux and a - // `.pdb` on Windows. The unpacked `.debug` file is listed too because a - // toolchain that does not support packing falls back to it. - const candidates = [ - path.join(profileDir, `${binaryName}.dSYM`), - path.join(profileDir, `${binaryName}.dwp`), - path.join(profileDir, `${binaryName}.pdb`), - path.join(profileDir, `${binaryName}.debug`), - ]; - // A dSYM directory that exists but holds no DWARF is a leftover, not a result. - const found = candidates.filter( - file => fs.existsSync(file) && !isEmptyDirectory(file), - ); - if (found.length === 0) { - console.log( - 'no release debug file was produced; a crash report will not be symbolizable', - ); - return; - } - for (const file of found) { - const target = path.join(outDir, path.basename(file)); - fs.rmSync(target, { recursive: true, force: true }); - fs.cpSync(file, target, { recursive: true, dereference: true }); - // A read-only directory here would make the next run fail to replace it. - fs.chmodSync(target, 0o755); - console.log(`debug symbols: ${target}`); - } -} - -/** The packages a run produced, newest first. */ -function listPackages(outDir) { - let entries; - try { - entries = fs.readdirSync(outDir, { withFileTypes: true }); - } catch { - return []; - } - return entries - .filter(entry => entry.isFile()) - .map(entry => path.join(outDir, entry.name)) - .sort(); -} - -/** - * The icon a package builds from: the one `desktop.json` names, or the CLI's - * placeholder. - * - * cargo-packager derives a macOS `.icns` entry from an icon's pixel size times - * its density, and only a handful of those pairs are ICNS types. A 1024x1024 - * PNG at 1x is not one of them, so a single file fails with "No matching - * IconType" — which is what stopped the app bundle as well as the AppImage. - * Naming the copy `@2x` says what the file is: a 1024px asset for a 512pt slot, - * which is a valid type, and every other format is derived from it. - * - * The `@2x` convention is cargo-packager's own, and the copy is why no image - * library is needed: the CLI never rescales a user's icon, it labels it. - * - * There is always an icon: an app that never set `icon` gets the placeholder, - * because the AppImage step refuses to build without a square one. - */ -function generateIcons(config, { crateDir }) { - const source = - config.icon === undefined - ? defaultIconPath() - : path.resolve(crateDir, config.icon); - if (!fs.existsSync(source)) { - throw new Error( - `desktop.json names an icon that does not exist: ${source}`, - ); - } - - const iconDir = path.join(crateDir, 'build', 'icons'); - fs.mkdirSync(iconDir, { recursive: true }); - const target = path.join(iconDir, `icon@2x${path.extname(source)}`); - if (path.resolve(source) !== path.resolve(target)) { - fs.copyFileSync(source, target); - } - return [path.relative(crateDir, target).split(path.sep).join('/')]; -} - -/** The icon `desktop.json` names, or the CLI's placeholder. */ -function appIconPath(projectRoot) { - const { icon } = loadDesktopConfig(projectRoot, process.platform); - const source = - icon === undefined - ? defaultIconPath() - : path.resolve(projectRoot, 'desktop', icon); - return fs.existsSync(source) ? source : defaultIconPath(); -} - -/// The square PNG bundled with the CLI, used when an app sets no icon. -function defaultIconPath() { - return path.join(cliDir, '..', 'assets', 'default-icon.png'); -} diff --git a/vendor/react-native-gpui/packages/cli/src/commands.test.js b/vendor/react-native-gpui/packages/cli/src/commands.test.js deleted file mode 100644 index 48e97df422..0000000000 --- a/vendor/react-native-gpui/packages/cli/src/commands.test.js +++ /dev/null @@ -1,861 +0,0 @@ -import { Buffer } from 'node:buffer'; -import fs from 'node:fs'; -import http from 'node:http'; -import os from 'node:os'; -import nodePath from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { afterAll, expect, test } from 'vitest'; -import { - runBundleHooks, - assertReleaseExists, - collectNodeAddons, - copyDebugSymbols, - gpuiVersionRange, - reactNativeMinor, - createLibrary, - desktopLaunchConfig, - isTransientPackagerFailure, - linuxBuildDependencyProblem, - metroProjectRoot, - metroTerminal, - runPackager, - scanNodeAddonCalls, - scaffoldDesktop, - signCollectedNodeAddons, - stageBundle, -} from './commands.js'; - -// The repository root by lookup, not by counting parents: this file sits at a -// different depth before and after a folder move. -const repoRoot = (() => { - let dir = nodePath.dirname(fileURLToPath(import.meta.url)); - for (;;) { - const manifest = nodePath.join(dir, 'package.json'); - if (fs.existsSync(manifest)) { - try { - if (JSON.parse(fs.readFileSync(manifest, 'utf8')).workspaces) - return dir; - } catch {} - } - const parent = nodePath.dirname(dir); - if (parent === dir) throw new Error('no workspace root above the test'); - dir = parent; - } -})(); -const temporaryRoots = []; - -afterAll(() => { - for (const root of temporaryRoots) { - fs.rmSync(root, { recursive: true, force: true }); - } -}); - -test('the Linux preflight accepts a complete system', () => { - expect(linuxBuildDependencyProblem('linux', () => true)).toBeNull(); -}); - -test('the Linux preflight names the missing module and its package', () => { - const problem = linuxBuildDependencyProblem('linux', pc => pc !== 'xcb'); - expect(problem).toContain('dependency xcb was not found'); - expect(problem).toContain('libxcb1-dev'); - expect(problem).toContain('PKG_CONFIG_PATH'); -}); - -test('the Linux preflight gives one package name per distribution', () => { - const problem = linuxBuildDependencyProblem( - 'linux', - pc => pc !== 'xkbcommon', - ); - expect(problem).toContain('Debian/Ubuntu: sudo apt install libxkbcommon-dev'); - expect(problem).toContain('Fedora: sudo dnf install libxkbcommon-devel'); - expect(problem).toContain('Arch: sudo pacman -S libxkbcommon'); -}); - -test('the Linux preflight prints the computed system pkg-config path', () => { - const path = '/usr/lib/x86_64-linux-gnu/pkgconfig:/usr/share/pkgconfig'; - const problem = linuxBuildDependencyProblem( - 'linux', - () => false, - () => path, - ); - expect(problem).toContain(`PKG_CONFIG_PATH=${path}`); -}); - -test('the Linux preflight falls back when the system path is unknown', () => { - const problem = linuxBuildDependencyProblem( - 'linux', - () => false, - () => null, - ); - expect(problem).not.toContain('PKG_CONFIG_PATH='); - expect(problem).toContain('point PKG_CONFIG_PATH at your system pkgconfig'); -}); - -test('the Linux preflight reports a missing pkg-config', () => { - expect( - linuxBuildDependencyProblem('linux', () => 'missing-pkg-config'), - ).toContain('pkg-config is required'); -}); - -test('the Linux preflight is a no-op on other platforms', () => { - expect(linuxBuildDependencyProblem('darwin', () => false)).toBeNull(); - expect(linuxBuildDependencyProblem('win32', () => false)).toBeNull(); -}); - -// --- collect-node-addons ----------------------------------------------------- - -test('the scanner reads every key/path pair a bundle emits', () => { - const bundle = [ - 'var a = _requireNodeLibrary("node_modules/pkg/prebuilds/x.node", "/app/node_modules/pkg/prebuilds/x.node");', - 'var b = _requireNodeLibrary(\n "local/deadbeef/y.node",\n "/app/build/Release/y.node"\n);', - ].join('\n'); - expect(scanNodeAddonCalls(bundle)).toEqual([ - { - key: 'node_modules/pkg/prebuilds/x.node', - path: '/app/node_modules/pkg/prebuilds/x.node', - }, - { key: 'local/deadbeef/y.node', path: '/app/build/Release/y.node' }, - ]); -}); - -test('the scanner reports one entry per key', () => { - const bundle = - '_requireNodeLibrary("a/x.node","/p/x.node");_requireNodeLibrary("a/x.node","/p/x.node");'; - expect(scanNodeAddonCalls(bundle)).toHaveLength(1); -}); - -test('the scanner ignores a call with only a key', () => { - expect(scanNodeAddonCalls('_requireNodeLibrary("a/x.node")')).toEqual([]); -}); - -test('the scanner unescapes the path Babel emitted', () => { - const bundle = String.raw`_requireNodeLibrary("local/1/a.node","C:\\app\\a.node");`; - expect(scanNodeAddonCalls(bundle)[0].path).toBe('C:\\app\\a.node'); -}); - -test('collect-node-addons copies each addon to /', () => { - const root = fs.mkdtempSync(nodePath.join(repoRoot, '.local/collect-')); - temporaryRoots.push(root); - const addonPath = nodePath.join(root, 'build/Release/addon.node'); - fs.mkdirSync(nodePath.dirname(addonPath), { recursive: true }); - fs.writeFileSync(addonPath, 'binary'); - const bundlePath = nodePath.join(root, 'bundle.js'); - // The Babel plugin emits the path through `t.stringLiteral`, so it is escaped - // as a JS string literal would be — backslashes and all on Windows. - fs.writeFileSync( - bundlePath, - `_requireNodeLibrary("local/1/addon.node",${JSON.stringify(addonPath)});`, - ); - const out = nodePath.join(root, 'node-addons'); - const result = collectNodeAddons({ bundle: bundlePath, out }); - expect(result.copied).toHaveLength(1); - expect( - fs.readFileSync(nodePath.join(out, 'local/1/addon.node'), 'utf8'), - ).toBe('binary'); -}); - -test('collect-node-addons copies sibling shared libraries', () => { - const root = fs.mkdtempSync(nodePath.join(repoRoot, '.local/collect-')); - temporaryRoots.push(root); - const directory = nodePath.join(root, 'build/Release'); - fs.mkdirSync(directory, { recursive: true }); - fs.writeFileSync(nodePath.join(directory, 'addon.node'), 'binary'); - fs.writeFileSync(nodePath.join(directory, 'libdep.so'), 'shared'); - fs.writeFileSync(nodePath.join(directory, 'libdep.so.1'), 'shared'); - fs.writeFileSync(nodePath.join(directory, 'unrelated.txt'), 'no'); - const bundlePath = nodePath.join(root, 'bundle.js'); - fs.writeFileSync( - bundlePath, - `_requireNodeLibrary("local/1/addon.node",${JSON.stringify(nodePath.join(directory, 'addon.node'))});`, - ); - const out = nodePath.join(root, 'node-addons'); - collectNodeAddons({ bundle: bundlePath, out, platform: 'linux' }); - expect(fs.existsSync(nodePath.join(out, 'local/1/libdep.so'))).toBe(true); - expect(fs.existsSync(nodePath.join(out, 'local/1/libdep.so.1'))).toBe(true); - expect(fs.existsSync(nodePath.join(out, 'local/1/unrelated.txt'))).toBe( - false, - ); -}); - -test('collect-node-addons fails when an embedded path is gone', () => { - const root = fs.mkdtempSync(nodePath.join(repoRoot, '.local/collect-')); - temporaryRoots.push(root); - const bundlePath = nodePath.join(root, 'bundle.js'); - fs.writeFileSync( - bundlePath, - '_requireNodeLibrary("local/1/gone.node","/nowhere/gone.node");', - ); - expect(() => - collectNodeAddons({ bundle: bundlePath, out: nodePath.join(root, 'out') }), - ).toThrow(/no longer exist/u); -}); - -test('collect-node-addons clears a stale directory when the bundle has none', () => { - const root = fs.mkdtempSync(nodePath.join(repoRoot, '.local/collect-')); - temporaryRoots.push(root); - const bundlePath = nodePath.join(root, 'bundle.js'); - fs.writeFileSync(bundlePath, 'var x = 1;'); - const out = nodePath.join(root, 'node-addons'); - fs.mkdirSync(out, { recursive: true }); - fs.writeFileSync(nodePath.join(out, 'stale'), 'x'); - const result = collectNodeAddons({ bundle: bundlePath, out }); - expect(result.copied).toEqual([]); - expect(fs.existsSync(out)).toBe(false); -}); - -test('collect-node-addons requires both arguments', () => { - expect(() => collectNodeAddons({})).toThrow(/--bundle/u); - expect(() => collectNodeAddons({ bundle: 'x' })).toThrow(/--out/u); -}); - -// The launch chain used to be built from `app.json`'s `desktop` key. It reads -// `desktop/desktop.json` now, and these check that the generated `main.rs` is -// the same for the same options. -test('urlSchemes reach the launch chain and turn single instance on', () => { - const chain = desktopLaunchConfig( - { devMenu: true, urlSchemes: ['myapp', 'my-app'], singleInstance: true }, - 'desktop/desktop.json', - ); - expect(chain).toContain('.url_schemes(&["myapp", "my-app"])'); - expect(chain).toContain('.single_instance(true)'); - const none = desktopLaunchConfig( - { devMenu: true, urlSchemes: [], singleInstance: false }, - 'desktop/desktop.json', - ); - expect(none).not.toContain('.url_schemes('); -}); - -test('menuBar: false asks the host for no menu bar, and its absence does not', () => { - const hidden = desktopLaunchConfig( - { window: { menuBar: false }, devMenu: true }, - 'desktop/desktop.json', - ); - expect(hidden).toContain('.menu_bar(false)'); - - // The default is a menu bar, so the call is only emitted when it is turned off: - // a chain that always emitted it would be the same thing, but the generated file - // reads better without a line saying what the default already is. - const shown = desktopLaunchConfig( - { window: { menuBar: true }, devMenu: true }, - 'desktop/desktop.json', - ); - expect(shown).not.toContain('.menu_bar('); -}); - -test('windowControlsPosition: left reaches the launch chain, and right does not', () => { - const left = desktopLaunchConfig( - { window: { windowControlsPosition: 'left' }, devMenu: true }, - 'desktop/desktop.json', - ); - expect(left).toContain('.window_controls_position("left")'); - const right = desktopLaunchConfig( - { window: { windowControlsPosition: 'right' }, devMenu: true }, - 'desktop/desktop.json', - ); - expect(right).not.toContain('.window_controls_position('); -}); - -test('a custom title bar and the traffic light position reach the launch chain', () => { - const hidden = desktopLaunchConfig( - { - window: { - titleBar: 'hidden', - trafficLightPosition: { x: 14, y: 10 }, - }, - devMenu: true, - }, - 'desktop/desktop.json', - ); - expect(hidden).toContain( - '.title_bar(react_native_gpui::WindowTitleBar::Hidden)', - ); - expect(hidden).toContain('.traffic_light_position(14.0, 10.0)'); - - const transparent = desktopLaunchConfig( - { window: { titleBar: 'transparent' }, devMenu: true }, - 'desktop/desktop.json', - ); - expect(transparent).toContain( - '.title_bar(react_native_gpui::WindowTitleBar::Transparent)', - ); - - // `default` is what an app that says nothing already gets, so it must not add - // a call that only restates it. - const plain = desktopLaunchConfig( - { window: { titleBar: 'default' }, devMenu: true }, - 'desktop/desktop.json', - ); - expect(plain).not.toContain('.title_bar('); - expect(plain).not.toContain('.traffic_light_position('); -}); - -test('a window background reaches the launch chain, and opaque adds nothing', () => { - const blurred = desktopLaunchConfig( - { window: { background: 'blurred' }, devMenu: true }, - 'desktop/desktop.json', - ); - expect(blurred).toContain( - '.background(react_native_gpui::WindowBackground::Blurred)', - ); - const opaque = desktopLaunchConfig( - { window: { background: 'opaque' }, devMenu: true }, - 'desktop/desktop.json', - ); - expect(opaque).not.toContain('.background('); - expect(() => - desktopLaunchConfig( - { window: { background: 'glass' }, devMenu: true }, - 'desktop/desktop.json', - ), - ).toThrow(/window.background must be/u); -}); - -test('an accessory app reaches the launch chain, and a regular one adds nothing', () => { - expect( - desktopLaunchConfig( - { accessory: true, devMenu: true }, - 'desktop/desktop.json', - ), - ).toContain('.accessory(true)'); - expect( - desktopLaunchConfig({ devMenu: true }, 'desktop/desktop.json'), - ).not.toContain('.accessory('); -}); - -test('hiding the window buttons and the shadow reaches the launch chain', () => { - const bare = desktopLaunchConfig( - { window: { windowButtons: false, shadow: false }, devMenu: true }, - 'desktop/desktop.json', - ); - expect(bare).toContain('.window_buttons(false)'); - expect(bare).toContain('.shadow(false)'); - const plain = desktopLaunchConfig( - { window: { windowButtons: true, shadow: true }, devMenu: true }, - 'desktop/desktop.json', - ); - expect(plain).not.toContain('.window_buttons('); - expect(plain).not.toContain('.shadow('); -}); - -test('a traffic light position without both coordinates is rejected', () => { - // The schema says `x` and `y` are both required; a launcher that silently used - // the origin would move the traffic lights to the corner of the window. - expect(() => - desktopLaunchConfig( - { window: { trafficLightPosition: { x: 14 } }, devMenu: true }, - 'desktop/desktop.json', - ), - ).toThrow(/trafficLightPosition needs x and y/u); -}); - -test('the launch chain reflects the window, dev menu and tray', () => { - const main = desktopLaunchConfig( - { - window: { width: 900, height: 700, title: 'My App', resizable: true }, - devMenu: true, - tray: { component: 'TrayRoot', tooltip: 'Open', accessory: true }, - }, - 'desktop/desktop.json', - ); - expect(main).toContain('.window_title("My App")'); - expect(main).toContain('.window_size(900.0, 700.0)'); - expect(main).toContain('.dev_menu(true)'); - expect(main).toContain( - '.tray(TrayConfig::default().component("TrayRoot").tooltip("Open"))', - ); - expect(main).toContain('options.is_resizable = true;'); -}); - -test('an app asking to restore nothing and be fixed-size says so', () => { - const main = desktopLaunchConfig( - { - window: { - width: 400, - height: 300, - resizable: false, - restoreState: false, - position: { x: 10, y: 20 }, - }, - devMenu: false, - }, - 'desktop/desktop.json', - ); - expect(main).toContain('.restore_window_state(false)'); - expect(main).toContain('.window_position(10.0, 20.0)'); - expect(main).toContain('.dev_menu(false)'); - expect(main).toContain('options.is_resizable = false;'); - expect(main).not.toContain('.tray('); -}); - -test('a tray with accessory false disables the accessory mode', () => { - const main = desktopLaunchConfig( - { - window: { width: 1, height: 1 }, - devMenu: true, - tray: { accessory: false }, - }, - 'desktop/desktop.json', - ); - expect(main).toContain('.tray(TrayConfig::default().accessory(false))'); -}); - -test('create-library writes version requirements, not crate paths', () => { - // A module crate installed from npm has no `../../../packages` above it, so a - // relative path to core cannot work there; `[patch.crates-io]` also cannot - // redirect a `path` dependency. The scaffolder therefore writes a version - // requirement and lets autolink patch it to the installed core. - const outer = fs.mkdtempSync(nodePath.join(repoRoot, '.local', 'scaffold-')); - try { - createLibrary({ - libraryName: 'example', - type: 'rust', - destination: outer, - packageName: '@react-native-gpui/example', - }); - const manifest = fs.readFileSync( - nodePath.join(outer, 'desktop/Cargo.toml'), - 'utf8', - ); - expect(manifest).toContain('rn-gpui-module = "0.1"'); - expect(manifest).toContain('rn-gpui-module-build = "0.1"'); - expect(manifest).not.toMatch(/path\s*=/u); - expect(manifest).not.toMatch(/git\s*=/u); - } finally { - fs.rmSync(outer, { recursive: true, force: true }); - } -}); - -test('scaffoldDesktop writes the env file that exposes the desktop types', () => { - // The augmentation is global, and a TypeScript augmentation only applies when - // its declaring file is compiled. This reference is what puts it in the app's - // compilation, so `desktopDragRegion` and `onContextMenu` type-check without an - // import of the desktop entry point. - const root = fs.mkdtempSync(nodePath.join(repoRoot, '.local', 'envtypes-')); - try { - fs.writeFileSync( - nodePath.join(root, 'package.json'), - `${JSON.stringify({ name: 'envapp', dependencies: { 'react-native': '0.87.1' } })}\n`, - ); - fs.writeFileSync( - nodePath.join(root, 'app.json'), - `${JSON.stringify({ name: 'EnvApp', displayName: 'EnvApp' })}\n`, - ); - scaffoldDesktop( - root, - JSON.parse(fs.readFileSync(nodePath.join(root, 'package.json'), 'utf8')), - ); - - const envPath = nodePath.join(root, 'react-native-gpui-env.d.ts'); - const written = fs.readFileSync(envPath, 'utf8'); - expect(written).toContain( - '/// ', - ); - expect(written).toContain('Do not edit'); - } finally { - fs.rmSync(root, { recursive: true, force: true }); - } -}); - -test('scaffoldDesktop keeps an app’s edited env file', () => { - // `preserveExisting` is how `init-desktop` runs on an app that already has a - // desktop folder, so an app that added its own references there must keep them. - const root = fs.mkdtempSync(nodePath.join(repoRoot, '.local', 'envkeep-')); - try { - fs.writeFileSync( - nodePath.join(root, 'package.json'), - `${JSON.stringify({ name: 'keepapp', dependencies: { 'react-native': '0.87.1' } })}\n`, - ); - fs.writeFileSync( - nodePath.join(root, 'app.json'), - `${JSON.stringify({ name: 'KeepApp', displayName: 'KeepApp' })}\n`, - ); - const envPath = nodePath.join(root, 'react-native-gpui-env.d.ts'); - const edited = '/// \n'; - fs.writeFileSync(envPath, edited); - - scaffoldDesktop( - root, - JSON.parse(fs.readFileSync(nodePath.join(root, 'package.json'), 'utf8')), - { preserveExisting: true }, - ); - expect(fs.readFileSync(envPath, 'utf8')).toBe(edited); - } finally { - fs.rmSync(root, { recursive: true, force: true }); - } -}); - -test('Metro opens in the requested terminal, then the platform default', () => { - const none = () => false; - expect(metroTerminal('Warp', { platform: 'darwin', env: {} })).toBe('Warp'); - expect( - metroTerminal(undefined, { - platform: 'darwin', - env: { REACT_TERMINAL: 'Ghostty' }, - }), - ).toBe('Ghostty'); - expect( - metroTerminal(undefined, { - platform: 'darwin', - env: { TERM_PROGRAM: 'vscode' }, - }), - ).toBe('Terminal'); - expect( - metroTerminal(undefined, { - platform: 'darwin', - env: { TERM_PROGRAM: 'iTerm.app' }, - }), - ).toBe('iTerm'); - expect(metroTerminal(undefined, { platform: 'win32', env: {} })).toBe( - 'cmd.exe', - ); - expect( - metroTerminal(undefined, { - platform: 'linux', - env: {}, - exists: command => command === 'konsole', - }), - ).toBe('konsole'); - expect( - metroTerminal(undefined, { platform: 'linux', env: {}, exists: none }), - ).toBeUndefined(); -}); - -test('a running Metro reports the project it serves', async () => { - const server = http.createServer((request, response) => { - response.setHeader('X-React-Native-Project-Root', '/some/project'); - response.end( - request.url === '/status' ? 'packager-status:running' : 'not found', - ); - }); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const { port } = server.address(); - try { - expect(await metroProjectRoot('127.0.0.1', port)).toBe('/some/project'); - } finally { - await new Promise(resolve => server.close(resolve)); - } - expect(await metroProjectRoot('127.0.0.1', port)).toBeUndefined(); -}); - -test('a tray icon in desktop.json is embedded in the launch chain', () => { - const chain = desktopLaunchConfig( - { - tray: { tooltip: 'Tray', icon: 'assets/tray.png', iconTemplate: true }, - devMenu: true, - }, - 'desktop/desktop.json', - ); - expect(chain).toContain( - '.icon_bytes(include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/assets/tray.png")))', - ); - expect(chain).toContain('.icon_template(true)'); - expect( - desktopLaunchConfig({ tray: { tooltip: 'Tray' }, devMenu: true }, 'x'), - ).not.toContain('.icon_bytes('); -}); - -function stageFixture(content) { - const projectRoot = fs.mkdtempSync( - nodePath.join(os.tmpdir(), 'stage-bundle-'), - ); - temporaryRoots.push(projectRoot); - const runtimeBundlePath = nodePath.join(projectRoot, 'compiled.bundle'); - fs.writeFileSync(runtimeBundlePath, content); - return { projectRoot, build: { runtimeBundlePath } }; -} - -test('stageBundle accepts the bytecode magic the engine declares', () => { - const magic = Buffer.from([0x01, 0x02, 0x03, 0x04]); - const staged = stageBundle({ - ...stageFixture(Buffer.concat([magic, Buffer.from('rest')])), - engine: { compile() {}, bytecodeMagic: magic }, - engineName: 'other', - }); - expect(fs.existsSync(staged)).toBe(true); -}); - -test('stageBundle names the engine when its output lacks the declared magic', () => { - expect(() => - stageBundle({ - ...stageFixture('console.log(1)'), - engine: { compile() {}, bytecodeMagic: Buffer.from([1, 2, 3, 4]) }, - engineName: 'other', - }), - ).toThrow(/the other engine did not produce bytecode/u); -}); - -test('stageBundle trusts an engine that compiles but declares no magic', () => { - const staged = stageBundle({ - ...stageFixture('opaque'), - engine: { compile() {} }, - engineName: 'other', - }); - expect(fs.readFileSync(staged, 'utf8')).toBe('opaque'); -}); - -test('stageBundle ships JavaScript for an engine without a compiler', () => { - const staged = stageBundle({ - ...stageFixture('console.log(1)'), - engine: {}, - engineName: 'plain', - }); - expect(fs.readFileSync(staged, 'utf8')).toBe('console.log(1)'); -}); - -test('the React Native minor comes from an exact version or a range', () => { - expect(reactNativeMinor('0.87.1')).toBe(87); - expect(reactNativeMinor('^0.88.0')).toBe(88); - expect(reactNativeMinor('~0.87.2')).toBe(87); - expect(reactNativeMinor('latest')).toBeUndefined(); - expect(reactNativeMinor(undefined)).toBeUndefined(); -}); - -test("our packages are asked for at the app's React Native minor", () => { - expect( - gpuiVersionRange('/nowhere', { - dependencies: { 'react-native': '0.87.1' }, - }), - ).toBe('~0.87.0-alpha.0'); - expect(() => gpuiVersionRange('/nowhere', { dependencies: {} })).toThrow( - /Cannot tell which React Native version/, - ); -}); - -test('scaffolding writes the matching range for every package it adds', () => { - const root = fs.mkdtempSync(nodePath.join(os.tmpdir(), 'rn-gpui-scaffold-')); - try { - fs.writeFileSync(nodePath.join(root, 'app.json'), '{"name":"App"}'); - const result = scaffoldDesktop(root, { - name: 'app', - dependencies: { 'react-native': '0.87.1' }, - }); - expect(result.dependencies['@react-native-gpui/core']).toBe( - '~0.87.0-alpha.0', - ); - expect(result.dependencies['@react-native-gpui/hermes']).toBe( - '~0.87.0-alpha.0', - ); - expect(result.devDependencies['@react-native-gpui/cli']).toBe( - '~0.87.0-alpha.0', - ); - expect(result.scripts.desktop).toBe('react-native run-desktop'); - } finally { - fs.rmSync(root, { recursive: true, force: true }); - } -}); - -test('scaffolding adds the desktop module of a library the app uses', () => { - const root = fs.mkdtempSync(nodePath.join(os.tmpdir(), 'rn-gpui-scaffold-')); - try { - fs.writeFileSync(nodePath.join(root, 'app.json'), '{"name":"App"}'); - const result = scaffoldDesktop(root, { - name: 'app', - dependencies: { - 'react-native': '0.87.1', - 'react-native-safe-area-context': '^5.5.2', - }, - }); - expect(result.dependencies['react-native-safe-area-context']).toBe( - '~5.10.0', - ); - expect(result.dependencies['@react-native-gpui/safe-area-context']).toBe( - '~5.10.0-alpha.0', - ); - } finally { - fs.rmSync(root, { recursive: true, force: true }); - } -}); - -test('a React Native minor without a release is refused with a clear message', () => { - const view = result => () => result; - expect(() => - assertReleaseExists('~0.88.0-alpha.0', { - registryView: view({ status: 0, stdout: '' }), - }), - ).toThrow(/supports React Native 0\.88/); - expect(() => - assertReleaseExists('~0.87.0-alpha.0', { - registryView: view({ status: 0, stdout: '"0.87.0-alpha.0"' }), - }), - ).not.toThrow(); - expect(() => - assertReleaseExists('~0.87.0-alpha.0', { - registryView: view({ status: 1, stderr: 'npm error code E404' }), - }), - ).toThrow(/not published/); - expect(() => - assertReleaseExists('~0.87.0-alpha.0', { - registryView: view({ status: 1, stderr: 'ENOTFOUND' }), - }), - ).not.toThrow(); -}); - -test('the tray popover position reaches the launch chain', () => { - const placed = desktopLaunchConfig( - { - tray: { - component: 'Panel', - popoverAnchor: 'top-left', - popoverOffset: { x: 4, y: -2 }, - }, - devMenu: true, - }, - 'desktop/desktop.json', - ); - expect(placed).toContain('.popover_anchor_name("top-left")'); - expect(placed).toContain('.popover_offset(4.0, -2.0)'); - - // 'auto' is the default, so no call is emitted for it. - const auto = desktopLaunchConfig( - { tray: { component: 'Panel', popoverAnchor: 'auto' }, devMenu: true }, - 'desktop/desktop.json', - ); - expect(auto).not.toContain('popover_anchor_name'); -}); - -test('a busy disk image and a failed download are told from a real failure', () => { - expect( - isTransientPackagerFailure( - 'stderr: hdiutil: create failed - Resource busy', - ), - ).toBe(true); - expect( - isTransientPackagerFailure( - 'ERROR https://github.com/x/NSIS.zip: status code 504', - ), - ).toBe(true); - expect(isTransientPackagerFailure('error: connection timed out')).toBe(true); - expect( - isTransientPackagerFailure('ERROR https://x/y.zip: status code 404'), - ).toBe(false); - expect(isTransientPackagerFailure('error[E0425]: cannot find value')).toBe( - false, - ); -}); - -test.skipIf(process.platform === 'win32')( - 'cargo-packager is run again when it fails in a passing way', - async () => { - const dir = fs.mkdtempSync(nodePath.join(os.tmpdir(), 'packager-')); - const counter = nodePath.join(dir, 'runs'); - const cargo = nodePath.join(dir, 'cargo'); - fs.writeFileSync( - cargo, - `#!/bin/sh\necho x >> "${counter}"\nif [ "$(wc -l < "${counter}")" -lt 3 ]; then echo 'ERROR https://x/NSIS.zip: status code 504' >&2; exit 1; fi\n`, - { mode: 0o755 }, - ); - const path = process.env.PATH; - process.env.PATH = `${dir}${nodePath.delimiter}${path}`; - const waits = []; - try { - await runPackager(['packager'], { - cwd: dir, - wait: ms => waits.push(ms), - }); - expect(waits).toEqual([5000, 10000]); - expect(fs.readFileSync(counter, 'utf8').trim().split('\n')).toHaveLength( - 3, - ); - fs.rmSync(counter); - await expect( - runPackager(['packager'], { cwd: dir, attempts: 2, wait: () => {} }), - ).rejects.toThrow(/Command failed/u); - } finally { - process.env.PATH = path; - fs.rmSync(dir, { recursive: true, force: true }); - } - }, -); - -test('runs the bundle hook of each autolinked package and collects what it ships', async () => { - const root = fs.mkdtempSync(nodePath.join(os.tmpdir(), 'bundle-hook-')); - try { - const hook = nodePath.join(root, 'hook.cjs'); - fs.writeFileSync( - hook, - "module.exports = async context => [require('node:path').join(context.bundleDir, 'workers')];\n", - ); - fs.mkdirSync(nodePath.join(root, 'desktop', 'autolink'), { - recursive: true, - }); - fs.writeFileSync( - nodePath.join(root, 'desktop', 'autolink', 'autolink.json'), - JSON.stringify({ bundleHooks: [{ dependencyName: 'x', module: hook }] }), - ); - const resources = await runBundleHooks({ - projectRoot: root, - desktopRoot: nodePath.join(root, 'desktop'), - bundleDir: nodePath.join(root, 'desktop', 'build'), - }); - expect(resources).toEqual([ - nodePath.join(root, 'desktop', 'build', 'workers'), - ]); - expect( - await runBundleHooks({ - projectRoot: root, - desktopRoot: nodePath.join(root, 'nothing'), - bundleDir: root, - }), - ).toEqual([]); - } finally { - fs.rmSync(root, { recursive: true, force: true }); - } -}); - -test('collected addons and their libraries are signed with the given identity on macOS only', () => { - const root = fs.mkdtempSync(nodePath.join(os.tmpdir(), 'rn-gpui-sign-')); - temporaryRoots.push(root); - const lib = nodePath.join(root, 'node_modules', 'pkg', 'lib'); - fs.mkdirSync(lib, { recursive: true }); - fs.writeFileSync(nodePath.join(lib, 'a.node'), ''); - fs.writeFileSync(nodePath.join(lib, 'libb.dylib'), ''); - fs.writeFileSync(nodePath.join(lib, 'readme.txt'), ''); - const calls = []; - const exec = (command, args) => calls.push([command, ...args]); - signCollectedNodeAddons({ - directory: root, - identity: 'ID', - platform: 'darwin', - exec, - }); - expect(calls.map(call => call.slice(0, 4))).toEqual([ - ['codesign', '--force', '--sign', 'ID'], - ['codesign', '--force', '--sign', 'ID'], - ]); - expect(calls.map(call => nodePath.basename(call[4])).sort()).toEqual([ - 'a.node', - 'libb.dylib', - ]); - calls.length = 0; - signCollectedNodeAddons({ directory: root, platform: 'darwin', exec }); - signCollectedNodeAddons({ - directory: root, - identity: 'ID', - platform: 'linux', - exec, - }); - expect(calls).toEqual([]); -}); - -test('packaging copies Cargo dSYM contents without retaining its build-tree symlink', () => { - fs.mkdirSync(nodePath.join(repoRoot, '.artifacts'), { recursive: true }); - const root = fs.mkdtempSync(nodePath.join(repoRoot, '.artifacts/gpui-dsym-')); - temporaryRoots.push(root); - const crateDir = nodePath.join(root, 'desktop'); - const release = nodePath.join(crateDir, 'target/release'); - const symbols = nodePath.join(release, 'deps/app-hash.dSYM'); - const dwarf = 'Contents/Resources/DWARF/app'; - fs.mkdirSync(nodePath.dirname(nodePath.join(symbols, dwarf)), { recursive: true }); - fs.writeFileSync(nodePath.join(symbols, dwarf), 'debug symbols'); - const cargoLink = nodePath.join(release, 'app.dSYM'); - fs.symlinkSync('deps/app-hash.dSYM', cargoLink); - const outDir = nodePath.join(root, 'dist'); - fs.mkdirSync(outDir); - - copyDebugSymbols({ crateDir, binaryName: 'app', outDir }); - - expect(fs.lstatSync(cargoLink).isSymbolicLink()).toBe(true); - expect(fs.lstatSync(nodePath.join(outDir, 'app.dSYM')).isSymbolicLink()).toBe(false); - fs.rmSync(release, { recursive: true }); - expect(fs.readFileSync(nodePath.join(outDir, 'app.dSYM', dwarf), 'utf8')).toBe('debug symbols'); -}); diff --git a/vendor/react-native-gpui/packages/cli/src/desktop-config.js b/vendor/react-native-gpui/packages/cli/src/desktop-config.js deleted file mode 100644 index e106d12be4..0000000000 --- a/vendor/react-native-gpui/packages/cli/src/desktop-config.js +++ /dev/null @@ -1,401 +0,0 @@ -/** - * `desktop/desktop.json` — the one declarative file that describes a desktop - * app: its name, identifier, version, icon, window, and how it is packaged. - * - * The model is Tauri's `tauri.conf.json`: the app owns the file, it is data - * rather than code, and it ships a JSON schema so editors can complete it. - * `react-native.config.js` keeps only build-tooling options, because it is - * executable JavaScript that nothing can read statically. - * - * Every field is optional. An app with no `desktop.json` still runs and packages - * with the defaults below. - */ -import fs from 'node:fs'; -import path from 'node:path'; - -/** The alpha formats each OS can produce. `all` expands to these. */ -export const TARGETS_BY_OS = { - macos: ['app', 'dmg'], - windows: ['nsis'], - linux: ['deb', 'appimage'], -}; - -/** Every format this phase can produce, on any OS. */ -export const ALL_TARGETS = ['app', 'dmg', 'nsis', 'deb', 'appimage']; - -/** - * The OS name this module's files and targets use, from a Node platform. - * - * `desktop.macos.json` rather than `desktop.darwin.json`: the file names the - * platform a person would, and `process.platform` uses Node's spelling. - */ -export function desktopOs(platform = process.platform) { - switch (platform) { - case 'darwin': - return 'macos'; - case 'win32': - return 'windows'; - default: - return platform; - } -} - -/** - * The key names that must never appear in a config file. - * - * Signing material comes from the environment (D6). A password, token or - * private key written into a file that gets committed and shipped is a leak - * whether or not it is still valid, so a config carrying one is refused rather - * than warned about. - */ -const SECRET_KEY = /password|secret|token|privateKey/iu; - -export const DEFAULT_WINDOW = { width: 1024, height: 768 }; -export const DEFAULT_MACOS_MINIMUM = '13.0'; - -/** - * RFC 7386 JSON Merge Patch. - * - * A `null` in `patch` removes the key, which is how a per-OS file turns off a - * value the base set: `{"bundle": {"macos": null}}`. Arrays and scalars replace - * wholesale; only objects merge. - */ -export function mergePatch(target, patch) { - if (typeof patch !== 'object' || patch === null || Array.isArray(patch)) { - return patch; - } - const base = - typeof target === 'object' && target !== null && !Array.isArray(target) - ? target - : {}; - const result = { ...base }; - for (const [key, value] of Object.entries(patch)) { - if (value === null) { - delete result[key]; - } else { - result[key] = mergePatch(base[key], value); - } - } - return result; -} - -/** `com.example.my-app`, from an app name. */ -export function identifierFromName(name) { - return `com.example.${String(name) - .toLowerCase() - .replaceAll(/[^a-z0-9-]/gu, '-')}`; -} - -/** - * The `desktop.json` path for an app. - * - * It lives in the app's existing `desktop/` folder, beside the Rust crate it - * configures. - */ -export function desktopConfigPath(projectRoot) { - return path.join(projectRoot, 'desktop', 'desktop.json'); -} - -function readJson(file, label) { - let text; - try { - text = fs.readFileSync(file, 'utf8'); - } catch (error) { - if (error.code === 'ENOENT') return undefined; - throw error; - } - try { - return JSON.parse(text); - } catch (error) { - throw new Error(`${label} is not valid JSON: ${file}\n${error.message}`); - } -} - -/** - * Loads the configuration for one OS. - * - * Reads `desktop/desktop.json`, merges `desktop/desktop..json` over it, - * fills the defaults, validates, and refuses a config carrying a secret. Pure - * apart from those reads. - */ -export function loadDesktopConfig(projectRoot, platform) { - const os = desktopOs(platform); - const basePath = path.join(projectRoot, 'desktop', 'desktop.json'); - const osPath = path.join(projectRoot, 'desktop', `desktop.${os}.json`); - const appConfigPath = path.join(projectRoot, 'app.json'); - const packageJsonPath = path.join(projectRoot, 'package.json'); - - const base = readJson(basePath, 'desktop/desktop.json'); - if (base !== undefined) assertObject(base, 'desktop/desktop.json', '$'); - const override = readJson(osPath, `desktop/desktop.${os}.json`); - if (override !== undefined) { - assertObject(override, `desktop/desktop.${os}.json`, '$'); - } - - const appConfig = readJson(appConfigPath, 'app.json') ?? {}; - - const merged = - base === undefined && override === undefined - ? {} - : mergePatch(base ?? {}, override ?? {}); - - // Secrets first: the schema rejects unknown keys, and "unknown key" is a - // misleading way to describe a password someone tried to commit. - assertNoSecrets(merged, '$'); - - const errors = []; - validateAgainst(merged, SCHEMA, '$', errors); - if ( - merged.jsThread !== undefined && - (merged.renderer ?? 'fabric') !== 'loom' - ) { - errors.push('$.jsThread: only available with "renderer": "loom"'); - } - if (errors.length > 0) { - throw new Error( - `invalid desktop/desktop.json:\n${errors.map(error => ` ${error}`).join('\n')}`, - ); - } - - const packageJson = readJson(packageJsonPath, 'package.json') ?? {}; - return withDefaults(merged, { appConfig, packageJson }); -} - -function assertObject(value, label, jsonPath) { - if (typeof value !== 'object' || value === null || Array.isArray(value)) { - throw new Error(`invalid ${label}: ${jsonPath} must be an object`); - } -} - -/** - * Fills every field an app may omit. - * - * `window.title` defaults to `productName` rather than the app name, so a - * title bar and the app's own name are the same string unless asked otherwise. - */ -function withDefaults(config, { appConfig, packageJson }) { - const productName = - config.productName ?? - appConfig.displayName ?? - appConfig.name ?? - packageJson.name ?? - 'App'; - const identifier = - config.identifier ?? identifierFromName(appConfig.name ?? productName); - const version = config.version ?? packageJson.version ?? '1.0.0'; - const renderer = config.renderer ?? 'fabric'; - const window = { ...DEFAULT_WINDOW, ...(config.window ?? {}) }; - if (window.title === undefined) window.title = productName; - if (window.resizable === undefined) window.resizable = true; - if (window.restoreState === undefined) window.restoreState = true; - if (window.visible === undefined) window.visible = true; - - const tray = - config.tray === undefined ? undefined : { accessory: true, ...config.tray }; - - const bundle = { ...(config.bundle ?? {}) }; - if (bundle.targets === undefined) bundle.targets = 'all'; - if (bundle.resources === undefined) bundle.resources = []; - bundle.macos = { - minimumSystemVersion: DEFAULT_MACOS_MINIMUM, - ...(bundle.macos ?? {}), - }; - if (bundle.macos.entitlements === undefined) bundle.macos.entitlements = null; - if (bundle.macos.infoPlist === undefined) bundle.macos.infoPlist = {}; - bundle.windows = bundle.windows ?? {}; - bundle.windows.nsis = { - installMode: 'currentUser', - ...(bundle.windows.nsis ?? {}), - }; - bundle.linux = bundle.linux ?? {}; - bundle.linux.deb = { depends: [], ...(bundle.linux.deb ?? {}) }; - bundle.linux.appimage = bundle.linux.appimage ?? {}; - - return { - productName, - identifier, - version, - ...(config.icon === undefined ? {} : { icon: config.icon }), - renderer, - ...(renderer === 'loom' - ? { jsThread: config.jsThread ?? 'background' } - : {}), - window, - ...(config.accessory === undefined ? {} : { accessory: config.accessory }), - devMenu: config.devMenu ?? true, - urlSchemes: config.urlSchemes ?? [], - singleInstance: - config.singleInstance ?? (config.urlSchemes ?? []).length > 0, - ...(tray === undefined ? {} : { tray }), - bundle, - }; -} - -/** The formats to build for one OS. */ -export function targetsFor(config, platform) { - const os = desktopOs(platform); - const available = TARGETS_BY_OS[os] ?? []; - const requested = config.bundle?.targets ?? 'all'; - const list = requested === 'all' ? available : requested; - const unknown = list.filter(target => !ALL_TARGETS.includes(target)); - if (unknown.length > 0) { - throw new Error( - `unknown bundle target(s) ${unknown.join(', ')}; expected one of ${ALL_TARGETS.join(', ')} or 'all'`, - ); - } - const unavailable = list.filter(target => !available.includes(target)); - if (unavailable.length > 0) { - throw new Error( - `${unavailable.join(', ')} cannot be built on ${os}; available targets are ${available.join(', ')}`, - ); - } - return list; -} - -/** - * Walks the merged config and refuses any key that names signing material. - * - * The values are not quoted in the error: printing a leaked secret into a build - * log is the same mistake twice. - */ -function assertNoSecrets(value, jsonPath) { - if (Array.isArray(value)) { - value.forEach((item, index) => - assertNoSecrets(item, `${jsonPath}[${index}]`), - ); - return; - } - if (typeof value !== 'object' || value === null) return; - for (const [key, child] of Object.entries(value)) { - if (SECRET_KEY.test(key)) { - throw new Error( - `desktop/desktop.json must not contain signing material: ${jsonPath}.${key}. ` + - 'Set it in the environment instead; see the README.', - ); - } - assertNoSecrets(child, `${jsonPath}.${key}`); - } -} - -/** - * Validates against `desktop.schema.json`. - * - * A small validator for exactly this schema, because the CLI ships with no - * dependencies and the plan asks before adding one. It reports the JSON path of - * the first problem at each location rather than only the first overall: a - * config with two typos should not need two runs to fix. - * - * The schema subset it implements is `type`, `enum`, `pattern`, `minLength`, - * `exclusiveMinimum`, `required`, `properties`, `additionalProperties`, - * `items`, `minItems`, `oneOf`. - */ -function typeMatches(value, type) { - switch (type) { - case 'object': - return ( - typeof value === 'object' && value !== null && !Array.isArray(value) - ); - case 'array': - return Array.isArray(value); - case 'string': - return typeof value === 'string'; - case 'number': - return typeof value === 'number' && Number.isFinite(value); - case 'boolean': - return typeof value === 'boolean'; - case 'null': - return value === null; - default: - return true; - } -} - -function validateAgainst(value, schema, jsonPath, errors) { - const types = - schema.type === undefined - ? undefined - : Array.isArray(schema.type) - ? schema.type - : [schema.type]; - if (types !== undefined && !types.some(type => typeMatches(value, type))) { - errors.push(`${jsonPath}: expected ${types.join(' or ')}`); - return; - } - - if (schema.enum !== undefined && !schema.enum.includes(value)) { - errors.push( - `${jsonPath}: expected one of ${schema.enum.map(item => JSON.stringify(item)).join(', ')}`, - ); - return; - } - if (schema.pattern !== undefined && typeof value === 'string') { - if (!new RegExp(schema.pattern, 'u').test(value)) { - errors.push(`${jsonPath}: does not match ${schema.pattern}`); - } - } - if (schema.minLength !== undefined && typeof value === 'string') { - if (value.length < schema.minLength) { - errors.push(`${jsonPath}: must not be empty`); - } - } - if (schema.exclusiveMinimum !== undefined && typeof value === 'number') { - if (value <= schema.exclusiveMinimum) { - errors.push( - `${jsonPath}: must be greater than ${schema.exclusiveMinimum}`, - ); - } - } - - if (schema.oneOf !== undefined) { - const matched = schema.oneOf.filter(branch => { - const branchErrors = []; - validateAgainst(value, branch, jsonPath, branchErrors); - return branchErrors.length === 0; - }); - if (matched.length !== 1) { - errors.push( - `${jsonPath}: matches ${matched.length} of ${schema.oneOf.length} allowed shapes, expected exactly one`, - ); - } - } - - if (Array.isArray(value)) { - if (schema.minItems !== undefined && value.length < schema.minItems) { - errors.push(`${jsonPath}: must have at least ${schema.minItems} item(s)`); - } - if (schema.items !== undefined) { - value.forEach((item, index) => - validateAgainst(item, schema.items, `${jsonPath}[${index}]`, errors), - ); - } - return; - } - - if (typeof value === 'object' && value !== null) { - for (const required of schema.required ?? []) { - if (value[required] === undefined) { - errors.push(`${jsonPath}: missing required key ${required}`); - } - } - const properties = schema.properties ?? {}; - for (const [key, child] of Object.entries(value)) { - const childPath = `${jsonPath}.${key}`; - if (properties[key] !== undefined) { - validateAgainst(child, properties[key], childPath, errors); - } else if (schema.additionalProperties === false) { - const known = Object.keys(properties).sort().join(', '); - errors.push(`${childPath}: unknown key; known keys are ${known}`); - } - } - } -} - -/** The schema, read once. `desktop.schema.json` is shipped and documented. */ -const SCHEMA = JSON.parse( - fs.readFileSync(new URL('../desktop.schema.json', import.meta.url), 'utf8'), -); - -/** The schema itself, for `--print-schema` and for callers that ship it. */ -export function desktopSchema() { - return SCHEMA; -} diff --git a/vendor/react-native-gpui/packages/cli/src/desktop-config.test.js b/vendor/react-native-gpui/packages/cli/src/desktop-config.test.js deleted file mode 100644 index b40dc8235c..0000000000 --- a/vendor/react-native-gpui/packages/cli/src/desktop-config.test.js +++ /dev/null @@ -1,327 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, describe, expect, test } from 'vitest'; -import { - identifierFromName, - loadDesktopConfig, - mergePatch, - targetsFor, -} from './desktop-config.js'; - -const roots = []; - -afterEach(() => { - while (roots.length > 0) { - fs.rmSync(roots.pop(), { recursive: true, force: true }); - } -}); - -/** - * A minimal app: `app.json` and `package.json` only. `files` adds or replaces - * files by path relative to the project root. - */ -function createProject({ appJson, packageJson, files = {} } = {}) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'rn-gpui-desktop-')); - roots.push(root); - fs.mkdirSync(path.join(root, 'desktop'), { recursive: true }); - fs.writeFileSync( - path.join(root, 'app.json'), - `${JSON.stringify( - appJson ?? { name: 'MyApp', displayName: 'My App' }, - null, - 2, - )}\n`, - ); - fs.writeFileSync( - path.join(root, 'package.json'), - `${JSON.stringify( - packageJson ?? { name: 'my-app', version: '2.3.4' }, - null, - 2, - )}\n`, - ); - for (const [relative, contents] of Object.entries(files)) { - const target = path.join(root, relative); - fs.mkdirSync(path.dirname(target), { recursive: true }); - fs.writeFileSync( - target, - typeof contents === 'string' - ? contents - : JSON.stringify(contents, null, 2), - ); - } - return root; -} - -describe('defaults', () => { - test('an app with no desktop.json gets every default', () => { - const root = createProject(); - const config = loadDesktopConfig(root, 'macos'); - expect(config.productName).toBe('My App'); - expect(config.identifier).toBe('com.example.myapp'); - expect(config.version).toBe('2.3.4'); - expect(config.window).toEqual({ - width: 1024, - height: 768, - title: 'My App', - resizable: true, - restoreState: true, - visible: true, - }); - expect(config.devMenu).toBe(true); - expect(config.urlSchemes).toEqual([]); - expect(config.singleInstance).toBe(false); - expect(config.tray).toBeUndefined(); - expect(config.bundle.targets).toBe('all'); - expect(config.bundle.resources).toEqual([]); - expect(config.bundle.macos.minimumSystemVersion).toBe('13.0'); - expect(config.bundle.macos.entitlements).toBeNull(); - expect(config.bundle.macos.infoPlist).toEqual({}); - expect(config.bundle.windows.nsis.installMode).toBe('currentUser'); - expect(config.bundle.linux.deb.depends).toEqual([]); - }); - - test('the window title defaults to productName, not the app name', () => { - const root = createProject({ - files: { 'desktop/desktop.json': { productName: 'Shiny' } }, - }); - expect(loadDesktopConfig(root, 'macos').window.title).toBe('Shiny'); - }); - - test('an explicit title wins over productName', () => { - const root = createProject({ - files: { - 'desktop/desktop.json': { - productName: 'Shiny', - window: { title: 'Other' }, - }, - }, - }); - expect(loadDesktopConfig(root, 'macos').window.title).toBe('Other'); - }); - - test('an identifier is derived from the app name when absent', () => { - const root = createProject({ appJson: { name: 'My_App 2' } }); - expect(loadDesktopConfig(root, 'macos').identifier).toBe( - 'com.example.my-app-2', - ); - expect(identifierFromName('A B')).toBe('com.example.a-b'); - }); -}); - -describe('per-OS overrides', () => { - test('desktop..json is merged over the base', () => { - const root = createProject({ - files: { - 'desktop/desktop.json': { - productName: 'Base', - window: { width: 800, height: 600 }, - }, - 'desktop/desktop.macos.json': { window: { width: 1200 } }, - }, - }); - const macos = loadDesktopConfig(root, 'macos'); - expect(macos.productName).toBe('Base'); - expect(macos.window.width).toBe(1200); - // Untouched keys keep the base value. - expect(macos.window.height).toBe(600); - - // The override only applies to its own OS. - expect(loadDesktopConfig(root, 'linux').window.width).toBe(800); - }); - - test('a null removes a key, as RFC 7386 says', () => { - const root = createProject({ - files: { - 'desktop/desktop.json': { - tray: { component: 'MyTray', tooltip: 'Hi' }, - }, - 'desktop/desktop.linux.json': { tray: null }, - }, - }); - expect(loadDesktopConfig(root, 'macos').tray).toEqual({ - component: 'MyTray', - tooltip: 'Hi', - accessory: true, - }); - expect(loadDesktopConfig(root, 'linux').tray).toBeUndefined(); - }); - - test('mergePatch replaces arrays rather than concatenating them', () => { - expect( - mergePatch( - { bundle: { resources: ['a', 'b'] } }, - { bundle: { resources: ['c'] } }, - ), - ).toEqual({ bundle: { resources: ['c'] } }); - }); - - test('merging into a missing base fills from the override alone', () => { - expect(mergePatch(undefined, { a: { b: 1 } })).toEqual({ a: { b: 1 } }); - }); -}); - -describe('validation', () => { - test('an unknown key is refused with its JSON path', () => { - const root = createProject({ - files: { 'desktop/desktop.json': { windo: { width: 1 } } }, - }); - expect(() => loadDesktopConfig(root, 'macos')).toThrow( - /\$\.windo: unknown key; known keys are/, - ); - }); - - test('a wrong type names the offending path', () => { - const root = createProject({ - files: { 'desktop/desktop.json': { window: { width: 'wide' } } }, - }); - expect(() => loadDesktopConfig(root, 'macos')).toThrow( - /\$\.window\.width: expected number/, - ); - }); - - test('a nested unknown key is caught too', () => { - const root = createProject({ - files: { 'desktop/desktop.json': { bundle: { macos: { nope: 1 } } } }, - }); - expect(() => loadDesktopConfig(root, 'macos')).toThrow( - /\$\.bundle\.macos\.nope: unknown key/, - ); - }); - - test('two problems are both reported', () => { - const root = createProject({ - files: { - 'desktop/desktop.json': { - window: { width: 'wide' }, - version: 7, - }, - }, - }); - expect(() => loadDesktopConfig(root, 'macos')).toThrow( - /window\.width: expected number[\s\S]*\$\.version: expected string/, - ); - }); - - test('a bad target is refused with the allowed list', () => { - const root = createProject({ - files: { 'desktop/desktop.json': { bundle: { targets: ['msi'] } } }, - }); - expect(() => loadDesktopConfig(root, 'macos')).toThrow( - /\$\.bundle\.targets: (matches 0 of|unknown bundle target)/, - ); - }); - - test('a target for another OS is refused by targetsFor, with what is available', () => { - // The schema allows any known format, because which ones an OS can build is - // a fact about the OS rather than about the file. - const root = createProject({ - files: { 'desktop/desktop.json': { bundle: { targets: ['nsis'] } } }, - }); - const config = loadDesktopConfig(root, 'macos'); - expect(() => targetsFor(config, 'macos')).toThrow( - /nsis cannot be built on macos; available targets are app, dmg/, - ); - }); - - test('a file that is not JSON says so', () => { - const root = createProject({ - files: { 'desktop/desktop.json': '{ nope' }, - }); - expect(() => loadDesktopConfig(root, 'macos')).toThrow( - /desktop\/desktop\.json is not valid JSON/, - ); - }); -}); - -describe('secrets', () => { - test.each([ - ['a password', { bundle: { macos: { password: 'hunter2' } } }], - ['a top-level secret', { secret: 'abc' }], - ['a token', { bundle: { windows: { token: 'abc' } } }], - ['a private key', { bundle: { macos: { privateKey: '---' } } }], - ['an oddly-cased name', { bundle: { macos: { PASSWORD: 'x' } } }], - ])('%s is refused, and its value is not printed', (_name, config) => { - const root = createProject({ files: { 'desktop/desktop.json': config } }); - let message = ''; - try { - loadDesktopConfig(root, 'macos'); - } catch (error) { - message = error.message; - } - expect(message).toMatch(/must not contain signing material/); - // Printing a leaked secret into a build log is the same mistake twice. - expect(message).not.toMatch(/hunter2|abc|---/u); - }); - - test('a key that merely resembles one is allowed', () => { - // `InfoPlist` contains "Plist", not a secret word; the check must not be so - // eager that it refuses the documented `infoPlist` setting. - const root = createProject({ - files: { - 'desktop/desktop.json': { bundle: { macos: { infoPlist: {} } } }, - }, - }); - expect(() => loadDesktopConfig(root, 'macos')).not.toThrow(); - }); -}); - -describe('renderer', () => { - test('defaults to fabric with no JS thread choice', () => { - const config = loadDesktopConfig(createProject(), 'macos'); - expect(config.renderer).toBe('fabric'); - expect(config.jsThread).toBeUndefined(); - }); - - test('loom runs JavaScript in the background unless told otherwise', () => { - const root = createProject({ - files: { 'desktop/desktop.json': { renderer: 'loom' } }, - }); - expect(loadDesktopConfig(root, 'macos').jsThread).toBe('background'); - const main = createProject({ - files: { - 'desktop/desktop.json': { renderer: 'loom', jsThread: 'main' }, - }, - }); - expect(loadDesktopConfig(main, 'macos').jsThread).toBe('main'); - }); - - test('a JS thread needs the loom renderer', () => { - const root = createProject({ - files: { 'desktop/desktop.json': { jsThread: 'main' } }, - }); - expect(() => loadDesktopConfig(root, 'macos')).toThrow( - /jsThread: only available with "renderer": "loom"/, - ); - }); - - test('an unknown renderer lists the choices', () => { - const root = createProject({ - files: { 'desktop/desktop.json': { renderer: 'skia' } }, - }); - expect(() => loadDesktopConfig(root, 'macos')).toThrow( - /\$\.renderer: expected one of "fabric", "loom"/, - ); - }); -}); - -describe('targetsFor', () => { - const config = targets => ({ bundle: { targets } }); - - test("'all' expands to the current OS's alpha formats", () => { - expect(targetsFor(config('all'), 'macos')).toEqual(['app', 'dmg']); - expect(targetsFor(config('all'), 'windows')).toEqual(['nsis']); - expect(targetsFor(config('all'), 'linux')).toEqual(['deb', 'appimage']); - }); - - test('an explicit list is filtered to what the OS can build', () => { - expect(targetsFor(config(['app']), 'macos')).toEqual(['app']); - }); - - test('an unknown format names every allowed one', () => { - expect(() => targetsFor(config(['msi']), 'macos')).toThrow( - /unknown bundle target\(s\) msi; expected one of app, dmg, nsis, deb, appimage or 'all'/, - ); - }); -}); diff --git a/vendor/react-native-gpui/packages/cli/src/doctor.cjs b/vendor/react-native-gpui/packages/cli/src/doctor.cjs deleted file mode 100644 index ee62c8600d..0000000000 --- a/vendor/react-native-gpui/packages/cli/src/doctor.cjs +++ /dev/null @@ -1,391 +0,0 @@ -'use strict'; - -const { spawnSync } = require('node:child_process'); - -const MIN_NODE = [22, 13, 0]; -const MIN_RUST = { - version: [1, 98, 0], - fix: 'rustup update stable; if this still reports an older version, another Rust installation comes first on PATH', -}; - -/** The libraries the app links on Linux, with each distribution's package. */ -const LINUX_LIBRARIES = [ - { - pc: 'xkbcommon', - packages: { - 'Debian/Ubuntu': 'libxkbcommon-dev', - Fedora: 'libxkbcommon-devel', - Arch: 'libxkbcommon', - }, - }, - { - pc: 'xkbcommon-x11', - packages: { - 'Debian/Ubuntu': 'libxkbcommon-x11-dev', - Fedora: 'libxkbcommon-x11-devel', - Arch: 'libxkbcommon-x11', - }, - }, - { - pc: 'xcb', - packages: { - 'Debian/Ubuntu': 'libxcb1-dev', - Fedora: 'libxcb-devel', - Arch: 'libxcb', - }, - }, -]; - -function installCommands(packages) { - return Object.entries(packages) - .map(([distribution, name]) => { - const command = - distribution === 'Arch' - ? `sudo pacman -S ${name}` - : `sudo ${distribution === 'Fedora' ? 'dnf' : 'apt'} install ${name}`; - return `${distribution}: ${command}`; - }) - .join(', '); -} - -/** Runs a command and never throws: a missing binary is `ok: false`. */ -function systemProbe() { - return { - run(command, args = []) { - const result = spawnSync(command, args, { - encoding: 'utf8', - shell: false, - windowsHide: true, - }); - return { - ok: !result.error && result.status === 0, - found: !result.error, - stdout: (result.stdout ?? '').trim(), - stderr: (result.stderr ?? '').trim(), - }; - }, - nodeVersion: process.versions.node, - }; -} - -function firstLine(text) { - return text.split(/\r?\n/u)[0].trim(); -} - -function versionIn(text) { - return /\d+\.\d+(?:\.\d+)?/u.exec(text)?.[0]; -} - -function atLeast(version, minimum) { - const parts = version.split('.').map(Number); - for (let index = 0; index < minimum.length; index += 1) { - const part = parts[index] ?? 0; - if (part !== minimum[index]) return part > minimum[index]; - } - return true; -} - -/** - * A check that passes when `command` runs, reporting the version it prints, - * and, with `minimum`, when that version is at least `minimum.version`. - */ -function tool(label, command, args, fix, minimum) { - return { - label, - check(probe) { - const result = probe.run(command, args); - if (!result.ok) - return { ok: false, message: `${command} was not found`, fix }; - const version = versionIn(firstLine(result.stdout || result.stderr)); - if (minimum && !(version && atLeast(version, minimum.version))) - return { - ok: false, - version, - message: `${label} ${minimum.version.join('.')} or newer is required`, - fix: minimum.fix, - }; - return { ok: true, version }; - }, - }; -} - -const node = { - label: 'Node.js', - check(probe) { - const version = probe.nodeVersion; - if (atLeast(version, MIN_NODE)) return { ok: true, version }; - return { - ok: false, - version, - message: `Node.js ${MIN_NODE.join('.')} or newer is required`, - fix: 'Install the current Node.js LTS from https://nodejs.org', - }; - }, -}; - -const rustupFix = { - darwin: "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh", - linux: "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh", - win32: 'winget install -e --id Rustlang.Rustup', -}; - -const cmakeFix = { - darwin: 'brew install cmake', - linux: 'Install the cmake package of your distribution', - win32: 'winget install -e --id Kitware.CMake', -}; - -const CLT_PATH = '/Library/Developer/CommandLineTools'; - -const macosChecks = [ - { - label: 'Xcode command line tools', - check(probe) { - const result = probe.run('xcode-select', ['-p']); - if (!result.ok) { - return { - ok: false, - message: 'the Xcode command line tools are not installed', - fix: 'xcode-select --install', - }; - } - if (result.stdout.startsWith(CLT_PATH)) return { ok: true }; - const version = probe.run('xcodebuild', ['-version']); - return { ok: true, version: versionIn(firstLine(version.stdout)) }; - }, - }, - { - label: 'Xcode license', - check(probe) { - const selected = probe.run('xcode-select', ['-p']); - if (!selected.ok || selected.stdout.startsWith(CLT_PATH)) - return { ok: true }; - if (probe.run('xcodebuild', ['-license', 'check']).ok) - return { ok: true }; - return { - ok: false, - message: 'the Xcode license has not been accepted', - fix: 'sudo xcodebuild -license accept', - }; - }, - }, -]; - -const windowsChecks = [ - { - label: 'MSVC compiler', - check(probe) { - if (probe.run('where.exe', ['cl']).ok) return { ok: true }; - return { - ok: false, - message: 'cl.exe is not on PATH', - fix: 'Run from a Developer PowerShell for VS 2022. If Visual Studio is missing: winget install -e --id Microsoft.VisualStudio.2022.BuildTools --override "--quiet --wait --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"', - }; - }, - }, - { - label: 'Strawberry Perl', - check(probe) { - const result = probe.run('perl', ['-e', 'print $^X']); - if (!result.ok) { - return { - ok: false, - message: 'perl was not found', - fix: 'winget install -e --id StrawberryPerl.StrawberryPerl', - }; - } - if (!/strawberry/iu.test(result.stdout)) { - return { - ok: false, - message: `perl resolves to ${result.stdout}, not to Strawberry Perl`, - fix: "Move C:\\Strawberry\\perl\\bin above Git's usr\\bin in PATH", - }; - } - return { ok: true }; - }, - }, - tool( - 'NASM', - 'nasm', - ['-v'], - 'winget install -e --id NASM.NASM, then add C:\\Program Files\\NASM to PATH', - ), - { - label: 'Long paths', - check(probe) { - const result = probe.run('reg', [ - 'query', - 'HKLM\\SYSTEM\\CurrentControlSet\\Control\\FileSystem', - '/v', - 'LongPathsEnabled', - ]); - if (/LongPathsEnabled\s+REG_DWORD\s+0x1\b/iu.test(result.stdout)) - return { ok: true }; - return { - ok: false, - message: 'long paths are not enabled', - fix: 'From an administrator PowerShell: New-ItemProperty -Path HKLM:\\SYSTEM\\CurrentControlSet\\Control\\FileSystem -Name LongPathsEnabled -Value 1 -PropertyType DWORD -Force, then restart', - }; - }, - }, -]; - -const linuxChecks = [ - tool( - 'C++ compiler', - 'c++', - ['--version'], - 'Install build-essential (Debian/Ubuntu), gcc-c++ (Fedora) or base-devel (Arch)', - ), - tool( - 'pkg-config', - 'pkg-config', - ['--version'], - 'Debian/Ubuntu: sudo apt install pkg-config, Fedora: sudo dnf install pkgconf-pkg-config, Arch: sudo pacman -S pkgconf', - ), - tool( - 'Perl', - 'perl', - ['-e', 'print "$^V"'], - 'Install the perl package of your distribution', - ), - ...LINUX_LIBRARIES.map(({ pc, packages }) => ({ - label: `${pc} development files`, - check(probe) { - const result = probe.run('pkg-config', ['--modversion', pc]); - if (result.ok) return { ok: true, version: firstLine(result.stdout) }; - return { - ok: false, - message: result.found - ? `pkg-config cannot find ${pc}` - : 'pkg-config was not found', - fix: installCommands(packages), - }; - }, - })), -]; - -/** The checks for one platform (`process.platform` values), in report order. */ -function desktopChecks(platform) { - return [ - node, - tool( - 'Rust', - 'rustc', - ['--version'], - rustupFix[platform] ?? rustupFix.linux, - MIN_RUST, - ), - tool( - 'Cargo', - 'cargo', - ['--version'], - rustupFix[platform] ?? rustupFix.linux, - MIN_RUST, - ), - tool('CMake', 'cmake', ['--version'], cmakeFix[platform] ?? cmakeFix.linux), - ...(platform === 'darwin' - ? macosChecks - : platform === 'win32' - ? windowsChecks - : platform === 'linux' - ? linuxChecks - : []), - ]; -} - -/** Runs every check for `platform` and returns the results in order. */ -function runDoctor(platform = process.platform, probe = systemProbe()) { - return desktopChecks(platform).map(({ label, check }) => ({ - label, - ...check(probe), - })); -} - -function colors(enabled) { - const wrap = (open, close) => text => - enabled ? `\u001b[${open}m${text}\u001b[${close}m` : text; - return { - red: wrap(31, 39), - green: wrap(32, 39), - dim: wrap(2, 22), - bold: wrap(1, 22), - }; -} - -const platformNames = { darwin: 'macOS', win32: 'Windows', linux: 'Linux' }; - -/** The report `doctor` prints. */ -function formatReport(results, platform, color = false) { - const c = colors(color); - const lines = [ - c.bold(`Desktop development on ${platformNames[platform] ?? platform}`), - ]; - for (const result of results) { - if (result.ok) { - lines.push( - ` ${c.green('✓')} ${result.label}${result.version ? c.dim(` ${result.version}`) : ''}`, - ); - } else { - lines.push(` ${c.red('✖')} ${result.label}: ${result.message}`); - if (result.fix) lines.push(` ${c.dim('Fix:')} ${result.fix}`); - } - } - const problems = results.filter(result => !result.ok).length; - lines.push(''); - lines.push( - problems === 0 - ? c.green('Everything needed to build a desktop app is installed.') - : c.red(`${problems} ${problems === 1 ? 'problem' : 'problems'} found.`), - ); - return lines.join('\n'); -} - -/** Prints the report and returns the process exit code. */ -function doctor({ - platform = process.platform, - probe, - stream = process.stdout, -} = {}) { - const results = runDoctor(platform, probe); - const color = Boolean(stream.isTTY) && !process.env.NO_COLOR; - stream.write(`${formatReport(results, platform, color)}\n`); - return results.every(result => result.ok) ? 0 : 1; -} - -/** The same checks as a category for `npx react-native doctor`. */ -function reactNativeHealthChecks(platform = process.platform) { - return [ - { - label: 'Desktop', - healthchecks: desktopChecks(platform).map(({ label, check }) => { - let last; - return { - label, - getDiagnostics: async () => { - last = check(systemProbe()); - return { - needsToBeFixed: !last.ok, - version: last.version, - description: last.ok ? undefined : last.message, - }; - }, - runAutomaticFix: async ({ loader, logManualInstallation }) => { - loader.fail(); - logManualInstallation({ message: last?.fix ?? `Fix ${label}` }); - }, - }; - }), - }, - ]; -} - -module.exports = { - LINUX_LIBRARIES, - desktopChecks, - doctor, - formatReport, - installCommands, - reactNativeHealthChecks, - runDoctor, -}; diff --git a/vendor/react-native-gpui/packages/cli/src/doctor.test.js b/vendor/react-native-gpui/packages/cli/src/doctor.test.js deleted file mode 100644 index aef27fc012..0000000000 --- a/vendor/react-native-gpui/packages/cli/src/doctor.test.js +++ /dev/null @@ -1,189 +0,0 @@ -import { describe, expect, test } from 'vitest'; -import { formatReport, reactNativeHealthChecks, runDoctor } from './doctor.cjs'; - -/** - * A probe whose commands answer from `outputs`, keyed by the command and its - * arguments. A key mapped to `null` is a missing binary; one that is absent - * runs and exits non-zero. - */ -function fakeProbe(outputs, nodeVersion = '22.20.0') { - return { - nodeVersion, - run(command, args = []) { - const key = [command, ...args].join(' '); - if (!(key in outputs)) - return { ok: false, found: true, stdout: '', stderr: '' }; - const stdout = outputs[key]; - if (stdout === null) - return { ok: false, found: false, stdout: '', stderr: '' }; - return { ok: true, found: true, stdout, stderr: '' }; - }, - }; -} - -const common = { - 'rustc --version': 'rustc 1.98.1 (0123abcde 2026-10-20)', - 'cargo --version': 'cargo 1.98.1 (a1b2c3d 2026-10-20)', - 'cmake --version': - 'cmake version 3.31.4\n\nCMake suite maintained by Kitware', -}; - -const macos = { - ...common, - 'xcode-select -p': '/Applications/Xcode.app/Contents/Developer', - 'xcodebuild -version': 'Xcode 26.6\nBuild version 17A100', - 'xcodebuild -license check': '', -}; - -const failures = results => - results.filter(result => !result.ok).map(result => result.label); - -describe('runDoctor on macOS', () => { - test('passes and reports versions when every tool is present', () => { - const results = runDoctor('darwin', fakeProbe(macos)); - expect(failures(results)).toEqual([]); - expect(results.find(result => result.label === 'CMake').version).toBe( - '3.31.4', - ); - expect( - results.find(result => result.label === 'Xcode command line tools') - .version, - ).toBe('26.6'); - }); - - test('flags an old Node.js', () => { - const results = runDoctor('darwin', fakeProbe(macos, '22.12.0')); - expect(failures(results)).toEqual(['Node.js']); - }); - - test('flags an old Rust toolchain', () => { - const probe = fakeProbe({ - ...macos, - 'rustc --version': 'rustc 1.90.0 (1159e78c4 2025-09-14) (Homebrew)', - 'cargo --version': 'cargo 1.90.0 (Homebrew)', - }); - expect(failures(runDoctor('darwin', probe))).toEqual(['Rust', 'Cargo']); - }); - - test('accepts the command line tools without Xcode', () => { - const { 'xcodebuild -license check': _license, ...rest } = macos; - const probe = fakeProbe({ - ...rest, - 'xcode-select -p': '/Library/Developer/CommandLineTools', - }); - expect(failures(runDoctor('darwin', probe))).toEqual([]); - }); - - test('flags missing command line tools, an unaccepted license and a missing CMake', () => { - const missingTools = fakeProbe({ ...macos, 'xcode-select -p': null }); - expect(failures(runDoctor('darwin', missingTools))).toEqual([ - 'Xcode command line tools', - ]); - const { 'xcodebuild -license check': _license, ...rest } = macos; - const results = runDoctor( - 'darwin', - fakeProbe({ ...rest, 'cmake --version': null }), - ); - expect(failures(results)).toEqual(['CMake', 'Xcode license']); - }); -}); - -describe('runDoctor on Windows', () => { - const windows = { - ...common, - 'where.exe cl': 'C:\\BuildTools\\VC\\bin\\cl.exe', - 'perl -e print $^X': 'C:\\Strawberry\\perl\\bin\\perl.exe', - 'nasm -v': 'NASM version 2.16.03 compiled on Apr 17 2024', - 'reg query HKLM\\SYSTEM\\CurrentControlSet\\Control\\FileSystem /v LongPathsEnabled': - ' LongPathsEnabled REG_DWORD 0x1', - }; - - test('passes when every tool is present', () => { - expect(failures(runDoctor('win32', fakeProbe(windows)))).toEqual([]); - }); - - test("flags Git's Perl, a missing cl.exe and disabled long paths", () => { - const { 'where.exe cl': _cl, ...rest } = windows; - const probe = fakeProbe({ - ...rest, - 'perl -e print $^X': 'C:\\Program Files\\Git\\usr\\bin\\perl.exe', - 'reg query HKLM\\SYSTEM\\CurrentControlSet\\Control\\FileSystem /v LongPathsEnabled': - ' LongPathsEnabled REG_DWORD 0x0', - }); - expect(failures(runDoctor('win32', probe))).toEqual([ - 'MSVC compiler', - 'Strawberry Perl', - 'Long paths', - ]); - }); -}); - -describe('runDoctor on Linux', () => { - const linux = { - ...common, - 'c++ --version': 'c++ (Ubuntu 13.2.0) 13.2.0', - 'pkg-config --version': '1.8.1', - 'perl -e print "$^V"': 'v5.38.2', - 'pkg-config --modversion xkbcommon': '1.6.0', - 'pkg-config --modversion xkbcommon-x11': '1.6.0', - 'pkg-config --modversion xcb': '1.15', - }; - - test('passes when every tool and library is present', () => { - expect(failures(runDoctor('linux', fakeProbe(linux)))).toEqual([]); - }); - - test("names each distribution's package for a missing library", () => { - const { 'pkg-config --modversion xkbcommon-x11': _missing, ...rest } = - linux; - const results = runDoctor('linux', fakeProbe(rest)); - const library = results.find( - result => result.label === 'xkbcommon-x11 development files', - ); - expect(library.ok).toBe(false); - expect(library.fix).toBe( - 'Debian/Ubuntu: sudo apt install libxkbcommon-x11-dev, Fedora: sudo dnf install libxkbcommon-x11-devel, Arch: sudo pacman -S libxkbcommon-x11', - ); - }); -}); - -describe('formatReport', () => { - test('lists passes with versions and failures with their fix', () => { - const report = formatReport( - [ - { label: 'Node.js', ok: true, version: '22.20.0' }, - { - label: 'CMake', - ok: false, - message: 'cmake was not found', - fix: 'brew install cmake', - }, - ], - 'darwin', - ); - expect(report).toBe( - [ - 'Desktop development on macOS', - ' ✓ Node.js 22.20.0', - ' ✖ CMake: cmake was not found', - ' Fix: brew install cmake', - '', - '1 problem found.', - ].join('\n'), - ); - }); -}); - -describe('reactNativeHealthChecks', () => { - test('adds one Desktop category with a health check per doctor check', () => { - const [category] = reactNativeHealthChecks('linux'); - expect(category.label).toBe('Desktop'); - expect(category.healthchecks.map(check => check.label)).toEqual( - runDoctor('linux', fakeProbe({})).map(result => result.label), - ); - for (const check of category.healthchecks) { - expect(typeof check.getDiagnostics).toBe('function'); - expect(typeof check.runAutomaticFix).toBe('function'); - } - }); -}); diff --git a/vendor/react-native-gpui/packages/cli/src/package-desktop.js b/vendor/react-native-gpui/packages/cli/src/package-desktop.js deleted file mode 100644 index 7f63733138..0000000000 --- a/vendor/react-native-gpui/packages/cli/src/package-desktop.js +++ /dev/null @@ -1,797 +0,0 @@ -/** - * The libraries and files a packaged app has to ship. - * - * A packaged app is copied to a machine that has no build tree, so every shared - * library the executable links at run time has to travel with it: the engine, - * the prebuilt runtime and anything a module built as a shared library. The list - * is read from what autolink recorded and from the build output, never from a - * hard-coded table, so a module that adds a library is shipped without anyone - * updating this file. - */ -import { execFileSync } from 'node:child_process'; -import fs from 'node:fs'; -import { createRequire } from 'node:module'; -import path from 'node:path'; - -// The engine's `runtimeFiles` is a CommonJS module inside the engine package, so -// it is loaded with a require rooted at this file rather than imported. -const require = createRequire(import.meta.url); - -/** Where an app's autolink manifest lives. */ -export function autolinkManifestPath(projectRoot) { - return path.join(projectRoot, 'desktop', 'autolink', 'autolink.json'); -} - -/** The shared-library extension for an OS, or `undefined` for another OS. */ -export function libraryExtension(os) { - switch (os) { - case 'macos': - return '.dylib'; - case 'windows': - return '.dll'; - case 'linux': - return '.so'; - default: - return undefined; - } -} - -/** - * Whether a file name is a shared library a packaged app must ship. - * - * Versioned Linux libraries (`libfoo.so.1`) count: the loader asks for the - * versioned name, and shipping only the `libfoo.so` symlink ships nothing. - */ -function isSharedLibrary(name, extension) { - if (extension === undefined) return false; - if (name.endsWith(extension)) return true; - return extension === '.so' && /\.so(\.\d+)+$/u.test(name); -} - -/** The files in `directory` that are shared libraries, sorted. */ -function sharedLibrariesIn(directory, extension) { - let entries; - try { - entries = fs.readdirSync(directory, { withFileTypes: true }); - } catch { - return []; - } - return entries - .filter(entry => entry.isFile() && isSharedLibrary(entry.name, extension)) - .map(entry => path.join(directory, entry.name)) - .sort(); -} - -/** - * The Visual C++ runtime DLLs of the toolset that built the app. - * - * The engine and JSI are DLLs built with the dynamic runtime and exchange - * standard-library objects with the executable (strings, shared pointers, - * exceptions), so they have to share one runtime: it cannot be linked statically - * into each module. The runtime travels beside the executable instead, which - * Microsoft documents as app-local deployment, so a machine without the - * Visual C++ Redistributable still starts the app. `VCToolsRedistDir` is set in - * a Visual Studio developer prompt; otherwise the installed editions are - * searched. - */ -export function vcRuntimeLibraries({ arch, env = process.env, roots } = {}) { - const folder = (arch ?? process.arch) === 'arm64' ? 'arm64' : 'x64'; - const candidates = []; - if (env.VCToolsRedistDir) { - candidates.push(path.join(env.VCToolsRedistDir, folder)); - } - for (const base of roots ?? [env.ProgramFiles, env['ProgramFiles(x86)']]) { - if (!base) continue; - const studio = path.join(base, 'Microsoft Visual Studio'); - for (const year of safeList(studio)) { - for (const edition of safeList(path.join(studio, year))) { - const msvc = path.join(studio, year, edition, 'VC', 'Redist', 'MSVC'); - for (const version of safeList(msvc).sort().reverse()) { - candidates.push(path.join(msvc, version, folder)); - } - } - } - } - for (const directory of candidates) { - const crt = safeList(directory).find(name => - /^Microsoft\.VC\d+\.CRT$/iu.test(name), - ); - if (crt === undefined) continue; - const dlls = sharedLibrariesIn(path.join(directory, crt), '.dll'); - if (dlls.length > 0) return dlls; - } - return []; -} - -function safeList(directory) { - try { - return fs.readdirSync(directory); - } catch { - return []; - } -} - -/** - * Every runtime library a packaged app must carry. - * - * `os` and `arch` are the ones being packaged — Node's `process.platform` and - * `process.arch` spellings — so this is testable without packaging anything. - * - * Returns absolute paths, de-duplicated and sorted. A missing autolink manifest - * is an empty list rather than an error: an app with no autolinked modules has - * nothing extra to ship. - */ -export function runtimeLibraries( - projectRoot, - { os, arch, release = true } = {}, -) { - const platform = os ?? process.platform; - const architecture = arch ?? process.arch; - const extension = libraryExtension( - platform === 'darwin' - ? 'macos' - : platform === 'win32' - ? 'windows' - : 'linux', - ); - const libraries = new Set(); - - const manifest = readManifest(autolinkManifestPath(projectRoot)); - if (manifest !== undefined) { - // The engine names its own files, because only it knows what its platform - // build produces (a dylib, a DLL, and on some builds extra archives). - for (const engine of manifest.jsEngines ?? []) { - if (typeof engine.runtimeFiles !== 'string' || !engine.runtimeFiles) { - continue; - } - let files; - try { - const resolve = require(engine.runtimeFiles); - files = resolve(platform, architecture, { release }) ?? []; - } catch { - continue; - } - for (const file of files) { - if (isSharedLibrary(path.basename(file), extension)) { - libraries.add(path.resolve(file)); - } - } - } - } - - // Libraries the build produced. The runtime's own dependencies land beside - // the crate that built them, so every candidate directory is scanned rather - // than a single assumed one. - for (const directory of buildLibraryDirectories(projectRoot, { release })) { - for (const file of sharedLibrariesIn(directory, extension)) { - libraries.add(file); - } - } - - // Finally, and most reliably, ask the executable what it links. A library can - // live outside both the profile directory and a crate's `out` — the C++ - // bridge's `libjsi` is built by CMake under its own tree — and only the - // binary's own dependencies say what it needs at run time. - for (const file of linkedSharedLibraries(projectRoot, { - release, - extension, - })) { - libraries.add(file); - } - - if (platform === 'win32') { - for (const file of vcRuntimeLibraries({ arch: architecture })) { - libraries.add(file); - } - } - - // One file per name. Two paths can supply the same library — the prebuilt cache - // and the CMake tree both hold `hermesvm` — and the packaging configs map each - // entry to a destination by name, so a second entry would silently target the - // same file twice. The first path wins, which is the recorded build order. - const byName = new Map(); - for (const library of libraries) { - const name = path.basename(library); - if (!byName.has(name)) byName.set(name, library); - } - return [...byName.values()].sort(); -} - -/** - * The shared libraries an executable links that are not system libraries. - * - * `otool -L` on macOS, `readelf -d` on Linux. A system library resolves from the - * OS and must not be bundled; anything resolved through a `@rpath` entry, or - * living under the build, is ours to ship. - */ -export function linkedSharedLibraries(projectRoot, { release, extension }) { - const binary = path.join( - targetProfileDir( - path.join(projectRoot, 'desktop'), - release ? 'release' : 'debug', - ), - executableName(projectRoot), - ); - if (!fs.existsSync(binary)) return []; - - let output; - try { - if (process.platform === 'darwin') { - output = execFileSync('otool', ['-L', binary], { encoding: 'utf8' }); - } else if (process.platform === 'linux') { - output = execFileSync('readelf', ['-d', binary], { encoding: 'utf8' }); - } else { - return []; - } - } catch { - return []; - } - - const found = new Set(); - for (const reference of parseSharedLibraryReferences( - output, - process.platform, - )) { - const resolved = resolveLinkedLibrary(reference, { - binary, - projectRoot, - }); - if (resolved === undefined) continue; - if (isSharedLibrary(path.basename(resolved), extension)) - found.add(resolved); - } - return [...found]; -} - -/** - * The library references in `otool -L` or `readelf -d` output. - * - * Pure, and separate from running the tool, because the two formats differ in - * the way that matters most: a Mach-O dependency names a path (`@rpath/foo`, - * `/abs/foo`), while an ELF `NEEDED` entry is a bare soname (`libjsi.so`) that - * says nothing about where the file came from. That difference is invisible to - * anyone developing on macOS, so it is tested against recorded output. - */ -export function parseSharedLibraryReferences(output, platform) { - const references = []; - for (const line of output.split('\n')) { - // `otool -L`: an indented path, then the compatibility version in parens. - // The first line is the binary's own path and must be ignored. - const machO = platform === 'darwin' ? line.match(/^\t(\S+)\s+\(/u) : null; - // `readelf -d`: `0x… (NEEDED) Shared library: [libjsi.so]`. - const elf = line.match(/NEEDED\)\s+Shared library: \[(\S+)\]/u); - const match = machO ?? elf; - if (match === null) continue; - if (!references.includes(match[1])) references.push(match[1]); - } - return references; -} - -/** - * `resolveLinkedLibrary`, exposed for tests. - * - * The bare-soname case only happens on Linux, where these tests cannot run, so - * the lookup has to be exercised from macOS against a synthesised build tree. - */ -export function resolveLinkedLibraryForTest(reference, projectRoot) { - return resolveLinkedLibrary(reference, { - binary: path.join(projectRoot, 'desktop', 'target', 'release', 'my-app'), - projectRoot, - }); -} - -/** - * Where a `@rpath`/`$ORIGIN` reference actually points, or `None` for a system - * library. - * - * The executable's own rpaths are what the loader uses, so they are what this - * walks. A reference into `/usr/lib` is the OS's to provide. - */ -function resolveLinkedLibrary(reference, { binary, projectRoot }) { - if (reference.startsWith('@rpath/')) { - const name = reference.slice('@rpath/'.length); - for (const rpath of rpathsOf(binary)) { - const candidate = path.join(rpath, name); - if (fs.existsSync(candidate)) return candidate; - } - // A packaging build carries only relative rpaths, so the absolute library - // directories are not in the file to be read back out. The directories the - // build recorded are, and they name the config it actually produced. - for (const directory of releaseLibraryDirectories(projectRoot)) { - const candidate = path.join(directory, name); - if (fs.existsSync(candidate)) return candidate; - } - return undefined; - } - if (reference.startsWith('$ORIGIN')) { - const candidate = path.join( - path.dirname(binary), - reference.slice('$ORIGIN/'.length), - ); - return fs.existsSync(candidate) ? candidate : undefined; - } - if (!path.isAbsolute(reference)) { - // ELF `NEEDED` entries are bare sonames (`libjsi.so`), not paths, so a Linux - // binary says nothing about where its libraries came from. Look for the name - // in the directories the build produced; a system library will not be there - // and is correctly skipped. - for (const directory of [ - // What the build recorded first — it names the prebuilt cache and the - // engine's own directory — then the release config's tree, then Cargo's - // release output. - ...releaseLibraryDirectories(projectRoot), - ...buildLibraryDirectories(projectRoot, { release: true }), - ]) { - const candidate = path.join(directory, reference); - if (fs.existsSync(candidate)) return candidate; - } - return undefined; - } - // A library under the repository belongs to the build; one under /usr or - // /System belongs to the OS. - if (reference.startsWith('/usr/') || reference.startsWith('/System/')) { - return undefined; - } - return reference.startsWith(projectRoot) ? reference : undefined; -} - -/** The rpaths a Mach-O binary carries, absolute entries only. */ -function rpathsOf(binary) { - let output; - try { - output = execFileSync('otool', ['-l', binary], { encoding: 'utf8' }); - } catch { - return []; - } - const out = []; - for (const line of output.split('\n')) { - const match = line.match(/^\s+path (\S+) \(offset/u); - if (match !== null && path.isAbsolute(match[1])) out.push(match[1]); - } - return out; -} - -/** - * The library directories the build itself recorded. - * - * `rn-gpui-sys` generates `rpath_dirs-.txt` while configuring CMake, and - * that list is what ends up in the executable's rpath. It is the only accurate - * answer: it names the *prebuilt* runtime's cache directory when the app used a - * prebuilt, and the Hermes binary directory, neither of which is under the build - * tree. Reading it is why a library cannot be missed by guessing at layouts. - */ -/// Where the CMake tree for this build lives. -/// -/// It sits beside the Cargo profile directory, so it moves with -/// `CARGO_TARGET_DIR`, which CI sets. -function cmakeRoot(projectRoot) { - return path.join( - path.dirname( - targetProfileDir(path.join(projectRoot, 'desktop'), 'release'), - ), - 'rn-gpui-cmake', - ); -} - -/** - * The release config directories under one triple. - * - * Only a release config may be searched: a `Debug` build's libraries are a - * different build, possibly against the other runtime, and a package that ships - * one is broken in a way no clean CI run can see — a fresh runner has only the - * single config it just built, while a developer's tree accumulates them all. - */ -function releaseConfigRoots(root) { - const found = []; - let triples; - try { - triples = fs.readdirSync(root, { withFileTypes: true }); - } catch { - return found; - } - for (const triple of triples) { - if (!triple.isDirectory()) continue; - const tripleDir = path.join(root, triple.name); - let configs; - try { - configs = fs.readdirSync(tripleDir, { withFileTypes: true }); - } catch { - continue; - } - for (const config of configs) { - if (config.isDirectory() && RELEASE_CONFIG.test(config.name)) { - found.push(path.join(tripleDir, config.name)); - } - } - } - // A prebuilt config first: it records the cache the package is actually - // linked against, so its answer outranks a source config's. - const rank = directory => (directory.endsWith('-prebuilt') ? 0 : 1); - return found.sort((a, b) => rank(a) - rank(b)); -} - -/** - * Every directory a release build may have put a shared library in. - * - * The recorded rpaths come first because they are the build's own answer, then - * the current release config's tree. Anything outside a release config is - * excluded on purpose — see `releaseConfigRoots`. - */ -export function releaseLibraryDirectories(projectRoot) { - return [ - ...recordedLibraryDirectories(projectRoot), - ...cmakeLibraryDirectories(projectRoot), - ]; -} - -export function recordedLibraryDirectories(projectRoot) { - const root = cmakeRoot(projectRoot); - const directories = []; - const candidates = releaseConfigRoots(root).flatMap(config => - walkDirectories(config), - ); - for (const file of candidates) { - let entries; - try { - entries = fs.readdirSync(file, { withFileTypes: true }); - } catch { - continue; - } - for (const entry of entries) { - if (!entry.isFile() || !/^rpath_dirs-.*\.txt$/u.test(entry.name)) - continue; - let text; - try { - text = fs.readFileSync(path.join(file, entry.name), 'utf8'); - } catch { - continue; - } - for (const line of text.split('\n')) { - const directory = line.trim(); - if (directory && !directories.includes(directory)) { - directories.push(directory); - } - } - } - } - return directories; -} - -/** - * Directories under the C++ build tree that hold its shared libraries. - * - * `libjsi` is built by CMake, not Cargo, so it is in neither the profile - * directory nor a crate's `out`: it sits under - * `/build/target/rn-gpui-cmake///build/...`. - */ -function cmakeLibraryDirectories(projectRoot) { - const found = []; - for (const configRoot of releaseConfigRoots(cmakeRoot(projectRoot))) { - // The libraries are at different depths per dependency, so walk. - for (const entry of walkDirectories(configRoot)) found.push(entry); - } - return found; -} - -/// A CMake config directory that produces a release binary. -/// -/// `Release-prebuilt` is what a prebuilt build configures (`-loom` for Loom's); `RelWithDebInfo` is -/// what an optimised build gets when debug info is kept. `Debug*` is excluded. -const RELEASE_CONFIG = /^(?:Release|RelWithDebInfo)(?:-loom)?(?:-prebuilt)?$/u; - -/** Every directory at or below `root`, breadth-first, bounded in depth. */ -function walkDirectories(root, depth = 0) { - if (depth > 5) return []; - const out = [root]; - let entries; - try { - entries = fs.readdirSync(root, { withFileTypes: true }); - } catch { - return out; - } - for (const entry of entries) { - if (entry.isDirectory()) - out.push(...walkDirectories(path.join(root, entry.name), depth + 1)); - } - return out; -} - -/** The executable's file name, from the desktop crate's Cargo.toml. */ -function executableName(projectRoot) { - try { - const manifest = fs.readFileSync( - path.join(projectRoot, 'desktop', 'Cargo.toml'), - 'utf8', - ); - return manifest.match(/^name\s*=\s*"([^"]+)"/mu)?.[1] ?? ''; - } catch { - return ''; - } -} - -function readManifest(file) { - try { - return JSON.parse(fs.readFileSync(file, 'utf8')); - } catch { - return undefined; - } -} - -/** - * Directories the build may have put shared libraries in. - * - * Both the crate's own target directory and the one Cargo was pointed at - * (`CARGO_TARGET_DIR`), because the CLI sets the latter for reproducible paths. - */ -export function buildLibraryDirectories(projectRoot, { release = true } = {}) { - const profile = release ? 'release' : 'debug'; - const crateDir = path.join(projectRoot, 'desktop'); - // `targetProfileDir` already applies `CARGO_TARGET_DIR` and the crate's own - // `target-dir`, so the other roots are only fallbacks for a library that - // landed somewhere less predictable. - const roots = [ - path.dirname(targetProfileDir(crateDir, profile)), - path.join(crateDir, 'target'), - path.join(projectRoot, 'target'), - ].filter(Boolean); - const directories = new Set(); - for (const root of roots) { - directories.add(path.join(root, profile)); - // The prebuilt runtime's shared library is placed under the sys crate's - // build output, which is keyed by a hash that is not predictable. - const buildRoot = path.join(root, profile, 'build'); - let entries; - try { - entries = fs.readdirSync(buildRoot, { withFileTypes: true }); - } catch { - continue; - } - for (const entry of entries) { - if (!entry.isDirectory()) continue; - directories.add(path.join(buildRoot, entry.name, 'out')); - } - } - return [...directories]; -} - -/// The cargo-packager version this CLI drives and installs. -/// -/// Pinned so a config written for one version is not silently handed to another: -/// the translator emits this version's schema, and an installed copy that differs -/// is replaced. -export const CARGO_PACKAGER_VERSION = '0.11.8'; - -/** - * Signing variables cargo-packager reads from the environment itself. - * - * Nothing here is ever written into a config file: the packager skips these - * fields when parsing JSON precisely so a secret cannot be committed, and this - * CLI passes its own environment through unchanged so setting one in the shell - * or in CI is all a user does. They are listed so a test can assert their values - * never reach the generated config. - */ -export const SIGNING_ENVIRONMENT = [ - 'APPLE_CERTIFICATE', - 'APPLE_CERTIFICATE_PASSWORD', - 'APPLE_SIGNING_IDENTITY', - 'APPLE_PROVIDER_SHORT_NAME', - 'APPLE_TEAM_ID', - 'APPLE_ID', - 'APPLE_PASSWORD', - 'APPLE_API_KEY', - 'APPLE_API_ISSUER', - 'APPLE_API_KEY_PATH', - 'WINDOWS_CERTIFICATE_THUMBPRINT', - 'WINDOWS_TIMESTAMP_SERVER_URL', - 'WINDOWS_TSP', -]; - -/** cargo-packager's name for each of this phase's formats. */ -const PACKAGER_FORMAT = { - app: 'app', - dmg: 'dmg', - nsis: 'nsis', - deb: 'deb', - appimage: 'appimage', -}; - -/** - * Where Cargo put the executable for a profile. - * - * The desktop crate's `.cargo/config.toml` redirects `target-dir` to - * `build/target`, so `target/release` does not exist. Reading the setting is the - * only way to be right for both layouts. - */ -export function targetProfileDir(crateDir, profile) { - // `CARGO_TARGET_DIR` overrides everything, and CI sets it so the build cache - // survives a deleted app folder. - if (process.env.CARGO_TARGET_DIR) { - return path.join(path.resolve(process.env.CARGO_TARGET_DIR), profile); - } - const compiledIn = path.join(crateDir, 'target', profile); - let config; - try { - config = fs.readFileSync( - path.join(crateDir, '.cargo', 'config.toml'), - 'utf8', - ); - } catch { - return compiledIn; - } - const match = config.match(/^\s*target-dir\s*=\s*"([^"]+)"/mu); - if (!match) return compiledIn; - // Cargo resolves a relative `target-dir` from the directory holding `.cargo/`, - // which is the crate, and it may climb out of the crate (`../../../target`). - return path.resolve(crateDir, match[1], profile); -} - -/** - * Translates `desktop.json` into cargo-packager's config. - * - * cargo-packager is an implementation detail: users never write its JSON, and - * replacing it would only change this function. Pure, so the whole translation - * is unit-testable without packaging anything. - * - * `build` carries what the caller observed — the crate directory, the - * executable's name, the directories holding the bundle and assets, the icon - * files and the libraries to ship — because none of that is in the config file. - */ -export function toPackagerConfig(config, build) { - const { - crateDir, - binaryName, - bundleDir, - assetsDir, - extraResources = [], - nodeAddonsDir, - icons = [], - libraries = [], - formats, - outDir, - os, - rpathDir, - } = build; - - // cargo-packager resolves paths relative to the crate directory, and its - // schema uses forward slashes on every platform. - const relative = absolute => - path.relative(crateDir, absolute).split(path.sep).join('/'); - - // The bundle and the assets travel as resources, so the release build's - // `resource_dir` finds them beside the executable. The bundle file and the - // assets directory are named separately rather than shipping the whole build - // directory, which holds the output of this very run. - const resources = []; - if (bundleDir !== undefined) { - // One file, one name. `package-desktop` stages it; there is no candidate list - // to get wrong, which is how a plain-JS bundle was shipped while the bytecode - // sat unused beside it. - const bundle = path.join(bundleDir, 'index.bundle'); - if (!fs.existsSync(bundle)) { - throw new Error(`the staged bundle is missing: ${bundle}`); - } - resources.push(relative(bundle)); - } - if (assetsDir !== undefined && fs.existsSync(assetsDir)) { - resources.push(relative(assetsDir)); - } - for (const resource of extraResources) resources.push(relative(resource)); - // Node addons keep their folder name, `node-addons`, and the libraries stay - // beside the addon that loads them: the runtime looks in - // `Resources/node-addons/` on macOS and `node-addons/` beside the - // executable elsewhere. - if (nodeAddonsDir !== undefined && fs.existsSync(nodeAddonsDir)) { - resources.push({ src: relative(nodeAddonsDir), target: 'node-addons' }); - } - // On Windows the runtime DLLs are already staged beside the executable by the - // app's build.rs, and the loader looks there — but NSIS installs only the - // binary and the resources, so "beside the executable" has to be expressed as - // resources or the DLLs are left behind. Elsewhere they are handled per format - // below (`Frameworks`, `lib/`). - if (os === 'windows') { - for (const library of libraries) resources.push(relative(library)); - } - for (const extra of config.bundle.resources ?? []) { - // `bundle.resources` is written relative to `desktop/`, which is the crate. - resources.push(relative(path.resolve(crateDir, extra))); - } - - const config_ = { - $schema: - 'https://raw.githubusercontent.com/crabnebula-dev/cargo-packager/dev/crates/packager/schema.json', - name: binaryName, - productName: config.productName, - version: config.version, - identifier: config.identifier, - // `binariesDir` is where the executables are; `outDir` is where the - // packages go. Without the first, cargo-packager looks for the binary - // inside the output directory. - binariesDir: targetProfileDir(crateDir, 'release'), - binaries: [{ path: binaryName, main: true }], - outDir: outDir ?? path.join(crateDir, 'build', 'dist'), - resources, - }; - if (formats !== undefined) { - config_.formats = formats.map(format => PACKAGER_FORMAT[format]); - } - if (icons.length > 0) config_.icons = icons; - if (config.bundle.copyright !== undefined) { - config_.copyright = config.bundle.copyright; - } - if (config.bundle.category !== undefined) { - config_.category = config.bundle.category; - } - - const macos = { - minimumSystemVersion: config.bundle.macos.minimumSystemVersion, - }; - // The linker's executable signature does not seal the packaged app's - // resources. Local macOS packages need a complete ad-hoc bundle signature. - if (os === 'macos') { - macos.signingIdentity = '-'; - // cargo-packager enables hardened runtime. Ad-hoc signatures have no Team - // ID, so library validation otherwise rejects even the bundled dylibs. - macos.entitlements = relative( - require.resolve('../templates/adhoc.entitlements.plist'), - ); - } - if (config.bundle.macos.entitlements !== null) { - macos.entitlements = relative( - path.resolve(process.cwd(), config.bundle.macos.entitlements), - ); - } - if (libraries.length > 0) { - // These are *source* paths, and absolute: cargo-packager copies each one - // into Contents/Frameworks, which is where the release build's - // `@executable_path/../Frameworks` rpath looks. They are absolute because a - // library can live outside the crate — the engine's come from its own - // package — and cargo-packager opens the string as given rather than - // resolving it against the config file. - macos.frameworks = libraries; - } - config_.macos = macos; - - if ((config.urlSchemes ?? []).length > 0) { - config_.deepLinkProtocols = [{ schemes: config.urlSchemes }]; - } - - if (config.bundle.windows.nsis !== undefined) { - config_.nsis = { installMode: config.bundle.windows.nsis.installMode }; - } - - // Linux keeps its libraries under `lib/`, which is where the release - // build's `$ORIGIN/../lib/` rpath looks. Both Linux formats map a - // source path to a destination inside the package, so the library goes to - // that directory rather than wherever resources land by default. - if (libraries.length > 0) { - // The two Linux formats need different directories, because they find - // libraries differently: - // - the deb installs to `usr/lib/`, which is where the release build's - // `$ORIGIN/../lib/` rpath looks; - // - the AppImage's `AppRun` puts `$APPDIR/usr/lib` on the library path, and - // `linuxdeploy` resolves the executable's dependencies from there before - // the bundle is assembled. A library one directory deeper is reported as - // `Could not find dependency`, which is how this was found. - const debFiles = {}; - const appimageFiles = {}; - for (const library of libraries) { - const name = path.basename(library); - // `rpathDir` is the directory the release build's rpath actually names, - // which is the app name from `app.json` — not the crate name and not - // `productName`. Using anything else installs the libraries one directory - // away from where the binary looks, and it fails to start. - debFiles[library] = `/usr/lib/${rpathDir}/${name}`; - appimageFiles[library] = `/usr/lib/${name}`; - } - config_.deb = { ...(config_.deb ?? {}), files: debFiles }; - config_.appimage = { files: appimageFiles }; - } - if (config.bundle.linux.deb.depends.length > 0) { - config_.deb = { - ...(config_.deb ?? {}), - depends: config.bundle.linux.deb.depends, - }; - } - - return config_; -} diff --git a/vendor/react-native-gpui/packages/cli/src/package-desktop.test.js b/vendor/react-native-gpui/packages/cli/src/package-desktop.test.js deleted file mode 100644 index 43e41b6e41..0000000000 --- a/vendor/react-native-gpui/packages/cli/src/package-desktop.test.js +++ /dev/null @@ -1,779 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, describe, expect, test } from 'vitest'; -import { - buildLibraryDirectories, - CARGO_PACKAGER_VERSION, - SIGNING_ENVIRONMENT, - libraryExtension, - parseSharedLibraryReferences, - recordedLibraryDirectories, - releaseLibraryDirectories, - resolveLinkedLibraryForTest, - runtimeLibraries, - vcRuntimeLibraries, - targetProfileDir, - toPackagerConfig, -} from './package-desktop.js'; - -const roots = []; - -afterEach(() => { - while (roots.length > 0) { - fs.rmSync(roots.pop(), { recursive: true, force: true }); - } -}); - -/** A project with an autolink manifest and whatever files are asked for. */ -function createProject({ engines = [], files = {} } = {}) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'rn-gpui-package-')); - roots.push(root); - write(root, 'package.json', { name: 'my-app' }); - if (engines.length > 0) { - write(root, 'desktop/autolink/autolink.json', { jsEngines: engines }); - } - for (const [relative, contents] of Object.entries(files)) { - write(root, relative, contents); - } - return root; -} - -function write(root, relative, contents) { - const target = path.join(root, relative); - fs.mkdirSync(path.dirname(target), { recursive: true }); - fs.writeFileSync( - target, - typeof contents === 'string' - ? contents - : `${JSON.stringify(contents, null, 2)}\n`, - ); -} - -describe('libraryExtension', () => { - test('each OS has its own shared-library extension', () => { - expect(libraryExtension('macos')).toBe('.dylib'); - expect(libraryExtension('windows')).toBe('.dll'); - expect(libraryExtension('linux')).toBe('.so'); - }); -}); - -describe('runtimeLibraries', () => { - test('an engine that names its own files is read from its module', () => { - const root = createProject(); - const engineDir = path.join(root, 'engine'); - fs.mkdirSync(engineDir, { recursive: true }); - const library = path.join(engineDir, 'libhermesvm.dylib'); - fs.writeFileSync(library, 'x'); - fs.writeFileSync( - path.join(engineDir, 'runtime-files.js'), - `const path = require('node:path'); - module.exports = (platform) => - platform === 'darwin' ? [path.join(__dirname, 'libhermesvm.dylib')] : []; - `, - ); - write(root, 'desktop/autolink/autolink.json', { - jsEngines: [ - { - name: 'hermes', - runtimeFiles: path.join(engineDir, 'runtime-files.js'), - }, - ], - }); - - // The engine resolves its own directory, which on macOS reaches the same - // file through the `/var` -> `/private/var` symlink. - const libs = runtimeLibraries(root, { os: 'darwin', arch: 'arm64' }); - expect(libs.map(file => fs.realpathSync(file))).toContain( - fs.realpathSync(library), - ); - }); - - test('a library the engine does not name for this platform is skipped', () => { - const root = createProject(); - const engineDir = path.join(root, 'engine'); - fs.mkdirSync(engineDir, { recursive: true }); - fs.writeFileSync(path.join(engineDir, 'libhermesvm.dylib'), 'x'); - fs.writeFileSync( - path.join(engineDir, 'runtime-files.js'), - `const path = require('node:path'); - module.exports = (platform) => - platform === 'darwin' ? [path.join(__dirname, 'libhermesvm.dylib')] : []; - `, - ); - write(root, 'desktop/autolink/autolink.json', { - jsEngines: [ - { - name: 'hermes', - runtimeFiles: path.join(engineDir, 'runtime-files.js'), - }, - ], - }); - - expect(runtimeLibraries(root, { os: 'win32', arch: 'x64' })).toEqual([]); - }); - - test('shared libraries the build produced are found beside the target', () => { - const root = createProject(); - write(root, 'desktop/target/release/libruntime.dylib', 'x'); - write(root, 'desktop/target/release/notes.txt', 'not a library'); - const libs = runtimeLibraries(root, { os: 'darwin', arch: 'arm64' }); - expect(libs.map(file => path.basename(file))).toEqual(['libruntime.dylib']); - }); - - test('the sys crate build output is scanned, keyed by its hash', () => { - const root = createProject(); - write( - root, - 'desktop/target/release/build/rn-gpui-sys-abc123/out/libjsi.dylib', - 'x', - ); - const libs = runtimeLibraries(root, { os: 'darwin', arch: 'arm64' }); - expect(libs.map(file => path.basename(file))).toEqual(['libjsi.dylib']); - }); - - test('a versioned Linux library counts as a library', () => { - const root = createProject(); - write(root, 'desktop/target/release/libfoo.so.1.2.3', 'x'); - write(root, 'desktop/target/release/libfoo.so', 'x'); - const libs = runtimeLibraries(root, { os: 'linux', arch: 'x64' }); - expect(libs.map(file => path.basename(file)).sort()).toEqual([ - 'libfoo.so', - 'libfoo.so.1.2.3', - ]); - }); - - test('a library for another OS is not shipped', () => { - const root = createProject(); - write(root, 'desktop/target/release/libfoo.dylib', 'x'); - expect(runtimeLibraries(root, { os: 'win32', arch: 'x64' })).toEqual([]); - }); - - test('a debug build reads the debug profile', () => { - const root = createProject(); - write(root, 'desktop/target/debug/libruntime.dylib', 'x'); - write(root, 'desktop/target/release/librelease.dylib', 'x'); - expect( - runtimeLibraries(root, { - os: 'darwin', - arch: 'arm64', - release: false, - }).map(file => path.basename(file)), - ).toEqual(['libruntime.dylib']); - }); - - test('a project with no autolink manifest ships no engine files', () => { - const root = createProject(); - expect(runtimeLibraries(root, { os: 'darwin', arch: 'arm64' })).toEqual([]); - }); - - test('the same library named twice is shipped once', () => { - const root = createProject(); - write(root, 'desktop/target/release/libfoo.dylib', 'x'); - const libs = runtimeLibraries(root, { os: 'darwin', arch: 'arm64' }); - expect(new Set(libs).size).toBe(libs.length); - }); -}); - -describe('buildLibraryDirectories', () => { - test('the release and debug profiles are distinct', () => { - const root = createProject(); - expect(buildLibraryDirectories(root, { release: true })[0]).toContain( - path.join('desktop', 'target', 'release'), - ); - expect(buildLibraryDirectories(root, { release: false })[0]).toContain( - path.join('desktop', 'target', 'debug'), - ); - }); -}); - -// The translator is the whole reason cargo-packager is an implementation -// detail: these hold what it emits for one config, so replacing the packager -// only changes one function and one set of expectations. -test('every package ships an icon', () => { - // cargo-packager's AppImage step refuses to build without a square icon, so - // the CLI always supplies one: the app's, or its own placeholder. An app that - // never set `icon` still packages every format. - const withIcon = icons => - toPackagerConfig( - { - productName: 'A', - identifier: 'com.a.b', - version: '1.0.0', - bundle: { - resources: [], - macos: { minimumSystemVersion: '13.0', entitlements: null }, - windows: {}, - linux: { deb: { depends: [] }, appimage: {} }, - }, - }, - { crateDir: '/p/desktop', binaryName: 'a', icons }, - ); - - expect(withIcon(['build/icons/icon.png']).icons).toEqual([ - 'build/icons/icon.png', - ]); - expect(withIcon(['assets/icon.png']).icons).toEqual(['assets/icon.png']); -}); - -test('the packager version is pinned to one release', () => { - // The translator emits this version's schema, and `ensureCargoPackager` - // installs it, so the two cannot drift apart. - expect(CARGO_PACKAGER_VERSION).toMatch(/^\d+\.\d+\.\d+$/u); -}); - -describe('toPackagerConfig', () => { - const desktopConfig = overrides => { - const { bundle: bundleOverrides, ...rest } = overrides ?? {}; - return { - productName: 'My App', - identifier: 'com.example.myapp', - version: '1.2.3', - window: { width: 1024, height: 768 }, - devMenu: true, - ...rest, - bundle: { - targets: 'all', - resources: [], - macos: { - minimumSystemVersion: '13.0', - entitlements: null, - infoPlist: {}, - }, - windows: { nsis: { installMode: 'currentUser' } }, - linux: { deb: { depends: [] }, appimage: {} }, - ...bundleOverrides, - }, - }; - }; - const build = overrides => ({ - crateDir: '/project/desktop', - binaryName: 'my-app', - formats: ['app', 'dmg'], - ...overrides, - }); - - test("what a package's bundle hook produced ships as a resource", () => { - const config = toPackagerConfig( - desktopConfig(), - build({ - extraResources: ['/project/desktop/build/package/workers'], - }), - ); - expect(config.resources).toContain('build/package/workers'); - }); - - test('url schemes become deep link protocols, which register them per OS', () => { - const config = toPackagerConfig( - desktopConfig({ urlSchemes: ['myapp'] }), - build(), - ); - expect(config.deepLinkProtocols).toEqual([{ schemes: ['myapp'] }]); - expect( - toPackagerConfig(desktopConfig(), build()).deepLinkProtocols, - ).toBeUndefined(); - }); - - test('a minimal app gives the fields cargo-packager needs', () => { - const config = toPackagerConfig(desktopConfig(), build()); - expect(config.productName).toBe('My App'); - expect(config.identifier).toBe('com.example.myapp'); - expect(config.version).toBe('1.2.3'); - expect(config.binariesDir).toBe('/project/desktop/target/release'); - expect(config.binaries).toEqual([{ path: 'my-app', main: true }]); - expect(config.formats).toEqual(['app', 'dmg']); - expect(config.outDir).toBe('/project/desktop/build/dist'); - }); - - test('the bundle file and the assets directory ship as resources', () => { - // A directory containing this run's output cannot be shipped, so the two - // are named. The asset directory has to exist to be listed. - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'rn-gpui-res-')); - roots.push(root); - const crateDir = path.join(root, 'desktop'); - fs.mkdirSync(path.join(crateDir, 'build', 'assets'), { recursive: true }); - fs.writeFileSync(path.join(crateDir, 'build', 'index.bundle'), 'x'); - const config = toPackagerConfig( - desktopConfig(), - build({ - crateDir, - bundleDir: path.join(crateDir, 'build'), - assetsDir: path.join(crateDir, 'build', 'assets'), - }), - ); - expect(config.resources).toEqual(['build/index.bundle', 'build/assets']); - }); - - test('macOS packages seal the app with an ad-hoc signature', () => { - const config = toPackagerConfig(desktopConfig(), build({ os: 'macos' })); - expect(config.macos.signingIdentity).toBe('-'); - }); - - test('ad-hoc macOS apps can load their bundled libraries without a Team ID', () => { - const context = build({ os: 'macos' }); - const config = toPackagerConfig(desktopConfig(), context); - expect(config.macos.entitlements).toBeTypeOf('string'); - const entitlements = fs.readFileSync( - path.resolve(context.crateDir, config.macos.entitlements), - 'utf8', - ); - expect(entitlements).toMatch( - /com\.apple\.security\.cs\.disable-library-validation<\/key>\s*/u, - ); - }); - - test('collected Node addons ship as the node-addons resource folder', () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'rn-gpui-res-')); - roots.push(root); - const crateDir = path.join(root, 'desktop'); - const addons = path.join(crateDir, 'build', 'node-addons'); - fs.mkdirSync(addons, { recursive: true }); - fs.writeFileSync(path.join(crateDir, 'build', 'index.bundle'), 'x'); - const config = toPackagerConfig( - desktopConfig(), - build({ - crateDir, - bundleDir: path.join(crateDir, 'build'), - nodeAddonsDir: addons, - }), - ); - expect(config.resources).toEqual([ - 'build/index.bundle', - { src: 'build/node-addons', target: 'node-addons' }, - ]); - }); - - test('a missing staged bundle is an error, not a silent omission', () => { - // A package without its bundle starts and then dies on a machine with no - // build tree, so the failure belongs here rather than at first launch. - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'rn-gpui-res-')); - roots.push(root); - const crateDir = path.join(root, 'desktop'); - fs.mkdirSync(path.join(crateDir, 'build'), { recursive: true }); - expect(() => - toPackagerConfig( - desktopConfig(), - build({ crateDir, bundleDir: path.join(crateDir, 'build') }), - ), - ).toThrow(/staged bundle is missing/u); - }); - - test('extra resources are relative to the crate', () => { - const config = toPackagerConfig( - desktopConfig({ bundle: { resources: ['extra/data.json'] } }), - build(), - ); - expect(config.resources).toEqual(['extra/data.json']); - }); - - test('runtime libraries become macOS frameworks, by source path', () => { - // cargo-packager copies each entry into Contents/Frameworks itself, so the - // entry is where the library is, not where it lands. - const config = toPackagerConfig( - desktopConfig(), - build({ libraries: ['/project/desktop/build/libjsi.dylib'] }), - ); - expect(config.macos.frameworks).toEqual([ - '/project/desktop/build/libjsi.dylib', - ]); - }); - - test('runtime libraries get the directory each Linux format searches', () => { - // The deb installs to `usr/lib/`, where the binary's - // `$ORIGIN/../lib/` rpath looks. The AppImage needs flat `usr/lib`, - // which is what AppRun puts on the library path and where linuxdeploy looks - // when resolving the executable's dependencies. - const config = toPackagerConfig( - desktopConfig(), - build({ rpathDir: 'My App', libraries: ['/build/libjsi.so'] }), - ); - // `rpathDir` is the app name the rpath names, not the crate name: the - // libraries have to land where the binary actually looks. - expect(config.deb.files).toEqual({ - '/build/libjsi.so': '/usr/lib/My App/libjsi.so', - }); - expect(config.appimage.files).toEqual({ - '/build/libjsi.so': '/usr/lib/libjsi.so', - }); - }); - - test('Windows ships the DLLs as resources', () => { - // NSIS installs the binary and the resources, not the profile directory - // beside the executable, so the DLLs have to be resources or they are left - // behind and the app fails to start. - const config = toPackagerConfig( - desktopConfig(), - build({ - os: 'windows', - crateDir: '/project/desktop', - libraries: ['/project/desktop/build/hermesvm.dll'], - }), - ); - expect(config.resources).toContain('build/hermesvm.dll'); - }); - - test('macOS and Linux do not ship libraries as resources', () => { - for (const platform of ['macos', 'linux']) { - const config = toPackagerConfig( - desktopConfig(), - build({ - os: platform, - libraries: ['/project/desktop/build/libjsi.dylib'], - }), - ); - expect(config.resources).not.toContain('build/libjsi.dylib'); - } - }); - - test('no libraries means no empty framework or files block', () => { - const config = toPackagerConfig(desktopConfig(), build()); - expect(config.macos.frameworks).toBeUndefined(); - expect(config.deb).toBeUndefined(); - expect(config.appimage).toBeUndefined(); - }); - - test('the NSIS install mode is carried over', () => { - const config = toPackagerConfig( - desktopConfig({ - bundle: { windows: { nsis: { installMode: 'perMachine' } } }, - }), - build({ formats: ['nsis'] }), - ); - expect(config.nsis).toEqual({ installMode: 'perMachine' }); - }); - - test('Debian dependencies are carried over', () => { - const config = toPackagerConfig( - desktopConfig({ - bundle: { linux: { deb: { depends: ['libgtk-3-0'] } } }, - }), - build({ formats: ['deb'] }), - ); - expect(config.deb.depends).toEqual(['libgtk-3-0']); - }); - - test('a copyright and category reach the output when set', () => { - const config = toPackagerConfig( - desktopConfig({ - bundle: { copyright: '© 2026 Me', category: 'DeveloperTool' }, - }), - build(), - ); - expect(config.copyright).toBe('© 2026 Me'); - expect(config.category).toBe('DeveloperTool'); - }); - - // D6: signing material comes from the environment, so no value of it may - // appear in the generated config, whatever the caller's environment holds. - test('no signing material appears in the output', () => { - const saved = new Map(); - for (const name of SIGNING_ENVIRONMENT) { - saved.set(name, process.env[name]); - process.env[name] = `SECRET-${name}`; - } - try { - const text = JSON.stringify( - toPackagerConfig( - desktopConfig(), - build({ libraries: ['/b/lib.dylib'] }), - ), - ); - for (const name of SIGNING_ENVIRONMENT) { - expect(text).not.toContain(`SECRET-${name}`); - } - // Nor may the variable names themselves appear: a config naming a - // credential is a config someone will fill in. - for (const name of SIGNING_ENVIRONMENT) { - expect(text).not.toContain(name); - } - } finally { - for (const [name, value] of saved) { - if (value === undefined) delete process.env[name]; - else process.env[name] = value; - } - } - }); - - test('paths use forward slashes on every platform', () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'rn-gpui-slash-')); - roots.push(root); - const crateDir = path.join(root, 'desktop'); - fs.mkdirSync(path.join(crateDir, 'build'), { recursive: true }); - fs.writeFileSync(path.join(crateDir, 'build', 'index.bundle'), 'x'); - const config = toPackagerConfig( - desktopConfig(), - build({ crateDir, bundleDir: path.join(crateDir, 'build') }), - ); - for (const entry of [ - ...config.resources, - ...config.binaries.map(binary => binary.path), - ]) { - expect(entry).not.toContain('\\'); - } - }); -}); - -describe('targetProfileDir', () => { - test('CARGO_TARGET_DIR wins over everything', () => { - // CI sets it so the Cargo cache survives a deleted app directory; a config - // that ignored it looked for the binary in a tree that does not exist. - const root = createProject(); - const saved = process.env.CARGO_TARGET_DIR; - process.env.CARGO_TARGET_DIR = '/ci/target'; - try { - expect(targetProfileDir(path.join(root, 'desktop'), 'release')).toBe( - path.join('/ci/target', 'release'), - ); - } finally { - if (saved === undefined) delete process.env.CARGO_TARGET_DIR; - else process.env.CARGO_TARGET_DIR = saved; - } - }); - - test('a crate with no cargo config uses target/', () => { - const root = createProject(); - expect(targetProfileDir(path.join(root, 'desktop'), 'release')).toBe( - path.join(root, 'desktop', 'target', 'release'), - ); - }); - - test("the crate's target-dir setting wins", () => { - // The scaffold redirects `target-dir` to `build/target` so build output does - // not sit beside the sources; `target/release` then does not exist at all. - const root = createProject({ - files: { - 'desktop/.cargo/config.toml': '[build]\ntarget-dir = "build/target"\n', - }, - }); - expect(targetProfileDir(path.join(root, 'desktop'), 'release')).toBe( - path.join(root, 'desktop', 'build', 'target', 'release'), - ); - }); - - test("the crate's target-dir may climb to a shared root target", () => { - // The tester desktop shares the repository's one `target/` by climbing out - // of its crate; resolving that from the crate is what finds the binary. - const root = createProject({ - files: { - 'desktop/.cargo/config.toml': - '[build]\ntarget-dir = "../../../target"\n', - }, - }); - expect(targetProfileDir(path.join(root, 'desktop'), 'release')).toBe( - path.resolve(root, 'desktop', '../../../target', 'release'), - ); - }); -}); - -// The Linux failure this covers was invisible from macOS for a whole round: an -// ELF `NEEDED` entry is a bare soname, so it must be resolved by searching the -// build, while a Mach-O dependency names its own path. -describe('parseSharedLibraryReferences', () => { - const readelf = ` - 0x0000000000000001 (NEEDED) Shared library: [libjsi.so] - 0x0000000000000001 (NEEDED) Shared library: [libhermesvm.so] - 0x0000000000000001 (NEEDED) Shared library: [libgtk-3.so.0] - 0x000000000000001d (RUNPATH) Library runpath: [$ORIGIN/../lib/my-app] -`; - - test('ELF NEEDED entries come back as bare sonames', () => { - expect(parseSharedLibraryReferences(readelf, 'linux')).toEqual([ - 'libjsi.so', - 'libhermesvm.so', - 'libgtk-3.so.0', - ]); - }); - - test('a RUNPATH line is not mistaken for a library', () => { - expect( - parseSharedLibraryReferences(readelf, 'linux').some(reference => - reference.includes('ORIGIN'), - ), - ).toBe(false); - }); - - test("otool's first line is the binary itself, not a dependency", () => { - const otool = [ - '/build/app/Contents/MacOS/app:', - '\t@rpath/libjsi.dylib (compatibility version 0.0.0, current version 0.0.0)', - '\t/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1319.0.0)', - ].join('\n'); - expect(parseSharedLibraryReferences(otool, 'darwin')).toEqual([ - '@rpath/libjsi.dylib', - '/usr/lib/libSystem.B.dylib', - ]); - }); - - test('a repeated dependency is listed once', () => { - const repeated = `${readelf}\n 0x0 (NEEDED) Shared library: [libjsi.so]`; - expect( - parseSharedLibraryReferences(repeated, 'linux').filter( - reference => reference === 'libjsi.so', - ), - ).toHaveLength(1); - }); -}); - -test('a bare soname is found in the CMake tree, and a system library is not', () => { - // The resolver cannot shell out to readelf on macOS, so the lookup it performs - // for a bare ELF name is tested directly. The layout is the scaffolded one: - // `.cargo/config.toml` redirects target-dir to `build/target`, and the C++ - // runtime's libraries are under `rn-gpui-cmake///...`. - const libjsi = - 'desktop/build/target/rn-gpui-cmake/x86_64-unknown-linux-gnu/Release/build/ReactCommon/jsi/libjsi.so'; - const root = createProject({ - files: { - 'desktop/.cargo/config.toml': '[build]\ntarget-dir = "build/target"\n', - 'desktop/Cargo.toml': '[package]\nname = "my-app"\nversion = "0.1.0"\n', - [libjsi]: 'x', - }, - }); - expect(resolveLinkedLibraryForTest('libjsi.so', root)).toBe( - path.join(root, libjsi), - ); - // A library the OS provides must not be shipped. - expect(resolveLinkedLibraryForTest('libgtk-3.so.0', root)).toBeUndefined(); -}); - -describe('recordedLibraryDirectories', () => { - test('the directories CMake recorded are read back', () => { - // The build writes `rpath_dirs-.txt` while configuring, and that list - // becomes the executable's rpath. It is the only source that names the - // prebuilt runtime's cache, which is not under the build tree at all. - const root = createProject({ - files: { - 'desktop/.cargo/config.toml': '[build]\ntarget-dir = "build/target"\n', - 'desktop/build/target/rn-gpui-cmake/x86_64-unknown-linux-gnu/Release/build/rpath_dirs-Release.txt': - '/opt/prebuilt/0.0.3/linux-x64/lib\n/opt/hermes/bin/linux-x64\n', - }, - }); - expect(recordedLibraryDirectories(root)).toEqual([ - '/opt/prebuilt/0.0.3/linux-x64/lib', - '/opt/hermes/bin/linux-x64', - ]); - }); - - test('a project with no build yet records nothing', () => { - expect(recordedLibraryDirectories(createProject())).toEqual([]); - }); -}); - -test('a prebuilt-only library is found through the recorded directories', () => { - // The case that failed on Linux: the app uses the prebuilt runtime, so - // `libjsi.so` exists only in the prebuilt cache, outside both the project and - // the build tree. The recorded rpath list is what makes it findable. - const root = createProject({ - files: { - 'desktop/.cargo/config.toml': '[build]\ntarget-dir = "build/target"\n', - 'desktop/Cargo.toml': '[package]\nname = "my-app"\nversion = "0.1.0"\n', - }, - }); - const cache = path.join(root, 'prebuilt-cache', 'linux-x64', 'lib'); - fs.mkdirSync(cache, { recursive: true }); - const library = path.join(cache, 'libjsi.so'); - fs.writeFileSync(library, 'x'); - write( - root, - 'desktop/build/target/rn-gpui-cmake/x86_64-unknown-linux-gnu/Release/build/rpath_dirs-Release.txt', - `${cache}\n`, - ); - expect(resolveLinkedLibraryForTest('libjsi.so', root)).toBe(library); -}); - -describe('a package only ships libraries from its own release build', () => { - // A clean runner has one config, so this cannot show up on CI. A developer's - // tree accumulates Debug, Release and both -prebuilt variants; the first match - // used to win and Debug sorts first, so a release package could pick up a Debug - // library, or one built against the other runtime. - function projectWithBothConfigs() { - const root = createProject({ - files: { - 'desktop/.cargo/config.toml': '[build]\ntarget-dir = "build/target"\n', - 'desktop/Cargo.toml': '[package]\nname = "my-app"\nversion = "0.1.0"\n', - // A Debug library, and a Release one, at the same relative depth. - 'desktop/build/target/rn-gpui-cmake/x86_64-unknown-linux-gnu/Debug/build/ReactCommon/jsi/libjsi.so': - 'debug', - 'desktop/build/target/rn-gpui-cmake/x86_64-unknown-linux-gnu/Release/build/ReactCommon/jsi/libjsi.so': - 'release', - }, - }); - return root; - } - - test('the Debug copy is not found', () => { - const root = projectWithBothConfigs(); - const found = resolveLinkedLibraryForTest('libjsi.so', root); - expect(found).toBeDefined(); - expect(found).toContain('Release'); - expect(found).not.toContain('Debug'); - }); - - test('every directory offered to the resolver is a release config', () => { - const root = projectWithBothConfigs(); - for (const directory of releaseLibraryDirectories(root)) { - expect(directory).not.toMatch(/[/\\]Debug/u); - } - }); - - test('Release-prebuilt outranks Release', () => { - const root = createProject({ - files: { - 'desktop/.cargo/config.toml': '[build]\ntarget-dir = "build/target"\n', - 'desktop/build/target/rn-gpui-cmake/x86_64-unknown-linux-gnu/Release/build/rpath_dirs-Release.txt': - '/from/release\n', - 'desktop/build/target/rn-gpui-cmake/x86_64-unknown-linux-gnu/Release-prebuilt/build/rpath_dirs-Release.txt': - '/from/release-prebuilt\n', - }, - }); - expect(recordedLibraryDirectories(root)[0]).toBe('/from/release-prebuilt'); - }); -}); - -test('a library reached by two paths is shipped once', () => { - // The prebuilt cache and the CMake tree can both hold the same engine library. - // The packaging configs map each entry to a destination by file name, so a - // second entry would target the same file twice. - const root = createProject({ - files: { - 'desktop/.cargo/config.toml': '[build]\ntarget-dir = "build/target"\n', - 'desktop/Cargo.toml': '[package]\nname = "my-app"\nversion = "0.1.0"\n', - 'desktop/target/release/libfoo.dylib': 'x', - 'desktop/build/target/release/libfoo.dylib': 'x', - }, - }); - const names = runtimeLibraries(root, { os: 'darwin', arch: 'arm64' }).map( - file => path.basename(file), - ); - expect(names.filter(name => name === 'libfoo.dylib')).toHaveLength(1); -}); - -describe('vcRuntimeLibraries', () => { - it('finds the CRT DLLs of the newest installed toolset', () => { - const base = fs.mkdtempSync(path.join(os.tmpdir(), 'vcredist-')); - const crt = version => - path.join( - base, - 'Microsoft Visual Studio', - '2022', - 'Enterprise', - 'VC', - 'Redist', - 'MSVC', - version, - 'x64', - 'Microsoft.VC143.CRT', - ); - for (const version of ['14.40.1', '14.44.2']) { - fs.mkdirSync(crt(version), { recursive: true }); - fs.writeFileSync(path.join(crt(version), 'vcruntime140.dll'), ''); - fs.writeFileSync(path.join(crt(version), 'msvcp140.dll'), ''); - } - const found = vcRuntimeLibraries({ arch: 'x64', env: {}, roots: [base] }); - expect(found.map(file => path.basename(file))).toEqual([ - 'msvcp140.dll', - 'vcruntime140.dll', - ]); - expect(found[0]).toContain('14.44.2'); - expect(vcRuntimeLibraries({ arch: 'x64', env: {}, roots: [] })).toEqual([]); - }); -}); diff --git a/vendor/react-native-gpui/packages/cli/src/target-gc.js b/vendor/react-native-gpui/packages/cli/src/target-gc.js deleted file mode 100644 index 38117f6d42..0000000000 --- a/vendor/react-native-gpui/packages/cli/src/target-gc.js +++ /dev/null @@ -1,420 +0,0 @@ -/** - * Keeps a Cargo target directory from growing without bound. - * - * Cargo never deletes anything from a target directory on its own. Every change - * that alters a unit's hash — a feature toggled, a dependency bumped, a new - * toolchain, an environment variable a build script tracks — leaves the old - * unit beside the new one, and incremental caches stay behind for crates that - * are no longer rebuilt. Over weeks of development that is tens of gigabytes. - * - * So the CLI records which units each build used — Cargo reports every one, - * fresh or rebuilt, as JSON — and before a build removes units no recorded build - * has used for a while. Access times cannot stand in for the record: Windows - * does not update them by default, and a fresh unit is never written to. - * - * A unit with no record — built by a plain `cargo` command, or by a workspace - * that shares the directory without going through this CLI — is only removed - * once a newer unit of the same crate and kind has replaced it, so a build the - * CLI never saw is not thrown away just for being old. - * - * @format - */ - -import fs from 'node:fs'; -import path from 'node:path'; -import readline from 'node:readline'; -import { execFileSync, spawn } from 'node:child_process'; - -export const DEFAULT_MAX_AGE_DAYS = 7; -/** How long a unit or cache that something newer has replaced is kept. */ -export const DEFAULT_SUPERSEDED_DAYS = 1; -const DAY_MS = 24 * 60 * 60 * 1000; - -/** - * The target directory Cargo will build `manifest` into, or `null`. - * - * Asked of Cargo rather than worked out here: `CARGO_TARGET_DIR`, the crate's - * own `.cargo/config.toml` and any parent directory's config all decide it. - */ -export function cargoTargetDirectory(manifest, { cwd, env } = {}) { - try { - const metadata = JSON.parse( - execFileSync( - 'cargo', - [ - 'metadata', - '--no-deps', - '--format-version', - '1', - '--manifest-path', - manifest, - ], - { - cwd, - env, - encoding: 'utf8', - stdio: ['ignore', 'pipe', 'ignore'], - maxBuffer: 64 * 1024 * 1024, - }, - ), - ); - return path.resolve(metadata.target_directory); - } catch { - return null; - } -} - -/** Where the record of used units lives, inside the target directory. */ -export const USAGE_FILE = '.rn-gpui-target-usage.json'; - -/** `-`, as Cargo names a unit's fingerprint and build directory. */ -const UNIT_DIR = /^(.+)-([0-9a-f]{16})$/u; -/** The hash in a file under `deps/`: `libfoo-.rlib`, `foo-.exe`. */ -const HASHED_FILE = /-([0-9a-f]{16})(?:\.|$)/u; - -/** Whether the collector runs: never in CI, and never when turned off. */ -export function targetGcEnabled(env = process.env) { - return !env.CI && env.RN_GPUI_TARGET_GC !== '0'; -} - -/** How many days an unused unit is kept, from `RN_GPUI_TARGET_GC_DAYS`. */ -export function targetGcMaxAgeDays(env = process.env) { - const days = Number(env.RN_GPUI_TARGET_GC_DAYS); - return Number.isFinite(days) && days > 0 ? days : DEFAULT_MAX_AGE_DAYS; -} - -/** - * How many days a superseded unit is kept, from - * `RN_GPUI_TARGET_GC_SUPERSEDED_DAYS`. - */ -export function targetGcSupersededDays(env = process.env) { - const days = Number(env.RN_GPUI_TARGET_GC_SUPERSEDED_DAYS); - return Number.isFinite(days) && days > 0 ? days : DEFAULT_SUPERSEDED_DAYS; -} - -/** - * The usage key of the unit a build output belongs to, or `null`. - * - * Keyed by the profile directory and the hash, which together name one unit: - * `debug/0123456789abcdef`. The hash is shared by the unit's fingerprint - * directory, its `build/` directory and its files in `deps/`. - */ -export function unitKey(targetDir, file) { - const parts = path.relative(targetDir, file).split(/[\\/]/u); - const at = parts.findIndex(part => - ['deps', 'build', 'examples', '.fingerprint'].includes(part), - ); - if (at <= 0 || at + 1 >= parts.length) return null; - const profile = parts.slice(0, at).join('/'); - const entry = parts[at + 1]; - const match = - parts[at] === 'build' || parts[at] === '.fingerprint' - ? UNIT_DIR.exec(entry) - : HASHED_FILE.exec(entry); - if (!match) return null; - const hash = match[match.length - 1]; - return `${profile}/${hash}`; -} - -function readUsage(targetDir) { - try { - const parsed = JSON.parse( - fs.readFileSync(path.join(targetDir, USAGE_FILE), 'utf8'), - ); - if (parsed && typeof parsed.units === 'object') return parsed; - } catch {} - return { version: 1, units: {} }; -} - -function writeUsage(targetDir, usage) { - try { - fs.writeFileSync(path.join(targetDir, USAGE_FILE), JSON.stringify(usage)); - } catch { - // The record only makes pruning more precise; a build never fails over it. - } -} - -/** Marks every unit the given build outputs belong to as used `now`. */ -export function recordUsage(targetDir, files, now = Date.now()) { - if (!fs.existsSync(targetDir)) return; - const usage = readUsage(targetDir); - for (const file of files) { - const key = unitKey(targetDir, file); - if (key) usage.units[key] = now; - } - writeUsage(targetDir, usage); -} - -/** - * The profile directories in a target directory: each one holds `.fingerprint`. - * A host build puts them at `/`, a cross build at - * `//`. - */ -function profileDirs(targetDir) { - const found = []; - const visit = (relative, depth) => { - const absolute = path.join(targetDir, relative); - if (fs.existsSync(path.join(absolute, '.fingerprint'))) { - found.push(relative); - return; - } - if (depth === 0) return; - let entries = []; - try { - entries = fs.readdirSync(absolute, { withFileTypes: true }); - } catch {} - for (const entry of entries) { - if (entry.isDirectory() && !entry.name.startsWith('.')) { - visit(path.join(relative, entry.name), depth - 1); - } - } - }; - visit('', 2); - return found.filter(Boolean); -} - -/** The newest modification time of a directory and its direct children. */ -function newestMtime(dir) { - let newest = 0; - try { - newest = fs.statSync(dir).mtimeMs; - for (const entry of fs.readdirSync(dir)) { - try { - newest = Math.max(newest, fs.statSync(path.join(dir, entry)).mtimeMs); - } catch {} - } - } catch {} - return newest; -} - -/** - * The kind of a unit, from its fingerprint: `lib-foo`, - * `build-script-build-script-build`, `run-build-script-build-script-build`. - * One package has several units of different kinds, none replacing another. - */ -function unitKind(fingerprintDir) { - try { - const json = fs - .readdirSync(fingerprintDir) - .find(name => name.endsWith('.json')); - return json ? json.slice(0, -'.json'.length) : ''; - } catch { - return ''; - } -} - -/** - * What a prune would remove: units and incremental caches, without touching - * anything. Pure apart from reading, so it is what the tests exercise. - */ -export function findStale( - targetDir, - { - now = Date.now(), - maxAgeDays = DEFAULT_MAX_AGE_DAYS, - supersededDays = DEFAULT_SUPERSEDED_DAYS, - } = {}, -) { - const maxAge = maxAgeDays * DAY_MS; - const supersededAge = Math.min(supersededDays, maxAgeDays) * DAY_MS; - const usage = readUsage(targetDir); - const units = []; - const incremental = []; - for (const profile of profileDirs(targetDir)) { - const profileKey = profile.split(path.sep).join('/'); - const fingerprints = path.join(targetDir, profile, '.fingerprint'); - const groups = new Map(); - for (const dirName of fs.readdirSync(fingerprints)) { - const match = UNIT_DIR.exec(dirName); - if (!match) continue; - const fingerprintDir = path.join(fingerprints, dirName); - const key = `${profileKey}/${match[2]}`; - const recorded = usage.units[key]; - const unit = { - profile, - dirName, - hash: match[2], - key, - recorded, - lastUsed: recorded ?? newestMtime(fingerprintDir), - }; - const group = `${match[1]}\u0000${unitKind(fingerprintDir)}`; - if (!groups.has(group)) groups.set(group, []); - groups.get(group).push(unit); - } - for (const group of groups.values()) { - const newest = Math.max(...group.map(unit => unit.lastUsed)); - for (const unit of group) { - const age = now - unit.lastUsed; - if (unit.lastUsed < newest) { - // Something newer of the same crate and kind has taken its place, - // as a pin bump does to every dependency: a day is long enough. - if (age > supersededAge) units.push(unit); - } else if (unit.recorded != null && age > maxAge) { - // The newest of its crate and kind: stale only when no build has - // used it for the whole period. - units.push(unit); - } - } - } - const incrementalDir = path.join(targetDir, profile, 'incremental'); - let caches = []; - try { - caches = fs.readdirSync(incrementalDir); - } catch {} - // `-`: the hash changes with the crate's inputs, so older - // caches of one crate are replaced by the newest. - const byCrate = new Map(); - for (const cache of caches) { - const cacheDir = path.join(incrementalDir, cache); - const crate = cache.replace(/-[0-9a-z]{8,}$/u, ''); - if (!byCrate.has(crate)) byCrate.set(crate, []); - byCrate.get(crate).push({ cacheDir, mtime: newestMtime(cacheDir) }); - } - for (const group of byCrate.values()) { - const newest = Math.max(...group.map(cache => cache.mtime)); - for (const { cacheDir, mtime } of group) { - // A session directory is written each time the crate is compiled, so a - // cache untouched for the period gives the next build nothing to reuse. - const limit = mtime < newest ? supersededAge : maxAge; - if (now - mtime > limit) incremental.push(cacheDir); - } - } - } - return { units, incremental }; -} - -function sizeOf(target) { - let total = 0; - try { - const stat = fs.lstatSync(target); - if (!stat.isDirectory()) return stat.size; - for (const entry of fs.readdirSync(target)) { - total += sizeOf(path.join(target, entry)); - } - } catch {} - return total; -} - -function remove(target) { - const size = sizeOf(target); - try { - fs.rmSync(target, { recursive: true, force: true }); - return size; - } catch { - return 0; - } -} - -/** Removes one unit: its fingerprint, its `build/` directory and its files. */ -function removeUnit(targetDir, unit) { - const profileDir = path.join(targetDir, unit.profile); - let freed = remove(path.join(profileDir, '.fingerprint', unit.dirName)); - freed += remove(path.join(profileDir, 'build', unit.dirName)); - for (const folder of ['deps', 'examples']) { - const dir = path.join(profileDir, folder); - let entries = []; - try { - entries = fs.readdirSync(dir); - } catch {} - for (const entry of entries) { - const match = HASHED_FILE.exec(entry); - if (match && match[1] === unit.hash) - freed += remove(path.join(dir, entry)); - } - } - return freed; -} - -/** - * Removes what `findStale` reports, and says how much it freed. Quiet when - * there was nothing to remove, so an ordinary build prints nothing extra. - */ -export function pruneTarget( - targetDir, - { - now = Date.now(), - maxAgeDays = DEFAULT_MAX_AGE_DAYS, - supersededDays = targetGcSupersededDays(), - log = message => console.log(message), - } = {}, -) { - if (!fs.existsSync(targetDir)) return { units: 0, caches: 0, bytes: 0 }; - const stale = findStale(targetDir, { now, maxAgeDays, supersededDays }); - let bytes = 0; - for (const unit of stale.units) bytes += removeUnit(targetDir, unit); - for (const cache of stale.incremental) bytes += remove(cache); - if (stale.units.length > 0) { - const usage = readUsage(targetDir); - for (const unit of stale.units) delete usage.units[unit.key]; - writeUsage(targetDir, usage); - } - if (bytes > 0) { - log( - `Removed ${stale.units.length} build unit(s) and ` + - `${stale.incremental.length} incremental cache(s) from ${targetDir} ` + - `(${(bytes / 1024 ** 3).toFixed(2)} GB): unused for ${maxAgeDays} days, ` + - `or replaced by a newer build and unused for ${supersededDays}. ` + - 'Set RN_GPUI_TARGET_GC=0 to keep them.', - ); - } - return { - units: stale.units.length, - caches: stale.incremental.length, - bytes, - }; -} - -/** - * Runs a Cargo build and records the units it used. - * - * `json-render-diagnostics` leaves the diagnostics to Cargo, rendered on stderr - * as usual, and puts only the build messages on stdout as JSON; anything on - * stdout that is not one of them — a build script's own output — is passed - * through. Resolves when Cargo succeeds and rejects when it fails, like the - * plain invocation it replaces. - */ -export function cargoBuildRecording(args, { cwd, env, targetDir }) { - const [command, ...rest] = args; - const cargoArgs = [ - command, - '--message-format=json-render-diagnostics', - ...rest, - ]; - return new Promise((resolve, reject) => { - const child = spawn('cargo', cargoArgs, { - cwd, - env, - stdio: ['inherit', 'pipe', 'inherit'], - }); - const used = []; - const lines = readline.createInterface({ input: child.stdout }); - lines.on('line', line => { - let message = null; - if (line.startsWith('{')) { - try { - message = JSON.parse(line); - } catch {} - } - if (message == null || typeof message.reason !== 'string') { - process.stdout.write(`${line}\n`); - return; - } - if (message.reason === 'compiler-artifact') { - used.push(...(message.filenames ?? [])); - if (message.executable) used.push(message.executable); - } else if (message.reason === 'build-script-executed') { - if (message.out_dir) used.push(message.out_dir); - } - }); - child.on('error', reject); - child.on('close', code => { - if (code !== 0) { - reject(new Error(`cargo ${cargoArgs.join(' ')} failed with ${code}`)); - return; - } - if (targetDir) recordUsage(targetDir, used); - resolve(); - }); - }); -} diff --git a/vendor/react-native-gpui/packages/cli/src/target-gc.test.js b/vendor/react-native-gpui/packages/cli/src/target-gc.test.js deleted file mode 100644 index ce99631813..0000000000 --- a/vendor/react-native-gpui/packages/cli/src/target-gc.test.js +++ /dev/null @@ -1,284 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, describe, expect, test } from 'vitest'; -import { - USAGE_FILE, - findStale, - pruneTarget, - recordUsage, - targetGcEnabled, - targetGcMaxAgeDays, - targetGcSupersededDays, - unitKey, -} from './target-gc.js'; - -const DAY = 24 * 60 * 60 * 1000; -const NOW = Date.UTC(2026, 9, 24); -const HASH_A = '0123456789abcdef'; -const HASH_B = 'fedcba9876543210'; -const HASH_C = '00112233445566ff'; - -const roots = []; -afterEach(() => { - for (const root of roots.splice(0)) { - fs.rmSync(root, { recursive: true, force: true }); - } -}); - -function targetDir() { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'rn-gpui-target-gc-')); - roots.push(root); - return root; -} - -function write(file, contents = 'x') { - fs.mkdirSync(path.dirname(file), { recursive: true }); - fs.writeFileSync(file, contents); -} - -function age(target, daysOld) { - const time = new Date(NOW - daysOld * DAY); - fs.utimesSync(target, time, time); -} - -/** - * One unit as Cargo lays it out: a fingerprint whose `.json` names its kind, a - * library in `deps/`, and for a build script its `build/` directory. - */ -function unit( - target, - { name, hash, kind = `lib-${name}`, daysOld, profile = 'debug' }, -) { - const profileDir = path.join(target, profile); - const fingerprint = path.join(profileDir, '.fingerprint', `${name}-${hash}`); - write(path.join(fingerprint, kind)); - write(path.join(fingerprint, `${kind}.json`), '{}'); - const crate = name.replaceAll('-', '_'); - write(path.join(profileDir, 'deps', `lib${crate}-${hash}.rlib`), 'rlib'); - write(path.join(profileDir, 'deps', `${crate}-${hash}.d`)); - if (kind.includes('build-script')) { - write( - path.join(profileDir, 'build', `${name}-${hash}`, 'out', 'generated.rs'), - ); - } - for (const entry of fs.readdirSync(fingerprint)) { - age(path.join(fingerprint, entry), daysOld); - } - age(fingerprint, daysOld); - return { profileDir, fingerprint, crate }; -} - -describe('unitKey', () => { - test('names a unit by its profile and hash, from any of its outputs', () => { - const target = targetDir(); - expect( - unitKey( - target, - path.join(target, 'debug', 'deps', `libserde-${HASH_A}.rlib`), - ), - ).toBe(`debug/${HASH_A}`); - expect( - unitKey( - target, - path.join(target, 'debug', 'build', `rn-gpui-sys-${HASH_B}`, 'out'), - ), - ).toBe(`debug/${HASH_B}`); - // A cross build nests the profile under the target triple. - expect( - unitKey( - target, - path.join( - target, - 'x86_64-pc-windows-msvc', - 'release', - 'deps', - `foo-${HASH_C}.dll`, - ), - ), - ).toBe(`x86_64-pc-windows-msvc/release/${HASH_C}`); - }); - - test('an uplifted binary belongs to no unit', () => { - const target = targetDir(); - expect(unitKey(target, path.join(target, 'debug', 'app.exe'))).toBeNull(); - }); -}); - -describe('pruning', () => { - test('a recorded unit no build used for the period is removed, with its files', () => { - const target = targetDir(); - const old = unit(target, { name: 'serde', hash: HASH_A, daysOld: 30 }); - unit(target, { name: 'log', hash: HASH_B, daysOld: 30 }); - recordUsage( - target, - [path.join(old.profileDir, 'deps', `libserde-${HASH_A}.rlib`)], - NOW - 10 * DAY, - ); - recordUsage( - target, - [path.join(old.profileDir, 'deps', `liblog-${HASH_B}.rlib`)], - NOW - DAY, - ); - - const result = pruneTarget(target, { - now: NOW, - maxAgeDays: 7, - log: () => {}, - }); - - expect(result.units).toBe(1); - expect(fs.existsSync(old.fingerprint)).toBe(false); - expect( - fs.existsSync( - path.join(old.profileDir, 'deps', `libserde-${HASH_A}.rlib`), - ), - ).toBe(false); - expect( - fs.existsSync(path.join(old.profileDir, 'deps', `serde-${HASH_A}.d`)), - ).toBe(false); - // Used yesterday, so kept, and its record survives. - expect( - fs.existsSync(path.join(old.profileDir, 'deps', `liblog-${HASH_B}.rlib`)), - ).toBe(true); - const usage = JSON.parse( - fs.readFileSync(path.join(target, USAGE_FILE), 'utf8'), - ); - expect(Object.keys(usage.units)).toEqual([`debug/${HASH_B}`]); - }); - - test('an old unit without a record is kept while it is the only one of its kind', () => { - // Built by a plain `cargo` command the CLI never saw: old is not enough. - const target = targetDir(); - unit(target, { name: 'gpui', hash: HASH_A, daysOld: 60 }); - expect(findStale(target, { now: NOW, maxAgeDays: 7 }).units).toEqual([]); - }); - - test('an old unit without a record goes once a newer one of the same kind replaced it', () => { - const target = targetDir(); - unit(target, { name: 'rn-gpui-sys', hash: HASH_A, daysOld: 30 }); - unit(target, { name: 'rn-gpui-sys', hash: HASH_B, daysOld: 1 }); - const stale = findStale(target, { now: NOW, maxAgeDays: 7 }); - expect(stale.units.map(staleUnit => staleUnit.hash)).toEqual([HASH_A]); - }); - - test("a package's build-script units are not replaced by its library", () => { - // One package has a library, a build script and the build script's run, - // each its own unit. The library being newer replaces none of the others. - const target = targetDir(); - const name = 'rn-gpui-sys'; - unit(target, { - name, - hash: HASH_A, - daysOld: 30, - kind: 'build-script-build-script-build', - }); - unit(target, { - name, - hash: HASH_B, - daysOld: 30, - kind: 'run-build-script-build-script-build', - }); - unit(target, { name, hash: HASH_C, daysOld: 1 }); - expect(findStale(target, { now: NOW, maxAgeDays: 7 }).units).toEqual([]); - }); - - test('an incremental cache untouched for the period is removed', () => { - const target = targetDir(); - unit(target, { name: 'app', hash: HASH_A, daysOld: 1 }); - const incremental = path.join(target, 'debug', 'incremental'); - write(path.join(incremental, 'app-old', 's-session', 'query-cache.bin')); - age(path.join(incremental, 'app-old', 's-session'), 20); - age(path.join(incremental, 'app-old'), 20); - write(path.join(incremental, 'app-new', 's-session', 'query-cache.bin')); - age(path.join(incremental, 'app-new', 's-session'), 0); - age(path.join(incremental, 'app-new'), 0); - - pruneTarget(target, { now: NOW, maxAgeDays: 7, log: () => {} }); - - expect(fs.existsSync(path.join(incremental, 'app-old'))).toBe(false); - expect(fs.existsSync(path.join(incremental, 'app-new'))).toBe(true); - }); - - test('a superseded unit goes after a day while the newest keeps the week', () => { - const target = targetDir(); - unit(target, { name: 'gpui', hash: HASH_A, daysOld: 3 }); - unit(target, { name: 'gpui', hash: HASH_B, daysOld: 2 }); - unit(target, { name: 'gpui', hash: HASH_C, daysOld: 0.5 }); - const stale = findStale(target, { now: NOW, maxAgeDays: 7 }); - // A and B were replaced and are older than a day; C is the newest. - expect(stale.units.map(staleUnit => staleUnit.hash).sort()).toEqual( - [HASH_A, HASH_B].sort(), - ); - }); - - test('a superseded unit used within the last day stays', () => { - const target = targetDir(); - unit(target, { name: 'gpui', hash: HASH_A, daysOld: 0.5 }); - unit(target, { name: 'gpui', hash: HASH_B, daysOld: 0.1 }); - expect(findStale(target, { now: NOW, maxAgeDays: 7 }).units).toEqual([]); - }); - - test('the superseded period can be changed', () => { - const target = targetDir(); - unit(target, { name: 'gpui', hash: HASH_A, daysOld: 2 }); - unit(target, { name: 'gpui', hash: HASH_B, daysOld: 0.1 }); - expect( - findStale(target, { now: NOW, maxAgeDays: 7, supersededDays: 3 }).units, - ).toEqual([]); - }); - - test('an older incremental cache of a crate goes after a day, the newest keeps the week', () => { - const target = targetDir(); - unit(target, { name: 'app', hash: HASH_A, daysOld: 0.1 }); - const incremental = path.join(target, 'debug', 'incremental'); - for (const [name, daysOld] of [ - [`app-${HASH_A}`, 2], - [`app-${HASH_B}`, 3], - [`other-${HASH_A}`, 3], - ]) { - write(path.join(incremental, name, 's-session', 'query-cache.bin')); - age(path.join(incremental, name, 's-session'), daysOld); - age(path.join(incremental, name), daysOld); - } - const stale = findStale(target, { now: NOW, maxAgeDays: 7 }); - // The 3-day cache of `app` was replaced by the 2-day one; `other` has no - // newer cache, so its 3 days are within the week. - expect(stale.incremental.map(dir => path.basename(dir))).toEqual([ - `app-${HASH_B}`, - ]); - }); - - test('a missing target directory is a no-op', () => { - const target = path.join(targetDir(), 'never-built'); - expect(pruneTarget(target, { now: NOW, log: () => {} })).toEqual({ - units: 0, - caches: 0, - bytes: 0, - }); - }); -}); - -describe('configuration', () => { - test('keeps replaced units for a day unless told otherwise', () => { - expect(targetGcSupersededDays({})).toBe(1); - expect( - targetGcSupersededDays({ RN_GPUI_TARGET_GC_SUPERSEDED_DAYS: '2' }), - ).toBe(2); - expect( - targetGcSupersededDays({ RN_GPUI_TARGET_GC_SUPERSEDED_DAYS: 'x' }), - ).toBe(1); - }); - - test('never runs in CI, and can be turned off', () => { - expect(targetGcEnabled({})).toBe(true); - expect(targetGcEnabled({ CI: 'true' })).toBe(false); - expect(targetGcEnabled({ RN_GPUI_TARGET_GC: '0' })).toBe(false); - }); - - test('keeps units for a week unless told otherwise', () => { - expect(targetGcMaxAgeDays({})).toBe(7); - expect(targetGcMaxAgeDays({ RN_GPUI_TARGET_GC_DAYS: '14' })).toBe(14); - expect(targetGcMaxAgeDays({ RN_GPUI_TARGET_GC_DAYS: 'nope' })).toBe(7); - }); -}); diff --git a/vendor/react-native-gpui/packages/cli/templates/adhoc.entitlements.plist b/vendor/react-native-gpui/packages/cli/templates/adhoc.entitlements.plist deleted file mode 100644 index 2f4ef70fdf..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/adhoc.entitlements.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - com.apple.security.cs.disable-library-validation - - - diff --git a/vendor/react-native-gpui/packages/cli/templates/app/babel.config.js b/vendor/react-native-gpui/packages/cli/templates/app/babel.config.js deleted file mode 100644 index 94781507ee..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/app/babel.config.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = { - presets: ['module:@react-native/babel-preset'], - plugins: [ - // Rewrites `require` of a `.node` file (directly, or through a loader such - // as `node-gyp-build`, `bindings` or a napi-rs generated file) into the - // path the desktop runtime opens. A no-op on other platforms, so the same - // config still builds for iOS and Android. - 'module:@react-native-gpui/core/babel-plugin-node-addons', - ], -}; diff --git a/vendor/react-native-gpui/packages/cli/templates/app/desktop/.cargo/config.toml b/vendor/react-native-gpui/packages/cli/templates/app/desktop/.cargo/config.toml deleted file mode 100644 index 650dca6817..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/app/desktop/.cargo/config.toml +++ /dev/null @@ -1,6 +0,0 @@ -[build] -target-dir = "build/target" - -[env] -RN_GPUI_AUTOLINK_MANIFEST = { value = "autolink/autolink.json", relative = true } -RN_GPUI_AUTOLINK_CMAKE = { value = "autolink/autolink.cmake", relative = true } diff --git a/vendor/react-native-gpui/packages/cli/templates/app/desktop/README.md b/vendor/react-native-gpui/packages/cli/templates/app/desktop/README.md deleted file mode 100644 index c9465567b1..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/app/desktop/README.md +++ /dev/null @@ -1,128 +0,0 @@ -# Desktop (GPUI) - -This is the app-local GPUI target. Its `Cargo.toml` depends on the `react-native-gpui` Rust crate; `src/main.rs` is the app's launch point, so you can add Rust modules and local crate dependencies without editing the platform package. iOS, Android, and desktop share the JavaScript entry point and JS dependencies. The build script reads the app name and `desktop.appId` from the project-root `app.json`. - -Run the desktop app from the project root with: - -```sh -npx react-native run-desktop -``` - -The default reuses this project's Metro on port 8081, or starts it in a new -terminal window (`--terminal ` or `$REACT_TERMINAL` picks the terminal), -and runs a debug Cargo build, so Fast Refresh and LogBox work. Change the Metro -port with `--port 8082`; `--no-packager` never starts Metro, and -`--packager-log` runs it in the background with its output in -`desktop/build/metro.log`. -Use `--release` to bundle JavaScript and run the optimized, Metro-free build. - -`npx react-native init-desktop` installs dependencies, autolinks native modules, and creates `build/index.bundle`; that bundle lets `cargo run` launch the latest initialized app without the CLI. For development with Fast Refresh, LogBox, and a live Metro server, use `npx react-native run-desktop`. - -Autolink output is generated under `desktop/autolink/` and gitignored. It is -recreated by `init-desktop` and each `run-desktop`; do not commit those generated -files. Cargo build output and bundles are also kept under `desktop/build/`. - -## Window configuration - -`src/main.rs` uses `DesktopAppConfig` to set the title and initial size. It can -also set an initial position, configure public GPUI `WindowOptions`, install -GPUI app services before launch, and access the live `gpui::Window` after it -opens. Window size and position restore from the previous run by default; call -`.restore_window_state(false)` to always use the configured initial geometry. - -## Project-local Rust TurboModules - -A local Rust TurboModule is a spec file plus a `mod` that implements the trait -generated from it: - -1. Add `src/NativeGreeting.ts` with a - `TurboModuleRegistry.getEnforcing('NativeGreeting')` spec. -2. List it in `desktop/build.rs`: - `rn_gpui_module_build::generate(&["src/NativeGreeting.ts"]);`. -3. Write the implementation in `desktop/src/greeting.rs`, deriving nothing by - hand: the generated file gives you `NativeGreetingSpec`, the events handle and - the value structs. - - ```rust - use rn_gpui_module::{ModuleError, ModuleThread, Value}; - - pub struct Greeting; - - impl NativeGreetingSpec for Greeting { - fn new(_events: NativeGreetingEvents) -> Self { - Self - } - - fn greet(&self, name: String) -> Result { - Ok(format!("Hello from Rust, {name}!")) - } - } - ``` - - A method that returns a value runs on the JS thread; a method that returns - `void` or a `Promise` runs on the module's own thread unless the impl adds - `const THREAD: ModuleThread = ModuleThread::Main;`. - -4. Declare `mod greeting;` in `src/main.rs` and register it before the app - starts: - - ```rust - react_native_gpui::register_module(native_greeting_module::()); - ``` - -`include_specs!()` in `main.rs` pulls in the generated traits, structs and -descriptors. A mistake against the spec is a compile error in this crate, not a -runtime surprise. The runtime crate is `rn-gpui-module`, and -`rn-gpui-module-build` runs the generator from `build.rs`. - -A Rust module depends on core and on gpui by **version**, never by path: - -```toml -[dependencies] -rn-gpui-module = "0.1" -gpui = "0.2" - -[build-dependencies] -rn-gpui-module-build = "0.1" -``` - -Those crates live inside `@react-native-gpui/core`, at a path that only exists -in this repository, so a relative path breaks the moment the package is -installed. Autolink reads core's `Cargo.toml` for the gpui revision and writes a -`[patch.crates-io]` table into the app's `desktop/Cargo.toml`, which is the only -place `[patch]` applies; that table points each crate at the core the app -actually installed and pins gpui to core's revision. It is regenerated on every -autolink run, so edit the version in your own manifest and leave the patch -alone. A path or git dependency on those crates is refused with an explanation -rather than failing later in an installed app. - -For a reusable TurboModule library, keep its TypeScript spec under `src/` and -its native implementation under `desktop/`, with `codegenConfig` and -`platforms.desktop` in `package.json`; `npx react-native create-library` creates -that layout. Autolink runs React Native Codegen over the package's specs and -writes `JSI.h` plus `.h`, the latter -declaring one spec class per spec file (`src/NativeGreeting.ts` defines -`NativeGreetingSpec`). A C++ implementation derives from that class and -declares one method per spec method, with typed arguments (`std::string`, -`double`, `bool`, `folly::dynamic`, `std::vector`, `std::optional`, -`rngpui::Callback<...>`) and either a return value or, for a spec `Promise`, -a `void` method taking `rngpui::Promise` last. `react/bridging` performs the -conversion, so a signature that disagrees with the spec fails to compile. - -Methods that return a value run on the JS thread and take `jsi::Runtime&` -first. Methods that return `void` or a `Promise` run on the module's own thread -by default, so they never block the JS thread; set -a `public static constexpr rngpui::ModuleThread kThread` to `Main` (the GPUI -main thread) or `JS` (inline on the JS thread, taking `jsi::Runtime&` first) to -choose another thread; the generated spec class reads `T::kThread`, so it has to -be public. A method that does not run on the JS thread cannot take -a JSI type. A spec `readonly onProgress: CodegenTypes.EventEmitter` -generates a protected `emitOnProgress(value)` that any thread may call, and -`sendEvent("name", body)` covers modules used through `NativeEventEmitter`. - -`desktop/desktop.json` is the app's own configuration: its name, identifier, -version, icon, window and how it is packaged. Its schema is -`@react-native-gpui/cli/desktop.schema.json`, so an editor completes it. A -`desktop..json` beside it is merged over the base for that OS. The -`Info.plist` is generated from these settings rather than hand-written, and -`npx react-native package-desktop` builds the installers from the same file. diff --git a/vendor/react-native-gpui/packages/cli/templates/app/desktop/assets/README.md b/vendor/react-native-gpui/packages/cli/templates/app/desktop/assets/README.md deleted file mode 100644 index 417a9a4a45..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/app/desktop/assets/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# Desktop assets - -Point `desktop.json`'s `icon` at one 1024×1024 PNG; the per-OS formats (`.icns`, -`.ico`, PNG sizes) are generated from it when the app is packaged. diff --git a/vendor/react-native-gpui/packages/cli/templates/app/desktop/assets/icon.png b/vendor/react-native-gpui/packages/cli/templates/app/desktop/assets/icon.png deleted file mode 100644 index 576f7080ed..0000000000 Binary files a/vendor/react-native-gpui/packages/cli/templates/app/desktop/assets/icon.png and /dev/null differ diff --git a/vendor/react-native-gpui/packages/cli/templates/app/desktop/build.rs b/vendor/react-native-gpui/packages/cli/templates/app/desktop/build.rs deleted file mode 100644 index a946a41fb7..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/app/desktop/build.rs +++ /dev/null @@ -1,172 +0,0 @@ -fn main() { - // Forwards the engine's Node-API exports out of this executable, which is - // what lets a stock `.node` addon resolve them on Windows. - // - // A DLL records every import as a name *plus the file it comes from*, and a - // node-gyp addon records "from `node.exe`" — Windows has no global symbol - // scope for it to fall back on. Node's own answer is that the host process - // exports the Node-API functions, so that is what this does: the executable - // re-exports each of the VM's `napi_*`/`node_api_*` names, forwarded to - // `hermesvm.dll`. Addons that use node-gyp's delay-load hook (the default) - // then reach this process instead of looking for `node.exe` on disk. - // - // It is a no-op on macOS and Linux, where an addon's imports resolve against - // whatever is already loaded and need no forwarding. Declare it once, before - // the module list; it does not depend on anything else in this file. - rn_gpui_module_build::forward_node_api_exports(); - - // App-local Rust TurboModules: list one entry per `src/Native*.ts` spec, - // for example `&["src/NativeGreeting.ts"]`. Their glue is generated into - // this crate's OUT_DIR, and main.rs registers the modules. - rn_gpui_module_build::generate(&[]); - - let desktop_root = std::path::PathBuf::from( - std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set"), - ); - // `app.json` names the app; `desktop/desktop.json` carries the identifier - // and everything else the packaging step needs. The loader the CLI uses is - // JavaScript, so this reads the same file directly and applies the two - // defaults it would apply. - let project_root = desktop_root - .parent() - .expect("desktop folder has a React Native project root"); - let app_json_path = project_root.join("app.json"); - println!("cargo:rerun-if-changed={}", app_json_path.display()); - let app_json: serde_json::Value = serde_json::from_slice( - &std::fs::read(&app_json_path) - .unwrap_or_else(|error| panic!("read {}: {error}", app_json_path.display())), - ) - .unwrap_or_else(|error| panic!("parse {}: {error}", app_json_path.display())); - let app_name = app_json["name"] - .as_str() - .filter(|name| !name.is_empty()) - .expect("app.json must define a nonempty name"); - if app_json["desktop"] - .as_object() - .is_some_and(|desktop| !desktop.is_empty()) - { - panic!("move `app.json` desktop.* into `desktop/desktop.json` (see the README)"); - } - - let desktop_json_path = project_root.join("desktop/desktop.json"); - println!("cargo:rerun-if-changed={}", desktop_json_path.display()); - let desktop_json: serde_json::Value = std::fs::read(&desktop_json_path) - .ok() - .and_then(|bytes| serde_json::from_slice(&bytes).ok()) - .unwrap_or(serde_json::Value::Null); - let app_id = match desktop_json["identifier"].as_str() { - Some(identifier) if !identifier.is_empty() => identifier.to_string(), - _ => format!( - "com.example.{}", - app_name - .to_lowercase() - .chars() - .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) - .collect::() - ), - }; - println!("cargo:rustc-env=RN_GPUI_APP_NAME={app_name}"); - println!("cargo:rustc-env=RN_GPUI_APP_ID={app_id}"); - // Only a debug build names the bundle it was developed against. A release - // binary must find the bundle beside its own executable, because the path - // baked in here is where this machine happened to build it — and on the - // machine the package is installed on, that path does not exist. - println!("cargo:rerun-if-env-changed=PROFILE"); - if std::env::var("PROFILE").as_deref() == Ok("debug") { - println!( - "cargo:rustc-env=RN_GPUI_DEFAULT_BUNDLE={}", - desktop_root.join("build/index.bundle").display() - ); - } - - println!("cargo:rerun-if-env-changed=DEP_RN_GPUI_RUNTIME_RPATHS"); - println!("cargo:rerun-if-env-changed=RN_GPUI_PACKAGING"); - let Ok(paths) = std::env::var("DEP_RN_GPUI_RUNTIME_RPATHS") else { - return; - }; - let dirs = paths.split('|').filter(|path| !path.is_empty()); - if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { - stage_shared_libraries(dirs); - return; - } - // `RN_GPUI_PACKAGING` means this binary is about to be installed somewhere - // else, so only the relative rpaths belong in it. Keeping the absolute ones - // would let a packaged app load this build tree's libraries in preference to - // its own on the machine that built it — which hides exactly the packaging - // bugs the packaged run exists to catch. - let packaging = std::env::var("RN_GPUI_PACKAGING").is_ok(); - if !packaging { - for path in dirs { - println!("cargo:rustc-link-arg=-Wl,-rpath,{path}"); - } - } - emit_relocatable_rpaths(app_name); -} - -/// rpaths that survive being installed somewhere else. -/// -/// The absolute paths above let a development build run from this tree. A -/// packaged app is copied to another machine, where those paths do not exist, -/// so a release build also carries paths relative to the executable: the -/// layout the installers produce. -fn emit_relocatable_rpaths(app_name: &str) { - if std::env::var("PROFILE").as_deref() != Ok("release") { - return; - } - let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); - let emit = |rpath: String| println!("cargo:rustc-link-arg=-Wl,-rpath,{rpath}"); - match os.as_str() { - // An app bundle puts the executable in Contents/MacOS and the shipped - // libraries in Contents/Frameworks. - "macos" => emit("@executable_path/../Frameworks".into()), - // Linux installs the executable at `usr/bin` and ships its libraries - // under `usr/lib`: - // - the deb puts them in `usr/lib/`; - // - an AppImage's libraries are flat in `usr/lib`, because that is the - // directory AppRun puts on the library path and the one linuxdeploy - // resolves dependencies from before the image is assembled. - // Both are covered, so one binary works in either layout. - "linux" => { - emit(format!("$ORIGIN/../lib/{app_name}")); - emit("$ORIGIN/../lib".into()); - emit("$ORIGIN".into()); - } - // Windows has no rpath: the DLLs are copied beside the executable. - _ => {} - } -} - -/// Windows has no rpath: the loader finds a DLL next to the executable or on -/// `PATH`, so every directory the runtime reports as holding a shared library -/// (the Hermes binary directory in particular) is copied into the profile -/// directory that receives this app's executable. Without this the app builds -/// and then fails to start with "hermesvm.dll was not found". -fn stage_shared_libraries<'a>(dirs: impl Iterator) { - let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR is set")); - // /build/-/out -> - let Some(profile_dir) = out_dir.ancestors().nth(3) else { - return; - }; - for dir in dirs { - let Ok(entries) = std::fs::read_dir(dir) else { - continue; - }; - for entry in entries.flatten() { - let source = entry.path(); - let is_shared_library = source - .extension() - .and_then(|extension| extension.to_str()) - .is_some_and(|extension| extension.eq_ignore_ascii_case("dll")); - if !is_shared_library { - continue; - } - let Some(name) = source.file_name() else { - continue; - }; - println!("cargo:rerun-if-changed={}", source.display()); - std::fs::copy(&source, profile_dir.join(name)).unwrap_or_else(|error| { - panic!("copy {} next to the executable: {error}", source.display()) - }); - } - } -} diff --git a/vendor/react-native-gpui/packages/cli/templates/app/desktop/desktop.json b/vendor/react-native-gpui/packages/cli/templates/app/desktop/desktop.json deleted file mode 100644 index a68c4834b5..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/app/desktop/desktop.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "bundle": { - "targets": "all", - "macos": { - "minimumSystemVersion": "13.0" - } - }, - "icon": "assets/icon.png" -} diff --git a/vendor/react-native-gpui/packages/cli/templates/app/desktop/e2e/app.e2e.ts b/vendor/react-native-gpui/packages/cli/templates/app/desktop/e2e/app.e2e.ts deleted file mode 100644 index 10b1f3f7ca..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/app/desktop/e2e/app.e2e.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { beforeAll, expect, test } from 'vitest'; -import { launchApp, type DesktopApp } from '@react-native-gpui/testing'; - -let app: DesktopApp; -beforeAll(async () => { - app = await launchApp({ - disableAnimations: true, - idleOptions: { ignore: ['animations'] }, - }); -}); - -test('renders the React Native app', async () => { - await app.waitForIdle(); - // Existing React Native apps do not need to add a testID to adopt desktop. - const tree = (await app.tree()) as { children: unknown[] }; - expect(tree.children.length).toBeGreaterThan(0); -}); diff --git a/vendor/react-native-gpui/packages/cli/templates/app/desktop/gitignore b/vendor/react-native-gpui/packages/cli/templates/app/desktop/gitignore deleted file mode 100644 index 2e460e95bb..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/app/desktop/gitignore +++ /dev/null @@ -1,3 +0,0 @@ -build/ -.cache/ -autolink/ diff --git a/vendor/react-native-gpui/packages/cli/templates/app/desktop/metro.config.js b/vendor/react-native-gpui/packages/cli/templates/app/desktop/metro.config.js deleted file mode 100644 index b799517712..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/app/desktop/metro.config.js +++ /dev/null @@ -1,6 +0,0 @@ -const path = require('path'); -const { makeMetroConfig } = require('@react-native-gpui/core/metro.config'); - -module.exports = makeMetroConfig({ - projectRoot: path.resolve(__dirname, '..'), -}); diff --git a/vendor/react-native-gpui/packages/cli/templates/app/desktop/src/main.rs b/vendor/react-native-gpui/packages/cli/templates/app/desktop/src/main.rs deleted file mode 100644 index 8f2300ba5b..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/app/desktop/src/main.rs +++ /dev/null @@ -1,41 +0,0 @@ -//! Project-owned desktop launch configuration. -//! -//! A local Rust TurboModule is a `Native*.ts` spec beside this file plus a -//! `mod` that implements the trait generated from it. `build.rs` lists the -//! specs, and `main` registers each module before the app starts. See -//! `desktop/README.md` for the full example. - -rn_gpui_module::include_specs!(); - -// mod greeting; -// use greeting::{native_greeting_module, Greeting}; - -fn main() { - // A debug build knows where its own bundle is; a release build does not, and - // must not: the path would name the machine that built it. A packaged release - // app resolves the bundle beside its executable instead (see `resources`). - #[cfg(debug_assertions)] - if std::env::var_os("RN_GPUI_BUNDLE").is_none() { - std::env::set_var("RN_GPUI_BUNDLE", env!("RN_GPUI_DEFAULT_BUNDLE")); - } - // App-local modules are registered before the app starts; a module the - // platform already provides would panic here. - // react_native_gpui::register_module(native_greeting_module::()); - - let config = react_native_gpui::DesktopAppConfig::from_env_with_defaults( - env!("RN_GPUI_APP_NAME"), - env!("RN_GPUI_APP_ID"), - ) - .window_title(env!("RN_GPUI_APP_NAME")) - .window_size(1024.0, 768.0) - // Uncomment to choose a fixed initial top-left location (screen DIPs). - // .window_position(120.0, 80.0) - // .restore_window_state(false) - .configure_window(|options| { - // GPUI window options are public: titlebar, resizability, display, - // decorations, min size, and other native window behavior. - options.is_resizable = true; - }); - - react_native_gpui::run_with(config); -} diff --git a/vendor/react-native-gpui/packages/cli/templates/app/desktop/vitest.e2e.config.ts b/vendor/react-native-gpui/packages/cli/templates/app/desktop/vitest.e2e.config.ts deleted file mode 100644 index 187439e21f..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/app/desktop/vitest.e2e.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { fileURLToPath } from 'node:url'; -import { defineConfig, mergeConfig } from 'vitest/config'; -import desktopPreset from '@react-native-gpui/testing/vitest-preset-e2e'; - -const projectRoot = fileURLToPath(new URL('..', import.meta.url)); -process.env.RN_GPUI_TEST_PROJECT = projectRoot; - -export default mergeConfig( - defineConfig(desktopPreset), - defineConfig({ - root: projectRoot, - test: { include: ['desktop/e2e/**/*.e2e.ts'] }, - }), -); diff --git a/vendor/react-native-gpui/packages/cli/templates/modules/cpp/CMakeLists.txt b/vendor/react-native-gpui/packages/cli/templates/modules/cpp/CMakeLists.txt deleted file mode 100644 index b1a45754f3..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/modules/cpp/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ -set_property( - GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_SOURCES - "${CMAKE_CURRENT_LIST_DIR}/cpp/RNModule.cpp") diff --git a/vendor/react-native-gpui/packages/cli/templates/modules/cpp/NativeModule.ts b/vendor/react-native-gpui/packages/cli/templates/modules/cpp/NativeModule.ts deleted file mode 100644 index ae8ddf7bc1..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/modules/cpp/NativeModule.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { TurboModuleRegistry, type TurboModule } from 'react-native'; - -export interface Spec extends TurboModule { - greet(name: string): string; -} - -export default TurboModuleRegistry.getEnforcing('RNModule'); diff --git a/vendor/react-native-gpui/packages/cli/templates/modules/cpp/RNModule.cpp b/vendor/react-native-gpui/packages/cli/templates/modules/cpp/RNModule.cpp deleted file mode 100644 index 47a9efd916..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/modules/cpp/RNModule.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "RNModule.hpp" - -#include - -#include -#include -#include - -namespace { -namespace jsi = facebook::jsi; -using facebook::react::CallInvoker; -using facebook::react::TurboModule; - -class RNModule final : public facebook::react::NativeModuleSpec { - public: - explicit RNModule(std::shared_ptr jsInvoker) - : NativeModuleSpec(std::move(jsInvoker)) {} - - std::string greet(jsi::Runtime&, std::string name) { - return "Hello from C++, " + name + "!"; - } -}; -} // namespace - -std::shared_ptr create_rn_module( - const std::string& name, - std::shared_ptr jsInvoker) { - return rngpui::provideTurboModule(name, std::move(jsInvoker)); -} diff --git a/vendor/react-native-gpui/packages/cli/templates/modules/cpp/RNModule.hpp b/vendor/react-native-gpui/packages/cli/templates/modules/cpp/RNModule.hpp deleted file mode 100644 index 3c40146aa6..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/modules/cpp/RNModule.hpp +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include -#include - -namespace facebook::react { -class CallInvoker; -class TurboModule; -} // namespace facebook::react - -std::shared_ptr create_rn_module( - const std::string& name, - std::shared_ptr jsInvoker); diff --git a/vendor/react-native-gpui/packages/cli/templates/modules/cpp/index.ts b/vendor/react-native-gpui/packages/cli/templates/modules/cpp/index.ts deleted file mode 100644 index c0550abf51..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/modules/cpp/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { default } from './NativeModule'; diff --git a/vendor/react-native-gpui/packages/cli/templates/modules/rust/NativeModule.ts b/vendor/react-native-gpui/packages/cli/templates/modules/rust/NativeModule.ts deleted file mode 100644 index ae8ddf7bc1..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/modules/rust/NativeModule.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { TurboModuleRegistry, type TurboModule } from 'react-native'; - -export interface Spec extends TurboModule { - greet(name: string): string; -} - -export default TurboModuleRegistry.getEnforcing('RNModule'); diff --git a/vendor/react-native-gpui/packages/cli/templates/modules/rust/build.rs b/vendor/react-native-gpui/packages/cli/templates/modules/rust/build.rs deleted file mode 100644 index f75076328e..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/modules/rust/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - rn_gpui_module_build::generate(&["../src/NativeModule.ts"]); -} diff --git a/vendor/react-native-gpui/packages/cli/templates/modules/rust/index.ts b/vendor/react-native-gpui/packages/cli/templates/modules/rust/index.ts deleted file mode 100644 index c0550abf51..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/modules/rust/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { default } from './NativeModule'; diff --git a/vendor/react-native-gpui/packages/cli/templates/modules/rust/lib.rs b/vendor/react-native-gpui/packages/cli/templates/modules/rust/lib.rs deleted file mode 100644 index 243c8839bf..0000000000 --- a/vendor/react-native-gpui/packages/cli/templates/modules/rust/lib.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! A Rust TurboModule: the trait, the events handle and the value structs come -//! from the spec file next to it. - -rn_gpui_module::include_specs!(); - -use rn_gpui_module::ModuleError; - -pub struct RNModule; - -impl NativeModuleSpec for RNModule { - fn new(_events: NativeModuleEvents) -> Self { - Self - } - - /// A method that returns a value runs on the JS thread. A method that - /// returns `void` or a `Promise` runs on the module's own thread unless the - /// impl adds `const THREAD: ModuleThread = ModuleThread::Main;`. - fn greet(&self, name: String) -> Result { - Ok(format!("Hello from Rust, {name}!")) - } -} - -/// Called by the app's autolink shim, which keeps these modules linked in. -pub fn rn_gpui_register() { - rn_gpui_module::register(native_RNMODULESNAKE_module::()); -} diff --git a/vendor/react-native-gpui/packages/codegen/CHANGELOG.md b/vendor/react-native-gpui/packages/codegen/CHANGELOG.md deleted file mode 100644 index c232fb62bc..0000000000 --- a/vendor/react-native-gpui/packages/codegen/CHANGELOG.md +++ /dev/null @@ -1,25 +0,0 @@ -# Changelog - -All notable changes to `@react-native-gpui/codegen` are listed here. Each version's section becomes the notes of its GitHub release. - -## 0.87.0-alpha.2 - 2026-11-26 - -- The context of a component in a native tree runs `with_window` in the window the tree is shown in (the new `NativeCall::window`), so a command that needs a window works there too. -- A component in a native tree reads a scalar prop that is not set as the default its spec declares (`WithDefault` reads `true`) instead of zero, as a Fabric node does. - -## 0.87.0-alpha.1 - 2026-11-12 - -- A crate with both a module spec and a component spec generates a component that means `host_component::Value` (serde_json's): the component half of the file names it `HostValue` instead of losing it to the module runtime's `Value`, which broke `as_str`, `as_i64` and `Map::get` in the generated create, update and command code. - -- A spec file set with both a Turbo Native Module and a host component generates one Rust file that compiles (the `Value` import is no longer repeated). -- An event payload field can be a union of string literals: it is an enum on the Rust side (`as_raw()` to C++, which fills the enum React Native generated; its name to a native tree). -- Every component spec is also a component of a native tree (a `NativeRoot`): the generated props view reads either the C++ props or the JSON props of a native tree instance through the same accessors (scalars, strings, enums, colors, `UnsafeMixed`, arrays, structs, arrays of structs, image sources and arrays of strings, with no accessor that can panic), the change mask can be built from prop names, events are sent to a native tree as `{ nativeEvent }` payloads, commands are called by name with JSON arguments, and the context has `children()`. The same `impl Spec for T` serves both; register it for a native tree with `Component::::register_native_tree()`. An image prop of a native tree is an object with the fields of a resolved React Native image source (`uri`, `scale`, ...). Existing implementations compile unchanged. -- The generated host component trait has an optional `measure(props, constraint)` for `measured` components. -- An event payload field named `value` or `emitter` no longer breaks the generated C++ with a redefinition error: the shim's parameters carry a `p_` prefix and the payload local is `rn_payload`. -- The generated host component context has `window()` and `with_window()`. -- The generated host component context has `app()`, which returns the GPUI `App` of the call the component was made in. - -## 0.87.0-alpha.0 - 2026-11-01 - -- First release. -- Generates Rust and C++ specs for Turbo Native Modules and host components, plugged into `@react-native/codegen`. diff --git a/vendor/react-native-gpui/packages/codegen/LICENSE b/vendor/react-native-gpui/packages/codegen/LICENSE deleted file mode 100644 index 149a0f8321..0000000000 --- a/vendor/react-native-gpui/packages/codegen/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Streetwriters - -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/vendor/react-native-gpui/packages/codegen/README.md b/vendor/react-native-gpui/packages/codegen/README.md deleted file mode 100644 index 70ed769c8c..0000000000 --- a/vendor/react-native-gpui/packages/codegen/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# @react-native-gpui/codegen - -Generates the Rust and C++ code for desktop native modules and components from their TypeScript specs, as a plug-in for [`@react-native/codegen`](https://github.com/react/react-native/tree/main/packages/react-native-codegen). - -Part of [react-native-gpui](https://github.com/streetwriters/react-native-gpui), React Native for macOS, Windows and Linux. - -You don't install this package yourself: `@react-native-gpui/core` depends on it, and the build runs it for the app and each library. - -## Documentation - -[Turbo Native Modules](https://streetwriters.github.io/react-native-gpui/docs/turbo-native-modules) - -## License - -MIT. See [LICENSE](LICENSE). diff --git a/vendor/react-native-gpui/packages/codegen/package.json b/vendor/react-native-gpui/packages/codegen/package.json deleted file mode 100644 index 366486e18a..0000000000 --- a/vendor/react-native-gpui/packages/codegen/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@react-native-gpui/codegen", - "version": "0.87.0-alpha.2", - "description": "C++ and Rust code generators for react-native-gpui, plugged into @react-native/codegen.", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/streetwriters/react-native-gpui.git", - "directory": "packages/codegen" - }, - "homepage": "https://streetwriters.github.io/react-native-gpui/", - "bugs": { - "url": "https://github.com/streetwriters/react-native-gpui/issues" - }, - "files": [ - "src", - "CHANGELOG.md", - "!**/*.test.js", - "!**/*.test.mjs", - "!**/*.test.ts", - "!**/*.test.cjs" - ], - "type": "module", - "exports": { - "./generate-cxx-spec": "./src/generate-cxx-spec.js", - "./generate-rust-spec": "./src/generate-rust-spec.js", - "./generate-host-component-cpp": "./src/generate-host-component-cpp.js" - }, - "scripts": { - "generate-cxx-spec": "node ./src/generate-cxx-spec.js", - "generate-rust-spec": "node ./src/generate-rust-spec.js" - }, - "dependencies": { - "@react-native/codegen": "0.87.1" - }, - "publishConfig": { - "access": "public", - "tag": "latest" - } -} diff --git a/vendor/react-native-gpui/packages/codegen/src/generate-cxx-spec.js b/vendor/react-native-gpui/packages/codegen/src/generate-cxx-spec.js deleted file mode 100644 index 585b4b3c4b..0000000000 --- a/vendor/react-native-gpui/packages/codegen/src/generate-cxx-spec.js +++ /dev/null @@ -1,341 +0,0 @@ -#!/usr/bin/env node -import fs from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { createRequire } from 'node:module'; - -const toPascalCase = value => - value.replaceAll(/(?:^|[^A-Za-z0-9]+)([A-Za-z0-9])/gu, (_match, character) => - character.toUpperCase(), - ); - -/** - * The C++ type an implementation declares for one spec type, plus the JSI type - * it converts to. A named object type maps to the struct React Native's own - * generator emits for that type alias in `JSI.h`. - */ -function cppTypeOf(annotation, context) { - const { hasteModuleName, aliasMap, fail } = context; - const recurse = inner => cppTypeOf(inner, context); - switch (annotation.type) { - case 'StringTypeAnnotation': - case 'StringLiteralTypeAnnotation': - return { cpp: 'std::string', jsi: 'jsi::String' }; - case 'NumberTypeAnnotation': - case 'DoubleTypeAnnotation': - case 'FloatTypeAnnotation': - case 'NumberLiteralTypeAnnotation': - return { cpp: 'double', jsi: 'double' }; - case 'Int32TypeAnnotation': - return { cpp: 'int32_t', jsi: 'int' }; - case 'BooleanTypeAnnotation': - case 'BooleanLiteralTypeAnnotation': - return { cpp: 'bool', jsi: 'bool' }; - case 'GenericObjectTypeAnnotation': - case 'ObjectTypeAnnotation': - return { cpp: 'folly::dynamic', jsi: 'jsi::Object' }; - case 'MixedTypeAnnotation': - return { cpp: 'folly::dynamic', jsi: 'jsi::Value' }; - case 'ArrayBufferTypeAnnotation': - // Copied, so a module-thread method never holds a runtime-bound object. - return { cpp: 'std::vector', jsi: 'jsi::ArrayBuffer' }; - case 'VoidTypeAnnotation': - return { cpp: 'void', jsi: 'jsi::Value' }; - case 'ArrayTypeAnnotation': { - const element = recurse(annotation.elementType); - return { cpp: `std::vector<${element.cpp}>`, jsi: 'jsi::Array' }; - } - case 'FunctionTypeAnnotation': - return { - cpp: `rngpui::Callback<${annotation.params - .map(parameter => cppParameterOf(parameter, context)) - .join(', ')}>`, - jsi: 'jsi::Function', - }; - case 'NullableTypeAnnotation': { - const inner = recurse(annotation.typeAnnotation); - return { cpp: `std::optional<${inner.cpp}>`, jsi: inner.jsi }; - } - case 'ReservedTypeAnnotation': - if (annotation.name === 'RootTag') { - return { cpp: 'double', jsi: 'double' }; - } - return fail(`ReservedTypeAnnotation(${annotation.name})`); - case 'EnumDeclaration': - switch (annotation.memberType) { - case 'NumberTypeAnnotation': - return { cpp: 'double', jsi: 'jsi::Value' }; - case 'StringTypeAnnotation': - return { cpp: 'std::string', jsi: 'jsi::String' }; - default: - return fail(`EnumDeclaration(${annotation.memberType})`); - } - case 'UnionTypeAnnotation': { - const memberTypes = new Set(annotation.types.map(member => member.type)); - if (memberTypes.size !== 1) { - return fail('UnionTypeAnnotation with mixed member types'); - } - switch ([...memberTypes][0]) { - case 'StringLiteralTypeAnnotation': - return { cpp: 'std::string', jsi: 'jsi::String' }; - case 'NumberLiteralTypeAnnotation': - return { cpp: 'double', jsi: 'double' }; - case 'BooleanLiteralTypeAnnotation': - return { cpp: 'bool', jsi: 'bool' }; - default: - return fail('UnionTypeAnnotation'); - } - } - case 'TypeAliasTypeAnnotation': { - const alias = aliasMap?.[annotation.name]; - if (!alias) { - return fail(`unresolved type alias ${annotation.name}`); - } - if ( - alias.type === 'ObjectTypeAnnotation' && - alias.properties.length > 0 - ) { - return { - cpp: `${hasteModuleName}${annotation.name}`, - jsi: 'jsi::Object', - }; - } - return recurse(alias); - } - default: - return fail(annotation.type); - } -} - -/// The C++ type an implementation declares for one parameter: a parameter the -/// spec marks optional may be omitted, so it is `std::optional`. -const cppParameterOf = (parameter, context) => { - const { cpp } = cppTypeOf(parameter.typeAnnotation, context); - return parameter.optional && - parameter.typeAnnotation.type !== 'NullableTypeAnnotation' - ? `std::optional<${cpp}>` - : cpp; -}; - -const isObjectType = annotation => - annotation.type === 'ObjectTypeAnnotation' || - annotation.type === 'GenericObjectTypeAnnotation'; - -function methodOf(name, typeAnnotation, context) { - const method = `${context.location}: ${name}`; - const returnType = typeAnnotation.returnTypeAnnotation; - const kind = - returnType.type === 'VoidTypeAnnotation' - ? 'void' - : returnType.type === 'PromiseTypeAnnotation' - ? 'promise' - : 'value'; - if (name === 'getConstants' && kind === 'promise') { - throw new Error(`${method}: getConstants cannot return a Promise`); - } - if ( - kind === 'value' && - typeAnnotation.params.some( - parameter => parameter.typeAnnotation.type === 'FunctionTypeAnnotation', - ) - ) { - throw new Error( - `${method}: a method that takes a callback must return void or a Promise`, - ); - } - const parameters = typeAnnotation.params.map(parameter => ({ - ...parameter, - context, - })); - const described = parameters - .map(parameter => `${cppParameterOf(parameter, context)} ${parameter.name}`) - .join(', '); - // A value method runs on the JS thread, so an object return may stay a JSI - // object; everything else uses the converted type. - const valueReturn = () => - isObjectType(returnType) - ? 'jsi::Object' - : cppTypeOf(returnType, context).cpp; - const promiseType = () => { - const element = returnType.elementType; - return `rngpui::Promise<${ - element && element.type !== 'VoidTypeAnnotation' - ? cppTypeOf(element, context).cpp - : '' - }>`; - }; - const signature = - kind === 'value' - ? `${valueReturn()} ${name}(jsi::Runtime& rt${described ? `, ${described}` : ''})` - : kind === 'void' - ? `void ${name}(${described})` - : `void ${name}(${described ? `${described}, ` : ''}${promiseType()})`; - // A value method always takes the runtime; a void or Promise method takes it - // only when the module asks for the JS thread, and a Promise method takes the - // promise last. - const countParts = []; - if (kind === 'value') { - countParts.push('1'); - } else { - countParts.push('(T::kThread == rngpui::ModuleThread::JS ? 1 : 0)'); - } - if (parameters.length > 0) { - countParts.push(`${parameters.length}`); - } - if (kind === 'promise') { - countParts.push('1'); - } - const parameterCount = countParts.join(' + '); - const registration = - kind === 'value' - ? `valueMethod` - : kind === 'void' - ? `voidMethod` - : `promiseMethod`; - return { - name, - parameterCount, - message: - kind === 'value' - ? `${name} must be declared as ${signature}` - : `${name} must be declared as ${signature}; with kThread = JS it takes jsi::Runtime& rt first`, - registration: `this->template ${registration}<&T::${name}>("${name}");`, - }; -} - -function eventOf(eventEmitter, context) { - const payload = eventEmitter.typeAnnotation.typeAnnotation; - const name = eventEmitter.name; - const emitName = `emit${toPascalCase(name)}`; - if (payload.type === 'VoidTypeAnnotation') { - return { - registration: `this->template addEvent<>("${name}");`, - emitter: ` void ${emitName}() { - this->emitEvent("${name}"); - }`, - }; - } - const type = cppTypeOf(payload, context); - return { - registration: `this->template addEvent("${name}");`, - emitter: ` template - void ${emitName}(V value) { - static_assert( - facebook::react::bridging::supportsToJs, - "${name}: the value cannot be converted to the event's JS type"); - this->emitEvent("${name}", std::move(value)); - }`, - }; -} - -/** - * The spec header for one codegen library: a `Spec` class per - * NativeModule that registers its methods, typed events and emitters with - * `rngpui::TurboModuleBase`. - */ -export function generateCxxSpec({ libraryName, schema, specPaths = {} }) { - const modules = Object.entries(schema.modules ?? {}).filter( - ([, module]) => module.type === 'NativeModule', - ); - const classes = modules.map(([hasteModuleName, module]) => { - const location = specPaths[hasteModuleName] ?? hasteModuleName; - // `where` is the method or event emitter a failing type came from, so the - // error names it and not just the spec file. - const contextFor = where => ({ - hasteModuleName, - aliasMap: module.aliasMap, - location, - where, - fail: typeName => { - throw new Error( - `${location}${where ? `: ${where}` : ''}: unsupported spec type ${typeName}`, - ); - }, - }); - const methods = module.spec.methods.map(({ name, typeAnnotation }) => - methodOf(name, typeAnnotation, contextFor(name)), - ); - const events = (module.spec.eventEmitters ?? []).map(eventEmitter => - eventOf(eventEmitter, contextFor(eventEmitter.name)), - ); - const assertions = methods - .map( - method => ` static_assert( - facebook::react::bridging::getParameterCount(&T::${method.name}) == - ${method.parameterCount}, - "${method.message}");`, - ) - .join('\n'); - const registrations = [ - ...methods.map(method => ` ${method.registration}`), - ...events.map(event => ` ${event.registration}`), - ].join('\n'); - const emitters = events.map(event => event.emitter).join('\n\n'); - return `template -class ${hasteModuleName}Spec : public rngpui::TurboModuleBase { - public: - static constexpr std::string_view kModuleName = "${module.moduleName}"; - - protected: - explicit ${hasteModuleName}Spec( - std::shared_ptr jsInvoker) - : rngpui::TurboModuleBase( - std::string{kModuleName}, std::move(jsInvoker)) { -${assertions} -${registrations} - } -${emitters ? `\n${emitters}\n` : ''}};`; - }); - return `// Generated by @react-native-gpui/codegen; do not edit. -#pragma once - -#include "GpuiTurboModule.h" - -#include <${libraryName}JSI.h> - -#include -#include -#include -#include - -namespace facebook::react { - -${classes.join('\n\n')} - -} // namespace facebook::react -`; -} - -if ( - process.argv[1] && - path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) -) { - const inputs = process.argv.slice(2); - const outputPath = inputs.pop(); - const libraryName = inputs.pop(); - if (!outputPath || !libraryName || inputs.length === 0) { - throw new Error( - 'usage: generate-cxx-spec ... ', - ); - } - const require = createRequire(import.meta.url); - const { - combineSchemasInFileList, - } = require('@react-native/codegen/lib/cli/combine/combine-js-to-schema'); - const specPaths = Object.fromEntries( - inputs.map(specPath => [ - path.basename(specPath).replace(/\.[^.]+$/u, ''), - specPath, - ]), - ); - const schema = combineSchemasInFileList(inputs, 'desktop', null, libraryName); - const generated = generateCxxSpec({ libraryName, schema, specPaths }); - fs.mkdirSync(path.dirname(outputPath), { recursive: true }); - // Keep the mtime stable so C++ that includes it is not recompiled. - if ( - !fs.existsSync(outputPath) || - fs.readFileSync(outputPath, 'utf8') !== generated - ) { - fs.writeFileSync(outputPath, generated); - } -} diff --git a/vendor/react-native-gpui/packages/codegen/src/generate-cxx-spec.test.js b/vendor/react-native-gpui/packages/codegen/src/generate-cxx-spec.test.js deleted file mode 100644 index 7a27b5b8be..0000000000 --- a/vendor/react-native-gpui/packages/codegen/src/generate-cxx-spec.test.js +++ /dev/null @@ -1,193 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { createRequire } from 'node:module'; -import { expect, test } from 'vitest'; -import { generateCxxSpec } from './generate-cxx-spec.js'; - -const require = createRequire(import.meta.url); - -const spec = `import type { CodegenTypes, TurboModule } from 'react-native'; -import { TurboModuleRegistry } from 'react-native'; - -export interface Spec extends TurboModule { - greet(name: string): string; - record(value: string): void; - greetLater(name: string): Promise; - lookup(key: string, callback: (value: string, found: boolean) => void): void; - readonly onProgress: CodegenTypes.EventEmitter; -} - -export default TurboModuleRegistry.getEnforcing('Probe'); -`; - -/** Runs the real TS parser over `source` and returns the generated header. */ -function generateFor(source) { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'rn-gpui-spec-')); - const specPath = path.join(directory, 'NativeProbe.ts'); - fs.writeFileSync(specPath, source); - const { - combineSchemasInFileList, - } = require('@react-native/codegen/lib/cli/combine/combine-js-to-schema'); - const schema = combineSchemasInFileList( - [specPath], - 'desktop', - null, - 'ProbeSpec', - ); - return generateCxxSpec({ - libraryName: 'ProbeSpec', - schema, - specPaths: { NativeProbe: specPath }, - }); -} - -test('generates a spec class per module with one registration per method', () => { - const header = generateFor(spec); - expect(header).toContain('#include "GpuiTurboModule.h"'); - expect(header).toContain('#include '); - expect(header).toContain( - 'class NativeProbeSpec : public rngpui::TurboModuleBase', - ); - expect(header).toContain( - 'static constexpr std::string_view kModuleName = "Probe";', - ); - expect(header).toContain('this->template valueMethod<&T::greet>("greet");'); - expect(header).toContain('this->template voidMethod<&T::record>("record");'); - expect(header).toContain( - 'this->template promiseMethod<&T::greetLater>("greetLater");', - ); -}); - -test('asserts the parameter count with the expected signature in words', () => { - const header = generateFor(spec); - expect(header).toContain( - '"greet must be declared as std::string greet(jsi::Runtime& rt, std::string name)"', - ); - expect(header).toContain( - '"record must be declared as void record(std::string value); with kThread = JS it takes jsi::Runtime& rt first"', - ); - expect(header).toContain( - '"greetLater must be declared as void greetLater(std::string name, rngpui::Promise); with kThread = JS it takes jsi::Runtime& rt first"', - ); - expect(header).toContain( - 'getParameterCount(&T::greet) ==\n 1 + 1,', - ); - expect(header).toContain( - 'getParameterCount(&T::greetLater) ==\n (T::kThread == rngpui::ModuleThread::JS ? 1 : 0) + 1 + 1,', - ); -}); - -test('converts a callback parameter to rngpui::Callback', () => { - const header = generateFor(spec); - expect(header).toContain('rngpui::Callback callback'); - expect(header).toContain( - 'void lookup(std::string key, rngpui::Callback callback)', - ); -}); - -test('registers a typed event and generates its emitter', () => { - const header = generateFor(spec); - expect(header).toContain( - 'this->template addEvent("onProgress");', - ); - expect(header).toContain('void emitOnProgress(V value)'); - expect(header).toContain( - 'facebook::react::bridging::supportsToJs', - ); - expect(header).toContain('this->emitEvent("onProgress", std::move(value));'); -}); - -test('rejects a value-returning method with a callback parameter', () => { - expect(() => - generateFor( - spec.replace( - 'lookup(key: string, callback: (value: string, found: boolean) => void): void;', - 'lookup(key: string, callback: (value: string, found: boolean) => void): string;', - ), - ), - ).toThrow( - /lookup: a method that takes a callback must return void or a Promise/u, - ); -}); - -test('rejects getConstants declared with a Promise', () => { - expect(() => - generateFor( - spec.replace( - 'greet(name: string): string;', - 'getConstants(): Promise;', - ), - ), - ).toThrow(/getConstants: getConstants cannot return a Promise/u); -}); - -test('describes an optional parameter as std::optional', () => { - const header = generateFor( - spec.replace( - 'record(value: string): void;', - 'record(value: string, tag?: string): void;', - ), - ); - expect(header).toContain( - 'record must be declared as void record(std::string value, std::optional tag)', - ); -}); - -test('maps an ArrayBuffer to bytes it owns, in arguments and results', () => { - const header = generateFor( - spec - .replace( - 'record(value: string): void;', - 'record(value: ArrayBuffer): void;', - ) - .replace( - 'readonly onProgress: CodegenTypes.EventEmitter;', - 'readonly onProgress: CodegenTypes.EventEmitter;', - ) - .replace( - 'greet(name: string): string;', - 'greet(name: string): ArrayBuffer;', - ), - ); - expect(header).toContain('void record(std::vector value);'); - expect(header).toContain('std::vector greet('); - expect(header).toContain('void emitOnProgress(V value)'); - expect(header).toContain('supportsToJs>'); -}); - -test('names the method or event emitter a failing type came from', () => { - expect(() => - generateFor( - spec.replace( - 'record(value: string): void;', - "record(value: 'a' | 1): void;", - ), - ), - ).toThrow( - /NativeProbe\.ts: record: unsupported spec type UnionTypeAnnotation with mixed member types/u, - ); -}); - -test('generates a payload-less event emitter and a Promise method', () => { - const header = generateFor( - spec - .replace( - 'readonly onProgress: CodegenTypes.EventEmitter;', - 'readonly onDone: CodegenTypes.EventEmitter;', - ) - .replace( - 'greet(name: string): string;', - 'greet(name: string): string;\n finish(): Promise;', - ), - ); - expect(header).toContain('this->template addEvent<>("onDone");'); - expect(header).toContain('void emitOnDone() {'); - expect(header).toContain('this->emitEvent("onDone");'); - expect(header).toContain( - '"finish must be declared as void finish(rngpui::Promise<>)', - ); - expect(header).toContain( - 'this->template promiseMethod<&T::finish>("finish");', - ); -}); diff --git a/vendor/react-native-gpui/packages/codegen/src/generate-host-component-cpp.js b/vendor/react-native-gpui/packages/codegen/src/generate-host-component-cpp.js deleted file mode 100644 index 08ce447d51..0000000000 --- a/vendor/react-native-gpui/packages/codegen/src/generate-host-component-cpp.js +++ /dev/null @@ -1,862 +0,0 @@ -import { createRequire } from 'node:module'; -import path from 'node:path'; -import { parseComponents, snakeCase } from './generate-rust-spec.js'; - -/// React Native's own C++ naming helpers, so an enum or a struct is named here -/// exactly as `Props.h` names it. -function loadNamingHelpers(hints) { - const failures = []; - for (const hint of hints) { - try { - const require = createRequire(hint); - const utils = require('@react-native/codegen/lib/generators/Utils.js'); - const cpp = require('@react-native/codegen/lib/generators/components/CppHelpers.js'); - return { - toSafeCppString: utils.toSafeCppString, - getEnumName: utils.getEnumName, - toIntEnumValueName: cpp.toIntEnumValueName, - }; - } catch (error) { - failures.push(`${hint}: ${error.message}`); - } - } - throw new Error( - `generate-host-component-cpp: cannot resolve @react-native/codegen; install it in the app.\n${failures.join('\n')}`, - ); -} - -/// The size and alignment of a Rust scalar as `repr(C)` lays it out. -const SCALAR_LAYOUT = { - i32: { size: 4, align: 4 }, - f32: { size: 4, align: 4 }, - f64: { size: 8, align: 8 }, - bool: { size: 1, align: 1 }, -}; - -/// The C++ type React Native's generator gives a Rust scalar. -const SCALAR_CPP = { - i32: 'int', - f32: 'rr::Float', - f64: 'double', - bool: 'bool', -}; - -/// The C ABI type of a scalar shim argument or return. -const SCALAR_ABI = { - i32: 'int32_t', - f32: 'float', - f64: 'double', - bool: 'bool', -}; - -const alignUp = (value, align) => Math.ceil(value / align) * align; - -/// `repr(C)` layout of a plain mirror: its size, alignment and field offsets. -function layoutOf(generator, mirror, cache = new Map()) { - if (cache.has(mirror.name)) return cache.get(mirror.name); - let offset = 0; - let align = 1; - const offsets = []; - for (const field of mirror.fields) { - let layout = SCALAR_LAYOUT[field.rustType]; - if (layout === undefined) { - const nested = generator.mirrors.find( - candidate => candidate.name === field.rustType, - ); - if (nested !== undefined) { - layout = layoutOf(generator, nested, cache); - } else if (generator.enums.some(e => e.name === field.rustType)) { - // `#[repr(i32)]`. - layout = { size: 4, align: 4 }; - } else { - throw new Error( - `generate-host-component-cpp: unknown mirror field type ${field.rustType}`, - ); - } - } - offset = alignUp(offset, layout.align); - offsets.push(offset); - offset += layout.size; - align = Math.max(align, layout.align); - } - const result = { size: alignUp(offset, align), align, offsets }; - cache.set(mirror.name, result); - return result; -} - -/// How expensive a prop is to compare, so the change mask checks cheap fields -/// first: a 10,000-point chart must not compare every point to answer "did the -/// title change". Bits are positional, so the order changes nothing observable. -function compareCost(shape) { - switch (shape.kind) { - case 'scalar': - case 'enum': - return 0; - case 'color': - case 'string': - return 1; - case 'mirror': - case 'view': - case 'image': - return 2; - case 'mixed': - return 4; - default: - return 3; - } -} - -const cppVar = value => value.replaceAll(/[^A-Za-z0-9_]/gu, '_'); - -/// One component's C++. -class ComponentCpp { - constructor(generator, flags, naming) { - this.generator = generator; - this.flags = flags; - this.naming = naming; - this.name = generator.name; - this.snake = snakeCase(generator.name); - this.propsType = `rr::${generator.name}Props`; - this.emitterType = `rr::${generator.name}EventEmitter`; - this.out = []; - } - - mirrorByName(name) { - return this.generator.mirrors.find(mirror => mirror.name === name); - } - - viewByName(name) { - return this.generator.views.find(view => view.name === name); - } - - cppMirror(name) { - return `rr::${this.mirrorByName(name).cppName}`; - } - - cppView(name) { - return `rr::${this.viewByName(name).cppName}`; - } - - enumCppName(declared) { - return this.naming.getEnumName(this.name, declared.propName); - } - - enumMemberCppName(declared, member) { - return declared.numeric - ? this.naming.toIntEnumValueName(declared.propName, member.text) - : this.naming.toSafeCppString(member.text); - } - - push(...lines) { - this.out.push(...lines); - } - - renderChecks() { - const { generator } = this; - this.push(`// ---- ${this.name}: layout checks`); - this.push( - `static_assert(std::is_base_of_v);`, - ); - const cache = new Map(); - for (const mirror of generator.mirrors) { - const type = `rr::${mirror.cppName}`; - const layout = layoutOf(generator, mirror, cache); - this.push(`static_assert(std::is_standard_layout_v<${type}>);`); - this.push(`static_assert(sizeof(${type}) == ${layout.size});`); - this.push(`static_assert(alignof(${type}) == ${layout.align});`); - mirror.fields.forEach((field, index) => { - this.push( - `static_assert(offsetof(${type}, ${field.jsName}) == ${layout.offsets[index]});`, - ); - const cppType = SCALAR_CPP[field.rustType]; - if (cppType !== undefined) { - this.push( - `static_assert(std::is_same_v);`, - ); - } - }); - } - for (const declared of generator.enums) { - if (declared.eventEnum) continue; - const type = `rr::${this.enumCppName(declared)}`; - this.push(`static_assert(sizeof(${type}) == sizeof(int32_t));`); - for (const member of declared.members) { - this.push( - `static_assert(static_cast(${type}::${this.enumMemberCppName(declared, member)}) == ${member.value});`, - ); - } - } - for (const prop of generator.props) { - const cppType = - prop.shape.kind === 'scalar' ? SCALAR_CPP[prop.shape.rustType] : null; - if (cppType !== null) { - this.push( - `static_assert(std::is_same_v);`, - ); - } - } - for (const view of generator.views) { - for (const field of view.fields) { - const cppType = - field.shape.kind === 'scalar' - ? SCALAR_CPP[field.shape.rustType] - : null; - if (cppType !== null) { - this.push( - `static_assert(std::is_same_v);`, - ); - } - } - } - this.push(''); - } - - /// How to compare two values of a shape for the change mask. - equal(shape, a, b) { - switch (shape.kind) { - case 'image': - return `rn_eq_image(${a}, ${b})`; - case 'mirror': - return `eq_${cppVar(shape.name)}(${a}, ${b})`; - case 'view': - return `eq_${cppVar(shape.name)}(${a}, ${b})`; - case 'array-plain': - return `rn_eq_vec(${a}, ${b}, eq_${cppVar(shape.name)})`; - case 'array-view': - return `rn_eq_vec(${a}, ${b}, eq_${cppVar(shape.name)})`; - default: - return `${a} == ${b}`; - } - } - - /// A mirror's field is a scalar, an enum or another mirror. - mirrorFieldEqual(field, a, b) { - if (this.mirrorByName(field.rustType) !== undefined) { - return `eq_${cppVar(field.rustType)}(${a}, ${b})`; - } - return `${a} == ${b}`; - } - - renderEqualityDeclarations() { - for (const mirror of this.generator.mirrors) { - this.push( - `bool eq_${cppVar(mirror.name)}(const rr::${mirror.cppName}& a, const rr::${mirror.cppName}& b);`, - ); - } - for (const view of this.generator.views) { - this.push( - `bool eq_${cppVar(view.name)}(const rr::${view.cppName}& a, const rr::${view.cppName}& b);`, - ); - } - } - - renderEqualityDefinitions() { - for (const mirror of this.generator.mirrors) { - const terms = mirror.fields.map(field => - this.mirrorFieldEqual(field, `a.${field.jsName}`, `b.${field.jsName}`), - ); - this.push( - `bool eq_${cppVar(mirror.name)}(const rr::${mirror.cppName}& a, const rr::${mirror.cppName}& b) {`, - ` return ${terms.length === 0 ? 'true' : terms.join(' &&\n ')};`, - '}', - '', - ); - } - for (const view of this.generator.views) { - const terms = view.fields.map(field => - this.equal(field.shape, `a.${field.jsName}`, `b.${field.jsName}`), - ); - this.push( - `bool eq_${cppVar(view.name)}(const rr::${view.cppName}& a, const rr::${view.cppName}& b) {`, - ` return ${terms.length === 0 ? 'true' : terms.join(' &&\n ')};`, - '}', - '', - ); - } - } - - renderChanged() { - const { generator } = this; - this.push( - `void ${this.snake}_changed(const rr::Props& rawBefore, const rr::Props& rawAfter, uint64_t* words) {`, - ` const auto& before = static_cast(rawBefore);`, - ` const auto& after = static_cast(rawAfter);`, - ); - const ordered = [...generator.props].sort( - (left, right) => - compareCost(left.shape) - compareCost(right.shape) || - left.index - right.index, - ); - for (const prop of ordered) { - const same = this.equal( - prop.shape, - `before.${prop.jsName}`, - `after.${prop.jsName}`, - ); - const word = Math.floor(prop.index / 64); - const bit = prop.index % 64; - this.push( - ` if (!(${same})) {`, - ` words[${word}] |= uint64_t{1} << ${bit};`, - ' }', - ); - } - this.push('}', ''); - } - - /// The shims for one owner: the props handle, or a view's struct address. - renderAccessors({ shimPrefix, owner, fields }) { - for (const field of fields) { - const shim = `${shimPrefix}_${snakeCase(field.jsName)}`; - const value = `p.${field.jsName}`; - const head = (returns, extra = '') => - `${returns} ${shim}(const void* handle${extra}) {`; - this.push(`// ${field.jsName}`); - switch (field.shape.kind) { - case 'scalar': - this.push( - head(SCALAR_ABI[field.shape.rustType]), - owner, - ` return ${value};`, - '}', - ); - break; - case 'string': - this.push( - head('RnGpuiStr'), - owner, - ` return rn_str(${value});`, - '}', - ); - break; - case 'enum': - this.push( - head('int32_t'), - owner, - ` return static_cast(${value});`, - '}', - ); - break; - case 'color': - this.push( - head('RnGpuiOptU32'), - owner, - ` return rn_color(${value});`, - '}', - ); - break; - case 'image': - case 'view': - this.push(head('const void*'), owner, ` return &${value};`, '}'); - break; - case 'mixed': - this.push( - head('void', ', RnTextSink sink, void* context'), - owner, - ` rn_text(${value}, sink, context);`, - '}', - ); - break; - case 'mirror': - this.push( - head(this.cppMirror(field.shape.name)), - owner, - ` return ${value};`, - '}', - ); - break; - case 'array-scalar': - this.push( - `static_assert(sizeof(decltype(${value.replace('p.', `std::declval<${field.ownerType}>().`)})::value_type) == sizeof(${SCALAR_ABI[field.shape.rustType]}));`, - ); - this.push( - head('RnGpuiSlice'), - owner, - ` return rn_slice(${value});`, - '}', - ); - break; - case 'array-plain': - this.push( - head('RnGpuiSlice'), - owner, - ` return rn_slice(${value});`, - '}', - ); - break; - case 'array-string': - this.push( - `size_t ${shim}_len(const void* handle) {`, - owner, - ` return ${value}.size();`, - '}', - `RnGpuiStr ${shim}_at(const void* handle, size_t index) {`, - owner, - ` return rn_str(${value}[index]);`, - '}', - ); - break; - case 'array-view': - this.push( - `size_t ${shim}_len(const void* handle) {`, - owner, - ` return ${value}.size();`, - '}', - `const void* ${shim}_at(const void* handle, size_t index) {`, - owner, - ` return &${value}[index];`, - '}', - ); - break; - default: - throw new Error( - `generate-host-component-cpp: unsupported accessor shape ${field.shape.kind}`, - ); - } - this.push(''); - } - } - - /// The shim parameters and the statements that fill the event struct, walking - /// the payload leaf by leaf in the order the Rust half flattens it. - flatten(declared, valueExpression, prefix, params, statements) { - for (const field of declared.fields) { - const argument = cppVar( - prefix === '' ? `p_${field.name}` : `${prefix}_${field.name}`, - ); - const target = `${valueExpression}.${field.jsName}`; - switch (field.shape.kind) { - case 'scalar': - params.push(`${SCALAR_ABI[field.shape.rustType]} ${argument}`); - statements.push(`${target} = ${argument};`); - break; - case 'enum': - params.push(`int32_t ${argument}`); - statements.push( - `${target} = static_cast(${argument});`, - ); - break; - case 'string': - params.push( - `const uint8_t* ${argument}_data`, - `size_t ${argument}_len`, - ); - statements.push( - `${target}.assign(reinterpret_cast(${argument}_data), ${argument}_len);`, - ); - break; - case 'array-scalar': - params.push( - `const ${SCALAR_ABI[field.shape.rustType]}* ${argument}_data`, - `size_t ${argument}_len`, - ); - statements.push( - `${target}.assign(${argument}_data, ${argument}_data + ${argument}_len);`, - ); - break; - case 'array-string': - params.push( - `const RnGpuiStr* ${argument}_data`, - `size_t ${argument}_len`, - ); - statements.push( - `${target}.clear();`, - `for (size_t i = 0; i < ${argument}_len; ++i) {`, - ` ${target}.emplace_back(reinterpret_cast(${argument}_data[i].data), ${argument}_data[i].len);`, - '}', - ); - break; - case 'object': { - const nested = this.generator.payloads.find( - candidate => candidate.name === field.shape.typeName, - ); - this.flatten(nested, target, argument, params, statements); - break; - } - default: - throw new Error( - `generate-host-component-cpp: unsupported event payload shape ${field.shape.kind}`, - ); - } - } - } - - renderEvents() { - for (const event of this.generator.events) { - const shim = `rn_gpui_${this.snake}_event_${snakeCase(event.name)}`; - this.push(`// ${event.jsName}`); - if (event.payload === null) { - this.push( - `void ${shim}(const void* emitter) {`, - ` rngpui::hostEmitter<${this.emitterType}>(emitter).${event.jsName}({});`, - '}', - '', - ); - continue; - } - const params = []; - const statements = []; - this.flatten(event.payload, 'rn_payload', '', params, statements); - this.push( - `void ${shim}(${['const void* emitter', ...params].join(', ')}) {`, - ` ${this.emitterType}::${event.payload.name} rn_payload{};`, - ...statements.map(statement => ` ${statement}`), - ` rngpui::hostEmitter<${this.emitterType}>(emitter).${event.jsName}(std::move(rn_payload));`, - '}', - '', - ); - } - } - - /// The check and the conversion of one command argument, as a - /// `HostCommandValue` appended to `values`. - commandArgument(parameter, position) { - const arg = `args[${position}]`; - const type = parameter.rustType; - const name = parameter.jsName; - const fail = what => - ` LOG(ERROR) << "[host-component] ${this.name}.${'${command}'}: argument '${name}' must be ${what}";\n return true;`; - switch (type) { - case 'i32': - case 'f32': - case 'f64': - return [ - ` if (!${arg}.isNumber()) {`, - fail('a number'), - ' }', - ` values.push_back(rn_number(${arg}.asDouble()));`, - ]; - case 'bool': - return [ - ` if (!${arg}.isBool()) {`, - fail('a boolean'), - ' }', - ` values.push_back(rn_bool(${arg}.asBool()));`, - ]; - case 'String': - return [ - ` if (!${arg}.isString()) {`, - fail('a string'), - ' }', - ` values.push_back(rn_string(${arg}.getString()));`, - ]; - case 'Vec': - case 'Vec': - case 'Vec': - return [ - ` if (!rn_all(${arg}, [](const folly::dynamic& v) { return v.isNumber(); })) {`, - fail('an array of numbers'), - ' }', - ` values.push_back(rn_numbers(${arg}));`, - ]; - case 'Vec': - return [ - ` if (!rn_all(${arg}, [](const folly::dynamic& v) { return v.isBool(); })) {`, - fail('an array of booleans'), - ' }', - ` values.push_back(rn_bools(${arg}));`, - ]; - case 'Vec': - return [ - ` if (!rn_all(${arg}, [](const folly::dynamic& v) { return v.isString(); })) {`, - fail('an array of strings'), - ' }', - ` values.push_back(rn_strings(${arg}));`, - ]; - default: - throw new Error( - `generate-host-component-cpp: unsupported command argument ${type}`, - ); - } - } - - renderCommand() { - const { commands } = this.generator; - this.push( - `bool ${this.snake}_command(int32_t tag, const std::string& command, const folly::dynamic& args) {`, - ); - commands.forEach((command, commandIndex) => { - this.push(` if (command == ${JSON.stringify(command.jsName)}) {`); - this.push( - ` if (!args.isArray() || args.size() != ${command.params.length}) {`, - ` LOG(ERROR) << "[host-component] ${this.name}.${command.jsName} takes ${command.params.length} argument(s)";`, - ' return true;', - ' }', - ' std::vector values;', - ` values.reserve(${command.params.length});`, - ); - command.params.forEach((parameter, position) => { - const lines = this.commandArgument(parameter, position) - .map(line => line.replace('${command}', command.jsName)) - .map(line => ` ${line}`); - this.push(...lines); - }); - this.push( - ` rngpui::dispatchHostCommand(tag, ${commandIndex}, std::move(values));`, - ' return true;', - ' }', - ); - }); - this.push(' (void)tag;', ' (void)args;', ' return false;', '}', ''); - } - - render() { - const { generator, flags } = this; - const nameVariable = `k${this.name}Name`; - const shadow = `${this.name}ShadowNode`; - const descriptor = `${this.name}Descriptor`; - this.push(`// ================= ${this.name} =================`, ''); - this.push('namespace {', ''); - this.push( - `inline constexpr char ${nameVariable}[] = ${JSON.stringify(this.name)};`, - ); - if (flags.container) { - this.push( - `using ${shadow} = rngpui::GpuiHostContainerShadowNode<${nameVariable}, ${this.propsType}, ${this.emitterType}>;`, - `using ${descriptor} = rngpui::GpuiHostContainerDescriptor<${shadow}>;`, - ); - } else { - this.push( - `using ${shadow} = rngpui::GpuiHostLeafShadowNode<${nameVariable}, ${this.propsType}, ${this.emitterType}, ${flags.measured ? 'true' : 'false'}>;`, - `using ${descriptor} = rr::ConcreteComponentDescriptor<${shadow}>;`, - ); - } - this.push(''); - this.renderChecks(); - this.renderEqualityDeclarations(); - this.push(''); - this.renderEqualityDefinitions(); - this.renderChanged(); - this.renderCommand(); - this.push(`} // namespace`, ''); - - this.push('extern "C" {', ''); - const propsOwner = ` const auto& p = rngpui::hostProps<${this.propsType}>(handle);`; - this.renderAccessors({ - shimPrefix: `rn_gpui_${this.snake}_props`, - owner: propsOwner, - fields: generator.props.map(prop => ({ - ...prop, - ownerType: this.propsType, - })), - }); - for (const view of generator.views) { - this.renderAccessors({ - shimPrefix: `rn_gpui_${snakeCase(view.name)}`, - owner: ` const auto& p = *static_cast(handle);`, - fields: view.fields.map(field => ({ - ...field, - ownerType: `rr::${view.cppName}`, - })), - }); - } - this.renderEvents(); - this.push('} // extern "C"', ''); - } - - registration(index) { - const { flags } = this; - const nameVariable = `k${this.name}Name`; - return [ - ' {', - ' rngpui::HostComponentEntry entry;', - ` entry.index = ${index};`, - ` entry.name = ${nameVariable};`, - ` entry.handle = ${this.name}ShadowNode::Handle();`, - ` entry.measured = ${flags.measured};`, - ` entry.container = ${flags.container};`, - ` entry.nativeSurface = ${flags.nativeSurface};`, - ` entry.provider = &rr::concreteComponentDescriptorProvider<${this.name}Descriptor>;`, - ` entry.changed = &${this.snake}_changed;`, - ` entry.changeWords = ${this.generator.changeWords};`, - ` entry.command = &${this.snake}_command;`, - ' rngpui::registerHostComponentEntry(entry);', - ' }', - ]; - } -} - -const PROLOGUE = `#include "GpuiHostComponentsCpp.h" - -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace rr = facebook::react; - -namespace { -// Borrowed views of C++ values, as the ABI structs core declares carry them. -inline RnGpuiStr rn_str(const std::string& text) { - return RnGpuiStr{reinterpret_cast(text.data()), text.size()}; -} - -template -inline RnGpuiSlice rn_slice(const std::vector& values) { - return RnGpuiSlice{values.data(), values.size()}; -} - -inline RnGpuiOptU32 rn_color(const rr::SharedColor& color) { - // React Native's unset color is zero. - return RnGpuiOptU32{static_cast(*color), static_cast(color)}; -} - -// A \`folly::dynamic\` has no layout to lend out: it is serialised once and the -// bytes are handed to a callback that copies them. -using RnTextSink = void (*)(void* context, const uint8_t* data, size_t len); - -inline void rn_text(const folly::dynamic& value, RnTextSink sink, void* context) { - const std::string text = folly::toJson(value); - sink(context, reinterpret_cast(text.data()), text.size()); -} - -inline bool rn_eq_image(const rr::ImageSource& a, const rr::ImageSource& b) { - return a.type == b.type && a.uri == b.uri && a.bundle == b.bundle && - a.scale == b.scale && a.size.width == b.size.width && - a.size.height == b.size.height && a.body == b.body && - a.method == b.method; -} - -template -inline bool rn_eq_vec(const std::vector& a, const std::vector& b, Equal equal) { - if (a.size() != b.size()) { - return false; - } - for (size_t i = 0; i < a.size(); ++i) { - if (!equal(a[i], b[i])) { - return false; - } - } - return true; -} - -// Command arguments, validated by the generated dispatcher below. -inline rngpui::HostCommandValue rn_number(double value) { - rngpui::HostCommandValue out; - out.kind = rngpui::HostCommandValue::Number; - out.number = value; - return out; -} - -inline rngpui::HostCommandValue rn_bool(bool value) { - rngpui::HostCommandValue out; - out.kind = rngpui::HostCommandValue::Bool; - out.number = value ? 1 : 0; - return out; -} - -inline rngpui::HostCommandValue rn_string(const std::string& value) { - rngpui::HostCommandValue out; - out.kind = rngpui::HostCommandValue::String; - out.text = value; - return out; -} - -template -inline bool rn_all(const folly::dynamic& array, Predicate predicate) { - if (!array.isArray()) { - return false; - } - for (const auto& item : array) { - if (!predicate(item)) { - return false; - } - } - return true; -} - -inline rngpui::HostCommandValue rn_numbers(const folly::dynamic& array) { - rngpui::HostCommandValue out; - out.kind = rngpui::HostCommandValue::Numbers; - for (const auto& item : array) { - out.numbers.push_back(item.asDouble()); - } - return out; -} - -inline rngpui::HostCommandValue rn_bools(const folly::dynamic& array) { - rngpui::HostCommandValue out; - out.kind = rngpui::HostCommandValue::Bools; - for (const auto& item : array) { - out.numbers.push_back(item.asBool() ? 1 : 0); - } - return out; -} - -inline rngpui::HostCommandValue rn_strings(const folly::dynamic& array) { - rngpui::HostCommandValue out; - out.kind = rngpui::HostCommandValue::Strings; - for (const auto& item : array) { - out.texts.push_back(item.getString()); - } - return out; -} -} // namespace -`; - -/// The C++ source for every component spec in \`specPaths\`. -export function generateHostComponentCpp({ - specPaths, - libraryName, - components, -}) { - const generators = parseComponents({ specPaths }); - if (generators.length === 0) { - return ''; - } - const naming = loadNamingHelpers([ - ...specPaths.map(specPath => path.resolve(specPath)), - path.join(process.cwd(), 'package.json'), - import.meta.url, - ]); - const parts = []; - const registrations = []; - for (const generator of generators) { - const declared = components[generator.name]; - if (declared === undefined) { - throw new Error( - `${generator.specPath}: ${generator.name} is not declared under platforms.desktop.hostComponents in react-native.config.js`, - ); - } - if (generator.component.interfaceOnly !== true) { - throw new Error( - `${generator.specPath}: ${generator.name} must be created with codegenNativeComponent(..., { interfaceOnly: true }); core supplies the shadow node and the descriptor, so React Native must not generate its own`, - ); - } - if (declared.measured && declared.container) { - throw new Error( - `${generator.name}: a host component cannot be both measured and a container; Fabric's MeasurableYogaNode requires a leaf, and a leaf cannot hold children`, - ); - } - const cpp = new ComponentCpp(generator, declared, naming); - cpp.render(); - parts.push(cpp.out.join('\n')); - registrations.push(cpp.registration(declared.index).join('\n')); - } - const identifier = cppVar(libraryName); - return `${[ - '// Generated by @react-native-gpui/codegen from TypeScript specs; do not edit.', - '//', - '// The C++ half of the host component API: it implements the shims the generated', - "// Rust declares, reading React Native's own generated props in place, and", - "// registers each component with core's registry.", - '', - `#include `, - `#include `, - '', - PROLOGUE, - ...parts, - `extern "C" void rn_gpui_register_host_components_${identifier}() {`, - ...registrations, - '}', - ].join('\n')}\n`; -} diff --git a/vendor/react-native-gpui/packages/codegen/src/generate-host-component-cpp.test.js b/vendor/react-native-gpui/packages/codegen/src/generate-host-component-cpp.test.js deleted file mode 100644 index 2083d081c3..0000000000 --- a/vendor/react-native-gpui/packages/codegen/src/generate-host-component-cpp.test.js +++ /dev/null @@ -1,486 +0,0 @@ -import { spawnSync } from 'node:child_process'; -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { createRequire } from 'node:module'; -import { describe, expect, test } from 'vitest'; -import { generateHostComponentCpp } from './generate-host-component-cpp.js'; -import { generateRustSpec } from './generate-rust-spec.js'; -import { KITCHEN_SINK_SPEC } from './kitchen-sink-spec.js'; - -const FLAGS = { - index: 0, - measured: false, - container: false, - nativeSurface: false, -}; - -const writeSpec = (name, source) => { - const directory = fs.mkdtempSync( - path.join(os.tmpdir(), 'host-component-cpp-'), - ); - const file = path.join(directory, `${name}NativeComponent.ts`); - fs.writeFileSync(file, source); - return file; -}; - -const specFile = writeSpec('FixtureChart', KITCHEN_SINK_SPEC); - -const cpp = generateHostComponentCpp({ - specPaths: [specFile], - libraryName: 'KitchenSinkSpec', - components: { FixtureChart: FLAGS }, -}); -const rust = generateRustSpec({ specPaths: [specFile] }); - -/// The names of the `extern "C"` shims the generated Rust declares. -const declaredShims = () => { - const block = rust.slice(rust.lastIndexOf('unsafe extern "C" {')); - return [...block.matchAll(/^\s+fn (rn_gpui_\w+)\(/gmu)].map( - match => match[1], - ); -}; - -describe('the C++ half implements the shims the Rust half declares', () => { - test('every declared shim has a definition of the same name', () => { - const shims = declaredShims(); - expect(shims.length).toBeGreaterThan(20); - const missing = shims.filter( - shim => !new RegExp(`\\b${shim}\\(`, 'u').test(cpp), - ); - expect( - missing.filter(shim => !shim.startsWith('rn_gpui_image_source_')), - ).toEqual([]); - }); - - test('no shim is defined that Rust does not declare', () => { - const declared = new Set(declaredShims()); - const defined = [...cpp.matchAll(/^\S.*\b(rn_gpui_\w+)\(/gmu)].map( - match => match[1], - ); - expect( - defined.filter( - shim => - !declared.has(shim) && - !shim.startsWith('rn_gpui_register_host_components_'), - ), - ).toEqual([]); - }); - - test('the Rust half has no shim for the change mask: C++ computes it', () => { - expect(rust).not.toContain('fn rn_gpui_fixture_chart_changed('); - expect(cpp).toContain('void fixture_chart_changed('); - }); -}); - -describe('the generated file registers the component with core', () => { - test('carries its index, flags and entry points', () => { - const declared = generateHostComponentCpp({ - specPaths: [specFile], - libraryName: 'KitchenSinkSpec', - components: { - FixtureChart: { - index: 7, - measured: false, - container: true, - nativeSurface: true, - }, - }, - }); - expect(declared).toContain('entry.index = 7;'); - expect(declared).toContain('entry.container = true;'); - expect(declared).toContain('entry.nativeSurface = true;'); - expect(declared).toContain('entry.measured = false;'); - expect(declared).toContain('entry.changeWords = 1;'); - expect(declared).toContain( - 'extern "C" void rn_gpui_register_host_components_KitchenSinkSpec() {', - ); - }); - - test("instantiates core's templates over the types React Native generated", () => { - expect(cpp).toContain( - 'rngpui::GpuiHostLeafShadowNode', - ); - expect(cpp).toContain( - 'rr::ConcreteComponentDescriptor', - ); - expect(cpp).toContain( - 'entry.provider = &rr::concreteComponentDescriptorProvider;', - ); - }); - - test('a measured component is a measured leaf, a container uses its own descriptor', () => { - const measured = generateHostComponentCpp({ - specPaths: [specFile], - libraryName: 'KitchenSinkSpec', - components: { FixtureChart: { ...FLAGS, measured: true } }, - }); - expect(measured).toContain('rr::FixtureChartEventEmitter, true>'); - const container = generateHostComponentCpp({ - specPaths: [specFile], - libraryName: 'KitchenSinkSpec', - components: { FixtureChart: { ...FLAGS, container: true } }, - }); - expect(container).toContain( - 'rngpui::GpuiHostContainerShadowNode', - ); - expect(container).toContain( - 'rngpui::GpuiHostContainerDescriptor', - ); - }); -}); - -describe('the change mask', () => { - test('sets one bit per changed prop, in the order the Rust mask names them', () => { - expect(cpp).toContain('words[0] |= uint64_t{1} << 0;'); - expect(cpp).toContain('words[0] |= uint64_t{1} << 14;'); - }); - - test('compares cheap fields before arrays and dynamic values', () => { - const body = cpp.slice(cpp.indexOf('void fixture_chart_changed(')); - const scalar = body.indexOf('before.lineWidth == after.lineWidth'); - const array = body.indexOf('rn_eq_vec(before.points'); - const dynamic = body.indexOf('before.extra == after.extra'); - expect(scalar).toBeGreaterThan(-1); - expect(array).toBeGreaterThan(scalar); - expect(dynamic).toBeGreaterThan(array); - }); - - test('compares a struct field by field, never by memcmp over padding', () => { - expect(cpp).not.toContain('memcmp'); - expect(cpp).toContain('bool eq_FixtureChartPoints('); - }); - - test('spans a word per 64 props', () => { - const props = Array.from( - { length: 130 }, - (_, index) => ` prop${index}?: Int32;`, - ); - const file = writeSpec( - 'Many', - `import { codegenNativeComponent, type ViewProps } from 'react-native'; -export interface NativeProps extends ViewProps { -${props.join('\n')} -} -export default codegenNativeComponent('Many', { interfaceOnly: true }); -`, - ); - const many = generateHostComponentCpp({ - specPaths: [file], - libraryName: 'ManySpec', - components: { Many: FLAGS }, - }); - expect(many).toContain('entry.changeWords = 3;'); - expect(many).toContain('words[2] |= uint64_t{1} << 1;'); - }); -}); - -describe('commands and events', () => { - test('validate arguments against the spec and dispatch by index', () => { - expect(cpp).toContain('bool fixture_chart_command('); - expect(cpp).toContain('if (command == "selectPoint")'); - expect(cpp).toContain( - 'rngpui::dispatchHostCommand(tag, 0, std::move(values));', - ); - expect(cpp).toContain( - 'rngpui::dispatchHostCommand(tag, 1, std::move(values));', - ); - expect(cpp).toContain( - 'rngpui::dispatchHostCommand(tag, 2, std::move(values));', - ); - expect(cpp).toContain('.isNumber()'); - expect(cpp).toContain('rn_numbers(args[0])'); - expect(cpp).toContain('.isString()'); - expect(cpp).toContain( - "FixtureChart.selectPoint: argument 'index' must be a number", - ); - }); - - test('fill the generated event struct from the flattened leaves', () => { - expect(cpp).toContain( - 'rr::FixtureChartEventEmitter::OnPointSelected rn_payload{};', - ); - expect(cpp).toContain('rn_payload.index = p_index;'); - expect(cpp).toContain('.onPointSelected(std::move(rn_payload));'); - expect(cpp).toContain('rn_payload.nested.flag = p_nested_flag;'); - expect(cpp).toContain('rn_payload.nested.names.emplace_back('); - expect(cpp).toContain( - 'void rn_gpui_fixture_chart_event_done(const void* emitter) {', - ); - }); - - test('a payload field called value or emitter cannot collide with a local or the emitter parameter', () => { - const shims = cpp - .split('\n') - .filter(line => /^void rn_gpui_\w+_event_\w+\(/u.test(line)); - expect(shims.length).toBeGreaterThan(1); - for (const shim of shims) { - expect(shim).not.toMatch( - /\b(?:int32_t|double|bool|size_t) (?:value|emitter)\b/u, - ); - } - expect(cpp).toMatch(/rn_payload\.\w+ = p_\w+;/u); - }); -}); - -describe('an event payload field named like a local of the shim', () => { - const source = ` -import { codegenNativeComponent, type CodegenTypes, type ViewProps } from 'react-native'; -export interface NativeProps extends ViewProps { - onChanged?: CodegenTypes.DirectEventHandler< - Readonly<{ value: string; emitter: CodegenTypes.Double }> - >; -} -export default codegenNativeComponent('FixtureValue', { interfaceOnly: true }); -`; - const file = writeSpec('FixtureValue', source); - const generated = generateHostComponentCpp({ - specPaths: [file], - libraryName: 'ValueSpec', - components: { FixtureValue: FLAGS }, - }); - - test('is a parameter of its own, apart from the payload and the emitter', () => { - expect(generated).toContain('rn_payload.value.assign('); - expect(generated).toContain('rn_payload.emitter = p_emitter;'); - expect(generated).not.toMatch(/\bvalue\{\}/u); - expect(generated).toMatch( - /const uint8_t\* p_value_data, size_t p_value_len/u, - ); - }); -}); - -describe('the generator rejects a component core cannot host', () => { - test('one that is not declared under hostComponents', () => { - expect(() => - generateHostComponentCpp({ - specPaths: [specFile], - libraryName: 'KitchenSinkSpec', - components: {}, - }), - ).toThrow( - /FixtureChart is not declared under platforms\.desktop\.hostComponents/u, - ); - }); - - test('one that is not interfaceOnly: React Native would generate a second descriptor', () => { - const file = writeSpec( - 'Plain', - KITCHEN_SINK_SPEC.replace( - /\{\s*interfaceOnly: true,?\s*\}/u, - '{ paperComponentName: "FixtureChart" }', - ), - ); - expect(() => - generateHostComponentCpp({ - specPaths: [file], - libraryName: 'KitchenSinkSpec', - components: { FixtureChart: FLAGS }, - }), - ).toThrow( - /must be created with codegenNativeComponent\(\.\.\., \{ interfaceOnly: true \}\)/u, - ); - }); - - test('one that is both measured and a container', () => { - expect(() => - generateHostComponentCpp({ - specPaths: [specFile], - libraryName: 'KitchenSinkSpec', - components: { - FixtureChart: { ...FLAGS, measured: true, container: true }, - }, - }), - ).toThrow(/cannot be both measured and a container/u); - }); -}); - -/// The compile flags of core's own C++, from a CMake tree that was built here. -/// Absent on a machine that never built the app, where the compile test skips. -const buildTree = path.resolve( - path.dirname(new URL(import.meta.url).pathname), - '../../../target/rn-gpui-cmake/aarch64-apple-darwin/Debug/build', -); -const flagsFile = path.join( - buildTree, - 'CMakeFiles/rn_gpui_core.dir/flags.make', -); -const canCompile = fs.existsSync(flagsFile) && fs.existsSync('/usr/bin/c++'); - -const flag = name => { - const line = fs - .readFileSync(flagsFile, 'utf8') - .split('\n') - .find(candidate => candidate.startsWith(`${name} =`)); - return line === undefined ? '' : line.slice(name.length + 3); -}; - -/// The newest cxx bridge header cargo generated, which declares the shared -/// structs core's headers include. -const bridgeInclude = () => { - const builds = path.resolve(buildTree, '../../../../debug/build'); - const candidates = fs - .readdirSync(builds) - .filter(entry => entry.startsWith('rn-gpui-sys-')) - .map(entry => path.join(builds, entry, 'out/cxxbridge/include')) - .filter(directory => - fs.existsSync(path.join(directory, 'rn-gpui-sys/src/lib.rs.h')), - ) - .sort( - (left, right) => - fs.statSync(path.join(right, 'rn-gpui-sys/src/lib.rs.h')).mtimeMs - - fs.statSync(path.join(left, 'rn-gpui-sys/src/lib.rs.h')).mtimeMs, - ); - return candidates[0]; -}; - -describe.skipIf(!canCompile)( - 'the generated file compiles against the real headers', - () => { - const root = path.resolve( - path.dirname(new URL(import.meta.url).pathname), - '../../..', - ); - - /// Generates React Native's own `Props.h` and `EventEmitters.h` for `file` - /// into a fresh include tree, and returns the include directory. - const reactNativeHeaders = (file, libraryName) => { - const require = createRequire(path.join(root, 'package.json')); - const schema = - require('@react-native/codegen/lib/cli/combine/combine-js-to-schema').combineSchemasInFileList( - [file], - 'desktop', - null, - libraryName, - ); - const include = fs.mkdtempSync( - path.join(os.tmpdir(), 'host-component-include-'), - ); - const staging = fs.mkdtempSync( - path.join(os.tmpdir(), 'host-component-rn-'), - ); - const generated = - require('@react-native/codegen/lib/generators/RNCodegen.js').generate( - { - libraryName, - schema, - outputDirectory: staging, - packageName: 'test', - assumeNonnull: false, - }, - { - generators: [ - 'descriptors', - 'events', - 'props', - 'states', - 'shadow-nodes', - ], - }, - ); - expect(generated).toBe(true); - const target = path.join( - include, - 'react/renderer/components', - libraryName, - ); - fs.mkdirSync(target, { recursive: true }); - for (const header of ['Props.h', 'EventEmitters.h']) { - fs.copyFileSync(path.join(staging, header), path.join(target, header)); - } - return include; - }; - - const compile = (source, include) => { - const file = path.join( - fs.mkdtempSync(path.join(os.tmpdir(), 'host-component-cc-')), - 'generated.cpp', - ); - fs.writeFileSync(file, source); - const bridge = bridgeInclude(); - const command = [ - '/usr/bin/c++', - flag('CXX_DEFINES'), - flag('CXX_FLAGS'), - `-I${include}`, - `-I${bridge}`, - `-I${path.join(bridge, '../crate')}`, - flag('CXX_INCLUDES'), - '-fsyntax-only', - file, - ].join(' '); - return spawnSync('/bin/sh', ['-c', command], { - cwd: buildTree, - encoding: 'utf8', - }); - }; - - test('every layout, offset and enum value matches the real types', () => { - const include = reactNativeHeaders(specFile, 'KitchenSinkSpec'); - const result = compile(cpp, include); - expect(result.stderr).toBe(''); - expect(result.status).toBe(0); - }, 120_000); - - test('a wrong layout breaks the build instead of corrupting a prop', () => { - const include = reactNativeHeaders(specFile, 'KitchenSinkSpec'); - const broken = cpp.replace( - 'offsetof(rr::FixtureChartPointsStruct, y) == 8', - 'offsetof(rr::FixtureChartPointsStruct, y) == 16', - ); - expect(broken).not.toBe(cpp); - const result = compile(broken, include); - expect(result.status).not.toBe(0); - expect(result.stderr).toContain('static assertion failed'); - }, 120_000); - - test('a measured leaf, a container and a 130 prop component compile too', () => { - const include = reactNativeHeaders(specFile, 'KitchenSinkSpec'); - for (const flags of [ - { ...FLAGS, measured: true }, - { ...FLAGS, container: true, nativeSurface: true }, - ]) { - const source = generateHostComponentCpp({ - specPaths: [specFile], - libraryName: 'KitchenSinkSpec', - components: { FixtureChart: flags }, - }); - const result = compile(source, include); - expect(result.stderr).toBe(''); - } - - const props = Array.from( - { length: 130 }, - (_, index) => ` prop${index}?: Int32;`, - ); - const many = writeSpec( - 'Many', - `import { codegenNativeComponent, type ViewProps } from 'react-native'; -export interface NativeProps extends ViewProps { -${props.join('\n')} -} -export default codegenNativeComponent('Many', { interfaceOnly: true }); -`, - ); - const manyInclude = reactNativeHeaders(many, 'ManySpec'); - const result = compile( - generateHostComponentCpp({ - specPaths: [many], - libraryName: 'ManySpec', - components: { Many: FLAGS }, - }), - manyInclude, - ); - expect(result.stderr).toBe(''); - }, 240_000); - }, -); - -describe('an enum in an event payload', () => { - test('is filled from its discriminant, and no layout check names a type for it', () => { - expect(cpp).toContain( - 'rn_payload.speed = static_cast(', - ); - expect(cpp).not.toContain('FixtureChartSpeed'); - }); -}); diff --git a/vendor/react-native-gpui/packages/codegen/src/generate-rust-spec.component.test.js b/vendor/react-native-gpui/packages/codegen/src/generate-rust-spec.component.test.js deleted file mode 100644 index 2b554df106..0000000000 --- a/vendor/react-native-gpui/packages/codegen/src/generate-rust-spec.component.test.js +++ /dev/null @@ -1,742 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { describe, expect, test } from 'vitest'; -import { generateRustSpec } from './generate-rust-spec.js'; -import { KITCHEN_SINK_SPEC as FIXTURE } from './kitchen-sink-spec.js'; - -/// Generates from a spec body, written to a temporary file because the parser -/// reads the spec from disk. -const generateFrom = spec => { - const directory = fs.mkdtempSync( - path.join(os.tmpdir(), 'rust-component-spec-'), - ); - const file = path.join(directory, 'FixtureComponentSpec.ts'); - fs.writeFileSync(file, spec); - return generateRustSpec({ specPaths: [file] }); -}; - -/// A spec with `props` as its only props, for one table row at a time. -const withProps = props => - `import { - codegenNativeComponent, - type CodegenTypes, - type ViewProps, -} from 'react-native'; - -export interface NativeProps extends ViewProps { -${props} -} - -const Temp: any = null; - -export default codegenNativeComponent('Temp', { interfaceOnly: true }); -`; - -const header = generateFrom(FIXTURE); - -const countOf = (text, needle) => text.split(needle).length - 1; - -describe('a component spec becomes the generated API', () => { - test('renders the seven artifacts 5.1 lists', () => { - expect(header).toContain('pub struct FixtureChartProps {'); - expect(header).toContain('pub struct FixtureChartChanged {'); - expect(header).toContain('pub struct FixtureChartEvents<'); - expect(header).toContain('pub trait FixtureChartSpec: Sized +'); - expect(header).toContain('pub struct FixtureChartContext {'); - expect(header).toContain( - 'pub const fn fixture_chart_component() -> FixtureChartComponent {', - ); - // The `#[repr(C)]` mirror the props and the C++ file agree on. - expect(header).toContain( - '#[repr(C)]\n#[derive(Clone, Copy, Debug, PartialEq)]\npub struct FixtureChartPoints {', - ); - }); - - test('generates the trait of 5.1 exactly', () => { - expect(header).toContain( - 'fn create(props: &FixtureChartProps, cx: &mut FixtureChartContext) -> Self;', - ); - expect(header).toContain( - 'fn update(\n &mut self,\n props: &FixtureChartProps,\n changed: FixtureChartChanged,\n cx: &mut FixtureChartContext,\n );', - ); - expect(header).toContain( - 'fn render(\n &mut self,\n props: &FixtureChartProps,\n window: &mut Window,\n cx: &mut FixtureChartContext,\n ) -> AnyElement;', - ); - }); - - test('gives every command a typed method, in snake_case', () => { - expect(header).toContain( - 'fn select_point(&mut self, index: i32, cx: &mut FixtureChartContext);', - ); - expect(header).toContain( - 'fn report_series(&mut self, values: Vec, cx: &mut FixtureChartContext);', - ); - expect(header).toContain( - 'fn set_title(&mut self, title: String, cx: &mut FixtureChartContext);', - ); - }); - - test('generates the context the trait methods take', () => { - expect(header).toContain('pub struct FixtureChartContext {'); - expect(header).toContain('host: HostContext,'); - expect(header).toContain( - "pub fn events(&mut self) -> FixtureChartEvents<'_> {", - ); - expect(header).toContain( - 'pub fn set_intrinsic_size(&mut self, width: f32, height: f32) {', - ); - expect(header).toContain( - 'pub fn set_insets(&mut self, top: f32, right: f32, bottom: f32, left: f32) {', - ); - expect(header).toContain( - 'pub fn app(&mut self) -> Option<&mut gpui::App> {', - ); - expect(header).toContain( - 'pub fn window(&mut self) -> Option<&mut gpui::Window> {', - ); - expect(header).toContain('pub fn with_window('); - }); - - test('generates a measure method the component may implement, and the adapter that reads the props handle for it', () => { - expect(header).toContain( - 'fn measure(props: &FixtureChartProps, constraint: &MeasureConstraint) -> Option {', - ); - expect(header).toContain( - 'fn measure(props: *const core::ffi::c_void, constraint: &MeasureConstraint) -> Option {', - ); - expect(header).toContain('T::measure(&view, constraint)'); - }); - - test('generates one typed event method per event', () => { - expect(header).toContain('pub struct OnPointSelected {'); - expect(header).toContain('pub index: i32,'); - expect(header).toContain('pub label: String,'); - expect(header).toContain( - 'pub fn point_selected(&mut self, value: OnPointSelected) {', - ); - expect(header).toContain('pub fn done(&mut self) {'); - expect(header).toContain('pub struct OnRichNested {'); - expect(header).toContain('pub fn rich(&mut self, value: OnRich) {'); - }); - - test('queues an event with an owned payload instead of sending it mid-call', () => { - expect(header).toContain( - 'self.context.host.as_mut().expect("a Fabric node has a host context").queue_event(move || {', - ); - expect(header).toContain( - 'let emitter = self.context.emitter.clone().expect("a Fabric node has an emitter");', - ); - expect(header).toContain('rn_gpui_fixture_chart_event_point_selected('); - expect(header).toContain( - 'pub struct FixtureChartContext {\n host: Option,\n emitter: Option,\n native: Option,\n}', - ); - }); - - test('gives a container an optional overlay that defaults to none', () => { - expect(header).toContain('fn render_overlay('); - expect(header).toContain(') -> Option {'); - expect(header).toContain('let _ = (props, window, cx);'); - }); - - test('hands out an owned event sender with the same typed methods', () => { - expect(header).toContain('pub struct FixtureChartEventSender {'); - expect(header).toContain( - 'pub fn event_sender(&self) -> FixtureChartEventSender', - ); - expect(header).toContain( - 'self.host.as_ref().expect("a Fabric node has an event sender").send(move || {', - ); - expect(header).toContain( - 'pub fn point_selected(&self, value: OnPointSelected)', - ); - // The shim is declared once, although two types send through it. - expect( - countOf(header, 'fn rn_gpui_fixture_chart_event_point_selected('), - ).toBe(1); - }); - - test('gives a native view component a view hook that defaults to an error', () => { - expect(header).toContain('fn create_view('); - expect(header).toContain( - '-> react_native_gpui::native_surface::Result', - ); - expect(header).toContain("parent: &NativeViewParent<'_>,"); - expect(header).toContain('fn update_view('); - expect(header).toContain( - 'self.component.create_view(&self.props, parent, window, &mut cx)', - ); - expect(header).toContain( - 'self.component.update_view(view, &self.props, changed, &mut cx)', - ); - }); - - test('wires the spec into core through a generated instance', () => { - expect(header).toContain( - 'struct FixtureChartInstance {', - ); - expect(header).toContain( - 'impl HostObject for FixtureChartInstance {', - ); - expect(header).toContain( - 'self.props = unsafe { FixtureChartProps::from_handle(props.as_ptr()) };', - ); - expect(header).toContain( - 'let changed = FixtureChartChanged::from_slice(changed);', - ); - expect(header).toContain( - '0 => self.component.select_point(args[0].to_i32(), &mut cx),', - ); - expect(header).toContain( - '1 => self.component.report_series(args[0].to_f64_vec(), &mut cx),', - ); - expect(header).toContain( - '2 => self.component.set_title(args[0].to_string_value(), &mut cx),', - ); - expect(header).toContain( - 'impl HostComponentSpec for FixtureChartComponent {', - ); - }); - - test('carries the declared shape on the registration value', () => { - expect(header).toContain('pub const NAME: &\'static str = "FixtureChart";'); - expect(header).toContain( - 'pub const PROPS: &\'static [&\'static str] = &[\n "lineWidth",\n "opacity",\n "ratio",\n "flag",', - ); - expect(header).toContain( - 'pub const EVENTS: &\'static [&\'static str] = &["onPointSelected", "onRich", "onDone"];', - ); - expect(header).toContain( - 'pub const COMMANDS: &\'static [&\'static str] = &["selectPoint", "reportSeries", "setTitle"];', - ); - }); -}); - -describe('the props view reads each type of the 5.2 table', () => { - test('a scalar is the value', () => { - expect(header).toContain('pub fn line_width(&self) -> i32 {'); - expect(header).toContain('pub fn opacity(&self) -> f32 {'); - expect(header).toContain('pub fn ratio(&self) -> f64 {'); - expect(header).toContain('pub fn flag(&self) -> bool {'); - expect(header).toContain( - 'fn rn_gpui_fixture_chart_props_line_width(props: *const core::ffi::c_void) -> i32;', - ); - }); - - test('a WithDefault prop is the value, with the default already applied by React Native', () => { - expect(header).toContain('pub fn tick_count(&self) -> i32 {'); - expect(header).not.toContain('pub fn tick_count(&self) -> Option'); - expect(header).toContain('pub fn mode(&self) -> FixtureChartMode {'); - }); - - test('a string union is a #[repr(i32)] enum whose discriminants match C++', () => { - expect(header).toContain('#[repr(i32)]'); - expect(header).toContain( - 'pub enum FixtureChartMode {\n /// `line`\n Line = 0,\n /// `bar`\n Bar = 1,\n}', - ); - expect(header).toContain('pub const fn as_raw(self) -> i32 {'); - expect(header).toContain('pub fn from_raw(value: i32) -> Self {'); - }); - - test('a string is borrowed as &str', () => { - expect(header).toContain('pub fn title(&self) -> &str {'); - expect(header).toContain( - 'unsafe { rn_gpui_str(rn_gpui_fixture_chart_props_title(self.handle)) }', - ); - expect(header).toContain( - 'fn rn_gpui_fixture_chart_props_title(props: *const core::ffi::c_void) -> RnGpuiStr;', - ); - expect(header).toContain('pub struct RnGpuiStr {'); - }); - - test('a ColorValue is Option', () => { - expect(header).toContain('pub fn line_color(&self) -> Option {'); - expect(header).toContain('if color.present {'); - expect(header).toContain('Some(color.value)'); - expect(header).toContain( - 'fn rn_gpui_fixture_chart_props_line_color(props: *const core::ffi::c_void) -> RnGpuiOptU32;', - ); - }); - - test('an ImageSource is a view with borrowed accessors', () => { - expect(header).toContain('pub fn icon(&self) -> RnGpuiImageSource {'); - expect(header).toContain('pub fn uri(&self) -> &str {'); - expect(header).toContain('pub fn scale(&self) -> f32 {'); - expect(header).toContain('pub fn width(&self) -> f32 {'); - expect(header).toContain('pub fn height(&self) -> f32 {'); - expect(header).toContain( - 'fn rn_gpui_image_source_uri(image: *const core::ffi::c_void) -> RnGpuiStr;', - ); - }); - - test('an array of plain structs is a borrowed &[T] of the #[repr(C)] mirror', () => { - expect(header).toContain('pub fn points(&self) -> &[FixtureChartPoints] {'); - expect(header).toContain( - 'unsafe { rn_gpui_slice(rn_gpui_fixture_chart_props_points(self.handle)) }', - ); - expect(header).toContain( - 'fn rn_gpui_fixture_chart_props_points(props: *const core::ffi::c_void) -> RnGpuiSlice;', - ); - expect(header).toContain( - 'pub struct FixtureChartPoints {\n /// `x`\n pub x: f64,\n /// `y`\n pub y: f64,\n}', - ); - }); - - test('an array of scalars is a borrowed &[T]', () => { - expect(header).toContain('pub fn values(&self) -> &[f64] {'); - expect(header).toContain( - 'fn rn_gpui_fixture_chart_props_values(props: *const core::ffi::c_void) -> RnGpuiSlice;', - ); - }); - - test('an array of strings is read one string at a time, without allocating', () => { - expect(header).toContain("pub fn labels(&self) -> RnGpuiStrArray<'_> {"); - expect(header).toContain( - 'let len = unsafe { rn_gpui_fixture_chart_props_labels_len(self.handle) };', - ); - expect(header).toContain( - 'unsafe { RnGpuiStrArray::new(self.handle, len, rn_gpui_fixture_chart_props_labels_at) }', - ); - expect(header).toContain("pub struct RnGpuiStrArray<'a> {"); - expect(header).not.toContain('RnGpuiStrSlice'); - }); - - test('an object with strings or arrays is a view with accessors', () => { - expect(header).toContain("pub struct FixtureChartCard<'a> {"); - expect(header).toContain('pub fn title(&self) -> &str {'); - expect(header).toContain( - "pub fn nested(&self) -> FixtureChartCardNested<'_> {", - ); - expect(header).not.toContain( - '#[repr(C)]\n#[derive(Clone, Copy, Debug, PartialEq)]\npub struct FixtureChartCard {', - ); - expect(header).toContain("pub struct FixtureChartCardNested<'a> {"); - expect(header).toContain('pub fn flag(&self) -> bool {'); - expect(header).toContain("pub fn names(&self) -> RnGpuiStrArray<'_> {"); - }); - - test('an array of non-plain structs is a length plus indexed views', () => { - expect(header).toContain( - "pub fn cards(&self) -> FixtureChartCardsSlice<'_> {", - ); - expect(header).toContain( - 'let len = unsafe { rn_gpui_fixture_chart_props_cards_len(self.handle) };', - ); - expect(header).toContain("pub struct FixtureChartCardsSlice<'a> {"); - expect(header).toContain( - "pub fn get(&self, index: usize) -> Option> {", - ); - expect(header).toContain( - 'let handle = unsafe { rn_gpui_fixture_chart_props_cards_at(self.handle, index) };', - ); - expect(header).toContain( - 'fn rn_gpui_fixture_chart_props_cards_len(props: *const core::ffi::c_void) -> usize;', - ); - expect(header).toContain('fn rn_gpui_fixture_chart_props_cards_at('); - expect(header).toContain('index: usize,'); - expect(header).toContain(') -> *const core::ffi::c_void;'); - }); - - test('UnsafeMixed is a Value, converted on the first read only', () => { - expect(header).toContain('pub fn extra(&self) -> &Value {'); - expect(header).toContain('mixed_extra: std::cell::OnceCell,'); - expect(header).toContain('self.mixed_extra.get_or_init(|| {'); - expect(header).toContain('rn_gpui_collect_text,'); - expect(header).toContain( - 'react_native_gpui::host_component::parse_value(&text)', - ); - expect(header).toContain('fn rn_gpui_fixture_chart_props_extra('); - expect(header).toContain('sink: RnGpuiTextSink,'); - expect(header).toContain('context: *mut core::ffi::c_void,'); - }); - - test('an array of booleans is rejected: std::vector is bit-packed', () => { - expect(() => - generateFrom(withProps(' flags?: ReadonlyArray;')), - ).toThrow( - /prop flags: an array of booleans is a bit-packed std::vector/u, - ); - }); - - test('a borrow is tied to &self, so it cannot outlive the handle', () => { - expect(header).toContain('pub fn title(&self) -> &str {'); - expect(header).toContain('pub fn points(&self) -> &[FixtureChartPoints] {'); - expect(header).toContain("pub fn card(&self) -> FixtureChartCard<'_> {"); - expect(header).not.toContain('pub fn title(&self) -> String {'); - }); -}); - -describe('the change mask', () => { - test('has one bit per prop, with a getter named after it', () => { - expect(header).toContain('words: [u64; 1],'); - expect(header).toContain('pub const fn line_width(&self) -> bool {'); - expect(header).toContain('self.words[0] & (1u64 << 0) != 0'); - expect(header).toContain('pub const fn extra(&self) -> bool {'); - expect(header).toContain('self.words[0] & (1u64 << 14) != 0'); - expect(header).not.toContain('pub const fn on_done(&self) -> bool {'); - }); - - test('reports a token with changed.report_token(), as 5.1 writes it', () => { - const reported = generateFrom(withProps(' reportToken?: Int32;')); - expect(reported).toContain('pub const fn report_token(&self) -> bool {'); - expect(reported).toContain('self.words[0] & (1u64 << 0) != 0'); - expect(header).toContain('pub const fn points(&self) -> bool {'); - }); - - test('has none/from_words/words/is_empty for core and for tests', () => { - expect(header).toContain('pub const fn none() -> Self {'); - expect(header).toContain('Self { words: [0; 1] }'); - expect(header).toContain( - 'pub const fn from_words(words: [u64; 1]) -> Self {', - ); - expect(header).toContain('pub const fn words(&self) -> [u64; 1] {'); - expect(header).toContain('pub fn is_empty(&self) -> bool {'); - expect(header).toContain('self.words.iter().all(|word| *word == 0)'); - expect(header).toContain('#[repr(transparent)]'); - }); - - test('uses one u64 up to 64 props and documents the threshold', () => { - expect(header).toContain('**Up to 64 props fit one `u64`;**'); - expect(header).toContain('pub const CHANGE_WORDS: usize = 1;'); - expect(header).not.toContain('fn rn_gpui_fixture_chart_changed('); - expect(header).toContain('pub fn from_slice(words: &[u64]) -> Self {'); - }); - - test('uses a word per 64 props above 64', () => { - const props = Array.from( - { length: 130 }, - (_, index) => ` prop${index}?: Int32;`, - ).join('\n'); - const many = generateFrom(withProps(props)); - expect(many).toContain('words: [u64; 3],'); - expect(many).toContain('pub const CHANGE_WORDS: usize = 3;'); - expect(many).toContain('pub const fn prop129(&self) -> bool {'); - expect(many).toContain('self.words[2] & (1u64 << 1) != 0'); - expect(many).not.toContain('fn rn_gpui_temp_changed('); - expect(many).toContain('pub fn from_slice(words: &[u64]) -> Self {'); - expect(many).toContain('let mut out = [0u64; 3];'); - }); - - test('is transparent over its word array, so the C++ comparison writes it in place', () => { - expect(header).toContain('#[repr(transparent)]'); - expect(header).toContain('words: [u64; 1],'); - expect(header).toMatch( - /#\[repr\(transparent\)\][\s\S]{0,200}pub struct FixtureChartChanged \{\n {4}words:/u, - ); - }); - - test('is empty for a spec with no props', () => { - const empty = generateFrom(withProps(' title?: string;')); - expect(empty).toContain('words: [u64; 1],'); - }); -}); - -describe('the generated file', () => { - test('emits the ABI types once, however many components it declares', () => { - expect(countOf(header, 'pub struct RnGpuiStr {')).toBe(1); - expect(countOf(header, 'pub struct RnGpuiSlice {')).toBe(1); - expect(countOf(header, 'pub struct RnGpuiImageSource {')).toBe(1); - const withoutImage = generateFrom(withProps(' title?: string;')); - expect(withoutImage).not.toContain('pub struct RnGpuiImageSource {'); - expect(withoutImage).toContain('pub struct RnGpuiStr {'); - }); - - test('names shims after the component, the prop and the path, for the C++ half', () => { - expect(header).toContain('fn rn_gpui_fixture_chart_props_line_width('); - expect(header).toContain('fn rn_gpui_fixture_chart_card_nested('); - expect(header).toContain('fn rn_gpui_fixture_chart_event_point_selected('); - expect(header).toContain('fn rn_gpui_fixture_chart_props_cards_len('); - expect(header).toContain('fn rn_gpui_fixture_chart_props_cards_at('); - expect(header).toContain('fn rn_gpui_fixture_chart_card_nested_names_len('); - expect(header).toContain('fn rn_gpui_fixture_chart_card_nested_names_at('); - }); - - test('converts a props string with a checked conversion, never unchecked', () => { - expect(countOf(header, 'from_utf8_unchecked(')).toBe(0); - expect(header).toContain('match core::str::from_utf8(bytes)'); - }); - - test('imports only what a component needs', () => { - expect(header).toContain('use gpui::{AnyElement, Window};'); - expect(header).toContain( - 'EmitterHandle, HostArg, HostComponentSpec, HostContext, HostEventSender, HostObject,', - ); - expect(header).not.toContain('use rn_gpui_module::'); - }); - - test('still generates a module for a NativeModule spec', async () => { - const { generateRustSpec: generate } = - await import('./generate-rust-spec.js'); - const fixtureSpec = path.resolve( - path.dirname(new URL(import.meta.url).pathname), - '../../../packages/core/ReactGpui/rn-gpui-module/tests/generated/specs/NativeProbe.ts', - ); - const module = generate({ specPaths: [fixtureSpec] }); - expect(module).toContain('pub trait NativeProbeSpec:'); - expect(module).toContain('use rn_gpui_module::'); - expect(module).not.toContain('pub struct NativeProbeProps {'); - }); -}); - -describe('the generator fails, naming the prop', () => { - test('for an array of a type it cannot lay out', () => { - expect(() => - generateFrom( - withProps(' icons?: ReadonlyArray;'), - ), - ).toThrow( - /FixtureComponentSpec\.ts: prop icons: unsupported array element MixedTypeAnnotation/u, - ); - }); - - test('for a prop type it does not know', () => { - expect(() => generateFrom(withProps(' host?: HostObject;'))).toThrow( - /Unknown prop type for "host": "HostObject"/u, - ); - }); -}); - -const nativeSpec = `import { - codegenNativeCommands, - codegenNativeComponent, - type CodegenTypes, - type ViewProps, -} from 'react-native'; - -type Reported = Readonly<{ - kind: string; - level: CodegenTypes.Int32; - speed: 'fast' | 'slow'; -}>; - -export interface NativeProps extends ViewProps { - title: string; - size?: CodegenTypes.Double; - count?: CodegenTypes.Int32; - active?: boolean; - mode?: CodegenTypes.WithDefault<'compact' | 'roomy', 'compact'>; - values?: ReadonlyArray; - onReported?: CodegenTypes.DirectEventHandler; - onPlain?: CodegenTypes.DirectEventHandler; -} - -export interface NativeFixtureCommands { - ping: ( - ref: React.ComponentRef, - label: string, - times: CodegenTypes.Int32, - ) => void; -} - -export const Commands = codegenNativeCommands({ - supportedCommands: ['ping'], -}); - -const NativeFixture: any = null; - -export default codegenNativeComponent('NativeFixture', { - interfaceOnly: true, -}); -`; - -describe('a component spec is also a component of a native tree', () => { - const generated = generateFrom(nativeSpec); - - test('reads its props from the JSON of a native tree instance, with the accessors it has for C++', () => { - expect(generated).toContain( - 'pub fn from_json(json: &Map) -> Self {', - ); - expect(generated).toContain('if !self.json.is_null() {'); - expect(generated).toContain( - 'return json.get("title").and_then(Value::as_str).unwrap_or_default();', - ); - expect(generated).toContain( - 'return json.get("size").and_then(Value::as_f64).unwrap_or(0_f64) as f64;', - ); - expect(generated).toContain( - 'return json.get("count").and_then(Value::as_i64).unwrap_or(0_i64) as i32;', - ); - expect(generated).toContain( - 'return json.get("active").and_then(Value::as_bool).unwrap_or(false);', - ); - expect(generated).toContain('return NativeFixtureMode::from_json('); - expect(generated).toContain('return self.native_values.get_or_init(|| {'); - }); - - test('names the props an update changed by their JavaScript names', () => { - expect(generated).toContain( - 'pub fn from_names(names: &[String]) -> Self {', - ); - expect(generated).toContain('"title" => out[0] |= 1u64 << 0,'); - expect(generated).toContain('"size" => out[0] |= 1u64 << 1,'); - }); - - test('sends an event of a native tree as the payload of a native event', () => { - expect(generated).toContain( - 'if let Some(native) = self.context.native.as_ref().map(|call| &call.emitter) {', - ); - expect(generated).toContain( - 'event.insert("nativeEvent".to_string(), value.to_json());', - ); - expect(generated).toContain( - 'native.emit("onReported", Value::Object(event));', - ); - expect(generated).toContain('pub fn to_json(&self) -> Value {'); - expect(generated).toContain( - 'event.insert("nativeEvent".to_string(), Value::Object(Map::new()));', - ); - expect(generated).toContain('if let Some(native) = self.native.as_ref() {'); - }); - - test('gives the component its children and tells it apart from a Fabric node', () => { - expect(generated).toContain( - 'pub fn children(&mut self) -> Vec {', - ); - expect(generated).toContain( - 'pub fn new_native(call: NativeCall) -> Self {', - ); - expect(generated).toContain( - 'impl NativeComponent for NativeFixtureNative {', - ); - expect(generated).toContain( - 'children: Vec,\n window: &mut Window,\n app: &mut gpui::App,', - ); - expect(generated).toContain('pub fn register_native_tree() {'); - expect(generated).toContain( - 'react_native_gpui::native_tree::register_native_component::>(Self::NAME);', - ); - }); - - test('calls a command by name with its JSON arguments', () => { - expect(generated).toContain('"ping" => self.component.ping('); - expect(generated).toContain( - 'args.get(0).and_then(Value::as_str).unwrap_or_default().to_string()', - ); - expect(generated).toContain( - 'args.get(1).and_then(Value::as_i64).unwrap_or_default() as i32', - ); - }); - - test('reads structs, arrays of structs, mirrors, images and arrays of strings from JSON too', () => { - expect(header).toContain('pub fn register_native_tree() {'); - expect(header).not.toContain('unreachable!'); - expect(header).toContain( - 'pub fn from_json(json: &Map) -> Self {', - ); - expect(header).toContain( - "pub fn from_json(json: &'a Map) -> Self {", - ); - expect(header).toContain("pub fn from_json(items: &'a [Value]) -> Self {"); - expect(header).toContain('return self.native_points.get_or_init(|| {'); - expect(header).toContain('FixtureChartPoints::from_json'); - expect(header).toContain('return RnGpuiStrArray::from_json('); - expect(header).toContain('return RnGpuiImageSource::from_json('); - expect(header).toContain( - 'pub fn from_json(source: &Map) -> Self {', - ); - }); - - test('sends an enum field of an event payload, as its discriminant to C++ and its name to a native tree', () => { - expect(generated).toContain('pub speed: NativeFixtureSpeed,'); - expect(generated).toContain('pub enum NativeFixtureSpeed {'); - expect(generated).toContain('Fast = 0,'); - expect(generated).toContain('Slow = 1,'); - expect(generated).toContain( - 'object.insert("speed".to_string(), self.speed.to_json());', - ); - expect(generated).toContain('Self::Slow => Value::from("slow"),'); - expect(generated).toContain('speed.as_raw()'); - }); -}); - -describe('a crate with a module spec and a component spec', () => { - const moduleSpec = `import { TurboModuleRegistry, type TurboModule } from 'react-native'; - -export interface Spec extends TurboModule { - greet(name: string): string; - load(options: { path: string }): Promise; -} - -export default TurboModuleRegistry.getEnforcing('NativeMixedCrate'); -`; - const componentSpec = `import { - codegenNativeCommands, - codegenNativeComponent, - type CodegenTypes, - type ViewProps, -} from 'react-native'; - -export interface NativeProps extends ViewProps { - title: string; - extra?: CodegenTypes.UnsafeMixed; - values?: ReadonlyArray; - items?: ReadonlyArray>; - onReported?: CodegenTypes.DirectEventHandler>; -} - -export interface MixedCrateCommands { - ping: (ref: React.ComponentRef, label: string) => void; -} - -export const Commands = codegenNativeCommands({ - supportedCommands: ['ping'], -}); - -const MixedCrate: any = null; - -export default codegenNativeComponent('MixedCrate', { - interfaceOnly: true, -}); -`; - const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'rust-mixed-crate-')); - const moduleFile = path.join(directory, 'NativeMixedCrate.ts'); - const componentFile = path.join(directory, 'MixedCrateNativeComponent.ts'); - fs.writeFileSync(moduleFile, moduleSpec); - fs.writeFileSync(componentFile, componentSpec); - const both = generateRustSpec({ specPaths: [moduleFile, componentFile] }); - const componentOnly = generateRustSpec({ specPaths: [componentFile] }); - - test('keeps the module runtime Value for the module and names the component one HostValue', () => { - expect(both).toContain('ModuleThread, Value,'); - expect(both).toContain('PropsHandle, Value as HostValue, empty_map,'); - expect(both).toContain('pub fn extra(&self) -> &HostValue {'); - expect(both).toContain('mixed_extra: std::cell::OnceCell,'); - expect(both).toContain('and_then(HostValue::as_array)'); - expect(both).toContain('and_then(HostValue::as_str)'); - expect(both).toContain( - 'pub fn from_json(json: &Map) -> Self {', - ); - expect(both).toContain( - 'fn create(props: &Map, cx: &mut NativeContext) -> Self {', - ); - expect(both).toContain('"extra"'); - }); - - test("leaves no module Value where the component means serde_json's", () => { - expect(both).not.toContain('Map'); - expect(both).not.toContain('&Value'); - expect(both).not.toContain('[Value]'); - expect(both).toContain("json: Option<&'a [HostValue]>,"); - }); - - test('a crate with only a component still uses the plain Value', () => { - expect(componentOnly).toContain('PropsHandle, Value, empty_map,'); - expect(componentOnly).toContain('pub fn extra(&self) -> &Value {'); - expect(componentOnly).not.toContain('HostValue'); - }); -}); - -describe('a native tree reads a prop that is not set as its default', () => { - test('scalar props fall back to the default of the spec', () => { - const out = generateFrom( - withProps(` open?: CodegenTypes.WithDefault; - count?: CodegenTypes.WithDefault; - ratio?: CodegenTypes.WithDefault; - plain?: boolean;`), - ); - expect(out).toContain('.and_then(Value::as_bool).unwrap_or(true)'); - expect(out).toContain('.and_then(Value::as_i64).unwrap_or(7_i64)'); - expect(out).toContain('.and_then(Value::as_f64).unwrap_or(0.5_f64)'); - expect(out).toContain('.and_then(Value::as_bool).unwrap_or(false)'); - }); -}); diff --git a/vendor/react-native-gpui/packages/codegen/src/generate-rust-spec.js b/vendor/react-native-gpui/packages/codegen/src/generate-rust-spec.js deleted file mode 100644 index 32f92df15c..0000000000 --- a/vendor/react-native-gpui/packages/codegen/src/generate-rust-spec.js +++ /dev/null @@ -1,3730 +0,0 @@ -// Generates the Rust glue a TurboModule library implements: one trait per spec -// file, the events handle, the value structs and enums, and the descriptor that -// registers the module with `rn-gpui-module`. - -import fs from 'node:fs'; -import path from 'node:path'; -import { createRequire } from 'node:module'; -import { fileURLToPath } from 'node:url'; - -/// `@react-native/codegen` belongs to the app, not to this package, so it is -/// resolved from the spec being generated and then from here. -export function loadTypeScriptParser(hints) { - const failures = []; - for (const hint of hints) { - try { - const require = createRequire(hint); - return require('@react-native/codegen/lib/parsers/typescript/parser.js') - .TypeScriptParser; - } catch (error) { - failures.push(`${hint}: ${error.message}`); - } - } - throw new Error( - `generate-rust-spec: cannot resolve @react-native/codegen; install it in the app.\n${failures.join('\n')}`, - ); -} - -const RUST_KEYWORDS = new Set([ - 'as', - 'break', - 'const', - 'continue', - 'crate', - 'dyn', - 'else', - 'enum', - 'extern', - 'false', - 'fn', - 'for', - 'if', - 'impl', - 'in', - 'let', - 'loop', - 'match', - 'mod', - 'move', - 'mut', - 'pub', - 'ref', - 'return', - 'self', - 'Self', - 'static', - 'struct', - 'super', - 'trait', - 'true', - 'type', - 'unsafe', - 'use', - 'where', - 'while', - 'async', - 'await', - 'dyn', - 'abstract', - 'become', - 'box', - 'do', - 'final', - 'macro', - 'override', - 'priv', - 'try', - 'typeof', - 'unsized', - 'virtual', - 'yield', -]); -const RAW_IDENTIFIER_INVALID = new Set(['crate', 'self', 'super', 'Self']); - -export function rustIdentifier(name) { - if (!RUST_KEYWORDS.has(name)) return name; - return RAW_IDENTIFIER_INVALID.has(name) ? `${name}_` : `r#${name}`; -} - -export function snakeCase(name) { - return name - .replaceAll(/([a-z0-9])([A-Z])/gu, '$1_$2') - .replaceAll(/([A-Z]+)([A-Z][a-z])/gu, '$1_$2') - .toLowerCase(); -} - -export function pascalCase(name) { - const words = name.split(/[^A-Za-z0-9]+/u).filter(Boolean); - const joined = words - .map(word => word[0].toUpperCase() + word.slice(1)) - .join(''); - if (joined.length === 0) return 'Value'; - return /^[0-9]/u.test(joined) ? `V${joined}` : joined; -} - -function variantName(name, index) { - const cleaned = name.replaceAll(/[^A-Za-z0-9]+/gu, ' ').trim(); - if (cleaned.length === 0) return `Value${index}`; - const variant = pascalCase(cleaned); - return RUST_KEYWORDS.has(variant) ? `${variant}Value` : variant; -} - -const pascal = name => pascalCase(name); - -/// A Rust string literal, so generated messages survive quotes in spec values. -const rustString = text => JSON.stringify(text); - -class SpecGenerator { - constructor({ specPath, hasteModuleName, module }) { - this.specPath = specPath; - this.hasteModuleName = hasteModuleName; - this.module = module; - this.spec = module.spec; - this.aliasMap = module.aliasMap ?? {}; - this.enumMap = module.enumMap ?? {}; - // Anonymous object types and string literal unions are named after the - // place they appear, so the same shape is generated once. - this.anonymous = new Map(); - this.types = []; - this.typeNames = new Set(); - } - - fail(where, detail) { - throw new Error(`${this.specPath}: ${where}: ${detail}`); - } - - /// The name JS asks for. The Rust names come from the spec file instead. - get moduleName() { - return this.module.moduleName ?? this.hasteModuleName; - } - - get stem() { - return path.basename(this.specPath).replace(/\.[^.]+$/u, ''); - } - - get traitName() { - return `${this.stem}Spec`; - } - - get eventsName() { - return `${this.stem}Events`; - } - - get instanceName() { - return `${this.stem}Instance`; - } - - get descriptorName() { - const stem = this.stem.replace(/^Native/u, ''); - return `native_${snakeCase(stem)}_module`; - } - - /// Maps a type annotation to a Rust type, generating a struct or enum when - /// the annotation names one. - typeOf(annotation, context) { - const { where } = context; - switch (annotation.type) { - case 'StringTypeAnnotation': - return 'String'; - case 'NumberTypeAnnotation': - case 'DoubleTypeAnnotation': - case 'FloatTypeAnnotation': - return 'f64'; - case 'Int32TypeAnnotation': - return 'i32'; - case 'BooleanTypeAnnotation': - return 'bool'; - case 'VoidTypeAnnotation': - return '()'; - case 'NullableTypeAnnotation': - return `Option<${this.typeOf(annotation.typeAnnotation, context)}>`; - case 'ArrayTypeAnnotation': - return `Vec<${this.typeOf(annotation.elementType, context)}>`; - case 'GenericObjectTypeAnnotation': - return 'Value'; - case 'ArrayBufferTypeAnnotation': - return 'ArrayBuffer'; - case 'ObjectTypeAnnotation': - return this.objectType(annotation, context); - case 'TypeAliasTypeAnnotation': { - const alias = this.aliasMap[annotation.name]; - if (!alias) this.fail(where, `unknown type alias ${annotation.name}`); - if (alias.type === 'ObjectTypeAnnotation') { - return this.objectType(alias, { - ...context, - name: annotation.name, - aliasName: annotation.name, - }); - } - if (alias.type === 'EnumDeclaration') { - return this.enumType(annotation.name, alias); - } - this.fail(where, `unsupported type alias ${annotation.name}`); - break; - } - case 'EnumDeclaration': { - const declared = this.enumMap[annotation.name]; - if (!declared) this.fail(where, `unknown enum ${annotation.name}`); - return this.enumType(annotation.name, declared); - } - case 'UnionTypeAnnotation': - return this.unionType(annotation, context); - case 'FunctionTypeAnnotation': - if (context.callbackAllowed !== true) { - this.fail( - where, - 'a method that takes a callback must return void or a Promise', - ); - } - return this.callbackType(annotation, context); - default: - this.fail(where, `unsupported spec type ${annotation.type}`); - break; - } - return 'Value'; - } - - objectType(annotation, context) { - if (context.aliasName && this.typeNames.has(context.aliasName)) { - return context.aliasName; - } - const name = this.uniqueName( - context.aliasName ?? context.name ?? `${pascal(context.where)}Value`, - ); - // Recursion would need a boxed field, which this generator does not write. - const nested = annotation.properties ?? []; - for (const property of nested) { - if (this.referencesAlias(property.typeAnnotation, context.aliasName)) { - this.fail( - context.where, - `recursive type alias ${context.aliasName ?? name} is not supported`, - ); - } - } - this.typeNames.add(name); - const fields = nested.map(property => ({ - name: rustIdentifier(snakeCase(property.name)), - jsName: property.name, - optional: property.optional === true, - nullable: property.typeAnnotation.type === 'NullableTypeAnnotation', - annotation: property.typeAnnotation, - })); - const struct = { - kind: 'struct', - name, - fields: fields.map(field => ({ - ...field, - rustType: this.fieldType(field, { ...context, where: context.where }), - })), - }; - // Nested objects are named after their parent, so register the struct - // before generating the fields that may add more types. - this.types.push(struct); - return name; - } - - fieldType(field, context) { - const inner = this.typeOf(field.annotation, { - ...context, - name: `${context.name ?? ''}${pascal(field.jsName)}`, - aliasName: undefined, - callbackAllowed: false, - }); - if (field.optional) { - return inner.startsWith('Option<') ? inner : `Option<${inner}>`; - } - return inner; - } - - referencesAlias(annotation, aliasName) { - if (!aliasName) return false; - if (annotation.type === 'TypeAliasTypeAnnotation') { - return annotation.name === aliasName; - } - if (annotation.type === 'NullableTypeAnnotation') { - return this.referencesAlias(annotation.typeAnnotation, aliasName); - } - if (annotation.type === 'ArrayTypeAnnotation') { - return this.referencesAlias(annotation.elementType, aliasName); - } - if (annotation.type === 'ObjectTypeAnnotation') { - return (annotation.properties ?? []).some(property => - this.referencesAlias(property.typeAnnotation, aliasName), - ); - } - return false; - } - - uniqueName(base) { - let name = base; - let suffix = 2; - while (this.typeNames.has(name)) { - name = `${base}${suffix}`; - suffix += 1; - } - this.typeNames.add(name); - return name; - } - - unionType(annotation, context) { - const members = (annotation.types ?? []).map(member => { - if (member.type !== 'StringLiteralTypeAnnotation') { - this.fail(context.where, `unsupported union member ${member.type}`); - } - return { name: String(member.value), value: member.value }; - }); - if (members.length === 0) this.fail(context.where, 'empty union type'); - const name = this.uniqueName( - context.name ?? `${pascal(context.where)}Value`, - ); - this.pushEnum(name, { - memberType: 'StringTypeAnnotation', - members: members.map(member => ({ - name: member.name, - value: { type: 'StringLiteralTypeAnnotation', value: member.value }, - })), - }); - return name; - } - - enumType(name, declaration) { - if (this.typeNames.has(name)) return name; - this.typeNames.add(name); - this.pushEnum(name, declaration); - return name; - } - - pushEnum(name, declaration) { - // As React Native's own generator does, anything that is not a string enum - // is numeric. - const numeric = declaration.memberType !== 'StringTypeAnnotation'; - const members = (declaration.members ?? []).map((member, index) => { - const value = member.value?.value ?? member.name; - if (numeric && typeof value !== 'number') { - this.fail( - `enum ${name}`, - `expected a numeric member for ${member.name}`, - ); - } - if (!numeric && typeof value !== 'string') { - this.fail( - `enum ${name}`, - `expected a string member for ${member.name}`, - ); - } - return { - variant: variantName(member.name ?? String(value), index), - value, - }; - }); - this.types.push({ kind: 'enum', name, numeric, members }); - } - - callbackType(annotation, context) { - const args = (annotation.params ?? []).map((parameter, index) => { - const declared = this.typeOf(parameter.typeAnnotation, { - where: `${context.where} callback argument ${index}`, - callbackAllowed: false, - }); - return parameter.optional && !declared.startsWith('Option<') - ? `Option<${declared}>` - : declared; - }); - return `Box`; - } - - methods() { - return (this.spec.methods ?? []).map((method, index) => { - const signature = method.typeAnnotation; - const returns = signature.returnTypeAnnotation; - const where = method.name; - const kind = - returns.type === 'VoidTypeAnnotation' - ? 'void' - : returns.type === 'PromiseTypeAnnotation' - ? 'promise' - : 'value'; - if (method.name === 'getConstants' && kind === 'promise') { - this.fail(where, 'getConstants cannot return a Promise'); - } - const callbackAllowed = kind !== 'value'; - const params = (signature.params ?? []).map((parameter, position) => ({ - jsName: parameter.name, - name: rustIdentifier(snakeCase(parameter.name)), - annotation: parameter.typeAnnotation, - optional: parameter.optional === true, - nullable: parameter.typeAnnotation.type === 'NullableTypeAnnotation', - position, - isCallback: parameter.typeAnnotation.type === 'FunctionTypeAnnotation', - })); - for (const parameter of params) { - const declared = this.typeOf(parameter.annotation, { - where, - name: `${pascal(method.name)}${pascal(parameter.jsName)}`, - callbackAllowed, - }); - parameter.rustType = - parameter.optional && !declared.startsWith('Option<') - ? `Option<${declared}>` - : declared; - if (parameter.isCallback) { - parameter.callbackArgTypes = (parameter.annotation.params ?? []).map( - (callbackArg, argumentIndex) => - this.typeOf(callbackArg.typeAnnotation, { - where, - name: `${pascal(method.name)}${pascal(parameter.jsName)}Argument${argumentIndex}`, - callbackAllowed: false, - }), - ); - } - } - let rustReturn = '()'; - let returnsVoid = false; - if (kind === 'value') { - rustReturn = this.typeOf(returns, { - where, - name: `${pascal(method.name)}Result`, - callbackAllowed: false, - }); - } else if (kind === 'promise') { - const element = returns.elementType; - if (element.type === 'VoidTypeAnnotation') { - returnsVoid = true; - } else { - rustReturn = this.typeOf(element, { - where, - name: `${pascal(method.name)}Result`, - callbackAllowed: false, - }); - } - } - // A parameter the spec marks optional may be omitted, so the required - // count stops after the last one that is not. - const requiredArgs = params.reduce( - (required, parameter, position) => - parameter.optional ? required : position + 1, - 0, - ); - return { - index, - jsName: method.name, - requiredArgs, - name: rustIdentifier(snakeCase(method.name)), - kind, - params, - rustReturn, - returnsVoid, - callbackArgs: params - .filter(parameter => parameter.isCallback) - .map(parameter => parameter.position), - }; - }); - } - - events() { - return (this.spec.eventEmitters ?? []).map(eventEmitter => { - const annotation = eventEmitter.typeAnnotation.typeAnnotation; - const hasValue = annotation.type !== 'VoidTypeAnnotation'; - return { - jsName: eventEmitter.name, - name: rustIdentifier(snakeCase(eventEmitter.name)), - hasValue, - rustType: hasValue - ? this.typeOf(annotation, { - where: `event ${eventEmitter.name}`, - name: `${pascal(eventEmitter.name)}Payload`, - callbackAllowed: false, - }) - : null, - }; - }); - } -} - -/// Parses the component specs in `specPaths` into the same generators the Rust -/// half renders from, so the C++ half is derived from one model of each prop and -/// the two cannot disagree about a shape. -export function parseComponents({ specPaths }) { - const TypeScriptParser = loadTypeScriptParser([ - ...specPaths.map(specPath => path.resolve(specPath)), - path.join(process.cwd(), 'package.json'), - import.meta.url, - ]); - const parser = new TypeScriptParser(); - const found = []; - for (const specPath of specPaths) { - const schema = parser.parseFile(specPath); - for (const [hasteModuleName, module] of Object.entries( - schema.modules ?? {}, - )) { - if (module.type !== 'Component') continue; - for (const [componentName, component] of Object.entries( - module.components ?? {}, - )) { - const generator = new ComponentGenerator({ - specPath, - hasteModuleName, - componentName, - component, - }); - generator.collect(); - found.push(generator); - } - } - } - return found; -} - -export function generateRustSpec({ specPaths }) { - const TypeScriptParser = loadTypeScriptParser([ - ...specPaths.map(specPath => path.resolve(specPath)), - path.join(process.cwd(), 'package.json'), - import.meta.url, - ]); - const parser = new TypeScriptParser(); - const modules = []; - const components = []; - let componentsUseImageSource = false; - for (const specPath of specPaths) { - const schema = parser.parseFile(specPath); - const entries = Object.entries(schema.modules ?? {}); - if (entries.length !== 1) { - throw new Error( - `${specPath}: expected exactly one spec, found ${entries.length}`, - ); - } - const [hasteModuleName, module] = entries[0]; - if (module.type === 'NativeModule') { - const generator = new SpecGenerator({ - specPath, - hasteModuleName, - module, - }); - modules.push( - renderSpec(generator, generator.methods(), generator.events()), - ); - } else if (module.type === 'Component') { - for (const [componentName, component] of Object.entries( - module.components ?? {}, - )) { - const generator = new ComponentGenerator({ - specPath, - hasteModuleName, - componentName, - component, - }); - components.push(renderComponent(generator)); - componentsUseImageSource ||= generator.usesImageSource; - } - } else { - throw new Error( - `${specPath}: expected a NativeModule or a component, found ${module.type}`, - ); - } - } - // A crate with a module spec imports the module runtime's `Value` (the JSI - // value). The component code means `host_component::Value` (`serde_json`'s), - // so it names that one `HostValue`; a string literal is left as it is. - const hostValue = - modules.length > 0 - ? text => text.replace(/(? text; - const header = [ - '// Generated by @react-native-gpui/codegen from TypeScript specs; do not edit.', - '', - modules.length > 0 ? MODULE_IMPORTS : null, - components.length > 0 - ? [ - modules.length > 0 - ? COMPONENT_IMPORTS.replace( - 'PropsHandle, Value,', - 'PropsHandle, Value as HostValue,', - ) - : COMPONENT_IMPORTS, - componentsUseImageSource ? hostValue(COMPONENT_IMAGE_SOURCE) : '', - hostValue(COMPONENT_ABI), - ] - .filter(part => part !== '') - .map(part => part.trimEnd()) - .join('\n') - : null, - ] - .filter(line => line !== null) - .join('\n'); - const body = [...modules, ...components.map(hostValue)] - .map(chunk => chunk.replace(/^\n+/u, '').trimEnd()) - .join('\n'); - return `${header.trimEnd()}\n\n${body}\n`; -} - -const MODULE_IMPORTS = `use std::sync::Arc; - -use rn_gpui_module::__private::{Args, FieldMap, Path}; -use rn_gpui_module::{ - ArrayBuffer, EventEmitter, EventInfo, FromValue, IntoValue, LocalBoxFuture, MethodInfo, MethodKind, - ModuleDescriptor, ModuleError, ModuleInstance, ModuleThread, Value, -}; -`; - -function renderSpec(generator, methods, events) { - const lines = []; - lines.push(`// ${generator.specPath}`); - lines.push(''); - lines.push(renderEvents(generator, events)); - lines.push(renderTrait(generator, methods)); - lines.push(renderDescriptor(generator, methods, events)); - lines.push(renderInstance(generator, methods)); - for (const type of generator.types) { - lines.push(type.kind === 'struct' ? renderStruct(type) : renderEnum(type)); - } - return lines.filter(line => line !== null).join('\n'); -} - -function renderEvents(generator, events) { - const lines = []; - lines.push('#[derive(Clone)]'); - lines.push(`pub struct ${generator.eventsName} {`); - lines.push(' emitter: EventEmitter,'); - lines.push('}'); - lines.push(''); - lines.push(`impl ${generator.eventsName} {`); - for (const event of events) { - if (event.hasValue) { - lines.push(` pub fn ${event.name}(&self, value: ${event.rustType}) {`); - lines.push( - ` self.emitter.emit(${JSON.stringify(event.jsName)}, Some(value.into_value()));`, - ); - lines.push(' }'); - } else { - lines.push(` pub fn ${event.name}(&self) {`); - lines.push( - ` self.emitter.emit(${JSON.stringify(event.jsName)}, None);`, - ); - lines.push(' }'); - } - lines.push(''); - } - lines.push(' pub fn send_event(&self, name: &str, body: Value) {'); - lines.push(' self.emitter.send_event(name, body);'); - lines.push(' }'); - lines.push('}'); - return lines.join('\n'); -} - -function methodSignature(method) { - const parameters = method.params - .map(parameter => `${parameter.name}: ${parameter.rustType}`) - .join(', '); - switch (method.kind) { - case 'value': - return ` fn ${method.name}(&self${parameters ? `, ${parameters}` : ''}) -> Result<${method.rustReturn}, ModuleError>;`; - case 'void': - return ` fn ${method.name}(&self${parameters ? `, ${parameters}` : ''});`; - default: - return ` async fn ${method.name}(&self${parameters ? `, ${parameters}` : ''}) -> Result<${method.rustReturn}, ModuleError>;`; - } -} - -function renderTrait(generator, methods) { - const lines = []; - lines.push('#[allow(async_fn_in_trait)]'); - lines.push( - `pub trait ${generator.traitName}: Send + Sync + Sized + 'static {`, - ); - lines.push(' const THREAD: ModuleThread = ModuleThread::Own;'); - lines.push(''); - lines.push(` fn new(events: ${generator.eventsName}) -> Self;`); - lines.push(''); - for (const method of methods) { - lines.push(methodSignature(method)); - } - lines.push('}'); - return lines.join('\n'); -} - -function renderDescriptor(generator, methods, events) { - const lines = []; - lines.push( - `pub fn ${generator.descriptorName}() -> ModuleDescriptor {`, - ); - lines.push(' ModuleDescriptor {'); - lines.push(` name: ${JSON.stringify(generator.moduleName)},`); - lines.push(' thread: M::THREAD,'); - lines.push(' methods: &['); - for (const method of methods) { - const kind = - method.kind === 'value' - ? 'MethodKind::Value' - : method.kind === 'void' - ? 'MethodKind::Void' - : 'MethodKind::Promise'; - const callbacks = `&[${method.callbackArgs.join(', ')}]`; - lines.push(' MethodInfo {'); - lines.push(` name: ${JSON.stringify(method.jsName)},`); - lines.push(` arg_count: ${method.params.length},`); - lines.push(` required_args: ${method.requiredArgs},`); - lines.push(` kind: ${kind},`); - lines.push(` returns_void: ${method.returnsVoid},`); - lines.push(` callback_args: ${callbacks},`); - lines.push(' },'); - } - lines.push(' ],'); - lines.push(' events: &['); - for (const event of events) { - lines.push(' EventInfo {'); - lines.push(` name: ${JSON.stringify(event.jsName)},`); - lines.push(` has_value: ${event.hasValue},`); - lines.push(' },'); - } - lines.push(' ],'); - lines.push( - ` create: |events| Arc::new(${generator.instanceName}::::new(events)) as Arc,`, - ); - lines.push(' }'); - lines.push('}'); - return lines.join('\n'); -} - -const ARGS_CURSOR = 'arguments_'; - -function argumentConversion(method, parameter) { - if (parameter.isCallback) { - const args = (parameter.annotation.params ?? []).map( - (callbackArg, index) => `a${index}: ${parameter.callbackArgTypes[index]}`, - ); - const values = (parameter.annotation.params ?? []) - .map((_, index) => `a${index}.into_value()`) - .join(', '); - return [ - ` let ${parameter.name} = ${ARGS_CURSOR}.next_callback(${JSON.stringify(parameter.jsName)})?;`, - ` let ${parameter.name}: ${parameter.rustType} =`, - ` Box::new(move |${args.join(', ')}| ${parameter.name}.invoke(vec![${values}]));`, - ]; - } - return [ - ` let ${parameter.name}: ${parameter.rustType} = ${ARGS_CURSOR}.next(${JSON.stringify(parameter.jsName)})?;`, - ]; -} - -function renderInstance(generator, methods) { - const lines = []; - lines.push(`struct ${generator.instanceName}(M);`); - lines.push(''); - lines.push(`impl ${generator.instanceName} {`); - lines.push(' fn new(events: EventEmitter) -> Self {'); - lines.push( - ` Self(M::new(${generator.eventsName} { emitter: events }))`, - ); - lines.push(' }'); - lines.push('}'); - lines.push(''); - lines.push( - `impl ModuleInstance for ${generator.instanceName} {`, - ); - for (const kind of ['value', 'void', 'promise']) { - const matching = methods.filter(method => method.kind === kind); - lines.push(renderCall(generator, kind, matching)); - lines.push(''); - } - lines.push('}'); - return lines.join('\n'); -} - -function renderCall(generator, kind, methods) { - const name = generator.moduleName; - const lines = []; - const signature = - kind === 'promise' - ? ' fn call_promise(\n self: Arc,\n method: usize,\n args: Vec,\n ) -> Result>, ModuleError> {' - : kind === 'value' - ? ' fn call_value(&self, method: usize, args: Vec) -> Result {' - : ` fn prepare_void(\n self: Arc,\n method: usize,\n args: Vec,\n ) -> Result, ModuleError> {`; - lines.push(signature); - lines.push(' match method {'); - for (const method of methods) { - lines.push(` ${method.index} => {`); - lines.push( - ` let mut ${ARGS_CURSOR} = Args::new(${JSON.stringify(name)}, ${JSON.stringify(method.jsName)}, args);`, - ); - for (const parameter of method.params) { - lines.push(...argumentConversion(method, parameter)); - } - const call = `self.0.${method.name}(${method.params.map(parameter => parameter.name).join(', ')})`; - if (kind === 'value') { - lines.push( - ` let result = rn_gpui_module::__private::catch(|| ${call})??;`, - ); - lines.push(' Ok(result.into_value())'); - } else if (kind === 'void') { - lines.push(' Ok(Box::new(move || {'); - lines.push( - ` rn_gpui_module::__private::run_void(${JSON.stringify(`${name}.${method.jsName}`)}, move || ${call});`, - ); - lines.push(' }))'); - } else { - lines.push(' Ok(Box::pin(async move {'); - lines.push( - ` let result = rn_gpui_module::__private::catch_async(${call}).await??;`, - ); - lines.push(' Ok(result.into_value())'); - lines.push(' }))'); - } - lines.push(' }'); - } - lines.push( - ` _ => Err(ModuleError::new(${JSON.stringify(`${name}: unknown method`)}))`, - ); - lines.push(' }'); - lines.push(' }'); - return lines.join('\n'); -} - -/// `Value` has no `Clone` or `PartialEq`, so a struct that holds one, directly -/// or behind `Option`/`Vec`, derives less. -function isValueType(rustType) { - const inner = rustType.endsWith('>') - ? rustType.slice(rustType.indexOf('<') + 1, -1) - : rustType; - return inner === 'Value' || (inner !== rustType && isValueType(inner)); -} - -function renderStruct(struct) { - const hasValueField = struct.fields.some(field => - isValueType(field.rustType), - ); - const derives = hasValueField - ? '#[derive(Debug)]' - : '#[derive(Debug, Clone, PartialEq)]'; - const lines = []; - lines.push(derives); - lines.push(`pub struct ${struct.name} {`); - for (const field of struct.fields) { - lines.push(` pub ${field.name}: ${field.rustType},`); - } - lines.push('}'); - lines.push(''); - lines.push(`impl FromValue for ${struct.name} {`); - lines.push( - ' fn from_value(value: Value, path: &mut Path) -> Result {', - ); - lines.push(' let fields = match value {'); - lines.push(' Value::Object(fields) => fields,'); - lines.push( - ' other => return Err(path.error(format!("expected object, got {}", other.type_name()))),', - ); - lines.push(' };'); - lines.push(' let mut fields = FieldMap::new(fields);'); - lines.push(` Ok(Self {`); - for (const field of struct.fields) { - const call = field.optional - ? `fields.take_optional::<${innerType(field.rustType)}>(path, ${JSON.stringify(field.jsName)})?` - : `fields.take::<${field.rustType}>(path, ${JSON.stringify(field.jsName)})?`; - lines.push(` ${field.name}: ${call},`); - } - lines.push(' })'); - lines.push(' }'); - lines.push('}'); - lines.push(''); - lines.push(`impl IntoValue for ${struct.name} {`); - lines.push(' fn into_value(self) -> Value {'); - lines.push(' Value::Object(vec!['); - for (const field of struct.fields) { - lines.push( - ` (${JSON.stringify(field.jsName)}.to_string(), self.${field.name}.into_value()),`, - ); - } - lines.push(' ])'); - lines.push(' }'); - lines.push('}'); - return lines.join('\n'); -} - -const innerType = rustType => - rustType.startsWith('Option<') && rustType.endsWith('>') - ? rustType.slice('Option<'.length, -1) - : rustType; - -function renderEnum(enumType) { - const lines = []; - lines.push('#[derive(Debug, Clone, Copy, PartialEq, Eq)]'); - lines.push(`pub enum ${enumType.name} {`); - for (const member of enumType.members) { - lines.push(` ${member.variant},`); - } - lines.push('}'); - lines.push(''); - lines.push(`impl FromValue for ${enumType.name} {`); - lines.push( - ' fn from_value(value: Value, path: &mut Path) -> Result {', - ); - lines.push(' match value {'); - const expected = enumType.members - .map(member => - enumType.numeric ? String(member.value) : JSON.stringify(member.value), - ) - .join(', '); - if (enumType.numeric) { - lines.push(' Value::Number(number) => match number as i64 {'); - for (const member of enumType.members) { - lines.push( - ` ${member.value} => Ok(Self::${member.variant}),`, - ); - } - lines.push( - ` other => Err(path.error(format!(${rustString(`expected one of ${expected}, got {other}`)}))),`, - ); - lines.push(' },'); - } else { - lines.push(' Value::String(text) => match text.as_str() {'); - for (const member of enumType.members) { - lines.push( - ` ${JSON.stringify(member.value)} => Ok(Self::${member.variant}),`, - ); - } - lines.push( - ` other => Err(path.error(format!(${rustString(`expected one of ${expected}, got "{other}"`)}))),`, - ); - lines.push(' },'); - } - lines.push( - ` other => Err(path.error(format!(${rustString( - enumType.numeric ? 'expected number, got {}' : 'expected string, got {}', - )}, other.type_name()))),`, - ); - lines.push(' }'); - lines.push(' }'); - lines.push('}'); - lines.push(''); - lines.push(`impl IntoValue for ${enumType.name} {`); - lines.push(' fn into_value(self) -> Value {'); - lines.push(' match self {'); - for (const member of enumType.members) { - const value = enumType.numeric - ? `Value::Number(${member.value} as f64)` - : `Value::String(${JSON.stringify(member.value)}.to_string())`; - lines.push(` Self::${member.variant} => ${value},`); - } - lines.push(' }'); - lines.push(' }'); - lines.push('}'); - return lines.join('\n'); -} - -/// The imports a component file needs. A crate that declares a host component -/// renders GPUI content, so it depends on `gpui` and on `react-native-gpui` -/// (for the host context). The module glue needs neither, so each group is -/// emitted only when it is used, and each is allowed to go unused. -const COMPONENT_IMPORTS = `#[allow(unused_imports)] -use gpui::{AnyElement, Window}; -#[allow(unused_imports)] -use react_native_gpui::host_component::{ - EmitterHandle, HostArg, HostComponentSpec, HostContext, HostEventSender, HostObject, Map, - MeasureConstraint, MeasuredSize, NativeCall, NativeComponent, NativeContext, NativeEmitter, - PropsHandle, Value, empty_map, -}; -#[allow(unused_imports)] -use react_native_gpui::native_surface::{NativeViewHandle, NativeViewParent}; -`; - -/// The C ABI between the generated Rust and the generated C++ file, emitted -/// once per generated file that declares a host component. -/// -/// Each struct is `#[repr(C)]` with pointer-sized fields in a fixed order, so -/// the C++ side can declare the same three structs and pass them by value; they -/// live once in core's `GpuiHostComponentsCpp.h`, with layout checks: -/// -/// ```c -/// struct RnGpuiStr { const uint8_t* data; size_t len; }; -/// struct RnGpuiSlice { const void* data; size_t len; }; -/// struct RnGpuiOptU32 { uint32_t value; bool present; }; -/// ``` -/// -/// Shims the C++ file implements, so both halves agree on the names: -/// -/// * props: `rn_gpui__props_`, first argument the opaque props -/// handle a `PropsHandle` owns; -/// * a generated view: `rn_gpui__`, first argument the address -/// of that C++ struct; -/// * events: `rn_gpui__event_`, first argument the opaque -/// emitter handle an `EmitterHandle` owns, then the payload's leaves as -/// arguments (a scalar by value, a string as bytes and a length, an array as a -/// pointer and a length). The C++ shim assigns them into the event struct React -/// Native generated, so the two payload layouts never have to be declared -/// twice. -/// -/// The change mask is computed in C++ against the previous shadow view and -/// arrives on the mount op, so there is no shim for it. -/// -/// What each returns: `i32` for `Int32` and for an enum's value, `f32` for -/// `Float`, `f64` for `Double`/`number`, `bool` for `boolean`, a `RnGpuiStr` -/// for a `std::string` (bytes plus length), a `RnGpuiOptU32` for a -/// `SharedColor`, the address of the field for an `ImageSource` or a struct, -/// `RnGpuiSlice` for a `std::vector` of plain data, `_len`/`_at` for a -/// `std::vector` of anything else (strings and structs), and, for a -/// `folly::dynamic`, JSON text handed to a callback. No shim allocates except -/// that last one, which serialises once per props object. -const COMPONENT_ABI = `/// A borrowed C++ \`std::string\`: bytes and an explicit length. -#[repr(C)] -#[derive(Clone, Copy)] -pub struct RnGpuiStr { - pub data: *const u8, - pub len: usize, -} - -impl RnGpuiStr { - /// A string as the event shims take one. - fn of(text: &str) -> Self { - Self { - data: text.as_ptr(), - len: text.len(), - } - } -} - -/// A borrowed C++ \`std::vector\` of plain data. -#[repr(C)] -#[derive(Clone, Copy)] -pub struct RnGpuiSlice { - pub data: *const core::ffi::c_void, - pub len: usize, -} - -/// A C++ \`SharedColor\`: \`present\` is false when React left the color unset. -#[repr(C)] -#[derive(Clone, Copy)] -pub struct RnGpuiOptU32 { - pub value: u32, - pub present: bool, -} - -/// The bytes of a \`RnGpuiStr\`, borrowed as a \`&str\`. -/// -/// The conversion is checked: a props string came from a JS string, which an -/// engine may hand over with a lone surrogate, and an unchecked conversion of -/// invalid UTF-8 is undefined behaviour in a release build. On failure it logs -/// the offset and returns an empty string rather than reading a different -/// string than the one JS sent. -/// -/// # Safety -/// -/// \`text\` must have been read from a live C++ \`std::string\` and must outlive -/// the borrow this returns. -unsafe fn rn_gpui_str<'a>(text: RnGpuiStr) -> &'a str { - if text.data.is_null() || text.len == 0 { - return ""; - } - let bytes = core::slice::from_raw_parts(text.data, text.len); - // Checked, not \`from_utf8_unchecked\`. A release build has no \`debug_assert\`, - // and \`from_utf8\` is SIMD-fast; on the failure path the offending bytes are - // reported by offset. - match core::str::from_utf8(bytes) { - Ok(text) => text, - Err(error) => { - eprintln!( - "[host-component] a props string is not UTF-8 (valid up to byte {})", - error.valid_up_to() - ); - "" - } - } -} - -/// The elements of a \`RnGpuiSlice\`, borrowed as a \`&[T]\`. -/// -/// # Safety -/// -/// \`slice\` must point at \`slice.len\` valid, aligned \`T\` values that outlive -/// the borrow this returns. -unsafe fn rn_gpui_slice<'a, T>(slice: RnGpuiSlice) -> &'a [T] { - if slice.data.is_null() || slice.len == 0 { - return &[]; - } - core::slice::from_raw_parts(slice.data.cast::(), slice.len) -} - -/// The callback a JSON-text shim hands its bytes to: it appends them to the -/// \`String\` \`context\` points at. -unsafe extern "C" fn rn_gpui_collect_text( - context: *mut core::ffi::c_void, - data: *const u8, - len: usize, -) { - if data.is_null() || len == 0 { - return; - } - // The one copy a props read can make; counted so a test can assert no other. - react_native_gpui::host_component::note_props_bytes_copied(len); - let out = &mut *context.cast::(); - out.push_str(&String::from_utf8_lossy(core::slice::from_raw_parts(data, len))); -} - -/// The signature of that callback, as the shims take it. -type RnGpuiTextSink = unsafe extern "C" fn(*mut core::ffi::c_void, *const u8, usize); - -/// A borrowed C++ \`std::vector\`, read one string at a time. -/// -/// The strings in a props struct cannot be lent out as a \`&[&str]\` without -/// allocating, so each one is read on demand through the \`_at\` shim. -#[derive(Clone, Copy)] -pub struct RnGpuiStrArray<'a> { - owner: *const core::ffi::c_void, - len: usize, - at: Option RnGpuiStr>, - json: Option<&'a [Value]>, - _borrow: core::marker::PhantomData<&'a ()>, -} - -impl<'a> RnGpuiStrArray<'a> { - /// # Safety - /// - /// \`owner\` must be a live C++ \`std::vector\`'s owner that - /// outlives \`'a\`, \`len\` its length, and \`at\` the shim that reads one - /// string. - unsafe fn new( - owner: *const core::ffi::c_void, - len: usize, - at: unsafe extern "C" fn(*const core::ffi::c_void, usize) -> RnGpuiStr, - ) -> Self { - Self { - owner, - len, - at: Some(at), - json: None, - _borrow: core::marker::PhantomData, - } - } - - /// The strings of a native tree prop. - pub fn from_json(items: &'a [Value]) -> Self { - Self { - owner: core::ptr::null(), - len: items.len(), - at: None, - json: Some(items), - _borrow: core::marker::PhantomData, - } - } - - pub fn len(&self) -> usize { - self.len - } - - pub fn is_empty(&self) -> bool { - self.len == 0 - } - - pub fn get(&self, index: usize) -> Option<&'a str> { - if index >= self.len { - return None; - } - if let Some(items) = self.json { - return items.get(index).and_then(Value::as_str); - } - let at = self.at?; - Some(unsafe { rn_gpui_str(at(self.owner, index)) }) - } - - pub fn iter(&self) -> impl Iterator + '_ { - (0..self.len).filter_map(move |index| self.get(index)) - } -} -`; - -/// React Native's C++ \`ImageSource\`, as a borrowed view. Every component uses -/// the same shape, so it is generated once per file. -const COMPONENT_IMAGE_SOURCE = `/// A borrowed view over React Native's C++ \`ImageSource\`. -#[derive(Clone, Copy)] -pub struct RnGpuiImageSource { - handle: *const core::ffi::c_void, - json: *const Map, -} - -impl RnGpuiImageSource { - /// # Safety - /// - /// \`handle\` must be the address of a live C++ \`ImageSource\` that outlives - /// the borrow the accessor returns. - unsafe fn from_handle(handle: *const core::ffi::c_void) -> Self { - Self { - handle, - json: core::ptr::null(), - } - } - - /// The source of a native tree prop: an object with the same fields React - /// Native's resolved image source has (\`uri\`, \`bundle\`, \`scale\`, \`width\`, - /// \`height\`, \`body\`, \`method\`). - pub fn from_json(source: &Map) -> Self { - Self { - handle: core::ptr::null(), - json: source, - } - } - - fn text(&self, key: &str) -> Option<&str> { - unsafe { self.json.as_ref() }.map(|source| source.get(key).and_then(Value::as_str).unwrap_or("")) - } - - fn number(&self, key: &str, default: f64) -> Option { - unsafe { self.json.as_ref() } - .map(|source| source.get(key).and_then(Value::as_f64).unwrap_or(default) as f32) - } - - /// The URI; empty when React did not set one. - pub fn uri(&self) -> &str { - if let Some(text) = self.text("uri") { - return text; - } - unsafe { rn_gpui_str(rn_gpui_image_source_uri(self.handle)) } - } - - /// The bundle name, for an image bundled with the app. - pub fn bundle(&self) -> &str { - if let Some(text) = self.text("bundle") { - return text; - } - unsafe { rn_gpui_str(rn_gpui_image_source_bundle(self.handle)) } - } - - /// The image scale, 3 by default as in React Native. - pub fn scale(&self) -> f32 { - if let Some(number) = self.number("scale", 3.0) { - return number; - } - unsafe { rn_gpui_image_source_scale(self.handle) } - } - - /// The intrinsic width. - pub fn width(&self) -> f32 { - if let Some(number) = self.number("width", 0.0) { - return number; - } - unsafe { rn_gpui_image_source_width(self.handle) } - } - - /// The intrinsic height. - pub fn height(&self) -> f32 { - if let Some(number) = self.number("height", 0.0) { - return number; - } - unsafe { rn_gpui_image_source_height(self.handle) } - } - - /// The request body, for a remote image. - pub fn body(&self) -> &str { - if let Some(text) = self.text("body") { - return text; - } - unsafe { rn_gpui_str(rn_gpui_image_source_body(self.handle)) } - } - - /// The request method, for a remote image. - pub fn method(&self) -> &str { - if let Some(text) = self.text("method") { - return text; - } - unsafe { rn_gpui_str(rn_gpui_image_source_method(self.handle)) } - } -} - -unsafe extern "C" { - fn rn_gpui_image_source_uri(image: *const core::ffi::c_void) -> RnGpuiStr; - fn rn_gpui_image_source_bundle(image: *const core::ffi::c_void) -> RnGpuiStr; - fn rn_gpui_image_source_scale(image: *const core::ffi::c_void) -> f32; - fn rn_gpui_image_source_width(image: *const core::ffi::c_void) -> f32; - fn rn_gpui_image_source_height(image: *const core::ffi::c_void) -> f32; - fn rn_gpui_image_source_body(image: *const core::ffi::c_void) -> RnGpuiStr; - fn rn_gpui_image_source_method(image: *const core::ffi::c_void) -> RnGpuiStr; -} -`; - -/// The scalar Rust type of a codegen scalar annotation, or null when the -/// annotation is not a scalar. -function scalarType(annotation) { - switch (annotation.type) { - case 'Int32TypeAnnotation': - return 'i32'; - case 'FloatTypeAnnotation': - return 'f32'; - case 'DoubleTypeAnnotation': - case 'NumberTypeAnnotation': - return 'f64'; - case 'BooleanTypeAnnotation': - return 'bool'; - default: - return null; - } -} - -/// The name of an enum member. A string union names its own members, which is -/// also what React Native's C++ enum uses; a numeric enum has no member names in -/// the schema, so the name is built from the prop and the value, exactly as -/// React Native's own generator does (`Rank0` for `0`). -function enumMemberName(value, numeric, index, propName) { - if (!numeric) return variantName(String(value), index); - const digits = String(value).replaceAll('-', 'Minus'); - return `${pascal(propName)}${digits}`; -} - -/// One component's generated Rust: the layout mirrors, the enums, the views, -/// the props view, the change mask, the events, the context, the trait and the -/// registration value. -export class ComponentGenerator { - constructor({ specPath, hasteModuleName, componentName, component }) { - this.specPath = specPath; - this.hasteModuleName = hasteModuleName; - this.componentName = componentName; - this.component = component; - this.mirrors = []; - this.enums = []; - this.views = []; - this.slices = []; - this.payloads = []; - this.typeNames = new Set(); - this.props = []; - this.events = []; - this.commands = []; - this.shims = []; - this.usesImageSource = false; - } - - fail(where, detail) { - throw new Error(`${this.specPath}: ${where}: ${detail}`); - } - - /// The Fabric component name: what JS mounts and what core registers. - get name() { - return this.componentName; - } - - get propsName() { - return `${this.name}Props`; - } - - get changedName() { - return `${this.name}Changed`; - } - - get eventsName() { - return `${this.name}Events`; - } - - get eventSenderName() { - return `${this.name}EventSender`; - } - - get contextName() { - return `${this.name}Context`; - } - - get specName() { - return `${this.name}Spec`; - } - - get registrationType() { - return `${this.name}Component`; - } - - get registrationFn() { - return `${snakeCase(this.name)}_component`; - } - - /// The Rust name for a nested type at `typePath`, e.g. `FixtureChartCardNested` - /// for the `nested` field of the `card` prop. - typeNameFor(typePath) { - return `${this.name}${typePath.map(pascal).join('')}`; - } - - /// React Native's own C++ name for the struct at `typePath`, so the generated - /// C++ file can `static_assert` the layouts match. - cppNameFor(typePath) { - return `${this.typeNameFor(typePath)}Struct`; - } - - get changeWords() { - return Math.max(1, Math.ceil(this.props.length / 64)); - } - - /// A type name nothing else claimed, so two props that would produce the same - /// name (`points` and `point`) get a suffix rather than colliding. - claim(base) { - let name = base; - let suffix = 2; - while (this.typeNames.has(name)) { - name = `${base}${suffix}`; - suffix += 1; - } - this.typeNames.add(name); - return name; - } - - /// The Rust enum for a codegen enum annotation, generating it once. - enumFor(propName, annotation) { - const numeric = annotation.type === 'Int32EnumTypeAnnotation'; - const options = annotation.options ?? []; - if (options.length === 0) { - this.fail(`prop ${propName}`, 'an enum needs at least one member'); - } - for (const [index, option] of options.entries()) { - if (numeric && typeof option !== 'number') { - this.fail(`prop ${propName}`, `enum member ${index} is not a number`); - } - if (!numeric && typeof option !== 'string') { - this.fail(`prop ${propName}`, `enum member ${index} is not a string`); - } - } - const name = this.claim(`${this.name}${pascal(propName)}`); - const declared = { - name, - propName, - numeric, - members: options.map((option, index) => ({ - name: enumMemberName(option, numeric, index, propName), - value: numeric ? option : index, - text: String(option), - })), - }; - this.enums.push(declared); - return declared; - } - - /// Whether every leaf of an annotation is plain data, so it can be mirrored - /// with `#[repr(C)]` and lent out as a slice of structs. - isPlain(annotation) { - switch (annotation.type) { - case 'Int32TypeAnnotation': - case 'FloatTypeAnnotation': - case 'DoubleTypeAnnotation': - case 'NumberTypeAnnotation': - case 'BooleanTypeAnnotation': - case 'StringEnumTypeAnnotation': - case 'Int32EnumTypeAnnotation': - return true; - case 'ObjectTypeAnnotation': - return (annotation.properties ?? []).every(property => - this.isPlain(property.typeAnnotation), - ); - default: - return false; - } - } - - /// A `#[repr(C)]` mirror of a plain object, named after React Native's own - /// struct for it so the C++ file can assert the two layouts match. - mirror(typePath, annotation, cppName) { - const name = this.claim(this.typeNameFor(typePath)); - const fields = (annotation.properties ?? []).map(property => ({ - jsName: property.name, - name: rustIdentifier(snakeCase(property.name)), - rustType: this.plainType(property.typeAnnotation, property.name), - })); - const mirror = { name, cppName, fields }; - this.mirrors.push(mirror); - return { kind: 'mirror', name }; - } - - /// The Rust type of a plain-data annotation, inside a mirror or a slice. - plainType(annotation, propName) { - const scalar = scalarType(annotation); - if (scalar) return scalar; - if ( - annotation.type === 'StringEnumTypeAnnotation' || - annotation.type === 'Int32EnumTypeAnnotation' - ) { - return this.enumFor(propName, annotation).name; - } - if (annotation.type === 'ObjectTypeAnnotation') { - return this.mirror([propName], annotation, null).name; - } - this.fail( - `prop ${propName}`, - `unsupported plain-data type ${annotation.type}`, - ); - return '()'; - } - - /// A view type for an object that holds strings or arrays: its fields are - /// read one at a time, so it is never mirrored. - view(typePath, annotation, cppName) { - const name = this.claim(this.typeNameFor(typePath)); - const view = { name, cppName, fields: [] }; - this.views.push(view); - view.fields = (annotation.properties ?? []).map(property => ({ - jsName: property.name, - name: rustIdentifier(snakeCase(property.name)), - shape: this.shape(property.typeAnnotation, { - typePath: [...typePath, property.name], - propName: property.name, - }), - })); - return { kind: 'view', name }; - } - - /// The shape of a props value: what its accessor returns and what the ABI - /// shim for it carries. - shape(annotation, { typePath, propName }) { - const scalar = scalarType(annotation); - if (scalar) { - const fallback = annotation.default; - return typeof fallback === 'boolean' || typeof fallback === 'number' - ? { kind: 'scalar', rustType: scalar, fallback } - : { kind: 'scalar', rustType: scalar }; - } - switch (annotation.type) { - case 'StringTypeAnnotation': - return { kind: 'string' }; - case 'StringEnumTypeAnnotation': - case 'Int32EnumTypeAnnotation': - return { - kind: 'enum', - typeName: this.enumFor(propName, annotation).name, - }; - case 'ReservedPropTypeAnnotation': - if (annotation.name === 'ColorPrimitive') return { kind: 'color' }; - if (annotation.name === 'ImageSourcePrimitive') { - this.usesImageSource = true; - return { kind: 'image' }; - } - this.fail( - `prop ${propName}`, - `unsupported reserved type ${annotation.name}`, - ); - break; - case 'MixedTypeAnnotation': - return { kind: 'mixed' }; - case 'ObjectTypeAnnotation': { - const cppName = this.cppNameFor(typePath); - if (this.isPlain(annotation)) { - return this.mirror(typePath, annotation, cppName); - } - return this.view(typePath, annotation, cppName); - } - case 'ArrayTypeAnnotation': { - const element = annotation.elementType; - if (element.type === 'StringTypeAnnotation') { - return { kind: 'array-string' }; - } - const elementScalar = scalarType(element); - if (elementScalar === 'bool') { - this.fail( - `prop ${propName}`, - 'an array of booleans is a bit-packed std::vector in C++ and cannot be borrowed; use an array of Int32', - ); - } - if (elementScalar) { - return { kind: 'array-scalar', rustType: elementScalar }; - } - if (element.type === 'ObjectTypeAnnotation') { - const cppName = this.cppNameFor(typePath); - if (this.isPlain(element)) { - return { - ...this.mirror(typePath, element, cppName), - kind: 'array-plain', - }; - } - const declared = this.view(typePath, element, cppName); - const slice = { name: `${declared.name}Slice`, view: declared.name }; - this.slices.push(slice); - return { - ...declared, - kind: 'array-view', - sliceName: slice.name, - }; - } - this.fail( - `prop ${propName}`, - `unsupported array element ${element.type}; arrays hold scalars, strings or objects`, - ); - break; - } - default: - this.fail( - `prop ${propName}`, - `unsupported component prop type ${annotation.type}`, - ); - break; - } - return { kind: 'scalar', rustType: 'f64' }; - } - - /// The shape of an event payload field. A payload travels Rust to C++ once, - /// so its fields are owned (`String`, `Vec`) rather than borrowed. - payloadShape(annotation, { payload, fieldName }) { - const scalar = scalarType(annotation); - if (scalar) return { kind: 'scalar', rustType: scalar }; - switch (annotation.type) { - case 'StringTypeAnnotation': - return { kind: 'string' }; - case 'StringEnumTypeAnnotation': - case 'Int32EnumTypeAnnotation': - return { - kind: 'enum', - typeName: this.enumFor(fieldName, annotation).name, - }; - case 'UnionTypeAnnotation': { - const options = (annotation.types ?? []).map(option => option.value); - if ( - options.length === 0 || - options.some(option => typeof option !== 'string') - ) { - this.fail( - `event ${payload} field ${fieldName}`, - 'a union in an event payload must be a union of string literals', - ); - } - const declared = this.enumFor(fieldName, { - type: 'StringEnumTypeAnnotation', - options, - }); - declared.eventEnum = true; - return { kind: 'enum', typeName: declared.name }; - } - case 'ObjectTypeAnnotation': { - const name = this.claim(`${payload}${pascal(fieldName)}`); - const declared = { - name, - label: `The \`${fieldName}\` field inside an event payload.`, - fields: [], - }; - this.payloads.push(declared); - declared.fields = (annotation.properties ?? []).map(property => ({ - jsName: property.name, - name: rustIdentifier(snakeCase(property.name)), - shape: this.payloadShape(property.typeAnnotation, { - payload: name, - fieldName: property.name, - }), - })); - return { kind: 'object', typeName: name }; - } - case 'ArrayTypeAnnotation': { - const element = annotation.elementType; - if (element.type === 'StringTypeAnnotation') { - return { kind: 'array-string' }; - } - const elementScalar = scalarType(element); - if (elementScalar) { - return { kind: 'array-scalar', rustType: elementScalar }; - } - this.fail( - `event ${payload} field ${fieldName}`, - `unsupported payload array element ${element.type}; React Native's own parser rejects those too`, - ); - break; - } - default: - this.fail( - `event ${payload} field ${fieldName}`, - `unsupported payload type ${annotation.type}`, - ); - break; - } - return { kind: 'scalar', rustType: 'f64' }; - } - - collect() { - this.props = (this.component.props ?? []).map((prop, index) => ({ - index, - jsName: prop.name, - name: rustIdentifier(snakeCase(prop.name)), - shape: this.shape(prop.typeAnnotation, { - typePath: [prop.name], - propName: prop.name, - }), - })); - - this.events = (this.component.events ?? []).map(event => { - const properties = event.typeAnnotation?.argument?.properties ?? null; - const name = rustIdentifier(snakeCase(event.name.replace(/^on/u, ''))); - if (properties === null || properties.length === 0) { - return { jsName: event.name, name, payload: null }; - } - const payload = { - name: this.claim(pascal(event.name)), - label: `The payload of the \`${event.name}\` event.`, - fields: [], - }; - this.payloads.push(payload); - this.activeLabel = payload.label; - payload.fields = properties.map(property => ({ - jsName: property.name, - name: rustIdentifier(snakeCase(property.name)), - shape: this.payloadShape(property.typeAnnotation, { - payload: payload.name, - fieldName: property.name, - }), - })); - return { jsName: event.name, name, payload }; - }); - - this.commands = (this.component.commands ?? []).map(command => ({ - jsName: command.name, - name: rustIdentifier(snakeCase(command.name)), - params: (command.typeAnnotation?.params ?? []).map(parameter => ({ - jsName: parameter.name, - name: rustIdentifier(snakeCase(parameter.name)), - rustType: this.commandType( - parameter.typeAnnotation, - command.name, - parameter.name, - ), - })), - })); - } - - /// A command argument's Rust type. The generated C++ dispatcher converts - /// `folly::dynamic` arguments to typed values once, so these - /// are owned. - commandType(annotation, commandName, parameterName) { - const scalar = scalarType(annotation); - if (scalar) return scalar; - switch (annotation.type) { - case 'StringTypeAnnotation': - return 'String'; - case 'ArrayTypeAnnotation': { - const element = this.commandType( - annotation.elementType, - commandName, - parameterName, - ); - if (!['i32', 'f32', 'f64', 'bool', 'String'].includes(element)) { - this.fail( - `command ${commandName}`, - `argument "${parameterName}" is an array of ${annotation.elementType.type}; commands take arrays of scalars or strings`, - ); - } - return `Vec<${element}>`; - } - default: - this.fail( - `command ${commandName}`, - `argument "${parameterName}" has type ${annotation.type}; commands take scalars, strings and arrays of them`, - ); - break; - } - return '()'; - } -} - -/// The indentation of an item inside a generated struct or trait. -const INDENT = ' '; -/// The indentation of a statement inside a generated method body. -const BODY = ' '; -const HANDLE = '*const core::ffi::c_void'; - -/// The width the generated Rust aims for, so a file out of this generator needs -/// no reformatting before it is read or reviewed. It matches rustfmt's default -/// `max_width`. -const WIDTH = 100; - -/// A `let Name { field: local, .. } = expression` line, wrapped when long. -function destructureLines(name, bindings, expression, indent = ' ') { - const oneLine = `let ${name} { ${bindings.join(', ')} } = ${expression};`; - const pattern = bindings.join(', '); - if (pattern.length <= 18 && indent.length + oneLine.length <= WIDTH) { - return [`${indent}${oneLine}`]; - } - return [ - `${indent}let ${name} {`, - ...bindings.map(binding => `${indent} ${binding},`), - `${indent}} = ${expression};`, - ]; -} - -/// A `&[&str]` constant, one entry per line when it would run past [`WIDTH`]. -function stringSliceLines(declaration, items, indent = INDENT) { - const oneLine = `${declaration} &[${items.map(rustString).join(', ')}];`; - if (indent.length + oneLine.length <= WIDTH) return [`${indent}${oneLine}`]; - return [ - `${indent}${declaration} &[`, - ...items.map(item => `${indent} ${rustString(item)},`), - `${indent}];`, - ]; -} - -/// One expression statement at method-body indentation, wrapped inside a block -/// when it would run past [`WIDTH`]. -function expressionLines(expression, indent = BODY) { - if (indent.length + expression.length <= WIDTH) { - return [`${indent}${expression}`]; - } - const unsafe = /^unsafe \{ (.*) \}$/u.exec(expression); - if (unsafe !== null) { - return [`${indent}unsafe {`, `${indent} ${unsafe[1]}`, `${indent}}`]; - } - return [`${indent}{`, `${indent} ${expression}`, `${indent}}`]; -} - -/// An `unsafe { shim(..) }` statement, one argument per line when it would run -/// past [`WIDTH`]. -function unsafeCallLines(callee, args, indent = BODY) { - const oneLine = `${indent}unsafe { ${callee}(${args.join(', ')}) }`; - if (oneLine.length <= WIDTH) return [oneLine]; - return [ - `${indent}unsafe {`, - ...(args.map(argument => `${indent} ${argument},`).length > 0 - ? [ - `${indent} ${callee}(`, - ...args.map(argument => `${indent} ${argument},`), - `${indent} )`, - ] - : [`${indent} ${callee}()`]), - `${indent}}`, - ]; -} - -/// A declaration, wrapped one parameter per line when it would run long. -function wrapDeclaration(declaration, indent = ' ') { - if (declaration.length <= 100) return [declaration]; - const open = declaration.indexOf('('); - const close = declaration.lastIndexOf(')'); - if (open === -1 || close === -1) return [declaration]; - const head = declaration.slice(0, open + 1); - const body = declaration.slice(open + 1, close); - const tail = declaration.slice(close); - const params = []; - let depth = 0; - let start = 0; - for (let index = 0; index < body.length; index += 1) { - const character = body[index]; - if ('<(['.includes(character)) depth += 1; - else if ('>)]'.includes(character)) depth -= 1; - else if (character === ',' && depth === 0) { - params.push(body.slice(start, index).trim()); - start = index + 1; - } - } - const last = body.slice(start).trim(); - if (last.length > 0) params.push(last); - return [ - head, - ...params.map(param => `${indent} ${param},`), - `${indent}${tail}`, - ]; -} - -/// A Rust doc comment block from lines of text. -function docComment(lines, indent = '') { - return lines.map(line => `${indent}/// ${line}`.trimEnd()).join('\n'); -} - -/// A doc comment saying what an accessor returns. -function accessorDoc(shape) { - switch (shape.kind) { - case 'scalar': - return `The value, as \`${shape.rustType}\`.`; - case 'string': - return 'The string, borrowed from the C++ field.'; - case 'enum': - return `The enum value, as \`${shape.typeName}\`.`; - case 'color': - return 'The ARGB color, or `None` when React left it unset.'; - case 'image': - return 'A borrowed view over the C++ `ImageSource`.'; - case 'mixed': - return 'The `UnsafeMixed` value, parsed once on the first read: the one accessor that copies.'; - case 'array-scalar': - return `The elements, borrowed, as \`&[${shape.rustType}]\`.`; - case 'array-string': - return 'The strings, read one at a time.'; - case 'mirror': - return `The value, as the \`#[repr(C)]\` mirror \`${shape.name}\`.`; - case 'array-plain': - return `The elements, borrowed, as \`&[${shape.name}]\`.`; - case 'view': - return 'A borrowed view over the C++ struct.'; - case 'array-view': - return 'The length, then one borrowed view per index.'; - default: - return ''; - } -} - -/// One accessor on a props view or a view type: its body, and the `extern "C"` -/// declaration of the shim it calls. -function accessor({ shimPrefix, shape, name, jsName, owner }) { - const shim = `${shimPrefix}_${snakeCase(jsName)}`; - const lines = []; - const externs = []; - const call = args => `unsafe { ${shim}(${args}) }`; - switch (shape.kind) { - case 'scalar': - lines.push(` pub fn ${name}(&self) -> ${shape.rustType} {`); - lines.push(` ${call('self.handle')}`); - lines.push(' }'); - externs.push(` fn ${shim}(${owner}: ${HANDLE}) -> ${shape.rustType};`); - break; - case 'string': - lines.push(` pub fn ${name}(&self) -> &str {`); - lines.push( - ...expressionLines(`unsafe { rn_gpui_str(${shim}(self.handle)) }`), - ); - lines.push(' }'); - externs.push(` fn ${shim}(${owner}: ${HANDLE}) -> RnGpuiStr;`); - break; - case 'enum': - lines.push(` pub fn ${name}(&self) -> ${shape.typeName} {`); - lines.push(` ${shape.typeName}::from_raw(${call('self.handle')})`); - lines.push(' }'); - externs.push(` fn ${shim}(${owner}: ${HANDLE}) -> i32;`); - break; - case 'color': - lines.push(` pub fn ${name}(&self) -> Option {`); - lines.push(` let color = ${call('self.handle')};`); - lines.push(' if color.present {'); - lines.push(' Some(color.value)'); - lines.push(' } else {'); - lines.push(' None'); - lines.push(' }'); - lines.push(' }'); - externs.push(` fn ${shim}(${owner}: ${HANDLE}) -> RnGpuiOptU32;`); - break; - case 'image': - lines.push(` pub fn ${name}(&self) -> RnGpuiImageSource {`); - lines.push( - ...expressionLines( - `unsafe { RnGpuiImageSource::from_handle(${shim}(self.handle)) }`, - ), - ); - lines.push(' }'); - externs.push(` fn ${shim}(${owner}: ${HANDLE}) -> ${HANDLE};`); - break; - case 'mixed': - lines.push(` pub fn ${name}(&self) -> &Value {`); - lines.push(` self.mixed_${name}.get_or_init(|| {`); - lines.push(' let mut text = String::new();'); - lines.push(' unsafe {'); - lines.push(` ${shim}(`); - lines.push(' self.handle,'); - lines.push(' rn_gpui_collect_text,'); - lines.push(' (&mut text as *mut String).cast(),'); - lines.push(' );'); - lines.push(' }'); - lines.push( - ' react_native_gpui::host_component::parse_value(&text)', - ); - lines.push(' })'); - lines.push(' }'); - externs.push( - ` fn ${shim}(${owner}: ${HANDLE}, sink: RnGpuiTextSink, context: *mut core::ffi::c_void);`, - ); - break; - case 'array-scalar': - lines.push(` pub fn ${name}(&self) -> &[${shape.rustType}] {`); - lines.push(` unsafe { rn_gpui_slice(${shim}(self.handle)) }`); - lines.push(' }'); - externs.push(` fn ${shim}(${owner}: ${HANDLE}) -> RnGpuiSlice;`); - break; - case 'array-string': - lines.push(` pub fn ${name}(&self) -> RnGpuiStrArray<'_> {`); - lines.push(` let len = unsafe { ${shim}_len(self.handle) };`); - lines.push( - ` unsafe { RnGpuiStrArray::new(self.handle, len, ${shim}_at) }`, - ); - lines.push(' }'); - externs.push(` fn ${shim}_len(${owner}: ${HANDLE}) -> usize;`); - externs.push( - ` fn ${shim}_at(${owner}: ${HANDLE}, index: usize) -> RnGpuiStr;`, - ); - break; - case 'mirror': - lines.push(` pub fn ${name}(&self) -> ${shape.name} {`); - lines.push(` ${call('self.handle')}`); - lines.push(' }'); - externs.push(` fn ${shim}(${owner}: ${HANDLE}) -> ${shape.name};`); - break; - case 'array-plain': - lines.push(` pub fn ${name}(&self) -> &[${shape.name}] {`); - lines.push(` unsafe { rn_gpui_slice(${shim}(self.handle)) }`); - lines.push(' }'); - externs.push(` fn ${shim}(${owner}: ${HANDLE}) -> RnGpuiSlice;`); - break; - case 'view': - lines.push(` pub fn ${name}(&self) -> ${shape.name}<'_> {`); - lines.push( - ...expressionLines( - `unsafe { ${shape.name}::from_handle(${shim}(self.handle)) }`, - ), - ); - lines.push(' }'); - externs.push(` fn ${shim}(${owner}: ${HANDLE}) -> ${HANDLE};`); - break; - case 'array-view': - lines.push(` pub fn ${name}(&self) -> ${shape.sliceName}<'_> {`); - lines.push(` let len = unsafe { ${shim}_len(self.handle) };`); - lines.push(` ${shape.sliceName}::new(self.handle, len)`); - lines.push(' }'); - externs.push(` fn ${shim}_len(${owner}: ${HANDLE}) -> usize;`); - externs.push( - ` fn ${shim}_at(${owner}: ${HANDLE}, index: usize) -> ${HANDLE};`, - ); - shape.atShim = `${shim}_at`; - break; - default: - throw new Error( - `generate-rust-spec: unsupported accessor shape ${shape.kind}`, - ); - } - return { lines, externs }; -} - -/// The trait signature of one command. -function commandSignature(command, contextName) { - const params = command.params - .map(parameter => `${parameter.name}: ${parameter.rustType}, `) - .join(''); - return ` fn ${command.name}(&mut self, ${params}cx: &mut ${contextName});`; -} - -function renderMirror(mirror) { - const lines = []; - lines.push( - docComment([ - `Layout mirror of the C++ \`${mirror.cppName}\`.`, - '', - 'Plain data only, so the generated C++ file asserts its size and every', - 'field offset against this struct, and a `std::vector` of them is lent out', - 'as a slice of these.', - ]), - ); - lines.push('#[repr(C)]'); - lines.push('#[derive(Clone, Copy, Debug, PartialEq)]'); - lines.push(`pub struct ${mirror.name} {`); - for (const field of mirror.fields) { - lines.push(` /// \`${field.jsName}\``); - lines.push(` pub ${field.name}: ${field.rustType},`); - } - lines.push('}'); - lines.push(''); - lines.push(`impl ${mirror.name} {`); - lines.push( - ' /// The value of a native tree prop: the fields of a JSON object.', - ); - lines.push(' pub fn from_json(json: &Map) -> Self {'); - lines.push(' Self {'); - for (const field of mirror.fields) { - lines.push( - ` ${field.name}: ${jsonScalar(`json.get(${rustString(field.jsName)})`, field.rustType)},`, - ); - } - lines.push(' }'); - lines.push(' }'); - lines.push('}'); - return lines; -} - -function renderComponentEnum(declared) { - const lines = []; - lines.push( - docComment([ - 'Mirror of the `enum class` React Native generates for this spec enum.', - '', - 'The discriminants match the C++ enum, so the value crosses the ABI as an', - '`i32` and the generated C++ file can assert the two agree.', - ]), - ); - lines.push('#[repr(i32)]'); - lines.push('#[derive(Clone, Copy, Debug, PartialEq, Eq)]'); - lines.push(`pub enum ${declared.name} {`); - for (const member of declared.members) { - lines.push(` /// \`${member.text}\``); - lines.push(` ${member.name} = ${member.value},`); - } - lines.push('}'); - lines.push(''); - lines.push(`impl ${declared.name} {`); - lines.push(' /// The value the C++ enum holds.'); - lines.push(' pub const fn as_raw(self) -> i32 {'); - lines.push(' self as i32'); - lines.push(' }'); - lines.push(''); - lines.push( - ' /// The member for a C++ enum value. The C++ side only ever sends a', - ); - lines.push( - ' /// declared member, so a mismatch means the two generated halves', - ); - lines.push( - ' /// disagree: a debug build trips here, a release build keeps the', - ); - lines.push( - ' /// first member rather than reading an invalid discriminant.', - ); - lines.push(' pub fn from_raw(value: i32) -> Self {'); - lines.push(' match value {'); - for (const member of declared.members) { - lines.push(` ${member.value} => Self::${member.name},`); - } - lines.push(' other => {'); - lines.push( - ` debug_assert!(false, "invalid ${declared.name} value {other}");`, - ); - lines.push(` Self::${declared.members[0].name}`); - lines.push(' }'); - lines.push(' }'); - lines.push(' }'); - lines.push(''); - lines.push( - ' /// The member a native tree prop holds: the JavaScript string, or the', - ); - lines.push(' /// number. An unknown value keeps the first member.'); - lines.push(' pub fn from_json(value: Option<&Value>) -> Self {'); - lines.push(' match value {'); - for (const member of declared.members) { - lines.push( - ` Some(Value::String(text)) if text == ${rustString(member.text)} => Self::${member.name},`, - ); - } - lines.push(' Some(Value::Number(number)) => {'); - lines.push( - ' Self::from_raw(number.as_i64().unwrap_or_default() as i32)', - ); - lines.push(' }'); - lines.push(` _ => Self::${declared.members[0].name},`); - lines.push(' }'); - lines.push(' }'); - lines.push(''); - lines.push(' /// The JavaScript string a native tree event carries.'); - lines.push(' pub fn to_json(self) -> Value {'); - lines.push(' match self {'); - for (const member of declared.members) { - lines.push( - ` Self::${member.name} => Value::from(${rustString(member.text)}),`, - ); - } - lines.push(' }'); - lines.push(' }'); - lines.push('}'); - return lines; -} - -/// The Rust type of an event payload field. -function payloadRustType(shape) { - switch (shape.kind) { - case 'scalar': - return shape.rustType; - case 'string': - return 'String'; - case 'enum': - return shape.typeName; - case 'object': - return shape.typeName; - case 'array-scalar': - return `Vec<${shape.rustType}>`; - case 'array-string': - return 'Vec'; - default: - return '()'; - } -} - -function renderPayload(payload) { - const lines = []; - lines.push( - docComment([ - payload.label, - '', - 'Owned, because an event travels Rust to C++ once. The shim fills the C++', - 'event struct React Native generated from it, one leaf at a time, rather', - 'than passing this struct across the ABI:', - '', - '- a scalar by value, an enum as its `i32`;', - '- a `String` as a pointer and a length;', - '- a `Vec` as a pointer and a length, and a `Vec` through a', - ' temporary `RnGpuiStr` slice.', - ]), - ); - lines.push('#[derive(Clone, Debug, PartialEq)]'); - lines.push(`pub struct ${payload.name} {`); - for (const field of payload.fields) { - lines.push(` /// \`${field.jsName}\``); - lines.push(` pub ${field.name}: ${payloadRustType(field.shape)},`); - } - lines.push('}'); - lines.push(''); - lines.push(`impl ${payload.name} {`); - lines.push(' /// The payload as a native tree event carries it.'); - lines.push(' pub fn to_json(&self) -> Value {'); - lines.push(' let mut object = Map::new();'); - for (const field of payload.fields) { - let expression; - switch (field.shape.kind) { - case 'enum': - case 'object': - expression = `self.${field.name}.to_json()`; - break; - case 'scalar': - expression = `Value::from(self.${field.name})`; - break; - default: - expression = `Value::from(self.${field.name}.clone())`; - } - lines.push( - ` object.insert(${rustString(field.jsName)}.to_string(), ${expression});`, - ); - } - lines.push(' Value::Object(object)'); - lines.push(' }'); - lines.push('}'); - return lines; -} - -/// The lines that flatten an owned payload into shim arguments, the shim's -/// parameter list, and the argument expressions. -function flattenPayload(generator, payload, indent = BODY) { - const params = []; - const lines = []; - const args = []; - - const walkValue = (field, local, argument) => { - const shape = field.shape; - switch (shape.kind) { - case 'scalar': - params.push(`${argument}: ${shape.rustType}`); - args.push(local); - return; - case 'enum': - params.push(`${argument}: i32`); - args.push(`${local}.as_raw()`); - return; - case 'string': - params.push(`${argument}_data: *const u8`); - params.push(`${argument}_len: usize`); - args.push(`${local}.as_ptr()`); - args.push(`${local}.len()`); - return; - case 'array-scalar': - params.push(`${argument}_data: *const ${shape.rustType}`); - params.push(`${argument}_len: usize`); - args.push(`${local}.as_ptr()`); - args.push(`${local}.len()`); - return; - case 'array-string': { - const strings = `__${argument}_strings`; - const head = `${indent}let ${strings}: Vec = ${local}`; - if ( - `${head}.iter().map(|text| RnGpuiStr::of(text)).collect();`.length <= - WIDTH - ) { - lines.push( - `${head}.iter().map(|text| RnGpuiStr::of(text)).collect();`, - ); - } else { - lines.push(head); - lines.push(`${indent} .iter()`); - lines.push(`${indent} .map(|text| RnGpuiStr::of(text))`); - lines.push(`${indent} .collect();`); - } - params.push(`${argument}_data: *const RnGpuiStr`); - params.push(`${argument}_len: usize`); - args.push(`${strings}.as_ptr()`); - args.push(`${strings}.len()`); - return; - } - case 'object': { - const declared = generator.payloads.find( - candidate => candidate.name === shape.typeName, - ); - walkObject(declared, local, argument); - return; - } - default: - throw new Error( - `generate-rust-spec: unsupported event payload shape ${shape.kind}`, - ); - } - }; - - const walkObject = (declared, expression, prefix) => { - const locals = declared.fields.map( - field => `__${prefix === '' ? '' : `${prefix}_`}${field.name}`, - ); - lines.push( - ...destructureLines( - declared.name, - declared.fields.map( - (field, index) => `${field.name}: ${locals[index]}`, - ), - expression, - indent, - ), - ); - declared.fields.forEach((field, index) => { - const argument = prefix === '' ? field.name : `${prefix}_${field.name}`; - walkValue(field, locals[index], argument); - }); - }; - - walkObject(payload, 'value', ''); - return { params, lines, args }; -} - -function renderComponentEvents(generator) { - const lines = []; - lines.push( - docComment([ - `The typed events of a \`${generator.name}\` node.`, - '', - 'An event is queued, not sent: the payload is owned by a closure that', - "joins the store's one ordered report queue and runs when the store", - 'delivers it. The closure calls the generated `extern "C"` shim for the', - 'event, which fills the C++ event struct React Native generated and hands it', - 'to the generated emitter. The payload crosses as its leaves — a scalar by', - 'value, a string as bytes and a length, an array as a pointer and a length —', - 'so no JSON is built on the way.', - ]), - ); - lines.push(`pub struct ${generator.eventsName}<'a> {`); - lines.push(` context: &'a mut ${generator.contextName},`); - lines.push('}'); - lines.push(''); - lines.push(`impl ${generator.eventsName}<'_> {`); - lines.push( - ...renderEventMethods(generator, { - receiver: '&mut self', - native: 'self.context.native.as_ref().map(|call| &call.emitter)', - emitter: - 'self.context.emitter.clone().expect("a Fabric node has an emitter")', - queue: - 'self.context.host.as_mut().expect("a Fabric node has a host context").queue_event', - verb: 'Queues', - registerShims: true, - }), - ); - lines.push('}'); - lines.push(''); - lines.push( - docComment([ - `Sends the typed events of a \`${generator.name}\` node from outside a`, - 'component method: an OS callback, a timer, a task on the main thread.', - '', - 'Take one with `event_sender()` from the context a method is given and keep', - 'it. An event joins the same ordered queue as `events()` and is delivered on', - 'a later turn; if the node has unmounted by then it is dropped, so sending', - "after the view's teardown is harmless. A sender is not `Send`: platform", - 'views call back on the main thread.', - ]), - ); - lines.push('#[derive(Clone)]'); - lines.push(`pub struct ${generator.eventSenderName} {`); - lines.push(' host: Option,'); - lines.push(' emitter: Option,'); - lines.push(' native: Option,'); - lines.push('}'); - lines.push(''); - lines.push(`impl ${generator.eventSenderName} {`); - lines.push( - ...renderEventMethods(generator, { - receiver: '&self', - native: 'self.native.as_ref()', - emitter: 'self.emitter.clone().expect("a Fabric node has an emitter")', - queue: - 'self.host.as_ref().expect("a Fabric node has an event sender").send', - verb: 'Sends', - registerShims: false, - }), - ); - lines.push('}'); - return lines; -} - -/// The methods that send each event of a component, for the context's `events()` -/// view and for the owned sender alike. `queue` is the call that takes the -/// closure carrying the payload. -function renderEventMethods(generator, options) { - const { receiver, native, emitter, queue, verb, registerShims } = options; - const lines = []; - let first = true; - for (const event of generator.events) { - const shim = `rn_gpui_${snakeCase(generator.name)}_event_${snakeCase(event.name)}`; - if (!first) lines.push(''); - first = false; - lines.push(` /// ${verb} \`${event.jsName}\`.`); - const nativeBranch = payload => [ - ` if let Some(native) = ${native} {`, - ' let mut event = Map::new();', - ` event.insert("nativeEvent".to_string(), ${payload});`, - ` native.emit(${rustString(event.jsName)}, Value::Object(event));`, - ' return;', - ' }', - ]; - if (event.payload === null) { - lines.push(` pub fn ${event.name}(${receiver}) {`); - lines.push(...nativeBranch('Value::Object(Map::new())')); - lines.push(` let emitter = ${emitter};`); - lines.push(` ${queue}(move || {`); - lines.push(` unsafe { ${shim}(emitter.as_ptr()) }`); - lines.push(' });'); - lines.push(' }'); - if (registerShims) { - generator.shims.push(` fn ${shim}(emitter: ${HANDLE});`); - } - continue; - } - const { - params, - lines: flatten, - args, - } = flattenPayload(generator, event.payload, ' '); - lines.push( - ` pub fn ${event.name}(${receiver}, value: ${event.payload.name}) {`, - ); - lines.push(...nativeBranch('value.to_json()')); - lines.push(` let emitter = ${emitter};`); - lines.push(` ${queue}(move || {`); - lines.push(...flatten); - lines.push( - ...unsafeCallLines(shim, ['emitter.as_ptr()', ...args], ' '), - ); - lines.push(' });'); - lines.push(' }'); - if (registerShims) { - generator.shims.push( - ` fn ${shim}(${['emitter: ' + HANDLE, ...params].join(', ')});`, - ); - } - } - return lines; -} - -function renderContext(generator) { - const lines = []; - lines.push( - docComment([ - `What a [\`${generator.specName}\`] method is given: core's host context plus`, - "the component's typed events.", - '', - "Core builds one per call from the node's [`HostContext`] and the event", - 'emitter handle it took at create. What the call reports goes straight', - "into the store's queue, which delivers it after the batch, the command or", - 'the frame that produced it.', - '', - 'A component that runs in a native tree (a `NativeRoot`) is given one built', - 'from the tree instead: the same methods work, `children()` holds its', - "children's elements, and what only a Fabric node has (`host()`, the", - 'window of a mount batch, intrinsic size and insets) is absent or ignored.', - ]), - ); - lines.push(`pub struct ${generator.contextName} {`); - lines.push(' host: Option,'); - lines.push(' emitter: Option,'); - lines.push(' native: Option,'); - lines.push('}'); - lines.push(''); - lines.push(`impl ${generator.contextName} {`); - lines.push( - " /// Core builds one for a call: the node's host context and emitter.", - ); - lines.push( - ' pub fn new(host: HostContext, emitter: EmitterHandle) -> Self {', - ); - lines.push( - ' Self { host: Some(host), emitter: Some(emitter), native: None }', - ); - lines.push(' }'); - lines.push(''); - lines.push( - ' /// Core builds one for a call on an instance of a native tree.', - ); - lines.push(' pub fn new_native(call: NativeCall) -> Self {'); - lines.push(' Self { host: None, emitter: None, native: Some(call) }'); - lines.push(' }'); - lines.push(''); - lines.push(" /// Core's context: the node's tag and what it reported."); - lines.push(' ///'); - lines.push(' /// # Panics'); - lines.push(' ///'); - lines.push(' /// In a native tree, which has no host context.'); - lines.push(' pub fn host(&self) -> &HostContext {'); - lines.push( - ' self.host.as_ref().expect("a component in a native tree has no host context")', - ); - lines.push(' }'); - lines.push(''); - lines.push( - " /// Core's context, mutably, for a component that reads back what it", - ); - lines.push(' /// reported in this call.'); - lines.push(' ///'); - lines.push(' /// # Panics'); - lines.push(' ///'); - lines.push(' /// In a native tree, which has no host context.'); - lines.push(' pub fn host_mut(&mut self) -> &mut HostContext {'); - lines.push( - ' self.host.as_mut().expect("a component in a native tree has no host context")', - ); - lines.push(' }'); - lines.push(''); - lines.push( - ' /// The Fabric tag of the node; in a native tree, the id of the instance.', - ); - lines.push(' pub fn tag(&self) -> i32 {'); - lines.push(' match (&self.host, &self.native) {'); - lines.push(' (Some(host), _) => host.tag,'); - lines.push(' (None, Some(call)) => call.id as i32,'); - lines.push(' (None, None) => 0,'); - lines.push(' }'); - lines.push(' }'); - lines.push(''); - lines.push( - " /// GPUI's `App`, for creating entities, subscribing and reading globals.", - ); - lines.push( - ' /// Present in the call core makes it for (a mount, a frame, a command);', - ); - lines.push(' /// `None` in a unit test and after the method returned.'); - lines.push(' pub fn app(&mut self) -> Option<&mut gpui::App> {'); - lines.push(' match (&mut self.host, &mut self.native) {'); - lines.push(' (Some(host), _) => host.app(),'); - lines.push( - ' (None, Some(call)) => Some(unsafe { &mut *call.app }),', - ); - lines.push(' (None, None) => None,'); - lines.push(' }'); - lines.push(' }'); - lines.push(''); - lines.push( - ' /// The `Window` of the call, for a command and the native view methods;', - ); - lines.push( - ' /// `None` in `create` and `update`, which run in a mount batch, and in a', - ); - lines.push(' /// native tree.'); - lines.push(' pub fn window(&mut self) -> Option<&mut gpui::Window> {'); - lines.push(' self.host.as_mut().and_then(|host| host.window())'); - lines.push(' }'); - lines.push(''); - lines.push( - " /// Runs `f` with the node's own window and the `App`: the window of the", - ); - lines.push( - ' /// call if it has one, otherwise the window the node is shown in. `None`', - ); - lines.push(' /// when that window is not known yet or is busy.'); - lines.push( - ' pub fn with_window(&mut self, f: impl FnOnce(&mut gpui::Window, &mut gpui::App) -> R) -> Option {', - ); - lines.push(' match (&mut self.host, &mut self.native) {'); - lines.push(' (Some(host), _) => host.with_window(f),'); - lines.push(' (None, Some(call)) => {'); - lines.push(' let window = call.window?;'); - lines.push(' let app = unsafe { &mut *call.app };'); - lines.push( - ' window.update(app, |_, window, app| f(window, app)).ok()', - ); - lines.push(' }'); - lines.push(' (None, None) => None,'); - lines.push(' }'); - lines.push(' }'); - lines.push(''); - lines.push( - ' /// Reports the size this component wants, in DIPs. A native tree', - ); - lines.push( - " /// lays out the component's elements instead, so it ignores this.", - ); - lines.push( - ' pub fn set_intrinsic_size(&mut self, width: f32, height: f32) {', - ); - lines.push(' if let Some(host) = &mut self.host {'); - lines.push(' host.set_intrinsic_size(width, height);'); - lines.push(' }'); - lines.push(' }'); - lines.push(''); - lines.push( - " /// Reports the padding this container's chrome needs around React's", - ); - lines.push(' /// children, in DIPs. Ignored in a native tree.'); - lines.push( - ' pub fn set_insets(&mut self, top: f32, right: f32, bottom: f32, left: f32) {', - ); - lines.push(' if let Some(host) = &mut self.host {'); - lines.push(' host.set_insets(top, right, bottom, left);'); - lines.push(' }'); - lines.push(' }'); - lines.push(''); - lines.push( - " /// The elements of the component's children in a native tree, taken: the", - ); - lines.push( - ' /// component places them in its own element. Empty for a Fabric node, whose', - ); - lines.push(' /// children core paints itself.'); - lines.push(' pub fn children(&mut self) -> Vec {'); - lines.push( - ' self.native.as_mut().map(|call| std::mem::take(&mut call.children)).unwrap_or_default()', - ); - lines.push(' }'); - lines.push(''); - lines.push(" /// The component's typed events."); - lines.push(` pub fn events(&mut self) -> ${generator.eventsName}<'_> {`); - lines.push(` ${generator.eventsName} { context: self }`); - lines.push(' }'); - lines.push(''); - lines.push( - ' /// A sender for the same events that outlives this call, for an OS', - ); - lines.push(' /// callback or a task on the main thread.'); - lines.push( - ` pub fn event_sender(&self) -> ${generator.eventSenderName} {`, - ); - lines.push(` ${generator.eventSenderName} {`); - lines.push( - ' host: self.host.as_ref().map(|host| host.event_sender()),', - ); - lines.push(' emitter: self.emitter.clone(),'); - lines.push( - ' native: self.native.as_ref().map(|call| call.emitter.clone()),', - ); - lines.push(' }'); - lines.push(' }'); - lines.push('}'); - return lines; -} - -function renderView(generator, view) { - const lines = []; - lines.push( - docComment([ - `A borrowing view over the C++ \`${view.cppName}\`.`, - '', - 'Its fields are read one at a time through generated accessors, because a', - 'struct holding a `std::string` or a `std::vector` has no plain layout to', - 'mirror.', - ]), - ); - const mixedFields = view.fields.filter(field => field.shape.kind === 'mixed'); - const caches = ownedCacheFields(view.fields); - lines.push(`pub struct ${view.name}<'a> {`); - lines.push(` handle: ${HANDLE},`); - lines.push(' json: *const Map,'); - lines.push(" _borrow: core::marker::PhantomData<&'a ()>,"); - for (const field of mixedFields) { - lines.push(` mixed_${field.name}: std::cell::OnceCell,`); - } - for (const cache of caches) { - lines.push(` ${cache.name}: ${cache.type},`); - } - lines.push('}'); - lines.push(''); - lines.push(`impl<'a> ${view.name}<'a> {`); - lines.push(' /// # Safety'); - lines.push(' ///'); - lines.push( - ` /// \`handle\` must be the address of a live C++ \`${view.cppName}\` that`, - ); - lines.push( - ' /// outlives the borrow the accessor that returned this view gave.', - ); - lines.push(` unsafe fn from_handle(handle: ${HANDLE}) -> Self {`); - lines.push(' Self {'); - lines.push(' handle,'); - lines.push(' json: core::ptr::null(),'); - lines.push(' _borrow: core::marker::PhantomData,'); - for (const field of mixedFields) { - lines.push(` mixed_${field.name}: std::cell::OnceCell::new(),`); - } - for (const cache of caches) { - lines.push(` ${cache.name}: std::cell::OnceCell::new(),`); - } - lines.push(' }'); - lines.push(' }'); - lines.push(''); - lines.push(' /// A view over the fields of a native tree prop.'); - lines.push(" pub fn from_json(json: &'a Map) -> Self {"); - lines.push(' Self {'); - lines.push(` handle: core::ptr::null(),`); - lines.push(' json,'); - lines.push(' _borrow: core::marker::PhantomData,'); - for (const field of mixedFields) { - lines.push(` mixed_${field.name}: std::cell::OnceCell::new(),`); - } - for (const cache of caches) { - lines.push(` ${cache.name}: std::cell::OnceCell::new(),`); - } - lines.push(' }'); - lines.push(' }'); - for (const field of view.fields) { - const rendered = accessor({ - shimPrefix: `rn_gpui_${snakeCase(view.name)}`, - shape: field.shape, - name: field.name, - jsName: field.jsName, - owner: 'value', - }); - lines.push(''); - lines.push(` /// ${accessorDoc(field.shape)}`); - lines.push( - rendered.lines[0], - ...nativeAccessorLines(field), - ...rendered.lines.slice(1), - ); - generator.shims.push(...rendered.externs); - } - lines.push('}'); - return lines; -} - -function renderSlice(slice, view, atShim) { - const lines = []; - lines.push( - docComment([ - `A borrowed C++ \`std::vector<${view.cppName}>\`:`, - 'the length, then one view per index.', - ]), - ); - lines.push(`pub struct ${slice.name}<'a> {`); - lines.push(` handle: ${HANDLE},`); - lines.push(' len: usize,'); - lines.push(" json: Option<&'a [Value]>,"); - lines.push(" _borrow: core::marker::PhantomData<&'a ()>,"); - lines.push('}'); - lines.push(''); - lines.push(`impl<'a> ${slice.name}<'a> {`); - lines.push(` fn new(handle: ${HANDLE}, len: usize) -> Self {`); - lines.push(' Self {'); - lines.push(' handle,'); - lines.push(' len,'); - lines.push(' json: None,'); - lines.push(' _borrow: core::marker::PhantomData,'); - lines.push(' }'); - lines.push(' }'); - lines.push(''); - lines.push(' /// The elements of a native tree prop.'); - lines.push(" pub fn from_json(items: &'a [Value]) -> Self {"); - lines.push(' Self {'); - lines.push(' handle: core::ptr::null(),'); - lines.push(' len: items.len(),'); - lines.push(' json: Some(items),'); - lines.push(' _borrow: core::marker::PhantomData,'); - lines.push(' }'); - lines.push(' }'); - lines.push(''); - lines.push(' pub fn len(&self) -> usize {'); - lines.push(' self.len'); - lines.push(' }'); - lines.push(''); - lines.push(' pub fn is_empty(&self) -> bool {'); - lines.push(' self.len == 0'); - lines.push(' }'); - lines.push(''); - lines.push( - ` pub fn get(&self, index: usize) -> Option<${view.name}<'a>> {`, - ); - lines.push(' if index >= self.len {'); - lines.push(' return None;'); - lines.push(' }'); - lines.push(' if let Some(items) = self.json {'); - lines.push( - ` return items.get(index).and_then(Value::as_object).map(${view.name}::from_json);`, - ); - lines.push(' }'); - lines.push(` let handle = unsafe { ${atShim}(self.handle, index) };`); - lines.push(' if handle.is_null() {'); - lines.push(' return None;'); - lines.push(' }'); - lines.push(` Some(unsafe { ${view.name}::from_handle(handle) })`); - lines.push(' }'); - lines.push(''); - lines.push( - ` pub fn iter(&self) -> impl Iterator> + '_ {`, - ); - lines.push(' (0..self.len).filter_map(move |index| self.get(index))'); - lines.push(' }'); - lines.push('}'); - return lines; -} - -/// A scalar read from an optional JSON value, as `rustType`. -function jsonScalar(value, rustType, fallback) { - const has = fallback !== undefined; - if (rustType === 'bool') { - return has - ? `${value}.and_then(Value::as_bool).unwrap_or(${fallback})` - : `${value}.and_then(Value::as_bool).unwrap_or_default()`; - } - if (rustType === 'f32' || rustType === 'f64') { - return has - ? `${value}.and_then(Value::as_f64).unwrap_or(${Number(fallback)}_f64) as ${rustType}` - : `${value}.and_then(Value::as_f64).unwrap_or_default() as ${rustType}`; - } - return has - ? `${value}.and_then(Value::as_i64).unwrap_or(${Math.trunc(Number(fallback))}_i64) as ${rustType}` - : `${value}.and_then(Value::as_i64).unwrap_or_default() as ${rustType}`; -} - -/// Every spec is a component of a native tree: each prop shape has a reading -/// of its JSON value. -function supportsNativeTree() { - return true; -} - -/// The fields a view over props or over a nested struct caches for the shapes -/// whose accessor lends a slice. -function ownedCacheFields(fields) { - return fields - .filter( - field => - field.shape.kind === 'array-scalar' || - field.shape.kind === 'array-plain', - ) - .map(field => ({ - name: `native_${field.name}`, - type: `std::cell::OnceCell>`, - })); -} - -/// The lines that read prop or field `prop` from the JSON of a native tree -/// instance, returned from the accessor before it reads the C++ ones. -function nativeAccessorLines(prop) { - const { shape, jsName, name } = prop; - const key = rustString(jsName); - const lines = [' if !self.json.is_null() {']; - lines.push(' let json = unsafe { &*self.json };'); - const object = `json.get(${key}).and_then(Value::as_object).unwrap_or_else(empty_map)`; - const array = `json.get(${key}).and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[])`; - switch (shape.kind) { - case 'scalar': - lines.push( - ` return ${jsonScalar(`json.get(${key})`, shape.rustType, shape.fallback)};`, - ); - break; - case 'string': - lines.push( - ` return json.get(${key}).and_then(Value::as_str).unwrap_or_default();`, - ); - break; - case 'enum': - lines.push( - ` return ${shape.typeName}::from_json(json.get(${key}));`, - ); - break; - case 'color': - lines.push( - ` return json.get(${key}).and_then(Value::as_i64).map(|color| color as u32);`, - ); - break; - case 'mixed': - lines.push( - ` return self.mixed_${name}.get_or_init(|| json.get(${key}).cloned().unwrap_or(Value::Null));`, - ); - break; - case 'array-scalar': { - const read = - shape.rustType === 'bool' - ? 'Value::as_bool' - : shape.rustType === 'f32' || shape.rustType === 'f64' - ? 'Value::as_f64' - : 'Value::as_i64'; - const cast = shape.rustType === 'bool' ? '' : ` as ${shape.rustType}`; - lines.push(` return self.native_${name}.get_or_init(|| {`); - lines.push( - ` ${array}.iter().filter_map(${read}).map(|item| item${cast}).collect()`, - ); - lines.push(' });'); - break; - } - case 'array-string': - lines.push(` return RnGpuiStrArray::from_json(${array});`); - break; - case 'image': - lines.push(` return RnGpuiImageSource::from_json(${object});`); - break; - case 'mirror': - lines.push(` return ${shape.name}::from_json(${object});`); - break; - case 'array-plain': - lines.push(` return self.native_${name}.get_or_init(|| {`); - lines.push( - ` ${array}.iter().filter_map(Value::as_object).map(${shape.name}::from_json).collect()`, - ); - lines.push(' });'); - break; - case 'view': - lines.push(` return ${shape.name}::from_json(${object});`); - break; - case 'array-view': - lines.push(` return ${shape.sliceName}::from_json(${array});`); - break; - default: - throw new Error( - `generate-rust-spec: unsupported accessor shape ${shape.kind}`, - ); - } - lines.push(' }'); - return lines; -} - -function renderPropsView(generator) { - const mixed = generator.props.filter(prop => prop.shape.kind === 'mixed'); - const lines = []; - lines.push( - docComment([ - `A typed, borrowing view over the C++ \`${generator.name}Props\`.`, - '', - 'It wraps the `shared_ptr` the mount op carries, as an', - 'opaque handle. Every accessor reads the C++ field in place, so no prop is', - 'serialised, copied or parsed on the commit path. A borrow lives as long as', - 'the `&self` it came from, so a read cannot outlive the handle.', - '', - 'A component that keeps data past the call copies what it needs in', - '`create`/`update` instead of holding the view.', - ]), - ); - const arrays = ownedCacheFields(generator.props); - lines.push(`pub struct ${generator.propsName} {`); - lines.push(` handle: ${HANDLE},`); - lines.push( - ' /// The props of a native tree instance, when this view is over those.', - ); - lines.push(' json: *const Map,'); - for (const prop of mixed) { - lines.push(` mixed_${prop.name}: std::cell::OnceCell,`); - } - for (const cache of arrays) { - lines.push(` ${cache.name}: ${cache.type},`); - } - lines.push('}'); - lines.push(''); - lines.push(`impl ${generator.propsName} {`); - lines.push(' /// # Safety'); - lines.push(' ///'); - lines.push( - ` /// \`handle\` must be the node's \`shared_ptr\``, - ); - lines.push( - ' /// and must stay alive for as long as the view is used: core holds it', - ); - lines.push(' /// until the next update replaces it.'); - const fieldInits = [ - ...mixed.map(prop => `mixed_${prop.name}: std::cell::OnceCell::new(),`), - ...arrays.map(cache => `${cache.name}: std::cell::OnceCell::new(),`), - ]; - lines.push(` pub unsafe fn from_handle(handle: ${HANDLE}) -> Self {`); - lines.push(' Self {'); - lines.push(' handle,'); - lines.push(' json: core::ptr::null(),'); - for (const init of fieldInits) lines.push(` ${init}`); - lines.push(' }'); - lines.push(' }'); - lines.push(''); - lines.push( - ' /// A view over the props of a native tree instance. The view must not', - ); - lines.push(' /// outlive the call that was given them.'); - lines.push(' pub fn from_json(json: &Map) -> Self {'); - lines.push(' Self {'); - lines.push(` handle: core::ptr::null(),`); - lines.push(' json,'); - for (const init of fieldInits) lines.push(` ${init}`); - lines.push(' }'); - lines.push(' }'); - for (const prop of generator.props) { - const rendered = accessor({ - shimPrefix: `rn_gpui_${snakeCase(generator.name)}_props`, - shape: prop.shape, - name: prop.name, - jsName: prop.jsName, - owner: 'props', - }); - lines.push(''); - lines.push(` /// ${accessorDoc(prop.shape)}`); - lines.push( - rendered.lines[0], - ...nativeAccessorLines(prop), - ...rendered.lines.slice(1), - ); - generator.shims.push(...rendered.externs); - } - lines.push('}'); - return lines; -} - -function renderChanged(generator) { - const words = generator.changeWords; - const lines = []; - lines.push( - docComment([ - 'Which props changed in an update.', - '', - `One bit per prop, in \`${generator.registrationType}::PROPS\` order: bit \`i\` is`, - 'the `i`-th prop, bit 0 of word 0 first. **Up to 64 props fit one `u64`;**', - 'more use one word per 64 (`CHANGE_WORDS` words in all), so 65 props take', - 'two words, 128 take two, 129 take three.', - '', - 'C++ computes it against the previous shadow view and the mount op carries', - 'the words, so it is always relative to the props this component last saw', - 'and needs no translation.', - ]), - ); - lines.push('#[repr(transparent)]'); - lines.push('#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]'); - lines.push(`pub struct ${generator.changedName} {`); - lines.push(` words: [u64; ${words}],`); - lines.push('}'); - lines.push(''); - lines.push(`impl ${generator.changedName} {`); - lines.push( - ' /// No prop changed. Core never calls `update` with an empty mask.', - ); - lines.push(' pub const fn none() -> Self {'); - lines.push(` Self { words: [0; ${words}] }`); - lines.push(' }'); - lines.push(''); - lines.push(' /// A mask from the words the C++ comparison wrote.'); - lines.push(` pub const fn from_words(words: [u64; ${words}]) -> Self {`); - lines.push(' Self { words }'); - lines.push(' }'); - lines.push(''); - lines.push( - ' /// A mask from the words the mount op carried. Missing words are zero.', - ); - lines.push(' pub fn from_slice(words: &[u64]) -> Self {'); - lines.push(` let mut out = [0u64; ${words}];`); - lines.push(' for (slot, word) in out.iter_mut().zip(words) {'); - lines.push(' *slot = *word;'); - lines.push(' }'); - lines.push(' Self { words: out }'); - lines.push(' }'); - lines.push(''); - lines.push( - ' /// A mask from the names of the props a native tree update changed.', - ); - lines.push(' pub fn from_names(names: &[String]) -> Self {'); - lines.push(` let mut out = [0u64; ${words}];`); - lines.push(' for name in names {'); - lines.push(' match name.as_str() {'); - for (const prop of generator.props) { - lines.push( - ` ${rustString(prop.jsName)} => out[${Math.floor(prop.index / 64)}] |= 1u64 << ${prop.index % 64},`, - ); - } - lines.push(' _ => {}'); - lines.push(' }'); - lines.push(' }'); - lines.push(' Self { words: out }'); - lines.push(' }'); - lines.push(''); - lines.push(' /// The words.'); - lines.push(` pub const fn words(&self) -> [u64; ${words}] {`); - lines.push(' self.words'); - lines.push(' }'); - lines.push(''); - lines.push(' /// Whether no prop changed at all.'); - lines.push(' pub fn is_empty(&self) -> bool {'); - lines.push(' self.words.iter().all(|word| *word == 0)'); - lines.push(' }'); - for (const prop of generator.props) { - const word = Math.floor(prop.index / 64); - const bit = prop.index % 64; - lines.push(''); - lines.push(` /// Whether the \`${prop.jsName}\` prop changed.`); - lines.push(` pub const fn ${prop.name}(&self) -> bool {`); - lines.push(` self.words[${word}] & (1u64 << ${bit}) != 0`); - lines.push(' }'); - } - lines.push('}'); - return lines; -} - -function renderSpecTrait(generator) { - const lines = []; - lines.push( - docComment([ - `What a package implements to render a \`${generator.name}\` node.`, - '', - 'Everything takes `&mut self` and the context rather than an `App`, because', - 'the store is leased while a batch is applied: a component that dispatched', - 'during a call would re-enter it, so the context records what to do and core', - 'applies it when the call returns.', - ]), - ); - lines.push(`pub trait ${generator.specName}: Sized + 'static {`); - lines.push( - ' /// Created once, when the node mounts, on the main thread, with the', - ); - lines.push(" /// node's full props."); - lines.push( - ` fn create(props: &${generator.propsName}, cx: &mut ${generator.contextName}) -> Self;`, - ); - lines.push(''); - lines.push(" /// The node's props changed."); - lines.push(' ///'); - lines.push( - ' /// Core calls this only when at least one prop changed — never for a', - ); - lines.push( - ' /// layout-only, state-only or reparenting update — and `changed` is', - ); - lines.push(' /// never empty.'); - lines.push(' fn update('); - lines.push(' &mut self,'); - lines.push(` props: &${generator.propsName},`); - lines.push(` changed: ${generator.changedName},`); - lines.push(` cx: &mut ${generator.contextName},`); - lines.push(' );'); - lines.push(''); - lines.push( - " /// The GPUI content, laid out inside the node's Yoga frame.", - ); - lines.push(' ///'); - lines.push( - ' /// Must be cheap: read `props` by reference and keep derived data in', - ); - lines.push( - " /// `create`/`update`. Core paints a container's React children itself", - ); - lines.push(' ///, so they are not passed here.'); - lines.push(' fn render('); - lines.push(' &mut self,'); - lines.push(` props: &${generator.propsName},`); - lines.push(' window: &mut Window,'); - lines.push(` cx: &mut ${generator.contextName},`); - lines.push(' ) -> AnyElement;'); - lines.push(''); - lines.push( - " /// Content painted above a container's React children (a focus ring, a", - ); - lines.push(' /// badge), if the component has any.'); - lines.push(' ///'); - lines.push( - ' /// Core calls this only for a component declared `container: true`.', - ); - lines.push(' fn render_overlay('); - lines.push(' &mut self,'); - lines.push(` props: &${generator.propsName},`); - lines.push(' window: &mut Window,'); - lines.push(` cx: &mut ${generator.contextName},`); - lines.push(' ) -> Option {'); - lines.push(' let _ = (props, window, cx);'); - lines.push(' None'); - lines.push(' }'); - lines.push(''); - lines.push( - ' /// The OS view this node hosts, for a component declared with', - ); - lines.push( - ' /// `nativeSurface: true`. Core calls it once, when the node is first', - ); - lines.push( - ' /// painted, and attaches the view to a composition surface at the', - ); - lines.push(" /// node's bounds."); - lines.push(' fn create_view('); - lines.push(' &mut self,'); - lines.push(` props: &${generator.propsName},`); - lines.push(" parent: &NativeViewParent<'_>,"); - lines.push(' window: &mut Window,'); - lines.push(` cx: &mut ${generator.contextName},`); - lines.push( - ' ) -> react_native_gpui::native_surface::Result {', - ); - lines.push(' let _ = (props, parent, window, cx);'); - lines.push( - ' Err(react_native_gpui::native_surface::Error::msg("the component hosts no native view"))', - ); - lines.push(' }'); - lines.push(''); - lines.push( - ' /// The props changed while the hosted view is attached. Called after', - ); - lines.push(' /// [`update`](Self::update).'); - lines.push(' fn update_view('); - lines.push(' &mut self,'); - lines.push(' view: NativeViewHandle,'); - lines.push(` props: &${generator.propsName},`); - lines.push(` changed: ${generator.changedName},`); - lines.push(` cx: &mut ${generator.contextName},`); - lines.push(' ) {'); - lines.push(' let _ = (view, props, changed, cx);'); - lines.push(' }'); - lines.push(''); - lines.push( - ' /// The size Yoga gives this node under `constraint`, for a component', - ); - lines.push( - ' /// declared `measured: true`; `None` keeps the size the node last', - ); - lines.push( - ' /// reported with `set_intrinsic_size`. Unlike every other method it runs', - ); - lines.push( - " /// on the layout thread, during Yoga's measure pass, with no `self`, no", - ); - lines.push( - ' /// context, no `App` and no `Window`: derive the size from `props` alone,', - ); - lines.push( - ' /// with `react_native_gpui::host_component::measure_text` for text.', - ); - lines.push( - ` fn measure(props: &${generator.propsName}, constraint: &MeasureConstraint) -> Option {`, - ); - lines.push(' let _ = (props, constraint);'); - lines.push(' None'); - lines.push(' }'); - for (const command of generator.commands) { - lines.push(''); - lines.push(` /// JS dispatched the \`${command.jsName}\` command.`); - lines.push(' ///'); - lines.push( - ' /// The arguments are already typed: the generated C++ dispatcher', - ); - lines.push( - ' /// converted them once, and an unknown command or a wrong argument', - ); - lines.push(' /// type never reaches here.'); - lines.push(commandSignature(command, generator.contextName)); - } - lines.push('}'); - return lines; -} - -function renderRegistration(generator) { - const lines = []; - lines.push( - docComment([ - `The registration value for [\`${generator.specName}\`].`, - '', - `\`react_native_gpui::host_component::register_component(${generator.registrationFn}::())\``, - 'registers `T` for the Fabric component [`NAME`](Self::NAME) before the', - 'first surface starts. The component must be declared under', - '`platforms.desktop.hostComponents` in `react-native.config.js`: autolink', - 'gives it its registry index and its layout flags from there.', - ]), - ); - lines.push( - `pub struct ${generator.registrationType} {`, - ); - lines.push(' _spec: core::marker::PhantomData T>,'); - lines.push('}'); - lines.push(''); - lines.push( - `/// The value \`register_component\` takes for the \`${generator.name}\` component.`, - ); - lines.push( - `pub const fn ${generator.registrationFn}() -> ${generator.registrationType} {`, - ); - lines.push(` ${generator.registrationType} {`); - lines.push(' _spec: core::marker::PhantomData,'); - lines.push(' }'); - lines.push('}'); - lines.push(''); - lines.push( - `impl ${generator.registrationType} {`, - ); - lines.push(' /// The Fabric component name the spec declares.'); - lines.push( - ` pub const NAME: &'static str = ${rustString(generator.name)};`, - ); - lines.push(''); - lines.push( - " /// The spec's own props, in change-mask bit order. `ViewProps` are", - ); - lines.push(" /// core's, not these."); - lines.push( - ...stringSliceLines( - "pub const PROPS: &'static [&'static str] =", - generator.props.map(prop => prop.jsName), - ), - ); - lines.push(''); - lines.push(' /// How many `u64` words the change mask has.'); - lines.push(` pub const CHANGE_WORDS: usize = ${generator.changeWords};`); - lines.push(''); - lines.push(' /// The events the spec declares, in schema order.'); - lines.push( - ...stringSliceLines( - "pub const EVENTS: &'static [&'static str] =", - generator.events.map(event => event.jsName), - ), - ); - lines.push(''); - lines.push(' /// The commands the spec declares, in schema order.'); - lines.push( - ...stringSliceLines( - "pub const COMMANDS: &'static [&'static str] =", - generator.commands.map(command => command.jsName), - ), - ); - lines.push('}'); - return lines; -} - -function renderComponentInstance(generator) { - const lines = []; - const instance = `${generator.name}Instance`; - const spec = generator.specName; - lines.push( - docComment([ - `One mounted \`${generator.name}\` node: the user's component, the props`, - 'view built once for the props version it was last given, and the handles', - 'that keep the C++ props and emitter alive.', - '', - 'Core stores it as a `Box` on the node, so after the node is', - 'created every call is a vtable call and nothing looks the component up.', - ]), - ); - lines.push(`struct ${instance} {`); - lines.push(' component: T,'); - lines.push(` props: ${generator.propsName},`); - lines.push( - ' /// Owns the C++ props `props` reads. Declared after it, so it drops last.', - ); - lines.push(' #[allow(dead_code)]'); - lines.push(' handle: PropsHandle,'); - lines.push(' emitter: EmitterHandle,'); - lines.push('}'); - lines.push(''); - lines.push(`impl HostObject for ${instance} {`); - lines.push( - ' fn update(&mut self, props: PropsHandle, changed: &[u64], cx: HostContext) {', - ); - lines.push( - ' // The new view is built once and kept: the `UnsafeMixed` caches in it', - ); - lines.push(' // then serialise at most once per props version.'); - lines.push( - ` self.props = unsafe { ${generator.propsName}::from_handle(props.as_ptr()) };`, - ); - lines.push( - ' // The previous props are released only now, after the view stopped', - ); - lines.push(' // pointing at them.'); - lines.push(' self.handle = props;'); - lines.push( - ` let mut cx = ${generator.contextName}::new(cx, self.emitter.clone());`, - ); - lines.push( - ` let changed = ${generator.changedName}::from_slice(changed);`, - ); - lines.push(' self.component.update(&self.props, changed, &mut cx);'); - lines.push(' }'); - lines.push(''); - lines.push( - ' fn render(&mut self, window: &mut Window, cx: HostContext) -> AnyElement {', - ); - lines.push( - ` let mut cx = ${generator.contextName}::new(cx, self.emitter.clone());`, - ); - lines.push(' self.component.render(&self.props, window, &mut cx)'); - lines.push(' }'); - lines.push(''); - lines.push( - ' fn render_overlay(&mut self, window: &mut Window, cx: HostContext) -> Option {', - ); - lines.push( - ` let mut cx = ${generator.contextName}::new(cx, self.emitter.clone());`, - ); - lines.push( - ' self.component.render_overlay(&self.props, window, &mut cx)', - ); - lines.push(' }'); - lines.push(''); - lines.push( - " fn create_view(&mut self, parent: &NativeViewParent<'_>, window: &mut Window, cx: HostContext) -> react_native_gpui::native_surface::Result {", - ); - lines.push( - ` let mut cx = ${generator.contextName}::new(cx, self.emitter.clone());`, - ); - lines.push( - ' self.component.create_view(&self.props, parent, window, &mut cx)', - ); - lines.push(' }'); - lines.push(''); - lines.push( - ' fn update_view(&mut self, view: NativeViewHandle, changed: &[u64], cx: HostContext) {', - ); - lines.push( - ` let mut cx = ${generator.contextName}::new(cx, self.emitter.clone());`, - ); - lines.push( - ` let changed = ${generator.changedName}::from_slice(changed);`, - ); - lines.push( - ' self.component.update_view(view, &self.props, changed, &mut cx);', - ); - lines.push(' }'); - lines.push(''); - lines.push( - ' fn command(&mut self, index: u32, args: &[HostArg], cx: HostContext) {', - ); - if (generator.commands.length === 0) { - lines.push(' let _ = (index, args, cx);'); - } else { - lines.push( - ` let mut cx = ${generator.contextName}::new(cx, self.emitter.clone());`, - ); - lines.push(' match index {'); - generator.commands.forEach((command, commandIndex) => { - const values = command.params.map((parameter, position) => { - const argument = `args[${position}]`; - return commandArgumentExpression(parameter.rustType, argument); - }); - const call = `self.component.${command.name}(${[...values, '&mut cx'].join(', ')})`; - lines.push(` ${commandIndex} => ${call},`); - }); - lines.push(' _ => {}'); - lines.push(' }'); - } - lines.push(' }'); - lines.push('}'); - lines.push(''); - lines.push( - `impl HostComponentSpec for ${generator.registrationType} {`, - ); - lines.push(` const NAME: &'static str = ${rustString(generator.name)};`); - lines.push(''); - lines.push( - ' fn create(props: PropsHandle, emitter: EmitterHandle, cx: HostContext) -> Box {', - ); - lines.push( - ` let view = unsafe { ${generator.propsName}::from_handle(props.as_ptr()) };`, - ); - lines.push( - ` let mut cx = ${generator.contextName}::new(cx, emitter.clone());`, - ); - lines.push(' let component = T::create(&view, &mut cx);'); - lines.push(` Box::new(${instance} {`); - lines.push(' component,'); - lines.push(' props: view,'); - lines.push(' handle: props,'); - lines.push(' emitter,'); - lines.push(' })'); - lines.push(' }'); - lines.push(''); - lines.push( - ' fn measure(props: *const core::ffi::c_void, constraint: &MeasureConstraint) -> Option {', - ); - lines.push( - ` let view = unsafe { ${generator.propsName}::from_handle(props) };`, - ); - lines.push(' T::measure(&view, constraint)'); - lines.push(' }'); - lines.push('}'); - return lines; -} - -/// How a command argument is read from the JSON a native tree sends. -function nativeCommandArgument(rustType, argument) { - const item = { - i32: 'Value::as_i64).map(|item| item as i32', - f32: 'Value::as_f64).map(|item| item as f32', - f64: 'Value::as_f64).map(|item| item', - bool: 'Value::as_bool).map(|item| item', - String: 'Value::as_str).map(|item| item.to_string()', - }; - switch (rustType) { - case 'i32': - return `${argument}.and_then(Value::as_i64).unwrap_or_default() as i32`; - case 'f32': - return `${argument}.and_then(Value::as_f64).unwrap_or_default() as f32`; - case 'f64': - return `${argument}.and_then(Value::as_f64).unwrap_or_default()`; - case 'bool': - return `${argument}.and_then(Value::as_bool).unwrap_or_default()`; - case 'String': - return `${argument}.and_then(Value::as_str).unwrap_or_default().to_string()`; - default: { - const element = /^Vec<(.+)>$/u.exec(rustType)?.[1]; - if (element === undefined || item[element] === undefined) { - throw new Error( - `generate-rust-spec: unsupported command argument ${rustType}`, - ); - } - return `${argument}.and_then(Value::as_array).map(|items| items.iter().filter_map(${item[element]}).collect()).unwrap_or_default()`; - } - } -} - -/// The component as an instance of a native tree: the same spec trait, driven -/// from JSON props, a list of changed prop names and the instance's children. -function renderNativeTree(generator) { - const lines = []; - const spec = generator.specName; - const native = `${generator.name}Native`; - const context = generator.contextName; - lines.push( - docComment([ - `One \`${generator.name}\` instance of a native tree (a \`NativeRoot\`): the same`, - `component as a Fabric node, given its props as JSON and its children as`, - 'elements.', - ]), - ); - lines.push(`struct ${native} {`); - lines.push(' component: T,'); - lines.push(' id: u64,'); - lines.push(' emitter: NativeEmitter,'); - lines.push('}'); - lines.push(''); - lines.push(`impl ${native} {`); - lines.push( - ` fn call(cx: &mut NativeContext, children: Vec) -> ${context} {`, - ); - lines.push(' let app: *mut gpui::App = &mut *cx.app;'); - lines.push(` ${context}::new_native(NativeCall {`); - lines.push(' id: cx.id,'); - lines.push(' emitter: cx.emitter(),'); - lines.push(' app,'); - lines.push(' window: cx.window(),'); - lines.push(' children,'); - lines.push(' })'); - lines.push(' }'); - lines.push('}'); - lines.push(''); - lines.push(`impl NativeComponent for ${native} {`); - lines.push( - ' fn create(props: &Map, cx: &mut NativeContext) -> Self {', - ); - lines.push(` let view = ${generator.propsName}::from_json(props);`); - lines.push(' let mut call = Self::call(cx, Vec::new());'); - lines.push(' Self {'); - lines.push(' component: T::create(&view, &mut call),'); - lines.push(' id: cx.id,'); - lines.push(' emitter: cx.emitter(),'); - lines.push(' }'); - lines.push(' }'); - lines.push(''); - lines.push( - ' fn update(&mut self, props: &Map, changed: &[String], cx: &mut NativeContext) {', - ); - lines.push(` let view = ${generator.propsName}::from_json(props);`); - lines.push( - ` let changed = ${generator.changedName}::from_names(changed);`, - ); - lines.push(' let mut call = Self::call(cx, Vec::new());'); - lines.push(' self.component.update(&view, changed, &mut call);'); - lines.push(' }'); - lines.push(''); - lines.push( - ' fn command(&mut self, props: &Map, name: &str, args: &[Value], cx: &mut NativeContext) {', - ); - if (generator.commands.length === 0) { - lines.push(' let _ = (props, name, args, cx);'); - } else { - lines.push(' let _ = props;'); - lines.push(' let mut call = Self::call(cx, Vec::new());'); - lines.push(' match name {'); - for (const command of generator.commands) { - const values = command.params.map((parameter, position) => - nativeCommandArgument(parameter.rustType, `args.get(${position})`), - ); - lines.push( - ` ${rustString(command.jsName)} => self.component.${command.name}(${[...values, '&mut call'].join(', ')}),`, - ); - } - lines.push(' _ => {}'); - lines.push(' }'); - } - lines.push(' }'); - lines.push(''); - lines.push(' fn render('); - lines.push(' &mut self,'); - lines.push(' props: &Map,'); - lines.push(' children: Vec,'); - lines.push(' window: &mut Window,'); - lines.push(' app: &mut gpui::App,'); - lines.push(' ) -> AnyElement {'); - lines.push(` let view = ${generator.propsName}::from_json(props);`); - lines.push(' let app: *mut gpui::App = &mut *app;'); - lines.push(` let mut call = ${context}::new_native(NativeCall {`); - lines.push(' id: self.id,'); - lines.push(' emitter: self.emitter.clone(),'); - lines.push(' app,'); - lines.push(' window: None,'); - lines.push(' children,'); - lines.push(' });'); - lines.push(' self.component.render(&view, window, &mut call)'); - lines.push(' }'); - lines.push('}'); - lines.push(''); - lines.push(`impl ${generator.registrationType} {`); - lines.push( - ` /// Registers \`T\` as the native tree component [\`NAME\`](Self::NAME), so a`, - ); - lines.push( - ' /// `NativeRoot` can hold it. Call it next to `register_component`.', - ); - lines.push(' pub fn register_native_tree() {'); - lines.push( - ` react_native_gpui::native_tree::register_native_component::<${native}>(Self::NAME);`, - ); - lines.push(' }'); - lines.push('}'); - return lines; -} - -/// How a command argument is read from the `HostArg` core hands the instance. -/// The C++ dispatcher validated the type, so the read is infallible. -function commandArgumentExpression(rustType, argument) { - switch (rustType) { - case 'i32': - return `${argument}.to_i32()`; - case 'f32': - return `${argument}.to_f32()`; - case 'f64': - return `${argument}.to_f64()`; - case 'bool': - return `${argument}.to_bool()`; - case 'String': - return `${argument}.to_string_value()`; - case 'Vec': - return `${argument}.to_i32_vec()`; - case 'Vec': - return `${argument}.to_f32_vec()`; - case 'Vec': - return `${argument}.to_f64_vec()`; - case 'Vec': - return `${argument}.to_bool_vec()`; - case 'Vec': - return `${argument}.to_string_vec()`; - default: - throw new Error( - `generate-rust-spec: unsupported command argument ${rustType}`, - ); - } -} - -/// Renders one component: its types first, then the API over them. -function renderComponent(generator) { - generator.collect(); - const lines = []; - lines.push(''); - lines.push(`// ${generator.specPath} — ${generator.name}`); - - for (const mirror of generator.mirrors) { - lines.push(''); - lines.push(...renderMirror(mirror)); - } - for (const declared of generator.enums) { - lines.push(''); - lines.push(...renderComponentEnum(declared)); - } - for (const payload of generator.payloads) { - lines.push(''); - lines.push(...renderPayload(payload)); - } - for (const view of generator.views) { - lines.push(''); - lines.push(...renderView(generator, view)); - } - lines.push(''); - lines.push(...renderPropsView(generator)); - const atShims = new Map(); - const recordShim = shape => { - if (shape.sliceName !== undefined && shape.atShim !== undefined) { - atShims.set(shape.sliceName, shape.atShim); - } - }; - for (const prop of generator.props) recordShim(prop.shape); - for (const view of generator.views) { - for (const field of view.fields) recordShim(field.shape); - } - for (const slice of generator.slices) { - const view = generator.views.find( - candidate => candidate.name === slice.view, - ); - lines.push(''); - lines.push(...renderSlice(slice, view, atShims.get(slice.name))); - } - lines.push(''); - lines.push(...renderChanged(generator)); - lines.push(''); - lines.push(...renderComponentEvents(generator)); - lines.push(''); - lines.push(...renderContext(generator)); - lines.push(''); - lines.push(...renderSpecTrait(generator)); - lines.push(''); - lines.push(...renderRegistration(generator)); - lines.push(''); - lines.push(...renderComponentInstance(generator)); - if (supportsNativeTree(generator)) { - lines.push(''); - lines.push(...renderNativeTree(generator)); - } - lines.push(''); - lines.push('// The shims the generated C++ file implements.'); - lines.push( - '// The ABI comment at the top of this file gives the naming and the shapes.', - ); - lines.push('#[allow(dead_code, clippy::all)]'); - lines.push('unsafe extern "C" {'); - for (const shim of generator.shims) { - const declaration = shim.startsWith(' fn ') - ? shim - : ` ${shim.trim()}`; - lines.push(...wrapDeclaration(declaration)); - } - lines.push('}'); - return lines.join('\n'); -} - -/// Writes the generated file only when it changed. -export function writeRustSpec({ specPaths, outputPath }) { - const contents = generateRustSpec({ specPaths }); - const existing = fs.existsSync(outputPath) - ? fs.readFileSync(outputPath, 'utf8') - : null; - if (existing !== contents) { - fs.mkdirSync(path.dirname(outputPath), { recursive: true }); - fs.writeFileSync(outputPath, contents); - } - return contents; -} - -const invokedDirectly = - process.argv[1] !== undefined && - path.resolve(process.argv[1]) === fileURLToPath(import.meta.url); - -if (invokedDirectly) { - const args = process.argv.slice(2); - if (args.length < 2) { - console.error('usage: generate-rust-spec ... '); - process.exit(2); - } - const outputPath = args.at(-1); - writeRustSpec({ specPaths: args.slice(0, -1), outputPath }); -} diff --git a/vendor/react-native-gpui/packages/codegen/src/generate-rust-spec.test.js b/vendor/react-native-gpui/packages/codegen/src/generate-rust-spec.test.js deleted file mode 100644 index e586a6b250..0000000000 --- a/vendor/react-native-gpui/packages/codegen/src/generate-rust-spec.test.js +++ /dev/null @@ -1,273 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { describe, expect, test } from 'vitest'; -import { - generateRustSpec, - snakeCase, - pascalCase, -} from './generate-rust-spec.js'; - -// The fixture spec is also what the integration crate compiles, so the two -// stay in step. -const fixtureSpec = path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - '../../../packages/core/ReactGpui/rn-gpui-module/tests/generated/specs/NativeProbe.ts', -); - -const generated = () => generateRustSpec({ specPaths: [fixtureSpec] }); - -const generateFor = spec => { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'rust-spec-')); - const file = path.join(directory, 'NativeTemp.ts'); - fs.writeFileSync(file, spec); - return generateRustSpec({ specPaths: [file] }); -}; - -const fixture = fs.readFileSync(fixtureSpec, 'utf8'); - -test('names are converted to Rust', () => { - expect(snakeCase('greetLater')).toBe('greet_later'); - expect(snakeCase('addListener')).toBe('add_listener'); - expect(snakeCase('URLForID')).toBe('url_for_id'); - expect(pascalCase('onProgress')).toBe('OnProgress'); - expect(pascalCase('no-op')).toBe('NoOp'); -}); - -describe('the generated glue', () => { - const header = generated(); - - test('describes the spec with a trait and a descriptor', () => { - expect(header).toContain('pub trait NativeProbeSpec:'); - expect(header).toContain('fn new(events: NativeProbeEvents) -> Self;'); - expect(header).toContain( - 'pub fn native_probe_module() -> ModuleDescriptor {', - ); - expect(header).toContain('name: "NativeProbe"'); - expect(header).toContain('thread: M::THREAD'); - expect(header).toContain( - 'create: |events| Arc::new(NativeProbeInstance::::new(events))', - ); - }); - - test('maps every type of the table', () => { - expect(header).toContain( - 'fn scalar(&self, text: String, count: f64, whole: i32, flag: bool) -> Result;', - ); - // An optional parameter and a nullable one. - expect(header).toContain( - 'fn optional_value(&self, maybe: Option, nullable: Option) -> Result, ModuleError>;', - ); - expect(header).toContain( - 'fn lists(&self, items: Vec, readonly_items: Vec) -> Result, ModuleError>;', - ); - // A named alias, used twice. - expect(header).toContain( - 'fn options(&self, value: Options, again: Options) -> Result;', - ); - // A TypeScript enum and a literal union. - expect(header).toContain( - 'fn level(&self, level: Level) -> Result;', - ); - // A numeric enum, and names that are Rust keywords. - expect(header).toContain( - 'fn rank(&self, value: Rank) -> Result;', - ); - expect(header).toContain( - 'fn r#match(&self, text: String) -> Result;', - ); - expect(header).toContain('pub r#type: String,'); - // `Object` and `UnsafeObject` stay untyped. - expect(header).toContain( - 'fn anything(&self, value: Value) -> Result;', - ); - // A void method, a Promise, and Promise. - expect(header).toContain('fn nothing(&self);'); - expect(header).toContain( - 'async fn later(&self, text: String) -> Result;', - ); - expect(header).toContain( - 'async fn done(&self) -> Result<(), ModuleError>;', - ); - // A callback parameter. - expect(header).toContain( - 'fn lookup(&self, key: String, callback: Box);', - ); - }); - - test('generates the events handle and the descriptor events', () => { - expect(header).toContain('pub struct NativeProbeEvents {'); - expect(header).toContain('pub fn on_progress(&self, value: f64) {'); - expect(header).toContain( - 'self.emitter.emit("onProgress", Some(value.into_value()));', - ); - expect(header).toContain('pub fn on_done(&self) {'); - expect(header).toContain('self.emitter.emit("onDone", None);'); - expect(header).toContain( - 'pub fn send_event(&self, name: &str, body: Value) {', - ); - expect(header).toContain('EventInfo {'); - expect(header).toContain('name: "onDone"'); - expect(header).toContain('has_value: false'); - }); - - test('generates a struct for a named alias with both conversions', () => { - expect(header).toContain('pub struct Options {'); - expect(header).toContain('pub label: Option,'); - expect(header).toContain('pub count: i32,'); - expect(header).toContain('pub mode: OptionsMode,'); - expect(header).toContain('impl FromValue for Options {'); - expect(header).toContain('fields.take_optional::(path, "label")?'); - expect(header).toContain('impl IntoValue for Options {'); - // The inline object of `inline(value: { x: number; y?: string })`. - expect(header).toContain('pub struct InlineValue {'); - expect(header).toContain('pub x: f64,'); - expect(header).toContain('pub y: Option,'); - // The nested object inside the alias. - expect(header).toContain('pub struct OptionsNested {'); - }); - - test('maps an ArrayBuffer to the crate type, in arguments and results', () => { - const mapped = generateFor( - fixture - .replace( - 'nothing(): void;', - 'nothing(buffer: ArrayBuffer): void;\n bytes(): ArrayBuffer;', - ) - .replace( - 'readonly onProgress: CodegenTypes.EventEmitter;', - 'readonly onProgress: CodegenTypes.EventEmitter;', - ), - ); - expect(mapped).toContain('fn nothing(&self, buffer: ArrayBuffer);'); - expect(mapped).toContain( - 'fn bytes(&self) -> Result;', - ); - expect(mapped).toContain('pub fn on_progress(&self, value: ArrayBuffer)'); - expect(mapped).toContain('ArrayBuffer, EventEmitter, EventInfo'); - }); - - test('drops the unusable derives when a struct holds an untyped field', () => { - expect(header).toContain('pub struct Meta {'); - expect(header).toContain('pub extra: Option,'); - expect(header).toContain('pub list: Option>,'); - expect(header).not.toContain('Clone, PartialEq)]\npub struct Meta'); - }); - - test('generates a numeric enum from a TypeScript enum', () => { - expect(header).toContain('pub enum Rank {'); - expect(header).toContain('Value::Number(number) => match number as i64 {'); - expect(header).toContain('0 => Ok(Self::Low),'); - expect(header).toContain('Self::High => Value::Number(1 as f64),'); - expect(header).toContain('expected one of 0, 1, got {other}'); - }); - - test('generates enums for a TypeScript enum and a literal union', () => { - expect(header).toContain('pub enum Level {'); - expect(header).toContain('Low,'); - expect(header).toContain('Self::Low => Value::String("low".to_string()),'); - expect(header).toContain('pub enum OptionsMode {'); - expect(header).toContain('"left" => Ok(Self::Left),'); - }); - - test('routes each method through the entry point of its kind', () => { - expect(header).toContain( - 'let result = rn_gpui_module::__private::catch(|| self.0.scalar(text, count, whole, flag))??;', - ); - // A void method is prepared on the calling thread and run on the module's. - expect(header).toContain( - 'rn_gpui_module::__private::run_void("NativeProbe.nothing", move || self.0.nothing());', - ); - expect(header).toContain( - " fn prepare_void(\n self: Arc,\n method: usize,\n args: Vec,\n ) -> Result, ModuleError> {", - ); - expect(header).toContain( - 'let result = rn_gpui_module::__private::catch_async(self.0.later(text)).await??;', - ); - expect(header).toContain('kind: MethodKind::Promise,'); - // `optionalValue(maybe?, nullable)` needs both arguments, `nothing()` none. - expect(header).toContain( - 'arg_count: 2,\n required_args: 2,', - ); - expect(header).toContain( - 'arg_count: 0,\n required_args: 0,', - ); - expect(header).toContain('returns_void: true,'); - expect(header).toContain('callback_args: &[1],'); - // The callback is built from a RawCallback and consumes it. The cursor has - // a name of its own, so an object parameter cannot shadow it. - expect(header).toContain( - 'let callback = arguments_.next_callback("callback")?;', - ); - expect(header).toContain( - 'callback.invoke(vec![a0.into_value(), a1.into_value()])', - ); - }); -}); - -describe('the generator fails', () => { - test('for a callback parameter on a value-returning method', () => { - expect(() => - generateFor( - fixture.replace( - 'lookup(key: string, callback: (value: string, found: boolean) => void): void;', - 'lookup(key: string, callback: (value: string, found: boolean) => void): string;', - ), - ), - ).toThrow( - /NativeTemp\.ts: lookup: a method that takes a callback must return void or a Promise/u, - ); - }); - - test('for a type it cannot map, naming the method', () => { - expect(() => - generateFor( - fixture.replace('nothing(): void;', 'nothing(rank: 1 | 2): void;'), - ), - ).toThrow( - /NativeTemp\.ts: nothing: unsupported union member NumberLiteralTypeAnnotation/u, - ); - }); - - test('for a host object, naming the spec', () => { - // React Native's parser rejects host types before the generator sees them. - expect(() => - generateFor( - fixture.replace('nothing(): void;', 'nothing(host: HostObject): void;'), - ), - ).toThrow(/NativeTemp: Unrecognized generic type 'HostObject'/u); - }); - - test('for a recursive alias', () => { - expect(() => - generateFor( - fixture.replace( - 'export type Options = {', - 'export type Options = {\n child?: Options;', - ), - ), - ).toThrow(/recursive type alias Options is not supported/u); - }); -}); - -test('reads a callback after an object parameter', () => { - const generated = - generateFor(`import {TurboModuleRegistry, type TurboModule} from 'react-native'; - -export type Args = { - title?: string; - buttons?: Array; -}; - -export interface Spec extends TurboModule { - readonly show: (args: Args, callback: (id: number, value: string) => void) => void; -} - -export default TurboModuleRegistry.getEnforcing('Temp'); -`); - expect(generated).toContain('let args: Args = arguments_.next("args")?;'); - expect(generated).toContain( - 'let callback = arguments_.next_callback("callback")?;', - ); -}); diff --git a/vendor/react-native-gpui/packages/codegen/src/kitchen-sink-spec.js b/vendor/react-native-gpui/packages/codegen/src/kitchen-sink-spec.js deleted file mode 100644 index a09f9a1a56..0000000000 --- a/vendor/react-native-gpui/packages/codegen/src/kitchen-sink-spec.js +++ /dev/null @@ -1,59 +0,0 @@ -export const KITCHEN_SINK_SPEC = `import { - codegenNativeCommands, - codegenNativeComponent, - type CodegenTypes, - type ColorValue, - type ImageSource, - type ViewProps, -} from 'react-native'; - -export interface NativeProps extends ViewProps { - lineWidth?: Int32; - opacity?: Float; - ratio?: Double; - flag?: boolean; - tickCount?: CodegenTypes.WithDefault; - mode?: CodegenTypes.WithDefault<'line' | 'bar', 'line'>; - title?: string; - lineColor?: ColorValue; - icon?: ImageSource; - points?: ReadonlyArray>; - values?: ReadonlyArray; - labels?: ReadonlyArray; - card?: Readonly<{ - title: string; - nested: Readonly<{ flag: boolean; names: ReadonlyArray }>; - }>; - cards?: ReadonlyArray>; - extra?: CodegenTypes.UnsafeMixed; - onPointSelected?: CodegenTypes.DirectEventHandler< - Readonly<{ index: Int32; x: Double; label: string }> - >; - onRich?: CodegenTypes.DirectEventHandler< - Readonly<{ - nested: Readonly<{ flag: boolean; names: string[] }>; - speed: 'fast' | 'slow'; - }> - >; - onDone?: CodegenTypes.DirectEventHandler; -} - -export interface FixtureChartCommands { - selectPoint: (ref: React.ComponentRef, index: Int32) => void; - reportSeries: ( - ref: React.ComponentRef, - values: Array, - ) => void; - setTitle: (ref: React.ComponentRef, title: string) => void; -} - -export const Commands = codegenNativeCommands({ - supportedCommands: ['selectPoint', 'reportSeries', 'setTitle'], -}); - -const FixtureChart: any = null; - -export default codegenNativeComponent('FixtureChart', { - interfaceOnly: true, -}); -`; diff --git a/vendor/react-native-gpui/packages/core/CHANGELOG.md b/vendor/react-native-gpui/packages/core/CHANGELOG.md deleted file mode 100644 index f995f5de34..0000000000 --- a/vendor/react-native-gpui/packages/core/CHANGELOG.md +++ /dev/null @@ -1,291 +0,0 @@ -# Changelog - -All notable changes to `@react-native-gpui/core` are listed here. Each version's section becomes the notes of its GitHub release. - -## 0.87.0-alpha.5 - 2026-11-26 - -- The prebuilt runtime is published for Fabric only for now. `scripts/prebuilt-renderers.mjs` lists the renderers the workflow builds and the pin check expects; an app that selects Loom builds it from source. -- The test driver's `scroll` starts a new wheel sequence each time it is called without a phase. gpui-fast latches wheel ticks less than 500 ms apart to the container the first one went to, so a second scroll sent straight after the first, at the same point, no longer stays on the first container. -- On Windows, C sources compiled with the runtime's preinclude header (lexbor, for one) no longer fail with `STL1003`: `msvc-preinclude.h` carries its standard-library includes only for C++. The header is an input of the prebuilt runtime, so the next release has a new prebuilt. -- gpui-fast is pinned to `1ad3cc3`. The test driver's `screenshot` of an element draws only that element's device-pixel region (`Window::render_region_to_image`) instead of the whole frame cropped afterwards, which makes headless captures of small elements faster. `RN_GPUI_TEST_SCREENSHOT_TIMING=1` makes the driver log each capture's time on stderr. - -- Experimental: with `RN_GPUI_TEST_HEADLESS=1`, a `test-driver` build runs on GPUI's test platform instead of AppKit, X11/Wayland or Win32, with the same bundle, bootstrap and driver socket. No window, display or window server is used, and `screenshot` draws the scene offscreen with Metal where a GPU is available and on the CPU (tiny-skia) where it is not, or always with `GPUI_TEST_RENDERER=cpu`. It runs inside a macOS sandbox that has no window server. The CPU renderer does not draw effect groups (group opacity, blur and drop-shadow filters), blend modes, masks or native views, and shell features (menus, Dock menu, tray, system clipboard, window activation and states, the accessibility tree, displays) are not available; see `docs/desktop-testing.md`. Needs gpui-fast `de5ebfa`. -- On Windows, the Loom runtime no longer fails to compile with `Cannot open include file: 'unistd.h'`: Loom's `LoomBindingInternals.h` includes it and calls nothing from it, so the Loom header variants carry an MSVC stand-in that forwards to the real header everywhere else. -- On Windows, the Loom renderer extracts its downloaded archive with the tar that ships with the OS, so a build from a Git Bash session no longer fails with `tar: Cannot connect to C: resolve failed`. -- A native root whose size changes with its tree (a page switch, a revisited page) now settles before the next display tick instead of one tick per round between the tree and the layout: while the window holds its last frame, the runtime draws the tree as soon as a batch is applied, so the root's size is reported in the same tick. Holds on revisited pages drop from 17 to 4 of 26 (0 with `jsThread` main), and the time to the final frame by about 4 ms with `jsThread` background, 4–18 ms with main. Needs gpui-fast `8ddec44`. -- With the Loom renderer, React Native's shared animation backend runs: the runtime provides its frame source, asking for frames while an animation runs and delivering one with each, so animation libraries such as Reanimated write animated props through the backend and Loom mounts them in the same frame, with no commit. An animation running through the backend counts as busy for the test driver's idle tracking, as a native animation driver does with Fabric, and a reload starts with the frame source stopped. Reanimated's layout animations on Loom need `@react-native-gpui/reanimated` with its Loom adapter. -- The prebuilt runtime is published for the Loom renderer too: the prebuilt-binaries workflow builds each platform twice, against React Native and against Loom's React Native tree, and publishes `prebuilt-binaries-loom-.tar.gz` in the same release; the pin file has a `loom` section with its own input hash, which includes the pinned Loom and its header variants. A Loom app uses its archive under the same rules as a Fabric one, and `project.desktop.prebuilt` `always` can be used with Loom. Before, the Loom runtime always built from source. -- With the Loom renderer, where JavaScript runs (`jsThread`) is fixed when the app is built, as Loom's iOS and Android builds fix it: `RN_GPUI_JS_THREAD` no longer changes it at launch. Set it in `desktop/desktop.json`, or with `RN_GPUI_JS_THREAD` or `--js-thread` for a build; a change rebuilds the Rust part of the runtime. -- With the Loom renderer, a `NativeRoot` without a height (or a width, with `fitWidth`) and a `NativeSlot` take the size the runtime measures as the node's Loom measured size, which React commits do not replace; it was never applied, and pages of native roots stayed collapsed, overlapping and without content. A root also starts at its remembered size, as under Fabric. Needs Loom `4245aca`. -- A press on a native root's content (a kit `TextView`, for one) is no longer stopped by the React Native views around it when the root itself has no touch handlers, so the native elements see the whole press: dragging selects text, a click clears a selection, and the release ends it. The views around it still get their touch events. -- A `NativeRoot` without a height (or, with `fitWidth`, a width) of its own no longer renders its component again when the runtime has measured its tree: the size goes into the node's Fabric state, which Yoga reads, so a measurement is one layout and commit. A `NativeSlot` gets the width the tree gives it the same way, without a render of the slot or its root. The box also starts at the size an earlier tree with the same element types and primitive props was measured at (a revisited page, identical badges), and corrects it when the measurement differs, so the window holds its last frame for new roots much less often and for less time. -- A page of native roots (`NativeRoot`, and the kit components built on it) no longer shows its first frames at sizes that are about to change: a root that has just appeared, with its tree or its height still to arrive (not the content of its slots), makes the window keep showing its last frame, for at most 250 ms, until it has its size, and again if its tree grows within that time. A window that is being scrolled is not held, nor one that has already held for 200 ms in the last second, so roots that mount one after another cannot keep it on its last frame. The new page then appears in one frame at its final layout, instead of sections overlapping and moving into place. Needs gpui-fast `bdecaba`. -- On Windows, a Debug build that compiles glog from source no longer fails with `D8016: '/RTC1' and '/O2' command-line options are incompatible`: the `-g -O2` React Native's glog build adds are dropped for MSVC, where the build type sets debug info and optimization. -- On Windows, a C++ build no longer fails with `C1083: Cannot open compiler generated file: ''` when a checkout's path is long: the CMake tree is named by architecture (`x64`, `arm64`) instead of the target triple, which keeps the longest ReactCommon object files under `MAX_PATH`, the limit cl.exe cannot write past. A cached object (ccache hit) never ran the compiler, so the failure showed only on a miss. -- On Windows, a build with ccache installed no longer fails: the build no longer sets `CCACHE_BASEDIR` for MSVC, which ccache rejected in the verbatim form (`\\?\D:\...`) `canonicalize` returns, and which, once accepted, made include paths longer than `MAX_PATH`. ccache still caches MSVC builds, but not across checkouts. -- `open_window` no longer warns about an unused `mut` when built for macOS or Windows. -- Global shortcuts no longer warn that `Modifiers::SUPER` is deprecated: the platform key is `Modifiers::META`, which `global-hotkey` already turned `SUPER` into, so the shortcuts registered are the same. -- A faded view (`opacity` below 1) whose nested views change no longer shows its content unfaded for a frame: gpui-fast `3bd25f1` builds a view that paints an effect group again instead of splicing it around the changed views. -- On Windows, text inside a `maskChildren` mask or a view with `opacity` below 1 is drawn again: text in an effect group is no longer drawn with subpixel (ClearType) rendering, which left no alpha in the group. -- A mounted view costs a fraction of the memory it did: on a grid of 10,000 text cells (21,000 views) the heap is about 13 KB per view, from 35 KB, and the physical footprint about 475 MB, from 810 MB; the renderer's share is about 6.6 KB, and no longer grows with the depth of the tree. Most of what is left is React Native's own shadow tree. Each view has one layout node (3.4 before): pointer handling wraps the view's element instead of adding a child, a `Text` paints its paragraph without a node of its own unless it clips to rounded corners or is translucent, and a view that takes no focus gets a focus handle only when it is pressed, focused by the test driver, or a screen reader is running. The pointer handlers of views alike are shared, a view registers three pointer listeners instead of seven, scroll state is kept only by scroll views and text-input state only by text inputs, the view props that are rarely set are kept out of line, extension props are kept parsed rather than also as JSON, and component names are shared. Needs gpui-fast `3efc3d0`. -- Moving focus, such as clicking a focusable view, no longer builds every view in the window again: gpui-fast `74dcd1f` marks only the views that read the focus state of the elements that gained and lost it, and draws the rest from the last frame. Unmounting 5,000 cells built 10,514 views before and builds 7 now. -- After a large tree is unmounted, or a window draws nothing for a second, the renderer gives back what its frames needed beyond what is on screen: element arena chunks, the spare frame's lists and the slack of the drawn frame's. -- The test driver's `layoutStats` reports `views`, the number of React Native views mounted. -- A change between mouse and keyboard input builds only the views that read which one was last used, instead of every view in the window: gpui-fast `841adea`. Only the focused view reads it, to draw its keyboard focus ring. With 5,000 views mounted, typing in a text input right after a click reaches its `onChangeText` handler in 4.5 ms, from 35 ms, and the frame that shows the character in 22 ms, from 53 ms. The same holds while a screen reader is running: gpui-fast `c291ac4` replays the ancestors of a view built again with their role, so a view built again inside a scroll view drawn from the last frame is still known to be inside it. Needs gpui-fast `3f7a51a`. -- A button or other control with an accessibility label of its own keeps it when it is drawn again from the last frame while a screen reader is running, instead of being named by the text inside it or left without a name: gpui-fast `bcfa3e3`. This fixes `3f7a51a`. -- A `WebSocketClient` no longer crashes with `Assertion 'id_ != T::id' failed` when two messages are sent at once, such as while DevTools is attached: the write slot is claimed and the next message taken under the output lock, so only one write is in flight at a time. -- A press that begins over a `NativeRoot` or other native content keeps delivering its moves to the native elements and its release ends the gesture even when a native element handles the release; React ancestors used to stop the moves, so a native text view could not select by dragging, and a native button's click left the pointer gesture active. -- The test driver's `mouseDown` and `drag` press with a click count of 1, as a real mouse does (`clickCount` sets it for `mouseDown`); the press carried a count of 0, which components that start a selection or a drag on a first click, such as a native text view, ignore. -- A right press on React content that no `View` or component claims as a context menu reaches the extension component around it, so a native context menu (the kit's `ContextMenu`) opens over React content. Before, the press stopped at the innermost node. -- A command sent to a codegen component inside a `NativeRoot` runs in the window the tree is shown in: the context's `with_window` gives that window, where it returned `None` and commands that need a window (an input's insert, say) did nothing. `NativeContext::window()` and `NativeTree::set_window` carry it. -- `NativeSlot` takes `clip`: `false` lets content drawn outside the slot's box (a button hanging over an edge) show, clipped only by the native parents. A slot clips by default unless it is `fit`. -- `NativeRoot` takes `fitWidth`: without a width in its style, the box is as wide as its native tree's content (its max-content width), as it is as high as it without a height. With less room it shrinks, but not below the content's min-content width, as a GPUI flex item does. -- GPUI's own requests (an `img` with a URL, a remote font or vector image) are sent as GET; they went out as POST with an empty body, and a server that answers POST differently (an avatar service, say) sent back something that was not the image. -- `NativeSlot` takes `fit`: the slot is as wide as its content instead of as wide as the native layout makes it, so a native parent that centres its children centres the content. It does not clip content that overflows it. -- A `NativeSlot` whose parent in the native tree is as wide as its content (a row item, an input's prefix) takes the width of its content; before, the layout gave it no width and its content was never shown. -- `react_native_gpui::register_asset_source` lets a module add a GPUI `AssetSource` (the icons of a component library, say) that the application loads assets from. -- A component in a native tree reads a scalar prop that is not set as the default its spec declares (`WithDefault` reads `true`), as a Fabric node does, instead of as zero. -- `react_native_gpui::native_tree::child_renderers()` gives a component of a native tree one renderer per child instance, which renders that child again on demand. A component whose content is built by a closure that GPUI calls on every frame (a dialog, a popover, a table cell) uses it instead of the single-use child elements. -- `react_native_gpui::animations_disabled()` is public, so a component library can follow the test driver's `setAnimationsEnabled(false)` the way it follows the system's reduce-motion setting. -- `NativeRoot` without a `height` in its style is as high as its native tree's content: the runtime lays the tree out at its natural height and reports it, and the box takes it. A `NativeRoot` with a height behaves as before. -- Apps choose the renderer in `desktop/desktop.json`: `"renderer": "fabric"` (the default) or `"loom"`, the [Loom](https://github.com/ammarahm-ed/Loom) renderer, and with Loom `"jsThread": "background"` (the default) or `"main"` (JavaScript on the UI thread). `RN_GPUI_RENDERER` and `RN_GPUI_JS_THREAD` override the file. Metro, autolink, the codegen and the native build all read from one React Native tree: the installed package for Fabric, Loom's copy of it for Loom. Loom is pinned by commit in `ReactGpui/loom-pin.json` and downloaded and verified into the shared native-dependency cache; `RN_GPUI_LOOM_DIR` points at a local `react-native-loom` package instead. A Loom build compiles the runtime from source (there is no prebuilt for it), and Reanimated is not supported with it. `ReactCommonOverrides.loom` holds the variants of files both Loom and core replace (`NativeDOM`), `overrides.json` records the Loom file each came from as `loomBaseHash`, and `npm run check:loom-overrides` verifies them. The JavaScript thread is a startup setting of Loom, so one native build serves both modes and changing `jsThread` needs no native rebuild. -- Under Loom, the host mounts without Fabric machinery for views, paragraphs, images, scroll views, text inputs and modals: Loom's raw props are converted key by key, with React Native's own value conversions, into the renderer's flat props, and a node keeps only its frame, insets, parent and what layout must resolve later (transforms, percentage radii, directional border widths). There is no `ShadowView`, shadow tree, mutation, family or event emitter for them. Components with their own descriptor (host components, the per-component prop extractors, third-party libraries) keep the typed props Loom's compat layer parses once, and mount through direct ops. Window events and wheel events reach JavaScript through Loom's event manager by tag. The host takes Loom's desktop defaults (`LoomSettings::configurePlatform`), live scroll and location reads on any thread, a new view's first frame with its insert, a remove for an unmounted subtree's root only, and one batched release of an unmount's event targets, so it carries no workarounds of its own for them. -- Paragraph shaping is kept: the shaped-text cache is a size-bounded LRU (by entry count and approximate bytes) instead of clearing itself whole at 256 entries, so text shaped off the main thread is still there when it is painted. Under Loom a paragraph is shaped when Loom measures it, and the layout travels with the paragraph's mount op, so the main thread paints it without shaping. -- Under Loom, an image's or a modal's events that fire before Loom registers the node's event target are held and delivered when it is. A host component whose event target is slow to register mounts after one flush and receives its emitter with a later update, with a warning in the log. -- Under Loom, the host builds an Image, ScrollView, TextInput, Modal or extension component's extension props only when its props or state changed, and runs a component's prop extractor only then. -- Loom is pinned to f89ca4d: tag-keyed map nodes come from a per-container arena, commit scratch is pre-sized and released after a large commit, a paragraph's text measurements are stored once, a node's props are shared with its create operation instead of copied, and a renderer node is 320 bytes instead of 576. Loom's share of a mounted 5k-cell grid fell from 53.6 MB in 315k allocations to 50.0 MB in 258k. It also skips unchanged committed children when it selects the drafts of a commit. -- The Loom host allocates less per op and keeps less per node. A mount op names its component with a string interned once for the process (`MountOp.component` is now `&'static str`), ops are built in place in the batch, a node's view props start from defaults without a copy and skip empty strings, the flush reuses its scratch, and the host's per-tag maps take their nodes from an arena. The host no longer keeps a separate geometry map for location reads. A 5k-cell mount makes 38% fewer allocations on the mount thread and an unmount 96% fewer, and the host keeps 1.0 MB instead of 2.7 MB for the mounted grid. The store builds the batch view it passes to store observers only when one is registered. -- Under Loom, a node's wheel event target is released on the JavaScript thread with its instance handle. -- With Loom's `"jsThread": "main"`, JavaScript tasks queued on the main thread count as pending JS work, so the test driver's `waitForIdle` waits for a promise continuation that is still queued. -- The test driver reports a Rust module promise call made in the last second and not yet settled as busy (`modules`), so `waitForIdle` after a press that opens a window waits for the window and the promise. -- `RN_GPUI_MOUNT_TRACE=1` logs, for every app-surface mount batch, when it was applied on the main thread and when the frame that shows it was presented, in wall-clock milliseconds that line up with JavaScript's `Date.now()`. The renderer benchmark reports them from the press as `appliedMs` and `presentedMs` for mount and unmount. -- `RN_GPUI_MOUNT_TRACE=1` also logs when the test driver dispatches a click or a keystroke, to measure input latency from the event. -- gpui-fast is pinned to `de5ebfa`. - -## 0.87.0-alpha.4 - 2026-11-16 - -- `DesktopWindow.focusNext()` and `focusPrevious()` move keyboard focus through the window's tab order, as Tab and Shift+Tab do. -- `hostComponents` entries take `maskChildren: true`: the component's first child masks the others, which are visible only where the mask paints, scaled by its alpha. It needs a codegen spec but no Rust code. Needs a gpui-fast with the `DestinationIn` blend mode. -- A host component can be implemented in C++. `hostComponents` entries take `cpp: true`, and a module registers a Fabric component descriptor provider and a `CppHostView` through `GpuiCppHostComponent.h`; core drives the view's props, native surface and unmount without Rust code or a codegen spec. Modules list the `extern "C"` init functions that register them in the `RN_GPUI_APP_CPP_INIT_FUNCTIONS` CMake property. -- `ViewProps` takes the `filterObjectKeys` argument of upstream React Native, so a props class that derives from it and keeps non-View props out of the View's own parsing (a Nitro View's) compiles. -- C++ modules can read and observe the window and appearance: `currentColorScheme` and `registerColorSchemeObserver` (the system's scheme or the `Appearance.setColorScheme` override), `registerWindowMetricsObserver` and `windowScale`, and `currentWindowInsets` beside `registerWindowInsetsObserver`, all declared in `GpuiModules.h`. -- On Windows with ccache and `cl.exe` on `PATH`, the C++ build uses Ninja and embeds debug info in the objects (`/Z7`, CMake policy CMP0141), so ccache can cache the MSVC build; `/MP` is only passed with the Visual Studio generator. CI restores and saves the ccache directory on Windows too. The MSVC unity batches (8 sources) stay, each batch is one cached compile under Ninja. -- `ReactGpui/Cargo.lock` and the tester's `Cargo.lock` now resolve every shared crate to the same version (both were refreshed with `cargo update`), so the Rust tests and the tester compile each dependency once. The lockfile is a prebuilt input, so the next release has a new prebuilt runtime. - -- The test driver pauses 4 ms (not 16 ms) after each frame it draws while it waits for the app to be idle, so every `waitForIdle` and click in an e2e suite is cheaper. `RN_GPUI_TEST_FRAME_MS` sets another pause. -- While no window can be drawn (none open yet, or one in the middle of an update), the test driver's idle and resize waits pause a frame between tries instead of retrying at once. The tight retry held the main thread, so the window could not open or finish its update and `waitForIdle` ran into its timeout. -- The test driver's repeated `scroll` sends delta k `k * intervalMs` after the first, whatever the frames in between take. It slept `intervalMs` after each frame, so on a slow machine the deltas came further apart and a flick lost speed. -- The test driver's `setWindowSize` returns once React has laid the window out at the new size (up to 5 s; the reply's `laidOut` says whether it did), not only once the window has it. A second resize within 50 ms of the first is held back before it reaches React, so a frame, query or screenshot read right after the call could still see the old layout. -- The sources of the C++ libraries a build needs (Boost, folly, fmt, glog, double-conversion, fast_float, nlohmann/json, curl) and the OpenSSL a source build compiles are kept in a cache shared by every build on the machine, `native-deps` next to the prebuilt runtime cache (`~/Library/Caches/react-native-gpui`, `%LOCALAPPDATA%\react-native-gpui`, `$XDG_CACHE_HOME` or `~/.cache`), instead of in each CMake build folder. A new checkout, worktree or target folder no longer downloads Boost and the rest, extracts them and compiles OpenSSL again. `RN_GPUI_NATIVE_DEPS_CACHE` sets another folder. Each archive is checked against a pinned SHA-256 and downloaded again when it differs, an interrupted download or extraction is never used, builds that run at the same time wait for each other instead of fetching or compiling twice, and the OpenSSL copy is keyed by target, build type, compiler and compiler flags. -- `RN_GPUI_APP_DATA_DIR` set to a folder replaces the per-user base folder (`~/Library/Application Support`, `%APPDATA%`, `$XDG_CONFIG_HOME` or `~/.config`) for everything the runtime keeps for the app: window state, `I18nManager` and settings files, the single-instance lock (so copies with different folders each open) and, on Linux, the window frame cache (under `cache/`). It lets several copies of an app run side by side with separate state. - -- On Windows, a source build of the runtime reconfigures CMake only when its inputs change, as on macOS and Linux. It reconfigured on every build, because it looked for a Makefile or `build.ninja` that the Visual Studio generator does not write. When the reconfigure passed different compiler flags, all of the C++ was rebuilt. -- A scroll view with `scrollEventThrottle` sends one `onScroll` per throttle period while it scrolls. When a scroll arrived after the period had passed but before the held-back event went out, both were sent within a few milliseconds of each other. -- Dragging a scroll bar thumb holds the content where the pointer is. While the button was held still, the hover check that follows each React commit was taken for a drag back to where the thumb was pressed, so the content jumped to the start and back. -- The thumb of a scroll view whose content is translucent or blurred follows the drag and is sized to the content. It read the viewport and the furthest offset from a scroll handle that such a scroll view never measures. -- A press on the scroll bar track outside the thumb scrolls a page towards the pointer, as in a browser. -- `onPointerEnter` and `onPointerLeave` reach a `Pressable` (and `TextInput` and the touchables) that has no `onHoverIn` or `onHoverOut`. Pressability returned those keys as `undefined`, and the component spread them over its own props. -- A Cargo target folder copied to another checkout (or a checkout that moved) keeps its C++ build: the build reconfigures it in place instead of deleting it ("detected home dir change, cleaning out entire build directory"), so the downloaded native dependencies stay and, with ccache, the C++ comes from the cache. -- The C++ build uses Ninja when `ninja` is on `PATH` and `CMAKE_GENERATOR` is not set, except with MSVC, which keeps the Visual Studio generator. The first build after the switch compiles the C++ again. -- With ccache, the C++ build passes `-ffile-prefix-map` for the checkout and the build folder (outside MSVC) and sets `CCACHE_BASEDIR` and `CCACHE_NOHASHDIR` unless they are configured, so the same sources hit the cache from another checkout. Debug information then names `/rn-gpui/src` and `/rn-gpui/build`; the native debugging docs show the debugger source map to set. -- React Native's FBReactNativeSpec codegen only runs when its inputs (the react-native and codegen packages, the spec files, the generator script) changed, and the build script only re-runs for files that feed the build. -- With ccache, the cxx bridge C++ (compiled on every run of the build script) also goes through ccache, unless `CXX` or a target-specific `CXX_` names a compiler or a wrapper is already set through `RUSTC_WRAPPER`. -- A build without autolink files (`desktop/autolink/autolink.json` and the rest) no longer re-runs the build script on every `cargo build`, and the build after one that compiled C++ no longer re-runs it either. - -## 0.87.0-alpha.3 - 2026-11-12 - -- A `runtime-shaders` feature on the runtime crate compiles the Metal shaders when the app starts instead of at build time, so a macOS build needs no Metal compiler. - -## 0.87.0-alpha.2 - 2026-11-12 - -- Builds against gpui-fast `3ad00a0`: on macOS, a test run's windows keep the frame they were given instead of being shrunk to a small display; on Linux, windows report themselves active while the test driver runs the app, so focus and blur reach the elements of a test window, as on macOS; on Windows, a test run's window scale factor (`RN_GPUI_TEST_SCALE_FACTOR`) applies, as on macOS and Linux, and unmaximizing a maximized window restores it; on macOS, a test run's windows open behind the user's and never activate; and accessibility names an unlabelled button, link or tab by its painted text, treats a clickable element with no role as a button, and supports hover and tooltips through the accessibility API. -- `RN_GPUI_TEST_SCALE_FACTOR` is honoured on Linux too: the runtime hands it to the X11 backend as `GPUI_X11_SCALE_FACTOR` before the platform starts, so a test run gets the same 2x display it gets on macOS. -- The test driver's `windowReveal` reports an alpha of 1 on platforms without a reveal alpha, instead of `null`. -- A native slot corrects for the offset of the window's frame (the menu bar and the frame a Linux window draws), so its React Native content is placed and hit where the slot is. -- On Linux a window's `isMaximized` reads the window manager's state, which it always reported as false. -- A mount update that changes nothing the runtime draws (no props, frame, text or host component change) no longer notifies its view. Fabric sends such updates for every ancestor of a node whose content overflows its parent, and each one rebuilt the whole screen under it on every commit. -- On Windows, showing a window that was minimized and then hidden restores it, as on macOS, instead of leaving it minimized. -- A window size held back during the resize interval is no longer stranded when the interval timer fires slightly early, as the coarse Windows clock does: the flush runs again until the interval is over. -- On Linux and Windows, where the scroll view carries a flick on itself, a wheel that reverses direction starts a new flick. Before, a scroll back within a tenth of a second of a long scroll was carried on in the direction the long scroll had gone, and the offset ran back to the start. -- The test driver's idle check waits for a window size that has not reached React yet, so a test that resizes a window and waits for idle sees the new layout. - -- The runtime builds on Linux and Windows again: the header the Rust bridge compiles no longer includes curl, whose headers only the C++ build has. -- Every module moved to react-native-gpui-modules, with its documentation, fixtures and tests: `fonts`, `fs`, `gesture-handler`, `reanimated`, `safe-area-context`, `screens`, `svg`, `vector-icons` and `worklets`, and the desktop-only `image-manipulator`, `notifications`, `pdf`, `secure-storage` (now part of `keychain`), `spellcheck`, `system`, `updater` and `webauthn`. This repository has the runtime and its tools only; the tester covers the runtime without any module. -- Escape cancels a view drag: the target gets `onDragLeave`, nothing drops and `onDragEnd` reports `dropped: false`. -- Views can be dragged to other views in the app. `draggable` views start a drag when a press moves 4 points, with `onDragStart`, `onDrag` and `onDragEnd`; `droppable` views get `onDragEnter`, `onDragOver`, `onDragLeave` and `onDrop` and take `dragOverStyle`. The drag follows the pointer out of the source. `DragDrop` (`setPayload`, `getPayload`, `getState`, `onMove`), `useDragState`, `useIsDragging`, `DragPreview` and `useDragAutoScroll` are exported from `@react-native-gpui/core/desktop`. Needs a prebuilt runtime built with the change. -- A one-line `Text` cut short with an ellipsis is as wide as the width it was given, as a block with `text-overflow: ellipsis` is, instead of as wide as the text that was left. A line is as tall as the tallest font it uses, fallback fonts such as Hiragino included, as in a browser; a color emoji font is left out, as there. -- A nested `Text` with a `backgroundColor` is painted behind its words: a rectangle over the font's content area, as a browser paints an inline span's background (a line that wraps keeps a whole-line-tall rectangle). -- While the test driver is on, windows report themselves active to the UI toolkit, so focus and blur events reach text inputs in a background run. `RN_GPUI_TEST_SCALE_FACTOR` makes a window lay out and draw at that scale whichever display it is on. Both need the gpui-fast revision that carries them. -- A background run opens its windows on the secondary display when there is one (`launchApp` passes `main` until the scale override is in the runtime), and `RN_GPUI_TEST_DISPLAY` (`main`, `secondary` or an index) chooses the display. A display that does not exist falls back to the main one with a log line. The test driver has a `displays` command. -- `Network.setDnsOverHttps()` takes a list of DNS-over-HTTPS servers. A name a server cannot resolve is asked of the next one and then of the system resolver, and `getSettings()` also reports `dnsOverHttpsServers`. -- An app launched with the argument `--hidden` opens its main window without showing it or taking focus, for an app that starts at login in the background behind a tray icon. -- Added `Network.setProxy()`, `setDnsOverHttps()`, `getSettings()` and `proxyForUrl()` to set the proxy (a proxy URL, Chromium proxy rules and a bypass list, `'direct'` or the system's) and a DNS-over-HTTPS server of the HTTP client that `fetch`, `XMLHttpRequest` and remote image and font loads share. On macOS requests follow the system proxy settings by default. WebSocket connections are not covered yet. Needs a prebuilt runtime built with the change. -- `extensions::rendering_node()` returns a `NodeHandle` for the node whose component renderer is running, and `NodeHandle::notify(cx)` builds and paints that node again. A renderer that rasterises or loads something in the background uses it to show the result when it is ready, which it could not do before: a render has no way to reach back into its node. -- `rngpui::createTurboModule(name, jsInvoker)` (in `GpuiModules.h`) makes a TurboModule the way the main runtime does, for the invoker it is given: the app's C++ provider, then the extension providers (Rust modules), then core's own. A library that runs another JavaScript runtime, such as a worker, uses it to give that runtime the app's native modules. -- On macOS the scroll bar follows the system's scroller style: with legacy scrollers (System Settings "Show scroll bars: Always", or Automatically while a mouse is connected) it is always shown on a track, and the app follows the setting as it changes. Overlay scrollers keep the auto-hide behaviour. `RN_GPUI_SCROLLER_STYLE=legacy|overlay` forces it on any platform. The bar overlays the content rather than taking layout width. Needs a prebuilt runtime built with the change. -- On macOS the scroll bar follows the system's scroller style: with legacy scrollers (System Settings "Show scroll bars: Always", or Automatically while a mouse is connected) it is always shown on a track, and the app follows the setting as it changes. Overlay scrollers keep the auto-hide behaviour. `RN_GPUI_SCROLLER_STYLE=legacy|overlay` forces it on any platform. With legacy scrollers the bar also takes 12 points (or the thickness of a `ScrollBar` child that sets one) from the scroll view's content on its scroll axis, as classic scroll bars do in AppKit and Chromium, and the layout follows the setting as it changes. Needs a prebuilt runtime built with the change. -- The scroll indicator no longer shows for a scroll the app asked for with `scrollTo` or `scrollToEnd`, which moves the content without showing the thumb, as a script's scroll does under a browser's overlay scrollbars. A sidebar scrolled to its selected item when it opened used to show a thumb until it timed out. `flashScrollIndicators()` now shows the thumb for its delay; it did nothing. Needs a prebuilt runtime built with the change. -- A React commit while the pointer rests inside the window no longer rebuilds every view. Typing in a field with the mouse over the window rebuilt the whole tree about 30 times per key: each mount batch asked for a window refresh to re-work hover, and the hover pass dispatched a synthetic mouse move that flipped GPUI's input modality from keyboard to mouse, which refreshes the window again on the next key. The hover pass now follows the pointer without a window refresh, and after keyboard input it finds the view under the pointer from the node frames, in paint order, so an absolute overlay over a row keeps the hover, instead of sending a mouse move, so the modality stays. Needs a prebuilt runtime built with the change. -- `buttons` on the pointer events is the mask of the mouse buttons actually held, as on the web: 1 left, 2 right, 4 middle, combined when several are held, and 0 when none is. A move while a button was held reported 0, so a handler that tests the held button to tell a drag from a hover saw no drag. `onPointerMove` now also fires for a move with nothing held, and a right or middle button drag reports its moves, and its release `onPointerUp`, to the view it started on; the release was not reported at all. Needs a prebuilt runtime built with the change. The window losing activation now ends every held press with `onPointerCancel` and clears the mask, as in a browser. -- `View` takes `onWheel` and `onWheelCapture`, the web's wheel event for the mouse wheel and the trackpad: `deltaX`, `deltaY` and `deltaZ` with the web's signs, `deltaMode` (pixels at full precision for a trackpad, lines for a mouse wheel), `isTrackpad`, `phase` and `momentum` for a trackpad gesture, the modifier keys, the pointer position and `timestamp`. A trackpad pinch arrives as a wheel event with `ctrlKey` and the zoom in `deltaY`, and shift with a mouse wheel gives `deltaX`, as in a browser. The event bubbles; `preventDefault()` or `stopPropagation()` keeps a parent `ScrollView` from scrolling, and a view with no wheel handler on its path scrolls at once. Events are delivered in order and none is dropped. Needs a prebuilt runtime built with the change. -- The keyboard focus ring of a focusable view follows its `borderRadius`, as Chromium's does. Needs a prebuilt runtime built with the change. -- A solid `outline` follows the view's `borderRadius`, as CSS does: the ring is rounded, with the border radius plus `outlineOffset` as its inner radius, and a corner with no radius stays square. The square ring also had a notch in each outer corner, now filled. Needs a prebuilt runtime built with the change. -- A single-line `TextInput` is as tall as a line of `Text` in the same font and size, as a browser input is: its content height is measured from its text, its placeholder or, when both are empty, its font, instead of being forced to 1.4 times the font size. An input with no `lineHeight` at 15 px is now 17.5 px of content at 2x instead of 21. A multiline input keeps its minimum height. Needs a prebuilt runtime built with the change. -- `window.visible: false` in `desktop.json` (and `DesktopAppConfig::visible(false)`) starts the main window hidden, as the `--hidden` argument does: it is created at its restored size and position, the app mounts and renders in it, and it is not shown, focused or activated until `DesktopWindow.show()`. A window that was hidden reports `isVisible: false` from the start, and is shown clear and made opaque once the frames after the show have been drawn (at most 80 ms later). Needs a prebuilt runtime built with the change, and a CLI with the new schema key. -- A press on a draggable view that is released before it moved far enough to become a drag now gives the touch its end, so a `Pressable` on a draggable view fires `onPress`. The release was dropped. -- A shortcut with no scope now takes a key from a menu accelerator on the same keys, as `docs/desktop-keyboard-shortcuts.md` orders them. The default menu's Close (`mod+w`) closed the window even when the app registered `mod+w`, because only scoped shortcuts were counted, a menu binding added later won a tie in the keymap, and with nothing focused the shortcut had no dispatch path. Needs a prebuilt runtime built with the change. -- A press now ends when the button is released outside the window, and the moves outside it reach the pressed view, as `docs/view.md` says: the root's pointer listeners only ran while the pointer was over the window, so a release outside left the gesture active and the app never became idle. Needs a prebuilt runtime built with the change. -- `RN_GPUI_TEST_DISPLAY=retina` opens a test window on the display with the highest scale factor, if it is at least 2, so a test that depends on the display's own scale does not depend on which display is main. `app.displays()` reports each display's `scaleFactor`. -- Dragging a scroll bar thumb no longer fails with "Unsupported top level event type topScrollBarDrag" when the scroll view has no `ScrollBar` child. `ScrollView`, and so `FlatList`, `SectionList` and `VirtualizedList`, take `onScrollBarDragStart`, `onScrollBarDrag` and `onScrollBarDragEnd`, which report the thumb drags with the scroll offset. The `ScrollBar` component's `onDrag*` props work as before. Needs a prebuilt runtime built with the change. -- `experimental_LayoutConformance` works on desktop: its component is registered, so a `strict` subtree gets Yoga's errata cleared. Desktop adds a Yoga errata, `FlexBasisAsIntrinsicSize`, that `strict` clears: a flex item that can grow and has a basis of zero or a percentage, as CSS gives `flex: 1`, is measured as content while its container is sized from its content, so a row item with a `flex: 1` inner row is as wide as its content instead of collapsing. The default conformance is unchanged. Copies of Yoga's `CalculateLayout.cpp`, `YGEnums` and `Errata.h` in `ReactCommonOverrides` carry it (see its README). Needs a prebuilt runtime built with the change. -- The test driver no longer scans every node after each draw for running transitions; it follows only the nodes a transition was started on, which shortens each draw by about a millisecond on a large tree. -- `XMLHttpRequest` (and so `fetch`) response headers are an object of names and values, as React Native's are: `getAllResponseHeaders()` returned `0: etag,"..."` lines, so `getResponseHeader('ETag')` was `null`. Headers a server sends more than once are joined with `, `. Needs a prebuilt runtime built with the change. -- Each instance of a native tree is in an element id scope of its own, so two components that use the same GPUI element id for their state (a `div().id("button")` in every button) no longer share it. A state update inside a native tree (a `setState` in one of its components) now sends its changes to the runtime; only the commits `NativeRoot` itself started did. Fast Refresh reaches components inside a native tree in development, with their state kept. -- A native component can tell JavaScript when the pointer enters or leaves it, and a native tree inside a React Native view is clipped by its rounded `overflow: hidden`, moved by its transforms, covered by React Native views over it and scrolled with the content around it; the tester's `mixed-matrix` test checks each, and `docs/mixed-views.md` is its support table. -- The test driver sees the instances of a native tree: `tree()` nests them under the node that shows them, `query` and the locators find them by `testID`, `text`, `role` and `label` and give them frames, and `click` and `hover` through a locator reach them. An instance with an `accessibilityRole` prop is in the accessibility tree with its `accessibilityLabel` and `testID`. The trees of nodes that are gone are dropped when a new one starts, and one shared reconciler registers with React's developer tools so Fast Refresh reaches components inside a tree. Needs a prebuilt runtime built with the change. -- `hostCounters()` of the testing client also reports `nativeOpsApplied`, `nativeApplyMicros` and `nativeRenderMicros`, for measuring native trees. One commit that changes the text of a thousand instances is a batch of 1,000 operations (44 KB of JSON), takes 3 to 5 ms in the reconciler, 0.15 ms to apply and 0.33 ms to build the elements. -- `NativeRoot` (from `@react-native-gpui/core/desktop`) renders React elements whose types name native components into a native tree with a second React reconciler (`react-reconciler` 0.33.0, with `its-fine` carrying the outer contexts in), one batch of operations per commit, handlers kept in JavaScript and called by events that name the instance, and render errors thrown again in the outer tree. Needs a prebuilt runtime built with the change. -- `NativeSlot` (from `@react-native-gpui/core/desktop`) puts React Native children inside a native tree. They are as wide as the tree's layout makes the slot and as high as their content (the components after the slot move with it), they are painted, clipped and hit where the slot is, `measure` and the test driver report their true place, and they see the contexts of the native tree as well as those of the `NativeRoot`. A `NativeRoot` can be nested in a slot. Needs a prebuilt runtime built with the change. -- `NativeSlot` takes a `fill` prop: the slot then has the height its native parent's layout gives it (a dialog, a tab, a panel of a fixed height) and its content is laid out in that, so a `ScrollView` or a list in it scrolls. Without it the slot is as high as its content and is clipped where the layout makes it shorter. -- `NativeVirtualList` (from `@react-native-gpui/core/desktop`) is a virtual list for native trees: it scrolls natively, reports the range in view, and only those items and a few more on each side exist. Items are as high as their content (native items measured by GPUI, items with a `NativeSlot` by their React Native content; unmeasured ones count as `estimatedItemHeight`), the scroll position moves with an item above the viewport that changes size so nothing jumps, and the ref has `scrollToIndex({ index, align })` (start, center or end) and `scrollToOffset`. `onEndReached` fires once when the end comes within `endReachedThreshold`. Items are keyed by `keyExtractor` and keep their React state; `recycleItems` keys them by position in the window instead, reusing their React state, for stateless rows only. Needs a prebuilt runtime built with the change. -- A native component can be reused: `NativeComponent::recyclable` and `recycle` let the tree keep the component of a removed instance in a pool of its type and hand it to the next instance of the type, so removing and creating items while scrolling does not build components. `hostCounters()` reports `nativeInstancesCreated` and `nativeInstancesRecycled`. -- Focus and keys work across the edge of a native tree. Tab and Shift+Tab move through a native tree in document order, entering and leaving the React Native content of its slots (a native tree is a tab group at the position of its `NativeRoot`, and React Native nodes inside a slot are ordered by position instead of by tag); a key the React Native content of a slot does not handle reaches the native components that contain the slot. -- A `NativeSlot` shows its content only once the content has the width the native layout gave the slot, so a slot in a popover or any freshly shown place never paints or takes presses at a wrong size. The test driver's idle check waits for slots that are still getting their width. -- An image prop of a component in a native tree takes what React Native accepts, as the view config the spec generated says it does: a `require()`d asset, a uri string, an object with `uri` or an array of sources, resolved with `Image.resolveAssetSource` before it reaches the runtime. -- The `Commands` of a spec work on a ref to a native tree instance as they do on a Fabric ref: `dispatchCommand` of the renderer proxy sends a command to the instance when the ref is one. -- A native tree instance can be sent a command: `NativeComponent::command` and the `command` operation, and the refs a `NativeRoot` gives for its instances have `command(name, ...args)`. A component that a spec generated (the same one a Fabric node runs) is registered for a native tree with `Component::::register_native_tree()`. -- Overlays work across the boundary: React Native content in a slot inside a native popover (a deferred panel) is over the other content and takes presses, and a native tree inside a React Native `Modal` takes presses. -- The test driver's `type` also types into the instances of a native tree, and the testing client has `compose(tag, steps)` to run an input method's steps (`{ mark }`, `{ commit }`) on a text input. -- `react_native_gpui::native_tree` holds native trees: instances of components created and updated by batches of operations (create, append, insert, remove, update), moved by keyed reorders, dropped with their subtrees, telling JavaScript through events that name the instance, and rendered as one GPUI element tree by the components that place their children. Needs a prebuilt runtime built with the change. -- The `rn-gpui-sys` build script tracks every C++ input: all of `ReactCxxPlatform`, the sources and include directories the app contributes (the host component glue autolink generates among them) and the headers React Native's codegen makes for the app's specs. Editing any of them is picked up by the next build; a changed host component spec configures CMake again, which fixed the link failure on `_props_*` symbols after a props-only change. -- A `measured` host component can implement `Spec::measure(props, constraint)`, which Yoga calls on the layout thread with the minimum and maximum size it offers, and `host_component::measure_text` sets text in a font under a width for it. The size is right in the first layout pass, where `set_intrinsic_size` arrives a commit later. Needs a prebuilt runtime built with the change. -- A press, release and click on a React child inside a `container` host component now also reach the component's own GPUI element, so its pressed and hover states work over its children. The press stopped at the child. Needs a prebuilt runtime built with the change. -- A host component command runs in the window of the view it was sent to, and the generated context has `window()` for it and `with_window(f)` for `create` and `update`, which run in a mount batch with no window of their own. Commands used the main window before. Needs a prebuilt runtime built with the change. -- Host components can reach GPUI's `App`: the generated context has `app()`, which returns the `App` of the mount, frame or command that called the component, for creating entities, subscribing and reading globals. Needs a prebuilt runtime built with the change. -- `register_app_init` and `register_root_wrapper` (re-exported from `react_native_gpui`) let a module run code once before the first window opens and wrap the root view of every window that hosts a React tree. Without a registration nothing changes. Needs a prebuilt runtime built with the change. -- A horizontal `ScrollView` scrolls with the wheel: the desktop view config did not pass its `horizontal` prop to the native side, so every scroll view scrolled only vertically. A sideways trackpad swipe and shift with a vertical wheel move a horizontal one; a vertical wheel alone no longer scrolls it sideways, and a sideways swipe no longer scrolls a vertical one, so a vertical scroll view inside a horizontal one routes each axis to the right view. `pagingEnabled` and the snap props work on the horizontal axis. Needs a prebuilt runtime built with the change. -- `experimental_backgroundImage` and `backgroundImage` also draw `repeating-linear-gradient()` and `repeating-radial-gradient()`: the stops from the first to the last repeat along the line or out from the centre, alone or among plain gradient layers. React Native's parser does not read them; desktop marks the layer in its view config and the renderer repeats the stops. Needs a prebuilt runtime built with the change. -- A menu drawn by the app (`ContextMenu.show` with `presentation: 'custom'`) is at most 80% of the window's height and scrolls when it has more rows than fit; the keyboard keeps the highlighted row in view and a submenu stays anchored to its row while the list is scrolled. Needs a bundle built with the change. -- Menu role `pasteWithoutFormatting` pastes the clipboard as plain text into the focused text input, with `mod+shift+v` as its accelerator. `Menu.performRole()` acts on the main window when no window is active, as when the app is in the background. Needs a prebuilt runtime built with the change. -- `App.beep()` plays the system alert sound. Needs a prebuilt runtime built with the change. -- `Tray.onClick(handler)` reports a click on the tray icon with its button and whether it is a double click. Needs a prebuilt runtime built with the change. -- `View` takes a `tooltip` string, shown after the pointer rests over the view as the web's `title` is. macOS uses the system tooltip; Windows and Linux draw one in the window for now (`RN_GPUI_TOOLTIP=drawn` forces that on macOS). It is placed with the window's zoom factor, follows a change of the text, hides on leave, press and window deactivation, and is the view's accessibility description. Needs a prebuilt runtime built with the change. -- `Menu.setDockMenu(items)` sets the menu of the Dock icon on macOS, with `onPress` per item. Needs a prebuilt runtime built with the change. -- Menu roles `zoomIn`, `zoomOut` and `resetZoom` step the focused window's zoom factor through a browser's levels and back to 100%, from the application menu or `Menu.performRole()`. Needs a prebuilt runtime built with the change. -- `App` (from `@react-native-gpui/core/desktop`): `launchArgs()`, `quit()`, `exit(code)`, `relaunch()` and `onSecondInstance(handler)`. With `singleInstance`, a second launch now shows the main window (restoring a minimized or hidden one) as well as focusing it, and its arguments reach JS. Needs a prebuilt runtime built with the change. -- Escape cancels a view drag: the target gets `onDragLeave`, nothing drops and `onDragEnd` reports `dropped: false`. -- Views can be dragged to other views in the app. `draggable` views start a drag when a press moves 4 points, with `onDragStart`, `onDrag` and `onDragEnd`; `droppable` views get `onDragEnter`, `onDragOver`, `onDragLeave` and `onDrop` and take `dragOverStyle`. The drag follows the pointer out of the source. `DragDrop` (`setPayload`, `getPayload`, `getState`, `onMove`), `useDragState`, `useIsDragging`, `DragPreview` and `useDragAutoScroll` are exported from `@react-native-gpui/core/desktop`. Needs a prebuilt runtime built with the change. -- A background test run can put a window in front of the others without activating the app or giving it focus: `RN_GPUI_TEST_ON_TOP=1` orders it front instead of behind. A window that other windows cover is occluded and macOS stops presenting its frames, so a test that reads the screen back (the compositor test of native views) saw no React view in a full run on a busy desktop. -- `Network.setDnsOverHttps()` takes a list of DNS-over-HTTPS servers. A name a server cannot resolve is asked of the next one and then of the system resolver, and `getSettings()` also reports `dnsOverHttpsServers`. -- An app launched with the argument `--hidden` opens its main window without showing it or taking focus, for an app that starts at login in the background behind a tray icon. -- Added `Network.setProxy()`, `setDnsOverHttps()`, `getSettings()` and `proxyForUrl()` to set the proxy (a proxy URL, Chromium proxy rules and a bypass list, `'direct'` or the system's) and a DNS-over-HTTPS server of the HTTP client that `fetch`, `XMLHttpRequest` and remote image and font loads share. On macOS requests follow the system proxy settings by default. WebSocket connections are not covered yet. Needs a prebuilt runtime built with the change. -- A one-line `Text` cut short with an ellipsis is as wide as the width it was given, as a block with `text-overflow: ellipsis` is, instead of as wide as the text that was left. A line is as tall as the tallest font it uses, fallback fonts such as Hiragino included, as in a browser; a color emoji font is left out, as there. -- A nested `Text` with a `backgroundColor` is painted behind its words: a rectangle over the font's content area, as a browser paints an inline span's background (a line that wraps keeps a whole-line-tall rectangle). -- While the test driver is on, windows report themselves active to the UI toolkit, so focus and blur events reach text inputs in a background run. `RN_GPUI_TEST_SCALE_FACTOR` makes a window lay out and draw at that scale whichever display it is on. Both need the gpui-fast revision that carries them. -- A background run opens its windows on the secondary display when there is one, and `RN_GPUI_TEST_DISPLAY` (`main`, `secondary` or an index) chooses the display. A display that does not exist falls back to the main one with a log line. The test driver has a `displays` command. -- Background mode: with the test driver on, or `RN_GPUI_BACKGROUND=1`, the app never activates itself, runs as an accessory application on macOS (no Dock icon or bounce, the menu bar stays the user's), opens its windows without focus and shows them behind the other windows, and `window.show()` and `window.focus()` stay behind and logical. `RN_GPUI_BACKGROUND=0` turns it off. Needs a prebuilt runtime built with the change. -- `ref.focus()` and `ref.blur()` on a `focusable` View move focus as `HTMLElement.focus()` and `blur()` do: the previously focused view loses its `focusStyle` and the new one gains it, and an `onFocus`/`onBlur` handler runs. Needs a prebuilt runtime built with the change. -- A text's height is rounded to the nearest device pixel rather than up, as Chromium snaps a block of lines: three lines of `lineHeight: 19.2` are 57.5 points tall at a scale of 2 (they were 58), two lines 38.5. -- The window options in `desktop/desktop.json` (`window.titleBar`, `trafficLightPosition`, `background`, `windowButtons`, `shadow`, `resizable`, `width`, `height`, `title` and the others, plus `accessory`) reach the app on every build instead of only when `init-desktop` regenerates `main.rs`. `DesktopAppConfig::from_env_with_defaults` applies them, and a builder call made after it still wins. Needs the CLI that records them. -- Text line boxes are rounded at the device scale, as Chromium lays text out in device pixels: a line without an explicit `lineHeight` is the ascent and descent each rounded to whole device pixels, so Inter at 13 points is 15.5 points tall at a scale of 2, not 16, and the baseline half leading is rounded down to a device pixel. Text measures already on the 1/scale grid, so Yoga's ceil no longer adds a pixel to every line. -- Text weighs what Chromium's does on macOS: glyph coverage follows Skia's luminance-dependent curve in place of Core Graphics' font smoothing. Light text on a dark background was about 7 to 10% lighter than Chromium's and regular dark text about 2% lighter; both are now within 1%, and the pixels that differ visibly fall from several percent to under one percent. Needs the gpui-fast revision that carries the change. -- A view inside a parent that has a border is painted where its layout frame puts it. It was drawn one border width up and to the left of its frame (2 points for a `borderLeftWidth` of 2), so everything inside a bordered list row was off by the border, and a press landed beside what was drawn. -- Text sits on the baseline a browser gives it: the line's ascent and descent are each rounded to whole points and the half leading is rounded down, where gpui centred the unrounded font metrics. Inter at 13 points was drawn one device pixel (half a point) higher at a scale of 2, which made most small text differ from Chromium's pixels; the glyph shapes and subpixel positions already matched. -- Clicking a view no longer focuses a `Text` or other node that only exists for accessibility: the press focuses the nearest `focusable` view. The accessibility-only focus was dropped as soon as that node was updated, which blurred the window and left a focusable ancestor's `onKeyDown` without events after a subtree had been hidden and shown again (`Activity`, react-freeze). -- A `boxShadow` blur is as wide as in CSS: its gaussian has a standard deviation of half the blur radius. The blur radius was used as the standard deviation, which made every blurred shadow twice as wide and darker at the edge. -- `hitSlop` now also extends hover and pointer moves (`onPointerEnter`, `onPointerLeave`, `onPointerMove`) and the view's `cursor`, not just presses, so a thin divider can be painted at 1 point and show `col-resize` over a wider grab area. `hoverStyle` still follows the painted box. -- A text is measured to the pixel and not rounded up to a whole point first, so its frame is Yoga's ceil to the device pixel grid (at a scale of 2 a text 39.16 points wide has a frame 39.5 wide, not 40). A line without an explicit `lineHeight` is as tall as its ascent and descent each rounded to a whole point, as in a browser: Inter at 13 and 15 points is 16 and 19 tall. -- A view that clips to its rounded corners (`borderRadius` with `overflow: 'hidden'`) now clips to the corners as drawn when it has a `transform`: the clip was left at its untransformed size and position, so a scaled view was cut to the unscaled shape. A rotation clips to the rotated view's bounding box. Needs the gpui-fast revision that carries the change. -- `RN_GPUI_DEBUG_JS_TASKS=1` makes the test driver's idle error list the JavaScript tasks that are queued or running, each with its age and the call stack that queued it. -- A one-line text with `numberOfLines` is no longer cut short with an ellipsis when it fits the box it was measured into within the pixel rounding of that box. -- A key press goes to the focused view once and bubbles through React, instead of being sent once for every focusable view on the path to it, so an `onKeyDown` on a list no longer runs two or three times per press. -- The `nativeEvent` of a press (`onPress`, the responder events) has `shiftKey`, `ctrlKey`, `altKey` and `metaKey`, as the pointer events do. -- `DesktopWindow.show()` brings back a window that was minimized, and neither it nor `hide()` logs `RefCell already borrowed` errors from GPUI's window code any more: the operating system's own window call now runs after the update that asked for it, since it reports the change while it makes it. -- State styles can change `outlineColor`, `outlineWidth` and `outlineOffset`, for example to draw a keyboard focus ring. -- A native-driven or Reanimated animation of `backgroundColor` or `color` now paints: colors that arrive as negative 32-bit integers, which is every color with a high alpha byte from Reanimated, were converted to unsigned through a double and came out transparent. -- Files dragged in from the operating system: `View` takes `acceptsFiles`, `onDragEnter`, `onDragOver`, `onDragLeave` and `onDrop` events carrying each file's path, name, size, media type and the pointer position, and a `dragOverStyle` state style. Needs a prebuilt runtime built with the change. -- Menu items take an `onPress` handler, run when the item is chosen in a context menu (`ContextMenu.show`, `ContextMenuView`) or in the application menu, alongside the id the menu already reports. -- What the pointer is over is worked out again after a mount batch, as a browser does after a layout: a view that mounts under a still pointer receives `onPointerEnter`, without the pointer moving. -- Added `DesktopWindow.setZoomFactor()` and `getZoomFactor()` to scale a window's content (0.25 to 5), `getTitle()`, and `isVisible`, `title` and `zoomFactor` in the window state. `stateChange` events now also report `isVisible`, `title` and `zoomFactor` changes. Needs a prebuilt runtime built with the change. -- Added `DesktopWindow.setBackgroundColor()` and `setChromeAppearance()` to color a window's background and give its native title bar a light or dark look. macOS only for now. -- Added state style props on every `View`: `hoverStyle`, `activeStyle`, `focusStyle`, `focusVisibleStyle`, `group`, `groupHoverStyle` and `groupActiveStyle`. A hover or press repaints in native code, without a round trip to JavaScript and without React rendering. They can change `backgroundColor`, `opacity`, `boxShadow`, border colors, `transform` and the `color` of the text inside, and a property that a native-driven animation is animating keeps its animated value. Needs a prebuilt runtime built with the change. -- Resizing a window continuously no longer crashes a large app with "Maximum update depth exceeded". `useWindowDimensions` in the main window no longer re-renders on every frame of a move or resize, `SafeAreaView` re-renders only when the title bar inset changes, a surface gets a new size at most every 50 ms during a live resize (the last size always arrives), events such as `onLayout` render at default priority instead of synchronously, and `windowResize` and `windowMove` fire only for what changed. -- LogBox is drawn above the app's portals, so it no longer overlaps an error screen the app shows in a modal. -- A view moved by a transform, such as a panel being swiped in or a sheet sliding up, draws its content correctly: clips move with the view, single-line text and icons are no longer hidden behind their own background, and the view no longer jumps for a frame while it moves. -- Builds against gpui-fast `9087620`, which is Longbridge's gpui-fast `main` merged in (upstream's public API for `ContentMask`, `Hitbox` and `paint_svg`, GPUI Kit 0.9.1), plus a rule that a character a focused text input takes is not offered to the key listeners of its ancestors, and `test-support` methods that drive the focused input handler as an input method would. A text input tracks focus on its own element so its own key handlers still see typed characters. -- Builds against gpui-fast `5392403`, which lets an automated run on macOS ask for a window scale factor (`RN_GPUI_TEST_SCALE_FACTOR`) and keeps windows active while the test driver runs the app in the background, so focus and blur work without activating the app. -- Builds against gpui-fast `3a4aada`: a view with rounded corners and overflow hidden clips its content correctly while it is scaled or moved by a transform, and text on macOS is rasterised with Skia's coverage curve instead of Core Graphics' font smoothing, so it carries the same weight as in Chromium (total ink within about 1%). -- Builds against gpui-fast `ac7018a`: content painted into a scroll layer keeps its transforms, so rows no longer stack on each other now and then, and a frame allocates far less, since retained views stop allocating placeholders and empty lists and the tab order is sorted only when focus moves by keyboard. With the allocation cuts below, scrolling a long list in a large app went from about 27.7 million allocations and 11.4 GB allocated to 13.9 million and 5.7 GB. -- A C++ TurboModule is created once per runtime and handed out again on each lookup, as on iOS and Android. Each lookup built a new instance, and a module whose instances share state lost it when an extra one was destroyed: `react-native-quick-sqlite` closed every open database that way, so an app could hang opening its database in a release build. Needs a prebuilt runtime built with the change. -- A source build (`RN_GPUI_BUILD_FROM_SOURCE=1`) of an app whose native modules include C sources, such as `react-native-quick-sqlite`'s `sqlite3.c`, no longer fails with "invalid argument '-std=c++20' not allowed with 'C'". React Native's flag list hands `-std=c++20` to every target that links one of its own; it now applies to C++ sources only. -- A list scrolled fast with the mouse wheel or the scroll bar no longer stays blank until it moves again. React Native held scroll and pointer events until its next event beat, which nothing else might tick, and a list ignored the offsets that arrived while it adjusted for rows above it changing size; events now go out at once, and the offset a wheel or scroll bar stops at is reported once more after it rests. -- An app built before the prebuilt pin changes links the newly pinned runtime instead of the previous one. CMake kept the runtime directory it found first in the build tree's cache, so the app linked the old runtime while the build log named the new one. -- Fewer allocations while drawing: a component renderer gets its node's subtree only when it reads it (`ComponentRenderer::reads_children`), mount observers get a node without its subtree, a node's pointer listeners are built once rather than on every render and registered without copying, a node without a component renderer finds its frame without snapshotting itself, and a node without a filter no longer parses one. - -## 0.87.0-alpha.1 - 2026-11-05 - -- Scrolling a list or `ScrollView` in a window the app decorates itself on Linux (a title bar with caption buttons) is composited from cached tiles again. The window is transparent for its shadow, and the scroll layer refused to cache content over a transparent window even where an opaque panel covered it, so every row was rebuilt on every frame. -- Images decode at the size they are shown and keep only their encoded bytes, so a screen of large photos no longer holds every full-size bitmap (a grid of 24 photos of 4000 x 3000 went from about 3 GB to 0.6 GB on macOS). `Image` is sized from its layout frame. -- Less GPU memory: path textures cover only the area the frame's paths need and are released when idle (about 82 MB for a 2560 x 1600 window down to 0 to 1.3 MB without large paths), instance buffers shrink after a long stretch of low use, windows on one Metal or DirectX device share their glyph atlas and compiled pipelines, and the scroll layer cache follows the window's size (16 to 64 MB). -- A rounded `overflow: 'hidden'` clip inside an effect group no longer crashes the app when the frame is replayed. -- On Windows colour glyphs (emoji) are composited on the CPU, which removes a GPU readback from rasterizing each one. -- On Linux the GPU adapter the compositor or `ZED_DEVICE_ID` names is opened first and the others are not enumerated unless it fails, which shortens startup (about 115 ms to 94 ms to the first frame on an Intel machine). -- A node the pointer came from stops being hovered when the pointer moves onto a native view (`onHoverOut` and the leave events fire). The native view took the pointer without telling the nodes under it, so the node stayed hovered. -- Reloading the app while the window resizes a surface no longer crashes. The reload thread removed the surface manager for a moment, and a resize from the UI thread in that gap (such as the title bar measuring where the menu bar goes) dereferenced it; the size is now kept and applied when the surface restarts. -- `Linking.canOpenURL` on Linux answers `true` for `http` and `https` where no default browser is registered but `$BROWSER` or `x-www-browser` is set, which is what `xdg-open` falls back to when it opens the address. -- Builds against gpui-fast `9e455ae`, which brings in longbridge/gpui-fast and zed `decd2399b1`. It needs Rust 1.98 or newer, so CI and the setup docs use 1.98.1 now. The host keeps its effect groups, colour filters and transforms. -- On Linux a window with a `'none'` title bar and a `'transparent'` or `'blurred'` background, opened with no `x` and `y`, is centred and closes when it loses focus, such as on Alt+Tab or a click elsewhere. On X11 it is kept out of the taskbar and the pager. Wayland ignores the position the app asks for, so it opened in the top-left corner on GNOME 46; the window is now drawn in the middle of a click-through window over the work area, on the monitor the compositor chooses, and `getState()` reports that window's size. -- On Wayland a click outside a tray popover goes to the window or desktop under the overlay. The overlay took it before and closed the popover with it, so the app behind needed a second click. Only the popover's own area takes input now, and the popover closes when it loses focus. -- On X11 a window with a `'none'` title bar no longer keeps the window manager's title bar when the window manager cannot leave the decorations to the app (Openbox, and any without `_GTK_FRAME_EXTENTS`). The frame is removed with the Motif hint, so a palette is frameless there, and translucent with a compositing manager. -- On X11 a window opened with `DesktopWindow.open` is placed at the position asked for, or centred, instead of wherever the window manager puts it (Openbox opened it in the top-left corner). -- On X11 a tray popover whose frame margin is given back is placed by its content, so it opens where the icon puts it and not a margin up and to the left. -- The app no longer panics at startup on a Wayland compositor that settles a window's decorations after it opens (sway). The title-bar inset changed inside the window-bounds observer and refreshed the surface while the root view was borrowed (`cannot read SurfaceRootView while it is already being updated`); the refresh now runs after the observer returns. -- Global shortcuts work on Wayland. They are bound through the desktop's `GlobalShortcuts` portal, which the user allows once, and a press arrives as the portal's `Activated` signal. They used to register through XWayland, which succeeded and never fired. `Shortcuts.onFailure` now also reports a refusal that arrives later, such as the user declining, and a desktop with no portal. The portal knows an app by an installed `.desktop` file, which the app writes into `~/.local/share/applications` when there is none. -- `DesktopWindow.open` with `alwaysOnTop` or `visibleOnAllWorkspaces` no longer rejects where the platform cannot do it. On Wayland it failed with `the session is not X11` and the window was left in a half-opened state; the window now opens and the request is skipped, with a warning in the log. -- On Linux a window with a see-through `background`, `shadow: false` or a `'none'` title bar gets no frame. The frame's shadow was painted under the window's content, so a translucent palette showed over a dark block. -- `TrayConfig::popover_anchor_name` sets the popover corner from text, which is how `tray.popoverAnchor` in `desktop.json` reaches it. -- `Tray.showPopover()`, `Tray.hidePopover()` and `Tray.togglePopover()` open and close the tray's popover from code, for example from an item of the tray's menu, and `Tray.setPopoverPosition({anchor, offset})` changes where it opens next time. -- A tray popover on Linux with Wayland opens at the end of the panel's edge instead of in the middle of the screen. The panel is found from the screen's work area, which XWayland publishes as `_NET_WORKAREA`, and the popover is drawn inside a transparent window that covers it; a press outside the popover closes it. `Tray.install` takes `popoverAnchor` and `popoverOffset` to choose the corner, and `RN_GPUI_TRAY_POPOVER_ANCHOR` and `RN_GPUI_TRAY_POPOVER_OFFSET` override them. A panel that reports the click position (KDE on a click, GNOME on a double-click) puts the popover centred on the icon, whether it reports points or device pixels, which differ at a display scale above 1. The work area is read the same way, since GNOME's XWayland reports it in device pixels and KDE's in points. On X11 the popover now also stays inside the work area. -- A tray popover on Linux is drawn with the same measured frame as other windows, rounded and with a shadow, and its content has the size you asked for: the window is grown by the frame's margin. On GNOME, where the compositor places the window, it still closes when it loses focus. -- A window with no menu bar no longer reserves room for one on Linux. A secondary window or a popover lost the menu bar's 26 points of height, and pointer positions in it were offset by them. -- On Linux the first `capabilities()` call waits until the window has reported whether the compositor gave it client-side decorations. `TitleBar` used to read the answer while the window was still opening, took the guess, and drew caption buttons next to the title bar KWin draws. The change is also sent to the app as `gpuiDesktop:windowDecorations`, and the new `useClientDecorations()` hook, exported from `@react-native-gpui/core/desktop`, follows it. -- A `TitleBar` in a window whose frame the compositor draws shows only its children as a toolbar row, with no title, caption buttons or drag area, and nothing when it has no children. -- The Linux window frame's shadow is fitted to the toolkit's measured shadow (opacity, blur, spread and downward offset) instead of one symmetric blur, and its blur no longer ends in a visible step at the edge of the margin. -- Every window except a popover draws its own frame on Linux when the compositor leaves the decorations to the app: rounded corners, a border and a shadow in a see-through margin, which goes away when the window is maximized, fullscreen or tiled. The corner radius, shadow and border are measured by rendering a window frame off-screen with GTK 4 and libadwaita, GTK 4 alone, or GTK 3, whichever is installed, in a short-lived child process, and cached until the theme, colour scheme, library versions or runtime change. `window.cornerRadius` in `desktop.json` is the radius used where nothing can be measured, `window.shadow: false` removes the shadow and margin, and `RN_GPUI_FRAME_PROBE=off` skips the measurement. -- `window.windowControlsPosition` in `desktop.json` (`"left"` or `"right"`) sets the side of the title bar the window controls use on Linux when neither the desktop's settings nor its theme say. The host config has a matching `window_controls_position` builder method. Defaults to right. -- On Linux the `TitleBar` caption buttons draw the icon theme's own `window-close-symbolic`, `window-minimize-symbolic`, `window-maximize-symbolic` and `window-restore-symbolic` icons, found through the theme and the themes it inherits, in the bar's text colour. They fall back to the drawn glyphs when no theme has them. -- On Linux the `TitleBar` caption buttons follow the desktop's button layout: the side they sit on, their order, and which of them exist. GNOME and other GTK desktops are read through `gsettings`, KDE from `kwinrc`, and anything else gets minimize, maximize and close on the right. Windows and macOS are unchanged. -- On Linux a `TitleBar` keeps a row for the in-window menu bar just under the bar, and the menu bar is drawn there in the bar's colors, instead of as a strip above the whole window. `TitleBar` takes `menuBar={false}` to keep the strip. `Menu.setMenuBarSlot` and `Menu.clearMenuBarSlot` let a custom bar do the same. -- `Menu.setMenuBarVisible` now removes the in-window menu bar on Linux. It used to resize the content and leave the bar drawn. -- The drawn menu shows accelerators as `Ctrl+Shift+Z` and no longer reads `secondary-shift-z`. -- `TitleBar` draws small round caption buttons on Linux, in place of the full-height rectangles of Windows with a red close button. -- A popover tray's built-in Open item opens the popover. GNOME's panel shows the menu on a single click and reports only a double click, so the popover could not be reached from the menu. -- A tray with no icon and an app with no icon now shows a filled round glyph on Windows and Linux, which can be seen on a dark panel. It used to be a black outline that was hardly visible. -- The title bar's minimize, maximize and close buttons now act on Linux. A press on the button's glyph used to be taken by a plain view inside it, and the button's own pointer position was measured against its parent. -- `alwaysOnTop` keeps a window above others on X11, as `_NET_WM_STATE_ABOVE`. It used to raise the window once. -- `visibleOnAllWorkspaces` and `setVisibleOnAllWorkspaces` are ignored on Windows and Linux instead of failing, so a window opened with them still opens without an error. -- Fixed the Windows build failing with C2084 when two libraries in an app define the same file-local function, such as `react-native-screens` with `react-native-safe-area-context`. -- `DesktopAppConfig::accessory` runs the app with no Dock icon on macOS, which lets its windows show over another app's full-screen Space. -- A shortcut with `global: true` fires while no window of the app has focus, on macOS, Windows and X11. `Shortcuts.onFailure` reports keys the system refused. -- `visibleOnAllWorkspaces` shows a window on every Space on macOS, over full-screen apps when it is also `alwaysOnTop`, as an option of `DesktopWindow.open` and as `setVisibleOnAllWorkspaces`. -- A press on the empty part of a `pointerEvents="box-none"` view now reaches the view behind it, as in React Native, instead of stopping at the nearest ancestor. -- The keyboard focus ring is no longer drawn around a `TextInput`, or around a view that sets its own outline. -- `titleBar: 'none'` removes all system chrome: on macOS a borderless window with no border line or system corners. -- Fixed an empty `TextInput` drawing its placeholder at a different size than typed text and its caret in the wrong color, which flickered when the text was cleared. -- Windows take `windowButtons` and `shadow` options to hide the macOS traffic lights and the system shadow. -- Windows can be `transparent`, `blurred` or `mica` with the `background` window option, in `desktop.json` and in `DesktopWindow.open`. -- `StatusBar` renders nothing and its methods do nothing on desktop, so the default React Native app no longer fails on a missing native module. -- `ScrollBar` styles the scrollbar of the nearest `ScrollView`, including a list's: thickness, colors, radius, margin, visibility, auto-hide, and drag events. It needs a new prebuilt runtime. -- The scroll indicator can be dragged, and appears when the pointer reaches the edge of a scrollable view. -- The prebuilt runtime download reports its progress and where it was installed. -- Fixed a view with a `borderWidth` and a `borderRadius` drawing a square border over its rounded background, as on the `NewAppScreen` cards. -- Fixed a scroll view jumping up when a press re-rendered it after a trackpad flick had carried it past the end. - -## 0.87.0-alpha.0 - 2026-11-01 - -- First release of the React Native desktop platform for macOS, Windows and Linux, for React Native 0.87. -- One GPU-accelerated renderer (GPUI) draws the core components on every platform, through Fabric and Yoga. -- Desktop APIs: multiple windows, application and context menus, a tray icon, keyboard shortcuts, deep links and single-instance apps. -- Accessibility tree for VoiceOver, Narrator and Orca; VoiceOver on macOS is the validated path. -- `Intl` on the system ICU. -- Uses the prebuilt C++ runtime 0.0.6, downloaded on the first build; set `prebuilt: 'never'` to build it from source. diff --git a/vendor/react-native-gpui/packages/core/LICENSE b/vendor/react-native-gpui/packages/core/LICENSE deleted file mode 100644 index 149a0f8321..0000000000 --- a/vendor/react-native-gpui/packages/core/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Streetwriters - -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/vendor/react-native-gpui/packages/core/README.md b/vendor/react-native-gpui/packages/core/README.md deleted file mode 100644 index ad816baf14..0000000000 --- a/vendor/react-native-gpui/packages/core/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# @react-native-gpui/core - -React Native for macOS, Windows and Linux. One GPU-accelerated renderer, [GPUI](https://github.com/zed-industries/zed/tree/main/crates/gpui), draws your app on every desktop, through React Native's Fabric renderer and Yoga layout. - -Part of [react-native-gpui](https://github.com/streetwriters/react-native-gpui), React Native for macOS, Windows and Linux. - -## Get started - -Create an app: - -```sh -npx @react-native-gpui/cli init MyApp -cd MyApp -npx react-native run-desktop -``` - -Or add a desktop target to an existing React Native app: - -```sh -npx react-native init-desktop -``` - -The first build downloads a prebuilt copy of React Native's C++ runtime, so only your app is compiled. - -## What you get - -- The core components and APIs, rendered on the GPU. -- Desktop APIs: windows, application and context menus, a tray icon, keyboard shortcuts, deep links and single-instance apps. -- An accessibility tree for VoiceOver, Narrator and Orca. -- Native modules in Rust or C++, native views, and Node-API addons. -- Packaging to `.app`/`.dmg`, an NSIS installer, and `.deb`/`.AppImage`. - -## Documentation - -[Getting started](https://streetwriters.github.io/react-native-gpui/docs/getting-started) - -## License - -MIT. See [LICENSE](LICENSE). diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides.loom/react/nativemodule/dom/NativeDOM.cpp b/vendor/react-native-gpui/packages/core/ReactCommonOverrides.loom/react/nativemodule/dom/NativeDOM.cpp deleted file mode 100644 index b29482cf9f..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides.loom/react/nativemodule/dom/NativeDOM.cpp +++ /dev/null @@ -1,547 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include -#include -#include -#include -#include -#include - -#if LOOM_RENDERER -#include -#endif - -#ifdef RN_DISABLE_OSS_PLUGIN_HEADER -#include "Plugins.h" -#endif - -#if LOOM_RENDERER -namespace facebook::react { -namespace { -class LoomNativeDOM final : public TurboModule { - public: - explicit LoomNativeDOM(std::shared_ptr jsInvoker) - : TurboModule("NativeDOMCxx", std::move(jsInvoker)) {} - - jsi::Value get(jsi::Runtime& rt, const jsi::PropNameID& name) override { - const auto method = name.utf8(rt); - const auto argCount = - method == "measureLayout" - ? 4 - : (method == "compareDocumentPosition" || - method == "getBoundingClientRect" || - method == "getElementById" || method == "linkRootNode" || - method == "measure" || method == "measureInWindow" || - method == "setNativeProps" || method == "hasPointerCapture" || - method == "setPointerCapture" || method == "releasePointerCapture" - ? 2 - : 1); - return jsi::Function::createFromHostFunction( - rt, - name, - argCount, - [method]( - jsi::Runtime& runtime, - const jsi::Value&, - const jsi::Value* arguments, - size_t count) -> jsi::Value { - auto binding = UIManagerBinding::getBinding(runtime); - auto* direct = dynamic_cast(binding.get()); - if (direct == nullptr) { - throw jsi::JSError( - runtime, - "NativeDOMCxx direct node references require LOOM_RENDERER"); - } - return direct->getDirectDOM(runtime, method, arguments, count); - }); - } -}; -} // namespace -} // namespace facebook::react -#endif - -std::shared_ptr -facebook::react::NativeDOMModuleProvider( - std::shared_ptr jsInvoker) { -#if LOOM_RENDERER - return std::make_shared( - std::move(jsInvoker)); -#else - return std::make_shared(std::move(jsInvoker)); -#endif -} - -// React Native defines this in the global namespace; keep that exported symbol as well -// (libraries and the default TurboModule provider link against it). -std::shared_ptr NativeDOMModuleProvider( - std::shared_ptr jsInvoker) { - return facebook::react::NativeDOMModuleProvider(std::move(jsInvoker)); -} - -namespace facebook::react { - -namespace { -inline std::shared_ptr getShadowNode( - facebook::jsi::Runtime& runtime, - jsi::Value& shadowNodeValue) { - return Bridging>::fromJs( - runtime, shadowNodeValue); -} - -#pragma mark - Private helpers - -UIManager& getUIManagerFromRuntime(facebook::jsi::Runtime& runtime) { - return UIManagerBinding::getBinding(runtime)->getUIManager(); -} - -RootShadowNode::Shared getCurrentShadowTreeRevision( - facebook::jsi::Runtime& runtime, - SurfaceId surfaceId) { - auto shadowTreeRevisionProvider = - getUIManagerFromRuntime(runtime).getShadowTreeRevisionProvider(); - return shadowTreeRevisionProvider->getCurrentRevision(surfaceId); -} - -RootShadowNode::Shared getCurrentShadowTreeRevision( - facebook::jsi::Runtime& runtime, - jsi::Value& nativeNodeReference) { - if (nativeNodeReference.isNumber()) { - return getCurrentShadowTreeRevision( - runtime, static_cast(nativeNodeReference.asNumber())); - } - - return getCurrentShadowTreeRevision( - runtime, getShadowNode(runtime, nativeNodeReference)->getSurfaceId()); -} - -facebook::react::PointerEventsProcessor& getPointerEventsProcessorFromRuntime( - facebook::jsi::Runtime& runtime) { - return facebook::react::UIManagerBinding::getBinding(runtime) - ->getPointerEventsProcessor(); -} - -std::vector getArrayOfInstanceHandlesFromShadowNodes( - const std::vector>& nodes, - facebook::jsi::Runtime& runtime) { - // JSI doesn't support adding elements to an array after creation, - // so we need to accumulate the values in a vector and then create - // the array when we know the size. - std::vector nonNullInstanceHandles; - nonNullInstanceHandles.reserve(nodes.size()); - for (const auto& shadowNode : nodes) { - auto instanceHandle = (*shadowNode).getInstanceHandle(runtime); - if (!instanceHandle.isNull()) { - nonNullInstanceHandles.push_back(std::move(instanceHandle)); - } - } - - return nonNullInstanceHandles; -} - -bool isRootShadowNode(const ShadowNode& shadowNode) { - return shadowNode.getTraits().check(ShadowNodeTraits::Trait::RootNodeKind); -} - -} // namespace - -#pragma mark - NativeDOM - -NativeDOM::NativeDOM(std::shared_ptr jsInvoker) - : NativeDOMCxxSpec(std::move(jsInvoker)) {} - -#pragma mark - Methods from the Node interface (for ReadOnlyNode). - -double NativeDOM::compareDocumentPosition( - jsi::Runtime& rt, - jsi::Value nativeNodeReference, - jsi::Value otherNativeNodeReference) { - auto currentRevision = getCurrentShadowTreeRevision(rt, nativeNodeReference); - if (currentRevision == nullptr) { - return dom::DOCUMENT_POSITION_DISCONNECTED; - } - - std::shared_ptr shadowNode; - std::shared_ptr otherShadowNode; - - // Check if document references are used - if (nativeNodeReference.isNumber() || otherNativeNodeReference.isNumber()) { - if (nativeNodeReference.isNumber() && otherNativeNodeReference.isNumber()) { - // Both are documents (and equality is handled in JS directly). - return dom::DOCUMENT_POSITION_DISCONNECTED; - } else if (nativeNodeReference.isNumber()) { - // Only the first is a document - auto surfaceId = nativeNodeReference.asNumber(); - shadowNode = currentRevision; - otherShadowNode = getShadowNode(rt, otherNativeNodeReference); - - if (isRootShadowNode(*otherShadowNode)) { - // If the other is a root node, we just need to check if it is its - // `documentElement` - return (surfaceId == otherShadowNode->getSurfaceId()) - ? dom::DOCUMENT_POSITION_CONTAINED_BY | - dom::DOCUMENT_POSITION_FOLLOWING - : dom::DOCUMENT_POSITION_DISCONNECTED; - } else { - // Otherwise, we'll use the root node to represent the document - // (the result should be the same) - } - } else { - // Only the second is a document - auto otherSurfaceId = otherNativeNodeReference.asNumber(); - shadowNode = getShadowNode(rt, nativeNodeReference); - otherShadowNode = getCurrentShadowTreeRevision(rt, otherSurfaceId); - - if (isRootShadowNode(*shadowNode)) { - // If this is a root node, we just need to check if the other is its - // document. - return (otherSurfaceId == shadowNode->getSurfaceId()) - ? dom::DOCUMENT_POSITION_CONTAINS | dom::DOCUMENT_POSITION_PRECEDING - : dom::DOCUMENT_POSITION_DISCONNECTED; - } else { - // Otherwise, we'll use the root node to represent the document - // (the result should be the same) - } - } - } else { - shadowNode = getShadowNode(rt, nativeNodeReference); - otherShadowNode = getShadowNode(rt, otherNativeNodeReference); - } - - return dom::compareDocumentPosition( - currentRevision, *shadowNode, *otherShadowNode); -} - -std::vector NativeDOM::getChildNodes( - jsi::Runtime& rt, - jsi::Value nativeNodeReference) { - auto currentRevision = getCurrentShadowTreeRevision(rt, nativeNodeReference); - if (currentRevision == nullptr) { - return std::vector{}; - } - - // The only child node of the document is the root node. - if (nativeNodeReference.isNumber()) { - return getArrayOfInstanceHandlesFromShadowNodes({currentRevision}, rt); - } - - auto childNodes = dom::getChildNodes( - currentRevision, *getShadowNode(rt, nativeNodeReference)); - return getArrayOfInstanceHandlesFromShadowNodes(childNodes, rt); -} - -jsi::Value NativeDOM::getElementById( - jsi::Runtime& rt, - SurfaceId surfaceId, - const std::string& id) { - auto currentRevision = getCurrentShadowTreeRevision(rt, surfaceId); - if (currentRevision == nullptr) { - return jsi::Value::undefined(); - } - - auto elementById = dom::getElementById(currentRevision, id); - if (elementById == nullptr) { - return jsi::Value::undefined(); - } - - return elementById->getInstanceHandle(rt); -} - -jsi::Value NativeDOM::getParentNode( - jsi::Runtime& rt, - jsi::Value nativeNodeReference) { - // The document does not have a parent node. - if (nativeNodeReference.isNumber()) { - return jsi::Value::undefined(); - } - - auto shadowNode = getShadowNode(rt, nativeNodeReference); - - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return jsi::Value::undefined(); - } - - // The parent of the surface's root node is the document. Only the actual - // root node qualifies: nested nodes that carry the `RootNodeKind` trait - // (e.g. , portals/overlays) still have a real parent in the shadow - // tree and must report it. Otherwise capture/bubble event propagation is - // silently severed at that boundary (a listener on an ancestor rendered - // above the modal would never receive descendant focus/blur, etc.). - if (ShadowNode::sameFamily(*currentRevision, *shadowNode)) { - return jsi::Value{shadowNode->getSurfaceId()}; - } - - auto parentShadowNode = dom::getParentNode(currentRevision, *shadowNode); - if (parentShadowNode == nullptr) { - return jsi::Value::undefined(); - } - - return parentShadowNode->getInstanceHandle(rt); -} - -bool NativeDOM::isConnected(jsi::Runtime& rt, jsi::Value nativeNodeReference) { - auto currentRevision = getCurrentShadowTreeRevision(rt, nativeNodeReference); - if (currentRevision == nullptr) { - return false; - } - - // The document is connected because we got a value for current revision. - if (nativeNodeReference.isNumber()) { - return true; - } - - auto shadowNode = getShadowNode(rt, nativeNodeReference); - return dom::isConnected(currentRevision, *shadowNode); -} - -#pragma mark - Methods from the Element interface (for ReactNativeElement). - -std::tuple< - /* topWidth: */ int, - /* rightWidth: */ int, - /* bottomWidth: */ int, - /* leftWidth: */ int> -NativeDOM::getBorderWidth( - jsi::Runtime& rt, - std::shared_ptr shadowNode) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return {0, 0, 0, 0}; - } - - auto borderWidth = dom::getBorderWidth(currentRevision, *shadowNode); - return std::tuple{ - borderWidth.top, borderWidth.right, borderWidth.bottom, borderWidth.left}; -} - -std::tuple< - /* x: */ double, - /* y: */ double, - /* width: */ double, - /* height: */ double> -NativeDOM::getBoundingClientRect( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - bool includeTransform) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return {0, 0, 0, 0}; - } - - auto domRect = dom::getBoundingClientRect( - currentRevision, *shadowNode, includeTransform); - - return std::tuple{domRect.x, domRect.y, domRect.width, domRect.height}; -} - -std::tuple NativeDOM::getInnerSize( - jsi::Runtime& rt, - std::shared_ptr shadowNode) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return {0, 0}; - } - - auto innerSize = dom::getInnerSize(currentRevision, *shadowNode); - return std::tuple{innerSize.width, innerSize.height}; -} - -std::tuple -NativeDOM::getScrollPosition( - jsi::Runtime& rt, - std::shared_ptr shadowNode) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return {0, 0}; - } - - auto domPoint = dom::getScrollPosition(currentRevision, *shadowNode); - return std::tuple{domPoint.x, domPoint.y}; -} - -std::tuple -NativeDOM::getScrollSize( - jsi::Runtime& rt, - std::shared_ptr shadowNode) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return {0, 0}; - } - - auto scrollSize = dom::getScrollSize(currentRevision, *shadowNode); - return std::tuple{scrollSize.width, scrollSize.height}; -} - -std::string NativeDOM::getTagName( - jsi::Runtime& /*rt*/, - std::shared_ptr shadowNode) { - return dom::getTagName(*shadowNode); -} - -std::string NativeDOM::getTextContent( - jsi::Runtime& rt, - std::shared_ptr shadowNode) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return ""; - } - - return dom::getTextContent(currentRevision, *shadowNode); -} - -bool NativeDOM::hasPointerCapture( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - double pointerId) { - bool isCapturing = getPointerEventsProcessorFromRuntime(rt).hasPointerCapture( - static_cast(pointerId), shadowNode.get()); - return isCapturing; -} - -void NativeDOM::releasePointerCapture( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - double pointerId) { - getPointerEventsProcessorFromRuntime(rt).releasePointerCapture( - static_cast(pointerId), shadowNode.get()); -} - -void NativeDOM::setPointerCapture( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - double pointerId) { - getPointerEventsProcessorFromRuntime(rt).setPointerCapture( - static_cast(pointerId), shadowNode); -} - -#pragma mark - Methods from the HTMLElement interface (for ReactNativeElement). - -std::tuple< - /* offsetParent: */ jsi::Value, - /* top: */ double, - /* left: */ double> -NativeDOM::getOffset( - jsi::Runtime& rt, - std::shared_ptr shadowNode) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return {jsi::Value::undefined(), 0, 0}; - } - - auto domOffset = dom::getOffset(currentRevision, *shadowNode); - - return std::tuple{ - domOffset.offsetParent == nullptr - ? jsi::Value::undefined() - : domOffset.offsetParent->getInstanceHandle(rt), - domOffset.top, - domOffset.left}; -} - -#pragma mark - Special methods to handle the root node. - -jsi::Value NativeDOM::linkRootNode( - jsi::Runtime& rt, - SurfaceId surfaceId, - jsi::Value instanceHandle) { - auto currentRevision = getCurrentShadowTreeRevision(rt, surfaceId); - if (currentRevision == nullptr) { - return jsi::Value::undefined(); - } - - auto instanceHandleWrapper = - std::make_shared(rt, instanceHandle, surfaceId); - currentRevision->setInstanceHandle(instanceHandleWrapper); - - return Bridging>::toJs(rt, currentRevision); -} - -#pragma mark - Legacy layout APIs (for ReactNativeElement). - -void NativeDOM::measure( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - const MeasureOnSuccessCallback& callback) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - callback(0, 0, 0, 0, 0, 0); - return; - } - - auto measureRect = dom::measure(currentRevision, *shadowNode); - - callback( - measureRect.x, - measureRect.y, - measureRect.width, - measureRect.height, - measureRect.pageX, - measureRect.pageY); -} - -void NativeDOM::measureInWindow( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - const MeasureInWindowOnSuccessCallback& callback) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - callback(0, 0, 0, 0); - return; - } - - auto rect = dom::measureInWindow(currentRevision, *shadowNode); - callback(rect.x, rect.y, rect.width, rect.height); -} - -void NativeDOM::measureLayout( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - std::shared_ptr relativeToShadowNode, - jsi::Function onFail, - const MeasureLayoutOnSuccessCallback& onSuccess) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - onFail.call(rt); - return; - } - - auto maybeRect = - dom::measureLayout(currentRevision, *shadowNode, *relativeToShadowNode); - - if (!maybeRect) { - onFail.call(rt); - return; - } - - auto rect = maybeRect.value(); - - onSuccess(rect.x, rect.y, rect.width, rect.height); -} - -#pragma mark - Legacy direct manipulation APIs (for ReactNativeElement). - -void NativeDOM::setNativeProps( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - jsi::Value updatePayload) { - getUIManagerFromRuntime(rt).setNativeProps_DEPRECATED( - shadowNode, RawProps(rt, updatePayload)); -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides.loom/react/nativemodule/dom/NativeDOM.h b/vendor/react-native-gpui/packages/core/ReactCommonOverrides.loom/react/nativemodule/dom/NativeDOM.h deleted file mode 100644 index cdb8fbf64e..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides.loom/react/nativemodule/dom/NativeDOM.h +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include - -#if __has_include("FBReactNativeSpecJSI.h") // CocoaPod headers on Apple -#include "FBReactNativeSpecJSI.h" -#else -#include -#endif - -#include -#include -#include - -namespace facebook::react { - -using MeasureOnSuccessCallback = SyncCallback; - -using MeasureInWindowOnSuccessCallback = SyncCallback; - -using MeasureLayoutOnSuccessCallback = SyncCallback; - -class NativeDOM : public NativeDOMCxxSpec { - public: - NativeDOM(std::shared_ptr jsInvoker); - -#pragma mark - Methods from the Node interface (for ReadOnlyNode). - - double compareDocumentPosition(jsi::Runtime &rt, jsi::Value nativeNodeReference, jsi::Value otherNativeNodeReference); - - std::vector getChildNodes(jsi::Runtime &rt, jsi::Value nativeNodeReference); - - jsi::Value getElementById(jsi::Runtime &rt, SurfaceId surfaceId, const std::string &id); - - jsi::Value getParentNode(jsi::Runtime &rt, jsi::Value nativeNodeReference); - - bool isConnected(jsi::Runtime &rt, jsi::Value nativeNodeReference); - -#pragma mark - Methods from the Element interface (for ReactNativeElement). - - std::tuple< - /* topWidth: */ int, - /* rightWidth: */ int, - /* bottomWidth: */ int, - /* leftWidth: */ int> getBorderWidth(jsi::Runtime &rt, std::shared_ptr shadowNode); - - std::tuple< - /* x: */ double, - /* y: */ double, - /* width: */ double, - /* height: */ double> - getBoundingClientRect(jsi::Runtime &rt, std::shared_ptr shadowNode, bool includeTransform); - - std::tuple getInnerSize( - jsi::Runtime &rt, - std::shared_ptr shadowNode); - - std::tuple getScrollPosition( - jsi::Runtime &rt, - std::shared_ptr shadowNode); - - std::tuple getScrollSize( - jsi::Runtime &rt, - std::shared_ptr shadowNode); - - std::string getTagName(jsi::Runtime &rt, std::shared_ptr shadowNode); - - std::string getTextContent(jsi::Runtime &rt, std::shared_ptr shadowNode); - - bool hasPointerCapture(jsi::Runtime &rt, std::shared_ptr shadowNode, double pointerId); - - void releasePointerCapture(jsi::Runtime &rt, std::shared_ptr shadowNode, double pointerId); - - void setPointerCapture(jsi::Runtime &rt, std::shared_ptr shadowNode, double pointerId); - -#pragma mark - Methods from the HTMLElement interface (for ReactNativeElement). - - std::tuple< - /* offsetParent: */ jsi::Value, - /* top: */ double, - /* left: */ double> getOffset(jsi::Runtime &rt, std::shared_ptr shadowNode); - -#pragma mark - Special methods to handle the root node. - - jsi::Value linkRootNode(jsi::Runtime &rt, SurfaceId surfaceId, jsi::Value instanceHandle); - -#pragma mark - Legacy layout APIs (for ReactNativeElement). - - void - measure(jsi::Runtime &rt, std::shared_ptr shadowNode, const MeasureOnSuccessCallback &callback); - - void measureInWindow( - jsi::Runtime &rt, - std::shared_ptr shadowNode, - const MeasureInWindowOnSuccessCallback &callback); - - void measureLayout( - jsi::Runtime &rt, - std::shared_ptr shadowNode, - std::shared_ptr relativeToShadowNode, - jsi::Function onFail, - const MeasureLayoutOnSuccessCallback &onSuccess); - -#pragma mark - Legacy direct manipulation APIs (for ReactNativeElement). - - void setNativeProps(jsi::Runtime &rt, std::shared_ptr shadowNode, jsi::Value updatePayload); -}; - -// The UI-thread renderer supplies a node-reference implementation because its -// direct nodes are not ShadowNode instances. The default provider selects the -// matching implementation for the build flag. -std::shared_ptr NativeDOMModuleProvider( - std::shared_ptr jsInvoker); - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides.loom/unistd.h b/vendor/react-native-gpui/packages/core/ReactCommonOverrides.loom/unistd.h deleted file mode 100644 index 9b5e1269a7..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides.loom/unistd.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -// Loom's LoomBindingInternals.h includes and calls nothing from it. -// MSVC has no such header; every other toolchain gets the real one. -#if defined(_MSC_VER) -#include -#include -#else -#include_next -#endif diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/README.md b/vendor/react-native-gpui/packages/core/ReactCommonOverrides/README.md deleted file mode 100644 index 9d2159329b..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# ReactCommonOverrides - -Copies of React Native sources that react-native-gpui compiles in place of the upstream file, or headers that shadow the upstream ones on the include path. Each one is tracked in `../overrides.json` with the hash of the upstream file it came from, so `react-native-platform-override validate` reports drift when React Native is upgraded. To re-apply a change after an upgrade, diff the new upstream file against the copy and carry the hunks over. - -The overrides are hashed into the prebuilt archive (`scripts/prebuilt-inputs.mjs`). Changing one makes a prebuilt built from other overrides stale, and the prebuilt has to be rebuilt. - -## Yoga: the `FlexBasisAsIntrinsicSize` errata - -Copied from React Native 0.87.1, `packages/react-native/ReactCommon/yoga/yoga`: - -| File | Change | -| --- | --- | -| `yoga/enums/Errata.h` | `FlexBasisAsIntrinsicSize = YGErrataFlexBasisAsIntrinsicSize` | -| `yoga/YGEnums.h` | `YGErrataFlexBasisAsIntrinsicSize = 16` in `YGErrata`. `YGErrataAll` and `YGErrataClassic` include it. | -| `yoga/YGEnums.cpp` | `YGErrataToString` returns `flex-basis-as-intrinsic-size` for it. | -| `yoga/algorithm/CalculateLayout.cpp` | In `computeFlexBasisForChild`, after `useResolvedFlexBasis` is computed: when the child does not have the errata, its main sizing mode is not `StretchFit`, `resolveFlexGrow() > 0`, and its basis is a percentage or resolves to 0, `useResolvedFlexBasis` is set to false so the child is measured for content. The computed basis is also recomputed on every call for a child without the errata, so the final layout uses the basis again. | - -With the errata set, which is the default (`YGErrataAll`) and what `classic` conformance gives, the code path is the upstream one. It is cleared in a `strict` `LayoutConformance` subtree, where `resolveErrata` returns only `MinSizeUndefinedInsteadOfAuto`. - -`yoga/algorithm/CalculateLayout.cpp` and `yoga/YGEnums.cpp` replace the upstream sources of the `yogacore` target in `ReactGpui/rn-gpui-sys/cpp/CMakeLists.txt`. The headers shadow the upstream ones on the include path. - -`ReactGpui/rn-gpui-sys/cpp/GpuiMountingManager.cpp` registers `LayoutConformanceComponentDescriptor`, so `experimental_LayoutConformance` creates a node on desktop. - -## Loom variants - -`../ReactCommonOverrides.loom` holds the replacements of files that Loom also replaces. A Loom build compiles those and puts that directory first on the include path. `NativeDOM.cpp` and `NativeDOM.h` are Loom's files with the same two changes as the copies above (no backticks in `#pragma mark`, the header included through the override include path). Each entry in `../overrides.json` names the Loom file it came from and its hash (`loomBaseHash`); see `../ReactGpui/LOOM_PIN.md`. diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/devsupport/DevServerHelper.cpp b/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/devsupport/DevServerHelper.cpp deleted file mode 100644 index b234dae95e..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/devsupport/DevServerHelper.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -// Override: resolved from the include root, because this copy is -// compiled from ReactCommonOverrides/ rather than next to the header. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -// Override: the cxx platform hardcodes the -// Android bundle identifier, which makes Metro serve the Android JS surface. -constexpr std::string_view DEFAULT_PLATFORM = "desktop"; - -std::string SHA256(const std::string& input) { - std::array hash{}; - SHA256_CTX sha256; - SHA256_Init(&sha256); - SHA256_Update(&sha256, input.c_str(), input.size()); - SHA256_Final(hash.data(), &sha256); - std::stringstream ss; - for (unsigned char i : hash) { - ss << std::hex << std::setw(2) << std::setfill('0') << (int)i; - } - return ss.str(); -} - -std::string urlEscape(const std::string& str) { - std::regex pattern("[^a-zA-Z0-9._~-]"); - return std::regex_replace(str, pattern, ""); -} - -} // namespace - -namespace facebook::react { - -DevServerHelper::DevServerHelper( - std::string appId, - std::string deviceName, - std::string devServerHost, - uint32_t devServerPort, - const HttpClientFactory& httpClientFactory, - JavaScriptModuleCallback javaScriptModuleCallback) noexcept - : appId_(std::move(appId)), - deviceName_(std::move(deviceName)), - devServerHost_(std::move(devServerHost)), - devServerPort_(devServerPort), - httpClient_(httpClientFactory()), - javaScriptModuleCallback_(std::move(javaScriptModuleCallback)) { - deviceId_ = SHA256(fmt::format("{}-{}", deviceName_, appId_)); -} - -std::future DevServerHelper::downloadBundleResourceSync( - const std::string& jsBundleUrl, - DownloadProgressCallback&& downloadProgressCallback) { - auto promise = std::make_shared>(); - // What the server said about the response, and whether the promise has been - // settled: a body that is not a bundle must reject it, and a response that - // completes without a body must not leave the caller waiting forever. - struct ResponseState { - uint16_t status{0}; - std::string contentType; - std::atomic settled{false}; - }; - auto state = std::make_shared(); - auto reject = [promise, state](const std::string& message) { - if (state->settled.exchange(true)) { - return; - } - LOG(WARNING) << message; - try { - throw std::runtime_error(message); - } catch (...) { - try { - promise->set_exception(std::current_exception()); - } catch (...) { - } - } - }; - http::NetworkCallbacks callbacks{ - .onResponse = - [state]( - uint16_t responseCode, - http::Headers headers, - const std::string& /*responseUrl*/) { - state->status = responseCode; - for (auto& [name, value] : headers) { - std::string lower = name; - std::transform( - lower.begin(), lower.end(), lower.begin(), [](char c) { - return static_cast(std::tolower(c)); - }); - if (lower == "content-type") { - state->contentType = value; - } - } - }, - .onBody = - [jsBundleUrl, promise, state, reject]( - std::unique_ptr ioBuf) { - std::string responseStr = ioBuf->moveToFbString().toStdString(); - // Something other than Metro may be listening on this port (another - // project's Metro, for example), and Metro itself answers a failed - // build with a JSON error. Either way the body is not a bundle, and - // handing it to the engine fails with a syntax error and a blank - // window. Reject it, so ReactHost falls back to the built-in bundle. - const bool okStatus = state->status == 0 || - (state->status >= 200 && state->status < 300); - const bool javascriptType = state->contentType.empty() || - state->contentType.find("javascript") != std::string::npos; - const auto first = responseStr.find_first_not_of(" \t\r\n"); - const bool looksLikeData = first != std::string::npos && - (responseStr[first] == '{' || responseStr[first] == '<'); - if (!okStatus || !javascriptType || looksLikeData) { - reject(fmt::format( - "The dev server at {} did not return a JS bundle (status {}, " - "content type '{}'): {}", - jsBundleUrl, - state->status, - state->contentType, - responseStr.substr(0, 300))); - return; - } - if (!state->settled.exchange(true)) { - promise->set_value(std::move(responseStr)); - } - }, - .onResponseComplete = - [jsBundleUrl, promise, state, reject, downloadProgressCallback]( - const std::string& error, bool timeoutError) { - if (error.empty() && !timeoutError && !state->settled.load()) { - if (downloadProgressCallback) { - downloadProgressCallback(DownloadProgressStatus::FAILED); - } - reject( - "The dev server at " + jsBundleUrl + - " returned an empty response"); - return; - } - if (!error.empty() || timeoutError) { - if (downloadProgressCallback) { - downloadProgressCallback(DownloadProgressStatus::FAILED); - } - reject( - "Failed to download JS bundle from Url: " + jsBundleUrl + - ". Error: " + (error.empty() ? "Timeout" : error)); - } else if (downloadProgressCallback) { - downloadProgressCallback(DownloadProgressStatus::FINISHED); - } - }}; - httpClient_->sendRequest(std::move(callbacks), "GET", jsBundleUrl); - if (downloadProgressCallback) { - downloadProgressCallback(DownloadProgressStatus::STARTED); - } - return promise->get_future(); -} - -std::string DevServerHelper::getInspectorUrl() const { - bool isProfilingBuild = - jsinspector_modern::InspectorFlags::getInstance().getIsProfilingBuild(); - - return fmt::format( - "ws://{}:{}/inspector/device?name={}&app={}&device={}&profiling={}", - devServerHost_, - devServerPort_, - urlEscape(deviceName_), - appId_, - deviceId_, - isProfilingBuild); -} - -std::string DevServerHelper::getBundleUrl() const { - if (sourcePath_.empty()) { - return ""; - } - - bool dev = true; - bool lazy = dev; - bool minify = false; - bool splitBundle = false; - bool modulesOnly = splitBundle; - bool runModule = !splitBundle; - return fmt::format( - "http://{}:{}/{}.bundle?platform={}&dev={}&lazy={}&minify={}&app={}&modulesOnly={}&runModule={}&inlineSourceMap=false&excludeSource=true&sourcePaths=url-server", - devServerHost_, - devServerPort_, - sourcePath_, - DEFAULT_PLATFORM, - dev, - lazy, - minify, - appId_, - modulesOnly, - runModule); -}; - -std::string DevServerHelper::getPackagerConnectionUrl() const { - return fmt::format("ws://{}:{}/message", devServerHost_, devServerPort_); -} - -void DevServerHelper::openDebugger() const { - auto requestUrl = fmt::format( - "http://{}:{}/open-debugger?device={}", - devServerHost_, - devServerPort_, - deviceId_); - httpClient_->sendRequest({}, "POST", requestUrl); -} - -void DevServerHelper::setupHMRClient() const { - folly::dynamic params = folly::dynamic::array( - DEFAULT_PLATFORM, - sourcePath_, - devServerHost_, - devServerPort_, - true /*enable*/); - javaScriptModuleCallback_("HMRClient", "setup", std::move(params)); -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/nativemodule/dom/NativeDOM.cpp b/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/nativemodule/dom/NativeDOM.cpp deleted file mode 100644 index 2d30287655..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/nativemodule/dom/NativeDOM.cpp +++ /dev/null @@ -1,485 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include -#include -#include -#include -#include -#include - -#ifdef RN_DISABLE_OSS_PLUGIN_HEADER -#include "Plugins.h" -#endif - -std::shared_ptr NativeDOMModuleProvider( - std::shared_ptr jsInvoker) { - return std::make_shared(std::move(jsInvoker)); -} - -namespace facebook::react { - -namespace { -inline std::shared_ptr getShadowNode( - facebook::jsi::Runtime& runtime, - jsi::Value& shadowNodeValue) { - return Bridging>::fromJs( - runtime, shadowNodeValue); -} - -#pragma mark - Private helpers - -UIManager& getUIManagerFromRuntime(facebook::jsi::Runtime& runtime) { - return UIManagerBinding::getBinding(runtime)->getUIManager(); -} - -RootShadowNode::Shared getCurrentShadowTreeRevision( - facebook::jsi::Runtime& runtime, - SurfaceId surfaceId) { - auto shadowTreeRevisionProvider = - getUIManagerFromRuntime(runtime).getShadowTreeRevisionProvider(); - return shadowTreeRevisionProvider->getCurrentRevision(surfaceId); -} - -RootShadowNode::Shared getCurrentShadowTreeRevision( - facebook::jsi::Runtime& runtime, - jsi::Value& nativeNodeReference) { - if (nativeNodeReference.isNumber()) { - return getCurrentShadowTreeRevision( - runtime, static_cast(nativeNodeReference.asNumber())); - } - - return getCurrentShadowTreeRevision( - runtime, getShadowNode(runtime, nativeNodeReference)->getSurfaceId()); -} - -facebook::react::PointerEventsProcessor& getPointerEventsProcessorFromRuntime( - facebook::jsi::Runtime& runtime) { - return facebook::react::UIManagerBinding::getBinding(runtime) - ->getPointerEventsProcessor(); -} - -std::vector getArrayOfInstanceHandlesFromShadowNodes( - const std::vector>& nodes, - facebook::jsi::Runtime& runtime) { - // JSI doesn't support adding elements to an array after creation, - // so we need to accumulate the values in a vector and then create - // the array when we know the size. - std::vector nonNullInstanceHandles; - nonNullInstanceHandles.reserve(nodes.size()); - for (const auto& shadowNode : nodes) { - auto instanceHandle = (*shadowNode).getInstanceHandle(runtime); - if (!instanceHandle.isNull()) { - nonNullInstanceHandles.push_back(std::move(instanceHandle)); - } - } - - return nonNullInstanceHandles; -} - -bool isRootShadowNode(const ShadowNode& shadowNode) { - return shadowNode.getTraits().check(ShadowNodeTraits::Trait::RootNodeKind); -} - -} // namespace - -#pragma mark - NativeDOM - -NativeDOM::NativeDOM(std::shared_ptr jsInvoker) - : NativeDOMCxxSpec(std::move(jsInvoker)) {} - -#pragma mark - Methods from the Node interface (for ReadOnlyNode). - -double NativeDOM::compareDocumentPosition( - jsi::Runtime& rt, - jsi::Value nativeNodeReference, - jsi::Value otherNativeNodeReference) { - auto currentRevision = getCurrentShadowTreeRevision(rt, nativeNodeReference); - if (currentRevision == nullptr) { - return dom::DOCUMENT_POSITION_DISCONNECTED; - } - - std::shared_ptr shadowNode; - std::shared_ptr otherShadowNode; - - // Check if document references are used - if (nativeNodeReference.isNumber() || otherNativeNodeReference.isNumber()) { - if (nativeNodeReference.isNumber() && otherNativeNodeReference.isNumber()) { - // Both are documents (and equality is handled in JS directly). - return dom::DOCUMENT_POSITION_DISCONNECTED; - } else if (nativeNodeReference.isNumber()) { - // Only the first is a document - auto surfaceId = nativeNodeReference.asNumber(); - shadowNode = currentRevision; - otherShadowNode = getShadowNode(rt, otherNativeNodeReference); - - if (isRootShadowNode(*otherShadowNode)) { - // If the other is a root node, we just need to check if it is its - // `documentElement` - return (surfaceId == otherShadowNode->getSurfaceId()) - ? dom::DOCUMENT_POSITION_CONTAINED_BY | - dom::DOCUMENT_POSITION_FOLLOWING - : dom::DOCUMENT_POSITION_DISCONNECTED; - } else { - // Otherwise, we'll use the root node to represent the document - // (the result should be the same) - } - } else { - // Only the second is a document - auto otherSurfaceId = otherNativeNodeReference.asNumber(); - shadowNode = getShadowNode(rt, nativeNodeReference); - otherShadowNode = getCurrentShadowTreeRevision(rt, otherSurfaceId); - - if (isRootShadowNode(*shadowNode)) { - // If this is a root node, we just need to check if the other is its - // document. - return (otherSurfaceId == shadowNode->getSurfaceId()) - ? dom::DOCUMENT_POSITION_CONTAINS | dom::DOCUMENT_POSITION_PRECEDING - : dom::DOCUMENT_POSITION_DISCONNECTED; - } else { - // Otherwise, we'll use the root node to represent the document - // (the result should be the same) - } - } - } else { - shadowNode = getShadowNode(rt, nativeNodeReference); - otherShadowNode = getShadowNode(rt, otherNativeNodeReference); - } - - return dom::compareDocumentPosition( - currentRevision, *shadowNode, *otherShadowNode); -} - -std::vector NativeDOM::getChildNodes( - jsi::Runtime& rt, - jsi::Value nativeNodeReference) { - auto currentRevision = getCurrentShadowTreeRevision(rt, nativeNodeReference); - if (currentRevision == nullptr) { - return std::vector{}; - } - - // The only child node of the document is the root node. - if (nativeNodeReference.isNumber()) { - return getArrayOfInstanceHandlesFromShadowNodes({currentRevision}, rt); - } - - auto childNodes = dom::getChildNodes( - currentRevision, *getShadowNode(rt, nativeNodeReference)); - return getArrayOfInstanceHandlesFromShadowNodes(childNodes, rt); -} - -jsi::Value NativeDOM::getElementById( - jsi::Runtime& rt, - SurfaceId surfaceId, - const std::string& id) { - auto currentRevision = getCurrentShadowTreeRevision(rt, surfaceId); - if (currentRevision == nullptr) { - return jsi::Value::undefined(); - } - - auto elementById = dom::getElementById(currentRevision, id); - if (elementById == nullptr) { - return jsi::Value::undefined(); - } - - return elementById->getInstanceHandle(rt); -} - -jsi::Value NativeDOM::getParentNode( - jsi::Runtime& rt, - jsi::Value nativeNodeReference) { - // The document does not have a parent node. - if (nativeNodeReference.isNumber()) { - return jsi::Value::undefined(); - } - - auto shadowNode = getShadowNode(rt, nativeNodeReference); - - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return jsi::Value::undefined(); - } - - // The parent of the surface's root node is the document. Only the actual - // root node qualifies: nested nodes that carry the `RootNodeKind` trait - // (e.g. , portals/overlays) still have a real parent in the shadow - // tree and must report it. Otherwise capture/bubble event propagation is - // silently severed at that boundary (a listener on an ancestor rendered - // above the modal would never receive descendant focus/blur, etc.). - if (ShadowNode::sameFamily(*currentRevision, *shadowNode)) { - return jsi::Value{shadowNode->getSurfaceId()}; - } - - auto parentShadowNode = dom::getParentNode(currentRevision, *shadowNode); - if (parentShadowNode == nullptr) { - return jsi::Value::undefined(); - } - - return parentShadowNode->getInstanceHandle(rt); -} - -bool NativeDOM::isConnected(jsi::Runtime& rt, jsi::Value nativeNodeReference) { - auto currentRevision = getCurrentShadowTreeRevision(rt, nativeNodeReference); - if (currentRevision == nullptr) { - return false; - } - - // The document is connected because we got a value for current revision. - if (nativeNodeReference.isNumber()) { - return true; - } - - auto shadowNode = getShadowNode(rt, nativeNodeReference); - return dom::isConnected(currentRevision, *shadowNode); -} - -#pragma mark - Methods from the Element interface (for ReactNativeElement). - -std::tuple< - /* topWidth: */ int, - /* rightWidth: */ int, - /* bottomWidth: */ int, - /* leftWidth: */ int> -NativeDOM::getBorderWidth( - jsi::Runtime& rt, - std::shared_ptr shadowNode) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return {0, 0, 0, 0}; - } - - auto borderWidth = dom::getBorderWidth(currentRevision, *shadowNode); - return std::tuple{ - borderWidth.top, borderWidth.right, borderWidth.bottom, borderWidth.left}; -} - -std::tuple< - /* x: */ double, - /* y: */ double, - /* width: */ double, - /* height: */ double> -NativeDOM::getBoundingClientRect( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - bool includeTransform) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return {0, 0, 0, 0}; - } - - auto domRect = dom::getBoundingClientRect( - currentRevision, *shadowNode, includeTransform); - - return std::tuple{domRect.x, domRect.y, domRect.width, domRect.height}; -} - -std::tuple NativeDOM::getInnerSize( - jsi::Runtime& rt, - std::shared_ptr shadowNode) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return {0, 0}; - } - - auto innerSize = dom::getInnerSize(currentRevision, *shadowNode); - return std::tuple{innerSize.width, innerSize.height}; -} - -std::tuple -NativeDOM::getScrollPosition( - jsi::Runtime& rt, - std::shared_ptr shadowNode) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return {0, 0}; - } - - auto domPoint = dom::getScrollPosition(currentRevision, *shadowNode); - return std::tuple{domPoint.x, domPoint.y}; -} - -std::tuple -NativeDOM::getScrollSize( - jsi::Runtime& rt, - std::shared_ptr shadowNode) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return {0, 0}; - } - - auto scrollSize = dom::getScrollSize(currentRevision, *shadowNode); - return std::tuple{scrollSize.width, scrollSize.height}; -} - -std::string NativeDOM::getTagName( - jsi::Runtime& /*rt*/, - std::shared_ptr shadowNode) { - return dom::getTagName(*shadowNode); -} - -std::string NativeDOM::getTextContent( - jsi::Runtime& rt, - std::shared_ptr shadowNode) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return ""; - } - - return dom::getTextContent(currentRevision, *shadowNode); -} - -bool NativeDOM::hasPointerCapture( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - double pointerId) { - bool isCapturing = getPointerEventsProcessorFromRuntime(rt).hasPointerCapture( - static_cast(pointerId), shadowNode.get()); - return isCapturing; -} - -void NativeDOM::releasePointerCapture( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - double pointerId) { - getPointerEventsProcessorFromRuntime(rt).releasePointerCapture( - static_cast(pointerId), shadowNode.get()); -} - -void NativeDOM::setPointerCapture( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - double pointerId) { - getPointerEventsProcessorFromRuntime(rt).setPointerCapture( - static_cast(pointerId), shadowNode); -} - -#pragma mark - Methods from the HTMLElement interface (for ReactNativeElement). - -std::tuple< - /* offsetParent: */ jsi::Value, - /* top: */ double, - /* left: */ double> -NativeDOM::getOffset( - jsi::Runtime& rt, - std::shared_ptr shadowNode) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - return {jsi::Value::undefined(), 0, 0}; - } - - auto domOffset = dom::getOffset(currentRevision, *shadowNode); - - return std::tuple{ - domOffset.offsetParent == nullptr - ? jsi::Value::undefined() - : domOffset.offsetParent->getInstanceHandle(rt), - domOffset.top, - domOffset.left}; -} - -#pragma mark - Special methods to handle the root node. - -jsi::Value NativeDOM::linkRootNode( - jsi::Runtime& rt, - SurfaceId surfaceId, - jsi::Value instanceHandle) { - auto currentRevision = getCurrentShadowTreeRevision(rt, surfaceId); - if (currentRevision == nullptr) { - return jsi::Value::undefined(); - } - - auto instanceHandleWrapper = - std::make_shared(rt, instanceHandle, surfaceId); - currentRevision->setInstanceHandle(instanceHandleWrapper); - - return Bridging>::toJs(rt, currentRevision); -} - -#pragma mark - Legacy layout APIs (for ReactNativeElement). - -void NativeDOM::measure( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - const MeasureOnSuccessCallback& callback) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - callback(0, 0, 0, 0, 0, 0); - return; - } - - auto measureRect = dom::measure(currentRevision, *shadowNode); - - callback( - measureRect.x, - measureRect.y, - measureRect.width, - measureRect.height, - measureRect.pageX, - measureRect.pageY); -} - -void NativeDOM::measureInWindow( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - const MeasureInWindowOnSuccessCallback& callback) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - callback(0, 0, 0, 0); - return; - } - - auto rect = dom::measureInWindow(currentRevision, *shadowNode); - callback(rect.x, rect.y, rect.width, rect.height); -} - -void NativeDOM::measureLayout( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - std::shared_ptr relativeToShadowNode, - jsi::Function onFail, - const MeasureLayoutOnSuccessCallback& onSuccess) { - auto currentRevision = - getCurrentShadowTreeRevision(rt, shadowNode->getSurfaceId()); - if (currentRevision == nullptr) { - onFail.call(rt); - return; - } - - auto maybeRect = - dom::measureLayout(currentRevision, *shadowNode, *relativeToShadowNode); - - if (!maybeRect) { - onFail.call(rt); - return; - } - - auto rect = maybeRect.value(); - - onSuccess(rect.x, rect.y, rect.width, rect.height); -} - -#pragma mark - Legacy direct manipulation APIs (for ReactNativeElement). - -void NativeDOM::setNativeProps( - jsi::Runtime& rt, - std::shared_ptr shadowNode, - jsi::Value updatePayload) { - getUIManagerFromRuntime(rt).setNativeProps_DEPRECATED( - shadowNode, RawProps(rt, updatePayload)); -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/nativemodule/dom/NativeDOM.h b/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/nativemodule/dom/NativeDOM.h deleted file mode 100644 index 78937e375f..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/nativemodule/dom/NativeDOM.h +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include - -#if __has_include("FBReactNativeSpecJSI.h") // CocoaPod headers on Apple -#include "FBReactNativeSpecJSI.h" -#else -#include -#endif - -#include -#include -#include - -namespace facebook::react { - -using MeasureOnSuccessCallback = SyncCallback; - -using MeasureInWindowOnSuccessCallback = SyncCallback; - -using MeasureLayoutOnSuccessCallback = SyncCallback; - -class NativeDOM : public NativeDOMCxxSpec { - public: - NativeDOM(std::shared_ptr jsInvoker); - -#pragma mark - Methods from the Node interface (for ReadOnlyNode). - - double compareDocumentPosition(jsi::Runtime &rt, jsi::Value nativeNodeReference, jsi::Value otherNativeNodeReference); - - std::vector getChildNodes(jsi::Runtime &rt, jsi::Value nativeNodeReference); - - jsi::Value getElementById(jsi::Runtime &rt, SurfaceId surfaceId, const std::string &id); - - jsi::Value getParentNode(jsi::Runtime &rt, jsi::Value nativeNodeReference); - - bool isConnected(jsi::Runtime &rt, jsi::Value nativeNodeReference); - -#pragma mark - Methods from the Element interface (for ReactNativeElement). - - std::tuple< - /* topWidth: */ int, - /* rightWidth: */ int, - /* bottomWidth: */ int, - /* leftWidth: */ int> getBorderWidth(jsi::Runtime &rt, std::shared_ptr shadowNode); - - std::tuple< - /* x: */ double, - /* y: */ double, - /* width: */ double, - /* height: */ double> - getBoundingClientRect(jsi::Runtime &rt, std::shared_ptr shadowNode, bool includeTransform); - - std::tuple getInnerSize( - jsi::Runtime &rt, - std::shared_ptr shadowNode); - - std::tuple getScrollPosition( - jsi::Runtime &rt, - std::shared_ptr shadowNode); - - std::tuple getScrollSize( - jsi::Runtime &rt, - std::shared_ptr shadowNode); - - std::string getTagName(jsi::Runtime &rt, std::shared_ptr shadowNode); - - std::string getTextContent(jsi::Runtime &rt, std::shared_ptr shadowNode); - - bool hasPointerCapture(jsi::Runtime &rt, std::shared_ptr shadowNode, double pointerId); - - void releasePointerCapture(jsi::Runtime &rt, std::shared_ptr shadowNode, double pointerId); - - void setPointerCapture(jsi::Runtime &rt, std::shared_ptr shadowNode, double pointerId); - -#pragma mark - Methods from the HTMLElement interface (for ReactNativeElement). - - std::tuple< - /* offsetParent: */ jsi::Value, - /* top: */ double, - /* left: */ double> getOffset(jsi::Runtime &rt, std::shared_ptr shadowNode); - -#pragma mark - Special methods to handle the root node. - - jsi::Value linkRootNode(jsi::Runtime &rt, SurfaceId surfaceId, jsi::Value instanceHandle); - -#pragma mark - Legacy layout APIs (for ReactNativeElement). - - void - measure(jsi::Runtime &rt, std::shared_ptr shadowNode, const MeasureOnSuccessCallback &callback); - - void measureInWindow( - jsi::Runtime &rt, - std::shared_ptr shadowNode, - const MeasureInWindowOnSuccessCallback &callback); - - void measureLayout( - jsi::Runtime &rt, - std::shared_ptr shadowNode, - std::shared_ptr relativeToShadowNode, - jsi::Function onFail, - const MeasureLayoutOnSuccessCallback &onSuccess); - -#pragma mark - Legacy direct manipulation APIs (for ReactNativeElement). - - void setNativeProps(jsi::Runtime &rt, std::shared_ptr shadowNode, jsi::Value updatePayload); -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/components/textinput/BaseTextInputShadowNode.h b/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/components/textinput/BaseTextInputShadowNode.h deleted file mode 100644 index e6db7cbdc2..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/components/textinput/BaseTextInputShadowNode.h +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -inline ShadowView shadowViewFromShadowNode(const ShadowNode &shadowNode) -{ - auto shadowView = ShadowView{shadowNode}; - // Clearing `props` and `state` (which we don't use) allows avoiding retain - // cycles. - shadowView.props = nullptr; - shadowView.state = nullptr; - return shadowView; -} - -/* - * Base `ShadowNode` for component. - */ -template -class BaseTextInputShadowNode - : public ConcreteViewShadowNode, - public BaseTextShadowNode { - public: - using BaseShadowNode = ConcreteViewShadowNode; - - using BaseShadowNode::ConcreteViewShadowNode; - - static ShadowNodeTraits BaseTraits() - { - auto traits = BaseShadowNode::BaseTraits(); - traits.set(ShadowNodeTraits::Trait::LeafYogaNode); - traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); - traits.set(ShadowNodeTraits::Trait::BaselineYogaNode); - return traits; - } - - /* - * Associates a shared `TextLayoutManager` with the node. - * `TextInputShadowNode` uses the manager to measure text content - * and construct `TextInputState` objects. - */ - void setTextLayoutManager(std::shared_ptr textLayoutManager) - { - Sealable::ensureUnsealed(); - textLayoutManager_ = std::move(textLayoutManager); - } - - protected: - Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override - { - const auto &props = BaseShadowNode::getConcreteProps(); - auto textConstraints = getTextConstraints(layoutConstraints); - - TextLayoutContext textLayoutContext{ - .pointScaleFactor = layoutContext.pointScaleFactor, - .surfaceId = BaseShadowNode::getSurfaceId(), - }; - auto textSize = textLayoutManager_ - ->measure( - attributedStringBoxToMeasure(layoutContext), - props.paragraphAttributes, - textLayoutContext, - textConstraints) - .size; - - return layoutConstraints.clamp(textSize); - } - - void layout(LayoutContext layoutContext) override - { - updateStateIfNeeded(layoutContext); - BaseShadowNode::layout(layoutContext); - } - - Float baseline(const LayoutContext &layoutContext, Size size) const override - { - const auto &props = BaseShadowNode::getConcreteProps(); - auto attributedString = getAttributedString(layoutContext); - - if (attributedString.isEmpty()) { - attributedString = getPlaceholderAttributedString(layoutContext); - } - - // Yoga expects a baseline relative to the Node's border-box edge instead of - // the content, so we need to adjust by the padding and border widths, which - // have already been set by the time of baseline alignment - auto top = YGNodeLayoutGetBorder(&this->yogaNode_, YGEdgeTop) + - YGNodeLayoutGetPadding(&this->yogaNode_, YGEdgeTop); - - AttributedStringBox attributedStringBox{attributedString}; - - if constexpr (TextLayoutManagerExtended::supportsLineMeasurement()) { - auto lines = TextLayoutManagerExtended(*textLayoutManager_) - .measureLines(attributedStringBox, props.paragraphAttributes, size); - return LineMeasurement::baseline(lines) + top; - } else { - LOG(WARNING) << "Baseline alignment is not supported by the current platform"; - return top; - } - } - - /* - * Determines the constraints to use while measure the underlying text - */ - LayoutConstraints getTextConstraints(const LayoutConstraints &layoutConstraints) const - { - if (BaseShadowNode::getConcreteProps().multiline) { - return layoutConstraints; - } else { - // A single line TextInput acts as a horizontal scroller of infinitely - // expandable text, so we want to measure the text as if it is allowed to - // infinitely expand horizontally, and later clamp to the constraints of - // the input. - return LayoutConstraints{ - .minimumSize = layoutConstraints.minimumSize, - .maximumSize = - Size{ - .width = std::numeric_limits::infinity(), - .height = layoutConstraints.maximumSize.height, - }, - .layoutDirection = layoutConstraints.layoutDirection, - }; - } - } - - std::shared_ptr textLayoutManager_; - - private: - /* - * Creates a `State` object if needed. - */ - void updateStateIfNeeded(const LayoutContext &layoutContext) - { - Sealable::ensureUnsealed(); - const auto &stateData = BaseShadowNode::getStateData(); - const auto &reactTreeAttributedString = getAttributedString(layoutContext); - - if (stateData.reactTreeAttributedString.isContentEqual(reactTreeAttributedString)) { - return; - } - - const auto &props = BaseShadowNode::getConcreteProps(); - BaseShadowNode::setStateData( - TextInputState{ - AttributedStringBox{reactTreeAttributedString}, - reactTreeAttributedString, - props.paragraphAttributes, - props.mostRecentEventCount}); - } - - /* - * Returns a `AttributedString` which represents text content of the node. - */ - AttributedString getAttributedString(const LayoutContext &layoutContext) const - { - const auto &props = BaseShadowNode::getConcreteProps(); - const auto textAttributes = props.getEffectiveTextAttributes(layoutContext.fontSizeMultiplier); - - AttributedString attributedString; - attributedString.appendFragment( - AttributedString::Fragment{ - .string = props.text, - .textAttributes = textAttributes, - .parentShadowView = shadowViewFromShadowNode(*this)}); - - auto attachments = BaseTextShadowNode::Attachments{}; - BaseTextShadowNode::buildAttributedString(textAttributes, *this, attributedString, attachments); - attributedString.setBaseTextAttributes(textAttributes); - return attributedString; - } - - /* - * Returns an `AttributedStringBox` which represents text content that should - * be used for measuring purposes. It might contain actual text value, - * placeholder value or some character that represents the size of the font. - */ - AttributedStringBox attributedStringBoxToMeasure(const LayoutContext &layoutContext) const - { - bool meaningfulState = BaseShadowNode::getState() && - BaseShadowNode::getState()->getRevision() != State::initialRevisionValue && - BaseShadowNode::getStateData().reactTreeAttributedString.getBaseTextAttributes().fontSizeMultiplier == - layoutContext.fontSizeMultiplier; - if (meaningfulState) { - const auto &stateData = BaseShadowNode::getStateData(); - auto attributedStringBox = stateData.attributedStringBox; - if (attributedStringBox.getMode() == AttributedStringBox::Mode::OpaquePointer || - !attributedStringBox.getValue().isEmpty()) { - return stateData.attributedStringBox; - } - } - - auto attributedString = meaningfulState ? AttributedString{} : getAttributedString(layoutContext); - - if (attributedString.isEmpty()) { - attributedString = getPlaceholderAttributedString(layoutContext); - } - return AttributedStringBox{attributedString}; - } - - AttributedString getPlaceholderAttributedString(const LayoutContext &layoutContext) const - { - const auto &props = BaseShadowNode::getConcreteProps(); - - AttributedString attributedString; - attributedString.setBaseTextAttributes(props.getEffectiveTextAttributes(layoutContext.fontSizeMultiplier)); - - if (!props.placeholder.empty()) { - attributedString.appendFragment( - {.string = props.placeholder, - .textAttributes = attributedString.getBaseTextAttributes(), - .parentShadowView = {}}); - } - return attributedString; - } -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/components/view/HostPlatformViewProps.h b/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/components/view/HostPlatformViewProps.h deleted file mode 100644 index d66f61b2b5..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/components/view/HostPlatformViewProps.h +++ /dev/null @@ -1,188 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook::react { -class HostPlatformViewProps : public BaseViewProps { - public: - HostPlatformViewProps() = default; - HostPlatformViewProps( - const PropsParserContext& context, - const HostPlatformViewProps& sourceProps, - const RawProps& rawProps, - const std::function& filterObjectKeys = nullptr) - : BaseViewProps(context, sourceProps, rawProps, filterObjectKeys), - focusable(convertRawProp( - context, - rawProps, - "focusable", - sourceProps.focusable, - false)), - desktopDragRegion(convertRawProp( - context, - rawProps, - "desktopDragRegion", - sourceProps.desktopDragRegion, - false)), - group(convertRawProp( - context, - rawProps, - "group", - sourceProps.group, - std::string{})), - hoverStyle(convertRawProp( - context, - rawProps, - "hoverStyle", - sourceProps.hoverStyle, - std::string{})), - activeStyle(convertRawProp( - context, - rawProps, - "activeStyle", - sourceProps.activeStyle, - std::string{})), - focusStyle(convertRawProp( - context, - rawProps, - "focusStyle", - sourceProps.focusStyle, - std::string{})), - focusVisibleStyle(convertRawProp( - context, - rawProps, - "focusVisibleStyle", - sourceProps.focusVisibleStyle, - std::string{})), - groupHoverStyle(convertRawProp( - context, - rawProps, - "groupHoverStyle", - sourceProps.groupHoverStyle, - std::string{})), - groupActiveStyle(convertRawProp( - context, - rawProps, - "groupActiveStyle", - sourceProps.groupActiveStyle, - std::string{})), - dragOverStyle(convertRawProp( - context, - rawProps, - "dragOverStyle", - sourceProps.dragOverStyle, - std::string{})), - acceptsFiles(convertRawProp( - context, - rawProps, - "acceptsFiles", - sourceProps.acceptsFiles, - false)), - tooltip(convertRawProp( - context, - rawProps, - "tooltip", - sourceProps.tooltip, - std::string{})), - draggable(convertRawProp( - context, - rawProps, - "draggable", - sourceProps.draggable, - false)), - droppable(convertRawProp( - context, - rawProps, - "droppable", - sourceProps.droppable, - false)), - // Either handler is enough to make the view a context-menu target. Fabric - // turns a function prop into `true`, so a view with only the capture - // handler used to get no listener at all. - onContextMenu( - convertRawProp( - context, - rawProps, - "onContextMenu", - sourceProps.onContextMenu, - false) || - convertRawProp( - context, - rawProps, - "onContextMenuCapture", - false, - false)), - onWheel( - convertRawProp( - context, - rawProps, - "onWheel", - sourceProps.onWheel, - false) || - convertRawProp( - context, - rawProps, - "onWheelCapture", - false, - false)) {} - - void setProp( - const PropsParserContext& context, - RawPropsPropNameHash hash, - const char* propName, - const RawValue& value) { - BaseViewProps::setProp(context, hash, propName, value); - static auto defaults = HostPlatformViewProps{}; - switch (hash) { - RAW_SET_PROP_SWITCH_CASE_BASIC(focusable); - RAW_SET_PROP_SWITCH_CASE_BASIC(desktopDragRegion); - RAW_SET_PROP_SWITCH_CASE_BASIC(group); - RAW_SET_PROP_SWITCH_CASE_BASIC(hoverStyle); - RAW_SET_PROP_SWITCH_CASE_BASIC(activeStyle); - RAW_SET_PROP_SWITCH_CASE_BASIC(focusStyle); - RAW_SET_PROP_SWITCH_CASE_BASIC(focusVisibleStyle); - RAW_SET_PROP_SWITCH_CASE_BASIC(groupHoverStyle); - RAW_SET_PROP_SWITCH_CASE_BASIC(groupActiveStyle); - RAW_SET_PROP_SWITCH_CASE_BASIC(dragOverStyle); - RAW_SET_PROP_SWITCH_CASE_BASIC(acceptsFiles); - RAW_SET_PROP_SWITCH_CASE_BASIC(tooltip); - RAW_SET_PROP_SWITCH_CASE_BASIC(draggable); - RAW_SET_PROP_SWITCH_CASE_BASIC(droppable); - // There is one stored flag, so only `onContextMenu` gets a case here; a - // second case would need a field that does not exist. An update to either - // prop still re-parses through the constructor above, where the two are - // OR'd, so a view that swaps `onContextMenu` for `onContextMenuCapture` - // keeps its listener. - RAW_SET_PROP_SWITCH_CASE_BASIC(onContextMenu); - RAW_SET_PROP_SWITCH_CASE_BASIC(onWheel); - } - } - - bool focusable{false}; - bool desktopDragRegion{false}; - /// The state style props arrive as JSON text produced by the view config in - /// JS; an empty string means the prop is not set. - std::string group; - std::string hoverStyle; - std::string activeStyle; - std::string focusStyle; - std::string focusVisibleStyle; - std::string groupHoverStyle; - std::string groupActiveStyle; - std::string dragOverStyle; - bool acceptsFiles{false}; - std::string tooltip; - bool draggable{false}; - bool droppable{false}; - /// True when the view has an `onContextMenu` handler (RN turns a function - /// prop into this boolean marker). - bool onContextMenu{false}; - /// True when the view has an `onWheel` or `onWheelCapture` handler. - bool onWheel{false}; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/components/view/HostPlatformViewTraitsInitializer.h b/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/components/view/HostPlatformViewTraitsInitializer.h deleted file mode 100644 index 95c9a888ef..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/components/view/HostPlatformViewTraitsInitializer.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include -#include - -namespace facebook::react::HostPlatformViewTraitsInitializer { -inline bool formsStackingContext(const ViewProps & /*props*/) -{ - return true; -} - -inline bool formsView(const ViewProps & /*props*/) -{ - return false; -} - -inline bool isKeyboardFocusable(const ViewProps &props) -{ - return props.focusable; -} - -} // namespace facebook::react::HostPlatformViewTraitsInitializer diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/imagemanager/platform/cxx/react/renderer/imagemanager/ImageManager.cpp b/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/imagemanager/platform/cxx/react/renderer/imagemanager/ImageManager.cpp deleted file mode 100644 index ac44b9c52a..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/imagemanager/platform/cxx/react/renderer/imagemanager/ImageManager.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -// Upstream's cxx `ImageManager::requestImage` returns a request that never -// completes, so no image event is ever sent. This one loads through the table -// in GpuiImageLoad.h and reports progress, completion and failure to the -// request's observers. - -#include -#include -#include -#include - -#include "GpuiImageLoad.h" // rngpui::gpuiImageLoadTable - -namespace rngpui { -namespace { -GpuiImageLoadTable gImageLoadTable{}; -} // namespace - -void setGpuiImageLoadTable(const GpuiImageLoadTable& table) { - gImageLoadTable = table; -} - -const GpuiImageLoadTable* gpuiImageLoadTable() { - return gImageLoadTable.start ? &gImageLoadTable : nullptr; -} -} // namespace rngpui - -namespace facebook::react { - -ImageManager::ImageManager( - const std::shared_ptr& /*contextContainer*/) { - // Silence unused-private-field warning. - (void)self_; -} - -ImageManager::~ImageManager() = default; - -ImageRequest ImageManager::requestImage( - const ImageSource& imageSource, - SurfaceId surfaceId, - const ImageRequestParams& /*imageRequestParams*/, - Tag /*tag*/) const { - auto telemetry = std::make_shared(surfaceId); - ImageRequest request{imageSource, telemetry, {}, {}}; - const auto* table = rngpui::gpuiImageLoadTable(); - if (!table || imageSource.type == ImageSource::Type::Invalid) { - return request; - } - std::weak_ptr weak = - request.getSharedObserverCoordinator(); - table->start( - imageSource.uri, - [weak](float progress, int64_t loaded, int64_t total) { - if (auto coordinator = weak.lock()) { - coordinator->nativeImageResponseProgress(progress, loaded, total); - } - }, - [weak](double width, double height, const char* error) { - auto coordinator = weak.lock(); - if (!coordinator) { - return; - } - if (error != nullptr) { - coordinator->nativeImageResponseFailed( - ImageLoadError(std::make_shared(error))); - return; - } - auto size = std::make_shared( - Size{static_cast(width), static_cast(height)}); - coordinator->nativeImageResponseComplete(ImageResponse(size, nullptr)); - }); - return request; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/textlayoutmanager/TextLayoutManager.h b/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/textlayoutmanager/TextLayoutManager.h deleted file mode 100644 index f95996a34a..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/textlayoutmanager/TextLayoutManager.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -class TextLayoutManager; - -/* - * Cross platform facade for text measurement (e.g. Android-specific - * TextLayoutManager) - */ -class TextLayoutManager { - public: - explicit TextLayoutManager(const std::shared_ptr &contextContainer); - virtual ~TextLayoutManager() = default; - - /* - * Not copyable. - */ - TextLayoutManager(const TextLayoutManager &) = delete; - TextLayoutManager &operator=(const TextLayoutManager &) = delete; - - /* - * Not movable. - */ - TextLayoutManager(TextLayoutManager &&) = delete; - TextLayoutManager &operator=(TextLayoutManager &&) = delete; - - /* - * Measures `attributedString` using native text rendering infrastructure. - */ - virtual TextMeasurement measure( - const AttributedStringBox &attributedStringBox, - const ParagraphAttributes ¶graphAttributes, - const TextLayoutContext &layoutContext, - const LayoutConstraints &layoutConstraints) const; - - /* - * Measures each laid-out line of `attributedStringBox` within `size`, for - * `onTextLayout` and baseline alignment. - */ - virtual LinesMeasurements measureLines( - const AttributedStringBox &attributedStringBox, - const ParagraphAttributes ¶graphAttributes, - const Size &size) const; - - protected: - std::shared_ptr contextContainer_; - TextMeasureCache textMeasureCache_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.cpp b/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.cpp deleted file mode 100644 index b23006e953..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -// Upstream's cxx `TextLayoutManager::measure` returns the Yoga minimum size; -// this one measures through the table in GpuiTextMeasure.h. - -// This file is compiled from ReactCommonOverrides/, not from next to its -// header, so the include is spelled relative to an include root -// (`${platform_DIR}` = .../textlayoutmanager/platform/cxx/). -#include - -#include "GpuiTextMeasure.h" // rngpui::gpuiTextMeasureTable - -namespace rngpui { -namespace { -GpuiTextMeasureTable gTextMeasureTable{}; -} // namespace - -void setGpuiTextMeasureTable(const GpuiTextMeasureTable& table) { - gTextMeasureTable = table; -} - -const GpuiTextMeasureTable* gpuiTextMeasureTable() { - return gTextMeasureTable.measureParagraph ? &gTextMeasureTable : nullptr; -} - -} // namespace rngpui - -namespace facebook::react { -TextLayoutManager::TextLayoutManager( - const std::shared_ptr& contextContainer) - : contextContainer_(contextContainer), textMeasureCache_(kSimpleThreadSafeCacheSizeCap) {} - -TextMeasurement TextLayoutManager::measure( - const AttributedStringBox& attributedStringBox, - const ParagraphAttributes& paragraphAttributes, - const TextLayoutContext& /*layoutContext*/, - const LayoutConstraints& layoutConstraints) const { - const auto& fragments = attributedStringBox.getValue().getFragments(); - - TextMeasurement::Attachments attachments; - for (const auto& fragment : fragments) { - if (fragment.isAttachment()) { - attachments.push_back( - TextMeasurement::Attachment{ - .frame = {.origin = {.x = 0, .y = 0}, .size = {.width = 0, .height = 0}}, - .isClipped = false}); - } - } - - // Without a table (GpuiHost not started yet) measure to zero, the same - // result the Rust side returns when no measure handler is registered. - rngpui::GpuiTextSize size{.width = 0, .height = 0}; - if (const auto* table = rngpui::gpuiTextMeasureTable()) { - size = table->measureParagraph( - attributedStringBox.getValue(), - paragraphAttributes, - layoutConstraints.maximumSize.width, - layoutConstraints.maximumSize.height); - } - - return TextMeasurement{ - .size = layoutConstraints.clamp({.width = size.width, .height = size.height}), - .attachments = std::move(attachments)}; -} - -LinesMeasurements TextLayoutManager::measureLines( - const AttributedStringBox& attributedStringBox, - const ParagraphAttributes& paragraphAttributes, - const Size& size) const { - LinesMeasurements lines; - const auto* table = rngpui::gpuiTextMeasureTable(); - if (table == nullptr || table->measureLines == nullptr) { - return lines; - } - for (auto& line : table->measureLines( - attributedStringBox.getValue(), paragraphAttributes, size.width)) { - lines.emplace_back( - std::move(line.text), - Rect{ - .origin = {.x = line.x, .y = line.y}, - .size = {.width = line.width, .height = line.height}}, - line.descender, - line.capHeight, - line.ascender, - line.xHeight); - } - return lines; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/yoga/YGEnums.cpp b/vendor/react-native-gpui/packages/core/ReactCommonOverrides/yoga/YGEnums.cpp deleted file mode 100644 index 9ba4c49389..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/yoga/YGEnums.cpp +++ /dev/null @@ -1,304 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -// @generated by enums.py -// clang-format off -#include - -const char* YGAlignToString(const YGAlign value) { - switch (value) { - case YGAlignAuto: - return "auto"; - case YGAlignFlexStart: - return "flex-start"; - case YGAlignCenter: - return "center"; - case YGAlignFlexEnd: - return "flex-end"; - case YGAlignStretch: - return "stretch"; - case YGAlignBaseline: - return "baseline"; - case YGAlignSpaceBetween: - return "space-between"; - case YGAlignSpaceAround: - return "space-around"; - case YGAlignSpaceEvenly: - return "space-evenly"; - case YGAlignStart: - return "start"; - case YGAlignEnd: - return "end"; - } - return "unknown"; -} - -const char* YGBoxSizingToString(const YGBoxSizing value) { - switch (value) { - case YGBoxSizingBorderBox: - return "border-box"; - case YGBoxSizingContentBox: - return "content-box"; - } - return "unknown"; -} - -const char* YGDimensionToString(const YGDimension value) { - switch (value) { - case YGDimensionWidth: - return "width"; - case YGDimensionHeight: - return "height"; - } - return "unknown"; -} - -const char* YGDirectionToString(const YGDirection value) { - switch (value) { - case YGDirectionInherit: - return "inherit"; - case YGDirectionLTR: - return "ltr"; - case YGDirectionRTL: - return "rtl"; - } - return "unknown"; -} - -const char* YGDisplayToString(const YGDisplay value) { - switch (value) { - case YGDisplayFlex: - return "flex"; - case YGDisplayNone: - return "none"; - case YGDisplayContents: - return "contents"; - case YGDisplayGrid: - return "grid"; - } - return "unknown"; -} - -const char* YGEdgeToString(const YGEdge value) { - switch (value) { - case YGEdgeLeft: - return "left"; - case YGEdgeTop: - return "top"; - case YGEdgeRight: - return "right"; - case YGEdgeBottom: - return "bottom"; - case YGEdgeStart: - return "start"; - case YGEdgeEnd: - return "end"; - case YGEdgeHorizontal: - return "horizontal"; - case YGEdgeVertical: - return "vertical"; - case YGEdgeAll: - return "all"; - } - return "unknown"; -} - -const char* YGErrataToString(const YGErrata value) { - switch (value) { - case YGErrataNone: - return "none"; - case YGErrataStretchFlexBasis: - return "stretch-flex-basis"; - case YGErrataAbsolutePositionWithoutInsetsExcludesPadding: - return "absolute-position-without-insets-excludes-padding"; - case YGErrataAbsolutePercentAgainstInnerSize: - return "absolute-percent-against-inner-size"; - case YGErrataMinSizeUndefinedInsteadOfAuto: - return "min-size-undefined-instead-of-auto"; - case YGErrataFlexBasisAsIntrinsicSize: - return "flex-basis-as-intrinsic-size"; - case YGErrataAll: - return "all"; - case YGErrataClassic: - return "classic"; - } - return "unknown"; -} - -const char* YGExperimentalFeatureToString(const YGExperimentalFeature value) { - switch (value) { - case YGExperimentalFeatureWebFlexBasis: - return "web-flex-basis"; - case YGExperimentalFeatureFixFlexBasisFitContent: - return "fix-flex-basis-fit-content"; - } - return "unknown"; -} - -const char* YGFlexDirectionToString(const YGFlexDirection value) { - switch (value) { - case YGFlexDirectionColumn: - return "column"; - case YGFlexDirectionColumnReverse: - return "column-reverse"; - case YGFlexDirectionRow: - return "row"; - case YGFlexDirectionRowReverse: - return "row-reverse"; - } - return "unknown"; -} - -const char* YGGridTrackTypeToString(const YGGridTrackType value) { - switch (value) { - case YGGridTrackTypeAuto: - return "auto"; - case YGGridTrackTypePoints: - return "points"; - case YGGridTrackTypePercent: - return "percent"; - case YGGridTrackTypeFr: - return "fr"; - case YGGridTrackTypeMinmax: - return "minmax"; - } - return "unknown"; -} - -const char* YGGutterToString(const YGGutter value) { - switch (value) { - case YGGutterColumn: - return "column"; - case YGGutterRow: - return "row"; - case YGGutterAll: - return "all"; - } - return "unknown"; -} - -const char* YGJustifyToString(const YGJustify value) { - switch (value) { - case YGJustifyAuto: - return "auto"; - case YGJustifyFlexStart: - return "flex-start"; - case YGJustifyCenter: - return "center"; - case YGJustifyFlexEnd: - return "flex-end"; - case YGJustifySpaceBetween: - return "space-between"; - case YGJustifySpaceAround: - return "space-around"; - case YGJustifySpaceEvenly: - return "space-evenly"; - case YGJustifyStretch: - return "stretch"; - case YGJustifyStart: - return "start"; - case YGJustifyEnd: - return "end"; - } - return "unknown"; -} - -const char* YGLogLevelToString(const YGLogLevel value) { - switch (value) { - case YGLogLevelError: - return "error"; - case YGLogLevelWarn: - return "warn"; - case YGLogLevelInfo: - return "info"; - case YGLogLevelDebug: - return "debug"; - case YGLogLevelVerbose: - return "verbose"; - case YGLogLevelFatal: - return "fatal"; - } - return "unknown"; -} - -const char* YGMeasureModeToString(const YGMeasureMode value) { - switch (value) { - case YGMeasureModeUndefined: - return "undefined"; - case YGMeasureModeExactly: - return "exactly"; - case YGMeasureModeAtMost: - return "at-most"; - } - return "unknown"; -} - -const char* YGNodeTypeToString(const YGNodeType value) { - switch (value) { - case YGNodeTypeDefault: - return "default"; - case YGNodeTypeText: - return "text"; - } - return "unknown"; -} - -const char* YGOverflowToString(const YGOverflow value) { - switch (value) { - case YGOverflowVisible: - return "visible"; - case YGOverflowHidden: - return "hidden"; - case YGOverflowScroll: - return "scroll"; - } - return "unknown"; -} - -const char* YGPositionTypeToString(const YGPositionType value) { - switch (value) { - case YGPositionTypeStatic: - return "static"; - case YGPositionTypeRelative: - return "relative"; - case YGPositionTypeAbsolute: - return "absolute"; - } - return "unknown"; -} - -const char* YGUnitToString(const YGUnit value) { - switch (value) { - case YGUnitUndefined: - return "undefined"; - case YGUnitPoint: - return "point"; - case YGUnitPercent: - return "percent"; - case YGUnitAuto: - return "auto"; - case YGUnitMaxContent: - return "max-content"; - case YGUnitFitContent: - return "fit-content"; - case YGUnitStretch: - return "stretch"; - } - return "unknown"; -} - -const char* YGWrapToString(const YGWrap value) { - switch (value) { - case YGWrapNoWrap: - return "no-wrap"; - case YGWrapWrap: - return "wrap"; - case YGWrapWrapReverse: - return "wrap-reverse"; - } - return "unknown"; -} diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/yoga/YGEnums.h b/vendor/react-native-gpui/packages/core/ReactCommonOverrides/yoga/YGEnums.h deleted file mode 100644 index 227200c60f..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/yoga/YGEnums.h +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -// @generated by enums.py -// clang-format off -#pragma once -#include - -YG_EXTERN_C_BEGIN - -YG_ENUM_DECL( - YGAlign, - YGAlignAuto, - YGAlignFlexStart, - YGAlignCenter, - YGAlignFlexEnd, - YGAlignStretch, - YGAlignBaseline, - YGAlignSpaceBetween, - YGAlignSpaceAround, - YGAlignSpaceEvenly, - YGAlignStart, - YGAlignEnd) - -YG_ENUM_DECL( - YGBoxSizing, - YGBoxSizingBorderBox, - YGBoxSizingContentBox) - -YG_ENUM_DECL( - YGDimension, - YGDimensionWidth, - YGDimensionHeight) - -YG_ENUM_DECL( - YGDirection, - YGDirectionInherit, - YGDirectionLTR, - YGDirectionRTL) - -YG_ENUM_DECL( - YGDisplay, - YGDisplayFlex, - YGDisplayNone, - YGDisplayContents, - YGDisplayGrid) - -YG_ENUM_DECL( - YGEdge, - YGEdgeLeft, - YGEdgeTop, - YGEdgeRight, - YGEdgeBottom, - YGEdgeStart, - YGEdgeEnd, - YGEdgeHorizontal, - YGEdgeVertical, - YGEdgeAll) - -YG_ENUM_DECL( - YGErrata, - YGErrataNone = 0, - YGErrataStretchFlexBasis = 1, - YGErrataAbsolutePositionWithoutInsetsExcludesPadding = 2, - YGErrataAbsolutePercentAgainstInnerSize = 4, - YGErrataMinSizeUndefinedInsteadOfAuto = 8, - YGErrataFlexBasisAsIntrinsicSize = 16, - YGErrataAll = 2147483647, - YGErrataClassic = 2147483646) -YG_DEFINE_ENUM_FLAG_OPERATORS(YGErrata) - -YG_ENUM_DECL( - YGExperimentalFeature, - YGExperimentalFeatureWebFlexBasis, - YGExperimentalFeatureFixFlexBasisFitContent) - -YG_ENUM_DECL( - YGFlexDirection, - YGFlexDirectionColumn, - YGFlexDirectionColumnReverse, - YGFlexDirectionRow, - YGFlexDirectionRowReverse) - -YG_ENUM_DECL( - YGGridTrackType, - YGGridTrackTypeAuto, - YGGridTrackTypePoints, - YGGridTrackTypePercent, - YGGridTrackTypeFr, - YGGridTrackTypeMinmax) - -YG_ENUM_DECL( - YGGutter, - YGGutterColumn, - YGGutterRow, - YGGutterAll) - -YG_ENUM_DECL( - YGJustify, - YGJustifyAuto, - YGJustifyFlexStart, - YGJustifyCenter, - YGJustifyFlexEnd, - YGJustifySpaceBetween, - YGJustifySpaceAround, - YGJustifySpaceEvenly, - YGJustifyStretch, - YGJustifyStart, - YGJustifyEnd) - -YG_ENUM_DECL( - YGLogLevel, - YGLogLevelError, - YGLogLevelWarn, - YGLogLevelInfo, - YGLogLevelDebug, - YGLogLevelVerbose, - YGLogLevelFatal) - -YG_ENUM_DECL( - YGMeasureMode, - YGMeasureModeUndefined, - YGMeasureModeExactly, - YGMeasureModeAtMost) - -YG_ENUM_DECL( - YGNodeType, - YGNodeTypeDefault, - YGNodeTypeText) - -YG_ENUM_DECL( - YGOverflow, - YGOverflowVisible, - YGOverflowHidden, - YGOverflowScroll) - -YG_ENUM_DECL( - YGPositionType, - YGPositionTypeStatic, - YGPositionTypeRelative, - YGPositionTypeAbsolute) - -YG_ENUM_DECL( - YGUnit, - YGUnitUndefined, - YGUnitPoint, - YGUnitPercent, - YGUnitAuto, - YGUnitMaxContent, - YGUnitFitContent, - YGUnitStretch) - -YG_ENUM_DECL( - YGWrap, - YGWrapNoWrap, - YGWrapWrap, - YGWrapWrapReverse) - -YG_EXTERN_C_END diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/yoga/algorithm/CalculateLayout.cpp b/vendor/react-native-gpui/packages/core/ReactCommonOverrides/yoga/algorithm/CalculateLayout.cpp deleted file mode 100644 index 30d2237b02..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/yoga/algorithm/CalculateLayout.cpp +++ /dev/null @@ -1,2820 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace facebook::yoga { - -std::atomic gCurrentGenerationCount(0); - -void constrainMaxSizeForMode( - const yoga::Node* node, - Direction direction, - FlexDirection axis, - float ownerAxisSize, - float ownerWidth, - /*in_out*/ SizingMode* mode, - /*in_out*/ float* size) { - const FloatOptional maxSize = - node->style().resolvedMaxDimension( - direction, dimension(axis), ownerAxisSize, ownerWidth) + - FloatOptional(node->style().computeMarginForAxis(axis, ownerWidth)); - switch (*mode) { - case SizingMode::StretchFit: - case SizingMode::FitContent: - *size = (maxSize.isUndefined() || *size < maxSize.unwrap()) - ? *size - : maxSize.unwrap(); - break; - case SizingMode::MaxContent: - if (maxSize.isDefined()) { - *mode = SizingMode::FitContent; - *size = maxSize.unwrap(); - } - break; - } -} - -static void computeFlexBasisForChild( - const yoga::Node* const node, - yoga::Node* const child, - const float width, - const SizingMode widthMode, - const float height, - const float ownerWidth, - const float ownerHeight, - const SizingMode heightMode, - const Direction direction, - LayoutData& layoutMarkerData, - const uint32_t depth, - const uint32_t generationCount) { - const FlexDirection mainAxis = - resolveDirection(node->style().flexDirection(), direction); - const bool isMainAxisRow = isRow(mainAxis); - const float mainAxisSize = isMainAxisRow ? width : height; - const float mainAxisOwnerSize = isMainAxisRow ? ownerWidth : ownerHeight; - - float childWidth = YGUndefined; - float childHeight = YGUndefined; - SizingMode childWidthSizingMode; - SizingMode childHeightSizingMode; - - const FloatOptional resolvedFlexBasis = child->resolveFlexBasis( - direction, mainAxis, mainAxisOwnerSize, ownerWidth); - const bool isRowStyleDimDefined = - child->hasDefiniteLength(Dimension::Width, ownerWidth); - const bool isColumnStyleDimDefined = - child->hasDefiniteLength(Dimension::Height, ownerHeight); - - const bool fixFlexBasisFitContent = - node->getConfig()->isExperimentalFeatureEnabled( - ExperimentalFeature::FixFlexBasisFitContent); - - bool useResolvedFlexBasis = - resolvedFlexBasis.isDefined() && yoga::isDefined(mainAxisSize); - if (fixFlexBasisFitContent && resolvedFlexBasis.isDefined() && - resolvedFlexBasis.unwrap() > 0) { - useResolvedFlexBasis = true; - } - - // CSS Flexbox 9.9: while the container is sized from its content, an item - // that can grow contributes its content rather than a basis of zero or a - // percentage. Without the errata the basis is left out of the intrinsic - // measurement here and used again, and recomputed, in the final layout. - const bool basisAsIntrinsicSize = - !child->hasErrata(Errata::FlexBasisAsIntrinsicSize); - if (useResolvedFlexBasis && basisAsIntrinsicSize && - (isMainAxisRow ? widthMode : heightMode) != SizingMode::StretchFit && - child->resolveFlexGrow() > 0 && - (child->style().flexBasis().isPercent() || - resolvedFlexBasis.unwrap() == 0)) { - useResolvedFlexBasis = false; - } - - if (useResolvedFlexBasis) { - if (basisAsIntrinsicSize || - child->getLayout().computedFlexBasis.isUndefined() || - (child->getConfig()->isExperimentalFeatureEnabled( - ExperimentalFeature::WebFlexBasis) && - child->getLayout().computedFlexBasisGeneration != generationCount)) { - const FloatOptional paddingAndBorder = FloatOptional( - paddingAndBorderForAxis(child, mainAxis, direction, ownerWidth)); - child->setLayoutComputedFlexBasis( - yoga::maxOrDefined(resolvedFlexBasis, paddingAndBorder)); - } - } else if (isMainAxisRow && isRowStyleDimDefined) { - // The width is definite, so use that as the flex basis. - const FloatOptional paddingAndBorder = - FloatOptional(paddingAndBorderForAxis( - child, FlexDirection::Row, direction, ownerWidth)); - - child->setLayoutComputedFlexBasis( - yoga::maxOrDefined( - child->getResolvedDimension( - direction, Dimension::Width, ownerWidth, ownerWidth), - paddingAndBorder)); - } else if (!isMainAxisRow && isColumnStyleDimDefined) { - // The height is definite, so use that as the flex basis. - const FloatOptional paddingAndBorder = - FloatOptional(paddingAndBorderForAxis( - child, FlexDirection::Column, direction, ownerWidth)); - child->setLayoutComputedFlexBasis( - yoga::maxOrDefined( - child->getResolvedDimension( - direction, Dimension::Height, ownerHeight, ownerWidth), - paddingAndBorder)); - } else { - // Compute the flex basis and hypothetical main size (i.e. the clamped flex - // basis). - childWidthSizingMode = SizingMode::MaxContent; - childHeightSizingMode = SizingMode::MaxContent; - - auto marginRow = - child->style().computeMarginForAxis(FlexDirection::Row, ownerWidth); - auto marginColumn = - child->style().computeMarginForAxis(FlexDirection::Column, ownerWidth); - - if (isRowStyleDimDefined) { - childWidth = child - ->getResolvedDimension( - direction, Dimension::Width, ownerWidth, ownerWidth) - .unwrap() + - marginRow; - childWidthSizingMode = SizingMode::StretchFit; - } - if (isColumnStyleDimDefined) { - childHeight = - child - ->getResolvedDimension( - direction, Dimension::Height, ownerHeight, ownerWidth) - .unwrap() + - marginColumn; - childHeightSizingMode = SizingMode::StretchFit; - } - - // The W3C spec doesn't say anything about the 'overflow' property, but all - // major browsers appear to implement the following logic. - if ((!isMainAxisRow && node->style().overflow() == Overflow::Scroll) || - node->style().overflow() != Overflow::Scroll) { - if (yoga::isUndefined(childWidth) && yoga::isDefined(width)) { - childWidth = width; - childWidthSizingMode = SizingMode::FitContent; - } - } - - // For height in the main axis (column direction): when the - // FixFlexBasisFitContent feature is enabled, skip FitContent for - // non-measure container children inside scroll subtrees. This makes the - // flex basis independent of content-determined heights, preventing - // unnecessary re-measurement cascades when a sibling changes size in a - // ScrollView, while preserving viewport bounds for wrappers outside the - // scroll subtree. - // - // We only optimize the height (column) axis because text wrapping depends - // on width constraints propagating through container nodes. Removing - // FitContent from the width axis would cause text inside nested - // containers to stop wrapping. - bool applyHeightFitContent = - isMainAxisRow || node->style().overflow() != Overflow::Scroll; - if (fixFlexBasisFitContent) { - bool nodeHasScrollAncestor = false; - for (auto owner = node->getOwner(); owner != nullptr; - owner = owner->getOwner()) { - if (owner->style().overflow() == Overflow::Scroll) { - nodeHasScrollAncestor = true; - break; - } - } - applyHeightFitContent = isMainAxisRow || - ((child->hasMeasureFunc() || !nodeHasScrollAncestor) && - node->style().overflow() != Overflow::Scroll); - } - if (applyHeightFitContent && yoga::isUndefined(childHeight) && - yoga::isDefined(height)) { - childHeight = height; - childHeightSizingMode = SizingMode::FitContent; - } - - const auto& childStyle = child->style(); - if (childStyle.aspectRatio().isDefined()) { - if (!isMainAxisRow && childWidthSizingMode == SizingMode::StretchFit) { - childHeight = marginColumn + - (childWidth - marginRow) / childStyle.aspectRatio().unwrap(); - childHeightSizingMode = SizingMode::StretchFit; - } else if ( - isMainAxisRow && childHeightSizingMode == SizingMode::StretchFit) { - childWidth = marginRow + - (childHeight - marginColumn) * childStyle.aspectRatio().unwrap(); - childWidthSizingMode = SizingMode::StretchFit; - } - } - - // If child has no defined size in the cross axis and is set to stretch, set - // the cross axis to be measured exactly with the available inner width - - const bool hasExactWidth = - yoga::isDefined(width) && widthMode == SizingMode::StretchFit; - const bool childWidthStretch = - resolveChildAlignment(node, child) == Align::Stretch && - childWidthSizingMode != SizingMode::StretchFit; - if (!isMainAxisRow && !isRowStyleDimDefined && hasExactWidth && - childWidthStretch) { - childWidth = width; - childWidthSizingMode = SizingMode::StretchFit; - if (childStyle.aspectRatio().isDefined()) { - childHeight = - (childWidth - marginRow) / childStyle.aspectRatio().unwrap(); - childHeightSizingMode = SizingMode::StretchFit; - } - } - - const bool hasExactHeight = - yoga::isDefined(height) && heightMode == SizingMode::StretchFit; - const bool childHeightStretch = - resolveChildAlignment(node, child) == Align::Stretch && - childHeightSizingMode != SizingMode::StretchFit; - if (isMainAxisRow && !isColumnStyleDimDefined && hasExactHeight && - childHeightStretch) { - childHeight = height; - childHeightSizingMode = SizingMode::StretchFit; - - if (childStyle.aspectRatio().isDefined()) { - childWidth = - (childHeight - marginColumn) * childStyle.aspectRatio().unwrap(); - childWidthSizingMode = SizingMode::StretchFit; - } - } - - constrainMaxSizeForMode( - child, - direction, - FlexDirection::Row, - ownerWidth, - ownerWidth, - &childWidthSizingMode, - &childWidth); - constrainMaxSizeForMode( - child, - direction, - FlexDirection::Column, - ownerHeight, - ownerWidth, - &childHeightSizingMode, - &childHeight); - - // Measure the child - calculateLayoutInternal( - child, - childWidth, - childHeight, - direction, - childWidthSizingMode, - childHeightSizingMode, - ownerWidth, - ownerHeight, - false, - LayoutPassReason::kMeasureChild, - layoutMarkerData, - depth, - generationCount); - - child->setLayoutComputedFlexBasis(FloatOptional( - yoga::maxOrDefined( - child->getLayout().measuredDimension(dimension(mainAxis)), - paddingAndBorderForAxis(child, mainAxis, direction, ownerWidth)))); - } - child->setLayoutComputedFlexBasisGeneration(generationCount); -} - -static void measureNodeWithMeasureFunc( - yoga::Node* const node, - const Direction direction, - float availableWidth, - float availableHeight, - const SizingMode widthSizingMode, - const SizingMode heightSizingMode, - const float ownerWidth, - const float ownerHeight, - LayoutData& layoutMarkerData, - const LayoutPassReason reason) { - yoga::assertFatalWithNode( - node, - node->hasMeasureFunc(), - "Expected node to have custom measure function"); - - if (widthSizingMode == SizingMode::MaxContent) { - availableWidth = YGUndefined; - } - if (heightSizingMode == SizingMode::MaxContent) { - availableHeight = YGUndefined; - } - - const auto& layout = node->getLayout(); - const float paddingAndBorderAxisRow = layout.padding(PhysicalEdge::Left) + - layout.padding(PhysicalEdge::Right) + layout.border(PhysicalEdge::Left) + - layout.border(PhysicalEdge::Right); - const float paddingAndBorderAxisColumn = layout.padding(PhysicalEdge::Top) + - layout.padding(PhysicalEdge::Bottom) + layout.border(PhysicalEdge::Top) + - layout.border(PhysicalEdge::Bottom); - - // We want to make sure we don't call measure with negative size - const float innerWidth = yoga::isUndefined(availableWidth) - ? availableWidth - : yoga::maxOrDefined(0.0f, availableWidth - paddingAndBorderAxisRow); - const float innerHeight = yoga::isUndefined(availableHeight) - ? availableHeight - : yoga::maxOrDefined(0.0f, availableHeight - paddingAndBorderAxisColumn); - - if (widthSizingMode == SizingMode::StretchFit && - heightSizingMode == SizingMode::StretchFit) { - // Don't bother sizing the text if both dimensions are already defined. - node->setLayoutMeasuredDimension( - boundAxis( - node, - FlexDirection::Row, - direction, - availableWidth, - ownerWidth, - ownerWidth), - Dimension::Width); - node->setLayoutMeasuredDimension( - boundAxis( - node, - FlexDirection::Column, - direction, - availableHeight, - ownerHeight, - ownerWidth), - Dimension::Height); - } else { - Event::publish(node); - - // Measure the text under the current constraints. - const YGSize measuredSize = node->measure( - innerWidth, - measureMode(widthSizingMode), - innerHeight, - measureMode(heightSizingMode)); - - layoutMarkerData.measureCallbacks += 1; - layoutMarkerData.measureCallbackReasonsCount[static_cast(reason)] += - 1; - - Event::publish( - node, - {.width = innerWidth, - .widthMeasureMode = unscopedEnum(measureMode(widthSizingMode)), - .height = innerHeight, - .heightMeasureMode = unscopedEnum(measureMode(heightSizingMode)), - .measuredWidth = measuredSize.width, - .measuredHeight = measuredSize.height, - .reason = reason}); - - node->setLayoutMeasuredDimension( - boundAxis( - node, - FlexDirection::Row, - direction, - (widthSizingMode == SizingMode::MaxContent || - widthSizingMode == SizingMode::FitContent) - ? measuredSize.width + paddingAndBorderAxisRow - : availableWidth, - ownerWidth, - ownerWidth), - Dimension::Width); - - node->setLayoutMeasuredDimension( - boundAxis( - node, - FlexDirection::Column, - direction, - (heightSizingMode == SizingMode::MaxContent || - heightSizingMode == SizingMode::FitContent) - ? measuredSize.height + paddingAndBorderAxisColumn - : availableHeight, - ownerHeight, - ownerWidth), - Dimension::Height); - } -} - -// For nodes with no children, use the available values if they were provided, -// or the minimum size as indicated by the padding and border sizes. -static void measureNodeWithoutChildren( - yoga::Node* const node, - const Direction direction, - const float availableWidth, - const float availableHeight, - const SizingMode widthSizingMode, - const SizingMode heightSizingMode, - const float ownerWidth, - const float ownerHeight) { - const auto& layout = node->getLayout(); - - float width = availableWidth; - if (widthSizingMode == SizingMode::MaxContent || - widthSizingMode == SizingMode::FitContent) { - width = layout.padding(PhysicalEdge::Left) + - layout.padding(PhysicalEdge::Right) + - layout.border(PhysicalEdge::Left) + layout.border(PhysicalEdge::Right); - } - node->setLayoutMeasuredDimension( - boundAxis( - node, FlexDirection::Row, direction, width, ownerWidth, ownerWidth), - Dimension::Width); - - float height = availableHeight; - if (heightSizingMode == SizingMode::MaxContent || - heightSizingMode == SizingMode::FitContent) { - height = layout.padding(PhysicalEdge::Top) + - layout.padding(PhysicalEdge::Bottom) + - layout.border(PhysicalEdge::Top) + layout.border(PhysicalEdge::Bottom); - } - node->setLayoutMeasuredDimension( - boundAxis( - node, - FlexDirection::Column, - direction, - height, - ownerHeight, - ownerWidth), - Dimension::Height); -} - -inline bool isFixedSize(float dim, SizingMode sizingMode) { - return sizingMode == SizingMode::StretchFit || - (yoga::isDefined(dim) && sizingMode == SizingMode::FitContent && - dim <= 0.0); -} - -static bool measureNodeWithFixedSize( - yoga::Node* const node, - const Direction direction, - const float availableWidth, - const float availableHeight, - const SizingMode widthSizingMode, - const SizingMode heightSizingMode, - const float ownerWidth, - const float ownerHeight) { - if (isFixedSize(availableWidth, widthSizingMode) && - isFixedSize(availableHeight, heightSizingMode)) { - node->setLayoutMeasuredDimension( - boundAxis( - node, - FlexDirection::Row, - direction, - yoga::isUndefined(availableWidth) || - (widthSizingMode == SizingMode::FitContent && - availableWidth < 0.0f) - ? 0.0f - : availableWidth, - ownerWidth, - ownerWidth), - Dimension::Width); - - node->setLayoutMeasuredDimension( - boundAxis( - node, - FlexDirection::Column, - direction, - yoga::isUndefined(availableHeight) || - (heightSizingMode == SizingMode::FitContent && - availableHeight < 0.0f) - ? 0.0f - : availableHeight, - ownerHeight, - ownerWidth), - Dimension::Height); - return true; - } - - return false; -} - -void zeroOutLayoutRecursively(yoga::Node* const node) { - node->getLayout() = {}; - node->setLayoutDimension(0, Dimension::Width); - node->setLayoutDimension(0, Dimension::Height); - node->setHasNewLayout(true); - - node->cloneChildrenIfNeeded(); - for (const auto child : node->getChildren()) { - zeroOutLayoutRecursively(child); - } -} - -void cleanupContentsNodesRecursively( - yoga::Node* const node, - bool didPerformLayout) { - if (node->hasContentsChildren()) [[unlikely]] { - node->cloneContentsChildrenIfNeeded(); - for (auto child : node->getChildren()) { - if (child->style().display() == Display::Contents) { - child->getLayout() = {}; - child->setLayoutDimension(0, Dimension::Width); - child->setLayoutDimension(0, Dimension::Height); - if (didPerformLayout) { - child->setHasNewLayout(true); - } - child->setDirty(false); - child->cloneChildrenIfNeeded(); - - cleanupContentsNodesRecursively(child, didPerformLayout); - } - } - } -} - -float calculateAvailableInnerDimension( - const yoga::Node* const node, - const Direction direction, - const Dimension dimension, - const float availableDim, - const float paddingAndBorder, - const float ownerDim, - const float ownerWidth) { - float availableInnerDim = availableDim - paddingAndBorder; - // Max dimension overrides predefined dimension value; Min dimension in turn - // overrides both of the above - if (yoga::isDefined(availableInnerDim)) { - // We want to make sure our available height does not violate min and max - // constraints - const FloatOptional minDimensionOptional = - node->style().resolvedMinDimension( - direction, dimension, ownerDim, ownerWidth); - const float minInnerDim = minDimensionOptional.isUndefined() - ? 0.0f - : minDimensionOptional.unwrap() - paddingAndBorder; - - const FloatOptional maxDimensionOptional = - node->style().resolvedMaxDimension( - direction, dimension, ownerDim, ownerWidth); - - const float maxInnerDim = maxDimensionOptional.isUndefined() - ? FLT_MAX - : maxDimensionOptional.unwrap() - paddingAndBorder; - availableInnerDim = yoga::maxOrDefined( - yoga::minOrDefined(availableInnerDim, maxInnerDim), minInnerDim); - } - - return availableInnerDim; -} - -static float computeFlexBasisForChildren( - yoga::Node* const node, - const float availableInnerWidth, - const float availableInnerHeight, - const float ownerWidth, - const float ownerHeight, - SizingMode widthSizingMode, - SizingMode heightSizingMode, - Direction direction, - FlexDirection mainAxis, - bool performLayout, - LayoutData& layoutMarkerData, - const uint32_t depth, - const uint32_t generationCount) { - float totalOuterFlexBasis = 0.0f; - YGNodeRef singleFlexChild = nullptr; - auto children = node->getLayoutChildren(); - SizingMode sizingModeMainDim = - isRow(mainAxis) ? widthSizingMode : heightSizingMode; - // If there is only one child with flexGrow + flexShrink it means we can set - // the computedFlexBasis to 0 instead of measuring and shrinking / flexing the - // child to exactly match the remaining space - if (sizingModeMainDim == SizingMode::StretchFit) { - for (auto child : children) { - if (child->isNodeFlexible()) { - if (singleFlexChild != nullptr || - yoga::inexactEquals(child->resolveFlexGrow(), 0.0f) || - yoga::inexactEquals(child->resolveFlexShrink(), 0.0f)) { - // There is already a flexible child, or this flexible child doesn't - // have flexGrow and flexShrink, abort - singleFlexChild = nullptr; - break; - } else { - singleFlexChild = child; - } - } - } - } - - for (auto child : children) { - child->processDimensions(); - if (child->style().display() == Display::None) { - // Only mutate display: none children during layout passes. Zeroing them - // out during measure-only passes contributes nothing to the measurement, - // but sets `hasNewLayout` on nodes the parent's layout pass may never - // visit (e.g. when its layout is restored from cache, skipping - // `cloneChildrenIfNeeded()`). Such a leaked flag survives the commit and - // is copied into lazily-shared clones, later tripping the ownership - // assertion in `YogaLayoutableShadowNode::layout`. - if (performLayout) { - zeroOutLayoutRecursively(child); - child->setHasNewLayout(true); - child->setDirty(false); - } - continue; - } - if (performLayout) { - // Set the initial position (relative to the owner). - const Direction childDirection = child->resolveDirection(direction); - child->setPosition( - childDirection, availableInnerWidth, availableInnerHeight); - } - - if (child->style().positionType() == PositionType::Absolute) { - continue; - } - if (child == singleFlexChild) { - child->setLayoutComputedFlexBasisGeneration(generationCount); - child->setLayoutComputedFlexBasis(FloatOptional(0)); - } else { - computeFlexBasisForChild( - node, - child, - availableInnerWidth, - widthSizingMode, - availableInnerHeight, - ownerWidth, - ownerHeight, - heightSizingMode, - direction, - layoutMarkerData, - depth, - generationCount); - } - - totalOuterFlexBasis += - (child->getLayout().computedFlexBasis.unwrap() + - child->style().computeMarginForAxis(mainAxis, availableInnerWidth)); - } - - return totalOuterFlexBasis; -} - -// Returns the min-content size of `node` along `requestedAxis`, used by CSS -// Flexbox §4.5 automatic minimum sizing. -// -// Mirrors RenderCore FlexLayout's `AlgorithmBase::computeMinContentSize` / -// `measureMinContentMainSize` pair (see `xplat/flexlayout/flexlayout/ -// FlexboxAlgorithm.h`). Unlike FlexLayout, which crosses a JNI/bridge -// boundary for nested flex containers via thread-local min-content markers, -// Yoga's flex containers are native nodes — so this function recurses -// directly into containers rather than going through a measure callback. -// -// Algorithm: -// * Leaf with measure function: invoke it with `AtMost 0` on the -// requested axis and `Undefined` on the other. Text measure-funcs -// respond with longest-word width; image/collection-like measures -// respond with 0 along their scroll axis. -// * Empty leaf: return 0. -// * Container: iterate in-flow children. For each, take its -// min-content along the container's own main axis (sum into -// `mainTotal`) and along its cross axis (max into `crossMax`), -// plus the child's margins. Add the container's own padding and -// border on both ends of each axis. Project onto `requestedAxis`. -// -// Container-level recursion does no layout writes (no positions, no -// alignment, no flex distribution); only the descendant leaf measure -// callbacks observe state changes (the same ones a normal layout pass -// would invoke). Roughly equivalent to FlexLayout's dedicated -// `computeMinContentSize` cost: one measure call per leaf + linear walk -// per container. -static float computeMinContentMainSize( - yoga::Node* const node, - const FlexDirection requestedAxis, - const Direction ownerDirection, - const float ownerWidth, - const float ownerHeight) { - const bool wantRow = isRow(requestedAxis); - - // 1. Static value wins for any node (leaf or container). Short-circuits - // both the measure callback path AND any container recursion. The most - // common use is `YGNodeSetMinContentWidth(node, 0)` declaring no - // contribution per CSS-Images (Image) or CSS-Overflow (scroll - // containers along their scroll axis). - const FloatOptional staticMin = - wantRow ? node->getMinContentWidth() : node->getMinContentHeight(); - if (staticMin.isDefined()) { - return staticMin.unwrap(); - } - - if (node->hasMeasureFunc()) { - // 2. Dynamic min-content callback if set (for Primitives whose - // min-content depends on state). Otherwise fall back to the regular - // measure function with `AtMost 0`, which text measurers naturally - // answer with longest-word width. - const YGSize size = node->hasMinContentMeasureFunc() - ? node->measureMinContent( - wantRow ? 0.0f : YGUndefined, - wantRow ? MeasureMode::AtMost : MeasureMode::Undefined, - wantRow ? YGUndefined : 0.0f, - wantRow ? MeasureMode::Undefined : MeasureMode::AtMost) - : node->measure( - wantRow ? 0.0f : YGUndefined, - wantRow ? MeasureMode::AtMost : MeasureMode::Undefined, - wantRow ? YGUndefined : 0.0f, - wantRow ? MeasureMode::Undefined : MeasureMode::AtMost); - // Add the leaf's own padding and border, like the container branch below. - const Direction leafDirection = node->resolveDirection(ownerDirection); - const float paddingAndBorder = - node->style().computeFlexStartPaddingAndBorder( - requestedAxis, leafDirection, ownerWidth) + - node->style().computeFlexEndPaddingAndBorder( - requestedAxis, leafDirection, ownerWidth); - return (wantRow ? size.width : size.height) + paddingAndBorder; - } - - if (node->getChildCount() == 0) { - return 0.0f; - } - - const Direction direction = node->resolveDirection(ownerDirection); - const FlexDirection nodeMainAxis = - resolveDirection(node->style().flexDirection(), direction); - const FlexDirection nodeCrossAxis = - resolveCrossDirection(nodeMainAxis, direction); - - float mainTotal = 0.0f; - float crossMax = 0.0f; - - for (size_t i = 0; i < node->getChildCount(); i++) { - auto* const child = node->getChild(i); - if (child->style().display() == Display::None || - child->style().positionType() == PositionType::Absolute) { - continue; - } - - float childMain = computeMinContentMainSize( - child, nodeMainAxis, direction, ownerWidth, ownerHeight); - childMain += child->style().computeMarginForAxis(nodeMainAxis, ownerWidth); - - float childCross = computeMinContentMainSize( - child, nodeCrossAxis, direction, ownerWidth, ownerHeight); - childCross += - child->style().computeMarginForAxis(nodeCrossAxis, ownerWidth); - - mainTotal += childMain; - crossMax = std::max(crossMax, childCross); - } - - mainTotal += node->style().computeFlexStartPaddingAndBorder( - nodeMainAxis, direction, ownerWidth) + - node->style().computeFlexEndPaddingAndBorder( - nodeMainAxis, direction, ownerWidth); - crossMax += node->style().computeFlexStartPaddingAndBorder( - nodeCrossAxis, direction, ownerWidth) + - node->style().computeFlexEndPaddingAndBorder( - nodeCrossAxis, direction, ownerWidth); - - const bool nodeMainIsRow = isRow(nodeMainAxis); - const float widthMin = nodeMainIsRow ? mainTotal : crossMax; - const float heightMin = nodeMainIsRow ? crossMax : mainTotal; - return wantRow ? widthMin : heightMin; -} - -// Computes the CSS Flexbox §4.5 automatic minimum main-axis size for -// `child`. Returns Undefined when no auto-min applies (feature off, explicit -// `min-{w,h}` already set, or `display:none`); 0 when the item's own -// `overflow != visible` (the spec's per-item escape hatch); or a concrete -// floor otherwise. -// -// Floor = min(content-size, specified-size) capped by max-size, with the -// transferred (aspect-ratio × cross-size) suggestion replacing the -// specified-size leg when the item has an aspect ratio but no specified -// main size. See https://www.w3.org/TR/css-flexbox-1/#min-size-auto. -static FloatOptional computeAutoMinMainSize( - yoga::Node* const child, - const FlexDirection mainAxis, - const Direction direction, - const float ownerMainAxisSize, - const float ownerWidth, - const float ownerHeight) { - if (child->hasErrata(Errata::MinSizeUndefinedInsteadOfAuto)) { - return FloatOptional{}; - } - if (child->style().display() == Display::None) { - return FloatOptional{}; - } - // Explicit `min-{w,h}` (including `0`) wins over auto. This is the - // CSS-spec opt-out (§4.5). - if (child->style().minDimension(dimension(mainAxis)).isDefined()) { - return FloatOptional{}; - } - // Per CSS §4.5: a flex item whose own `overflow` is not `visible` gets - // auto-min = 0 (let scroll/clip handle overflow rather than enforce a - // content-based minimum). - if (child->style().overflow() != Overflow::Visible) { - return FloatOptional{0.0f}; - } - - const Dimension mainDim = dimension(mainAxis); - const Dimension crossDim = - isRow(mainAxis) ? Dimension::Height : Dimension::Width; - const bool isMainAxisRow = isRow(mainAxis); - - // Specified size suggestion: the resolved main-axis style dimension. - const FloatOptional specifiedMain = child->getResolvedDimension( - direction, mainDim, ownerMainAxisSize, ownerWidth); - - // Transferred size suggestion: cross × aspect-ratio, if both are definite. - FloatOptional transferredMain; - const FloatOptional aspectRatio = child->style().aspectRatio(); - if (aspectRatio.isDefined()) { - const float crossOwner = isMainAxisRow ? ownerHeight : ownerWidth; - const FloatOptional crossResolved = child->getResolvedDimension( - direction, crossDim, crossOwner, ownerWidth); - if (crossResolved.isDefined()) { - const float ratio = aspectRatio.unwrap(); - const float crossValue = crossResolved.unwrap(); - transferredMain = FloatOptional{ - isMainAxisRow ? crossValue * ratio : crossValue / ratio}; - } - } - - // Content size suggestion: probe via min-content recursion. - const FloatOptional contentMain = FloatOptional{computeMinContentMainSize( - child, mainAxis, direction, ownerWidth, ownerHeight)}; - - // Combine per §4.5: floor = min(content, specified) when specified is - // definite; otherwise floor = min(content, transferred) when transferred - // applies (item has aspect-ratio + definite cross + no specified main); - // else floor = content. - FloatOptional floor = contentMain; - if (specifiedMain.isDefined()) { - if (floor.isUndefined() || specifiedMain < floor) { - floor = specifiedMain; - } - } else if (transferredMain.isDefined()) { - if (floor.isUndefined() || transferredMain < floor) { - floor = transferredMain; - } - } - - // §4.5: cap by the max main size. - const FloatOptional maxMain = child->style().resolvedMaxDimension( - direction, mainDim, ownerMainAxisSize, ownerWidth); - if (maxMain.isDefined() && floor > maxMain) { - floor = maxMain; - } - - if (floor.isUndefined() || floor.unwrap() < 0.0f) { - floor = FloatOptional{0.0f}; - } - return floor; -} - -// boundAxis with an additional lower bound from `child`'s cached -// `computedAutoMinMainSize`, applied on the main axis only. Used inside -// the flex-shrink distribution to honor CSS §4.5 auto-min while preserving -// the existing min/max/padding-and-border clamping. -static float boundAxisWithAutoMin( - const yoga::Node* const child, - const FlexDirection axis, - const Direction direction, - const float value, - const float axisSize, - const float widthSize) { - float bounded = boundAxis(child, axis, direction, value, axisSize, widthSize); - const FloatOptional autoMin = child->getLayout().computedAutoMinMainSize; - if (autoMin.isDefined() && bounded < autoMin.unwrap()) { - bounded = autoMin.unwrap(); - } - return bounded; -} - -// It distributes the free space to the flexible items and ensures that the size -// of the flex items abide the min and max constraints. At the end of this -// function the child nodes would have proper size. Prior using this function -// please ensure that distributeFreeSpaceFirstPass is called. -static float distributeFreeSpaceSecondPass( - FlexLine& flexLine, - yoga::Node* const node, - const FlexDirection mainAxis, - const FlexDirection crossAxis, - const Direction direction, - const float ownerWidth, - const float mainAxisOwnerSize, - const float availableInnerMainDim, - const float availableInnerCrossDim, - const float availableInnerWidth, - const float availableInnerHeight, - const bool mainAxisOverflows, - const SizingMode sizingModeCrossDim, - const bool performLayout, - LayoutData& layoutMarkerData, - const uint32_t depth, - const uint32_t generationCount) { - float childFlexBasis = 0; - float flexShrinkScaledFactor = 0; - float flexGrowFactor = 0; - float deltaFreeSpace = 0; - const bool isMainAxisRow = isRow(mainAxis); - const bool isNodeFlexWrap = node->style().flexWrap() != Wrap::NoWrap; - - for (auto currentLineChild : flexLine.itemsInFlow) { - childFlexBasis = boundAxisWithinMinAndMax( - currentLineChild, - direction, - mainAxis, - currentLineChild->getLayout().computedFlexBasis, - mainAxisOwnerSize, - ownerWidth) - .unwrap(); - float updatedMainSize = childFlexBasis; - - if (yoga::isDefined(flexLine.layout.remainingFreeSpace) && - flexLine.layout.remainingFreeSpace < 0) { - flexShrinkScaledFactor = - -currentLineChild->resolveFlexShrink() * childFlexBasis; - // Is this child able to shrink? - if (flexShrinkScaledFactor != 0) { - float childSize = YGUndefined; - - if (yoga::isDefined(flexLine.layout.totalFlexShrinkScaledFactors) && - flexLine.layout.totalFlexShrinkScaledFactors == 0) { - childSize = childFlexBasis + flexShrinkScaledFactor; - } else { - childSize = childFlexBasis + - (flexLine.layout.remainingFreeSpace / - flexLine.layout.totalFlexShrinkScaledFactors) * - flexShrinkScaledFactor; - } - - updatedMainSize = boundAxisWithAutoMin( - currentLineChild, - mainAxis, - direction, - childSize, - availableInnerMainDim, - availableInnerWidth); - } - } else if ( - yoga::isDefined(flexLine.layout.remainingFreeSpace) && - flexLine.layout.remainingFreeSpace > 0) { - flexGrowFactor = currentLineChild->resolveFlexGrow(); - - // Is this child able to grow? - if (!std::isnan(flexGrowFactor) && flexGrowFactor != 0) { - updatedMainSize = boundAxisWithAutoMin( - currentLineChild, - mainAxis, - direction, - childFlexBasis + - flexLine.layout.remainingFreeSpace / - flexLine.layout.totalFlexGrowFactors * flexGrowFactor, - availableInnerMainDim, - availableInnerWidth); - } - } - - deltaFreeSpace += updatedMainSize - childFlexBasis; - - const float marginMain = currentLineChild->style().computeMarginForAxis( - mainAxis, availableInnerWidth); - const float marginCross = currentLineChild->style().computeMarginForAxis( - crossAxis, availableInnerWidth); - - float childCrossSize = YGUndefined; - float childMainSize = updatedMainSize + marginMain; - SizingMode childCrossSizingMode; - SizingMode childMainSizingMode = SizingMode::StretchFit; - - const auto& childStyle = currentLineChild->style(); - if (childStyle.aspectRatio().isDefined()) { - childCrossSize = isMainAxisRow - ? (childMainSize - marginMain) / childStyle.aspectRatio().unwrap() - : (childMainSize - marginMain) * childStyle.aspectRatio().unwrap(); - childCrossSizingMode = SizingMode::StretchFit; - - childCrossSize += marginCross; - } else if ( - !std::isnan(availableInnerCrossDim) && - !currentLineChild->hasDefiniteLength( - dimension(crossAxis), availableInnerCrossDim) && - sizingModeCrossDim == SizingMode::StretchFit && - !(isNodeFlexWrap && mainAxisOverflows) && - resolveChildAlignment(node, currentLineChild) == Align::Stretch && - !currentLineChild->style().flexStartMarginIsAuto( - crossAxis, direction) && - !currentLineChild->style().flexEndMarginIsAuto(crossAxis, direction)) { - childCrossSize = availableInnerCrossDim; - childCrossSizingMode = SizingMode::StretchFit; - } else if (!currentLineChild->hasDefiniteLength( - dimension(crossAxis), availableInnerCrossDim)) { - childCrossSize = availableInnerCrossDim; - childCrossSizingMode = yoga::isUndefined(childCrossSize) - ? SizingMode::MaxContent - : SizingMode::FitContent; - } else { - childCrossSize = currentLineChild - ->getResolvedDimension( - direction, - dimension(crossAxis), - availableInnerCrossDim, - availableInnerWidth) - .unwrap() + - marginCross; - const bool isLoosePercentageMeasurement = - currentLineChild->getProcessedDimension(dimension(crossAxis)) - .isPercent() && - sizingModeCrossDim != SizingMode::StretchFit; - childCrossSizingMode = - yoga::isUndefined(childCrossSize) || isLoosePercentageMeasurement - ? SizingMode::MaxContent - : SizingMode::StretchFit; - } - - constrainMaxSizeForMode( - currentLineChild, - direction, - mainAxis, - availableInnerMainDim, - availableInnerWidth, - &childMainSizingMode, - &childMainSize); - constrainMaxSizeForMode( - currentLineChild, - direction, - crossAxis, - availableInnerCrossDim, - availableInnerWidth, - &childCrossSizingMode, - &childCrossSize); - - const bool requiresStretchLayout = - !currentLineChild->hasDefiniteLength( - dimension(crossAxis), availableInnerCrossDim) && - resolveChildAlignment(node, currentLineChild) == Align::Stretch && - !currentLineChild->style().flexStartMarginIsAuto( - crossAxis, direction) && - !currentLineChild->style().flexEndMarginIsAuto(crossAxis, direction); - - const float childWidth = isMainAxisRow ? childMainSize : childCrossSize; - const float childHeight = !isMainAxisRow ? childMainSize : childCrossSize; - - const SizingMode childWidthSizingMode = - isMainAxisRow ? childMainSizingMode : childCrossSizingMode; - const SizingMode childHeightSizingMode = - !isMainAxisRow ? childMainSizingMode : childCrossSizingMode; - - const bool isLayoutPass = performLayout && !requiresStretchLayout; - // Recursively call the layout algorithm for this child with the updated - // main size. - calculateLayoutInternal( - currentLineChild, - childWidth, - childHeight, - node->getLayout().direction(), - childWidthSizingMode, - childHeightSizingMode, - availableInnerWidth, - availableInnerHeight, - isLayoutPass, - isLayoutPass ? LayoutPassReason::kFlexLayout - : LayoutPassReason::kFlexMeasure, - layoutMarkerData, - depth, - generationCount); - node->setLayoutHadOverflow( - node->getLayout().hadOverflow() || - currentLineChild->getLayout().hadOverflow()); - } - return deltaFreeSpace; -} - -// It distributes the free space to the flexible items.For those flexible items -// whose min and max constraints are triggered, those flex item's clamped size -// is removed from the remaingfreespace. -static void distributeFreeSpaceFirstPass( - FlexLine& flexLine, - const Direction direction, - const FlexDirection mainAxis, - const float ownerWidth, - const float mainAxisOwnerSize, - const float availableInnerMainDim, - const float availableInnerWidth) { - float flexShrinkScaledFactor = 0; - float flexGrowFactor = 0; - float baseMainSize = 0; - float boundMainSize = 0; - float deltaFreeSpace = 0; - - for (auto currentLineChild : flexLine.itemsInFlow) { - float childFlexBasis = boundAxisWithinMinAndMax( - currentLineChild, - direction, - mainAxis, - currentLineChild->getLayout().computedFlexBasis, - mainAxisOwnerSize, - ownerWidth) - .unwrap(); - - if (flexLine.layout.remainingFreeSpace < 0) { - flexShrinkScaledFactor = - -currentLineChild->resolveFlexShrink() * childFlexBasis; - - // Is this child able to shrink? - if (yoga::isDefined(flexShrinkScaledFactor) && - flexShrinkScaledFactor != 0) { - baseMainSize = childFlexBasis + - flexLine.layout.remainingFreeSpace / - flexLine.layout.totalFlexShrinkScaledFactors * - flexShrinkScaledFactor; - boundMainSize = boundAxisWithAutoMin( - currentLineChild, - mainAxis, - direction, - baseMainSize, - availableInnerMainDim, - availableInnerWidth); - if (yoga::isDefined(baseMainSize) && yoga::isDefined(boundMainSize) && - baseMainSize != boundMainSize) { - // By excluding this item's size and flex factor from remaining, this - // item's min/max constraints should also trigger in the second pass - // resulting in the item's size calculation being identical in the - // first and second passes. - deltaFreeSpace += boundMainSize - childFlexBasis; - flexLine.layout.totalFlexShrinkScaledFactors -= - (-currentLineChild->resolveFlexShrink() * - currentLineChild->getLayout().computedFlexBasis.unwrap()); - } - } - } else if ( - yoga::isDefined(flexLine.layout.remainingFreeSpace) && - flexLine.layout.remainingFreeSpace > 0) { - flexGrowFactor = currentLineChild->resolveFlexGrow(); - - // Is this child able to grow? - if (yoga::isDefined(flexGrowFactor) && flexGrowFactor != 0) { - baseMainSize = childFlexBasis + - flexLine.layout.remainingFreeSpace / - flexLine.layout.totalFlexGrowFactors * flexGrowFactor; - boundMainSize = boundAxis( - currentLineChild, - mainAxis, - direction, - baseMainSize, - availableInnerMainDim, - availableInnerWidth); - - if (yoga::isDefined(baseMainSize) && yoga::isDefined(boundMainSize) && - baseMainSize != boundMainSize) { - // By excluding this item's size and flex factor from remaining, this - // item's min/max constraints should also trigger in the second pass - // resulting in the item's size calculation being identical in the - // first and second passes. - deltaFreeSpace += boundMainSize - childFlexBasis; - flexLine.layout.totalFlexGrowFactors -= flexGrowFactor; - } - } - } - } - flexLine.layout.remainingFreeSpace -= deltaFreeSpace; -} - -// Do two passes over the flex items to figure out how to distribute the -// remaining space. -// -// The first pass finds the items whose min/max constraints trigger, freezes -// them at those sizes, and excludes those sizes from the remaining space. -// -// The second pass sets the size of each flexible item. It distributes the -// remaining space amongst the items whose min/max constraints didn't trigger in -// the first pass. For the other items, it sets their sizes by forcing their -// min/max constraints to trigger again. -// -// This two pass approach for resolving min/max constraints deviates from the -// spec. The spec -// (https://www.w3.org/TR/CSS-flexbox-1/#resolve-flexible-lengths) describes a -// process that needs to be repeated a variable number of times. The algorithm -// implemented here won't handle all cases but it was simpler to implement and -// it mitigates performance concerns because we know exactly how many passes -// it'll do. -// -// At the end of this function the child nodes would have the proper size -// assigned to them. -// -static void resolveFlexibleLength( - yoga::Node* const node, - FlexLine& flexLine, - const FlexDirection mainAxis, - const FlexDirection crossAxis, - const Direction direction, - const float ownerWidth, - const float mainAxisOwnerSize, - const float availableInnerMainDim, - const float availableInnerCrossDim, - const float availableInnerWidth, - const float availableInnerHeight, - const bool mainAxisOverflows, - const SizingMode sizingModeCrossDim, - const bool performLayout, - LayoutData& layoutMarkerData, - const uint32_t depth, - const uint32_t generationCount) { - const float originalFreeSpace = flexLine.layout.remainingFreeSpace; - - // CSS Flexbox §4.5: compute each item's automatic minimum main-axis size - // up front so the bounding helpers below can floor shrunk values. - // computeAutoMinMainSize returns Undefined when the feature is off or an - // explicit `min-{w,h}` already pins the floor, in which case the cached - // value is also Undefined and `boundAxisWithAutoMin` reduces to `boundAxis`. - if (!node->hasErrata(Errata::MinSizeUndefinedInsteadOfAuto)) { - for (auto currentLineChild : flexLine.itemsInFlow) { - currentLineChild->getLayout().computedAutoMinMainSize = - computeAutoMinMainSize( - currentLineChild, - mainAxis, - direction, - mainAxisOwnerSize, - availableInnerWidth, - availableInnerHeight); - } - } else { - for (auto currentLineChild : flexLine.itemsInFlow) { - currentLineChild->getLayout().computedAutoMinMainSize = FloatOptional{}; - } - } - - // First pass: detect the flex items whose min/max constraints trigger - distributeFreeSpaceFirstPass( - flexLine, - direction, - mainAxis, - ownerWidth, - mainAxisOwnerSize, - availableInnerMainDim, - availableInnerWidth); - - // Second pass: resolve the sizes of the flexible items - const float distributedFreeSpace = distributeFreeSpaceSecondPass( - flexLine, - node, - mainAxis, - crossAxis, - direction, - ownerWidth, - mainAxisOwnerSize, - availableInnerMainDim, - availableInnerCrossDim, - availableInnerWidth, - availableInnerHeight, - mainAxisOverflows, - sizingModeCrossDim, - performLayout, - layoutMarkerData, - depth, - generationCount); - - flexLine.layout.remainingFreeSpace = originalFreeSpace - distributedFreeSpace; -} - -static void justifyMainAxis( - yoga::Node* const node, - FlexLine& flexLine, - const FlexDirection mainAxis, - const FlexDirection crossAxis, - const Direction direction, - const SizingMode sizingModeMainDim, - const SizingMode sizingModeCrossDim, - const float mainAxisOwnerSize, - const float ownerWidth, - const float availableInnerMainDim, - const float availableInnerCrossDim, - const float availableInnerWidth, - const bool performLayout) { - const auto& style = node->style(); - - const float leadingPaddingAndBorderMain = - node->style().computeFlexStartPaddingAndBorder( - mainAxis, direction, ownerWidth); - const float trailingPaddingAndBorderMain = - node->style().computeFlexEndPaddingAndBorder( - mainAxis, direction, ownerWidth); - - const float gap = - node->style().computeGapForAxis(mainAxis, availableInnerMainDim); - // If we are using "at most" rules in the main axis, make sure that - // remainingFreeSpace is 0 when min main dimension is not given - if (sizingModeMainDim == SizingMode::FitContent && - flexLine.layout.remainingFreeSpace > 0) { - if (style.minDimension(dimension(mainAxis)).isDefined() && - style - .resolvedMinDimension( - direction, dimension(mainAxis), mainAxisOwnerSize, ownerWidth) - .isDefined()) { - // This condition makes sure that if the size of main dimension(after - // considering child nodes main dim, leading and trailing padding etc) - // falls below min dimension, then the remainingFreeSpace is reassigned - // considering the min dimension - - // `minAvailableMainDim` denotes minimum available space in which child - // can be laid out, it will exclude space consumed by padding and border. - const float minAvailableMainDim = - style - .resolvedMinDimension( - direction, dimension(mainAxis), mainAxisOwnerSize, ownerWidth) - .unwrap() - - leadingPaddingAndBorderMain - trailingPaddingAndBorderMain; - const float occupiedSpaceByChildNodes = - availableInnerMainDim - flexLine.layout.remainingFreeSpace; - flexLine.layout.remainingFreeSpace = yoga::maxOrDefined( - 0.0f, minAvailableMainDim - occupiedSpaceByChildNodes); - } else { - flexLine.layout.remainingFreeSpace = 0; - } - } - - // In order to position the elements in the main axis, we have two controls. - // The space between the beginning and the first element and the space between - // each two elements. - float leadingMainDim = 0; - float betweenMainDim = gap; - const Justify justifyContent = flexLine.layout.remainingFreeSpace >= 0 - ? node->style().justifyContent() - : fallbackAlignment(node->style().justifyContent()); - - if (flexLine.numberOfAutoMargins == 0) { - switch (justifyContent) { - case Justify::Start: - case Justify::End: - case Justify::Auto: - // No-Op - break; - case Justify::Stretch: - // No-Op - break; - case Justify::Center: - leadingMainDim = flexLine.layout.remainingFreeSpace / 2; - break; - case Justify::FlexEnd: - leadingMainDim = flexLine.layout.remainingFreeSpace; - break; - case Justify::SpaceBetween: - if (flexLine.itemsInFlow.size() > 1) { - betweenMainDim += flexLine.layout.remainingFreeSpace / - static_cast(flexLine.itemsInFlow.size() - 1); - } - break; - case Justify::SpaceEvenly: - // Space is distributed evenly across all elements - leadingMainDim = flexLine.layout.remainingFreeSpace / - static_cast(flexLine.itemsInFlow.size() + 1); - betweenMainDim += leadingMainDim; - break; - case Justify::SpaceAround: - // Space on the edges is half of the space between elements - leadingMainDim = 0.5f * flexLine.layout.remainingFreeSpace / - static_cast(flexLine.itemsInFlow.size()); - betweenMainDim += leadingMainDim * 2; - break; - case Justify::FlexStart: - break; - } - } - - flexLine.layout.mainDim = leadingPaddingAndBorderMain + leadingMainDim; - flexLine.layout.crossDim = 0; - - float maxAscentForCurrentLine = 0; - float maxDescentForCurrentLine = 0; - bool isNodeBaselineLayout = isBaselineLayout(node); - for (auto child : flexLine.itemsInFlow) { - const LayoutResults& childLayout = child->getLayout(); - if (child->style().flexStartMarginIsAuto(mainAxis, direction) && - flexLine.layout.remainingFreeSpace > 0.0f) { - flexLine.layout.mainDim += flexLine.layout.remainingFreeSpace / - static_cast(flexLine.numberOfAutoMargins); - } - - if (performLayout) { - child->setLayoutPosition( - childLayout.position(flexStartEdge(mainAxis)) + - flexLine.layout.mainDim, - flexStartEdge(mainAxis)); - } - - if (child != flexLine.itemsInFlow.back()) { - flexLine.layout.mainDim += betweenMainDim; - } - - if (child->style().flexEndMarginIsAuto(mainAxis, direction) && - flexLine.layout.remainingFreeSpace > 0.0f) { - flexLine.layout.mainDim += flexLine.layout.remainingFreeSpace / - static_cast(flexLine.numberOfAutoMargins); - } - bool canSkipFlex = - !performLayout && sizingModeCrossDim == SizingMode::StretchFit; - if (canSkipFlex) { - // If we skipped the flex step, then we can't rely on the measuredDims - // because they weren't computed. This means we can't call - // dimensionWithMargin. - flexLine.layout.mainDim += - child->style().computeMarginForAxis(mainAxis, availableInnerWidth) + - boundAxisWithinMinAndMax( - child, - direction, - mainAxis, - childLayout.computedFlexBasis, - mainAxisOwnerSize, - ownerWidth) - .unwrap(); - flexLine.layout.crossDim = availableInnerCrossDim; - } else { - // The main dimension is the sum of all the elements dimension plus - // the spacing. - flexLine.layout.mainDim += - child->dimensionWithMargin(mainAxis, availableInnerWidth); - - if (isNodeBaselineLayout) { - // If the child is baseline aligned then the cross dimension is - // calculated by adding maxAscent and maxDescent from the baseline. - const float ascent = calculateBaseline(child) + - child->style().computeFlexStartMargin( - FlexDirection::Column, direction, availableInnerWidth); - const float descent = - child->getLayout().measuredDimension(Dimension::Height) + - child->style().computeMarginForAxis( - FlexDirection::Column, availableInnerWidth) - - ascent; - - maxAscentForCurrentLine = - yoga::maxOrDefined(maxAscentForCurrentLine, ascent); - maxDescentForCurrentLine = - yoga::maxOrDefined(maxDescentForCurrentLine, descent); - } else { - // The cross dimension is the max of the elements dimension since - // there can only be one element in that cross dimension in the case - // when the items are not baseline aligned - flexLine.layout.crossDim = yoga::maxOrDefined( - flexLine.layout.crossDim, - child->dimensionWithMargin(crossAxis, availableInnerWidth)); - } - } - } - flexLine.layout.mainDim += trailingPaddingAndBorderMain; - - if (isNodeBaselineLayout) { - flexLine.layout.crossDim = - maxAscentForCurrentLine + maxDescentForCurrentLine; - } -} - -// -// This is the main routine that implements a subset of the flexbox layout -// algorithm described in the W3C CSS documentation: -// https://www.w3.org/TR/CSS3-flexbox/. -// -// Limitations of this algorithm, compared to the full standard: -// * Display property is always assumed to be 'flex' except for Text nodes, -// which are assumed to be 'inline-flex'. -// * The 'zIndex' property (or any form of z ordering) is not supported. Nodes -// are stacked in document order. -// * The 'order' property is not supported. The order of flex items is always -// defined by document order. -// * The 'visibility' property is always assumed to be 'visible'. Values of -// 'collapse' and 'hidden' are not supported. -// * There is no support for forced breaks. -// * It does not support vertical inline directions (top-to-bottom or -// bottom-to-top text). -// -// Deviations from standard: -// * Section 4.5 of the spec indicates that all flex items have a default -// minimum main size. For text blocks, for example, this is the width of the -// widest word. Calculating the minimum width is expensive, so we forego it -// and assume a default minimum main size of 0. -// * Min/Max sizes in the main axis are not honored when resolving flexible -// lengths. -// * The spec indicates that the default value for 'flexDirection' is 'row', -// but the algorithm below assumes a default of 'column'. -// -// Input parameters: -// - node: current node to be sized and laid out -// - availableWidth & availableHeight: available size to be used for sizing -// the node or YGUndefined if the size is not available; interpretation -// depends on layout flags -// - ownerDirection: the inline (text) direction within the owner -// (left-to-right or right-to-left) -// - widthSizingMode: indicates the sizing rules for the width (see below -// for explanation) -// - heightSizingMode: indicates the sizing rules for the height (see below -// for explanation) -// - performLayout: specifies whether the caller is interested in just the -// dimensions of the node or it requires the entire node and its subtree to -// be laid out (with final positions) -// -// Details: -// This routine is called recursively to lay out subtrees of flexbox -// elements. It uses the information in node.style, which is treated as a -// read-only input. It is responsible for setting the layout.direction and -// layout.measuredDimensions fields for the input node as well as the -// layout.position and layout.lineIndex fields for its child nodes. The -// layout.measuredDimensions field includes any border or padding for the -// node but does not include margins. -// -// When calling calculateLayoutImpl and calculateLayoutInternal, if the -// caller passes an available size of undefined then it must also pass a -// measure mode of SizingMode::MaxContent in that dimension. -// -static void calculateLayoutImpl( - yoga::Node* const node, - const float availableWidth, - const float availableHeight, - const Direction ownerDirection, - const SizingMode widthSizingMode, - const SizingMode heightSizingMode, - const float ownerWidth, - const float ownerHeight, - const bool performLayout, - const LayoutPassReason reason, - LayoutData& layoutMarkerData, - const uint32_t depth, - const uint32_t generationCount) { - yoga::assertFatalWithNode( - node, - yoga::isUndefined(availableWidth) - ? widthSizingMode == SizingMode::MaxContent - : true, - "availableWidth is indefinite so widthSizingMode must be " - "SizingMode::MaxContent"); - yoga::assertFatalWithNode( - node, - yoga::isUndefined(availableHeight) - ? heightSizingMode == SizingMode::MaxContent - : true, - "availableHeight is indefinite so heightSizingMode must be " - "SizingMode::MaxContent"); - - (performLayout ? layoutMarkerData.layouts : layoutMarkerData.measures) += 1; - - // Set the resolved resolution in the node's layout. - const Direction direction = node->resolveDirection(ownerDirection); - node->setLayoutDirection(direction); - - const FlexDirection flexRowDirection = - resolveDirection(FlexDirection::Row, direction); - const FlexDirection flexColumnDirection = - resolveDirection(FlexDirection::Column, direction); - - const auto startEdge = - direction == Direction::LTR ? PhysicalEdge::Left : PhysicalEdge::Right; - const auto endEdge = - direction == Direction::LTR ? PhysicalEdge::Right : PhysicalEdge::Left; - - const float marginRowLeading = node->style().computeInlineStartMargin( - flexRowDirection, direction, ownerWidth); - node->setLayoutMargin(marginRowLeading, startEdge); - const float marginRowTrailing = node->style().computeInlineEndMargin( - flexRowDirection, direction, ownerWidth); - node->setLayoutMargin(marginRowTrailing, endEdge); - const float marginColumnLeading = node->style().computeInlineStartMargin( - flexColumnDirection, direction, ownerWidth); - node->setLayoutMargin(marginColumnLeading, PhysicalEdge::Top); - const float marginColumnTrailing = node->style().computeInlineEndMargin( - flexColumnDirection, direction, ownerWidth); - node->setLayoutMargin(marginColumnTrailing, PhysicalEdge::Bottom); - - const float marginAxisRow = marginRowLeading + marginRowTrailing; - const float marginAxisColumn = marginColumnLeading + marginColumnTrailing; - - node->setLayoutBorder( - node->style().computeInlineStartBorder(flexRowDirection, direction), - startEdge); - node->setLayoutBorder( - node->style().computeInlineEndBorder(flexRowDirection, direction), - endEdge); - node->setLayoutBorder( - node->style().computeInlineStartBorder(flexColumnDirection, direction), - PhysicalEdge::Top); - node->setLayoutBorder( - node->style().computeInlineEndBorder(flexColumnDirection, direction), - PhysicalEdge::Bottom); - - node->setLayoutPadding( - node->style().computeInlineStartPadding( - flexRowDirection, direction, ownerWidth), - startEdge); - node->setLayoutPadding( - node->style().computeInlineEndPadding( - flexRowDirection, direction, ownerWidth), - endEdge); - node->setLayoutPadding( - node->style().computeInlineStartPadding( - flexColumnDirection, direction, ownerWidth), - PhysicalEdge::Top); - node->setLayoutPadding( - node->style().computeInlineEndPadding( - flexColumnDirection, direction, ownerWidth), - PhysicalEdge::Bottom); - - if (node->hasMeasureFunc()) { - measureNodeWithMeasureFunc( - node, - direction, - availableWidth - marginAxisRow, - availableHeight - marginAxisColumn, - widthSizingMode, - heightSizingMode, - ownerWidth, - ownerHeight, - layoutMarkerData, - reason); - - // Clean and update all display: contents nodes with a direct path to the - // current node as they will not be traversed - cleanupContentsNodesRecursively(node, performLayout); - return; - } - - const auto childCount = node->getLayoutChildCount(); - if (childCount == 0) { - measureNodeWithoutChildren( - node, - direction, - availableWidth - marginAxisRow, - availableHeight - marginAxisColumn, - widthSizingMode, - heightSizingMode, - ownerWidth, - ownerHeight); - - // Clean and update all display: contents nodes with a direct path to the - // current node as they will not be traversed - cleanupContentsNodesRecursively(node, performLayout); - return; - } - - // If we're not being asked to perform a full layout we can skip the algorithm - // if we already know the size - if (!performLayout && - measureNodeWithFixedSize( - node, - direction, - availableWidth - marginAxisRow, - availableHeight - marginAxisColumn, - widthSizingMode, - heightSizingMode, - ownerWidth, - ownerHeight)) { - // Clean and update all display: contents nodes with a direct path to the - // current node as they will not be traversed - cleanupContentsNodesRecursively(node, /* didPerformLayout */ false); - return; - } - - // At this point we know we're going to perform work. Ensure that each child - // has a mutable copy. - node->cloneChildrenIfNeeded(); - // Reset layout flags, as they could have changed. - node->setLayoutHadOverflow(false); - - // Clean and update all display: contents nodes with a direct path to the - // current node as they will not be traversed - cleanupContentsNodesRecursively(node, performLayout); - - // STEP 1: CALCULATE VALUES FOR REMAINDER OF ALGORITHM - const FlexDirection mainAxis = - resolveDirection(node->style().flexDirection(), direction); - const FlexDirection crossAxis = resolveCrossDirection(mainAxis, direction); - const bool isMainAxisRow = isRow(mainAxis); - const bool isNodeFlexWrap = node->style().flexWrap() != Wrap::NoWrap; - - const float mainAxisOwnerSize = isMainAxisRow ? ownerWidth : ownerHeight; - const float crossAxisOwnerSize = isMainAxisRow ? ownerHeight : ownerWidth; - - const float paddingAndBorderAxisMain = - paddingAndBorderForAxis(node, mainAxis, direction, ownerWidth); - const float paddingAndBorderAxisCross = - paddingAndBorderForAxis(node, crossAxis, direction, ownerWidth); - const float leadingPaddingAndBorderCross = - node->style().computeFlexStartPaddingAndBorder( - crossAxis, direction, ownerWidth); - - SizingMode sizingModeMainDim = - isMainAxisRow ? widthSizingMode : heightSizingMode; - SizingMode sizingModeCrossDim = - isMainAxisRow ? heightSizingMode : widthSizingMode; - - const float paddingAndBorderAxisRow = - isMainAxisRow ? paddingAndBorderAxisMain : paddingAndBorderAxisCross; - const float paddingAndBorderAxisColumn = - isMainAxisRow ? paddingAndBorderAxisCross : paddingAndBorderAxisMain; - - // STEP 2: DETERMINE AVAILABLE SIZE IN MAIN AND CROSS DIRECTIONS - - float availableInnerWidth = calculateAvailableInnerDimension( - node, - direction, - Dimension::Width, - availableWidth - marginAxisRow, - paddingAndBorderAxisRow, - ownerWidth, - ownerWidth); - float availableInnerHeight = calculateAvailableInnerDimension( - node, - direction, - Dimension::Height, - availableHeight - marginAxisColumn, - paddingAndBorderAxisColumn, - ownerHeight, - ownerWidth); - - float availableInnerMainDim = - isMainAxisRow ? availableInnerWidth : availableInnerHeight; - const float availableInnerCrossDim = - isMainAxisRow ? availableInnerHeight : availableInnerWidth; - - // STEP 3: DETERMINE FLEX BASIS FOR EACH ITEM - - // When this node is measured with MaxContent (FixFlexBasisFitContent - // behavior), availableInnerHeight is NaN. - // To preserve percentage resolution for descendants, derive a definite - // owner-size from the parent-provided ownerHeight. - float ownerWidthForChildren = availableInnerWidth; - float ownerHeightForChildren = availableInnerHeight; - - if (node->getConfig()->isExperimentalFeatureEnabled( - ExperimentalFeature::FixFlexBasisFitContent)) { - const auto* owner = node->getOwner(); - const bool isChildOfScrollContainer = - owner != nullptr && owner->style().overflow() == Overflow::Scroll; - - if (!isChildOfScrollContainer) { - if (yoga::isUndefined(ownerWidthForChildren) && - yoga::isDefined(ownerWidth)) { - ownerWidthForChildren = calculateAvailableInnerDimension( - node, - direction, - Dimension::Width, - ownerWidth - marginAxisRow, - paddingAndBorderAxisRow, - ownerWidth, - ownerWidth); - } - if (yoga::isUndefined(ownerHeightForChildren) && - yoga::isDefined(ownerHeight)) { - ownerHeightForChildren = calculateAvailableInnerDimension( - node, - direction, - Dimension::Height, - ownerHeight - marginAxisColumn, - paddingAndBorderAxisColumn, - ownerHeight, - ownerWidth); - } - } - } - - // Computed basis + margins + gap - float totalMainDim = 0; - totalMainDim += computeFlexBasisForChildren( - node, - availableInnerWidth, - availableInnerHeight, - ownerWidthForChildren, - ownerHeightForChildren, - widthSizingMode, - heightSizingMode, - direction, - mainAxis, - performLayout, - layoutMarkerData, - depth, - generationCount); - - if (childCount > 1) { - totalMainDim += - node->style().computeGapForAxis(mainAxis, availableInnerMainDim) * - static_cast(childCount - 1); - } - - const bool mainAxisOverflows = - (sizingModeMainDim != SizingMode::MaxContent) && - totalMainDim > availableInnerMainDim; - - if (isNodeFlexWrap && mainAxisOverflows && - sizingModeMainDim == SizingMode::FitContent) { - sizingModeMainDim = SizingMode::StretchFit; - } - // STEP 4: COLLECT FLEX ITEMS INTO FLEX LINES - - // Iterator representing the beginning of the current line - Node::LayoutableChildren::Iterator startOfLineIterator = - node->getLayoutChildren().begin(); - - // Number of lines. - size_t lineCount = 0; - - // Accumulated cross dimensions of all lines so far. - float totalLineCrossDim = 0; - - const float crossAxisGap = - node->style().computeGapForAxis(crossAxis, availableInnerCrossDim); - - // Max main dimension of all the lines. - float maxLineMainDim = 0; - for (; startOfLineIterator != node->getLayoutChildren().end(); lineCount++) { - auto flexLine = calculateFlexLine( - node, - ownerDirection, - ownerWidth, - mainAxisOwnerSize, - availableInnerWidth, - availableInnerMainDim, - startOfLineIterator, - lineCount); - - // If we don't need to measure the cross axis, we can skip the entire flex - // step. - const bool canSkipFlex = - !performLayout && sizingModeCrossDim == SizingMode::StretchFit; - - // STEP 5: RESOLVING FLEXIBLE LENGTHS ON MAIN AXIS - // Calculate the remaining available space that needs to be allocated. If - // the main dimension size isn't known, it is computed based on the line - // length, so there's no more space left to distribute. - - bool sizeBasedOnContent = false; - // If we don't measure with exact main dimension we want to ensure we don't - // violate min and max - if (sizingModeMainDim != SizingMode::StretchFit) { - const auto& style = node->style(); - const float minInnerWidth = - style - .resolvedMinDimension( - direction, Dimension::Width, ownerWidth, ownerWidth) - .unwrap() - - paddingAndBorderAxisRow; - const float maxInnerWidth = - style - .resolvedMaxDimension( - direction, Dimension::Width, ownerWidth, ownerWidth) - .unwrap() - - paddingAndBorderAxisRow; - const float minInnerHeight = - style - .resolvedMinDimension( - direction, Dimension::Height, ownerHeight, ownerWidth) - .unwrap() - - paddingAndBorderAxisColumn; - const float maxInnerHeight = - style - .resolvedMaxDimension( - direction, Dimension::Height, ownerHeight, ownerWidth) - .unwrap() - - paddingAndBorderAxisColumn; - - const float minInnerMainDim = - isMainAxisRow ? minInnerWidth : minInnerHeight; - const float maxInnerMainDim = - isMainAxisRow ? maxInnerWidth : maxInnerHeight; - - if (yoga::isDefined(minInnerMainDim) && - flexLine.sizeConsumed < minInnerMainDim) { - availableInnerMainDim = minInnerMainDim; - } else if ( - yoga::isDefined(maxInnerMainDim) && - flexLine.sizeConsumed > maxInnerMainDim) { - availableInnerMainDim = maxInnerMainDim; - } else { - bool useLegacyStretchBehaviour = - node->hasErrata(Errata::StretchFlexBasis); - - if (!useLegacyStretchBehaviour && - ((yoga::isDefined(flexLine.layout.totalFlexGrowFactors) && - flexLine.layout.totalFlexGrowFactors == 0) || - (yoga::isDefined(node->resolveFlexGrow()) && - node->resolveFlexGrow() == 0))) { - // If we don't have any children to flex or we can't flex the node - // itself, space we've used is all space we need. Root node also - // should be shrunk to minimum - availableInnerMainDim = flexLine.sizeConsumed; - } - - sizeBasedOnContent = !useLegacyStretchBehaviour; - } - } - - if (!sizeBasedOnContent && yoga::isDefined(availableInnerMainDim)) { - flexLine.layout.remainingFreeSpace = - availableInnerMainDim - flexLine.sizeConsumed; - } else if (flexLine.sizeConsumed < 0) { - // availableInnerMainDim is indefinite which means the node is being sized - // based on its content. sizeConsumed is negative which means - // the node will allocate 0 points for its content. Consequently, - // remainingFreeSpace is 0 - sizeConsumed. - flexLine.layout.remainingFreeSpace = -flexLine.sizeConsumed; - } - - if (!canSkipFlex) { - resolveFlexibleLength( - node, - flexLine, - mainAxis, - crossAxis, - direction, - ownerWidth, - mainAxisOwnerSize, - availableInnerMainDim, - availableInnerCrossDim, - availableInnerWidth, - availableInnerHeight, - mainAxisOverflows, - sizingModeCrossDim, - performLayout, - layoutMarkerData, - depth, - generationCount); - } - - node->setLayoutHadOverflow( - node->getLayout().hadOverflow() || - (flexLine.layout.remainingFreeSpace < 0)); - - // STEP 6: MAIN-AXIS JUSTIFICATION & CROSS-AXIS SIZE DETERMINATION - - // At this point, all the children have their dimensions set in the main - // axis. Their dimensions are also set in the cross axis with the exception - // of items that are aligned "stretch". We need to compute these stretch - // values and set the final positions. - - justifyMainAxis( - node, - flexLine, - mainAxis, - crossAxis, - direction, - sizingModeMainDim, - sizingModeCrossDim, - mainAxisOwnerSize, - ownerWidth, - availableInnerMainDim, - availableInnerCrossDim, - availableInnerWidth, - performLayout); - - float containerCrossAxis = availableInnerCrossDim; - if (sizingModeCrossDim == SizingMode::MaxContent || - sizingModeCrossDim == SizingMode::FitContent) { - // Compute the cross axis from the max cross dimension of the children. - containerCrossAxis = - boundAxis( - node, - crossAxis, - direction, - flexLine.layout.crossDim + paddingAndBorderAxisCross, - crossAxisOwnerSize, - ownerWidth) - - paddingAndBorderAxisCross; - } - - // If there's no flex wrap, the cross dimension is defined by the container. - if (!isNodeFlexWrap && sizingModeCrossDim == SizingMode::StretchFit) { - flexLine.layout.crossDim = availableInnerCrossDim; - } - - // As-per https://www.w3.org/TR/css-flexbox-1/#cross-sizing, the - // cross-size of the line within a single-line container should be bound to - // min/max constraints before alignment within the line. In a multi-line - // container, affecting alignment between the lines. - if (!isNodeFlexWrap) { - flexLine.layout.crossDim = - boundAxis( - node, - crossAxis, - direction, - flexLine.layout.crossDim + paddingAndBorderAxisCross, - crossAxisOwnerSize, - ownerWidth) - - paddingAndBorderAxisCross; - } - - // STEP 7: CROSS-AXIS ALIGNMENT - // We can skip child alignment if we're just measuring the container. - if (performLayout) { - for (auto child : flexLine.itemsInFlow) { - float leadingCrossDim = leadingPaddingAndBorderCross; - - // For a relative children, we're either using alignItems (owner) or - // alignSelf (child) in order to determine the position in the cross - // axis - const Align alignItem = resolveChildAlignment(node, child); - - // If the child uses align stretch, we need to lay it out one more - // time, this time forcing the cross-axis size to be the computed - // cross size for the current line. - if (alignItem == Align::Stretch && - !child->style().flexStartMarginIsAuto(crossAxis, direction) && - !child->style().flexEndMarginIsAuto(crossAxis, direction)) { - // If the child defines a definite size for its cross axis, there's - // no need to stretch. - if (!child->hasDefiniteLength( - dimension(crossAxis), availableInnerCrossDim)) { - float childMainSize = - child->getLayout().measuredDimension(dimension(mainAxis)); - const auto& childStyle = child->style(); - float childCrossSize = childStyle.aspectRatio().isDefined() - ? child->style().computeMarginForAxis( - crossAxis, availableInnerWidth) + - (isMainAxisRow - ? childMainSize / childStyle.aspectRatio().unwrap() - : childMainSize * childStyle.aspectRatio().unwrap()) - : flexLine.layout.crossDim; - - childMainSize += child->style().computeMarginForAxis( - mainAxis, availableInnerWidth); - - SizingMode childMainSizingMode = SizingMode::StretchFit; - SizingMode childCrossSizingMode = SizingMode::StretchFit; - constrainMaxSizeForMode( - child, - direction, - mainAxis, - availableInnerMainDim, - availableInnerWidth, - &childMainSizingMode, - &childMainSize); - constrainMaxSizeForMode( - child, - direction, - crossAxis, - availableInnerCrossDim, - availableInnerWidth, - &childCrossSizingMode, - &childCrossSize); - - const float childWidth = - isMainAxisRow ? childMainSize : childCrossSize; - const float childHeight = - !isMainAxisRow ? childMainSize : childCrossSize; - - auto alignContent = node->style().alignContent(); - auto crossAxisDoesNotGrow = - alignContent != Align::Stretch && isNodeFlexWrap; - const SizingMode childWidthSizingMode = - yoga::isUndefined(childWidth) || - (!isMainAxisRow && crossAxisDoesNotGrow) - ? SizingMode::MaxContent - : SizingMode::StretchFit; - const SizingMode childHeightSizingMode = - yoga::isUndefined(childHeight) || - (isMainAxisRow && crossAxisDoesNotGrow) - ? SizingMode::MaxContent - : SizingMode::StretchFit; - - calculateLayoutInternal( - child, - childWidth, - childHeight, - direction, - childWidthSizingMode, - childHeightSizingMode, - availableInnerWidth, - availableInnerHeight, - true, - LayoutPassReason::kStretch, - layoutMarkerData, - depth, - generationCount); - } - } else { - const float remainingCrossDim = containerCrossAxis - - child->dimensionWithMargin(crossAxis, availableInnerWidth); - - if (child->style().flexStartMarginIsAuto(crossAxis, direction) && - child->style().flexEndMarginIsAuto(crossAxis, direction)) { - leadingCrossDim += yoga::maxOrDefined(0.0f, remainingCrossDim / 2); - } else if (child->style().flexEndMarginIsAuto(crossAxis, direction)) { - // No-Op - } else if (child->style().flexStartMarginIsAuto( - crossAxis, direction)) { - leadingCrossDim += yoga::maxOrDefined(0.0f, remainingCrossDim); - } else if (alignItem == Align::FlexStart) { - // No-Op - } else if (alignItem == Align::Center) { - leadingCrossDim += remainingCrossDim / 2; - } else { - leadingCrossDim += remainingCrossDim; - } - } - // And we apply the position - child->setLayoutPosition( - child->getLayout().position(flexStartEdge(crossAxis)) + - totalLineCrossDim + leadingCrossDim, - flexStartEdge(crossAxis)); - } - } - - const float appliedCrossGap = lineCount != 0 ? crossAxisGap : 0.0f; - totalLineCrossDim += flexLine.layout.crossDim + appliedCrossGap; - maxLineMainDim = - yoga::maxOrDefined(maxLineMainDim, flexLine.layout.mainDim); - } - - // STEP 8: MULTI-LINE CONTENT ALIGNMENT - // currentLead stores the size of the cross dim - if (performLayout && (isNodeFlexWrap || isBaselineLayout(node))) { - float leadPerLine = 0; - float currentLead = leadingPaddingAndBorderCross; - float extraSpacePerLine = 0; - - const float unclampedCrossDim = sizingModeCrossDim == SizingMode::StretchFit - ? availableInnerCrossDim + paddingAndBorderAxisCross - : node->hasDefiniteLength(dimension(crossAxis), crossAxisOwnerSize) - ? node->getResolvedDimension( - direction, - dimension(crossAxis), - crossAxisOwnerSize, - ownerWidth) - .unwrap() - : totalLineCrossDim + paddingAndBorderAxisCross; - - const float innerCrossDim = boundAxis( - node, - crossAxis, - direction, - unclampedCrossDim, - crossAxisOwnerSize, - ownerWidth) - - paddingAndBorderAxisCross; - - const float remainingAlignContentDim = innerCrossDim - totalLineCrossDim; - - const auto alignContent = remainingAlignContentDim >= 0 - ? node->style().alignContent() - : fallbackAlignment(node->style().alignContent()); - - switch (alignContent) { - case Align::Start: - case Align::End: - // No-Op - break; - case Align::FlexEnd: - currentLead += remainingAlignContentDim; - break; - case Align::Center: - currentLead += remainingAlignContentDim / 2; - break; - case Align::Stretch: - extraSpacePerLine = - remainingAlignContentDim / static_cast(lineCount); - break; - case Align::SpaceAround: - currentLead += - remainingAlignContentDim / (2 * static_cast(lineCount)); - leadPerLine = remainingAlignContentDim / static_cast(lineCount); - break; - case Align::SpaceEvenly: - currentLead += - remainingAlignContentDim / static_cast(lineCount + 1); - leadPerLine = - remainingAlignContentDim / static_cast(lineCount + 1); - break; - case Align::SpaceBetween: - if (lineCount > 1) { - leadPerLine = - remainingAlignContentDim / static_cast(lineCount - 1); - } - break; - case Align::Auto: - case Align::FlexStart: - case Align::Baseline: - break; - } - Node::LayoutableChildren::Iterator endIterator = - node->getLayoutChildren().begin(); - for (size_t i = 0; i < lineCount; i++) { - const Node::LayoutableChildren::Iterator startIterator = endIterator; - auto iterator = startIterator; - - // compute the line's height and find the endIndex - float lineHeight = 0; - float maxAscentForCurrentLine = 0; - float maxDescentForCurrentLine = 0; - for (; iterator != node->getLayoutChildren().end(); iterator++) { - const auto child = *iterator; - if (child->style().display() == Display::None) { - continue; - } - if (child->style().positionType() != PositionType::Absolute) { - if (child->getLineIndex() != i) { - break; - } - if (child->isLayoutDimensionDefined(crossAxis)) { - lineHeight = yoga::maxOrDefined( - lineHeight, - child->getLayout().measuredDimension(dimension(crossAxis)) + - child->style().computeMarginForAxis( - crossAxis, availableInnerWidth)); - } - if (resolveChildAlignment(node, child) == Align::Baseline) { - const float ascent = calculateBaseline(child) + - child->style().computeFlexStartMargin( - FlexDirection::Column, direction, availableInnerWidth); - const float descent = - child->getLayout().measuredDimension(Dimension::Height) + - child->style().computeMarginForAxis( - FlexDirection::Column, availableInnerWidth) - - ascent; - maxAscentForCurrentLine = - yoga::maxOrDefined(maxAscentForCurrentLine, ascent); - maxDescentForCurrentLine = - yoga::maxOrDefined(maxDescentForCurrentLine, descent); - lineHeight = yoga::maxOrDefined( - lineHeight, maxAscentForCurrentLine + maxDescentForCurrentLine); - } - } - } - endIterator = iterator; - currentLead += i != 0 ? crossAxisGap : 0; - lineHeight += extraSpacePerLine; - - for (iterator = startIterator; iterator != endIterator; iterator++) { - const auto child = *iterator; - if (child->style().display() == Display::None) { - continue; - } - if (child->style().positionType() != PositionType::Absolute) { - switch (resolveChildAlignment(node, child)) { - case Align::Start: - case Align::End: - // Not yet implemented - break; - case Align::FlexStart: { - child->setLayoutPosition( - currentLead + - child->style().computeFlexStartPosition( - crossAxis, direction, availableInnerWidth), - flexStartEdge(crossAxis)); - break; - } - case Align::FlexEnd: { - child->setLayoutPosition( - currentLead + lineHeight - - child->style().computeFlexEndMargin( - crossAxis, direction, availableInnerWidth) - - child->getLayout().measuredDimension( - dimension(crossAxis)), - flexStartEdge(crossAxis)); - break; - } - case Align::Center: { - float childHeight = - child->getLayout().measuredDimension(dimension(crossAxis)); - - child->setLayoutPosition( - currentLead + (lineHeight - childHeight) / 2, - flexStartEdge(crossAxis)); - break; - } - case Align::Stretch: { - child->setLayoutPosition( - currentLead + - child->style().computeFlexStartMargin( - crossAxis, direction, availableInnerWidth), - flexStartEdge(crossAxis)); - - // Remeasure child with the line height as it as been only - // measured with the owners height yet. - if (!child->hasDefiniteLength( - dimension(crossAxis), availableInnerCrossDim)) { - const float childWidth = isMainAxisRow - ? (child->getLayout().measuredDimension(Dimension::Width) + - child->style().computeMarginForAxis( - mainAxis, availableInnerWidth)) - : leadPerLine + lineHeight; - - const float childHeight = !isMainAxisRow - ? (child->getLayout().measuredDimension(Dimension::Height) + - child->style().computeMarginForAxis( - crossAxis, availableInnerWidth)) - : leadPerLine + lineHeight; - - if (!(yoga::inexactEquals( - childWidth, - child->getLayout().measuredDimension( - Dimension::Width)) && - yoga::inexactEquals( - childHeight, - child->getLayout().measuredDimension( - Dimension::Height)))) { - calculateLayoutInternal( - child, - childWidth, - childHeight, - direction, - SizingMode::StretchFit, - SizingMode::StretchFit, - availableInnerWidth, - availableInnerHeight, - true, - LayoutPassReason::kMultilineStretch, - layoutMarkerData, - depth, - generationCount); - } - } - break; - } - case Align::Baseline: { - child->setLayoutPosition( - currentLead + maxAscentForCurrentLine - - calculateBaseline(child) + - child->style().computeFlexStartPosition( - FlexDirection::Column, - direction, - availableInnerCrossDim), - PhysicalEdge::Top); - - break; - } - case Align::Auto: - case Align::SpaceBetween: - case Align::SpaceAround: - case Align::SpaceEvenly: - break; - } - } - } - - currentLead = currentLead + leadPerLine + lineHeight; - } - } - - // STEP 9: COMPUTING FINAL DIMENSIONS - - node->setLayoutMeasuredDimension( - boundAxis( - node, - FlexDirection::Row, - direction, - availableWidth - marginAxisRow, - ownerWidth, - ownerWidth), - Dimension::Width); - - node->setLayoutMeasuredDimension( - boundAxis( - node, - FlexDirection::Column, - direction, - availableHeight - marginAxisColumn, - ownerHeight, - ownerWidth), - Dimension::Height); - - // If the user didn't specify a width or height for the node, set the - // dimensions based on the children. - if (sizingModeMainDim == SizingMode::MaxContent || - (node->style().overflow() != Overflow::Scroll && - sizingModeMainDim == SizingMode::FitContent)) { - // Clamp the size to the min/max size, if specified, and make sure it - // doesn't go below the padding and border amount. - node->setLayoutMeasuredDimension( - boundAxis( - node, - mainAxis, - direction, - maxLineMainDim, - mainAxisOwnerSize, - ownerWidth), - dimension(mainAxis)); - - } else if ( - sizingModeMainDim == SizingMode::FitContent && - node->style().overflow() == Overflow::Scroll) { - node->setLayoutMeasuredDimension( - yoga::maxOrDefined( - yoga::minOrDefined( - availableInnerMainDim + paddingAndBorderAxisMain, - boundAxisWithinMinAndMax( - node, - direction, - mainAxis, - FloatOptional{maxLineMainDim}, - mainAxisOwnerSize, - ownerWidth) - .unwrap()), - paddingAndBorderAxisMain), - dimension(mainAxis)); - } - - if (sizingModeCrossDim == SizingMode::MaxContent || - (node->style().overflow() != Overflow::Scroll && - sizingModeCrossDim == SizingMode::FitContent)) { - // Clamp the size to the min/max size, if specified, and make sure it - // doesn't go below the padding and border amount. - node->setLayoutMeasuredDimension( - boundAxis( - node, - crossAxis, - direction, - totalLineCrossDim + paddingAndBorderAxisCross, - crossAxisOwnerSize, - ownerWidth), - dimension(crossAxis)); - - } else if ( - sizingModeCrossDim == SizingMode::FitContent && - node->style().overflow() == Overflow::Scroll) { - node->setLayoutMeasuredDimension( - yoga::maxOrDefined( - yoga::minOrDefined( - availableInnerCrossDim + paddingAndBorderAxisCross, - boundAxisWithinMinAndMax( - node, - direction, - crossAxis, - FloatOptional{ - totalLineCrossDim + paddingAndBorderAxisCross}, - crossAxisOwnerSize, - ownerWidth) - .unwrap()), - paddingAndBorderAxisCross), - dimension(crossAxis)); - } - - // As we only wrapped in normal direction yet, we need to reverse the - // positions on wrap-reverse. - if (performLayout && node->style().flexWrap() == Wrap::WrapReverse) { - for (auto child : node->getLayoutChildren()) { - if (child->style().positionType() != PositionType::Absolute) { - child->setLayoutPosition( - node->getLayout().measuredDimension(dimension(crossAxis)) - - child->getLayout().position(flexStartEdge(crossAxis)) - - child->getLayout().measuredDimension(dimension(crossAxis)), - flexStartEdge(crossAxis)); - } - } - } - - if (performLayout) { - // STEP 10: SETTING TRAILING POSITIONS FOR CHILDREN - const bool needsMainTrailingPos = needsTrailingPosition(mainAxis); - const bool needsCrossTrailingPos = needsTrailingPosition(crossAxis); - - if (needsMainTrailingPos || needsCrossTrailingPos) { - for (auto child : node->getLayoutChildren()) { - // Absolute children will be handled by their containing block since we - // cannot guarantee that their positions are set when their parents are - // done with layout. - if (child->style().display() == Display::None || - child->style().positionType() == PositionType::Absolute) { - continue; - } - if (needsMainTrailingPos) { - setChildTrailingPosition(node, child, mainAxis); - } - - if (needsCrossTrailingPos) { - setChildTrailingPosition(node, child, crossAxis); - } - } - } - - // STEP 11: SIZING AND POSITIONING ABSOLUTE CHILDREN - // Let the containing block layout its absolute descendants. - if (node->style().positionType() != PositionType::Static || - node->alwaysFormsContainingBlock() || depth == 1) { - layoutAbsoluteDescendants( - node, - node, - isMainAxisRow ? sizingModeMainDim : sizingModeCrossDim, - direction, - layoutMarkerData, - depth, - generationCount, - 0.0f, - 0.0f, - availableInnerWidth, - availableInnerHeight); - } - } -} - -// -// This is a wrapper around the calculateLayoutImpl function. It determines -// whether the layout request is redundant and can be skipped. -// -// Parameters: -// Input parameters are the same as calculateLayoutImpl (see above) -// Return parameter is true if layout was performed, false if skipped -// -bool calculateLayoutInternal( - yoga::Node* const node, - const float availableWidth, - const float availableHeight, - const Direction ownerDirection, - const SizingMode widthSizingMode, - const SizingMode heightSizingMode, - const float ownerWidth, - const float ownerHeight, - const bool performLayout, - const LayoutPassReason reason, - LayoutData& layoutMarkerData, - uint32_t depth, - const uint32_t generationCount) { - LayoutResults* layout = &node->getLayout(); - - depth++; - - const bool needToVisitNode = - (node->isDirty() && layout->generationCount != generationCount) || - layout->configVersion != node->getConfig()->getVersion() || - layout->lastOwnerDirection != ownerDirection; - - if (needToVisitNode) { - // Invalidate the cached results. - layout->nextCachedMeasurementsIndex = 0; - layout->cachedLayout.availableWidth = -1; - layout->cachedLayout.availableHeight = -1; - layout->cachedLayout.widthSizingMode = SizingMode::MaxContent; - layout->cachedLayout.heightSizingMode = SizingMode::MaxContent; - layout->cachedLayout.computedWidth = -1; - layout->cachedLayout.computedHeight = -1; - } - - CachedMeasurement* cachedResults = nullptr; - - // Determine whether the results are already cached. We maintain a separate - // cache for layouts and measurements. A layout operation modifies the - // positions and dimensions for nodes in the subtree. The algorithm assumes - // that each node gets laid out a maximum of one time per tree layout, but - // multiple measurements may be required to resolve all of the flex - // dimensions. We handle nodes with measure functions specially here because - // they are the most expensive to measure, so it's worth avoiding redundant - // measurements if at all possible. - if (node->hasMeasureFunc()) { - const float marginAxisRow = - node->style().computeMarginForAxis(FlexDirection::Row, ownerWidth); - const float marginAxisColumn = - node->style().computeMarginForAxis(FlexDirection::Column, ownerWidth); - - // First, try to use the layout cache. - if (canUseCachedMeasurement( - widthSizingMode, - availableWidth, - heightSizingMode, - availableHeight, - layout->cachedLayout.widthSizingMode, - layout->cachedLayout.availableWidth, - layout->cachedLayout.heightSizingMode, - layout->cachedLayout.availableHeight, - layout->cachedLayout.computedWidth, - layout->cachedLayout.computedHeight, - marginAxisRow, - marginAxisColumn, - node->getConfig())) { - cachedResults = &layout->cachedLayout; - } else { - // Try to use the measurement cache. - for (size_t i = 0; i < layout->nextCachedMeasurementsIndex; i++) { - if (canUseCachedMeasurement( - widthSizingMode, - availableWidth, - heightSizingMode, - availableHeight, - layout->cachedMeasurements[i].widthSizingMode, - layout->cachedMeasurements[i].availableWidth, - layout->cachedMeasurements[i].heightSizingMode, - layout->cachedMeasurements[i].availableHeight, - layout->cachedMeasurements[i].computedWidth, - layout->cachedMeasurements[i].computedHeight, - marginAxisRow, - marginAxisColumn, - node->getConfig())) { - cachedResults = &layout->cachedMeasurements[i]; - break; - } - } - } - } else if (performLayout) { - if (yoga::inexactEquals( - layout->cachedLayout.availableWidth, availableWidth) && - yoga::inexactEquals( - layout->cachedLayout.availableHeight, availableHeight) && - layout->cachedLayout.widthSizingMode == widthSizingMode && - layout->cachedLayout.heightSizingMode == heightSizingMode) { - cachedResults = &layout->cachedLayout; - } - } else { - for (uint32_t i = 0; i < layout->nextCachedMeasurementsIndex; i++) { - if (yoga::inexactEquals( - layout->cachedMeasurements[i].availableWidth, availableWidth) && - yoga::inexactEquals( - layout->cachedMeasurements[i].availableHeight, availableHeight) && - layout->cachedMeasurements[i].widthSizingMode == widthSizingMode && - layout->cachedMeasurements[i].heightSizingMode == heightSizingMode) { - cachedResults = &layout->cachedMeasurements[i]; - break; - } - } - } - - if (!needToVisitNode && cachedResults != nullptr) { - layout->setMeasuredDimension( - Dimension::Width, cachedResults->computedWidth); - layout->setMeasuredDimension( - Dimension::Height, cachedResults->computedHeight); - - (performLayout ? layoutMarkerData.cachedLayouts - : layoutMarkerData.cachedMeasures) += 1; - } else { - calculateLayoutImpl( - node, - availableWidth, - availableHeight, - ownerDirection, - widthSizingMode, - heightSizingMode, - ownerWidth, - ownerHeight, - performLayout, - reason, - layoutMarkerData, - depth, - generationCount); - - layout->lastOwnerDirection = ownerDirection; - layout->configVersion = node->getConfig()->getVersion(); - - if (cachedResults == nullptr) { - layoutMarkerData.maxMeasureCache = std::max( - layoutMarkerData.maxMeasureCache, - layout->nextCachedMeasurementsIndex + 1u); - - if (layout->nextCachedMeasurementsIndex == - LayoutResults::MaxCachedMeasurements) { - layout->nextCachedMeasurementsIndex = 0; - } - - CachedMeasurement* newCacheEntry = nullptr; - if (performLayout) { - // Use the single layout cache entry. - newCacheEntry = &layout->cachedLayout; - } else { - // Allocate a new measurement cache entry. - newCacheEntry = - &layout->cachedMeasurements[layout->nextCachedMeasurementsIndex]; - layout->nextCachedMeasurementsIndex++; - } - - newCacheEntry->availableWidth = availableWidth; - newCacheEntry->availableHeight = availableHeight; - newCacheEntry->widthSizingMode = widthSizingMode; - newCacheEntry->heightSizingMode = heightSizingMode; - newCacheEntry->computedWidth = - layout->measuredDimension(Dimension::Width); - newCacheEntry->computedHeight = - layout->measuredDimension(Dimension::Height); - } - } - - if (performLayout) { - node->setLayoutDimension( - node->getLayout().measuredDimension(Dimension::Width), - Dimension::Width); - node->setLayoutDimension( - node->getLayout().measuredDimension(Dimension::Height), - Dimension::Height); - - node->setHasNewLayout(true); - node->setDirty(false); - } - - layout->generationCount = generationCount; - - LayoutType layoutType; - if (performLayout) { - layoutType = !needToVisitNode && cachedResults == &layout->cachedLayout - ? LayoutType::kCachedLayout - : LayoutType::kLayout; - } else { - layoutType = cachedResults != nullptr ? LayoutType::kCachedMeasure - : LayoutType::kMeasure; - } - Event::publish(node, {layoutType}); - - return (needToVisitNode || cachedResults == nullptr); -} - -void calculateLayout( - yoga::Node* const node, - const float ownerWidth, - const float ownerHeight, - const Direction ownerDirection) { - Event::publish(node); - LayoutData markerData = {}; - - // Increment the generation count. This will force the recursive routine to - // visit all dirty nodes at least once. Subsequent visits will be skipped if - // the input parameters don't change. - gCurrentGenerationCount.fetch_add(1, std::memory_order_relaxed); - node->processDimensions(); - const Direction direction = node->resolveDirection(ownerDirection); - float width = YGUndefined; - SizingMode widthSizingMode = SizingMode::MaxContent; - const auto& style = node->style(); - if (node->hasDefiniteLength(Dimension::Width, ownerWidth)) { - width = - (node->getResolvedDimension( - direction, - dimension(FlexDirection::Row), - ownerWidth, - ownerWidth) - .unwrap() + - node->style().computeMarginForAxis(FlexDirection::Row, ownerWidth)); - widthSizingMode = SizingMode::StretchFit; - } else if (style - .resolvedMaxDimension( - direction, Dimension::Width, ownerWidth, ownerWidth) - .isDefined()) { - width = style - .resolvedMaxDimension( - direction, Dimension::Width, ownerWidth, ownerWidth) - .unwrap(); - widthSizingMode = SizingMode::FitContent; - } else { - width = ownerWidth; - widthSizingMode = yoga::isUndefined(width) ? SizingMode::MaxContent - : SizingMode::StretchFit; - } - - float height = YGUndefined; - SizingMode heightSizingMode = SizingMode::MaxContent; - if (node->hasDefiniteLength(Dimension::Height, ownerHeight)) { - height = - (node->getResolvedDimension( - direction, - dimension(FlexDirection::Column), - ownerHeight, - ownerWidth) - .unwrap() + - node->style().computeMarginForAxis(FlexDirection::Column, ownerWidth)); - heightSizingMode = SizingMode::StretchFit; - } else if (style - .resolvedMaxDimension( - direction, Dimension::Height, ownerHeight, ownerWidth) - .isDefined()) { - height = style - .resolvedMaxDimension( - direction, Dimension::Height, ownerHeight, ownerWidth) - .unwrap(); - heightSizingMode = SizingMode::FitContent; - } else { - height = ownerHeight; - heightSizingMode = yoga::isUndefined(height) ? SizingMode::MaxContent - : SizingMode::StretchFit; - } - if (calculateLayoutInternal( - node, - width, - height, - ownerDirection, - widthSizingMode, - heightSizingMode, - ownerWidth, - ownerHeight, - true, - LayoutPassReason::kInitial, - markerData, - 0, // tree root - gCurrentGenerationCount.load(std::memory_order_relaxed))) { - node->setPosition(node->getLayout().direction(), ownerWidth, ownerHeight); - roundLayoutResultsToPixelGrid(node, 0.0f, 0.0f); - } - - Event::publish(node, {&markerData}); -} - -} // namespace facebook::yoga diff --git a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/yoga/enums/Errata.h b/vendor/react-native-gpui/packages/core/ReactCommonOverrides/yoga/enums/Errata.h deleted file mode 100644 index 7113a97421..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCommonOverrides/yoga/enums/Errata.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -// @generated by enums.py -// clang-format off -#pragma once - -#include -#include -#include - -namespace facebook::yoga { - -enum class Errata : uint32_t { - None = YGErrataNone, - StretchFlexBasis = YGErrataStretchFlexBasis, - AbsolutePositionWithoutInsetsExcludesPadding = YGErrataAbsolutePositionWithoutInsetsExcludesPadding, - AbsolutePercentAgainstInnerSize = YGErrataAbsolutePercentAgainstInnerSize, - MinSizeUndefinedInsteadOfAuto = YGErrataMinSizeUndefinedInsteadOfAuto, - FlexBasisAsIntrinsicSize = YGErrataFlexBasisAsIntrinsicSize, - All = YGErrataAll, - Classic = YGErrataClassic, -}; - -YG_DEFINE_ENUM_FLAG_OPERATORS(Errata) - -constexpr Errata scopedEnum(YGErrata unscoped) { - return static_cast(unscoped); -} - -constexpr YGErrata unscopedEnum(Errata scoped) { - return static_cast(scoped); -} - -inline const char* toString(Errata e) { - return YGErrataToString(unscopedEnum(e)); -} - -} // namespace facebook::yoga diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/AppStateModule.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/AppStateModule.cpp deleted file mode 100644 index ec9425494c..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/AppStateModule.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "AppStateModule.h" - -#include - -namespace facebook::react { - -namespace { -std::mutex stateMutex; -std::string currentState = "active"; -} // namespace - -void AppStateModule::setState(const std::string& state) { - std::lock_guard lock(stateMutex); - currentState = state; -} - -std::string AppStateModule::state() { - std::lock_guard lock(stateMutex); - return currentState; -} - -AppStateConstants AppStateModule::getConstants(jsi::Runtime& /*rt*/) { - return AppStateConstants{.initialAppState = state()}; -} - -void AppStateModule::getCurrentAppState( - jsi::Runtime& /*rt*/, - const AsyncCallback& success, - jsi::Function /*error*/) { - success(AppState{state()}); -} - -void AppStateModule::addListener( - jsi::Runtime& /*rt*/, - const std::string& /*eventName*/) {} - -void AppStateModule::removeListeners(jsi::Runtime& /*rt*/, double /*count*/) {} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/AppStateModule.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/AppStateModule.h deleted file mode 100644 index 6ac2eb9fb2..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/AppStateModule.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include - -namespace facebook::react { - -using AppStateConstants = NativeAppStateAppStateConstants; - -template <> -struct Bridging : NativeAppStateAppStateConstantsBridging {}; - -using AppState = NativeAppStateAppState; - -template <> -struct Bridging : NativeAppStateAppStateBridging {}; - -class AppStateModule : public NativeAppStateCxxSpec { - public: - explicit AppStateModule(std::shared_ptr jsInvoker) : NativeAppStateCxxSpec(jsInvoker) {} - - static void setState(const std::string &state); - static std::string state(); - - AppStateConstants getConstants(jsi::Runtime &rt); - - void getCurrentAppState(jsi::Runtime &rt, const AsyncCallback &success, jsi::Function error); - void addListener(jsi::Runtime &rt, const std::string &eventName); - - void removeListeners(jsi::Runtime &rt, double count); -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/CMakeLists.txt b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/CMakeLists.txt deleted file mode 100644 index 401bb8616a..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -include(${REACT_COMMON_DIR}/cmake-utils/react-native-flags.cmake) - -file(GLOB react_cxx_platform_react_coremodules_SRC CONFIGURE_DEPENDS *.cpp) -add_library(react_cxx_platform_react_coremodules OBJECT ${react_cxx_platform_react_coremodules_SRC}) - -target_include_directories(react_cxx_platform_react_coremodules PUBLIC ${REACT_CXX_PLATFORM_DIR}) - -target_link_libraries(react_cxx_platform_react_coremodules - folly_runtime - jsi - react_nativemodule_core - react_codegen_rncore -) -target_compile_reactnative_options(react_cxx_platform_react_coremodules PRIVATE) -target_compile_options(react_cxx_platform_react_coremodules PRIVATE -Wpedantic) diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/DeviceInfoModule.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/DeviceInfoModule.cpp deleted file mode 100644 index e915b6da39..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/DeviceInfoModule.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "DeviceInfoModule.h" - -#include - -namespace facebook::react { - -namespace { -std::atomic windowWidth{1280.0}; -std::atomic windowHeight{720.0}; -std::atomic displayScale{1.0}; -std::atomic screenWidth{0.0}; -std::atomic screenHeight{0.0}; -std::atomic textScale{1.0}; -} // namespace - -bool DeviceInfoModule::setWindowMetrics(double width, double height, double scale) { - const auto validScale = scale > 0.0 ? scale : 1.0; - const auto oldWidth = windowWidth.exchange(width, std::memory_order_relaxed); - const auto oldHeight = windowHeight.exchange(height, std::memory_order_relaxed); - const auto oldScale = displayScale.exchange(validScale, std::memory_order_relaxed); - return oldWidth != width || oldHeight != height || oldScale != validScale; -} - -bool DeviceInfoModule::setDisplayMetrics(double width, double height, double fontScale) { - const auto validFontScale = fontScale > 0.0 ? fontScale : 1.0; - const auto oldWidth = screenWidth.exchange(width, std::memory_order_relaxed); - const auto oldHeight = screenHeight.exchange(height, std::memory_order_relaxed); - const auto oldFontScale = textScale.exchange(validFontScale, std::memory_order_relaxed); - return oldWidth != width || oldHeight != height || oldFontScale != validFontScale; -} - -double DeviceInfoModule::fontScale() { - return textScale.load(std::memory_order_relaxed); -} - -Size DeviceInfoModule::screenSize() { - const auto width = screenWidth.load(std::memory_order_relaxed); - const auto height = screenHeight.load(std::memory_order_relaxed); - if (width <= 0.0 || height <= 0.0) { - return windowSize(); - } - return Size{.width = static_cast(width), .height = static_cast(height)}; -} - -double DeviceInfoModule::scale() { - return displayScale.load(std::memory_order_relaxed); -} - -Size DeviceInfoModule::windowSize() { - return Size{ - .width = static_cast(windowWidth.load(std::memory_order_relaxed)), - .height = static_cast(windowHeight.load(std::memory_order_relaxed)), - }; -} - -DeviceInfoConstants DeviceInfoModule::getConstants(jsi::Runtime& /*rt*/) { - const auto scale = displayScale.load(std::memory_order_relaxed); - const auto fontScale = textScale.load(std::memory_order_relaxed); - const auto screen = screenSize(); - return DeviceInfoConstants{ - .Dimensions = - {.window = - DisplayMetrics{ - windowWidth.load(std::memory_order_relaxed), - windowHeight.load(std::memory_order_relaxed), - scale, - fontScale, - }, - .screen = - DisplayMetrics{ - static_cast(screen.width), - static_cast(screen.height), - scale, - fontScale, - }}, - }; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/DeviceInfoModule.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/DeviceInfoModule.h deleted file mode 100644 index 728f26878d..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/DeviceInfoModule.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include - -namespace facebook::react { - -using DisplayMetrics = NativeDeviceInfoDisplayMetrics; - -using DisplayMetricsAndroid = NativeDeviceInfoDisplayMetricsAndroid; - -using DimensionsPayload = NativeDeviceInfoDimensionsPayload< - std::optional, - std::optional, - std::optional, - std::optional>; - -using DeviceInfoConstants = - NativeDeviceInfoDeviceInfoConstants, std::optional>; - -template <> -struct Bridging : NativeDeviceInfoDisplayMetricsBridging {}; - -template <> -struct Bridging : NativeDeviceInfoDisplayMetricsAndroidBridging {}; - -template <> -struct Bridging : NativeDeviceInfoDimensionsPayloadBridging {}; - -template <> -struct Bridging : NativeDeviceInfoDeviceInfoConstantsBridging {}; - -class DeviceInfoModule : public NativeDeviceInfoCxxSpec { - public: - explicit DeviceInfoModule(std::shared_ptr jsInvoker) : NativeDeviceInfoCxxSpec(jsInvoker) {} - - static bool setWindowMetrics(double width, double height, double scale); - static Size windowSize(); - static double scale(); - static bool setDisplayMetrics(double screenWidth, double screenHeight, double fontScale); - static double fontScale(); - static Size screenSize(); - - DeviceInfoConstants getConstants(jsi::Runtime &rt); -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/PlatformConstantsModule.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/PlatformConstantsModule.cpp deleted file mode 100644 index 196a4e3a8d..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/PlatformConstantsModule.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "PlatformConstantsModule.h" - -#include "GpuiJsEngine.h" - -namespace facebook::react { - -jsi::Object PlatformConstantsModule::getConstants(jsi::Runtime& rt) { - const PlatformConstantsAndroid constants{ - .isTesting = false, - .isDisableAnimations = false, - .reactNativeVersion = - { - .major = 1000, - .minor = 0, - .patch = 0, - .prerelease = std::nullopt, - }, - .Version = 33, // Android 13 (API level 33) - .Release = "", - .Fingerprint = "", - .Model = "", - .ServerHost = "", - .uiMode = "", - .Brand = "", - .Manufacturer = "", - }; - auto result = bridging::toJs(rt, constants, jsInvoker_); - - // `Platform.constants.jsEngine`, reported by the active engine package. An - // engine without a version still reports its name. - const auto& engine = rngpui::activeJsEngine().info; - auto jsEngine = jsi::Object(rt); - jsEngine.setProperty(rt, "name", jsi::String::createFromUtf8(rt, engine.name)); - jsEngine.setProperty( - rt, "version", jsi::String::createFromUtf8(rt, engine.version)); - result.setProperty(rt, "jsEngine", std::move(jsEngine)); - return result; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/PlatformConstantsModule.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/PlatformConstantsModule.h deleted file mode 100644 index c9cef78cc4..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/coremodules/PlatformConstantsModule.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include - -namespace facebook::react { - -using ReactNativeVersionAndroid = - NativePlatformConstantsAndroidReactNativeVersionAndroid>; - -template <> -struct Bridging - : NativePlatformConstantsAndroidReactNativeVersionAndroidBridging {}; - -using PlatformConstantsAndroid = NativePlatformConstantsAndroidPlatformConstantsAndroid< - bool, - std::optional, - ReactNativeVersionAndroid, - int, - std::string, - std::string, - std::string, - std::string, - std::optional, - std::string, - std::string, - std::string>; - -template <> -struct Bridging - : NativePlatformConstantsAndroidPlatformConstantsAndroidBridging {}; - -// T159303412: [RN] Metro: Need support for new target platform -class PlatformConstantsModule : public NativePlatformConstantsAndroidCxxSpec { - public: - explicit PlatformConstantsModule(std::shared_ptr jsInvoker) - : NativePlatformConstantsAndroidCxxSpec(jsInvoker) - { - } - - std::string getAndroidID(jsi::Runtime & /*rt*/) - { - return ""; - } - - // Returns the generated constants plus a `jsEngine: { name, version }` field - // reported by the active engine package. The generated Android constants - // struct cannot carry the extra field, so the object is built here. - jsi::Object getConstants(jsi::Runtime &rt); -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/CMakeLists.txt b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/CMakeLists.txt deleted file mode 100644 index fc695df675..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/CMakeLists.txt +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -include(${REACT_COMMON_DIR}/cmake-utils/react-native-flags.cmake) - -file(GLOB react_cxx_platform_react_devsupport_SRC CONFIGURE_DEPENDS - *.cpp - inspector/*.cpp) -add_library(react_cxx_platform_react_devsupport OBJECT ${react_cxx_platform_react_devsupport_SRC}) - -target_include_directories(react_cxx_platform_react_devsupport PUBLIC ${REACT_CXX_PLATFORM_DIR}) - -target_link_libraries(react_cxx_platform_react_devsupport - glog - nlohmann_json - folly_runtime - jsi - OpenSSL::Crypto - react_cxx_platform_react_http - react_cxx_platform_react_nativemodule - react_cxx_platform_react_renderer_scheduler - react_cxx_platform_react_renderer_scheduler - react_cxx_platform_react_threading - react_codegen_rncore - jsinspector - react_debug - react_renderer_graphics -) -target_compile_reactnative_options(react_cxx_platform_react_devsupport PRIVATE) -target_compile_options(react_cxx_platform_react_devsupport PRIVATE -Wpedantic -Wno-deprecated-declarations) diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevLoadingViewModule.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevLoadingViewModule.cpp deleted file mode 100644 index 2569842c1a..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevLoadingViewModule.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "DevLoadingViewModule.h" - -namespace facebook::react { - -const int32_t DEFAULT_TEXT_COLOR = 0xFFFFFFFF; -const int32_t DEFAULT_BACKGROUND_COLOR = 0xFF2584E8; - -DevLoadingViewModule::DevLoadingViewModule( - std::shared_ptr jsInvoker, - std::weak_ptr devUIDelegate) - : NativeDevLoadingViewCxxSpec(jsInvoker), - devUIDelegate_(std::move(devUIDelegate)) {} - -DevLoadingViewModule::~DevLoadingViewModule() { - if (auto devUIDelegate = devUIDelegate_.lock()) { - devUIDelegate->hideLoadingView(); - } -} - -void DevLoadingViewModule::showMessage( - jsi::Runtime& /*rt*/, - const std::string& message, - std::optional textColor, - std::optional backgroundColor, - std::optional /*dismissButton*/) { - if (auto devUIDelegate = devUIDelegate_.lock()) { - devUIDelegate->showLoadingView( - message, - SharedColor{textColor.value_or(DEFAULT_TEXT_COLOR)}, - SharedColor{backgroundColor.value_or(DEFAULT_BACKGROUND_COLOR)}); - } -} - -void DevLoadingViewModule::hide(jsi::Runtime& /*rt*/) { - if (auto devUIDelegate = devUIDelegate_.lock()) { - devUIDelegate->hideLoadingView(); - } -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevLoadingViewModule.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevLoadingViewModule.h deleted file mode 100644 index 0cedcb1837..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevLoadingViewModule.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include "IDevUIDelegate.h" - -#include -#include -#include - -namespace facebook::react { - -class DevLoadingViewModule : public NativeDevLoadingViewCxxSpec { - public: - DevLoadingViewModule(std::shared_ptr jsInvoker, std::weak_ptr devUIDelegate); - - ~DevLoadingViewModule() override; - - void showMessage( - jsi::Runtime &rt, - const std::string &message, - std::optional textColor, - std::optional backgroundColor, - std::optional dismissButton); - void hide(jsi::Runtime &rt); - - private: - std::weak_ptr devUIDelegate_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevServerHelper.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevServerHelper.cpp deleted file mode 100644 index 139aee91cf..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevServerHelper.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "DevServerHelper.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -constexpr std::string_view DEFAULT_PLATFORM = "android"; - -std::string SHA256(const std::string& input) { - std::array hash{}; - SHA256_CTX sha256; - SHA256_Init(&sha256); - SHA256_Update(&sha256, input.c_str(), input.size()); - SHA256_Final(hash.data(), &sha256); - std::stringstream ss; - for (unsigned char i : hash) { - ss << std::hex << std::setw(2) << std::setfill('0') << (int)i; - } - return ss.str(); -} - -std::string urlEscape(const std::string& str) { - std::regex pattern("[^a-zA-Z0-9._~-]"); - return std::regex_replace(str, pattern, ""); -} - -} // namespace - -namespace facebook::react { - -DevServerHelper::DevServerHelper( - std::string appId, - std::string deviceName, - std::string devServerHost, - uint32_t devServerPort, - const HttpClientFactory& httpClientFactory, - JavaScriptModuleCallback javaScriptModuleCallback) noexcept - : appId_(std::move(appId)), - deviceName_(std::move(deviceName)), - devServerHost_(std::move(devServerHost)), - devServerPort_(devServerPort), - httpClient_(httpClientFactory()), - javaScriptModuleCallback_(std::move(javaScriptModuleCallback)) { - deviceId_ = SHA256(fmt::format("{}-{}", deviceName_, appId_)); -} - -std::future DevServerHelper::downloadBundleResourceSync( - const std::string& jsBundleUrl, - DownloadProgressCallback&& downloadProgressCallback) { - auto promise = std::make_shared>(); - http::NetworkCallbacks callbacks{ - .onBody = - [jsBundleUrl, promise, downloadProgressCallback]( - std::unique_ptr ioBuf) { - std::string responseStr = ioBuf->moveToFbString().toStdString(); - promise->set_value(responseStr); - }, - .onResponseComplete = - [jsBundleUrl, promise, downloadProgressCallback]( - const std::string& error, bool timeoutError) { - if (!error.empty() || timeoutError) { - if (downloadProgressCallback) { - downloadProgressCallback(DownloadProgressStatus::FAILED); - } - std::string errorMessage = - "Failed to download JS bundle from Url: " + jsBundleUrl + - ". Error: " + (error.empty() ? "Timeout" : error); - LOG(WARNING) << errorMessage; - try { - throw std::runtime_error(errorMessage); - } catch (...) { - try { - promise->set_exception(std::current_exception()); - } catch (...) { - } - } - } else if (downloadProgressCallback) { - downloadProgressCallback(DownloadProgressStatus::FINISHED); - } - }}; - httpClient_->sendRequest(std::move(callbacks), "GET", jsBundleUrl); - if (downloadProgressCallback) { - downloadProgressCallback(DownloadProgressStatus::STARTED); - } - return promise->get_future(); -} - -std::string DevServerHelper::getInspectorUrl() const { - bool isProfilingBuild = - jsinspector_modern::InspectorFlags::getInstance().getIsProfilingBuild(); - - return fmt::format( - "ws://{}:{}/inspector/device?name={}&app={}&device={}&profiling={}", - devServerHost_, - devServerPort_, - urlEscape(deviceName_), - appId_, - deviceId_, - isProfilingBuild); -} - -std::string DevServerHelper::getBundleUrl() const { - if (sourcePath_.empty()) { - return ""; - } - - bool dev = true; - bool lazy = dev; - bool minify = false; - bool splitBundle = false; - bool modulesOnly = splitBundle; - bool runModule = !splitBundle; - return fmt::format( - "http://{}:{}/{}.bundle?platform={}&dev={}&lazy={}&minify={}&app={}&modulesOnly={}&runModule={}&inlineSourceMap=false&excludeSource=true&sourcePaths=url-server", - devServerHost_, - devServerPort_, - sourcePath_, - DEFAULT_PLATFORM, - dev, - lazy, - minify, - appId_, - modulesOnly, - runModule); -}; - -std::string DevServerHelper::getPackagerConnectionUrl() const { - return fmt::format("ws://{}:{}/message", devServerHost_, devServerPort_); -} - -void DevServerHelper::openDebugger() const { - auto requestUrl = fmt::format( - "http://{}:{}/open-debugger?device={}", - devServerHost_, - devServerPort_, - deviceId_); - httpClient_->sendRequest({}, "POST", requestUrl); -} - -void DevServerHelper::setupHMRClient() const { - folly::dynamic params = folly::dynamic::array( - DEFAULT_PLATFORM, - sourcePath_, - devServerHost_, - devServerPort_, - true /*enable*/); - javaScriptModuleCallback_("HMRClient", "setup", std::move(params)); -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevServerHelper.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevServerHelper.h deleted file mode 100644 index 7497f070e5..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevServerHelper.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -class DevServerHelper { - public: - enum class DownloadProgressStatus : short { STARTED, FAILED, FINISHED }; - using DownloadProgressCallback = std::function; - - DevServerHelper( - std::string appId, - std::string deviceName, - std::string devServerHost, - uint32_t devServerPort, - const HttpClientFactory &httpClientFactory, - JavaScriptModuleCallback javaScriptModuleCallback) noexcept; - ~DevServerHelper() noexcept = default; - - std::future downloadBundleResourceSync( - const std::string &jsBundleUrl, - DownloadProgressCallback &&downloadProgressCallback = nullptr); - - std::string getInspectorUrl() const; - - std::string getBundleUrl() const; - - std::string getPackagerConnectionUrl() const; - - void openDebugger() const; - - void setSourcePath(const std::string &sourcePath) - { - sourcePath_ = sourcePath; - } - - void setupHMRClient() const; - - // react-native-gpui: the Dev Menu's "Configure Bundler". Every URL this - // helper hands out is built from these on demand, so the next bundle load - // and the connections made after it use the new server. - void setDevServer(std::string host, uint32_t port) - { - devServerHost_ = std::move(host); - devServerPort_ = port; - } - - const std::string &devServerHost() const - { - return devServerHost_; - } - - uint32_t devServerPort() const - { - return devServerPort_; - } - - private: - std::string appId_; - std::string deviceName_; - std::string devServerHost_; - uint32_t devServerPort_; - std::unique_ptr httpClient_; - JavaScriptModuleCallback javaScriptModuleCallback_; - std::string deviceId_; - std::string sourcePath_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevSettingsModule.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevSettingsModule.cpp deleted file mode 100644 index 5c0cd31efa..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevSettingsModule.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "DevSettingsModule.h" - -#include - -/// Defined in `rn-gpui-sys/cpp/GpuiHost.cpp`: forwards a `DevSettings` toggle -/// to the GPUI main thread, which owns the perf monitor and the Dev Menu. -extern "C" void rn_gpui_dev_settings_changed(const char* name, bool enabled); - -namespace facebook::react { - -void DevSettingsModule::reload(jsi::Runtime& /*rt*/) { - LOG(INFO) << "DevSettingsModule::reload"; - if (liveReloadCallback_) { - liveReloadCallback_(); - } -} - -void DevSettingsModule::reloadWithReason( - jsi::Runtime& /*rt*/, - const std::string& reason) { - LOG(INFO) << "DevSettingsModule::reloadWithReason: " << reason; - if (liveReloadCallback_) { - liveReloadCallback_(); - } -} - -void DevSettingsModule::onFastRefresh(jsi::Runtime& /*rt*/) { - LOG(INFO) << "DevSettingsModule::onFastRefresh"; -} - -void DevSettingsModule::setHotLoadingEnabled( - jsi::Runtime& /*rt*/, - bool isHotLoadingEnabled) { - LOG(INFO) << "DevSettingsModule::setHotLoadingEnabled: " - << (int)isHotLoadingEnabled; - rn_gpui_dev_settings_changed("hotLoading", isHotLoadingEnabled); -} - -void DevSettingsModule::setIsDebuggingRemotely( - jsi::Runtime& /*rt*/, - bool /*isDebuggingRemotelyEnabled*/) {} - -void DevSettingsModule::setProfilingEnabled( - jsi::Runtime& /*rt*/, - bool isProfilingEnabled) { - // The Perf Monitor is the desktop's profiling surface (plan 7.6). - rn_gpui_dev_settings_changed("profiling", isProfilingEnabled); -} - -void DevSettingsModule::toggleElementInspector(jsi::Runtime& /*rt*/) { - rn_gpui_dev_settings_changed("inspectorToggle", true); -} - -void DevSettingsModule::addMenuItem( - jsi::Runtime& /*rt*/, - const std::string& title) { - // Carried on the same shim as the toggles: the name says which one. - rn_gpui_dev_settings_changed(("menuItem:" + title).c_str(), true); -} - -void DevSettingsModule::setIsShakeToShowDevMenuEnabled( - jsi::Runtime& /*rt*/, - bool /*enabled*/) {} - -void DevSettingsModule::openDebugger(jsi::Runtime& /*rt*/) { - if (auto devServerHelper = devServerHelper_.lock()) { - devServerHelper->openDebugger(); - } -} - -void DevSettingsModule::addListener( - jsi::Runtime& /*rt*/, - const std::string& /*eventName*/) { - // noop -} - -void DevSettingsModule::removeListeners( - jsi::Runtime& /*rt*/, - double /*count*/) { - // noop -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevSettingsModule.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevSettingsModule.h deleted file mode 100644 index a9ec5cd419..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/DevSettingsModule.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include - -namespace facebook::react { - -class DevSettingsModule : public NativeDevSettingsCxxSpec { - using LiveReloadCallback = std::function; - - public: - DevSettingsModule( - std::shared_ptr jsInvoker, - std::weak_ptr devServerHelper, - LiveReloadCallback liveReloadCallback) - : NativeDevSettingsCxxSpec(jsInvoker), - devServerHelper_(std::move(devServerHelper)), - liveReloadCallback_(std::move(liveReloadCallback)) - { - } - - void reload(jsi::Runtime &rt); - - void reloadWithReason(jsi::Runtime &rt, const std::string &reason); - - void onFastRefresh(jsi::Runtime &rt); - - void setHotLoadingEnabled(jsi::Runtime &rt, bool isHotLoadingEnabled); - - void setIsDebuggingRemotely(jsi::Runtime &rt, bool isDebuggingRemotelyEnabled); - - void setProfilingEnabled(jsi::Runtime &rt, bool isProfilingEnabled); - - void toggleElementInspector(jsi::Runtime &rt); - - void addMenuItem(jsi::Runtime &rt, const std::string &title); - - void setIsShakeToShowDevMenuEnabled(jsi::Runtime &rt, bool enabled); - - void openDebugger(jsi::Runtime &rt); - - void addListener(jsi::Runtime &rt, const std::string &eventName); - - void removeListeners(jsi::Runtime &rt, double count); - - private: - std::weak_ptr devServerHelper_; - LiveReloadCallback liveReloadCallback_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/IDevUIDelegate.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/IDevUIDelegate.h deleted file mode 100644 index 958cc19019..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/IDevUIDelegate.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include - -namespace facebook::react { - -struct IDevUIDelegate { - virtual ~IDevUIDelegate() noexcept = default; - - virtual void showDownloadBundleProgress() = 0; - - virtual void hideDownloadBundleProgress() = 0; - - virtual void showLoadingView(const std::string &message, SharedColor textColor, SharedColor backgroundColor) = 0; - - virtual void hideLoadingView() = 0; - - virtual void showDebuggerOverlay(std::function &&resumeDebuggerFn) = 0; - - virtual void hideDebuggerOverlay() = 0; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/LogBoxModule.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/LogBoxModule.cpp deleted file mode 100644 index 745fb3953c..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/LogBoxModule.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "LogBoxModule.h" - -#include - -namespace facebook::react { - -LogBoxModule::LogBoxModule( - std::shared_ptr jsInvoker, - std::shared_ptr surfaceDelegate) - : NativeLogBoxCxxSpec(jsInvoker), - surfaceDelegate_(std::move(surfaceDelegate)) { - LOG(INFO) << "LogBoxModule initialized"; - surfaceDelegate_->createContentView("LogBox"); -} - -LogBoxModule::~LogBoxModule() { - surfaceDelegate_->destroyContentView(); -} - -void LogBoxModule::show(jsi::Runtime& /*rt*/) { - LOG(INFO) << "LogBoxModule show"; - if (surfaceDelegate_->isContentViewReady() && - !surfaceDelegate_->isShowing()) { - surfaceDelegate_->show(); - } -} - -void LogBoxModule::hide(jsi::Runtime& /*rt*/) { - LOG(INFO) << "LogBoxModule hide"; - if (surfaceDelegate_->isShowing()) { - surfaceDelegate_->hide(); - } -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/LogBoxModule.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/LogBoxModule.h deleted file mode 100644 index 0ee88e327e..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/LogBoxModule.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include - -namespace facebook::react { -class LogBoxModule : public NativeLogBoxCxxSpec { - public: - LogBoxModule(std::shared_ptr jsInvoker, std::shared_ptr surfaceDelegate); - ~LogBoxModule() override; - - void show(jsi::Runtime &rt); - - void hide(jsi::Runtime &rt); - - private: - std::shared_ptr surfaceDelegate_; -}; -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/PackagerConnection.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/PackagerConnection.cpp deleted file mode 100644 index d17bae6ce7..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/PackagerConnection.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "PackagerConnection.h" - -#include -#include - -namespace facebook::react { - -PackagerConnection::PackagerConnection( - WebSocketClientFactory webSocketClientFactory, - std::string packagerConnectionUrl, - LiveReloadCallback&& liveReloadCallback, - ShowDevMenuCallback&& showDevMenuCallback) - : webSocketClientFactory_(std::move(webSocketClientFactory)), - packagerConnectionUrl_(std::move(packagerConnectionUrl)), - liveReloadCallback_(std::move(liveReloadCallback)), - showDevMenuCallback_(std::move(showDevMenuCallback)) { - attemptConnection(); -} - -PackagerConnection::~PackagerConnection() noexcept { - reconnectThread_.quit(); - if (websocket_) { - websocket_->setOnClosedCallback(nullptr); - websocket_->setOnMessageCallback(nullptr); - websocket_->close("PackagerConnection destroyed"); - } -} - -void PackagerConnection::attemptConnection() { - if (websocket_) { - websocket_->setOnClosedCallback(nullptr); - websocket_->close("reconnecting"); - } - websocket_ = webSocketClientFactory_(); - websocket_->setOnMessageCallback([this](const std::string& message) { - LOG(INFO) << "Received message from packager: " << message; - auto json = nlohmann::json::parse(message, nullptr, false); - if (json.is_discarded() || json.is_null() || json["version"] != 2) { - return; - } - auto method = json["method"]; - if (method == "reload") { - liveReloadCallback_(); - } else if (method == "showDevMenu") { - showDevMenuCallback_(); - } - }); - websocket_->setOnClosedCallback([this](const std::string& reason) { - LOG(INFO) << "PackagerConnection closed: " << reason; - scheduleReconnect(); - }); - websocket_->connect( - packagerConnectionUrl_, - [this](bool success, const std::string& /*error*/) { - if (success) { - if (!isInitialConnection_) { - LOG(INFO) - << "PackagerConnection connected to Metro - triggering live reload"; - liveReloadCallback_(); - } else { - LOG(INFO) << "PackagerConnection connected to Metro"; - } - } else { - scheduleReconnect(); - } - isInitialConnection_ = false; - }); -} - -void PackagerConnection::scheduleReconnect() { - if (reconnectPending_.exchange(true)) { - return; - } - reconnectThread_.runAsync( - [this]() { - reconnectPending_ = false; - attemptConnection(); - }, - std::chrono::milliseconds(5000)); -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/PackagerConnection.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/PackagerConnection.h deleted file mode 100644 index 7e1596c0f2..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/PackagerConnection.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -class PackagerConnection { - using LiveReloadCallback = std::function; - using ShowDevMenuCallback = std::function; - - public: - PackagerConnection( - WebSocketClientFactory webSocketClientFactory, - std::string packagerConnectionUrl, - LiveReloadCallback &&liveReloadCallback, - ShowDevMenuCallback &&showDevMenuCallback); - ~PackagerConnection() noexcept; - PackagerConnection(const PackagerConnection &other) = delete; - PackagerConnection &operator=(PackagerConnection &other) = delete; - PackagerConnection(PackagerConnection &&other) = delete; - PackagerConnection &operator=(PackagerConnection &&other) = delete; - - private: - void attemptConnection(); - void scheduleReconnect(); - - const WebSocketClientFactory webSocketClientFactory_; - const std::string packagerConnectionUrl_; - const LiveReloadCallback liveReloadCallback_; - const ShowDevMenuCallback showDevMenuCallback_; - std::unique_ptr websocket_; - std::atomic isInitialConnection_{true}; - std::atomic reconnectPending_{false}; - TaskDispatchThread reconnectThread_{"PackagerReconnect"}; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/SourceCodeModule.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/SourceCodeModule.cpp deleted file mode 100644 index d7ccc10514..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/SourceCodeModule.cpp +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "SourceCodeModule.h" - -namespace facebook::react { - -SourceCodeConstants SourceCodeModule::getConstants(jsi::Runtime& /*rt*/) { - return SourceCodeConstants{.scriptURL = sourceURL_}; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/SourceCodeModule.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/SourceCodeModule.h deleted file mode 100644 index 7924c5ad1b..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/SourceCodeModule.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include - -namespace facebook::react { - -using SourceCodeConstants = NativeSourceCodeSourceCodeConstants; - -template <> -struct Bridging : NativeSourceCodeSourceCodeConstantsBridging {}; - -class SourceCodeModule : public NativeSourceCodeCxxSpec { - public: - explicit SourceCodeModule(std::shared_ptr jsInvoker, std::string sourceURL = "") - : NativeSourceCodeCxxSpec(jsInvoker), sourceURL_(std::move(sourceURL)) - { - } - - SourceCodeConstants getConstants(jsi::Runtime &rt); - - private: - std::string sourceURL_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/Inspector.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/Inspector.cpp deleted file mode 100644 index 68a82cf1df..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/Inspector.cpp +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "Inspector.h" -#include "InspectorPackagerConnectionDelegate.h" - -#include -#include - -namespace facebook::react { - -namespace { - -constexpr std::string_view INTEGRATION_NAME = "RNHOST"; - -class InspectorHostTargetDelegate - : public jsinspector_modern::HostTargetDelegate, - public std::enable_shared_from_this { - public: - InspectorHostTargetDelegate( - std::string appName, - std::string deviceName, - const HttpClientFactory& httpClientFactory, - LiveReloadCallbackFn&& liveReloadCallbackFn, - ToggleDebuggerOverlayFn&& toggleDebuggerOverlayFn) noexcept - : appName_(std::move(appName)), - deviceName_(std::move(deviceName)), - httpClient_(httpClientFactory()), - liveReloadCallbackFn_(std::move(liveReloadCallbackFn)), - toggleDebuggerOverlayFn_(std::move(toggleDebuggerOverlayFn)) {} - - jsinspector_modern::HostTargetMetadata getMetadata() override { - return { - .appIdentifier = appName_, - .deviceName = deviceName_, - .integrationName = std::string(INTEGRATION_NAME), - }; - } - - void onReload( - const jsinspector_modern::HostTargetDelegate::PageReloadRequest& - /*request*/) override { - if (liveReloadCallbackFn_ != nullptr) { - liveReloadCallbackFn_(); - } - } - - void onSetPausedInDebuggerMessage( - const jsinspector_modern::HostTargetDelegate:: - OverlaySetPausedInDebuggerMessageRequest& request) override { - if (toggleDebuggerOverlayFn_ != nullptr) { - toggleDebuggerOverlayFn_( - request.message.has_value(), [target = target_]() { - if (auto strongTarget = target.lock()) { - strongTarget->sendCommand( - jsinspector_modern::HostCommand::DebuggerResume); - } - }); - } - } - - void loadNetworkResource( - const jsinspector_modern::LoadNetworkResourceRequest& params, - jsinspector_modern::ScopedExecutor< - jsinspector_modern::NetworkRequestListener> executor) override { - http::NetworkCallbacks callbacks{ - .onResponse = - [executor]( - uint32_t responseCode, - const http::Headers& headers, - const std::string& /*responseUrl*/) { - executor([responseCode, headers]( - jsinspector_modern::NetworkRequestListener& - listener) { - facebook::react::jsinspector_modern::Headers responseHeaders; - for (const auto& [key, value] : headers) { - responseHeaders[key] = value; - } - listener.onHeaders(responseCode, responseHeaders); - }); - }, - .onBody = - [executor](std::unique_ptr ioBuf) { - executor( - [response = ioBuf->moveToFbString().toStdString()]( - jsinspector_modern::NetworkRequestListener& listener) { - listener.onData(response); - }); - }, - .onResponseComplete = - [executor, url = params.url]( - const std::string& error, bool timeout) { - if (error.empty() && !timeout) { - executor( - [](jsinspector_modern::NetworkRequestListener& listener) { - listener.onCompletion(); - }); - } else { - executor( - [errorMessage = - "Failed to download JS bundle from Url: " + url + - ". Error: " + (error.empty() ? "Timeout" : error)]( - jsinspector_modern::NetworkRequestListener& listener) { - listener.onError(errorMessage); - }); - } - }}; - httpClient_->sendRequest(std::move(callbacks), "GET", params.url); - } - - void setTarget(std::weak_ptr target) { - target_ = std::move(target); - } - - private: - std::string appName_; - std::string deviceName_; - std::unique_ptr httpClient_; - LiveReloadCallbackFn liveReloadCallbackFn_; - ToggleDebuggerOverlayFn toggleDebuggerOverlayFn_; - std::weak_ptr target_; -}; - -} // namespace - -Inspector::Inspector( - std::string appName, - std::string deviceName, - WebSocketClientFactory webSocketClientFactory, - HttpClientFactory httpClientFactory) noexcept - : appName_(std::move(appName)), - deviceName_(std::move(deviceName)), - webSocketClientFactory_(std::move(webSocketClientFactory)), - httpClientFactory_(std::move(httpClientFactory)) {} - -Inspector::~Inspector() noexcept { - if (pageId_) { - jsinspector_modern::getInspectorInstance().removePage(*pageId_); - taskDispatchThread_.runSync([weakThis = weak_from_this()]() { - if (auto strongThis = weakThis.lock()) { - strongThis->pageId_.reset(); - strongThis->target_.reset(); - } - }); - } - taskDispatchThread_.quit(); -} - -void Inspector::connectDebugger(const std::string& inspectorUrl) noexcept { - invokeElsePost([weakThis = weak_from_this(), inspectorUrl]() { - auto self = weakThis.lock(); - if (!self) { - return; - } - if (!self->packagerConnection_) { - self->packagerConnection_ = - std::make_unique( - inspectorUrl, - self->deviceName_, - self->appName_, - std::make_unique( - weakThis, self->webSocketClientFactory_)); - } - if (!self->packagerConnection_->isConnected()) { - self->packagerConnection_->connect(); - } - }); -} - -void Inspector::disconnectDebugger() noexcept { - invokeElsePost([weakThis = weak_from_this()]() { - if (auto self = weakThis.lock()) { - self->packagerConnection_.reset(); - } - }); -} - -void Inspector::ensureHostTarget( - LiveReloadCallbackFn&& liveReloadCallbackFn, - ToggleDebuggerOverlayFn&& toggleDebuggerOverlayFn) noexcept { - hostDelegate_ = std::make_shared( - appName_, - deviceName_, - httpClientFactory_, - std::move(liveReloadCallbackFn), - std::move(toggleDebuggerOverlayFn)); - target_ = jsinspector_modern::HostTarget::create( - *hostDelegate_, - [weakThis = weak_from_this()](std::function&& callback) { - if (auto strongThis = weakThis.lock()) { - strongThis->invokeElsePost(std::move(callback)); - } - }); - static_cast(*hostDelegate_).setTarget(target_); - jsinspector_modern::InspectorTargetCapabilities capabilities{ - .nativePageReloads = true}; - pageId_ = jsinspector_modern::getInspectorInstance().addPage( - std::string(INTEGRATION_NAME), - "", /*vm*/ - [weakInspectorTarget = std::weak_ptr(target_)]( - std::unique_ptr remote) - -> std::unique_ptr { - if (auto inspectorTarget = weakInspectorTarget.lock()) { - return inspectorTarget->connect(std::move(remote)); - } - // Reject the connection on destruction - return nullptr; - }, - capabilities); -} - -void Inspector::invokeElsePost( - TaskDispatchThread::TaskFn&& callback, - std::chrono::milliseconds delayMs) { - if (taskDispatchThread_.isOnThread() && - delayMs == std::chrono::milliseconds::zero()) { - callback(); - } else { - taskDispatchThread_.runAsync(std::move(callback), delayMs); - } -} - -std::shared_ptr Inspector::inspectorTarget() - const { - return target_; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/Inspector.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/Inspector.h deleted file mode 100644 index 886f32a6e3..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/Inspector.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include "InspectorThread.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -using ToggleDebuggerOverlayFn = std::function &&)>; - -using LiveReloadCallbackFn = std::function; - -class Inspector : public InspectorThread, public std::enable_shared_from_this { - public: - Inspector( - std::string appName, - std::string deviceName, - WebSocketClientFactory webSocketClientFactory, - HttpClientFactory httpClientFactory) noexcept; - ~Inspector() noexcept override; - Inspector(const Inspector &other) = delete; - Inspector &operator=(Inspector &other) = delete; - Inspector(Inspector &&other) = delete; - Inspector &operator=(Inspector &&other) = delete; - - void connectDebugger(const std::string &inspectorUrl) noexcept; - - // react-native-gpui: drop the connection to the dev server, so the next - // `connectDebugger` connects to the URL it is given (the server changed). - void disconnectDebugger() noexcept; - - void ensureHostTarget( - LiveReloadCallbackFn &&liveReloadCallbackFn, - ToggleDebuggerOverlayFn &&toggleDebuggerOverlayFn) noexcept; - - std::shared_ptr inspectorTarget() const; - - private: - void invokeElsePost( - TaskDispatchThread::TaskFn &&callback, - std::chrono::milliseconds delayMs = std::chrono::milliseconds::zero()) override; - - TaskDispatchThread taskDispatchThread_{"InspectorThread"}; - std::string appName_; - std::string deviceName_; - WebSocketClientFactory webSocketClientFactory_; - HttpClientFactory httpClientFactory_; - std::shared_ptr hostDelegate_; - std::shared_ptr target_; - std::optional pageId_; - std::unique_ptr packagerConnection_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/InspectorPackagerConnectionDelegate.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/InspectorPackagerConnectionDelegate.cpp deleted file mode 100644 index 86dbca6a26..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/InspectorPackagerConnectionDelegate.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "InspectorPackagerConnectionDelegate.h" - -#include -#include - -namespace facebook::react { - -InspectorPackagerConnectionDelegate::WebSocket::WebSocket( - const std::string& url, - std::weak_ptr webSocketDelegate, - std::weak_ptr inspectorThread, - const WebSocketClientFactory& webSocketClientFactory) - : webSocketDelegate_{webSocketDelegate}, - inspectorThread_(std::move(inspectorThread)) { - websocket_ = webSocketClientFactory(); - websocket_->setOnMessageCallback( - [webSocketDelegate, - inspectorThread = inspectorThread_](const std::string& message) { - auto strongInspectorThread = inspectorThread.lock(); - if (!strongInspectorThread) { - return; - } - strongInspectorThread->invokeElsePost([webSocketDelegate, message]() { - if (const auto strongDelegate = webSocketDelegate.lock()) { - strongDelegate->didReceiveMessage(message); - } - }); - }); - websocket_->setOnClosedCallback( - [webSocketDelegate, - inspectorThread = inspectorThread_](const std::string& /*message*/) { - auto strongInspectorThread = inspectorThread.lock(); - if (!strongInspectorThread) { - return; - } - strongInspectorThread->invokeElsePost([webSocketDelegate]() { - if (const auto strongDelegate = webSocketDelegate.lock()) { - strongDelegate->didClose(); - } - }); - }); - websocket_->connect( - url, - [webSocketDelegate, inspectorThread = inspectorThread_]( - bool success, const std::string& message) { - auto strongInspectorThread = inspectorThread.lock(); - if (!strongInspectorThread) { - return; - } - strongInspectorThread->invokeElsePost( - [webSocketDelegate, success, message]() { - if (auto strongDelegate = webSocketDelegate.lock()) { - if (success) { - strongDelegate->didOpen(); - } else { - // Assume the server is not running, and suppress an error log - strongDelegate->didFailWithError(ECONNREFUSED, message); - } - } - }); - }); -} - -InspectorPackagerConnectionDelegate::WebSocket::~WebSocket() { - websocket_->close("InspectorPackagerConnectionDelegate destroyed"); -}; - -void InspectorPackagerConnectionDelegate::WebSocket::send( - std::string_view message) { - if (auto strongInspectorThread = inspectorThread_.lock()) { - strongInspectorThread->invokeElsePost( - [this, message = std::string(message)]() { - if (websocket_) { - websocket_->send(message); - } - }); - } -} - -InspectorPackagerConnectionDelegate::InspectorPackagerConnectionDelegate( - std::weak_ptr inspectorThread, - WebSocketClientFactory webSocketClientFactory) noexcept - : inspectorThread_(std::move(inspectorThread)), - webSocketClientFactory_(std::move(webSocketClientFactory)) {} - -std::unique_ptr -InspectorPackagerConnectionDelegate::connectWebSocket( - const std::string& url, - std::weak_ptr delegate) { - return std::make_unique( - url, delegate, inspectorThread_, webSocketClientFactory_); -} - -void InspectorPackagerConnectionDelegate::scheduleCallback( - std::function callback, - std::chrono::milliseconds delayMs) { - if (auto inspectorThread = inspectorThread_.lock()) { - inspectorThread->invokeElsePost(std::move(callback), delayMs); - } -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/InspectorPackagerConnectionDelegate.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/InspectorPackagerConnectionDelegate.h deleted file mode 100644 index e91d5be9f6..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/InspectorPackagerConnectionDelegate.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include "InspectorThread.h" - -#include -#include -#include -#include -#include - -namespace facebook::react { - -class IWebSocketClient; - -class InspectorPackagerConnectionDelegate final : public jsinspector_modern::InspectorPackagerConnectionDelegate { - class WebSocket : public jsinspector_modern::IWebSocket { - public: - WebSocket( - const std::string &url, - std::weak_ptr webSocketDelegate, - std::weak_ptr inspectorThread, - const WebSocketClientFactory &webSocketClientFactory); - ~WebSocket() override; - WebSocket(const WebSocket &other) = delete; - WebSocket &operator=(WebSocket &other) = delete; - WebSocket(WebSocket &&other) = delete; - WebSocket &operator=(WebSocket &&other) = delete; - - void send(std::string_view message) override; - - private: - std::weak_ptr webSocketDelegate_; - std::weak_ptr inspectorThread_; - std::unique_ptr websocket_; - }; - - public: - InspectorPackagerConnectionDelegate( - std::weak_ptr inspectorThread, - WebSocketClientFactory webSocketClientFactory) noexcept; - - std::unique_ptr connectWebSocket( - const std::string &url, - std::weak_ptr delegate) override; - - void scheduleCallback( - std::function callback, - std::chrono::milliseconds delayMs = std::chrono::milliseconds::zero()) override; - - private: - std::weak_ptr inspectorThread_; - WebSocketClientFactory webSocketClientFactory_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/InspectorThread.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/InspectorThread.h deleted file mode 100644 index 1dbee83051..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/devsupport/inspector/InspectorThread.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include - -namespace facebook::react { - -class InspectorThread { - public: - InspectorThread() noexcept = default; - virtual ~InspectorThread() = default; - InspectorThread(const InspectorThread &other) = delete; - InspectorThread &operator=(InspectorThread &other) = delete; - InspectorThread(InspectorThread &&other) = delete; - InspectorThread &operator=(InspectorThread &&other) = delete; - - virtual void invokeElsePost( - TaskDispatchThread::TaskFn &&callback, - std::chrono::milliseconds delayMs = std::chrono::milliseconds(0)) = 0; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/CMakeLists.txt b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/CMakeLists.txt deleted file mode 100644 index e25095d9f5..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -include(${REACT_COMMON_DIR}/cmake-utils/react-native-flags.cmake) - -file(GLOB react_cxx_platform_react_http_SRC CONFIGURE_DEPENDS *.cpp) -add_library(react_cxx_platform_react_http OBJECT ${react_cxx_platform_react_http_SRC}) - -target_include_directories(react_cxx_platform_react_http PUBLIC ${REACT_CXX_PLATFORM_DIR}) - -target_link_libraries(react_cxx_platform_react_http - folly_runtime -) -target_compile_reactnative_options(react_cxx_platform_react_http PRIVATE) -target_compile_options(react_cxx_platform_react_http PRIVATE -Wpedantic) diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/IHttpClient.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/IHttpClient.cpp deleted file mode 100644 index 59774dabb4..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/IHttpClient.cpp +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -namespace facebook::react { - -// NOLINTNEXTLINE(modernize-avoid-c-arrays) -extern const char HttpClientFactoryKey[] = "HttpClientFactory"; - -// NOLINTNEXTLINE(modernize-avoid-c-arrays) -extern const char DevToolsHttpClientFactoryKey[] = "DevToolsHttpClientFactory"; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/IHttpClient.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/IHttpClient.h deleted file mode 100644 index 6249505dec..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/IHttpClient.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -namespace http { - -using Headers = std::vector>; - -struct FormDataField { - std::string fieldName; - Headers headers; - std::optional string; - std::optional uri; -}; - -struct BlobReference { - std::string blobId; - uint64_t offset{0}; - uint64_t size{0}; -}; - -using FormData = std::vector; - -struct Body { - std::optional string; - std::optional blob; - std::optional formData; - std::optional base64; - bool withCredentials{true}; -}; - -using OnUploadProgress = std::function; -using OnResponse = std::function; -using OnBody = std::function body)>; -using OnBodyIncremental = std::function body)>; -using OnBodyProgress = std::function; -using OnResponseComplete = std::function; - -struct NetworkCallbacks { - OnUploadProgress onUploadProgress{nullptr}; - OnResponse onResponse{nullptr}; - OnBody onBody{nullptr}; - OnBodyIncremental onBodyIncremental{nullptr}; - OnBodyProgress onBodyProgress{nullptr}; - OnResponseComplete onResponseComplete{nullptr}; - bool sendIncrementalUpdates{false}; - bool sendProgressUpdates{false}; -}; - -struct IRequestToken { - virtual ~IRequestToken() = default; - - virtual void cancel() noexcept = 0; -}; - -} // namespace http - -struct IHttpClient { - virtual ~IHttpClient() = default; - - virtual std::unique_ptr sendRequest( - http::NetworkCallbacks &&callback, - const std::string &method, - const std::string &url, - const http::Headers &headers = {}, - const http::Body &body = {}, - uint32_t timeout = 0, - std::optional loggingId = std::nullopt) = 0; -}; - -extern const char HttpClientFactoryKey[]; - -extern const char DevToolsHttpClientFactoryKey[]; - -using HttpClientFactory = std::function()>; - -HttpClientFactory getHttpClientFactory(); - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/IWebSocketClient.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/IWebSocketClient.cpp deleted file mode 100644 index 838f687e37..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/IWebSocketClient.cpp +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -namespace facebook::react { - -// NOLINTNEXTLINE(modernize-avoid-c-arrays) -extern const char WebSocketClientFactoryKey[] = "WebSocketClientFactory"; - -// NOLINTNEXTLINE(modernize-avoid-c-arrays) -extern const char DevToolsWebSocketClientFactoryKey[] = - "DevToolsWebSocketClientFactory"; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/IWebSocketClient.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/IWebSocketClient.h deleted file mode 100644 index 7bbb36c766..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/IWebSocketClient.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace facebook::react { - -class IWebSocketClient { - public: - using OnConnectCallback = std::function; - using OnClosedCallback = std::function; - using OnMessageCallback = std::function; - using OnMessageFrameCallback = std::function; - using OnClosedFrameCallback = std::function; - - virtual ~IWebSocketClient() = default; - - virtual void setOnClosedCallback(OnClosedCallback &&callback) noexcept = 0; - - virtual void setOnMessageCallback(OnMessageCallback &&callback) noexcept = 0; - - virtual void setOnMessageFrameCallback(OnMessageFrameCallback &&callback) noexcept { - setOnMessageCallback([callback = std::move(callback)](const std::string &message) { - callback(message, false); - }); - } - - virtual void setOnClosedFrameCallback(OnClosedFrameCallback &&callback) noexcept { - setOnClosedCallback([callback = std::move(callback)](const std::string &reason) { - callback(1006, reason); - }); - } - - virtual void connect(const std::string &url, OnConnectCallback && = nullptr) = 0; - - virtual void close(const std::string &reason) = 0; - - virtual void close(uint16_t code, const std::string &reason) { - (void)code; - close(reason); - } - - virtual void send(const std::string &message) = 0; - - virtual void sendBinary(const std::string &bytes) { - send(bytes); - } - - virtual void ping() = 0; -}; - -extern const char WebSocketClientFactoryKey[]; - -extern const char DevToolsWebSocketClientFactoryKey[]; - -using WebSocketClientFactory = std::function()>; - -WebSocketClientFactory getWebSocketClientFactory(); - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/platform/cxx/WebSocketClient.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/platform/cxx/WebSocketClient.cpp deleted file mode 100644 index 907fc1efeb..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/platform/cxx/WebSocketClient.cpp +++ /dev/null @@ -1,606 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "WebSocketClient.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if defined(__APPLE__) -#include -#endif -#if defined(_WIN32) -#include -#include -#include -#include -#endif - -namespace facebook::react { - -namespace { -std::atomic webSocketMessagesInFlight{0}; - -using PlainWebSocket = - boost::beast::websocket::stream; -using TlsWebSocket = boost::beast::websocket::stream< - boost::beast::ssl_stream>; -using AnyWebSocket = std::variant; - -#if defined(__APPLE__) -bool verifyWithMacSystemTrust( - const std::string& hostname, - X509_STORE_CTX* storeContext) { - CFMutableArrayRef certificates = - CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); - if (certificates == nullptr) { - return false; - } - - auto* chain = X509_STORE_CTX_get0_chain(storeContext); - const int certificateCount = chain == nullptr ? 0 : sk_X509_num(chain); - for (int index = 0; index < certificateCount; ++index) { - auto* certificate = sk_X509_value(chain, index); - const int encodedSize = i2d_X509(certificate, nullptr); - if (encodedSize <= 0) { - CFRelease(certificates); - return false; - } - std::vector encoded(static_cast(encodedSize)); - auto* encodedCursor = encoded.data(); - i2d_X509(certificate, &encodedCursor); - CFDataRef data = CFDataCreate( - kCFAllocatorDefault, - encoded.data(), - static_cast(encoded.size())); - SecCertificateRef secCertificate = - SecCertificateCreateWithData(kCFAllocatorDefault, data); - CFRelease(data); - if (secCertificate == nullptr) { - CFRelease(certificates); - return false; - } - CFArrayAppendValue(certificates, secCertificate); - CFRelease(secCertificate); - } - - CFStringRef host = CFStringCreateWithCString( - kCFAllocatorDefault, hostname.c_str(), kCFStringEncodingUTF8); - SecPolicyRef policy = SecPolicyCreateSSL(true, host); - CFRelease(host); - SecTrustRef trust = nullptr; - const auto createStatus = - SecTrustCreateWithCertificates(certificates, policy, &trust); - CFRelease(policy); - CFRelease(certificates); - if (createStatus != errSecSuccess || trust == nullptr) { - return false; - } - const bool trusted = SecTrustEvaluateWithError(trust, nullptr); - CFRelease(trust); - return trusted; -} -#endif - -#if defined(_WIN32) -void loadWindowsSystemRoots(boost::asio::ssl::context& context) { - const DWORD scopes[] = { - CERT_SYSTEM_STORE_CURRENT_USER, CERT_SYSTEM_STORE_LOCAL_MACHINE}; - for (const auto scope : scopes) { - HCERTSTORE store = CertOpenStore( - CERT_STORE_PROV_SYSTEM_W, - 0, - 0, - scope | CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG, - L"ROOT"); - if (store == nullptr) { - continue; - } - PCCERT_CONTEXT certificateContext = nullptr; - while ((certificateContext = CertEnumCertificatesInStore( - store, certificateContext)) != nullptr) { - const unsigned char* encoded = certificateContext->pbCertEncoded; - X509* certificate = d2i_X509( - nullptr, - &encoded, - static_cast(certificateContext->cbCertEncoded)); - if (certificate != nullptr) { - X509_STORE_add_cert( - SSL_CTX_get_cert_store(context.native_handle()), certificate); - X509_free(certificate); - ERR_clear_error(); // Ignore duplicate certificates in the store. - } - } - CertCloseStore(store, 0); - } -} -#endif -} // namespace - -extern "C" uint64_t rn_gpui_websocket_messages_in_flight() noexcept { - return webSocketMessagesInFlight.load(std::memory_order_relaxed); -} - -struct WebSocketClient::Impl final : public std::enable_shared_from_this { - void onResolveCompleted( - boost::system::error_code ec, - const boost::asio::ip::tcp::resolver::results_type& results); - - void onConnectionCompleted(boost::system::error_code ec); - - void onTlsHandshakeCompleted(boost::system::error_code ec); - - void onHandshakeCompleted(boost::system::error_code ec); - - void listen(); - - void write(); - - void onConnectCallback(bool connected, const std::string& error); - void onClosed(uint16_t code, const std::string& reason); - - // Callbacks and Uri - OnConnectCallback onConnectCallback_; - OnClosedCallback onClosedCallback_; - OnMessageCallback onMessageCallback_; - OnMessageFrameCallback onMessageFrameCallback_; - OnClosedFrameCallback onClosedFrameCallback_; - std::optional uri_; - - // Boost Beast WebSocket Client - boost::asio::io_context ioContext_; - boost::asio::ip::tcp::resolver resolver_{ioContext_}; - boost::beast::multi_buffer buffer_; - boost::asio::ssl::context tlsContext_{boost::asio::ssl::context::tls_client}; - folly::Synchronized ws_{ - AnyWebSocket{PlainWebSocket{ioContext_}}}; - - // Input and Output handling - std::mutex mutexOut_; - std::queue> messagesOut_; - std::atomic isWriting_{false}; - std::atomic isClosing_{false}; - std::atomic didReportClosed_{false}; -}; - -WebSocketClient::WebSocketClient() noexcept - : impl_(std::make_shared()) {} - -WebSocketClient::~WebSocketClient() { - WebSocketClient::close("Force close as WebSocketClient being destroyed"); -} - -void WebSocketClient::setOnClosedCallback( - OnClosedCallback&& callback) noexcept { - impl_->onClosedCallback_ = std::move(callback); -} - -void WebSocketClient::setOnMessageCallback( - OnMessageCallback&& callback) noexcept { - impl_->onMessageCallback_ = std::move(callback); -} - -void WebSocketClient::setOnMessageFrameCallback( - OnMessageFrameCallback&& callback) noexcept { - impl_->onMessageFrameCallback_ = std::move(callback); -} - -void WebSocketClient::setOnClosedFrameCallback( - OnClosedFrameCallback&& callback) noexcept { - impl_->onClosedFrameCallback_ = std::move(callback); -} - -void WebSocketClient::connect( - const std::string& url, - OnConnectCallback&& callback) { - if (thread_) { - react_native_assert(false && "WebSocketClient::connect() called twice"); - return; - } - - impl_->onConnectCallback_ = std::move(callback); - impl_->uri_ = folly::Uri{url}; - // React Native hands its own clients http(s) URLs (Metro's HMR client opens - // `http://host:port/hot`) and every platform's socket takes them as ws(s). - if (impl_->uri_->scheme() == "http") { - impl_->uri_ = folly::Uri{"ws" + url.substr(4)}; - } else if (impl_->uri_->scheme() == "https") { - impl_->uri_ = folly::Uri{"wss" + url.substr(5)}; - } - if (impl_->uri_->scheme() != "ws" && impl_->uri_->scheme() != "wss") { - impl_->onConnectCallback(false, "WebSocket URL must use ws:// or wss://"); - return; - } - if (impl_->uri_->scheme() == "wss") { - try { - impl_->tlsContext_.set_default_verify_paths(); - } catch (const std::exception& error) { - LOG(WARNING) << "[gpui-ws] OpenSSL default trust paths unavailable: " - << error.what(); - } - impl_->tlsContext_.set_verify_mode(boost::asio::ssl::verify_peer); -#if defined(_WIN32) - loadWindowsSystemRoots(impl_->tlsContext_); -#endif - auto ws = impl_->ws_.wlock(); - ws->emplace(impl_->ioContext_, impl_->tlsContext_); - auto& tls = std::get(*ws); - const auto hostname = impl_->uri_->hostname(); - tls.next_layer().set_verify_callback( - [hostname]( - bool preverified, boost::asio::ssl::verify_context& verifyContext) { - if (boost::asio::ssl::host_name_verification(hostname)( - preverified, verifyContext)) { - return true; - } -#if defined(__APPLE__) - return verifyWithMacSystemTrust( - hostname, verifyContext.native_handle()); -#else - return false; -#endif - }); - if (SSL_set_tlsext_host_name( - tls.next_layer().native_handle(), - impl_->uri_->hostname().c_str()) != 1) { - impl_->onConnectCallback(false, "Could not configure TLS server name"); - return; - } - } - - // Resolve the domain name - impl_->resolver_.async_resolve( - impl_->uri_->hostname(), - std::to_string( - impl_->uri_->port() == 0 ? (impl_->uri_->scheme() == "wss" ? 443 : 80) - : impl_->uri_->port()), - [weakImpl = std::weak_ptr(impl_)]( - boost::system::error_code ec, - const boost::asio::ip::tcp::resolver::results_type& results) { - if (auto impl = weakImpl.lock()) { - impl->onResolveCompleted(ec, results); - } - }); - - // Start the I/O thread - static int32_t s_threadId = 0; - thread_ = std::make_unique( - [weakImpl = std::weak_ptr(impl_), tid = s_threadId++]() { - folly::setThreadName("WebSocket" + std::to_string(tid)); - if (auto impl = weakImpl.lock()) { - impl->ioContext_.run(); - } - }); -} - -void WebSocketClient::close(const std::string& reason) { - close(1000, reason); -} - -void WebSocketClient::close(uint16_t code, const std::string& reason) { - if (!impl_->isClosing_.exchange(true)) { - impl_->onClosed(code, reason); - { - std::lock_guard lock(impl_->mutexOut_); - const auto queued = impl_->messagesOut_.size(); - while (!impl_->messagesOut_.empty()) impl_->messagesOut_.pop(); - if (queued > 0) - webSocketMessagesInFlight.fetch_sub(queued, std::memory_order_relaxed); - } - { - auto ws = impl_->ws_.wlock(); - std::visit( - [code, &reason](auto& socket) { - if (socket.is_open()) { - boost::beast::websocket::close_reason closeReason; - closeReason.code = - static_cast(code); - closeReason.reason = reason; - socket.async_close(closeReason, [](auto&&) {}); - } else { - boost::system::error_code ignored; - boost::beast::get_lowest_layer(socket).close(ignored); - } - }, - *ws); - } - // Outside the lock: the I/O thread takes it in every completion handler, - // so joining while holding it deadlocks against a connection that is - // still being set up. - if (thread_) { - thread_->join(); - } - } - thread_ = nullptr; -} - -void WebSocketClient::send(const std::string& message) { - { - std::lock_guard lock(impl_->mutexOut_); - if (impl_->isClosing_) return; - impl_->messagesOut_.emplace(message, false); - webSocketMessagesInFlight.fetch_add(1, std::memory_order_relaxed); - } - impl_->write(); -} - -void WebSocketClient::sendBinary(const std::string& bytes) { - { - std::lock_guard lock(impl_->mutexOut_); - if (impl_->isClosing_) return; - impl_->messagesOut_.emplace(bytes, true); - webSocketMessagesInFlight.fetch_add(1, std::memory_order_relaxed); - } - impl_->write(); -} - -void WebSocketClient::ping() { - auto ws = impl_->ws_.wlock(); - std::visit( - [weakImpl = std::weak_ptr(impl_)](auto& socket) { - socket.async_ping({}, [weakImpl](boost::beast::error_code ec) { - auto impl = weakImpl.lock(); - if (!impl || impl->isClosing_) { - return; - } - if (ec) { - LOG(ERROR) << "Error pinging websocket: " << ec.message(); - } - }); - }, - *ws); -} - -void WebSocketClient::Impl::onResolveCompleted( - boost::system::error_code ec, - const boost::asio::ip::tcp::resolver::results_type& results) { - if (ec) { - // TODO: Handle retry logic here - onConnectCallback(false, "Failed to resolve host"); - return; - } - if (isClosing_) { - // `close()` already closed the socket; connecting now would reopen it and - // keep `close()` waiting on this thread until the attempt fails. - return; - } - - auto ws = ws_.wlock(); - std::visit( - [weakImpl = weak_from_this(), &results](auto& socket) { - boost::asio::async_connect( - boost::beast::get_lowest_layer(socket), - results.begin(), - results.end(), - [weakImpl](boost::system::error_code connectError, const auto&) { - if (auto impl = weakImpl.lock()) { - impl->onConnectionCompleted(connectError); - } - }); - }, - *ws); -} - -void WebSocketClient::Impl::onConnectionCompleted( - boost::system::error_code ec) { - if (ec) { - // TODO: Handle retry logic here - onConnectCallback(false, "Failed to connect"); - return; - } - - { - auto ws = ws_.wlock(); - if (std::holds_alternative(*ws)) { - std::get(*ws).next_layer().async_handshake( - boost::asio::ssl::stream_base::client, - [weakImpl = - weak_from_this()](boost::system::error_code handshakeError) { - if (auto impl = weakImpl.lock()) { - impl->onTlsHandshakeCompleted(handshakeError); - } - }); - return; - } - } - // Outside the lock: `onTlsHandshakeCompleted` takes it again, and it is not - // recursive, so a plain ws:// connection would stop here for good. - onTlsHandshakeCompleted({}); -} - -void WebSocketClient::Impl::onTlsHandshakeCompleted( - boost::system::error_code ec) { - if (ec) { - onConnectCallback(false, "TLS handshake failed: " + ec.message()); - onClosed(1006, ec.message()); - return; - } - auto ws = ws_.wlock(); - // https://datatracker.ietf.org/doc/html/rfc6455#section-3: - // > The "resource-name" (also known as /resource name/ in - // > https://datatracker.ietf.org/doc/html/rfc6455#section-4.1) - // > can be constructed by concatenating the following: - // > - // > o "/" if the path component is empty - // > - // > o the path component - // > - // > o "?" if the query component is non-empty - // > - // > o the query component - auto resourceName = (uri_->path().empty() ? "/" : uri_->path()) + - (uri_->query().empty() ? "" : "?" + uri_->query()); - // Perform the websocket handshake - const auto port = - uri_->port() == 0 ? (uri_->scheme() == "wss" ? 443 : 80) : uri_->port(); - const auto host = uri_->host() + ":" + std::to_string(port); - std::visit( - [weakImpl = weak_from_this(), host, resourceName](auto& socket) { - socket.async_handshake( - host, - resourceName, - [weakImpl](boost::system::error_code handshakeError) { - if (auto impl = weakImpl.lock()) { - impl->onHandshakeCompleted(handshakeError); - } - }); - }, - *ws); -} - -void WebSocketClient::Impl::onHandshakeCompleted(boost::system::error_code ec) { - if (ec) { - // TODO: Handle retry logic here - onConnectCallback(false, "Failed to handshake"); - return; - } - - onConnectCallback(true, "Connected"); - // Listen for any messages from the server - listen(); - - // Start writing any buffered messages - write(); -} - -void WebSocketClient::Impl::listen() { - if (isClosing_) { - return; - } - auto ws = ws_.wlock(); - std::visit( - [this, weakImpl = weak_from_this()](auto& socket) { - socket.async_read( - buffer_, - [weakImpl]( - boost::beast::error_code ec, std::size_t bytes_transferred) { - auto impl = weakImpl.lock(); - if (!impl || impl->isClosing_) { - return; - } - if (ec) { - if (ec == boost::beast::websocket::error::closed) { - auto ws = impl->ws_.rlock(); - const auto& reason = std::visit( - [](const auto& current) -> const auto& { - return current.reason(); - }, - *ws); - impl->onClosed( - static_cast(reason.code), - std::string(reason.reason.data(), reason.reason.size())); - } else { - LOG(ERROR) - << "Error reading from websocket: " << ec.message(); - impl->onClosed(1006, ec.message()); - } - return; - } - std::string message( - boost::beast::buffers_to_string(impl->buffer_.data())); - const bool isBinary = std::visit( - [](const auto& current) { return !current.got_text(); }, - *impl->ws_.rlock()); - if (impl->onMessageCallback_) { - impl->onMessageCallback_(message); - } - if (impl->onMessageFrameCallback_) { - impl->onMessageFrameCallback_(message, isBinary); - } - impl->buffer_.consume(bytes_transferred); - impl->listen(); - }); - }, - *ws); -} - -void WebSocketClient::Impl::write() { - // `send()` calls this on the caller's thread and a finished write calls it - // on the I/O thread. Beast allows one write in flight per stream, so - // claiming the write slot and taking the message happen together under - // `mutexOut_`: two threads can't both start a write, and a message queued - // while a write finishes isn't left behind. - std::shared_ptr> message; - { - std::lock_guard lock(mutexOut_); - if (isClosing_ || isWriting_ || messagesOut_.empty()) { - return; - } - isWriting_ = true; - message = std::make_shared>( - std::move(messagesOut_.front())); - messagesOut_.pop(); - } - - auto ws = ws_.wlock(); - std::visit( - [message, weakImpl = weak_from_this()](auto& socket) { - socket.binary(message->second); - socket.async_write( - boost::beast::net::buffer(message->first), - [message, weakImpl]( - boost::beast::error_code ec, - std::size_t /*bytes_transferred*/) mutable { - webSocketMessagesInFlight.fetch_sub(1, std::memory_order_relaxed); - auto impl = weakImpl.lock(); - if (!impl) { - return; - } - { - std::lock_guard lock(impl->mutexOut_); - impl->isWriting_ = false; - } - if (ec) { - LOG(ERROR) << "Error writing to websocket: " << ec.message(); - return; - } - impl->write(); - message.reset(); // Release the message after it's been sent - }); - }, - *ws); -} - -void WebSocketClient::Impl::onConnectCallback( - bool connected, - const std::string& error) { - if (!connected) { - LOG(WARNING) << "WebSocket " << (uri_ ? uri_->host() : "") << " did not connect: " << error; - } - if (onConnectCallback_) { - onConnectCallback_(connected, error); - } -} - -void WebSocketClient::Impl::onClosed(uint16_t code, const std::string& reason) { - if (didReportClosed_.exchange(true)) { - return; - } - if (onClosedFrameCallback_) { - onClosedFrameCallback_(code, reason); - } - if (onClosedCallback_) { - onClosedCallback_(reason); - } -} - -WebSocketClientFactory getWebSocketClientFactory() { - return []() { return std::make_unique(); }; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/platform/cxx/WebSocketClient.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/platform/cxx/WebSocketClient.h deleted file mode 100644 index 9526c0cf24..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/http/platform/cxx/WebSocketClient.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include - -namespace facebook::react { - -class WebSocketClient : public IWebSocketClient { - public: - WebSocketClient() noexcept; - ~WebSocketClient() override; - WebSocketClient(WebSocketClient &other) = delete; - WebSocketClient &operator=(WebSocketClient &other) = delete; - WebSocketClient(WebSocketClient &&other) = delete; - WebSocketClient &operator=(WebSocketClient &&other) = delete; - - void setOnClosedCallback(OnClosedCallback &&callback) noexcept override; - - void setOnMessageCallback(OnMessageCallback &&callback) noexcept override; - void setOnMessageFrameCallback(OnMessageFrameCallback &&callback) noexcept override; - void setOnClosedFrameCallback(OnClosedFrameCallback &&callback) noexcept override; - - void connect(const std::string &url, OnConnectCallback &&onConnectCallback = nullptr) override; - - void close(const std::string &reason) override; - void close(uint16_t code, const std::string &reason) override; - - void send(const std::string &message) override; - void sendBinary(const std::string &bytes) override; - - void ping() override; - - private: - struct Impl; - - // Instance data and IO thread - const std::shared_ptr impl_; - std::unique_ptr thread_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/BlobModule.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/BlobModule.cpp deleted file mode 100644 index a4317224c4..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/BlobModule.cpp +++ /dev/null @@ -1,133 +0,0 @@ -#include "BlobModule.h" - -#include -#include -#include -#include -#include -#include -#include - -namespace facebook::react { -namespace { -std::mutex blobMutex; -std::unordered_map blobs; -std::unordered_set blobWebSocketHandlers; - -http::BlobReference blobReference(jsi::Runtime& rt, const jsi::Object& value) { - http::BlobReference reference; - reference.blobId = value.getProperty(rt, "blobId").asString(rt).utf8(rt); - reference.offset = static_cast( - value.getProperty(rt, "offset").asNumber()); - reference.size = static_cast( - value.getProperty(rt, "size").asNumber()); - return reference; -} -} // namespace - -BlobModule::BlobModule(std::shared_ptr jsInvoker) - : NativeBlobModuleCxxSpec(std::move(jsInvoker)) {} - -jsi::Object BlobModule::getConstants(jsi::Runtime& rt) { - jsi::Object constants(rt); - constants.setProperty( - rt, "BLOB_URI_SCHEME", jsi::String::createFromAscii(rt, "blob")); - constants.setProperty( - rt, "BLOB_URI_HOST", jsi::String::createFromAscii(rt, "gpui.local")); - return constants; -} - -void BlobModule::addNetworkingHandler(jsi::Runtime& /*rt*/) {} - -void BlobModule::addWebSocketHandler(jsi::Runtime& /*rt*/, double socketId) { - setBlobWebSocketHandler(static_cast(socketId), true); -} - -void BlobModule::removeWebSocketHandler( - jsi::Runtime& /*rt*/, - double socketId) { - setBlobWebSocketHandler(static_cast(socketId), false); -} - -void BlobModule::sendOverSocket( - jsi::Runtime& rt, - jsi::Object blob, - double socketId) { - auto reference = blobReference(rt, blob); - auto bytes = readBlob(reference.blobId, reference.offset, reference.size); - if (!bytes) { - throw jsi::JSError(rt, "Blob data is no longer available"); - } - if (!sendBlobOverWebSocket(static_cast(socketId), *bytes)) { - throw jsi::JSError(rt, "WebSocket is no longer available"); - } -} - -void BlobModule::createFromParts( - jsi::Runtime& rt, - jsi::Array parts, - std::string blobId) { - std::string bytes; - for (size_t index = 0; index < parts.size(rt); ++index) { - auto part = parts.getValueAtIndex(rt, index).asObject(rt); - auto type = part.getProperty(rt, "type").asString(rt).utf8(rt); - auto data = part.getProperty(rt, "data"); - if (type == "string") { - bytes += data.asString(rt).utf8(rt); - } else if (type == "blob") { - auto reference = blobReference(rt, data.asObject(rt)); - auto content = readBlob(reference.blobId, reference.offset, reference.size); - if (!content) { - throw jsi::JSError(rt, "Blob part data is no longer available"); - } - bytes += *content; - } else { - throw jsi::JSError(rt, "Unsupported Blob part type"); - } - } - storeBlob(std::move(blobId), std::move(bytes)); -} - -void BlobModule::release(jsi::Runtime& /*rt*/, std::string blobId) { - eraseBlob(blobId); -} - -void storeBlob(std::string blobId, std::string bytes) { - std::lock_guard lock(blobMutex); - blobs[std::move(blobId)] = std::move(bytes); -} - -std::optional readBlob( - const std::string& blobId, - uint64_t offset, - uint64_t size) { - std::lock_guard lock(blobMutex); - auto it = blobs.find(blobId); - if (it == blobs.end() || offset > it->second.size()) { - return std::nullopt; - } - const auto available = static_cast(it->second.size()) - offset; - const auto length = std::min(size, available); - return it->second.substr(static_cast(offset), static_cast(length)); -} - -void eraseBlob(const std::string& blobId) { - std::lock_guard lock(blobMutex); - blobs.erase(blobId); -} - -void setBlobWebSocketHandler(int32_t socketId, bool enabled) { - std::lock_guard lock(blobMutex); - if (enabled) { - blobWebSocketHandlers.insert(socketId); - } else { - blobWebSocketHandlers.erase(socketId); - } -} - -bool isBlobWebSocketHandler(int32_t socketId) { - std::lock_guard lock(blobMutex); - return blobWebSocketHandlers.contains(socketId); -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/BlobModule.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/BlobModule.h deleted file mode 100644 index 9e2731d7f6..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/BlobModule.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace facebook::react { - -class BlobModule final : public NativeBlobModuleCxxSpec { - public: - explicit BlobModule(std::shared_ptr jsInvoker); - - jsi::Object getConstants(jsi::Runtime& rt); - void addNetworkingHandler(jsi::Runtime& rt); - void addWebSocketHandler(jsi::Runtime& rt, double socketId); - void removeWebSocketHandler(jsi::Runtime& rt, double socketId); - void sendOverSocket(jsi::Runtime& rt, jsi::Object blob, double socketId); - void createFromParts(jsi::Runtime& rt, jsi::Array parts, std::string blobId); - void release(jsi::Runtime& rt, std::string blobId); -}; - -void storeBlob(std::string blobId, std::string bytes); -std::optional readBlob( - const std::string& blobId, - uint64_t offset, - uint64_t size); -void eraseBlob(const std::string& blobId); -void setBlobWebSocketHandler(int32_t socketId, bool enabled); -bool isBlobWebSocketHandler(int32_t socketId); -bool sendBlobOverWebSocket(int32_t socketId, const std::string& bytes); - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/CMakeLists.txt b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/CMakeLists.txt deleted file mode 100644 index 42c589f05c..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -include(${REACT_COMMON_DIR}/cmake-utils/react-native-flags.cmake) - -file(GLOB react_cxx_platform_react_io_SRC CONFIGURE_DEPENDS *.cpp platform/cxx/*.cpp) -add_library(react_cxx_platform_react_io OBJECT ${react_cxx_platform_react_io_SRC}) - -target_include_directories(react_cxx_platform_react_io PUBLIC ${REACT_CXX_PLATFORM_DIR}) - -target_link_libraries(react_cxx_platform_react_io - glog - jsi - react_cxx_platform_react_nativemodule - react_cxx_platform_react_http - react_cxx_platform_react_threading - react_codegen_rncore - react_bridging -) -target_compile_reactnative_options(react_cxx_platform_react_io PRIVATE) -target_compile_options(react_cxx_platform_react_io PRIVATE -Wpedantic) diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/FileReaderModule.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/FileReaderModule.cpp deleted file mode 100644 index 2e83f85072..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/FileReaderModule.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "FileReaderModule.h" - -#include -#include -#include - -namespace facebook::react { -namespace { -http::BlobReference readBlobReference( - jsi::Runtime& rt, - const jsi::Object& blob) { - return http::BlobReference{ - .blobId = blob.getProperty(rt, "blobId").asString(rt).utf8(rt), - .offset = static_cast( - blob.getProperty(rt, "offset").asNumber()), - .size = static_cast(blob.getProperty(rt, "size").asNumber())}; -} -} // namespace - -FileReaderModule::FileReaderModule(std::shared_ptr jsInvoker) - : NativeFileReaderModuleCxxSpec(jsInvoker), - jsInvoker_(std::move(jsInvoker)) {} - -AsyncPromise FileReaderModule::readAsDataURL( - jsi::Runtime& rt, - jsi::Object blob) { - AsyncPromise promise(rt, jsInvoker_); - const auto reference = readBlobReference(rt, blob); - const auto bytes = readBlob(reference.blobId, reference.offset, reference.size); - if (!bytes) { - promise.reject("Blob data is no longer available"); - return promise; - } - const auto type = blob.getProperty(rt, "type").asString(rt).utf8(rt); - promise.resolve("data:" + type + ";base64," + base64Encode(*bytes)); - return promise; -} - -AsyncPromise FileReaderModule::readAsText( - jsi::Runtime& rt, - jsi::Object blob, - std::string encoding) { - AsyncPromise promise(rt, jsInvoker_); - if (encoding != "utf-8" && encoding != "UTF-8" && encoding != "utf8") { - promise.reject("Only UTF-8 Blob text decoding is currently supported"); - return promise; - } - const auto reference = readBlobReference(rt, blob); - const auto bytes = readBlob(reference.blobId, reference.offset, reference.size); - if (!bytes) { - promise.reject("Blob data is no longer available"); - } else { - promise.resolve(*bytes); - } - return promise; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/FileReaderModule.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/FileReaderModule.h deleted file mode 100644 index ae180d22d1..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/FileReaderModule.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace facebook::react { - -class FileReaderModule final - : public NativeFileReaderModuleCxxSpec { - public: - explicit FileReaderModule(std::shared_ptr jsInvoker); - - AsyncPromise readAsDataURL( - jsi::Runtime& rt, - jsi::Object blob); - AsyncPromise readAsText( - jsi::Runtime& rt, - jsi::Object blob, - std::string encoding); - - private: - std::shared_ptr jsInvoker_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/IImageLoader.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/IImageLoader.h deleted file mode 100644 index 8362646682..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/IImageLoader.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include - -namespace facebook::react { - -using IImageLoaderOnLoadCallback = std::function; - -class IImageLoader { - public: - enum class CacheStatus { - None = 0, - Disk = 0x1, - Memory = 0x1 << 1, - }; - - virtual ~IImageLoader() = default; - - virtual void loadImage(const std::string &uri, const IImageLoaderOnLoadCallback &&onLoad) = 0; - - virtual CacheStatus getCacheStatus(const std::string &uri) = 0; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/ImageLoaderModule.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/ImageLoaderModule.cpp deleted file mode 100644 index 7b52271ee8..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/ImageLoaderModule.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "ImageLoaderModule.h" -#include "IImageLoader.h" - -namespace facebook::react { - -jsi::Object ImageLoaderModule::getConstants(jsi::Runtime& rt) { - return jsi::Object(rt); -} - -void ImageLoaderModule::abortRequest(jsi::Runtime& rt, int32_t requestId) {} - -AsyncPromise> ImageLoaderModule::getSize( - jsi::Runtime& rt, - const std::string& uri) { - auto promise = AsyncPromise>(rt, jsInvoker_); - if (auto imageLoader = imageLoader_.lock()) { - imageLoader->loadImage( - uri, - [promise]( - double imageWidth, - double imageHeight, - const char* errorMessage) mutable { - if (errorMessage == nullptr) { - promise.resolve({imageWidth, imageHeight}); - } else { - promise.reject(errorMessage); - } - }); - } else { - promise.reject("Failed to get image size: image loader is not available."); - } - return promise; -} - -AsyncPromise ImageLoaderModule::getSizeWithHeaders( - jsi::Runtime& rt, - const std::string& uri, - jsi::Object /*headers*/) { - auto promise = AsyncPromise(rt, jsInvoker_); - if (auto imageLoader = imageLoader_.lock()) { - imageLoader->loadImage(uri, [promise](double width, double height, const char* error) mutable { - if (error == nullptr) promise.resolve({.width = width, .height = height}); - else promise.reject(error); - }); - } else { - promise.reject("Failed to get image size: image loader is not available."); - } - return promise; -} - -AsyncPromise ImageLoaderModule::prefetchImage( - jsi::Runtime& rt, - const std::string& uri) { - auto promise = AsyncPromise(rt, jsInvoker_); - if (auto imageLoader = imageLoader_.lock()) { - imageLoader->loadImage( - uri, - [promise]( - double /*imageWidth*/, - double /*imageHeight*/, - const char* errorMessage) mutable { - if (errorMessage == nullptr) { - promise.resolve(true); - } else { - promise.reject(errorMessage); - } - }); - } else { - promise.reject("Failed to get image size: image loader is not available."); - } - return promise; -} - -AsyncPromise ImageLoaderModule::prefetchImageWithMetadata( - jsi::Runtime& rt, - const std::string& uri, - const std::string& /*queryRootName*/, - int32_t /*rootTag*/) { - return prefetchImage(rt, uri); -} - -jsi::Object ImageLoaderModule::queryCache( - jsi::Runtime& rt, - const std::vector& uris) { - auto result = jsi::Object(rt); - if (auto imageLoader = imageLoader_.lock()) { - for (const auto& uri : uris) { - auto cacheStatus = static_cast(imageLoader->getCacheStatus(uri)); - if (cacheStatus == static_cast(IImageLoader::CacheStatus::None)) { - continue; - } - const bool isOnDisk = - (cacheStatus & static_cast(IImageLoader::CacheStatus::Disk)) != - 0; - const bool isInMemory = - (cacheStatus & static_cast(IImageLoader::CacheStatus::Memory)) != - 0; - - std::string cacheStatusString; - if (isOnDisk && isInMemory) { - cacheStatusString = "disk/memory"; - } else if (isInMemory) { - cacheStatusString = "memory"; - } else if (isOnDisk) { - cacheStatusString = "disk"; - } - result.setProperty(rt, uri.c_str(), cacheStatusString.c_str()); - } - } - return result; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/ImageLoaderModule.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/ImageLoaderModule.h deleted file mode 100644 index 2980d9df46..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/ImageLoaderModule.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -class IImageLoader; - -using ImageSize = NativeImageLoaderAndroidImageSize; - -template <> -struct Bridging : NativeImageLoaderAndroidImageSizeBridging {}; - -class ImageLoaderModule : public NativeImageLoaderIOSCxxSpec { - public: - explicit ImageLoaderModule( - std::shared_ptr jsInvoker, - std::weak_ptr imageLoader = std::weak_ptr()) - : NativeImageLoaderIOSCxxSpec(jsInvoker), imageLoader_(std::move(imageLoader)) - { - } - - jsi::Object getConstants(jsi::Runtime &rt); - void abortRequest(jsi::Runtime &rt, int32_t requestId); - - AsyncPromise> getSize(jsi::Runtime &rt, const std::string &uri); - - AsyncPromise getSizeWithHeaders(jsi::Runtime &rt, const std::string &uri, jsi::Object headers); - - AsyncPromise prefetchImage(jsi::Runtime &rt, const std::string &uri); - - AsyncPromise prefetchImageWithMetadata( - jsi::Runtime &rt, - const std::string &uri, - const std::string &queryRootName, - int32_t rootTag); - - jsi::Object queryCache(jsi::Runtime &rt, const std::vector &uris); - - private: - std::weak_ptr imageLoader_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/NetworkingModule.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/NetworkingModule.cpp deleted file mode 100644 index f5449557d3..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/NetworkingModule.cpp +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "NetworkingModule.h" -#include -#include -#include -#include - -#include -#include - -namespace facebook::react { - -// The requests abstraction is here to deal with a family of race conditions -// which can happen due to the async nature of this code: -// -// * store token vs callback -// * callback vs cancel -// * stop vs everything -// -// All of the access to the Requests data is protected by a mutex, so it is -// effectively serialized. The code takes care to handle execution in any -// order, so long as reserve for an id precedes any other operation on that id; -// the tests verify that behavior is correct for all use cases. - -Requests::~Requests() { - react_native_assert(isStopped() && "Requests::stop() was not called"); -} - -bool Requests::reserve(uint32_t id) { - if (stopped_) { - return false; - } - std::lock_guard lock(tokensMutex_); - tokens_.emplace(id, nullptr); - return true; -} - -void Requests::store(uint32_t id, std::unique_ptr token) { - // Three possibilities here: - - // 1. HttpClient is shutting down. Cancel the token, don't save it. - // 2. The entry in tokens_ has been erased, which means the callbacks have - // run. We cancel, which should be harmless, just in case. Nothing to save. - // 3. HttpClient and the request are still running. Save the token. - - { - if (stopped_) { - // option 1: fall past the lock and cancel - } else { - std::lock_guard lock(tokensMutex_); - if (auto iter = tokens_.find(id); iter == tokens_.end()) { - // option 2: fall past the lock and cancel - } else { - // option 3: save the token - iter->second = std::move(token); - return; - } - } - } - - if (token) { - token->cancel(); - } -} - -bool Requests::erase(uint32_t id) { - if (stopped_) { - return false; - } - std::lock_guard lock(tokensMutex_); - tokens_.erase(id); - return true; -} - -void Requests::cancel(uint32_t id) { - std::lock_guard lock(tokensMutex_); - if (auto iter = tokens_.find(id); iter != tokens_.end()) { - if (iter->second) { - iter->second->cancel(); - } - tokens_.erase(iter); - } -} - -void Requests::stop() { - stopped_ = true; - decltype(tokens_) tokensCopy; - { - std::lock_guard lock(tokensMutex_); - tokensCopy.swap(tokens_); - } - - for (const auto& token : tokensCopy) { - if (token.second) { - token.second->cancel(); - } - } -} - -bool Requests::isStopped() { - if (stopped_) { - std::lock_guard lock(tokensMutex_); - assert(tokens_.empty()); - } - return stopped_; -} - -NetworkingModule::NetworkingModule( - std::shared_ptr jsInvoker, - const HttpClientFactory& httpClientFactory) - : NativeNetworkingAndroidCxxSpec(jsInvoker) { - httpClient_ = httpClientFactory(); -} - -NetworkingModule::~NetworkingModule() { - requests_.stop(); -} - -void NetworkingModule::sendRequest( - jsi::Runtime& /*rt*/, - const std::string& method, - const std::string& url, - uint32_t requestId, - const http::Headers& headers, - const http::Body& body, - const std::string& responseType, - bool useIncrementalUpdates, - uint32_t timeout, - bool withCredentials) { - if (!requests_.reserve(requestId)) { - // If the NetworkingModule is shutting down, don't invoke the callback. - return; - } - - bool sendIncrementalUpdates = responseType == "text" && useIncrementalUpdates; - bool sendProgressUpdates = responseType != "text" && useIncrementalUpdates; - - http::NetworkCallbacks callbacks{ - .onUploadProgress = - [weakThis = weak_from_this(), requestId]( - int64_t progress, int64_t total) { - if (auto strongThis = weakThis.lock()) { - strongThis->didSendNetworkData(requestId, progress, total); - } - }, - .onResponse = - [weakThis = weak_from_this(), requestId]( - uint32_t responseCode, - const http::Headers& headers, - const std::string& responseUrl) { - if (auto strongThis = weakThis.lock()) { - strongThis->didReceiveNetworkResponse( - requestId, responseCode, headers, responseUrl); - } - }, - .onBody = - [weakThis = weak_from_this(), requestId, responseType]( - std::unique_ptr data) { - if (auto strongThis = weakThis.lock()) { - try { - strongThis->didReceiveNetworkData( - requestId, responseType, std::move(data)); - } catch (const std::exception& e) { - LOG(ERROR) << "Failed to parse network response body: " - << e.what(); - } catch (...) { - LOG(ERROR) << "Failed to parse network response body."; - } - } - }, - .onBodyIncremental = - [weakThis = weak_from_this(), requestId]( - int64_t progress, - int64_t total, - std::unique_ptr body) { - int64_t bytesRead = 0; - if (auto strongThis = weakThis.lock()) { - bytesRead = strongThis->didReceiveNetworkIncrementalData( - requestId, std::move(body), progress, total); - } - return bytesRead; - }, - .onBodyProgress = - [weakThis = weak_from_this(), requestId]( - int64_t loaded, int64_t total) { - if (auto strongThis = weakThis.lock()) { - strongThis->didReceiveNetworkDataProgress( - requestId, loaded, total); - } - }, - .onResponseComplete = - [weakThis = weak_from_this(), requestId]( - const std::string& error, bool timeout) { - if (auto strongThis = weakThis.lock()) { - strongThis->didCompleteNetworkResponse(requestId, error, timeout); - } - }, - .sendIncrementalUpdates = sendIncrementalUpdates, - .sendProgressUpdates = sendProgressUpdates}; - - auto requestBody = body; - requestBody.withCredentials = withCredentials; - auto token = httpClient_->sendRequest( - std::move(callbacks), - method, - url, - headers, - requestBody, - timeout, - std::to_string(requestId)); - if (token) { - requests_.store(requestId, std::move(token)); - } -} - -void NetworkingModule::didSendNetworkData( - uint32_t requestId, - int64_t progress, - int64_t total) { - if (requests_.isStopped()) { - return; - } - emitDeviceEvent( - "didSendNetworkData", - [requestId, progress, total, jsInvoker = jsInvoker_]( - jsi::Runtime& rt, std::vector& args) { - auto result = std::make_tuple( - requestId, - static_cast(progress), - static_cast(total)); - args.emplace_back(bridging::toJs(rt, result, jsInvoker)); - }); -} - -void NetworkingModule::didReceiveNetworkResponse( - uint32_t requestId, - uint32_t statusCode, - const http::Headers& headers, - const std::string& responseUrl) noexcept { - if (requests_.isStopped()) { - return; - } - emitDeviceEvent( - "didReceiveNetworkResponse", - [requestId, statusCode, headers, responseUrl]( - jsi::Runtime& rt, std::vector& args) { - auto headerMap = jsi::Object(rt); - std::vector names; - std::unordered_map joined; - for (const auto& [name, value] : headers) { - auto found = joined.find(name); - if (found == joined.end()) { - names.push_back(name); - joined.emplace(name, value); - } else { - found->second += ", " + value; - } - } - for (const auto& name : names) { - headerMap.setProperty( - rt, name.c_str(), jsi::String::createFromUtf8(rt, joined[name])); - } - args.emplace_back( - rt, - jsi::Array::createWithElements( - rt, - static_cast(requestId), - static_cast(statusCode), - std::move(headerMap), - jsi::String::createFromUtf8(rt, responseUrl))); - }); -} - -int64_t NetworkingModule::didReceiveNetworkIncrementalData( - uint32_t requestId, - std::unique_ptr buf, - int64_t progress, - int64_t total) { - auto data = buf->moveToFbString().toStdString(); - auto bytesRead = data.size(); - emitDeviceEvent( - "didReceiveNetworkIncrementalData", - [requestId, data, progress, total, jsInvoker = jsInvoker_]( - jsi::Runtime& rt, std::vector& args) { - args.emplace_back( - rt, - jsi::Array::createWithElements( - rt, - static_cast(requestId), - data, - static_cast(progress), - static_cast(total))); - }); - return bytesRead; -}; - -namespace { -// Encodes a response body for delivery to JS according to responseType. -// -// The JS XMLHttpRequest layer base64-decodes the delivered string for -// 'base64'-type responses (responseType 'arraybuffer'), so binary bodies must -// be base64-encoded here, matching the Android and iOS NetworkingModule -// implementations. Without this, base64.toByteArray() on the JS side -// mis-decodes the raw payload and corrupts the response (e.g. JSON.parse -// failures on arraybuffer fetches). All other response types are delivered -// unchanged. -std::string encodeResponseBody( - const std::string& responseType, - std::string body) { - if (responseType == "base64") { - return base64Encode(body); - } - return body; -} -} // namespace - -void NetworkingModule::didReceiveNetworkData( - uint32_t requestId, - const std::string& responseType, - std::unique_ptr buf) { - if (requests_.isStopped()) { - return; - } - - auto body = buf->toString(); - if (responseType == "blob") { - static std::atomic blobSequence{0}; - const auto blobId = "gpui-response-" + std::to_string(requestId) + "-" + - std::to_string(blobSequence.fetch_add(1)); - const auto size = body.size(); - storeBlob(blobId, std::move(body)); - emitDeviceEvent( - "didReceiveNetworkData", - [requestId, blobId, size, jsInvoker = jsInvoker_] ( - jsi::Runtime& rt, std::vector& args) { - jsi::Object data(rt); - data.setProperty( - rt, "blobId", jsi::String::createFromUtf8(rt, blobId)); - data.setProperty(rt, "offset", 0); - data.setProperty(rt, "size", static_cast(size)); - data.setProperty(rt, "type", ""); - args.emplace_back( - rt, - jsi::Array::createWithElements( - rt, static_cast(requestId), std::move(data))); - }); - return; - } - auto responseData = encodeResponseBody(responseType, std::move(body)); - emitDeviceEvent( - "didReceiveNetworkData", - [requestId, - responseData = std::move(responseData), - jsInvoker = jsInvoker_]( - jsi::Runtime& rt, std::vector& args) { - args.emplace_back( - rt, - jsi::Array::createWithElements( - rt, static_cast(requestId), responseData)); - }); -} - -void NetworkingModule::didReceiveNetworkDataProgress( - uint32_t requestId, - int64_t bytesRead, - int64_t total) { - emitDeviceEvent( - "didReceiveNetworkDataProgress", - [requestId, bytesRead, total, jsInvoker = jsInvoker_]( - jsi::Runtime& rt, std::vector& args) { - args.emplace_back( - rt, - jsi::Array::createWithElements( - rt, - static_cast(requestId), - static_cast(bytesRead), - static_cast(total))); - }); -} - -void NetworkingModule::didCompleteNetworkResponse( - uint32_t requestId, - const std::string& error, - bool timeoutError) { - if (requests_.isStopped() || !requests_.erase(requestId)) { - // If the HttpClient is shutting down, don't invoke the callback. - return; - } - emitDeviceEvent( - "didCompleteNetworkResponse", - [requestId, error, timeoutError, jsInvoker = jsInvoker_]( - jsi::Runtime& rt, std::vector& args) { - if (error.empty()) { - auto result = std::make_tuple(static_cast(requestId)); - args.emplace_back(bridging::toJs(rt, result, jsInvoker)); - } else { - auto result = std::make_tuple( - static_cast(requestId), error, timeoutError); - args.emplace_back(bridging::toJs(rt, result, jsInvoker)); - } - }); -} - -void NetworkingModule::abortRequest(jsi::Runtime& /*rt*/, uint32_t requestId) { - requests_.cancel(requestId); -} - -void NetworkingModule::clearCookies( - jsi::Runtime& /*rt*/, - const AsyncCallback& callback) { - callback(rngpui::gpui_http_client_clear_cookies()); -} - -void NetworkingModule::addListener( - jsi::Runtime& /*rt*/, - const std::string& /*eventName*/) {} - -void NetworkingModule::removeListeners( - jsi::Runtime& /*rt*/, - uint32_t /*count*/) {} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/NetworkingModule.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/NetworkingModule.h deleted file mode 100644 index 54c4bc28fc..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/NetworkingModule.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -template <> -struct Bridging { - static http::FormDataField - fromJs(jsi::Runtime &rt, const jsi::Object &value, const std::shared_ptr &jsInvoker) - { - auto fieldName = bridging::fromJs(rt, value.getProperty(rt, "fieldName"), jsInvoker); - auto headers = bridging::fromJs(rt, value.getProperty(rt, "headers"), jsInvoker); - auto string = bridging::fromJs>(rt, value.getProperty(rt, "string"), jsInvoker); - auto uri = bridging::fromJs>(rt, value.getProperty(rt, "uri"), jsInvoker); - return http::FormDataField{.fieldName = fieldName, .headers = headers, .string = string, .uri = uri}; - } -}; - -template <> -struct Bridging { - static http::Body fromJs(jsi::Runtime &rt, const jsi::Object &value, const std::shared_ptr &jsInvoker) - { - return http::Body{ - .string = bridging::fromJs>(rt, value.getProperty(rt, "string"), jsInvoker), - .blob = value.getProperty(rt, "blob").isObject() - ? std::optional(http::BlobReference{ - .blobId = value.getProperty(rt, "blob").asObject(rt).getProperty(rt, "blobId").asString(rt).utf8(rt), - .offset = static_cast(value.getProperty(rt, "blob").asObject(rt).getProperty(rt, "offset").asNumber()), - .size = static_cast(value.getProperty(rt, "blob").asObject(rt).getProperty(rt, "size").asNumber())}) - : std::nullopt, - .formData = bridging::fromJs>(rt, value.getProperty(rt, "formData"), jsInvoker), - .base64 = bridging::fromJs>(rt, value.getProperty(rt, "base64"), jsInvoker), - .withCredentials = true, - - }; - } -}; - -class Requests { - public: - Requests() noexcept = default; - ~Requests(); - Requests(Requests &other) = delete; - Requests &operator=(Requests &other) = delete; - Requests(Requests &&other) = delete; - Requests &operator=(Requests &&other) = delete; - - bool reserve(uint32_t id); - void store(uint32_t id, std::unique_ptr token); - bool erase(uint32_t id); - void cancel(uint32_t id); - void stop(); - bool isStopped(); - - private: - std::mutex tokensMutex_; - std::unordered_map> tokens_; - std::atomic stopped_{false}; -}; - -// Implementation of "Networking" TurboModule -class NetworkingModule : public NativeNetworkingAndroidCxxSpec, - public std::enable_shared_from_this { - public: - NetworkingModule(std::shared_ptr jsInvoker, const HttpClientFactory &httpClientFactory); - - ~NetworkingModule() override; - - void sendRequest( - jsi::Runtime &rt, - const std::string &method, - const std::string &url, - uint32_t requestId, - const http::Headers &headers, - const http::Body &body, - const std::string &responseType, - bool useIncrementalUpdates, - uint32_t timeout, - bool withCredentials); - - void abortRequest(jsi::Runtime &rt, uint32_t requestId); - - void clearCookies(jsi::Runtime &rt, const AsyncCallback &callback); - - // RCTEventEmitter - void addListener(jsi::Runtime &rt, const std::string &eventName); - void removeListeners(jsi::Runtime &rt, uint32_t count); - - private: - void didSendNetworkData(uint32_t requestId, int64_t progress, int64_t total); - - void didReceiveNetworkResponse( - uint32_t requestId, - uint32_t statusCode, - const http::Headers &headers, - const std::string &responseUrl) noexcept; - - void didReceiveNetworkData(uint32_t requestId, const std::string &responseType, std::unique_ptr buf); - - int64_t didReceiveNetworkIncrementalData( - uint32_t requestId, - std::unique_ptr buf, - int64_t progress, - int64_t total); - - void didReceiveNetworkDataProgress(uint32_t requestId, int64_t bytesRead, int64_t total); - - void didCompleteNetworkResponse(uint32_t requestId, const std::string &error, bool timeoutError); - - std::unique_ptr httpClient_; - Requests requests_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/ResourceLoader.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/ResourceLoader.cpp deleted file mode 100644 index dd7e681719..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/ResourceLoader.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "ResourceLoader.h" - -#include -#include - -namespace facebook::react { -/* static */ bool ResourceLoader::isAbsolutePath(const std::string& path) { - return std::filesystem::path(path).is_absolute(); -} - -/* static */ bool ResourceLoader::isDirectory(const std::string& path) { - if (isAbsolutePath(path) && std::filesystem::is_directory(path)) { - return true; - } - - return isResourceDirectory(path); -} - -/* static */ bool ResourceLoader::isFile(const std::string& path) { - if (isAbsolutePath(path) && std::filesystem::exists(path) && - !std::filesystem::is_directory(path)) { - return true; - } - - return isResourceFile(path); -} - -/* static */ std::unique_ptr ResourceLoader::getFileContents( - const std::string& path) { - if (isResourceFile(path)) { - return getResourceFileContents(path); - } else { - return JSBigFileString::fromPath(path); - } -} - -/* static */ std::filesystem::path ResourceLoader::getCacheDirectory( - const std::string& path) { - auto root = getCacheRootPath() / CACHE_DIR; - if (!std::filesystem::exists(root)) { - try { - std::filesystem::create_directory(root); - } catch (...) { - LOG(ERROR) << "Failed to create root cache directory: " << root; - throw; - } - } - - if (path.empty()) { - return root; - } - - auto dir = root / path; - try { - std::filesystem::create_directories(dir); - return dir; - } catch (...) { - LOG(ERROR) << "Failed to create cache directory: " << dir; - throw; - } -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/ResourceLoader.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/ResourceLoader.h deleted file mode 100644 index 8b4588a1e8..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/ResourceLoader.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include - -namespace facebook::react { - -class JSBigString; - -class ResourceLoader { - public: - static bool isDirectory(const std::string &path); - static bool isFile(const std::string &path); - static bool isAbsolutePath(const std::string &path); - static std::unique_ptr getFileContents(const std::string &path); - static std::filesystem::path getCacheDirectory(const std::string &path = std::string()); - - protected: - static bool isResourceDirectory(const std::string &path); - static bool isResourceFile(const std::string &path); - static std::unique_ptr getResourceFileContents(const std::string &path); - - private: - static constexpr const auto CACHE_DIR = ".react-native-cxx-cache"; - static std::filesystem::path getCacheRootPath(); -}; -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/WebSocketModule.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/WebSocketModule.cpp deleted file mode 100644 index f63ab695fb..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/WebSocketModule.cpp +++ /dev/null @@ -1,275 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "WebSocketModule.h" - -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -namespace { -std::mutex socketSendersMutex; -std::unordered_map> socketSenders; - -void removeSocketSender(int32_t socketId) { - std::lock_guard lock(socketSendersMutex); - socketSenders.erase(socketId); -} -} // namespace - -bool sendBlobOverWebSocket(int32_t socketId, const std::string& bytes) { - std::function sender; - { - std::lock_guard lock(socketSendersMutex); - auto it = socketSenders.find(socketId); - if (it == socketSenders.end()) return false; - sender = it->second; - } - sender(bytes); - return true; -} - -WebSocketModule::WebSocketModule( - std::shared_ptr jsInvoker, - WebSocketClientFactory webSocketClientFactory) - : NativeWebSocketModuleCxxSpec(jsInvoker), - webSocketClientFactory_(std::move(webSocketClientFactory)) {} - -WebSocketModule::~WebSocketModule() { - for (const auto& [socketId, _] : connections_) { - removeSocketSender(socketId); - } - connections_.clear(); -} - -void WebSocketModule::releaseConnection(int32_t socketID) { - // Only the JS thread owns connections_. Destroying a client joins its IO - // thread, so terminal callbacks must dispatch here rather than delete it - // from that IO thread. RN's JS WebSocket is already CLOSED when it receives - // a terminal event and does not call the native close method afterward. - auto it = connections_.find(socketID); - if (it == connections_.end()) { - return; - } - removeSocketSender(socketID); - setBlobWebSocketHandler(socketID, false); - connections_.erase(it); -} - -void WebSocketModule::connect( - jsi::Runtime& /*rt*/, - const std::string& url, - const std::optional>& /*protocols*/, - jsi::Object /*options*/, - int32_t socketID) { - auto webSocket = webSocketClientFactory_(); - connections_.emplace(socketID, std::move(webSocket)); - { - std::lock_guard lock(socketSendersMutex); - socketSenders[socketID] = [weakThis = weak_from_this(), socketID]( - const std::string& bytes) { - if (auto strongThis = weakThis.lock()) { - auto it = strongThis->connections_.find(socketID); - if (it != strongThis->connections_.end()) { - it->second->sendBinary(bytes); - } - } - }; - } - connections_[socketID]->setOnMessageFrameCallback([weakThis = weak_from_this(), - socketID]( - const std::string& message, - bool isBinary) { - auto strongThis = weakThis.lock(); - if (!strongThis) { - return; - } - const bool asBlob = isBinary && isBlobWebSocketHandler(socketID); - static std::atomic blobSequence{0}; - const auto blobId = asBlob - ? "gpui-websocket-" + std::to_string(socketID) + "-" + - std::to_string(blobSequence.fetch_add(1)) - : std::string{}; - if (asBlob) { - storeBlob(blobId, message); - } - strongThis->emitDeviceEvent( - "websocketMessage", - [socketID, message = std::string(message), isBinary, asBlob, blobId]( - jsi::Runtime& rt, std::vector& args) { - auto arg = jsi::Object(rt); - arg.setProperty(rt, "id", jsi::Value(socketID)); - arg.setProperty( - rt, - "type", - facebook::jsi::String::createFromAscii( - rt, asBlob ? "blob" : (isBinary ? "binary" : "string"))); - if (asBlob) { - jsi::Object data(rt); - data.setProperty( - rt, "blobId", jsi::String::createFromUtf8(rt, blobId)); - data.setProperty(rt, "offset", 0); - data.setProperty(rt, "size", static_cast(message.size())); - data.setProperty(rt, "type", "application/octet-stream"); - arg.setProperty(rt, "data", std::move(data)); - } else { - arg.setProperty( - rt, - "data", - facebook::jsi::String::createFromUtf8( - rt, isBinary ? base64Encode(message) : message)); - } - args.emplace_back(rt, arg); - }); - }); - connections_[socketID]->setOnClosedFrameCallback( - [weakThis = weak_from_this(), socketID](uint16_t code, const std::string& reason) { - auto strongThis = weakThis.lock(); - if (!strongThis) { - return; - } - strongThis->jsInvoker_->invokeAsync([weakThis, socketID, code, reason](jsi::Runtime&) { - auto owner = weakThis.lock(); - if (!owner || owner->connections_.find(socketID) == owner->connections_.end()) { - return; - } - owner->releaseConnection(socketID); - owner->emitDeviceEvent( - "websocketClosed", - [socketID, code, reason](jsi::Runtime& rt, std::vector& args) { - auto arg = jsi::Object(rt); - arg.setProperty(rt, "id", jsi::Value(socketID)); - arg.setProperty(rt, "code", jsi::Value(code)); - arg.setProperty( - rt, - "reason", - facebook::jsi::String::createFromUtf8(rt, reason)); - args.emplace_back(rt, arg); - }); - }); - }); - - connections_[socketID]->connect( - url, - [weakThis = weak_from_this(), socketID]( - bool success, const std::optional& /*message*/) { - auto strongThis = weakThis.lock(); - if (!strongThis) { - return; - } - if (success) { - strongThis->emitDeviceEvent( - "websocketOpen", - [socketID](jsi::Runtime& rt, std::vector& args) { - auto arg = jsi::Object(rt); - arg.setProperty(rt, "id", jsi::Value(socketID)); - args.emplace_back(rt, arg); - }); - } else { - strongThis->jsInvoker_->invokeAsync([weakThis, socketID](jsi::Runtime&) { - auto owner = weakThis.lock(); - if (!owner || owner->connections_.find(socketID) == owner->connections_.end()) { - return; - } - owner->releaseConnection(socketID); - owner->emitDeviceEvent( - "websocketFailed", - [socketID](jsi::Runtime& rt, std::vector& args) { - auto arg = jsi::Object(rt); - arg.setProperty(rt, "id", jsi::Value(socketID)); - arg.setProperty( - rt, - "message", - facebook::jsi::String::createFromAscii( - rt, "Could not connect to websocket.")); - args.emplace_back(rt, arg); - }); - }); - } - }); -} - -void WebSocketModule::send( - jsi::Runtime& /*rt*/, - const std::string& message, - int32_t socketID) { - auto it = connections_.find(static_cast(socketID)); - if (it == connections_.end()) { - LOG(ERROR) << "Failed to send data to a socket (" << socketID - << "), the socket is not open."; - return; - } - it->second->send(message); -} - -void WebSocketModule::sendBinary( - jsi::Runtime& rt, - const std::string& base64String, - int32_t forSocketID) { - auto it = connections_.find(static_cast(forSocketID)); - if (it == connections_.end()) { - LOG(ERROR) << "Failed to send binary data to a socket (" << forSocketID - << "), the socket is not open."; - return; - } - std::string decoded; - decoded.reserve(base64String.size() * 3 / 4); - uint32_t value = 0; - int bits = -8; - for (char ch : base64String) { - if (ch == '=') break; - const std::string_view alphabet = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - const auto index = alphabet.find(ch); - if (index == std::string_view::npos) continue; - value = (value << 6) | static_cast(index); - bits += 6; - if (bits >= 0) { - decoded.push_back(static_cast((value >> bits) & 0xff)); - bits -= 8; - } - } - it->second->sendBinary(decoded); -} - -void WebSocketModule::ping(jsi::Runtime& /*rt*/, int32_t socketID) { - auto it = connections_.find(static_cast(socketID)); - if (it == connections_.end()) { - LOG(ERROR) << "Failed to ping a socket (" << socketID - << "), the socket is not open."; - return; - } - it->second->ping(); -} - -void WebSocketModule::close( - jsi::Runtime& /*rt*/, - int32_t code, - const std::string& reason, - int32_t socketID) { - auto it = connections_.find(static_cast(socketID)); - if (it == connections_.end()) { - LOG(ERROR) << "Failed to close a socket (" << socketID - << "), the socket is not open."; - return; - } - it->second->close(static_cast(code), reason); -} - -void WebSocketModule::addListener( - jsi::Runtime& /*rt*/, - const std::string& /*eventName*/) {} - -void WebSocketModule::removeListeners(jsi::Runtime& /*rt*/, int32_t /*count*/) { -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/WebSocketModule.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/WebSocketModule.h deleted file mode 100644 index 3c81c90fcd..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/WebSocketModule.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -class IWebSocketClient; - -class WebSocketModule : public NativeWebSocketModuleCxxSpec, - public std::enable_shared_from_this { - public: - WebSocketModule(std::shared_ptr jsInvoker, WebSocketClientFactory webSocketClientFactory); - ~WebSocketModule() override; - WebSocketModule(const WebSocketModule &other) = delete; - WebSocketModule &operator=(WebSocketModule &other) = delete; - WebSocketModule(WebSocketModule &&other) = delete; - WebSocketModule &operator=(WebSocketModule &&other) = delete; - - void connect( - jsi::Runtime &rt, - const std::string &url, - const std::optional> &protocols, - jsi::Object options, - int32_t socketID); - - void send(jsi::Runtime &rt, const std::string &message, int32_t socketID); - - void sendBinary(jsi::Runtime &rt, const std::string &base64String, int32_t socketID); - - void ping(jsi::Runtime &rt, int32_t socketID); - - void close(jsi::Runtime &rt, int32_t code, const std::string &reason, int32_t socketID); - - void addListener(jsi::Runtime &rt, const std::string &eventName); - - void removeListeners(jsi::Runtime &rt, int32_t count); - - private: - void releaseConnection(int32_t socketID); - - WebSocketClientFactory webSocketClientFactory_; - std::unordered_map> connections_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/platform/android/AssetManagerHelpers.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/platform/android/AssetManagerHelpers.cpp deleted file mode 100644 index 8fd3a182d4..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/platform/android/AssetManagerHelpers.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "AssetManagerHelpers.h" - -#include -#include - -namespace facebook::react { - -jobject getAssetManagerObject(JNIEnv* env) { - auto contextObject = getApplication(env); - auto contextClass = env->GetObjectClass(contextObject); - auto getAssetsMethod = env->GetMethodID( - contextClass, "getAssets", "()Landroid/content/res/AssetManager;"); - return env->CallObjectMethod(contextObject, getAssetsMethod); -} - -AAssetManager* getJavaAssetManager() { - auto env = facebook::jni::Environment::ensureCurrentThreadIsAttached(); - auto AssetManagerObject = getAssetManagerObject(env); - return AAssetManager_fromJava(env, AssetManagerObject); -} - -bool isDirectoryNotEmpty(const std::string& path) { - auto env = facebook::jni::Environment::ensureCurrentThreadIsAttached(); - auto AssetManagerObject = getAssetManagerObject(env); - auto listMethodID = env->GetMethodID( - env->GetObjectClass(AssetManagerObject), - "list", - "(Ljava/lang/String;)[Ljava/lang/String;"); - - auto pathString = env->NewStringUTF(path.c_str()); - auto filesObject = static_cast( - env->CallObjectMethod(AssetManagerObject, listMethodID, pathString)); - env->DeleteLocalRef(pathString); - - auto length = env->GetArrayLength(filesObject); - for (int i = 0; i < length; i++) { - auto jstr = - static_cast(env->GetObjectArrayElement(filesObject, i)); - - const char* filename = env->GetStringUTFChars(jstr, nullptr); - - if (filename != nullptr) { - env->ReleaseStringUTFChars(jstr, filename); - env->DeleteLocalRef(jstr); - return true; - } - - env->DeleteLocalRef(jstr); - } - return false; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/platform/android/AssetManagerHelpers.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/platform/android/AssetManagerHelpers.h deleted file mode 100644 index 8df2d98ca9..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/platform/android/AssetManagerHelpers.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include - -namespace facebook::react { - -AAssetManager *getJavaAssetManager(); - -bool isDirectoryNotEmpty(const std::string &path); - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/platform/android/ResourceLoader.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/platform/android/ResourceLoader.cpp deleted file mode 100644 index 616a23a281..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/platform/android/ResourceLoader.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "ResourceLoader.h" -#include "AssetManagerHelpers.h" - -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -namespace { - -AAssetManager* assetManager_ = nullptr; - -AAssetManager* getAssetManager() { - if (assetManager_ == nullptr) { - assetManager_ = getJavaAssetManager(); - } - - return assetManager_; -} -} // namespace - -bool ResourceLoader::isResourceDirectory(const std::string& path) { - auto assetDir = AAssetManager_openDir(getAssetManager(), path.c_str()); - if (assetDir == nullptr) { - return false; - } - - bool exists = AAssetDir_getNextFileName(assetDir) != nullptr; - AAssetDir_close(assetDir); - if (exists) { - return true; - } - return isDirectoryNotEmpty(path); -} - -bool ResourceLoader::isResourceFile(const std::string& path) { - auto asset = AAssetManager_open( - getAssetManager(), path.c_str(), AASSET_MODE_STREAMING); - if (asset == nullptr) { - return false; - } - - AAsset_close(asset); - return true; -} - -std::unique_ptr ResourceLoader::getResourceFileContents( - const std::string& path) { - return loadScriptFromAssets(getAssetManager(), path); -} - -std::filesystem::path ResourceLoader::getCacheRootPath() { - return getContext()->getCacheDir()->getAbsolutePath(); -} -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/platform/cxx/ResourceLoader.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/platform/cxx/ResourceLoader.cpp deleted file mode 100644 index 2ff6f35455..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/platform/cxx/ResourceLoader.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include -#include - -#include - -namespace facebook::react { - -bool ResourceLoader::isResourceDirectory(const std::string& path) { - return std::filesystem::is_directory(path); -} - -bool ResourceLoader::isResourceFile(const std::string& path) { - return std::filesystem::exists(path) && !std::filesystem::is_directory(path); -} - -/* static */ std::unique_ptr -ResourceLoader::getResourceFileContents(const std::string& path) { - return JSBigFileString::fromPath(path); -} - -/* static */ std::filesystem::path ResourceLoader::getCacheRootPath() { - return std::filesystem::temp_directory_path(); -} -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/tests/NetworkingModuleTests.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/tests/NetworkingModuleTests.cpp deleted file mode 100644 index a75cc58013..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/tests/NetworkingModuleTests.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#ifdef _WIN32 -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -#include - -#include "TestJsRuntime.h" - -namespace facebook::react { - -class NetworkingModuleTests : public testing::Test { - protected: - void SetUp() override { - // The engine comes from the test binary's registration, not from this - // file, so the test only needs a JSI runtime. - runtime_ = tests::createTestRuntimeFromActiveEngine(); - jsInvoker_ = std::make_shared(runtime_->getRuntime()); - } - - static void verifyFormData( - const http::FormDataField& formData, - const std::string& fieldName, - const std::string& string, - std::vector headerValues) { - EXPECT_EQ(formData.fieldName, fieldName); - EXPECT_EQ(formData.string, string); - for (int i = 0; i * 2 < headerValues.size(); ++i) { - EXPECT_EQ(formData.headers[i].first, headerValues[i * 2]); - EXPECT_EQ(formData.headers[i].second, headerValues[i * 2 + 1]); - } - } - - std::unique_ptr runtime_; - std::shared_ptr jsInvoker_; -}; - -// Test parsing a body with form data -TEST_F(NetworkingModuleTests, formDataTest) { - auto dynamic = folly::parseJson( - R"({ - "formData":[ - { - "fieldName":"field1", - "headers":[["header1","form-data; name=\"header1\""]], - "string":"string1" - }, - { - "fieldName":"field2", - "headers":[ - ["header1","form-data; name=\"header1\""], - ["header2","form-data; name=\"header2\""] - ], - "string":"string2" - } - ]})"); - auto jsiValue = jsi::valueFromDynamic(*rt_, dynamic); - auto body = bridging::fromJs(*rt_, jsiValue, jsInvoker_); - - EXPECT_TRUE(body.formData.has_value()); - - EXPECT_FALSE(body.base64.has_value()); - EXPECT_FALSE(body.blob.has_value()); - EXPECT_FALSE(body.string.has_value()); - - auto formData = body.formData.value(); - EXPECT_EQ(formData.size(), 2); - verifyFormData( - formData[0], - "field1", - "string1", - {"header1", "form-data; name=\"header1\""}); - verifyFormData( - formData[1], - "field2", - "string2", - {"header1", - "form-data; name=\"header1\"", - "header2", - "form-data; name=\"header2\""}); -} - -// Test parsing a body with string data -TEST_F(NetworkingModuleTests, stringDataTest) { - auto dynamic = folly::parseJson( - R"({ - "string": "testString" - })"); - auto jsiValue = jsi::valueFromDynamic(*rt_, dynamic); - auto body = bridging::fromJs(*rt_, jsiValue, jsInvoker_); - - EXPECT_TRUE(body.string.has_value()); - - EXPECT_FALSE(body.base64.has_value()); - EXPECT_FALSE(body.blob.has_value()); - EXPECT_FALSE(body.formData.has_value()); - - auto stringData = body.string.value(); - EXPECT_EQ(stringData, "testString"); -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/tests/TestJsRuntime.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/tests/TestJsRuntime.h deleted file mode 100644 index 032b2c8fe6..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/io/tests/TestJsRuntime.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include "GpuiJsEngine.h" - -#include -#include - -#include -#include - -namespace facebook::react::tests { - -/// Creates the JSI runtime a test should use from `factory` — the same seam -/// ReactHost uses for every (re)load. Tests take a factory instead of -/// constructing a VM of their own, so no test depends on an engine. -inline std::unique_ptr createTestRuntime( - JSRuntimeFactory& factory, - std::shared_ptr messageQueueThread = nullptr) { - return factory.createJSRuntime(std::move(messageQueueThread)); -} - -/// The same runtime, built from the engine the test binary registered. A test -/// binary registers an engine package exactly like an app does (see -/// GpuiJsEngine.h); without one this reports the registry's error. -inline std::unique_ptr createTestRuntimeFromActiveEngine( - std::shared_ptr messageQueueThread = nullptr) { - return createTestRuntime( - *rngpui::activeJsEngine().makeRuntimeFactory(), - std::move(messageQueueThread)); -} - -} // namespace facebook::react::tests diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/jni/JniHelper.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/jni/JniHelper.cpp deleted file mode 100644 index 3799ed893a..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/jni/JniHelper.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "JniHelper.h" - -#include -#include - -namespace facebook::react { - -jobject getApplication(JNIEnv* env) { - auto activityThreadClass = env->FindClass("android/app/ActivityThread"); - auto currentApplicationMethodID = env->GetStaticMethodID( - activityThreadClass, "currentApplication", "()Landroid/app/Application;"); - return env->CallStaticObjectMethod( - activityThreadClass, currentApplicationMethodID); -} - -jni::alias_ref getContext() { - auto env = facebook::jni::Environment::ensureCurrentThreadIsAttached(); - auto application = getApplication(env); - return facebook::jni::wrap_alias( - static_cast(application)); -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/jni/JniHelper.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/jni/JniHelper.h deleted file mode 100644 index b449ca2540..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/jni/JniHelper.h +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include - -namespace facebook::react { - -jobject getApplication(JNIEnv *env); - -jni::alias_ref getContext(); - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/CMakeLists.txt b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/CMakeLists.txt deleted file mode 100644 index 3aa3e63bf5..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/CMakeLists.txt +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -include(${REACT_COMMON_DIR}/cmake-utils/react-native-flags.cmake) - -file(GLOB react_cxx_platform_react_logging_SRC CONFIGURE_DEPENDS *.cpp) -add_library(react_cxx_platform_react_logging OBJECT ${react_cxx_platform_react_logging_SRC}) - -target_include_directories(react_cxx_platform_react_logging PUBLIC ${REACT_CXX_PLATFORM_DIR}) - -target_link_libraries(react_cxx_platform_react_logging - glog - react_codegen_rncore - jserrorhandler - react_bridging - logger -) -target_compile_reactnative_options(react_cxx_platform_react_logging PRIVATE) -target_compile_options(react_cxx_platform_react_logging PRIVATE -Wpedantic) diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/DefaultLogger.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/DefaultLogger.cpp deleted file mode 100644 index 4e2d9e3dc4..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/DefaultLogger.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "DefaultLogger.h" - -#include -#include -#include - -namespace facebook::react { - -Logger getDefaultLogger() { - return [](const std::string& message, unsigned int logLevel) { - static std::string tag = "[JavaScript]: "; - switch (logLevel) { - case ReactNativeLogLevelFatal: - case ReactNativeLogLevelError: - LOG(ERROR) << tag << message; - break; - case ReactNativeLogLevelWarning: - LOG(WARNING) << tag << message; - break; - case ReactNativeLogLevelInfo: - default: - LOG(INFO) << tag << message; - break; - } - }; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/DefaultLogger.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/DefaultLogger.h deleted file mode 100644 index d887dd168b..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/DefaultLogger.h +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include - -namespace facebook::react { - -using Logger = std::function; - -Logger getDefaultLogger(); - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/DefaultOnJsErrorHandler.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/DefaultOnJsErrorHandler.h deleted file mode 100644 index d512d2b006..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/DefaultOnJsErrorHandler.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include - -namespace facebook::react { - -static inline JsErrorHandler::OnJsError getDefaultOnJsErrorFunc() -{ - return [](jsi::Runtime & /*runtime*/, const JsErrorHandler::ProcessedError &error) { - LOG(ERROR) << "[onJsError called]: " << error << std::endl; - }; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/LogOnce.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/LogOnce.cpp deleted file mode 100644 index c35fa9b342..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/LogOnce.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "LogOnce.h" - -#include - -#include - -namespace facebook::react { - -LogOnceWrapper::~LogOnceWrapper() { - std::string message = str(); - - static std::unordered_set loggedMessages; - if (loggedMessages.find(message) != loggedMessages.end()) { - return; - } - - switch (severity_) { - case Severity::Info: - LOG(INFO) << message; - break; - case Severity::Warning: - LOG(WARNING) << message; - break; - case Severity::Error: - LOG(ERROR) << message; - break; - case Severity::Fatal: - default: - LOG(FATAL) << message; - break; - } - - loggedMessages.insert(message); -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/LogOnce.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/LogOnce.h deleted file mode 100644 index ad66d1f21b..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/LogOnce.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include - -#include - -#define LOG_INFO_ONCE LogOnceWrapper(LogOnceWrapper::Severity::Info) -#define LOG_WARNING_ONCE LogOnceWrapper(LogOnceWrapper::Severity::Warning) -#define LOG_ERROR_ONCE LogOnceWrapper(LogOnceWrapper::Severity::Error) -#define LOG_FATAL_ONCE LogOnceWrapper(LogOnceWrapper::Severity::Fatal) - -namespace facebook::react { - -class LogOnceWrapper : public std::stringstream { - public: - enum class Severity { Info, Warning, Error, Fatal }; - - LogOnceWrapper(Severity severity = Severity::Info) : severity_(severity) {} - - ~LogOnceWrapper(); - - private: - Severity severity_{Severity::Info}; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/NativeExceptionsManager.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/NativeExceptionsManager.cpp deleted file mode 100644 index ef920df59f..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/NativeExceptionsManager.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "NativeExceptionsManager.h" - -#include - -namespace facebook::react { - -void NativeExceptionsManager::reportFatalException( - jsi::Runtime& rt, - std::string message, - std::vector stack, - int32_t exceptionId) { - reportException( - rt, - ExceptionData{ - .message = std::move(message), - .stack = std::move(stack), - .id = exceptionId, - .isFatal = true}); -} - -void NativeExceptionsManager::reportSoftException( - jsi::Runtime& rt, - std::string message, - std::vector stack, - int32_t exceptionId) { - reportException( - rt, - ExceptionData{ - .message = std::move(message), - .stack = std::move(stack), - .id = exceptionId, - .isFatal = false}); -} - -void NativeExceptionsManager::reportException( - jsi::Runtime& runtime, - const ExceptionData& data) { - if (onJsError_) { - std::vector frames; - frames.reserve(data.stack.size()); - for (const auto& frame : data.stack) { - frames.push_back( - JsErrorHandler::ProcessedError::StackFrame{ - .file = frame.file, - .methodName = frame.methodName, - .lineNumber = frame.lineNumber, - .column = frame.column}); - } - JsErrorHandler::ProcessedError processedError{ - .message = data.message, - .originalMessage = std::nullopt, - .name = std::nullopt, - .componentStack = std::nullopt, - .stack = frames, - .id = data.id, - .isFatal = data.isFatal, - .extraData = jsi::Object(runtime), - }; - onJsError_(runtime, processedError); - } -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/NativeExceptionsManager.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/NativeExceptionsManager.h deleted file mode 100644 index 4dba94aa3f..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/logging/NativeExceptionsManager.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -// https://github.com/facebook/react-native/blob/v0.71.1/Libraries/Core/NativeExceptionsManager.js#L17-L35 -using StackFrame = NativeExceptionsManagerStackFrame< - std::optional, - std::optional, - std::optional, - std::string, - std::optional>; - -template <> -struct Bridging : NativeExceptionsManagerStackFrameBridging {}; - -using ExceptionData = NativeExceptionsManagerExceptionData< - std::string, - std::optional, - std::optional, - std::optional, - std::vector, - int32_t, - bool, - std::optional>>; - -template <> -struct Bridging : NativeExceptionsManagerExceptionDataBridging {}; - -class NativeExceptionsManager : public NativeExceptionsManagerCxxSpec { - public: - NativeExceptionsManager(JsErrorHandler::OnJsError onJsError, std::shared_ptr jsInvoker) - : NativeExceptionsManagerCxxSpec(jsInvoker), onJsError_(std::move(onJsError)) - { - } - - void reportFatalException(jsi::Runtime &rt, std::string message, std::vector stack, int32_t exceptionId); - - void reportSoftException(jsi::Runtime &rt, std::string message, std::vector stack, int32_t exceptionId); - - void reportException(jsi::Runtime &runtime, const ExceptionData &data); - - void updateExceptionMessage(jsi::Runtime &rt, jsi::String message, jsi::Array stack, double exceptionId) - { - // This method is not in modern React Native: - // https://github.com/search?q=repo%3Afacebook%2Freact-native+updateExceptionMessage&type=code - } - - void dismissRedbox(jsi::Runtime &rt) - { - // Redbox is not supported at this time, LogBox is: - // https://reactnative.dev/blog/2020/07/06/version-0.63 - } - - private: - JsErrorHandler::OnJsError onJsError_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/nativemodule/CMakeLists.txt b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/nativemodule/CMakeLists.txt deleted file mode 100644 index e71e8d17c2..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/nativemodule/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -include(${REACT_COMMON_DIR}/cmake-utils/react-native-flags.cmake) - -add_library(react_cxx_platform_react_nativemodule INTERFACE) - -target_include_directories(react_cxx_platform_react_nativemodule INTERFACE ${REACT_CXX_PLATFORM_DIR}) - -target_link_libraries(react_cxx_platform_react_nativemodule INTERFACE - folly_runtime - react_nativemodule_core -) -target_compile_reactnative_options(react_cxx_platform_react_nativemodule INTERFACE) -target_compile_options(react_cxx_platform_react_nativemodule INTERFACE -Wpedantic) diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/nativemodule/JavaScriptModule.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/nativemodule/JavaScriptModule.h deleted file mode 100644 index 5b038a00c2..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/nativemodule/JavaScriptModule.h +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include - -namespace facebook::react { - -using JavaScriptModuleCallback = - std::function; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/nativemodule/TurboModuleProvider.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/nativemodule/TurboModuleProvider.h deleted file mode 100644 index b10c248aab..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/nativemodule/TurboModuleProvider.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include - -namespace facebook::react { - -class CallInvoker; -class TurboModule; - -using TurboModuleProvider = - std::function(const std::string &name, const std::shared_ptr &jsInvoker)>; - -using TurboModuleProviders = std::vector; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/CMakeLists.txt b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/CMakeLists.txt deleted file mode 100644 index 61e5cd07c4..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -include(${REACT_COMMON_DIR}/cmake-utils/react-native-flags.cmake) - -file(GLOB react_cxx_platform_react_profiling_SRC CONFIGURE_DEPENDS *.cpp) -add_library(react_cxx_platform_react_profiling OBJECT ${react_cxx_platform_react_profiling_SRC}) - -target_include_directories(react_cxx_platform_react_profiling PUBLIC ${REACT_CXX_PLATFORM_DIR}) - -target_link_libraries(react_cxx_platform_react_profiling - fmt - glog - jsi -) -target_compile_reactnative_options(react_cxx_platform_react_profiling PRIVATE) -target_compile_options(react_cxx_platform_react_profiling PRIVATE -Wpedantic) diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/FrameStats.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/FrameStats.cpp deleted file mode 100644 index 576332c095..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/FrameStats.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "FrameStats.h" -#include "TimeSeries.h" - -#include - -#include - -namespace facebook::react { - -static constexpr double FRAME_STATS_LOGGING_INTERVAL_MS = 1000.0; -static constexpr int FRAME_STATS_SERIES_CAPACITY = 256; - -struct FrameStatsLogger { - bool enablePrinting{false}; - double lastLoggedTimeMs{0.0}; - TimeSeries frameTimeSeries{FRAME_STATS_SERIES_CAPACITY}; -}; - -static FrameStatsLogger& getFrameStatsLogger() { - static FrameStatsLogger s_FrameStatsLogger; - return s_FrameStatsLogger; -} - -void enableFrameStatsPrinting(bool enable) { - getFrameStatsLogger().enablePrinting = enable; -} -void logFrameStats(double timeStampMs, double durationMs) { - auto& logger = getFrameStatsLogger(); - logger.frameTimeSeries.appendValue(timeStampMs, durationMs); - - if (logger.lastLoggedTimeMs == 0.0) { - logger.lastLoggedTimeMs = timeStampMs; - } - - if (logger.enablePrinting && - timeStampMs >= - logger.lastLoggedTimeMs + FRAME_STATS_LOGGING_INTERVAL_MS) { - const auto& timeSeries = logger.frameTimeSeries; - const auto startTime = timeStampMs - FRAME_STATS_LOGGING_INTERVAL_MS; - const auto endTime = timeStampMs; - - const int fps = timeSeries.getCount(startTime, endTime) * 1000.0 / - FRAME_STATS_LOGGING_INTERVAL_MS; - - const auto frameTimeAvg = timeSeries.getAverage(startTime, endTime); - const auto frameTimeMax = timeSeries.getMax(startTime, endTime); - const auto frameTimeMin = timeSeries.getMin(startTime, endTime); - const auto frameTimeP50 = timeSeries.getPercentile(50, startTime, endTime); - const auto frameTimeP75 = timeSeries.getPercentile(75, startTime, endTime); - const auto frameTimeP95 = timeSeries.getPercentile(95, startTime, endTime); - - LOG(INFO) << std::fixed << std::setprecision(2) << std::setfill(' ') - << std::left << "[FRAME STATS] FPS=" << std::setw(2) << fps - << " frame(ms): avg=" << std::setw(5) << std::left << frameTimeAvg - << " min=" << std::setw(5) << std::left << frameTimeMin - << " p50=" << std::setw(5) << std::left << frameTimeP50 - << " p75=" << std::setw(5) << std::left << frameTimeP75 - << " p95=" << std::setw(5) << std::left << frameTimeP95 - << " max=" << std::setw(5) << std::left << frameTimeMax; - - logger.lastLoggedTimeMs = timeStampMs; - } -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/FrameStats.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/FrameStats.h deleted file mode 100644 index ec2d5340c3..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/FrameStats.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include - -#include "perfetto.h" - -#define RENDER_FRAME_EVENT() \ - TRACE_EVENT("rncxx", "render"); \ - facebook::react::FrameStatsBlock __frameStatsBlock_##__LINE__; - -#define PROCESS_FRAME_EVENT() \ - TRACE_EVENT("rncxx", "frame"); \ - facebook::react::FrameStatsBlock __frameStatsBlock_##__LINE__; - -namespace facebook::react { -class TimeSeries; - -void enableFrameStatsPrinting(bool enable = true); -void logFrameStats(double timeStampMs, double durationMs); - -inline double getTimeStampMs() -{ - return std::chrono::duration_cast( - std::chrono::high_resolution_clock::now().time_since_epoch()) - .count() / - 1000000.0; -} - -class FrameStatsBlock { - public: - FrameStatsBlock() : startTimeStamp_(getTimeStampMs()) {} - - ~FrameStatsBlock() - { - logFrameStats(startTimeStamp_, getTimeStampMs() - startTimeStamp_); - } - - private: - double startTimeStamp_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.cpp deleted file mode 100644 index c838515c88..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "RuntimeHeapInfoCollector.h" -#include -#include -#include -#include - -namespace facebook::react { - -RuntimeHeapInfoCollector::RuntimeHeapInfoCollector( - std::chrono::milliseconds intervalMs) - : intervalMs_(intervalMs) { - if (intervalMs_ <= std::chrono::milliseconds::zero()) { - throw std::runtime_error( - fmt::format( - "Invalid interval, must be > 0ms, got {} ms", intervalMs_.count())); - } - - lastCollectionTime_ = std::chrono::steady_clock::now(); -} - -std::unique_ptr RuntimeHeapInfoCollector::create( - std::chrono::milliseconds intervalMs) { - if (intervalMs <= std::chrono::milliseconds::zero()) { - LOG(INFO) << "RuntimeHeapInfoCollector is disabled"; - return nullptr; - } - - return std::make_unique(intervalMs); -} - -void RuntimeHeapInfoCollector::collectHeapInfo(jsi::Runtime& runtime) { - auto now = std::chrono::steady_clock::now(); - if (now - lastCollectionTime_ < intervalMs_) { - return; - } - - lastCollectionTime_ = now; - auto heap = runtime.instrumentation().getHeapInfo(false); - heapInfo_ = { - .allocatedBytes = heap["hermes_allocatedBytes"], - .heapSize = heap["hermes_heapSize"], - .numCollections = heap["hermes_numCollections"], - }; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.h deleted file mode 100644 index 120c394fa7..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/RuntimeHeapInfoCollector.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include - -namespace facebook::react { - -struct HeapInfo { - int64_t allocatedBytes{0}; - int64_t heapSize{0}; - int64_t numCollections{0}; -}; - -inline std::ostream &operator<<(std::ostream &os, HeapInfo &heapInfo) -{ - os << "[heapInfo: allocatedBytes: " << heapInfo.allocatedBytes << ", heapSize: " << heapInfo.heapSize - << ", numCollections: " << heapInfo.numCollections << "]"; - return os; -} - -class RuntimeHeapInfoCollector { - public: - RuntimeHeapInfoCollector(std::chrono::milliseconds intervalMs); - - static std::unique_ptr create(std::chrono::milliseconds intervalMs); - - void collectHeapInfo(jsi::Runtime &runtime); - - HeapInfo getHeapInfo() - { - return heapInfo_; - } - - private: - HeapInfo heapInfo_{}; - std::chrono::milliseconds intervalMs_; - std::chrono::steady_clock::time_point lastCollectionTime_; -}; -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/TimeSeries.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/TimeSeries.cpp deleted file mode 100644 index ee01167018..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/TimeSeries.cpp +++ /dev/null @@ -1,330 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "TimeSeries.h" - -#include -#include - -namespace facebook::react { - -TimeSeries::TimeSeries(int capacity) { - setCapacity(capacity); -} - -bool TimeSeries::operator==(const TimeSeries& rhs) const { - const int n = getNumPoints(); - if (n != rhs.getNumPoints()) { - return false; - } - - for (int i = 0; i < n; i++) { - if (timeAtIndex(i) != rhs.timeAtIndex(i) || - valueAtIndex(i) != rhs.valueAtIndex(i)) { - return false; - } - } - return true; -} - -void TimeSeries::setCapacity(int capacity) { - // Could have preserved the data, but don't bother for now - times_ = std::vector(); - times_.reserve(capacity); - - values_ = std::vector(); - values_.reserve(capacity); -} - -void TimeSeries::reset() { - times_ = {}; - values_ = {}; - position_ = 0; -} - -int TimeSeries::findHistoryPointIndex(double t, TimeSeries::Bound bound) const { - if (times_.empty()) { - return -1; - } - if (t >= times_[0]) { - auto it = (bound == Bound::Lower) - ? std::lower_bound(times_.begin(), times_.begin() + position_, t) - : std::upper_bound(times_.begin(), times_.begin() + position_, t); - return std::min( - static_cast(it - times_.begin()), static_cast(position_ - 1)); - } else if (position_ < times_.size()) { - auto it = (bound == Bound::Lower) - ? std::lower_bound(times_.begin() + position_, times_.end(), t) - : std::upper_bound(times_.begin() + position_, times_.end(), t); - return static_cast(it - times_.begin()); - } else { - return 0; - } -} - -TimeSeries::Range TimeSeries::findHistoryPointRange( - double timeFrom, - double timeTo) const { - Range res; - if (times_.empty() || timeTo < timeFrom) { - return res; - } - const int position = static_cast(position_); - const int numPoints = static_cast(times_.size()); - - // index of time point greater or equal to timeFrom - int idxL = findHistoryPointIndex(timeFrom, Bound::Lower); - if (idxL == position - 1 && times_[idxL] < timeFrom) { - idxL++; - } - - // index of time point lower or equal to timeTo - int idxR = findHistoryPointIndex(timeTo, Bound::Upper); - if (idxR < numPoints && times_[idxR] <= timeTo) { - idxR++; - } - - const bool fullRange = timeFrom <= getMinTime() && timeTo >= getMaxTime(); - if (fullRange) { - if (position < numPoints) { - res.idxFrom1 = position; - res.idxTo1 = numPoints; - res.idxFrom2 = 0; - res.idxTo2 = position; - } else { - res.idxFrom1 = 0; - res.idxTo1 = numPoints; - res.idxFrom2 = 0; - res.idxTo2 = 0; - } - } else if (idxL >= numPoints) { - res.idxFrom1 = 0; - res.idxTo1 = idxR; - res.idxFrom2 = 0; - res.idxTo2 = 0; - } else if (idxL > idxR) { - res.idxFrom1 = idxL; - res.idxTo1 = numPoints; - res.idxFrom2 = 0; - res.idxTo2 = idxR; - } else { - res.idxFrom1 = idxL; - res.idxTo1 = idxR; - res.idxFrom2 = 0; - res.idxTo2 = 0; - } - - return res; -} - -TimeSeries::Range TimeSeries::wholeRange() const { - Range res; - const int position = static_cast(position_); - const int numPoints = static_cast(times_.size()); - - if (position >= numPoints) { - res.idxFrom1 = 0; - res.idxTo1 = position; - res.idxFrom2 = 0; - res.idxTo2 = 0; - } else { - res.idxFrom1 = position; - res.idxTo1 = numPoints; - res.idxFrom2 = 0; - res.idxTo2 = position; - } - return res; -} - -void TimeSeries::appendValue(double t, double value) { - if (getMaxTime() > t) { - // ignore old values - return; - } - if (!times_.empty() && getMaxTime() == t) { - values_[values_.size() - 1] = value; - } else if (times_.size() < times_.capacity()) { - times_.push_back(t); - values_.push_back(value); - position_ = times_.size(); - } else { - position_ = position_ % times_.size(); - times_[position_] = t; - values_[position_] = value; - position_++; - } -} - -void TimeSeries::accumulateValue(double timeFrom, double timeTo, double value) { - if (timeTo - timeFrom <= 0.0) { - return; - } - - if (getNumPoints() == 0 || timeFrom >= getMaxTime()) { - appendValue(timeFrom, 0.0); - appendValue(timeTo, value); - return; - } - - double curTime = timeFrom; - const int n = getNumPoints(); - int curPoint = - (findHistoryPointIndex(timeFrom, Bound::Upper) + n - position_) % n; - - while (curPoint < n && timeAtIndex(curPoint) < timeTo) { - const double t = timeAtIndex(curPoint); - valueAtIndex(curPoint) += value * (t - curTime) / (timeTo - timeFrom); - curTime = t; - curPoint++; - } - - if (curTime < timeTo) { - const double dVal = value * (timeTo - curTime) / (timeTo - timeFrom); - if (curPoint == n) { - appendValue(timeTo, dVal); - } else { - valueAtIndex(curPoint) += dVal; - } - } -} - -double TimeSeries::getPercentile( - unsigned int percentile, - const TimeSeries::Range& range) const { - if (range.isEmpty()) { - return 0.0f; - } - std::vector values(range.size()); - std::copy( - values_.begin() + range.idxFrom1, - values_.begin() + range.idxTo1, - values.begin()); - std::copy( - values_.begin() + range.idxFrom2, - values_.begin() + range.idxTo2, - values.begin() + (range.idxTo1 - range.idxFrom1)); - - const size_t k = percentile * values.size() / 100; - std::nth_element(values.begin(), values.begin() + k, values.end()); - return *(values.begin() + k); -} - -double TimeSeries::getSum(const TimeSeries::Range& range) const { - if (range.isEmpty()) { - return 0.0f; - } - double sum = std::accumulate( - values_.begin() + range.idxFrom1, values_.begin() + range.idxTo1, 0.0); - sum = std::accumulate( - values_.begin() + range.idxFrom2, values_.begin() + range.idxTo2, sum); - return sum; -} - -double TimeSeries::getAverage(const TimeSeries::Range& range) const { - if (range.isEmpty()) { - return 0.0f; - } - return getSum(range) / range.size(); -} - -double TimeSeries::getMax(const TimeSeries::Range& range) const { - if (range.isEmpty()) { - return 0.0f; - } - const double v1 = *std::max_element( - values_.begin() + range.idxFrom1, values_.begin() + range.idxTo1); - const double v2 = range.isContinuous() - ? v1 - : *std::max_element( - values_.begin() + range.idxFrom2, values_.begin() + range.idxTo2); - return std::max(v1, v2); -} - -double TimeSeries::getMin(const TimeSeries::Range& range) const { - if (range.isEmpty()) { - return 0.0f; - } - const double v1 = *std::min_element( - values_.begin() + range.idxFrom1, values_.begin() + range.idxTo1); - const double v2 = range.isContinuous() - ? v1 - : *std::min_element( - values_.begin() + range.idxFrom2, values_.begin() + range.idxTo2); - return std::min(v1, v2); -} - -double TimeSeries::getPercentile(unsigned int percentile) const { - return getPercentile(percentile, wholeRange()); -} - -double TimeSeries::getPercentile( - unsigned int percentile, - double timeFrom, - double timeTo) const { - return getPercentile(percentile, findHistoryPointRange(timeFrom, timeTo)); -} - -double TimeSeries::getAverage() const { - return getAverage(wholeRange()); -} - -double TimeSeries::getAverage(double timeFrom, double timeTo) const { - return getAverage(findHistoryPointRange(timeFrom, timeTo)); -} - -double TimeSeries::getMax() const { - return getMax(wholeRange()); -} - -double TimeSeries::getMax(double timeFrom, double timeTo) const { - return getMax(findHistoryPointRange(timeFrom, timeTo)); -} - -double TimeSeries::getMin() const { - return getMin(wholeRange()); -} - -double TimeSeries::getMin(double timeFrom, double timeTo) const { - return getMin(findHistoryPointRange(timeFrom, timeTo)); -} - -double TimeSeries::getSum() const { - return getSum(wholeRange()); -} - -double TimeSeries::getSum(double timeFrom, double timeTo) const { - return getSum(findHistoryPointRange(timeFrom, timeTo)); -} - -int TimeSeries::getCount(double timeFrom, double timeTo) const { - return findHistoryPointRange(timeFrom, timeTo).size(); -} - -double TimeSeries::getMaxTime() const { - if (times_.empty()) { - return 0.0; - } - return times_[position_ - 1]; -} - -double TimeSeries::getMinTime() const { - if (times_.empty()) { - return 0.0; - } - return times_[position_ % times_.size()]; -} - -double TimeSeries::getValue(double t) const { - if (times_.empty()) { - return 0.0; - } - int pidx = findHistoryPointIndex(t); - pidx = std::min(std::max(pidx, 0), static_cast(times_.size() - 1)); - return values_[pidx]; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/TimeSeries.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/TimeSeries.h deleted file mode 100644 index 1e2ba3669d..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/TimeSeries.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include - -namespace facebook::react { - -class TimeSeries { - // A "compound range" structure to account for wrapped around intervals - struct Range { - int idxFrom1{0}; - int idxTo1{0}; - int idxFrom2{0}; - int idxTo2{0}; - - int size() const - { - return (idxTo1 - idxFrom1) + (idxTo2 - idxFrom2); - } - - bool isEmpty() const - { - return size() == 0; - } - - bool isContinuous() const - { - return idxTo2 - idxFrom2 == 0; - } - }; - - public: - static constexpr int DEFAULT_CAPACITY = 100; - enum class Bound { Upper = 0, Lower = 1 }; - - TimeSeries(int capacity = DEFAULT_CAPACITY); - - bool operator==(const TimeSeries &rhs) const; - - int getCapacity() const - { - return static_cast(times_.capacity()); - } - void setCapacity(int capacity); - - void reset(); - - int findHistoryPointIndex(double t, Bound bound = Bound::Lower) const; - - int getNumPoints() const - { - return static_cast(times_.size()); - } - - double &valueAtIndex(int idx) - { - const int numPoints = getNumPoints(); - return values_[(idx + position_) % numPoints]; - } - - double &timeAtIndex(int idx) - { - const int numPoints = getNumPoints(); - return times_[(idx + position_) % numPoints]; - } - - double valueAtIndex(int idx) const - { - const int numPoints = getNumPoints(); - return values_[(idx + position_) % numPoints]; - } - - double timeAtIndex(int idx) const - { - const int numPoints = getNumPoints(); - return times_[(idx + position_) % numPoints]; - } - - void appendValue(double time, double value); - - void accumulateValue(double timeFrom, double timeTo, double value); - - double getValue(double time) const; - - double getPercentile(unsigned int percentile) const; - double getPercentile(unsigned int percentile, double timeFrom, double timeTo) const; - - double getAverage() const; - double getAverage(double timeFrom, double timeTo) const; - - double getMax() const; - double getMax(double timeFrom, double timeTo) const; - - double getMin() const; - double getMin(double timeFrom, double timeTo) const; - - double getSum() const; - double getSum(double timeFrom, double timeTo) const; - - int getCount(double timeFrom, double timeTo) const; - - double getMaxTime() const; - double getMinTime() const; - - friend std::ostream &operator<<(std::ostream &os, const TimeSeries &ts); - friend std::ostream &operator<<(std::ostream &os, const TimeSeries::Range &range); - - private: - std::vector times_; - std::vector values_; - - size_t position_{0}; - - Range findHistoryPointRange(double timeFrom, double timeTo) const; - Range wholeRange() const; - - double getPercentile(unsigned int percentile, const Range &range) const; - double getAverage(const Range &range) const; - double getMax(const Range &range) const; - double getMin(const Range &range) const; - double getSum(const Range &range) const; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/Tracing.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/Tracing.cpp deleted file mode 100644 index 88e36158e2..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/Tracing.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "tracy_noop.h" - -#if RNCXX_WITH_PROFILING_PROVIDER -HZT_DEFINE_STATIC_STORAGE(facebook::react); -#endif diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/perfetto.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/perfetto.cpp deleted file mode 100644 index c15a1179ae..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/perfetto.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include - -#if WITH_PERFETTO -#include - -void initializePerfetto() { - static std::once_flag s_PerfettoIsInitialized; - - std::call_once(s_PerfettoIsInitialized, []() { - perfetto::TracingInitArgs args; - args.shmem_size_hint_kb = 20 * 1024; -#ifdef ANDROID - args.backends |= perfetto::kSystemBackend; -#else - args.backends |= perfetto::kInProcessBackend; -#endif - args.use_monotonic_clock = true; - perfetto::Tracing::Initialize(args); - facebook::react::TrackEvent::Register(); - }); -} - -#endif // WITH_PERFETTO diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/perfetto.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/perfetto.h deleted file mode 100644 index ea7fe39a95..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/perfetto.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include - -#include - -#ifndef WITH_PERFETTO -#define WITH_PERFETTO 0 -#endif - -#if WITH_PERFETTO -#include - -PERFETTO_DEFINE_CATEGORIES_IN_NAMESPACE( - facebook::react, - perfetto::Category("rncxx").SetDescription("Events from RN/Granite")); - -void initializePerfetto(); - -inline uint64_t getCurrentPerfettoTimestamp() -{ - return std::chrono::duration_cast( - std::chrono::high_resolution_clock::now().time_since_epoch()) - .count(); -} - -#else -#define TRACE_EVENT(category, name, ...) SCOPED_TRACE_CPU((category "_" name)) -#define TRACE_COUNTER(category, name, value, ...) - -inline void initializePerfetto() {} -#endif // WITH_PERFETTO diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/tests/TimeSeriesTests.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/tests/TimeSeriesTests.cpp deleted file mode 100644 index 12888b98ce..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/tests/TimeSeriesTests.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include - -#include - -namespace facebook::react { - -class TimeSeriesTests : public testing::Test {}; - -std::ostream& operator<<(std::ostream& os, const TimeSeries& ts) { - const size_t n = ts.getNumPoints(); - os << "Position: " << ts.position_ << ", "; - os << "Points: " << ts.getNumPoints() << ", "; - for (size_t i = 0; i < n; i++) { - os << "[" << ts.times_[i] << ", " << ts.values_[i] << "] "; - } - return os; -} - -std::ostream& operator<<(std::ostream& os, const TimeSeries::Range& range) { - os << " [" << range.idxFrom1 << " " << range.idxTo1 << "] [" << range.idxFrom2 - << " " << range.idxTo2 << "]"; - return os; -} - -TEST_F(TimeSeriesTests, basicOperations) { - TimeSeries ts(5); - - EXPECT_FLOAT_EQ(0.0, ts.getAverage()); - EXPECT_FLOAT_EQ(0.0, ts.getPercentile(75)); - EXPECT_FLOAT_EQ(0.0, ts.getMin()); - EXPECT_FLOAT_EQ(0.0, ts.getMax()); - - ts.appendValue(0.0, 3.0); - EXPECT_FLOAT_EQ(3.0, ts.getValue(0.0)); - - ts.appendValue(1.0, 6.0); - ts.appendValue(3.0, 0.0); - EXPECT_FLOAT_EQ(6.0, ts.getValue(1.0)); - - ts.appendValue(4.0, 10.0); - ts.appendValue(5.0, 1.0); - - EXPECT_FLOAT_EQ(3.0, ts.getValue(-1.0)); - EXPECT_FLOAT_EQ(3.0, ts.getValue(0.0)); - EXPECT_FLOAT_EQ(6.0, ts.getValue(1.0)); - EXPECT_FLOAT_EQ(0.0, ts.getValue(3.0)); - EXPECT_FLOAT_EQ(10.0, ts.getValue(4.0)); - EXPECT_FLOAT_EQ(1.0, ts.getValue(5.0)); - EXPECT_FLOAT_EQ(1.0, ts.getValue(6.0)); - - EXPECT_FLOAT_EQ(4.0, ts.getAverage()); - EXPECT_FLOAT_EQ(3.0, ts.getPercentile(50)); - EXPECT_FLOAT_EQ(0.0, ts.getMin()); - EXPECT_FLOAT_EQ(10.0, ts.getMax()); - - ts.appendValue(6.0, 2.0); - ts.appendValue(10.0, 7.0); - - EXPECT_FLOAT_EQ(10.0, ts.getMaxTime()); - EXPECT_FLOAT_EQ(3.0, ts.getMinTime()); - - EXPECT_FLOAT_EQ(0.0, ts.getValue(-1.0)); - EXPECT_FLOAT_EQ(0.0, ts.getValue(2.0)); - EXPECT_FLOAT_EQ(0.0, ts.getValue(3.0)); - EXPECT_FLOAT_EQ(10.0, ts.getValue(4.0)); - EXPECT_FLOAT_EQ(1.0, ts.getValue(5.0)); - EXPECT_FLOAT_EQ(2.0, ts.getValue(6.0)); - EXPECT_FLOAT_EQ(7.0, ts.getValue(10.0)); - EXPECT_FLOAT_EQ(7.0, ts.getValue(20.0)); - - ts.appendValue(11.0, -7.0); - EXPECT_FLOAT_EQ(-7.0, ts.getMin()); - EXPECT_FLOAT_EQ(10.0, ts.getMax()); -} - -TEST_F(TimeSeriesTests, rangeOperations) { - TimeSeries ts(5); - ts.appendValue(0.0, 0.0); - ts.appendValue(1.0, 1.0); - ts.appendValue(2.0, 2.0); - - EXPECT_FLOAT_EQ(0.0, ts.getMin(-1.0, 100.0)); - EXPECT_FLOAT_EQ(2.0, ts.getMax(-1.0, 100.0)); - - EXPECT_FLOAT_EQ(0.0, ts.getMin(-1.0, 1.5)); - EXPECT_FLOAT_EQ(1.0, ts.getMax(-1.0, 1.5)); - - EXPECT_FLOAT_EQ(1.0, ts.getMin(0.5, 1.5)); - EXPECT_FLOAT_EQ(1.0, ts.getMax(-1.0, 1.5)); - EXPECT_FLOAT_EQ(1.0, ts.getMax(1.0, 1.5)); - - EXPECT_FLOAT_EQ(1.5, ts.getAverage(0.5, 2.0)); - EXPECT_FLOAT_EQ(1.5, ts.getAverage(0.5, 3.0)); - - ts.appendValue(3.0, 3.0); - ts.appendValue(4.0, 4.0); - ts.appendValue(5.0, 5.0); - ts.appendValue(6.0, 6.0); - - // Current circular buffer layout should be: 5 6 | 2 3 4 - // Cover corner cases by sampling different ranges - EXPECT_EQ(1, ts.getCount(6.0, 6.0)); - EXPECT_EQ(2, ts.getCount(4.5, 6.0)); - EXPECT_EQ(5, ts.getCount(0.0, 6.0)); - EXPECT_EQ(5, ts.getCount(0.0, 7.0)); - EXPECT_EQ(2, ts.getCount(3.5, 5.0)); - EXPECT_EQ(0, ts.getCount(7.0, 8.0)); - EXPECT_EQ(2, ts.getCount(4.5, 7.0)); - EXPECT_EQ(2, ts.getCount(3.5, 5.5)); - - EXPECT_FLOAT_EQ(2.0, ts.getMin(0.0, 2.0)); - EXPECT_FLOAT_EQ(2.0, ts.getMin(0.0, 2.5)); - EXPECT_FLOAT_EQ(0.0, ts.getMin(0.0, 1.0)); - EXPECT_FLOAT_EQ(0.0, ts.getMin(100.0, 101.0)); - EXPECT_FLOAT_EQ(0.0, ts.getAverage(0.0, 1.0)); - - EXPECT_FLOAT_EQ(4.0, ts.getMin(3.5, 5.5)); - EXPECT_FLOAT_EQ(5.0, ts.getMax(3.5, 5.5)); - EXPECT_FLOAT_EQ(4.5, ts.getAverage(3.5, 5.5)); - - EXPECT_FLOAT_EQ(3.0, ts.getMin(2.5, 4.5)); - EXPECT_FLOAT_EQ(4.0, ts.getMax(2.5, 4.5)); - EXPECT_FLOAT_EQ(3.5, ts.getAverage(2.5, 4.5)); - - EXPECT_FLOAT_EQ(6.0, ts.getMin(5.5, 7.5)); - EXPECT_FLOAT_EQ(6.0, ts.getMax(5.5, 7.5)); - EXPECT_FLOAT_EQ(6.0, ts.getAverage(5.5, 7.5)); - - EXPECT_FLOAT_EQ(5.0, ts.getMin(4.5, 7.5)); - EXPECT_FLOAT_EQ(6.0, ts.getMax(4.5, 7.5)); - EXPECT_FLOAT_EQ(5.5, ts.getAverage(4.5, 7.5)); -} - -TEST_F(TimeSeriesTests, accumulateOperations) { - TimeSeries ts(5); - ts.accumulateValue(1.0, 2.0, 1.0); - - EXPECT_EQ(2, ts.getNumPoints()); - - EXPECT_FLOAT_EQ(1.0, ts.timeAtIndex(0)); - EXPECT_FLOAT_EQ(2.0, ts.timeAtIndex(1)); - - EXPECT_FLOAT_EQ(0.0, ts.valueAtIndex(0)); - EXPECT_FLOAT_EQ(1.0, ts.valueAtIndex(1)); - - ts.appendValue(3.0, 2.0); - - ts.accumulateValue(1.5, 4.5, 3.0); - EXPECT_EQ(4, ts.getNumPoints()); - - EXPECT_FLOAT_EQ(0.0, ts.valueAtIndex(0)); - EXPECT_FLOAT_EQ(1.5, ts.valueAtIndex(1)); - EXPECT_FLOAT_EQ(3.0, ts.valueAtIndex(2)); - EXPECT_FLOAT_EQ(1.5, ts.valueAtIndex(3)); - - EXPECT_FLOAT_EQ(1.0, ts.timeAtIndex(0)); - EXPECT_FLOAT_EQ(2.0, ts.timeAtIndex(1)); - EXPECT_FLOAT_EQ(3.0, ts.timeAtIndex(2)); - EXPECT_FLOAT_EQ(4.5, ts.timeAtIndex(3)); - - ts.accumulateValue(2.0, 3.5, 1.5); - - EXPECT_EQ(4, ts.getNumPoints()); - - EXPECT_FLOAT_EQ(0.0, ts.valueAtIndex(0)); - EXPECT_FLOAT_EQ(1.5, ts.valueAtIndex(1)); - EXPECT_FLOAT_EQ(4.0, ts.valueAtIndex(2)); - EXPECT_FLOAT_EQ(2.0, ts.valueAtIndex(3)); - - EXPECT_FLOAT_EQ(1.0, ts.timeAtIndex(0)); - EXPECT_FLOAT_EQ(2.0, ts.timeAtIndex(1)); - EXPECT_FLOAT_EQ(3.0, ts.timeAtIndex(2)); - EXPECT_FLOAT_EQ(4.5, ts.timeAtIndex(3)); - - ts.appendValue(5.0, 0.0); - ts.appendValue(5.5, 0.0); - ts.appendValue(6.0, 0.0); - - EXPECT_EQ(5, ts.getNumPoints()); - - ts.accumulateValue(4.0, 7.0, 6.0); - EXPECT_EQ(5, ts.getNumPoints()); - - EXPECT_EQ(3, ts.findHistoryPointIndex(4.0, TimeSeries::Bound::Upper)); - - EXPECT_FLOAT_EQ(3.0, ts.valueAtIndex(0)); - EXPECT_FLOAT_EQ(1.0, ts.valueAtIndex(1)); - EXPECT_FLOAT_EQ(1.0, ts.valueAtIndex(2)); - EXPECT_FLOAT_EQ(1.0, ts.valueAtIndex(3)); - EXPECT_FLOAT_EQ(2.0, ts.valueAtIndex(4)); - - EXPECT_FLOAT_EQ(4.5, ts.timeAtIndex(0)); - EXPECT_FLOAT_EQ(5.0, ts.timeAtIndex(1)); - EXPECT_FLOAT_EQ(5.5, ts.timeAtIndex(2)); - EXPECT_FLOAT_EQ(6.0, ts.timeAtIndex(3)); - EXPECT_FLOAT_EQ(7.0, ts.timeAtIndex(4)); -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/tracy_noop.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/tracy_noop.h deleted file mode 100644 index 40ec4d9e99..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/profiling/tracy_noop.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#ifndef RNCXX_WITH_PROFILING_PROVIDER -#define RNCXX_WITH_PROFILING_PROVIDER 0 -#endif - -#if RNCXX_WITH_PROFILING_PROVIDER -#include - -#ifndef TRACE_FUNCTION -#if defined(__GNUC__) || defined(__clang__) -#define TRACE_FUNCTION __PRETTY_FUNCTION__ -#else -#define TRACE_FUNCTION __FUNCTION__ -#endif -#endif // TRACE_FUNCTION - -static inline constexpr char kTraceCategory[] = "react_native"; - -HZT_DEFINE_TRACING_CATEGORIES( - facebook::react, - horizon::tracing::Category(kTraceCategory, "react_native", horizon::tracing::StrippingLevel::Important)); - -#define SCOPED_TRACE_CPU_AUTO() HZT_TRACE_SCOPE_NS(::facebook::react, kTraceCategory, TRACE_FUNCTION); - -#define SCOPED_TRACE_CPU(name) HZT_TRACE_SCOPE_NS(::facebook::react, kTraceCategory, name); - -#else -#ifndef SCOPED_TRACE_CPU_AUTO -#define SCOPED_TRACE_CPU_AUTO() ((void)0) -#endif -#ifndef SCOPED_TRACE_CPU -#define SCOPED_TRACE_CPU(name) ((void)0) -#endif -#endif diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopcontextmenuview/DesktopContextMenuView.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopcontextmenuview/DesktopContextMenuView.cpp deleted file mode 100644 index a48e6c631d..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopcontextmenuview/DesktopContextMenuView.cpp +++ /dev/null @@ -1,83 +0,0 @@ -#include "DesktopContextMenuView.h" - -#include -#include -#include -#include - -namespace facebook::react { - -const char DesktopContextMenuViewComponentName[] = "DesktopContextMenuView"; - -DesktopContextMenuViewProps::DesktopContextMenuViewProps( - const PropsParserContext& context, - const DesktopContextMenuViewProps& sourceProps, - const RawProps& rawProps) - : ViewProps(context, sourceProps, rawProps), - // `convertRawProp` reaches `folly::dynamic` through `RawValue`'s explicit - // conversion, so the recursive model arrives as-is: no serialisation in - // JS and no second shape to keep in step with `MenuItemSpec`. - items(convertRawProp( - context, - rawProps, - "items", - sourceProps.items, - folly::dynamic::array())), - presentation(convertRawProp( - context, - rawProps, - "presentation", - sourceProps.presentation, - std::string{"default"})), - disabled(convertRawProp( - context, - rawProps, - "disabled", - sourceProps.disabled, - false)) {} - -#ifdef RN_SERIALIZABLE_STATE -ComponentName DesktopContextMenuViewProps::getDiffPropsImplementationTarget() - const { - return DesktopContextMenuViewComponentName; -} - -folly::dynamic DesktopContextMenuViewProps::getDiffProps( - const Props* prevProps) const { - static const auto defaultProps = DesktopContextMenuViewProps(); - const auto* oldProps = prevProps == nullptr - ? &defaultProps - : static_cast(prevProps); - if (this == oldProps) { - return folly::dynamic::object(); - } - - folly::dynamic result = ViewProps::getDiffProps(prevProps); - // Compared as values, so a rebuilt array with the same entries is not a - // change. That is what makes a memoised-but-reallocated `items` cheap. - if (!(items == oldProps->items)) { - result["items"] = items; - } - if (presentation != oldProps->presentation) { - result["presentation"] = presentation; - } - if (disabled != oldProps->disabled) { - result["disabled"] = disabled; - } - return result; -} -#endif - -#if RN_DEBUG_STRING_CONVERTIBLE -SharedDebugStringConvertibleList DesktopContextMenuViewProps::getDebugProps() - const { - return ViewProps::getDebugProps() + - SharedDebugStringConvertibleList{ - debugStringConvertibleItem("items", folly::toJson(items)), - debugStringConvertibleItem("presentation", presentation), - debugStringConvertibleItem("disabled", disabled), - }; -} -#endif - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopcontextmenuview/DesktopContextMenuView.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopcontextmenuview/DesktopContextMenuView.h deleted file mode 100644 index 5718567a0b..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopcontextmenuview/DesktopContextMenuView.h +++ /dev/null @@ -1,61 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include - -// Hand-written rather than generated: core has no component codegen, because -// autolink only runs it for dependencies and core is the runtime. This follows -// `windowcontrol/WindowControl.h`, core's other hand-registered component. -namespace facebook::react { - -extern const char DesktopContextMenuViewComponentName[]; - -/// A view whose secondary click opens a menu from native. -/// -/// `items` is the menu model itself — a recursive array that codegen cannot -/// describe, which is why the JS spec types it as `UnsafeMixed` and it arrives -/// here as `folly::dynamic`. The Rust renderer reads it as JSON from the props -/// reader, in the same shape `MenuItemSpec` uses everywhere else, so a menu -/// shown by this component and one shown by `ContextMenu.show` cannot differ. -class DesktopContextMenuViewProps final : public ViewProps { - public: - DesktopContextMenuViewProps() = default; - DesktopContextMenuViewProps( - const PropsParserContext& context, - const DesktopContextMenuViewProps& sourceProps, - const RawProps& rawProps); - - // Copy-init, not brace-init: `folly::dynamic` has an initializer-list - // constructor, so braces here would build a one-element array holding an empty - // array. - folly::dynamic items = folly::dynamic::array(); - /// `default`, `native` or `custom`. `custom` is opened by JS, so the native - /// renderer leaves it alone; `default` means whatever the app asked for, - /// which this path can only serve as a native menu. - std::string presentation{"default"}; - bool disabled{false}; - -#ifdef RN_SERIALIZABLE_STATE - ComponentName getDiffPropsImplementationTarget() const override; - folly::dynamic getDiffProps(const Props* prevProps) const override; -#endif - -#if RN_DEBUG_STRING_CONVERTIBLE - SharedDebugStringConvertibleList getDebugProps() const override; -#endif -}; - -using DesktopContextMenuViewShadowNode = ConcreteViewShadowNode< - DesktopContextMenuViewComponentName, - DesktopContextMenuViewProps, - ViewEventEmitter>; -using DesktopContextMenuViewComponentDescriptor = - ConcreteComponentDescriptor; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopscrollbar/DesktopScrollBar.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopscrollbar/DesktopScrollBar.cpp deleted file mode 100644 index ba4e7a087f..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopscrollbar/DesktopScrollBar.cpp +++ /dev/null @@ -1,128 +0,0 @@ -#include "DesktopScrollBar.h" - -#include -#include -#include - -namespace facebook::react { - -const char DesktopScrollBarComponentName[] = "DesktopScrollBar"; - -DesktopScrollBarProps::DesktopScrollBarProps( - const PropsParserContext& context, - const DesktopScrollBarProps& sourceProps, - const RawProps& rawProps) - : ViewProps(context, sourceProps, rawProps), - thickness(convertRawProp( - context, - rawProps, - "thickness", - sourceProps.thickness, - Float{-1})), - minLength(convertRawProp( - context, - rawProps, - "minLength", - sourceProps.minLength, - Float{-1})), - margin(convertRawProp( - context, - rawProps, - "margin", - sourceProps.margin, - Float{-1})), - color(convertRawProp( - context, - rawProps, - "color", - sourceProps.color, - SharedColor{})), - radius(convertRawProp( - context, - rawProps, - "radius", - sourceProps.radius, - Float{-1})), - trackColor(convertRawProp( - context, - rawProps, - "trackColor", - sourceProps.trackColor, - SharedColor{})), - visibility(convertRawProp( - context, - rawProps, - "visibility", - sourceProps.visibility, - std::string{})), - autoHideDelay(convertRawProp( - context, - rawProps, - "autoHideDelay", - sourceProps.autoHideDelay, - Float{-1})), - interactive(convertRawProp( - context, - rawProps, - "interactive", - sourceProps.interactive, - true)) {} - -#ifdef RN_SERIALIZABLE_STATE -ComponentName DesktopScrollBarProps::getDiffPropsImplementationTarget() const { - return DesktopScrollBarComponentName; -} - -folly::dynamic DesktopScrollBarProps::getDiffProps( - const Props* prevProps) const { - static const auto defaultProps = DesktopScrollBarProps(); - const auto* oldProps = prevProps == nullptr - ? &defaultProps - : static_cast(prevProps); - if (this == oldProps) { - return folly::dynamic::object(); - } - - folly::dynamic result = ViewProps::getDiffProps(prevProps); - if (thickness != oldProps->thickness) { - result["thickness"] = thickness; - } - if (minLength != oldProps->minLength) { - result["minLength"] = minLength; - } - if (margin != oldProps->margin) { - result["margin"] = margin; - } - if (color != oldProps->color) { - result["color"] = *color; - } - if (radius != oldProps->radius) { - result["radius"] = radius; - } - if (trackColor != oldProps->trackColor) { - result["trackColor"] = *trackColor; - } - if (visibility != oldProps->visibility) { - result["visibility"] = visibility; - } - if (autoHideDelay != oldProps->autoHideDelay) { - result["autoHideDelay"] = autoHideDelay; - } - if (interactive != oldProps->interactive) { - result["interactive"] = interactive; - } - return result; -} -#endif - -#if RN_DEBUG_STRING_CONVERTIBLE -SharedDebugStringConvertibleList DesktopScrollBarProps::getDebugProps() const { - return ViewProps::getDebugProps() + SharedDebugStringConvertibleList{ - debugStringConvertibleItem("thickness", thickness), - debugStringConvertibleItem("visibility", visibility), - debugStringConvertibleItem("interactive", interactive), - }; -} -#endif - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopscrollbar/DesktopScrollBar.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopscrollbar/DesktopScrollBar.h deleted file mode 100644 index fdd293b876..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopscrollbar/DesktopScrollBar.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include - -// Hand-written like `shortcutscope/ShortcutScope.h`: core has no component -// codegen. The component paints and lays out nothing. The scroll view that -// contains it reads these props and draws its own scrollbar from them, and the -// drag events go out on this node. -namespace facebook::react { - -extern const char DesktopScrollBarComponentName[]; - -/// How the scrollbar of the nearest scroll view looks and behaves. A negative -/// number, an empty string or an unset color keeps the default. -class DesktopScrollBarProps final : public ViewProps { - public: - DesktopScrollBarProps() = default; - DesktopScrollBarProps( - const PropsParserContext& context, - const DesktopScrollBarProps& sourceProps, - const RawProps& rawProps); - - Float thickness{-1}; - Float minLength{-1}; - Float margin{-1}; - SharedColor color{}; - Float radius{-1}; - SharedColor trackColor{}; - /// `auto`, `always` or `hover`. - std::string visibility{}; - Float autoHideDelay{-1}; - bool interactive{true}; - -#ifdef RN_SERIALIZABLE_STATE - ComponentName getDiffPropsImplementationTarget() const override; - folly::dynamic getDiffProps(const Props* prevProps) const override; -#endif - -#if RN_DEBUG_STRING_CONVERTIBLE - SharedDebugStringConvertibleList getDebugProps() const override; -#endif -}; - -using DesktopScrollBarShadowNode = ConcreteViewShadowNode< - DesktopScrollBarComponentName, - DesktopScrollBarProps, - ViewEventEmitter>; -using DesktopScrollBarComponentDescriptor = - ConcreteComponentDescriptor; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopswitch/DesktopSwitch.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopswitch/DesktopSwitch.cpp deleted file mode 100644 index 16ea1bf537..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopswitch/DesktopSwitch.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include "DesktopSwitch.h" - -#include - -namespace facebook::react { - -const char DesktopSwitchComponentName[] = "Switch"; - -Size DesktopSwitchShadowNode::measureContent( - const LayoutContext& /*layoutContext*/, - const LayoutConstraints& layoutConstraints) const { -#if defined(__APPLE__) - const Size size{38, 22}; -#elif defined(_WIN32) - const Size size{40, 20}; -#else - const Size size{46, 26}; -#endif - return layoutConstraints.clamp(size); -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopswitch/DesktopSwitch.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopswitch/DesktopSwitch.h deleted file mode 100644 index dfe349f4e3..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/desktopswitch/DesktopSwitch.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -// `Switch` is measured natively, as on iOS (`AppleSwitchShadowNode`): React -// Native's JS gives it no width or height. -namespace facebook::react { - -extern const char DesktopSwitchComponentName[]; - -class DesktopSwitchShadowNode final : public ConcreteViewShadowNode< - DesktopSwitchComponentName, - SwitchProps, - SwitchEventEmitter> { - public: - using ConcreteViewShadowNode::ConcreteViewShadowNode; - - static ShadowNodeTraits BaseTraits() { - auto traits = ConcreteViewShadowNode::BaseTraits(); - traits.set(ShadowNodeTraits::Trait::LeafYogaNode); - traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode); - return traits; - } - - Size measureContent( - const LayoutContext& layoutContext, - const LayoutConstraints& layoutConstraints) const override; -}; - -using DesktopSwitchComponentDescriptor = - ConcreteComponentDescriptor; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/nativeroot/NativeRoot.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/nativeroot/NativeRoot.cpp deleted file mode 100644 index 56e13c372c..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/nativeroot/NativeRoot.cpp +++ /dev/null @@ -1,129 +0,0 @@ -#include "NativeRoot.h" - -#include -#include -#include -#include - -namespace facebook::react { - -const char NativeRootComponentName[] = "DesktopNativeRoot"; - -NativeRootProps::NativeRootProps( - const PropsParserContext& context, - const NativeRootProps& sourceProps, - const RawProps& rawProps) - : ViewProps(context, sourceProps, rawProps), - rootId(convertRawProp( - context, - rawProps, - "rootId", - sourceProps.rootId, - 0)), - hintHeight(convertRawProp( - context, - rawProps, - "hintHeight", - sourceProps.hintHeight, - -1.f)), - hintWidth(convertRawProp( - context, - rawProps, - "hintWidth", - sourceProps.hintWidth, - -1.f)), - hintMinWidth(convertRawProp( - context, - rawProps, - "hintMinWidth", - sourceProps.hintMinWidth, - -1.f)) {} - -#ifdef RN_SERIALIZABLE_STATE -ComponentName NativeRootProps::getDiffPropsImplementationTarget() const { - return NativeRootComponentName; -} - -folly::dynamic NativeRootProps::getDiffProps(const Props* prevProps) const { - static const auto defaultProps = NativeRootProps(); - const auto* oldProps = prevProps == nullptr - ? &defaultProps - : static_cast(prevProps); - if (this == oldProps) { - return folly::dynamic::object(); - } - - folly::dynamic result = ViewProps::getDiffProps(prevProps); - if (rootId != oldProps->rootId) { - result["rootId"] = rootId; - } - if (hintHeight != oldProps->hintHeight) { - result["hintHeight"] = hintHeight; - } - if (hintWidth != oldProps->hintWidth) { - result["hintWidth"] = hintWidth; - } - if (hintMinWidth != oldProps->hintMinWidth) { - result["hintMinWidth"] = hintMinWidth; - } - return result; -} -#endif - -#if !(defined(LOOM_RENDERER) && LOOM_RENDERER) -void NativeRootShadowNode::applyContentSize() { - const auto& data = getStateData(); - const auto& props = static_cast(*getProps()); - const auto& base = props.yogaStyle; - const auto height = data.hasHeight ? data.height : props.hintHeight; - const auto width = data.hasWidth ? data.width : props.hintWidth; - const auto minWidth = data.hasWidth ? data.minWidth : props.hintMinWidth; - auto style = yogaNode_.style(); - const auto open = [&](yoga::Dimension axis) { - const auto size = base.dimension(axis); - return size.isUndefined() || size.isAuto(); - }; - if (height >= 0 && open(yoga::Dimension::Height)) { - style.setDimension( - yoga::Dimension::Height, yoga::StyleSizeLength::points(height)); - } - if (width >= 0 && minWidth >= 0) { - if (base.minDimension(yoga::Dimension::Width).isUndefined()) { - style.setMinDimension( - yoga::Dimension::Width, yoga::StyleSizeLength::points(minWidth)); - } - if (base.maxDimension(yoga::Dimension::Width).isUndefined()) { - style.setMaxDimension( - yoga::Dimension::Width, yoga::StyleSizeLength::percent(100)); - } - if (base.flexShrink().isUndefined()) { - style.setFlexShrink(yoga::FloatOptional{1}); - } - style.setDimension( - yoga::Dimension::Width, yoga::StyleSizeLength::points(width)); - } - if (style != yogaNode_.style()) { - ensureUnsealed(); - yogaNode_.setStyle(style); - yogaNode_.setDirty(true); - } -} - -void NativeRootComponentDescriptor::adopt(ShadowNode& shadowNode) const { - static_cast(shadowNode).applyContentSize(); - ConcreteComponentDescriptor::adopt(shadowNode); -} -#endif - -#if RN_DEBUG_STRING_CONVERTIBLE -SharedDebugStringConvertibleList NativeRootProps::getDebugProps() const { - return ViewProps::getDebugProps() + SharedDebugStringConvertibleList{ - debugStringConvertibleItem("rootId", rootId), - debugStringConvertibleItem("hintHeight", hintHeight), - debugStringConvertibleItem("hintWidth", hintWidth), - debugStringConvertibleItem("hintMinWidth", hintMinWidth), - }; -} -#endif - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/nativeroot/NativeRoot.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/nativeroot/NativeRoot.h deleted file mode 100644 index 05a90b9fe9..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/nativeroot/NativeRoot.h +++ /dev/null @@ -1,87 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -// Hand-written like `shortcutscope/ShortcutScope.h`: core has no component -// codegen. The component is a box whose content is a native tree: the nested -// components a second React reconciler describes, built natively without a -// Fabric node each. Its one prop names the tree. -namespace facebook::react { - -extern const char NativeRootComponentName[]; - -class NativeRootProps final : public ViewProps { - public: - NativeRootProps() = default; - NativeRootProps( - const PropsParserContext& context, - const NativeRootProps& sourceProps, - const RawProps& rawProps); - - /// The id of the native tree this node shows. Zero shows nothing. - int rootId{0}; - - /// A size remembered from an earlier tree like this one, which a box takes - /// until the runtime reports the real one. Negative for none. - float hintHeight{-1}; - float hintWidth{-1}; - float hintMinWidth{-1}; - -#ifdef RN_SERIALIZABLE_STATE - ComponentName getDiffPropsImplementationTarget() const override; - folly::dynamic getDiffProps(const Props* prevProps) const override; -#endif - -#if RN_DEBUG_STRING_CONVERTIBLE - SharedDebugStringConvertibleList getDebugProps() const override; -#endif -}; - -/// The size of the content the runtime laid out on the main thread. A box -/// without a height (or, with `fitWidth`, a width) of its own takes it as its -/// size. -struct NativeRootState { - float height{0}; - bool hasHeight{false}; - float width{0}; - float minWidth{0}; - bool hasWidth{false}; -}; - -#if defined(LOOM_RENDERER) && LOOM_RENDERER -// Loom lays the box out from its props; the runtime writes the measured size -// through Loom's native props lane instead of a state. -using NativeRootShadowNode = - ConcreteViewShadowNode; -using NativeRootComponentDescriptor = - ConcreteComponentDescriptor; -#else -class NativeRootShadowNode final : public ConcreteViewShadowNode< - NativeRootComponentName, - NativeRootProps, - ViewEventEmitter, - NativeRootState> { - public: - using ConcreteViewShadowNode::ConcreteViewShadowNode; - - /// Applies the reported size to Yoga's style where the props leave the - /// dimension open. Props set a style anew on every change, so this runs on - /// every clone. - void applyContentSize(); -}; - -class NativeRootComponentDescriptor final - : public ConcreteComponentDescriptor { - public: - using ConcreteComponentDescriptor::ConcreteComponentDescriptor; - - void adopt(ShadowNode& shadowNode) const override; -}; -#endif - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/nativeslot/NativeSlot.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/nativeslot/NativeSlot.cpp deleted file mode 100644 index d637dcdfe0..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/nativeslot/NativeSlot.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include "NativeSlot.h" - -#include -#include -#include -#include - -namespace facebook::react { - -const char NativeSlotComponentName[] = "DesktopNativeSlot"; - -NativeSlotProps::NativeSlotProps( - const PropsParserContext& context, - const NativeSlotProps& sourceProps, - const RawProps& rawProps) - : ViewProps(context, sourceProps, rawProps), - rootId(convertRawProp( - context, - rawProps, - "rootId", - sourceProps.rootId, - 0)), - slotId(convertRawProp( - context, - rawProps, - "slotId", - sourceProps.slotId, - 0)) {} - -#ifdef RN_SERIALIZABLE_STATE -ComponentName NativeSlotProps::getDiffPropsImplementationTarget() const { - return NativeSlotComponentName; -} - -folly::dynamic NativeSlotProps::getDiffProps(const Props* prevProps) const { - static const auto defaultProps = NativeSlotProps(); - const auto* oldProps = prevProps == nullptr - ? &defaultProps - : static_cast(prevProps); - if (this == oldProps) { - return folly::dynamic::object(); - } - - folly::dynamic result = ViewProps::getDiffProps(prevProps); - if (rootId != oldProps->rootId) { - result["rootId"] = rootId; - } - if (slotId != oldProps->slotId) { - result["slotId"] = slotId; - } - return result; -} -#endif - -#if !(defined(LOOM_RENDERER) && LOOM_RENDERER) -void NativeSlotShadowNode::applySlotSize() { - const auto& data = getStateData(); - const auto& base = getConcreteProps().yogaStyle; - auto style = yogaNode_.style(); - const auto open = [&](yoga::Dimension axis) { - const auto size = base.dimension(axis); - return size.isUndefined() || size.isAuto(); - }; - if (data.hasWidth && open(yoga::Dimension::Width)) { - style.setDimension( - yoga::Dimension::Width, yoga::StyleSizeLength::points(data.width)); - } - if (data.hasHeight && open(yoga::Dimension::Height)) { - style.setDimension( - yoga::Dimension::Height, yoga::StyleSizeLength::points(data.height)); - } - if (style != yogaNode_.style()) { - ensureUnsealed(); - yogaNode_.setStyle(style); - yogaNode_.setDirty(true); - } -} - -void NativeSlotComponentDescriptor::adopt(ShadowNode& shadowNode) const { - static_cast(shadowNode).applySlotSize(); - ConcreteComponentDescriptor::adopt(shadowNode); -} -#endif - -#if RN_DEBUG_STRING_CONVERTIBLE -SharedDebugStringConvertibleList NativeSlotProps::getDebugProps() const { - return ViewProps::getDebugProps() + SharedDebugStringConvertibleList{ - debugStringConvertibleItem("rootId", rootId), - debugStringConvertibleItem("slotId", slotId), - }; -} -#endif - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/nativeslot/NativeSlot.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/nativeslot/NativeSlot.h deleted file mode 100644 index 9c1b86c372..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/nativeslot/NativeSlot.h +++ /dev/null @@ -1,74 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -// Hand-written like `shortcutscope/ShortcutScope.h`: core has no component -// codegen. The component holds React Native children for a place in a native -// tree: the native side paints it where the placeholder of the same slot is. -namespace facebook::react { - -extern const char NativeSlotComponentName[]; - -class NativeSlotProps final : public ViewProps { - public: - NativeSlotProps() = default; - NativeSlotProps( - const PropsParserContext& context, - const NativeSlotProps& sourceProps, - const RawProps& rawProps); - - /// The native tree this slot belongs to, and its id in that tree. - int rootId{0}; - int slotId{0}; - -#ifdef RN_SERIALIZABLE_STATE - ComponentName getDiffPropsImplementationTarget() const override; - folly::dynamic getDiffProps(const Props* prevProps) const override; -#endif - -#if RN_DEBUG_STRING_CONVERTIBLE - SharedDebugStringConvertibleList getDebugProps() const override; -#endif -}; - -/// The size the native layout gave the slot's placeholder. The content takes -/// its width, and with `fill` its height, where the style leaves them open. -struct NativeSlotState { - float width{0}; - bool hasWidth{false}; - float height{0}; - bool hasHeight{false}; -}; - -#if defined(LOOM_RENDERER) && LOOM_RENDERER -using NativeSlotShadowNode = - ConcreteViewShadowNode; -using NativeSlotComponentDescriptor = - ConcreteComponentDescriptor; -#else -class NativeSlotShadowNode final : public ConcreteViewShadowNode< - NativeSlotComponentName, - NativeSlotProps, - ViewEventEmitter, - NativeSlotState> { - public: - using ConcreteViewShadowNode::ConcreteViewShadowNode; - - void applySlotSize(); -}; - -class NativeSlotComponentDescriptor final - : public ConcreteComponentDescriptor { - public: - using ConcreteComponentDescriptor::ConcreteComponentDescriptor; - - void adopt(ShadowNode& shadowNode) const override; -}; -#endif - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/shortcutscope/ShortcutScope.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/shortcutscope/ShortcutScope.cpp deleted file mode 100644 index 51c54051cc..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/shortcutscope/ShortcutScope.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include "ShortcutScope.h" - -#include -#include -#include -#include - -namespace facebook::react { - -const char ShortcutScopeComponentName[] = "DesktopShortcutScope"; - -ShortcutScopeProps::ShortcutScopeProps( - const PropsParserContext& context, - const ShortcutScopeProps& sourceProps, - const RawProps& rawProps) - : ViewProps(context, sourceProps, rawProps), - name(convertRawProp( - context, - rawProps, - "name", - sourceProps.name, - std::string{})) {} - -#ifdef RN_SERIALIZABLE_STATE -ComponentName ShortcutScopeProps::getDiffPropsImplementationTarget() const { - return ShortcutScopeComponentName; -} - -folly::dynamic ShortcutScopeProps::getDiffProps(const Props* prevProps) const { - static const auto defaultProps = ShortcutScopeProps(); - const auto* oldProps = prevProps == nullptr - ? &defaultProps - : static_cast(prevProps); - if (this == oldProps) { - return folly::dynamic::object(); - } - - folly::dynamic result = ViewProps::getDiffProps(prevProps); - // A renamed scope is a different scope: every shortcut registered with - // `when: ` stops matching, so the rename has to reach the renderer. - if (name != oldProps->name) { - result["name"] = name; - } - return result; -} -#endif - -#if RN_DEBUG_STRING_CONVERTIBLE -SharedDebugStringConvertibleList ShortcutScopeProps::getDebugProps() const { - return ViewProps::getDebugProps() + SharedDebugStringConvertibleList{ - debugStringConvertibleItem("name", name), - }; -} -#endif - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/shortcutscope/ShortcutScope.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/shortcutscope/ShortcutScope.h deleted file mode 100644 index 004c505694..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/shortcutscope/ShortcutScope.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include - -// Hand-written rather than generated: core has no component codegen, because -// autolink only runs it for dependencies and core is the runtime. This follows -// `windowcontrol/WindowControl.h` and -// `desktopcontextmenuview/DesktopContextMenuView.h`, core's other -// hand-registered components. -// -// The component is a plain box with a name. Everything it means is decided -// natively: the Rust renderer turns `name` into a keymap context, and GPUI's -// keymap does the precedence. So the props here are one string, and the rest of -// the behaviour lives in `rn-gpui/src/builtins/shortcut_scope`. -namespace facebook::react { - -extern const char ShortcutScopeComponentName[]; - -/// A named scope for keyboard shortcuts. Scopes nest; an inner scope's binding -/// outranks an outer one's. -class ShortcutScopeProps final : public ViewProps { - public: - ShortcutScopeProps() = default; - ShortcutScopeProps( - const PropsParserContext& context, - const ShortcutScopeProps& sourceProps, - const RawProps& rawProps); - - /// The name a `useShortcut`'s `when` refers to. Empty claims no context. - std::string name{}; - -#ifdef RN_SERIALIZABLE_STATE - ComponentName getDiffPropsImplementationTarget() const override; - folly::dynamic getDiffProps(const Props* prevProps) const override; -#endif - -#if RN_DEBUG_STRING_CONVERTIBLE - SharedDebugStringConvertibleList getDebugProps() const override; -#endif -}; - -using ShortcutScopeShadowNode = ConcreteViewShadowNode< - ShortcutScopeComponentName, - ShortcutScopeProps, - ViewEventEmitter>; -using ShortcutScopeComponentDescriptor = - ConcreteComponentDescriptor; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/windowcontrol/WindowControl.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/windowcontrol/WindowControl.cpp deleted file mode 100644 index cdd029253e..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/windowcontrol/WindowControl.cpp +++ /dev/null @@ -1,75 +0,0 @@ -#include "WindowControl.h" - -#include -#include -#include -#include - -namespace facebook::react { - -const char WindowControlComponentName[] = "DesktopWindowControl"; - -namespace { - -WindowControlAction parseAction( - const PropsParserContext& context, - const RawProps& rawProps, - const std::string& fallback) { - const std::string action = convertRawProp( - context, rawProps, "action", fallback, std::string{"close"}); - if (action == "minimize") return WindowControlAction::Minimize; - if (action == "maximize") return WindowControlAction::Maximize; - return WindowControlAction::Close; -} - -const char* actionName(WindowControlAction action) { - switch (action) { - case WindowControlAction::Minimize: - return "minimize"; - case WindowControlAction::Maximize: - return "maximize"; - default: - return "close"; - } -} - -} // namespace - -WindowControlProps::WindowControlProps( - const PropsParserContext& context, - const WindowControlProps& sourceProps, - const RawProps& rawProps) - : ViewProps(context, sourceProps, rawProps), - action(parseAction(context, rawProps, actionName(sourceProps.action))), - disabled(convertRawProp( - context, rawProps, "disabled", sourceProps.disabled, false)) {} - -#ifdef RN_SERIALIZABLE_STATE -ComponentName WindowControlProps::getDiffPropsImplementationTarget() const { - return "DesktopWindowControl"; -} - -folly::dynamic WindowControlProps::getDiffProps(const Props* prevProps) const { - static const auto defaultProps = WindowControlProps(); - const auto* oldProps = prevProps == nullptr - ? &defaultProps - : static_cast(prevProps); - if (this == oldProps) return folly::dynamic::object(); - - folly::dynamic result = ViewProps::getDiffProps(prevProps); - if (action != oldProps->action) result["action"] = actionName(action); - if (disabled != oldProps->disabled) result["disabled"] = disabled; - return result; -} -#endif - -#if RN_DEBUG_STRING_CONVERTIBLE -SharedDebugStringConvertibleList WindowControlProps::getDebugProps() const { - return ViewProps::getDebugProps() + SharedDebugStringConvertibleList{ - debugStringConvertibleItem("action", std::string(actionName(action))), - debugStringConvertibleItem("disabled", disabled), - }; -} -#endif - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/windowcontrol/WindowControl.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/windowcontrol/WindowControl.h deleted file mode 100644 index 800947f312..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/components/windowcontrol/WindowControl.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -// Hand-written rather than generated: core has no component codegen, because -// autolink only runs it for dependencies and core is the runtime. -namespace facebook::react { - -extern const char WindowControlComponentName[]; - -/// The action a caption button performs. -enum class WindowControlAction { - Minimize, - Maximize, - Close, -}; - -class WindowControlProps final : public ViewProps { - public: - WindowControlProps() = default; - WindowControlProps( - const PropsParserContext& context, - const WindowControlProps& sourceProps, - const RawProps& rawProps); - - WindowControlAction action{WindowControlAction::Close}; - bool disabled{false}; - -#ifdef RN_SERIALIZABLE_STATE - ComponentName getDiffPropsImplementationTarget() const override; - folly::dynamic getDiffProps(const Props* prevProps) const override; -#endif - -#if RN_DEBUG_STRING_CONVERTIBLE - SharedDebugStringConvertibleList getDebugProps() const override; -#endif -}; - -using WindowControlShadowNode = ConcreteViewShadowNode< - WindowControlComponentName, - WindowControlProps, - ViewEventEmitter>; -using WindowControlComponentDescriptor = - ConcreteComponentDescriptor; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/scheduler/CMakeLists.txt b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/scheduler/CMakeLists.txt deleted file mode 100644 index 0f47b39da8..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/scheduler/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -include(${REACT_COMMON_DIR}/cmake-utils/react-native-flags.cmake) - -file(GLOB react_cxx_platform_react_renderer_scheduler_SRC CONFIGURE_DEPENDS *.cpp) -add_library(react_cxx_platform_react_renderer_scheduler OBJECT ${react_cxx_platform_react_renderer_scheduler_SRC}) - -target_include_directories(react_cxx_platform_react_renderer_scheduler PUBLIC ${REACT_CXX_PLATFORM_DIR}) - -target_link_libraries(react_cxx_platform_react_renderer_scheduler - react_renderer_mounting - react_renderer_scheduler - react_cxx_platform_react_renderer_uimanager -) -target_compile_reactnative_options(react_cxx_platform_react_renderer_scheduler PRIVATE) -target_compile_options(react_cxx_platform_react_renderer_scheduler PRIVATE -Wpedantic) diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/scheduler/SchedulerDelegateImpl.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/scheduler/SchedulerDelegateImpl.cpp deleted file mode 100644 index ebf5669b87..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/scheduler/SchedulerDelegateImpl.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "SchedulerDelegateImpl.h" -#include - -namespace facebook::react { - -SchedulerDelegateImpl::SchedulerDelegateImpl( - std::shared_ptr mountingManager) noexcept - : mountingManager_(std::move(mountingManager)) {} - -void SchedulerDelegateImpl::setUIManager( - std::shared_ptr uiManager) noexcept { - uiManager_ = uiManager; -} - -void SchedulerDelegateImpl::schedulerDidFinishTransaction( - const std::shared_ptr& /*mountingCoordinator*/) { - // no-op, we will flush the transaction from schedulerShouldRenderTransactions -} - -void SchedulerDelegateImpl::schedulerShouldRenderTransactions( - const std::shared_ptr& mountingCoordinator) { - auto surfaceId = mountingCoordinator->getSurfaceId(); - if (auto transaction = mountingCoordinator->pullTransaction(); - transaction.has_value()) { - if (auto& transactionValue = transaction.value(); - !transactionValue.getMutations().empty()) { - mountingManager_->executeMount(surfaceId, std::move(transactionValue)); - } - } -} - -void SchedulerDelegateImpl::schedulerShouldMergeReactRevision( - SurfaceId surfaceId) { - uiManager_->getShadowTreeRegistry().visit( - surfaceId, - [](const ShadowTree& shadowTree) { shadowTree.mergeReactRevision(); }); -} - -void SchedulerDelegateImpl::schedulerDidRequestPreliminaryViewAllocation( - const ShadowNode& shadowNode) {} - -void SchedulerDelegateImpl::schedulerDidDispatchCommand( - const ShadowView& shadowView, - const std::string& commandName, - const folly::dynamic& args) { - mountingManager_->dispatchCommand(shadowView, commandName, args); -} - -void SchedulerDelegateImpl::schedulerDidSetIsJSResponder( - const ShadowView& shadowView, - bool isJSResponder, - bool blockNativeResponder) { - mountingManager_->setIsJSResponder( - shadowView, isJSResponder, blockNativeResponder); -} - -void SchedulerDelegateImpl::schedulerDidSendAccessibilityEvent( - const ShadowView& shadowView, - const std::string& eventType) { - if (eventType == "focus") { - mountingManager_->setAccessibilityFocusedView(shadowView.tag); - } else if (eventType == "click") { - mountingManager_->accessibleClickAction(shadowView.tag); - } -} - -void SchedulerDelegateImpl::schedulerShouldSynchronouslyUpdateViewOnUIThread( - Tag tag, - const folly::dynamic& props) { - mountingManager_->synchronouslyUpdateViewOnUIThread(tag, props); -} - -void SchedulerDelegateImpl::schedulerDidUpdateShadowTree( - const std::unordered_map& tagToProps) { - mountingManager_->onUpdateShadowTree(tagToProps); -} - -void SchedulerDelegateImpl::schedulerDidCaptureViewSnapshot( - Tag /*tag*/, - SurfaceId /*surfaceId*/) {} - -void SchedulerDelegateImpl::schedulerDidSetViewSnapshot( - Tag /*sourceTag*/, - Tag /*targetTag*/, - SurfaceId /*surfaceId*/) {} - -void SchedulerDelegateImpl::schedulerDidClearPendingSnapshots() {} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/scheduler/SchedulerDelegateImpl.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/scheduler/SchedulerDelegateImpl.h deleted file mode 100644 index 089b64d573..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/scheduler/SchedulerDelegateImpl.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include - -namespace facebook::react { - -class IMountingManager; - -class SchedulerDelegateImpl : public SchedulerDelegate { - public: - SchedulerDelegateImpl(std::shared_ptr mountingManager) noexcept; - - ~SchedulerDelegateImpl() noexcept override = default; - - SchedulerDelegateImpl(SchedulerDelegateImpl &&) noexcept = default; - SchedulerDelegateImpl &operator=(SchedulerDelegateImpl &&) noexcept = default; - SchedulerDelegateImpl(const SchedulerDelegateImpl &) = delete; - SchedulerDelegateImpl &operator=(const SchedulerDelegateImpl &) = delete; - - void setUIManager(std::shared_ptr uiManager) noexcept; - - private: - void schedulerDidFinishTransaction(const std::shared_ptr &mountingCoordinator) override; - - void schedulerShouldRenderTransactions( - const std::shared_ptr &mountingCoordinator) override; - - void schedulerShouldMergeReactRevision(SurfaceId surfaceId) override; - - void schedulerDidRequestPreliminaryViewAllocation(const ShadowNode &shadowNode) override; - - void schedulerDidDispatchCommand( - const ShadowView &shadowView, - const std::string &commandName, - const folly::dynamic &args) override; - - void schedulerDidSetIsJSResponder(const ShadowView &shadowView, bool isJSResponder, bool blockNativeResponder) - override; - - void schedulerDidSendAccessibilityEvent(const ShadowView &shadowView, const std::string &eventType) override; - - void schedulerShouldSynchronouslyUpdateViewOnUIThread(Tag tag, const folly::dynamic &props) override; - - void schedulerDidUpdateShadowTree(const std::unordered_map &tagToProps) override; - - void schedulerDidCaptureViewSnapshot(Tag tag, SurfaceId surfaceId) override; - - void schedulerDidSetViewSnapshot(Tag sourceTag, Tag targetTag, SurfaceId surfaceId) override; - - void schedulerDidClearPendingSnapshots() override; - - std::shared_ptr mountingManager_; - std::shared_ptr uiManager_; -}; - -}; // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/scheduler/SurfaceDelegate.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/scheduler/SurfaceDelegate.h deleted file mode 100644 index 8797e67948..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/scheduler/SurfaceDelegate.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include - -namespace facebook::react { -/** - * Interface for handling a surface in React Native. Each platform can have - * custom logic to show/hide. - * Inspired by - * xplat/js/react-native-github/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/SurfaceDelegate.java - */ -class SurfaceDelegate { - public: - virtual ~SurfaceDelegate() = default; - - /** - * Create the React content view that uses the appKey as the React application - * name - */ - virtual void createContentView(std::string appKey) = 0; - - /** - * Check if the content view is created and ready to be shown - */ - virtual bool isContentViewReady() = 0; - - /** Destroy the React content view to avoid memory leak */ - virtual void destroyContentView() = 0; - - /** Show the surface containing the React content view */ - virtual void show() = 0; - - /** Hide the surface containing the React content view */ - virtual void hide() = 0; - - /** Check if the surface is currently showing */ - virtual bool isShowing() = 0; -}; -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/uimanager/CMakeLists.txt b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/uimanager/CMakeLists.txt deleted file mode 100644 index 929954e700..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/uimanager/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -include(${REACT_COMMON_DIR}/cmake-utils/react-native-flags.cmake) - -add_library(react_cxx_platform_react_renderer_uimanager INTERFACE) - -target_include_directories(react_cxx_platform_react_renderer_uimanager INTERFACE ${REACT_CXX_PLATFORM_DIR}) - -target_link_libraries(react_cxx_platform_react_renderer_uimanager INTERFACE - react_renderer_core - react_renderer_componentregistry - react_renderer_mounting -) -target_compile_reactnative_options(react_cxx_platform_react_renderer_uimanager INTERFACE) -target_compile_options(react_cxx_platform_react_renderer_uimanager INTERFACE -Wpedantic) diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/uimanager/IMountingManager.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/uimanager/IMountingManager.h deleted file mode 100644 index b68da46f54..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/renderer/uimanager/IMountingManager.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include - -namespace facebook::react { - -class Scheduler; -class UIManager; -class IImageLoader; - -using SchedulerTask = std::function; -using SchedulerTaskExecutor = std::function; - -using EventEmitterListener = - std::function; - -class IMountingManager { - public: - IMountingManager() noexcept = default; - - virtual ~IMountingManager() noexcept = default; - - IMountingManager(IMountingManager &&) noexcept = default; - IMountingManager &operator=(IMountingManager &&) noexcept = default; - IMountingManager(const IMountingManager &) = delete; - IMountingManager &operator=(const IMountingManager &) = delete; - - virtual void executeMount(SurfaceId surfaceId, MountingTransaction &&mountingTransaction) = 0; - - virtual void - dispatchCommand(const ShadowView &shadowView, const std::string &commandName, const folly::dynamic &args) = 0; - - virtual void - setIsJSResponder(const ShadowView & /* shadowView */, bool /* isJSResponder */, bool /* blockNativeResponder */) - { - } - - virtual void synchronouslyUpdateViewOnUIThread(Tag /* reactTag */, const folly::dynamic & /* changedProps */) {} - - virtual void onUpdateShadowTree(const std::unordered_map & /* tagToProps */) {} - - virtual void initializeAccessibilityManager() {} - - virtual void setAccessibilityFocusedView(Tag /* viewTag */) {} - - virtual void setFocusedView(Tag /* viewTag */) {} - - virtual void clearAccessibilityFocusedView(Tag /* viewTag */) {} - - virtual void accessibleClickAction(Tag /* viewTag */) {} - - virtual void accessibleScrollInDirection(Tag /* viewTag */, int /* direction */) {} - - virtual void accessibleSetText(Tag /* viewTag */, const std::string & /* text */) {} - - virtual void clearFocusedView(Tag /* viewTag */) {} - - virtual void setAfterMountCallback(std::function && /* onAfterMount */) {} - - virtual ComponentRegistryFactory getComponentRegistryFactory() - { - return nullptr; - } - - virtual bool hasComponent(const std::string & /*name*/) - { - return false; - } - - virtual void setSchedulerTaskExecutor(SchedulerTaskExecutor && /* schedulerTaskExecutor */) noexcept {} - - virtual void setEventEmitterListener(std::shared_ptr /* listener */) noexcept {} - - virtual void setUIManager(std::weak_ptr /* uiManager */) noexcept {} - - virtual std::shared_ptr getImageLoader() noexcept - { - return nullptr; - } -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/CMakeLists.txt b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/CMakeLists.txt deleted file mode 100644 index ad9d5f94ff..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/CMakeLists.txt +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -include(${REACT_COMMON_DIR}/cmake-utils/react-native-flags.cmake) - -file(GLOB react_cxx_platform_react_runtime_SRC CONFIGURE_DEPENDS *.cpp) -add_library(react_cxx_platform_react_runtime OBJECT ${react_cxx_platform_react_runtime_SRC}) - -target_include_directories(react_cxx_platform_react_runtime - PUBLIC - ${REACT_CXX_PLATFORM_DIR}) - -target_link_libraries(react_cxx_platform_react_runtime - bridgeless - callinvoker - glog - jserrorhandler - jsinspector - react_codegen_rncore - react_cxx_platform_react_coremodules - react_cxx_platform_react_devsupport - react_cxx_platform_react_devsupport - react_cxx_platform_react_http - react_cxx_platform_react_io - react_cxx_platform_react_logging - react_cxx_platform_react_nativemodule - react_renderer_animated - react_renderer_animationbackend - react_cxx_platform_react_renderer_uimanager - react_cxx_platform_react_threading - react_cxx_platform_react_utils - react_cxxreact - react_debug - react_nativemodule_core - react_nativemodule_defaults - react_nativemodule_intersectionobserver - react_nativemodule_mutationobserver - react_nativemodule_webperformance - react_renderer_graphics - react_renderer_runtimescheduler - react_renderer_scheduler - rrc_native - rrc_view -) -target_compile_reactnative_options(react_cxx_platform_react_runtime PRIVATE) -target_compile_options(react_cxx_platform_react_runtime PRIVATE -Wpedantic -Wno-deprecated-declarations) diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/GpuiDebug.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/GpuiDebug.h deleted file mode 100644 index 8eaa9fcc60..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/GpuiDebug.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -namespace facebook::react { - -inline bool gpuiDebugAnimationEnabled() noexcept { - static const bool enabled = std::getenv("RN_GPUI_DEBUG_ANIMATION") != nullptr; - return enabled; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/PlatformTimerRegistryImpl.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/PlatformTimerRegistryImpl.cpp deleted file mode 100644 index cb457b8d83..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/PlatformTimerRegistryImpl.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "PlatformTimerRegistryImpl.h" - -#include -#include -#include -#include - -namespace facebook::react { - -std::mutex PlatformTimerRegistryImpl::registriesMutex_; -std::unordered_set PlatformTimerRegistryImpl::registries_; - -PlatformTimerRegistryImpl::PlatformTimerRegistryImpl() noexcept { - std::lock_guard guard(registriesMutex_); - registries_.insert(this); -} - -PlatformTimerRegistryImpl::~PlatformTimerRegistryImpl() noexcept { - quit(); - std::lock_guard guard(registriesMutex_); - registries_.erase(this); -} - -uint64_t PlatformTimerRegistryImpl::pendingDueWithin(uint64_t windowMs) noexcept { - const auto limit = std::chrono::steady_clock::now() + - std::chrono::milliseconds(windowMs); - std::lock_guard registriesGuard( - PlatformTimerRegistryImpl::registriesMutex_); - uint64_t count = 0; - for (auto* registry : PlatformTimerRegistryImpl::registries_) { - std::lock_guard timersGuard(registry->timersMutex_); - for (const auto& [id, timer] : registry->timers_) { - (void)id; - if (!timer.isRecurring && timer.due <= limit) ++count; - } - } - return count; -} - -uint64_t PlatformTimerRegistryImpl::pendingDump( - uint64_t windowMs, - char* buffer, - uint64_t capacity) noexcept { - const auto now = std::chrono::steady_clock::now(); - const auto limit = now + std::chrono::milliseconds(windowMs); - std::string text; - std::lock_guard registriesGuard( - PlatformTimerRegistryImpl::registriesMutex_); - for (auto* registry : PlatformTimerRegistryImpl::registries_) { - std::lock_guard timersGuard(registry->timersMutex_); - for (const auto& [id, timer] : registry->timers_) { - if (timer.isRecurring || timer.due > limit) continue; - const auto remaining = - std::chrono::duration_cast(timer.due - now) - .count(); - text += "timer " + std::to_string(id) + ": set for " + - std::to_string(static_cast(timer.durationMs)) + " ms, due in " + - std::to_string(static_cast(remaining)) + " ms\n"; - } - } - const uint64_t length = std::min(text.size(), capacity); - std::copy_n(text.data(), length, buffer); - return length; -} - -extern "C" uint64_t rn_gpui_pending_timers_dump( - uint64_t windowMs, - char* buffer, - uint64_t capacity) noexcept { - return PlatformTimerRegistryImpl::pendingDump(windowMs, buffer, capacity); -} - -extern "C" uint64_t rn_gpui_pending_timers_due_within( - uint64_t windowMs) noexcept { - return PlatformTimerRegistryImpl::pendingDueWithin(windowMs); -} - -void PlatformTimerRegistryImpl::quit() { - LOG(INFO) << "Shutting down PlatformTimerRegistryImpl..."; - taskDispatchThread_.quit(); - std::lock_guard guard(timersMutex_); - timers_.clear(); -} - -void PlatformTimerRegistryImpl::createTimer(uint32_t timerId, double delayMs) { - createTimerInternal(timerId, delayMs, false); -} - -void PlatformTimerRegistryImpl::deleteTimer(uint32_t timerId) { - std::lock_guard guard(timersMutex_); - if (auto it = timers_.find(timerId); it != timers_.end()) { - timers_.erase(it); - } -} - -void PlatformTimerRegistryImpl::createRecurringTimer( - uint32_t timerId, - double delayMs) { - createTimerInternal(timerId, delayMs, true); -} - -void PlatformTimerRegistryImpl::createTimerInternal( - uint32_t timerId, - double delayMs, - bool recurring) { - { - std::lock_guard guard(timersMutex_); - timers_.emplace( - timerId, - Timer{ - .timerId = timerId, - .durationMs = delayMs, - .isRecurring = recurring}); - } - startTimer(timerId, delayMs); -} - -void PlatformTimerRegistryImpl::startTimer(uint32_t timerId, double delayMs) { - // RN's generic TimerManager currently implements requestAnimationFrame as - // setTimeout(0). Re-arming that timer with a zero delay spins this worker and - // floods the JS runtime (observed at >70k Animated.Value updates/second), - // starving input and making transforms visibly janky. Pace sub-frame timers - // at 60 Hz; JS still receives the normal timer callback, but at a useful - // desktop frame cadence instead of an unbounded tight loop. - constexpr double kMinimumFrameTimerMs = 1000.0 / 60.0; - const auto scheduledDelayMs = std::max(delayMs, kMinimumFrameTimerMs); - { - std::lock_guard guard(timersMutex_); - if (auto it = timers_.find(timerId); it != timers_.end()) { - it->second.due = std::chrono::steady_clock::now() + - std::chrono::milliseconds(static_cast(scheduledDelayMs)); - } else { - return; - } - } - taskDispatchThread_.runAsync( - [this, timerId, delayMs]() { - bool isRecurring = true; - { - std::lock_guard guard(timersMutex_); - auto it = timers_.find(timerId); - if (it == timers_.end()) { - // timer was deleted before it could have been dispatched (at this - // iteration) - return; - } - if (!it->second.isRecurring) { - timers_.erase(it); - isRecurring = false; - } - } - - if (auto timerManagerStrong = timerManager_.lock()) { - timerManagerStrong->callTimer(timerId); - } - - if (isRecurring) { - startTimer(timerId, delayMs); - } - }, - std::chrono::milliseconds(static_cast(scheduledDelayMs))); -} - -void PlatformTimerRegistryImpl::setTimerManager( - std::weak_ptr timerManager) { - timerManager_ = timerManager; -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/PlatformTimerRegistryImpl.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/PlatformTimerRegistryImpl.h deleted file mode 100644 index f5710edb8b..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/PlatformTimerRegistryImpl.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -class PlatformTimerRegistryImpl : public PlatformTimerRegistry { - public: - PlatformTimerRegistryImpl() noexcept; - PlatformTimerRegistryImpl(const PlatformTimerRegistryImpl &) = delete; - PlatformTimerRegistryImpl(PlatformTimerRegistryImpl &&) = delete; - PlatformTimerRegistryImpl &operator=(const PlatformTimerRegistryImpl &) = delete; - PlatformTimerRegistryImpl &operator=(PlatformTimerRegistryImpl &&) = delete; - ~PlatformTimerRegistryImpl() noexcept override; - - void createTimer(uint32_t timerId, double delayMs) override; - - void deleteTimer(uint32_t timerId) override; - - void createRecurringTimer(uint32_t timerID, double delayMs) override; - - void setTimerManager(std::weak_ptr timerManager) override; - - void quit() override; - static uint64_t pendingDueWithin(uint64_t windowMs) noexcept; - static uint64_t pendingDump( - uint64_t windowMs, - char* buffer, - uint64_t capacity) noexcept; - - private: - struct Timer { - uint32_t timerId{0}; - double durationMs{0.0}; - bool isRecurring{false}; - std::chrono::steady_clock::time_point due; - }; - - TaskDispatchThread taskDispatchThread_{"PlatformTimerRegistry"}; - std::weak_ptr timerManager_; - std::unordered_map timers_; - std::mutex timersMutex_; - - void createTimerInternal(uint32_t timerID, double delayMs, bool isRecurring = false); - - void startTimer(uint32_t timerId, double delayMs); - static std::mutex registriesMutex_; - static std::unordered_set registries_; -}; - -extern "C" uint64_t rn_gpui_pending_timers_due_within(uint64_t windowMs) noexcept; -extern "C" uint64_t rn_gpui_pending_timers_dump( - uint64_t windowMs, - char* buffer, - uint64_t capacity) noexcept; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactCxxTurboModuleProvider.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactCxxTurboModuleProvider.cpp deleted file mode 100644 index c8c778be80..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactCxxTurboModuleProvider.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "ReactCxxTurboModuleProvider.h" -#include "GpuiDebug.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace facebook::react; - -ReactCxxTurboModuleProvider::ReactCxxTurboModuleProvider( - TurboModuleProviders turboModuleProviders, - std::shared_ptr jsInvoker, - JsErrorHandler::OnJsError onJsError, - std::shared_ptr - animatedNodesManagerProvider, - std::shared_ptr devServerHelper, - std::shared_ptr devUIDelegate, - std::shared_ptr logBoxSurfaceDelegate, - HttpClientFactory httpClientFactory, - WebSocketClientFactory webSocketClientFactory, - std::function liveReloadCallback, - std::shared_ptr sourceURL, - std::weak_ptr imageLoader) - : turboModuleProviders_(std::move(turboModuleProviders)), - jsInvoker_(std::move(jsInvoker)), - onJsError_(std::move(onJsError)), - animatedNodesManagerProvider_(std::move(animatedNodesManagerProvider)), - devServerHelper_(std::move(devServerHelper)), - devUIDelegate_(std::move(devUIDelegate)), - logBoxSurfaceDelegate_(std::move(logBoxSurfaceDelegate)), - httpClientFactory_(std::move(httpClientFactory)), - webSocketClientFactory_(std::move(webSocketClientFactory)), - liveReloadCallback_(std::move(liveReloadCallback)), - sourceURL_(std::move(sourceURL)), - imageLoader_(std::move(imageLoader)), - modules_(std::make_shared< - std::unordered_map>>()) {} - -std::shared_ptr ReactCxxTurboModuleProvider::operator()( - const std::string& name) const { - react_native_assert(!name.empty() && "TurboModule name must not be empty"); - - // JS looks a module up by name every time it asks for it, and the binding - // leaves caching to the manager, as the iOS and Android ones do. A module - // built again on each lookup would destroy the state its other instances - // share when the extra one goes. - if (auto cached = modules_->find(name); cached != modules_->end()) { - return cached->second; - } - auto turboModule = create(name); - if (turboModule) { - modules_->emplace(name, turboModule); - } - return turboModule; -} - -std::shared_ptr ReactCxxTurboModuleProvider::create( - const std::string& name) const { - - for (const auto& turboModuleProvider : turboModuleProviders_) { - if (turboModuleProvider) { - if (auto turboModule = turboModuleProvider(name, jsInvoker_)) { - return turboModule; - } - } - } - - if (animatedNodesManagerProvider_ != nullptr && - name == AnimatedModule::kModuleName) { - if (gpuiDebugAnimationEnabled()) { - LOG(INFO) << "[native-animated] NativeAnimatedModule requested"; - } - // when animatedNodesManagerProvider_ is null, defer to default - return std::make_shared( - jsInvoker_, animatedNodesManagerProvider_); - } else if (name == AppStateModule::kModuleName) { - return std::make_shared(jsInvoker_); - } else if (name == DeviceInfoModule::kModuleName) { - return std::make_shared(jsInvoker_); - } else if ( - devUIDelegate_ != nullptr && name == DevLoadingViewModule::kModuleName) { - return std::make_shared(jsInvoker_, devUIDelegate_); - } else if (devServerHelper_ && name == DevSettingsModule::kModuleName) { - return std::make_shared( - jsInvoker_, devServerHelper_, liveReloadCallback_); - } else if (name == PlatformConstantsModule::kModuleName) { - return std::make_shared(jsInvoker_); - } else if (name == ImageLoaderModule::kModuleName) { - return std::make_shared(jsInvoker_, imageLoader_); - } else if (name == SourceCodeModule::kModuleName) { - return std::make_shared( - jsInvoker_, sourceURL_ ? *sourceURL_ : ""); - } else if (name == WebSocketModule::kModuleName) { - return std::make_shared( - jsInvoker_, webSocketClientFactory_); - } else if (name == NativeExceptionsManager::kModuleName) { - return std::make_shared(onJsError_, jsInvoker_); - } else if (name == NativeIntersectionObserver::kModuleName) { - return std::make_shared(jsInvoker_); - } else if (name == NativeMutationObserver::kModuleName) { - return std::make_shared(jsInvoker_); - } else if (name == NetworkingModule::kModuleName) { - return std::make_shared(jsInvoker_, httpClientFactory_); - } else if (name == BlobModule::kModuleName) { - return std::make_shared(jsInvoker_); - } else if (name == FileReaderModule::kModuleName) { - return std::make_shared(jsInvoker_); - } else if (name == LogBoxModule::kModuleName) { - if (logBoxSurfaceDelegate_) { - return std::make_shared(jsInvoker_, logBoxSurfaceDelegate_); - } - } - - if (auto turboModule = - DefaultTurboModules::getTurboModule(name, jsInvoker_)) { - return turboModule; - } - - LOG(WARNING) << "Failed to load TurboModule: " << name; - return nullptr; -} diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactCxxTurboModuleProvider.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactCxxTurboModuleProvider.h deleted file mode 100644 index 5911619755..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactCxxTurboModuleProvider.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace facebook::react { - -class CallInvoker; -class IImageLoader; -class DevServerHelper; -class NativeAnimatedNodesManagerProvider; -class SurfaceDelegate; -struct IDevUIDelegate; - -class ReactCxxTurboModuleProvider final { - public: - ReactCxxTurboModuleProvider( - TurboModuleProviders turboModuleProviders, - std::shared_ptr jsInvoker, - JsErrorHandler::OnJsError onJsError, - std::shared_ptr animatedNodesManagerProvider = nullptr, - std::shared_ptr devServerHelper = nullptr, - std::shared_ptr devUIDelegate = nullptr, - std::shared_ptr logBoxSurfaceDelegate = nullptr, - HttpClientFactory httpClientFactory = nullptr, - WebSocketClientFactory webSocketClientFactory = nullptr, - std::function liveReloadCallback = nullptr, - std::shared_ptr sourceURL = nullptr, - std::weak_ptr imageLoader = {}); - - std::shared_ptr operator()(const std::string &name) const; - - private: - std::shared_ptr create(const std::string &name) const; - - TurboModuleProviders turboModuleProviders_; - std::shared_ptr jsInvoker_; - JsErrorHandler::OnJsError onJsError_; - std::shared_ptr animatedNodesManagerProvider_; - std::shared_ptr devServerHelper_; - std::shared_ptr devUIDelegate_; - std::shared_ptr logBoxSurfaceDelegate_; - HttpClientFactory httpClientFactory_; - WebSocketClientFactory webSocketClientFactory_; - std::function liveReloadCallback_; - std::shared_ptr sourceURL_; - std::weak_ptr imageLoader_; - // Shared by the copies `std::function` makes of the provider, so each name - // has one instance per runtime. - std::shared_ptr>> modules_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactHost.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactHost.cpp deleted file mode 100644 index 735ce8a0e0..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactHost.cpp +++ /dev/null @@ -1,588 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "ReactHost.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "ReactCxxTurboModuleProvider.h" - -namespace facebook::react { -struct ReactInstanceData { - std::shared_ptr mountingManager; - std::shared_ptr messageQueueThread; - std::shared_ptr runLoopObserverManager; - std::shared_ptr contextContainer; - ComponentRegistryFactory componentRegistryFactory; - JsErrorHandler::OnJsError onJsError; - Logger logger; - std::shared_ptr devUIDelegate; - TurboModuleProviders turboModuleProviders; - std::shared_ptr logBoxSurfaceDelegate; - std::shared_ptr - animatedNodesManagerProvider; - ReactInstance::BindingsInstallFunc bindingsInstallFunc; - std::shared_ptr animationChoreographer; -}; - -ReactHost::ReactHost( - ReactInstanceConfig reactInstanceConfig, - std::shared_ptr mountingManager, - std::shared_ptr runLoopObserverManager, - std::shared_ptr contextContainer, - JsErrorHandler::OnJsError onJsError, - Logger logger, - std::shared_ptr devUIDelegate, - TurboModuleProviders turboModuleProviders, - std::shared_ptr logBoxSurfaceDelegate, - std::shared_ptr - animatedNodesManagerProvider, - ReactInstance::BindingsInstallFunc bindingsInstallFunc, - std::shared_ptr animationChoreographer) - : reactInstanceConfig_(std::move(reactInstanceConfig)) { - auto componentRegistryFactory = - mountingManager->getComponentRegistryFactory(); - reactInstanceData_ = std::make_unique(ReactInstanceData{ - .mountingManager = mountingManager, - .messageQueueThread = nullptr, - .runLoopObserverManager = runLoopObserverManager, - .contextContainer = std::move(contextContainer), - .componentRegistryFactory = std::move(componentRegistryFactory), - .onJsError = std::move(onJsError), - .logger = std::move(logger), - .devUIDelegate = devUIDelegate, - .turboModuleProviders = std::move(turboModuleProviders), - .logBoxSurfaceDelegate = logBoxSurfaceDelegate, - .animatedNodesManagerProvider = animatedNodesManagerProvider, - .bindingsInstallFunc = std::move(bindingsInstallFunc), - .animationChoreographer = std::move(animationChoreographer)}); - if (!reactInstanceData_->contextContainer - ->find(MessageQueueThreadFactoryKey) - .has_value()) { - reactInstanceData_->contextContainer->insert( - MessageQueueThreadFactoryKey, MessageQueueThreadFactory([]() { - return std::make_shared(); - })); - } - if (!reactInstanceData_->contextContainer - ->find(HttpClientFactoryKey) - .has_value()) { - throw std::runtime_error("No HttpClientFactory provided"); - } - if (!reactInstanceData_->contextContainer - ->find(WebSocketClientFactoryKey) - .has_value()) { - throw std::runtime_error("No WebSocketClientFactory provided"); - } - createReactInstance(); -} - -ReactHost::~ReactHost() noexcept { - destroyReactInstance(); -} - -void ReactHost::createReactInstance() { - // A new JS instance is coming up. Bumping the generation here — the one place - // both the first load and a reload pass through — is what lets a caller wait - // for *this* instance rather than infer it from an empty tree. The increment - // happens before any mount, so a tree observed afterwards belongs to this - // instance and cannot be the previous one's. - instanceGeneration_.fetch_add(1, std::memory_order_relaxed); - - if (reactInstanceConfig_.animatedNodesManagerProviderFactory) { - reactInstanceData_->animatedNodesManagerProvider = - reactInstanceConfig_.animatedNodesManagerProviderFactory(); - } - // Set up timers - std::unique_ptr platformTimers; - if (reactInstanceConfig_.platformTimerRegistryFactory) { - platformTimers = reactInstanceConfig_.platformTimerRegistryFactory(); - } else { - platformTimers = std::make_unique(); - } - auto* platformTimersPtr = platformTimers.get(); - auto timerManager = std::make_shared(std::move(platformTimers)); - platformTimersPtr->setTimerManager(timerManager); - - auto httpClientFactory = - reactInstanceData_->contextContainer->at( - HttpClientFactoryKey); - - auto webSocketClientFactory = - reactInstanceData_->contextContainer->at( - WebSocketClientFactoryKey); - - auto devToolsHttpClientFactory = - reactInstanceData_->contextContainer - ->find(DevToolsHttpClientFactoryKey) - .value_or(httpClientFactory); - - auto devToolsWebSocketClientFactory = - reactInstanceData_->contextContainer - ->find(DevToolsWebSocketClientFactoryKey) - .value_or(webSocketClientFactory); - - // Create devServerHelper - if (!devServerHelper_ && - (reactInstanceConfig_.enableInspector || - reactInstanceConfig_.enableDevMode)) { - devServerHelper_ = std::make_shared( - reactInstanceConfig_.appId, - reactInstanceConfig_.deviceName, - reactInstanceConfig_.devServerHost, - reactInstanceConfig_.devServerPort, - devToolsHttpClientFactory, - [this]( - const std::string& moduleName, - const std::string& methodName, - folly::dynamic&& args) { - reactInstance_->callFunctionOnModule( - moduleName, methodName, std::move(args)); - }); - } - - if (!inspector_ && reactInstanceConfig_.enableInspector) { - inspector_ = std::make_shared( - reactInstanceConfig_.appId, - reactInstanceConfig_.deviceName, - devToolsWebSocketClientFactory, - devToolsHttpClientFactory); - inspector_->ensureHostTarget( - [this]() { reloadReactInstance(); }, - [weakDevUIDelegate = - std::weak_ptr(reactInstanceData_->devUIDelegate)]( - bool showDebuggerOverlay, - std::function&& resumeDebuggerFn) { - if (auto debugUIDelegate = weakDevUIDelegate.lock()) { - if (showDebuggerOverlay) { - debugUIDelegate->showDebuggerOverlay(std::move(resumeDebuggerFn)); - } else { - debugUIDelegate->hideDebuggerOverlay(); - } - } - }); - } - - if (!packagerConnection_ && reactInstanceConfig_.enableDevMode) { - packagerConnection_ = std::make_unique( - devToolsWebSocketClientFactory, - devServerHelper_->getPackagerConnectionUrl(), - [this]() { reloadReactInstance(); }, - []() {}); - } - - // Create the React Instance - auto messageQueueThreadFactory = - reactInstanceData_->contextContainer->at( - MessageQueueThreadFactoryKey); - reactInstanceData_->messageQueueThread = messageQueueThreadFactory(); - if (reactInstanceConfig_.jsRuntimeFactory == nullptr) { - throw std::runtime_error("No JSRuntimeFactory provided"); - } - std::unique_ptr runtime = - reactInstanceConfig_.jsRuntimeFactory->createJSRuntime( - reactInstanceData_->messageQueueThread); - - if (reactInstanceConfig_.enableInspector) { - react_native_assert( - inspector_ != nullptr && "Inspector is not initialized"); - } - reactInstance_ = std::make_unique( - std::move(runtime), - reactInstanceData_->messageQueueThread, - timerManager, - reactInstanceData_->onJsError, - inspector_ != nullptr ? inspector_->inspectorTarget().get() : nullptr); - timerManager->setRuntimeExecutor( - reactInstance_->getBufferedRuntimeExecutor()); - reactInstanceData_->contextContainer->insert( - RuntimeSchedulerKey, - std::weak_ptr(reactInstance_->getRuntimeScheduler())); - - // Create scheduler - auto toolbox = SchedulerToolbox{}; - toolbox.contextContainer = reactInstanceData_->contextContainer; - toolbox.runtimeExecutor = reactInstance_->getBufferedRuntimeExecutor(); - toolbox.bridgelessBindingsExecutor = - reactInstance_->getUnbufferedRuntimeExecutor(); - toolbox.componentRegistryFactory = - reactInstanceData_->componentRegistryFactory; - toolbox.eventBeatFactory = - [runLoopObserverManager = reactInstanceData_->runLoopObserverManager, - runtimeScheduler = reactInstance_->getRuntimeScheduler()]( - std::shared_ptr ownerBox) { - return runLoopObserverManager->createEventBeat( - ownerBox, *runtimeScheduler); - }; - toolbox.animationChoreographer = reactInstanceData_->animationChoreographer; - - auto schedulerDelegate = std::make_unique( - reactInstanceData_->mountingManager); - scheduler_ = - std::make_unique(toolbox, nullptr, schedulerDelegate.get()); - - { - std::lock_guard lock(surfaceManagerMutex_); - surfaceManager_ = std::make_unique(*scheduler_); - } - schedulerDelegate->setUIManager(scheduler_->getUIManager()); - schedulerDelegate_ = std::move(schedulerDelegate); - - reactInstanceData_->mountingManager->setSchedulerTaskExecutor( - [this](SchedulerTask&& task) { runOnScheduler(std::move(task)); }); - - reactInstanceData_->mountingManager->setUIManager(scheduler_->getUIManager()); - - auto jsInvoker = std::make_shared( - reactInstance_->getRuntimeScheduler()); - - if (inspector_ != nullptr) { - inspector_->connectDebugger(devServerHelper_->getInspectorUrl()); - } - - auto liveReloadCallback = [this]() { reloadReactInstance(); }; - ReactCxxTurboModuleProvider turboModuleManager( - reactInstanceData_->turboModuleProviders, - jsInvoker, - reactInstanceData_->onJsError, - reactInstanceData_->animatedNodesManagerProvider, - reactInstanceConfig_.enableDevMode ? devServerHelper_ : nullptr, - reactInstanceData_->devUIDelegate, - reactInstanceData_->logBoxSurfaceDelegate, - httpClientFactory, - webSocketClientFactory, - std::move(liveReloadCallback), - sourceURL_, - reactInstanceData_->mountingManager->getImageLoader()); - - reactInstance_->initializeRuntime( - { -#if defined(WITH_PERFETTO) || defined(RNCXX_WITH_PROFILING_PROVIDER) - .isProfiling = true, -#else - .isProfiling = false, -#endif - .runtimeDiagnosticFlags = ""}, - [weakMountingManager = - std::weak_ptr(reactInstanceData_->mountingManager), - logger = reactInstanceData_->logger, - bindingsInstallFunc = reactInstanceData_->bindingsInstallFunc, - turboModuleManager = - std::move(turboModuleManager)](jsi::Runtime& runtime) mutable { - if (logger) { - bindNativeLogger(runtime, logger); - } - - // Set up component provider - bindHasComponentProvider( - runtime, [weakMountingManager](const std::string& name) -> bool { - if (auto strongMountingManager = weakMountingManager.lock()) { - return strongMountingManager->hasComponent(name); - } - return false; - }); - - // Set up TurboModules - TurboModuleBinding::install(runtime, std::move(turboModuleManager)); - - if (bindingsInstallFunc) { - bindingsInstallFunc(runtime); - } - }); -} - -void ReactHost::destroyReactInstance() { - if (reactInstanceConfig_.beforeInstanceDestroy) { - reactInstanceConfig_.beforeInstanceDestroy(); - } - if (inspector_ != nullptr) { - reactInstance_->unregisterFromInspector(); - } - std::unique_ptr surfaceManager; - { - std::lock_guard lock(surfaceManagerMutex_); - surfaceManager = std::move(surfaceManager_); - } - if (surfaceManager) { - surfaceManager->stopAllSurfaces(); - } - reactInstanceData_->messageQueueThread->quitSynchronous(); - surfaceManager = nullptr; - scheduler_ = nullptr; - schedulerDelegate_ = nullptr; - - reactInstanceData_->contextContainer->erase(RuntimeSchedulerKey); - reactInstanceData_->mountingManager->setSchedulerTaskExecutor(nullptr); - reactInstance_ = nullptr; - reactInstanceData_->messageQueueThread = nullptr; -} - -void ReactHost::reloadReactInstance() { - if (isReloadingReactInstance_.exchange(true)) { - return; - } - - std::thread([this]() { - folly::setThreadName("ReactReload"); - - std::vector surfaceProps; - for (auto& surfaceId : surfaceManager_->getRunningSurfaces()) { - if (auto surfaceProp = surfaceManager_->getSurfaceProps(surfaceId); - surfaceProp.has_value()) { - surfaceProps.emplace_back(*surfaceProp); - } - } - destroyReactInstance(); - { - std::optional> devServer; - { - std::lock_guard lock(pendingDevServerMutex_); - devServer.swap(pendingDevServer_); - } - if (devServer && devServerHelper_) { - // Both connections were opened to the old server and are kept across - // reloads; dropping them makes `createReactInstance` open new ones. - devServerHelper_->setDevServer(devServer->first, devServer->second); - packagerConnection_.reset(); - if (inspector_ != nullptr) { - inspector_->disconnectDebugger(); - } - } - } - createReactInstance(); - loadScript(lastBundlePath_, lastSourcePath_); - for (auto& surfaceProp : surfaceProps) { - { - std::lock_guard lock(surfaceManagerMutex_); - if (auto latest = latestConstraints_.find(surfaceProp.surfaceId); - latest != latestConstraints_.end()) { - surfaceProp.layoutConstraints = latest->second.first; - surfaceProp.layoutContext = latest->second.second; - } - } - startSurface( - surfaceProp.surfaceId, - surfaceProp.moduleName, - surfaceProp.props, - surfaceProp.layoutConstraints, - surfaceProp.layoutContext); - } - isReloadingReactInstance_ = false; - }).detach(); -} - -bool ReactHost::setDevServer(const std::string& host, uint32_t port) { - if (!devServerHelper_ || host.empty() || port == 0) { - return false; - } - { - std::lock_guard lock(pendingDevServerMutex_); - pendingDevServer_ = std::make_pair(host, port); - } - reloadReactInstance(); - return true; -} - -std::string ReactHost::devServerAddress() const { - if (!devServerHelper_) { - return ""; - } - return devServerHelper_->devServerHost() + ":" + - std::to_string(devServerHelper_->devServerPort()); -} - -bool ReactHost::loadScript( - const std::string& bundlePath, - const std::string& sourcePath) noexcept { - lastBundlePath_ = bundlePath; - lastSourcePath_ = sourcePath; - bool isLoaded = false; - if (reactInstanceConfig_.enableDevMode && devServerHelper_) { - devServerHelper_->setSourcePath(sourcePath); - isLoaded = loadScriptFromDevServer(); - } - if (!isLoaded) { - LOG(INFO) << "Devserver is not provided."; - isLoaded = loadScriptFromBundlePath(bundlePath); - } - return isLoaded; -} - -void ReactHost::openDebugger() { - if (inspector_ != nullptr && devServerHelper_ != nullptr) { - devServerHelper_->openDebugger(); - } -} - -bool ReactHost::loadScriptFromDevServer() { - try { - auto bundleUrl = devServerHelper_->getBundleUrl(); - auto response = - devServerHelper_ - ->downloadBundleResourceSync( - bundleUrl, - [weakDevUIDelegate = std::weak_ptr( - reactInstanceData_->devUIDelegate)]( - DevServerHelper::DownloadProgressStatus status) { - if (auto devUIDelegate = weakDevUIDelegate.lock()) { - if (status == - DevServerHelper::DownloadProgressStatus::STARTED) { - devUIDelegate->showDownloadBundleProgress(); - } else { - devUIDelegate->hideDownloadBundleProgress(); - } - } - }) - .get(); - auto script = std::make_unique(std::move(response)); - *sourceURL_ = bundleUrl; - reactInstance_->loadScript(std::move(script), bundleUrl); - devServerHelper_->setupHMRClient(); - return true; - } catch (const std::exception& error) { - // The reason is logged where it is known (no server, a failed request, or - // a response that is not a bundle); this says what happens next. - LOG(WARNING) << "Not using the dev server (" << error.what() - << "); loading the built-in JS bundle instead. Start Metro " - << "for this app to get live reload."; - return false; - } catch (...) { - LOG(WARNING) << "Not using the dev server; loading the built-in JS bundle " - << "instead. Start Metro for this app to get live reload."; - return false; - } -} - -bool ReactHost::loadScriptFromBundlePath(const std::string& bundlePath) { - try { - LOG(INFO) << "Loading JS bundle from bundle path: " << bundlePath; - auto script = ResourceLoader::getFileContents(bundlePath); - *sourceURL_ = ""; - reactInstance_->loadScript(std::move(script), bundlePath); - LOG(INFO) << "Loaded JS bundle from bundle path: " << bundlePath; - return true; - } catch (...) { - LOG(WARNING) << "Unable to read bundle from bundle path" << bundlePath; - return false; - } -} - -void ReactHost::startSurface( - SurfaceId surfaceId, - const std::string& moduleName, - const folly::dynamic& initialProps, - const LayoutConstraints& layoutConstraints, - const LayoutContext& layoutContext) noexcept { - surfaceManager_->startSurface( - surfaceId, moduleName, initialProps, layoutConstraints, layoutContext); -} - -void ReactHost::setSurfaceConstraints( - SurfaceId surfaceId, - const LayoutConstraints& layoutConstraints, - const LayoutContext& layoutContext) noexcept { - std::lock_guard lock(surfaceManagerMutex_); - latestConstraints_[surfaceId] = {layoutConstraints, layoutContext}; - if (surfaceManager_) { - surfaceManager_->constraintSurfaceLayout( - surfaceId, layoutConstraints, layoutContext); - } -} - -void ReactHost::stopSurface(SurfaceId surfaceId) noexcept { - std::lock_guard lock(surfaceManagerMutex_); - if (surfaceManager_) { - surfaceManager_->stopSurface(surfaceId); - } -} - -void ReactHost::stopAllSurfaces() noexcept { - std::lock_guard lock(surfaceManagerMutex_); - if (surfaceManager_) { - surfaceManager_->stopAllSurfaces(); - } -} - -bool ReactHost::isSurfaceRunning(SurfaceId surfaceId) const noexcept { - std::lock_guard lock(surfaceManagerMutex_); - return surfaceManager_ && surfaceManager_->isSurfaceRunning(surfaceId); -} - -std::unordered_set ReactHost::getRunningSurfaces() const noexcept { - std::lock_guard lock(surfaceManagerMutex_); - if (!surfaceManager_) { - return {}; - } - return surfaceManager_->getRunningSurfaces(); -} - -std::optional ReactHost::surfaceContentSize( - SurfaceId surfaceId) const { - if (isReloadingReactInstance_ || scheduler_ == nullptr) { - return std::nullopt; - } - const auto uiManager = scheduler_->getUIManager(); - if (uiManager == nullptr) { - return std::nullopt; - } - const auto root = - uiManager->getShadowTreeRevisionProvider()->getCurrentRevision(surfaceId); - if (root == nullptr) { - return std::nullopt; - } - const auto& frame = root->getLayoutMetrics().frame; - return Size{frame.size.width, frame.size.height}; -} - -void ReactHost::runOnScheduler( - std::function&& task) const { - if (!isReloadingReactInstance_) { - task(*scheduler_); - } -} - -void ReactHost::runOnRuntimeScheduler( - std::function&& task, - SchedulerPriority priority) const noexcept { - if (!isReloadingReactInstance_) { - reactInstance_->getRuntimeScheduler()->scheduleTask( - priority, std::move(task)); - } -} - -void ReactHost::emitDeviceEvent(folly::dynamic&& args) { - if (!isReloadingReactInstance_) { - reactInstance_->callFunctionOnModule( - "RCTDeviceEventEmitter", "emit", std::move(args)); - } -} -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactHost.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactHost.h deleted file mode 100644 index 018fe0c3dc..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactHost.h +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include "ReactInstanceConfig.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace facebook::react { -class AnimatedMountingOverrideDelegate; -class DevServerHelper; -class IMountingManager; -class Inspector; -class NativeAnimatedNodesManagerProvider; -class PackagerConnection; -class SchedulerDelegate; -class SurfaceDelegate; -class SurfaceManager; -struct IDevUIDelegate; -struct ReactInstanceData; - -class ReactHost { - public: - ReactHost( - ReactInstanceConfig reactInstanceConfig, - std::shared_ptr mountingManager, - std::shared_ptr runLoopObserverManager, - std::shared_ptr contextContainer, - JsErrorHandler::OnJsError onJsError, - Logger logger, - std::shared_ptr devUIDelegate = nullptr, - TurboModuleProviders turboModuleProviders = {}, - std::shared_ptr logBoxSurfaceDelegate = nullptr, - std::shared_ptr animatedNodesManagerProvider = nullptr, - ReactInstance::BindingsInstallFunc bindingsInstallFunc = nullptr, - std::shared_ptr animationChoreographer = nullptr); - ReactHost(const ReactHost &) = delete; - ReactHost &operator=(const ReactHost &) = delete; - ReactHost(ReactHost &&) noexcept = delete; - ReactHost &operator=(ReactHost &&) noexcept = delete; - ~ReactHost() noexcept; - - bool loadScript(const std::string &bundlePath, const std::string &sourcePath) noexcept; - - void openDebugger(); - void requestReload() { reloadReactInstance(); } - bool isReloading() const { return isReloadingReactInstance_.load(); } - - /// Monotonic count of the React instances this host has created, starting at - /// 1 for the first. A reload destroys the old instance and creates a new one, - /// so a test can tell "the tree is empty because the old instance is being - /// torn down" from "the tree is empty because the new one has not mounted - /// yet" by watching this change, instead of inferring it from an empty tree. - uint64_t instanceGeneration() const { - return instanceGeneration_.load(std::memory_order_relaxed); - } - - void startSurface( - SurfaceId surfaceId, - const std::string &moduleName /* can be empty */, - const folly::dynamic &initialProps, - const LayoutConstraints &layoutConstraints, - const LayoutContext &layoutContext = {}) noexcept; - - void setSurfaceConstraints( - SurfaceId surfaceId, - const LayoutConstraints &layoutConstraints, - const LayoutContext &layoutContext) noexcept; - - void stopSurface(SurfaceId surfaceId) noexcept; - - void stopAllSurfaces() noexcept; - - bool isSurfaceRunning(SurfaceId surfaceId) const noexcept; - - std::unordered_set getRunningSurfaces() const noexcept; - - void runOnScheduler(std::function &&task) const; - - std::optional surfaceContentSize(SurfaceId surfaceId) const; - - void runOnRuntimeScheduler( - std::function &&task, - SchedulerPriority priority = SchedulerPriority::NormalPriority) const noexcept; - - void emitDeviceEvent(folly::dynamic &&args); - - // react-native-gpui: the Dev Menu's "Configure Bundler". Points the dev - // server connections at `host:port` and reloads from there. Returns false - // when this build has no dev server (dev mode off). - bool setDevServer(const std::string &host, uint32_t port); - // "host:port" of the dev server in use, or empty without one. - std::string devServerAddress() const; - - private: - void createReactInstance(); - void destroyReactInstance(); - void reloadReactInstance(); - - bool loadScriptFromDevServer(); - bool loadScriptFromBundlePath(const std::string &bundlePath); - - std::string lastBundlePath_; - std::string lastSourcePath_; - const ReactInstanceConfig reactInstanceConfig_; - std::unique_ptr reactInstanceData_; - std::unique_ptr reactInstance_; - std::atomic isReloadingReactInstance_{false}; - /// Incremented by `createReactInstance`, so it is 1 for the first instance and - /// one more after each reload. See `instanceGeneration`. - std::atomic instanceGeneration_{0}; - - std::unique_ptr schedulerDelegate_; - std::unique_ptr scheduler_; - std::unique_ptr surfaceManager_; - // `surfaceManager_` is gone between the old instance and the new one of a - // reload, which runs on its own thread, while the UI thread keeps resizing and - // asking about surfaces. Calls from other threads take this, and a size that - // arrives in that gap is kept in `latestConstraints_` for the restarted surface. - mutable std::mutex surfaceManagerMutex_; - std::unordered_map> - latestConstraints_; - - std::shared_ptr devServerHelper_; - std::shared_ptr sourceURL_ = std::make_shared(); - std::shared_ptr inspector_; - std::unique_ptr packagerConnection_; - // Applied by the next reload, between the old instance and the new one. - std::mutex pendingDevServerMutex_; - std::optional> pendingDevServer_; - - std::shared_ptr animatedMountingOverrideDelegate_; -}; -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactInstanceConfig.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactInstanceConfig.h deleted file mode 100644 index d8be9d5e63..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/runtime/ReactInstanceConfig.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include - -namespace facebook::react { - -class JSRuntimeFactory; -class PlatformTimerRegistry; -class NativeAnimatedNodesManagerProvider; - -struct ReactInstanceConfig { - std::string appId; - std::string deviceName; -#ifdef REACT_NATIVE_DEBUG - bool enableDevMode{true}; - bool enableInspector{true}; -#else - bool enableDevMode{false}; - bool enableInspector{false}; -#endif - std::string devServerHost{"localhost"}; - uint32_t devServerPort{8081}; - - // Factory used to create the JS runtime for every (re)load. Supplied by the - // active JS engine package; ReactHost throws when it is null. - std::shared_ptr jsRuntimeFactory{nullptr}; - - // Optional factory used to create the PlatformTimerRegistry for the instance. - // When unset, a default thread-based PlatformTimerRegistryImpl is used. This - // is a seam for tests (e.g. Fantom) to inject a deterministic, mockable timer - // registry. - std::function()> platformTimerRegistryFactory{nullptr}; - - // Native animation graphs hold UIManager/runtime references and must not be - // reused across a reload. Platforms with render callbacks create a provider - // per instance and quiesce those callbacks before the instance is destroyed. - std::function()> - animatedNodesManagerProviderFactory{nullptr}; - std::function beforeInstanceDestroy{nullptr}; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/CMakeLists.txt b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/CMakeLists.txt deleted file mode 100644 index 5165780045..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -include(${REACT_COMMON_DIR}/cmake-utils/react-native-flags.cmake) - -file(GLOB react_cxx_platform_react_threading_SRC CONFIGURE_DEPENDS *.cpp) -add_library(react_cxx_platform_react_threading OBJECT ${react_cxx_platform_react_threading_SRC}) - -target_include_directories(react_cxx_platform_react_threading PUBLIC ${REACT_CXX_PLATFORM_DIR}) - -target_link_libraries(react_cxx_platform_react_threading - folly_runtime - react_cxxreact -) -target_compile_reactnative_options(react_cxx_platform_react_threading PRIVATE) -target_compile_options(react_cxx_platform_react_threading PRIVATE -Wpedantic) diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/MessageQueueThreadImpl.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/MessageQueueThreadImpl.cpp deleted file mode 100644 index d67d95a5fc..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/MessageQueueThreadImpl.cpp +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "MessageQueueThreadImpl.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if defined(__APPLE__) || defined(__linux__) -#include -#endif - -namespace { -std::atomic pendingJsTasks{0}; - -// With RN_GPUI_DEBUG_JS_TASKS set, every queued task remembers where it was -// queued from, so a task that never finishes can be named. -struct TaskRecord { - std::chrono::steady_clock::time_point queuedAt; - std::chrono::steady_clock::time_point startedAt; - bool started{false}; - std::vector frames; -}; - -bool debugTasks() { - static const bool enabled = std::getenv("RN_GPUI_DEBUG_JS_TASKS") != nullptr; - return enabled; -} - -std::mutex& recordsMutex() { - static std::mutex mutex; - return mutex; -} - -std::map& records() { - static std::map map; - return map; -} - -std::atomic nextTaskId{1}; - -std::vector callSite() { - std::vector frames; -#if defined(__APPLE__) || defined(__linux__) - void* stack[24]; - const int count = backtrace(stack, 24); - char** symbols = backtrace_symbols(stack, count); - if (symbols != nullptr) { - // Skip this function, `tracked` and the queue call itself. - for (int i = 3; i < count; ++i) { - frames.emplace_back(symbols[i]); - } - free(symbols); - } -#endif - return frames; -} - -struct PendingTask { - uint64_t id{0}; - PendingTask() { - ++pendingJsTasks; - if (debugTasks()) { - id = nextTaskId++; - TaskRecord record; - record.queuedAt = std::chrono::steady_clock::now(); - record.frames = callSite(); - std::lock_guard lock(recordsMutex()); - records()[id] = std::move(record); - } - } - ~PendingTask() { - --pendingJsTasks; - if (id != 0) { - std::lock_guard lock(recordsMutex()); - records().erase(id); - } - } - void markStarted() const { - if (id != 0) { - std::lock_guard lock(recordsMutex()); - auto it = records().find(id); - if (it != records().end()) { - it->second.started = true; - it->second.startedAt = std::chrono::steady_clock::now(); - } - } - } -}; - -std::function tracked(std::function runnable) { - auto activity = std::make_shared(); - return [activity, runnable = std::move(runnable)]() { - activity->markStarted(); - runnable(); - }; -} -} - -// The outstanding JS tasks, oldest first, as text; empty unless -// RN_GPUI_DEBUG_JS_TASKS is set. Copies at most `capacity` bytes into `buffer` -// and returns the length of the whole text. -extern "C" uint64_t rn_gpui_pending_js_tasks_dump( - char* buffer, - uint64_t capacity) noexcept { - std::string text; - { - std::lock_guard lock(recordsMutex()); - const auto now = std::chrono::steady_clock::now(); - for (const auto& [id, record] : records()) { - const auto since = record.started ? record.startedAt : record.queuedAt; - const auto ms = - std::chrono::duration_cast(now - since) - .count(); - text += "task " + std::to_string(id) + - (record.started ? " running for " : " queued for ") + - std::to_string(ms) + " ms, queued from:\n"; - for (const auto& frame : record.frames) { - text += " " + frame + "\n"; - } - } - } - if (buffer != nullptr && capacity > 0) { - const auto copied = std::min(capacity, text.size()); - std::memcpy(buffer, text.data(), copied); - } - return text.size(); -} - -extern "C" uint64_t rn_gpui_pending_js_tasks() noexcept { - return pendingJsTasks.load(); -} - -namespace facebook::react { - -std::function trackJsTask(std::function runnable) { - return tracked(std::move(runnable)); -} - -void MessageQueueThreadImpl::runOnQueue(std::function&& runnable) { - if (!taskDispatchThread_.isRunning()) { - return; - } - taskDispatchThread_.runAsync(tracked(std::move(runnable))); -} - -void MessageQueueThreadImpl::runOnQueueSync(std::function&& runnable) { - if (!taskDispatchThread_.isRunning()) { - return; - } - if (taskDispatchThread_.isOnThread()) { - tracked(std::move(runnable))(); - } else { - taskDispatchThread_.runSync(tracked(std::move(runnable))); - } -} - -void MessageQueueThreadImpl::quitSynchronous() { - taskDispatchThread_.quit(); -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/MessageQueueThreadImpl.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/MessageQueueThreadImpl.h deleted file mode 100644 index 3d25003bbc..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/MessageQueueThreadImpl.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include - -namespace facebook::react { - -using MessageQueueThreadFactory = std::function()>; - -constexpr char MessageQueueThreadFactoryKey[] = "MessageQueueThreadFactoryKey"; - -/** - * Wraps a JavaScript task so that, from now until it has run, it counts as - * queued JS work for the test driver's idle check. For a queue that does not - * run through `MessageQueueThreadImpl`. - */ -std::function trackJsTask(std::function runnable); - -/** - * MessageQueueThread implementation that uses a TaskDispatchThread for - * queueing and threading logic - */ -class MessageQueueThreadImpl : public MessageQueueThread { - public: - MessageQueueThreadImpl() noexcept = default; - explicit MessageQueueThreadImpl(int priorityOffset) noexcept : taskDispatchThread_("MessageQueue", priorityOffset) {} - - ~MessageQueueThreadImpl() noexcept override = default; - - /** Add a job to the queue asynchronously */ - void runOnQueue(std::function &&runnable) override; - - /** - * Add a job to the queue synchronously - call won't return until runnable - * has completed. Will run immediately if called from the looper thread. - * Should only be used for initialization. - */ - void runOnQueueSync(std::function &&runnable) override; - - /** - * Stop the message queue thread. Should only be used for cleanup - once it - * returns, no further work should run on the queue. - */ - void quitSynchronous() override; - - private: - TaskDispatchThread taskDispatchThread_{"MessageQueue"}; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/TaskDispatchThread.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/TaskDispatchThread.cpp deleted file mode 100644 index c8298edbf4..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/TaskDispatchThread.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "TaskDispatchThread.h" - -#include -#include -#include -#include -#include -#include - -#ifdef ANDROID -#include -#include -#include -#endif - -namespace facebook::react { - -TaskDispatchThread::TaskDispatchThread( - std::string_view threadName, - int priorityOffset) noexcept - : threadName_(threadName) { -#ifdef ANDROID - // Attaches the thread to JVM just in case anything calls out to Java - thread_ = std::thread([&]() { - facebook::jni::ThreadScope::WithClassLoader([&]() { - int result = setpriority( - PRIO_PROCESS, - static_cast(::syscall(SYS_gettid)), - priorityOffset); - - if (result != 0) { - LOG(INFO) << " setCurrentThreadPriority failed with pri errno: " - << errno; - } - - loop(); - }); - }); - -#else - thread_ = std::thread(&TaskDispatchThread::loop, this); -#endif -} - -TaskDispatchThread::~TaskDispatchThread() noexcept { - quit(); - - if (thread_.joinable()) { - thread_.join(); - } -} - -bool TaskDispatchThread::isOnThread() noexcept { - return std::this_thread::get_id() == thread_.get_id(); -} - -bool TaskDispatchThread::isRunning() noexcept { - return running_; -} - -void TaskDispatchThread::runAsync( - TaskFn&& task, - std::chrono::milliseconds delayMs) noexcept { - std::lock_guard guard(mutex_); - if (!running_) { - return; - } - auto dispatchTime = std::chrono::system_clock::now() + delayMs; - queue_.emplace(dispatchTime, std::move(task)); - loopCv_.notify_one(); -} - -void TaskDispatchThread::runSync(TaskFn&& task) noexcept { - // Calling runSync from the dispatch thread would deadlock, as the thread - // would wait for itself to execute the task it just queued. - assert(!isOnThread()); - - // Use shared_ptr to ensure the promise outlives both the caller and the - // queued task. The destructor guard ensures the promise is fulfilled even - // if the task is destroyed without executing (e.g., when quit() clears the - // queue during shutdown). - auto promise = std::make_shared>(); - auto guard = std::shared_ptr( - nullptr, [promise](void*) { promise->set_value(); }); - - runAsync([guard = std::move(guard), task = std::move(task)]() { task(); }); - promise->get_future().wait(); -} - -void TaskDispatchThread::quit() noexcept { - { - /* - We should hold lock even when changing atomic variable to correctly - publish the modificatino to the waiting thread - from: https://en.cppreference.com/w/cpp/thread/condition_variable.html - */ - std::unique_lock lock(mutex_); - if (!running_.exchange(false)) { - return; - } - } - - loopCv_.notify_one(); - if (!isOnThread()) { - loopStoppedPromise_.get_future().wait(); - } -} - -void TaskDispatchThread::loop() noexcept { - if (!threadName_.empty()) { - folly::setThreadName(threadName_); - } - while (running_) { - std::unique_lock lock(mutex_); - loopCv_.wait(lock, [&]() { return !running_ || !queue_.empty(); }); - - while (!queue_.empty()) { - auto task = queue_.top(); - auto now = std::chrono::system_clock::now(); - - if (running_) { - if (task.dispatchTime > now) { - // Wait until the scheduled task time, if delayed - loopCv_.wait_until(lock, task.dispatchTime); - continue; - } - } else { - // Shutting down, skip all the remaining tasks - queue_ = {}; - break; - } - - // We should check whether the task thread is still running at this - // point (which may not anymore be the case since the previous check) - if (running_) { - lock.unlock(); - task.fn(); - lock.lock(); - } - queue_.pop(); - } - } - - loopStoppedPromise_.set_value(); -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/TaskDispatchThread.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/TaskDispatchThread.h deleted file mode 100644 index 2dd86991b9..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/TaskDispatchThread.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -/** - * Representation of a thread looper which can add tasks to a queue and handle - * the synchronization of callers. - */ -class TaskDispatchThread { - public: - using TaskFn = std::function; - using TimePoint = std::chrono::time_point; - - TaskDispatchThread(std::string_view threadName = "", int priorityOffset = 0) noexcept; - - ~TaskDispatchThread() noexcept; - - /** Return true if the current thread is the same as this looper's thread. */ - bool isOnThread() noexcept; - - /** Return true until TaskDispatchThread.quit() is called */ - bool isRunning() noexcept; - - /** Add task to the queue and return immediately. */ - void runAsync(TaskFn &&task, std::chrono::milliseconds delayMs = std::chrono::milliseconds::zero()) noexcept; - - /** Add task to the queue and wait until it has completed. */ - void runSync(TaskFn &&task) noexcept; - - /** Shut down and clean up the thread. */ - void quit() noexcept; - - protected: - struct Task { - TimePoint dispatchTime; - TaskFn fn; - - Task(TimePoint dispatchTime, TaskFn &&fn) : dispatchTime(dispatchTime), fn(std::move(fn)) {} - - bool operator<(const Task &other) const - { - // Have the earliest tasks be at the front of the queue. - return dispatchTime > other.dispatchTime; - } - }; - - void loop() noexcept; - - std::mutex mutex_; - std::condition_variable loopCv_; - std::priority_queue queue_; - std::atomic running_{true}; - std::string threadName_; - std::thread thread_; - - std::promise loopStoppedPromise_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/tests/.clang-tidy b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/tests/.clang-tidy deleted file mode 100644 index 700d6cc363..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/tests/.clang-tidy +++ /dev/null @@ -1,5 +0,0 @@ ---- -InheritParentConfig: true -Checks: ' --facebook-hte-BadCall-sleep_for, -' diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/tests/TaskDispatchThreadTests.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/tests/TaskDispatchThreadTests.cpp deleted file mode 100644 index 99e35cd516..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/threading/tests/TaskDispatchThreadTests.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include -#include -#include -#include -#include -#include - -namespace facebook::react { - -class TaskDispatchThreadTest : public ::testing::Test { - protected: - std::unique_ptr dispatcher{ - std::make_unique()}; -}; - -// Test: isOnThread returns true inside the looper thread -TEST_F(TaskDispatchThreadTest, IsOnThreadReturnsTrueInLooper) { - bool result = false; - dispatcher->runSync([&] { result = dispatcher->isOnThread(); }); - EXPECT_TRUE(result); -} - -// Test: isRunning returns true before quit, false after -TEST_F(TaskDispatchThreadTest, IsRunningFlag) { - EXPECT_TRUE(dispatcher->isRunning()); - dispatcher->quit(); - EXPECT_FALSE(dispatcher->isRunning()); -} - -// Test: runAsync executes the task -TEST_F(TaskDispatchThreadTest, RunAsyncExecutesTask) { - std::atomic counter{0}; - dispatcher->runAsync([&] { counter++; }); - // Wait for task to complete - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - EXPECT_EQ(counter.load(), 1); -} - -// Test: runSync executes the task and blocks until done -TEST_F(TaskDispatchThreadTest, RunSyncExecutesTask) { - std::atomic counter{0}; - dispatcher->runSync([&] { counter++; }); - EXPECT_EQ(counter.load(), 1); -} - -// Test: runAsync with delay -TEST_F(TaskDispatchThreadTest, RunAsyncWithDelay) { - std::atomic counter{0}; - std::promise taskDone; - auto future = taskDone.get_future(); - dispatcher->runAsync( - [&] { - counter++; - taskDone.set_value(); - }, - std::chrono::milliseconds(200)); - std::this_thread::sleep_for(std::chrono::milliseconds(20)); - EXPECT_EQ(counter.load(), 0); // 20ms << 200ms, not yet executed - ASSERT_EQ( - future.wait_for(std::chrono::seconds(5)), std::future_status::ready); - EXPECT_EQ(counter.load(), 1); // Task completed -} - -// Test: Multiple delayed tasks execute in order -TEST_F(TaskDispatchThreadTest, MultipleDelayedTasksOrder) { - std::vector results; - dispatcher->runAsync( - [&] { results.push_back(1); }, std::chrono::milliseconds(50)); - dispatcher->runAsync( - [&] { results.push_back(2); }, std::chrono::milliseconds(100)); - std::this_thread::sleep_for(std::chrono::milliseconds(120)); - ASSERT_EQ(results.size(), 2); - EXPECT_EQ(results[0], 1); - EXPECT_EQ(results[1], 2); -} - -// Test: runSync blocks until task is done -TEST_F(TaskDispatchThreadTest, RunSyncBlocksUntilDone) { - std::atomic started{false}; - std::atomic finished{false}; - dispatcher->runAsync([&] { - started = true; - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - finished = true; - }); - dispatcher->runSync([&] { - EXPECT_TRUE(started); - EXPECT_TRUE(finished); - }); -} - -// Test: quit prevents further tasks from running -TEST_F(TaskDispatchThreadTest, QuitPreventsFurtherTasks) { - dispatcher->quit(); - std::atomic counter{0}; - dispatcher->runAsync([&] { counter++; }); - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - EXPECT_EQ(counter.load(), 0); -} - -// Test: Multiple runSync tasks execute serially -TEST_F(TaskDispatchThreadTest, MultipleRunSyncSerialExecution) { - std::vector results; - dispatcher->runSync([&] { results.push_back(1); }); - dispatcher->runSync([&] { results.push_back(2); }); - EXPECT_EQ(results.size(), 2); - EXPECT_EQ(results[0], 1); - EXPECT_EQ(results[1], 2); -} - -// Test: Edge case - runSync after quit should not execute -TEST_F(TaskDispatchThreadTest, RunSyncAfterQuitDoesNotExecute) { - dispatcher->quit(); - std::atomic counter{0}; - dispatcher->runSync([&] { counter++; }); - EXPECT_EQ(counter.load(), 0); -} - -// Test: Thread safety - runAsync from multiple threads -TEST_F(TaskDispatchThreadTest, RunAsyncFromMultipleThreads) { - std::atomic counter{0}; - auto task = [&] { dispatcher->runAsync([&] { counter++; }); }; - std::thread t1(task); - std::thread t2(task); - std::thread t3(task); - t1.join(); - t2.join(); - t3.join(); - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - EXPECT_EQ(counter.load(), 3); -} - -// Test: quit() shouldn't block if it is called inside loop thread -TEST_F(TaskDispatchThreadTest, QuitInTaskShouldntBeBlockedForever) { - dispatcher->runSync([&] { dispatcher->quit(); }); -} - -// Test: quit() should wait for already running task in the thread -TEST_F(TaskDispatchThreadTest, QuitShouldWaitAlreadyRunningTask) { - { - std::unique_ptr counter = std::make_unique(0); - dispatcher->runAsync([&] { - std::this_thread::sleep_for(std::chrono::milliseconds(300)); - *counter = 1; - }); - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - // if quit doesn't wait for running task, then *counter will access already - // deleted object - dispatcher->quit(); - } - // forcing dispatcher to join thread - dispatcher.reset(); -} - -// Test: sync tasks shouldn't be blocked for forever due to delayed task -TEST_F(TaskDispatchThreadTest, SyncTaskShouldntBeBlockedDueToDelayedTask) { - std::atomic counter = 0; - constexpr int kHugeDelay = 100000; - dispatcher->runAsync([&] {}, std::chrono::seconds(kHugeDelay)); - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - dispatcher->runSync([&] { counter++; }); - EXPECT_EQ(counter.load(), 1); -} - -// Test: runSync should not block forever when quit() is called concurrently -// This tests the fix where the RAII guard ensures the promise is fulfilled -// even if the task is destroyed without executing during shutdown. -TEST_F(TaskDispatchThreadTest, RunSyncDoesNotBlockWhenQuitCalledConcurrently) { - for (int i = 0; i < 100; ++i) { - auto localDispatcher = std::make_unique(); - - std::atomic runSyncCompleted{false}; - - // Block the dispatcher thread with a slow task - localDispatcher->runAsync( - [&] { std::this_thread::sleep_for(std::chrono::milliseconds(10)); }); - - // Start runSync from another thread - it will queue a task and wait - std::thread syncThread([&] { - localDispatcher->runSync([&] {}); - runSyncCompleted = true; - }); - - // Concurrently call quit() - this should cause the queued task to be - // destroyed without executing, but runSync should still return (not block - // forever) because the RAII guard fulfills the promise on destruction. - std::this_thread::sleep_for(std::chrono::milliseconds(5)); - localDispatcher->quit(); - - // If the fix works, syncThread should complete. If not, this would hang. - syncThread.join(); - - // runSync should have completed (either task ran or was skipped due to - // shutdown) - EXPECT_TRUE(runSyncCompleted.load()); - - localDispatcher.reset(); - } -} -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/utils/CMakeLists.txt b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/utils/CMakeLists.txt deleted file mode 100644 index 024447be3d..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/utils/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -include(${REACT_COMMON_DIR}/cmake-utils/react-native-flags.cmake) - -file(GLOB react_cxx_platform_react_utils_SRC CONFIGURE_DEPENDS *.cpp) -add_library(react_cxx_platform_react_utils OBJECT ${react_cxx_platform_react_utils_SRC}) - -target_include_directories(react_cxx_platform_react_utils PUBLIC ${REACT_CXX_PLATFORM_DIR}) - -target_link_libraries(react_cxx_platform_react_utils - react_debug - react_renderer_core - react_utils -) -target_compile_reactnative_options(react_cxx_platform_react_utils PRIVATE) -target_compile_options(react_cxx_platform_react_utils PRIVATE -Wpedantic) diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/utils/PlatformRunLoopObserver.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/utils/PlatformRunLoopObserver.h deleted file mode 100644 index 69cafe5632..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/utils/PlatformRunLoopObserver.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include -#include -#include - -namespace facebook::react { - -class PlatformRunLoopObserver; - -class PlatformRunLoopObserver : public RunLoopObserver { - public: - PlatformRunLoopObserver(RunLoopObserver::Activity activities, const RunLoopObserver::WeakOwner &owner) - : RunLoopObserver(activities, owner) - { - } - ~PlatformRunLoopObserver() override = default; - - PlatformRunLoopObserver(PlatformRunLoopObserver &other) = delete; - PlatformRunLoopObserver &operator=(PlatformRunLoopObserver &other) = delete; - PlatformRunLoopObserver(PlatformRunLoopObserver &&other) = delete; - PlatformRunLoopObserver &operator=(PlatformRunLoopObserver &&other) = delete; - - bool isOnRunLoopThread() const noexcept override - { - return false; - } - - void onRender() const noexcept - { - if (auto owner = owner_.lock()) { - activityDidChange(activities_); - } - } - - private: - void startObserving() const noexcept override {} - void stopObserving() const noexcept override {} -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/utils/RunLoopObserverManager.cpp b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/utils/RunLoopObserverManager.cpp deleted file mode 100644 index cd02314d27..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/utils/RunLoopObserverManager.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#include "RunLoopObserverManager.h" - -#include - -namespace facebook::react { - -/* - * Event beat associated with JavaScript runtime. The beat is called on - * RuntimeScheduler's thread induced by the UI thread event loop. - */ -class EventBeatImpl : public EventBeat, public RunLoopObserver::Delegate { - public: - EventBeatImpl( - std::shared_ptr ownerBox, - std::shared_ptr uiRunLoopObserver, - RuntimeScheduler& runtimeScheduler) - : EventBeat(std::move(ownerBox), runtimeScheduler), - uiRunLoopObserver_(std::move(uiRunLoopObserver)) { - uiRunLoopObserver_->setDelegate(this); - uiRunLoopObserver_->enable(); - } - -#pragma mark - RunLoopObserver::Delegate - - void activityDidChange( - const RunLoopObserver::Delegate* delegate, - RunLoopObserver::Activity /*activity*/) const noexcept override { - react_native_assert(delegate == this); - induce(); - } - - private: - std::shared_ptr uiRunLoopObserver_; -}; - -std::unique_ptr RunLoopObserverManager::createEventBeat( - std::shared_ptr ownerBox, - RuntimeScheduler& runtimeScheduler) { - auto observer = std::make_shared( - RunLoopObserver::Activity::BeforeWaiting, ownerBox->owner); - observer_ = observer; - return std::make_unique( - std::move(ownerBox), std::move(observer), runtimeScheduler); -} - -void RunLoopObserverManager::onRender() const noexcept { - if (auto observer = observer_.lock()) { - observer->onRender(); - } -} - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/utils/RunLoopObserverManager.h b/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/utils/RunLoopObserverManager.h deleted file mode 100644 index f7b0f241e9..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactCxxPlatform/react/utils/RunLoopObserverManager.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#pragma once - -#include "PlatformRunLoopObserver.h" - -#include -#include -#include - -namespace facebook::react { - -class RunLoopObserverManager : std::enable_shared_from_this { - public: - std::unique_ptr createEventBeat( - std::shared_ptr ownerBox, - RuntimeScheduler &runtimeScheduler); - - void onRender() const noexcept; - - void induce() const noexcept; - - private: - std::weak_ptr observer_; -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/Cargo.lock b/vendor/react-native-gpui/packages/core/ReactGpui/Cargo.lock deleted file mode 100644 index 9f48912a2e..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/Cargo.lock +++ /dev/null @@ -1,8189 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "accesskit" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320" -dependencies = [ - "enumn", - "uuid", -] - -[[package]] -name = "accesskit_atspi_common" -version = "0.19.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "023da0e5097f46df7092d5280b02efb9bbf8d93298daeced42652463e357d636" -dependencies = [ - "accesskit", - "accesskit_consumer", - "atspi-common", - "phf", - "serde", - "zvariant", -] - -[[package]] -name = "accesskit_consumer" -version = "0.38.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245" -dependencies = [ - "accesskit", - "hashbrown 0.16.1", -] - -[[package]] -name = "accesskit_macos" -version = "0.26.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076" -dependencies = [ - "accesskit", - "accesskit_consumer", - "hashbrown 0.16.1", - "objc2 0.5.3", - "objc2-app-kit 0.2.2", - "objc2-foundation 0.2.2", -] - -[[package]] -name = "accesskit_unix" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e156ed3802e35eefe894ef2671bc6c889303d8a7e110b5e1b48f504b91362f" -dependencies = [ - "accesskit", - "accesskit_atspi_common", - "async-channel", - "async-executor", - "async-task", - "atspi", - "futures-lite", - "futures-util", - "serde", - "zbus 5.19.0", -] - -[[package]] -name = "accesskit_windows" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "106c2b961215864d1c2e703ee63269c25c4e80a577ffb2c1017b9c17dcdf83a1" -dependencies = [ - "accesskit", - "accesskit_consumer", - "hashbrown 0.16.1", - "static_assertions", - "windows 0.62.2", - "windows-core 0.62.2", -] - -[[package]] -name = "addr2line" -version = "0.27.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e567177890eb1617b1f774005b66b26b2377afd138a2ca37aae7d8f0c81429d4" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "aes" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" -dependencies = [ - "cfg-if", - "cipher", - "cpufeatures 0.2.17", - "zeroize", -] - -[[package]] -name = "ahash" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" -dependencies = [ - "cfg-if", - "const-random", - "once_cell", - "version_check", - "zerocopy", -] - -[[package]] -name = "aho-corasick" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" -dependencies = [ - "memchr", -] - -[[package]] -name = "aligned" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" -dependencies = [ - "as-slice", -] - -[[package]] -name = "aligned-vec" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" -dependencies = [ - "equator", -] - -[[package]] -name = "alloca" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5a7d05ea6aea7e9e64d25b9156ba2fee3fdd659e34e41063cd2fc7cd020d7f4" -dependencies = [ - "cc", -] - -[[package]] -name = "allocator-api2" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" - -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - -[[package]] -name = "anes" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" - -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - -[[package]] -name = "anyhow" -version = "1.0.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" - -[[package]] -name = "arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" - -[[package]] -name = "arc-swap" -version = "1.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" -dependencies = [ - "rustversion", -] - -[[package]] -name = "arg_enum_proc_macro" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "arrayref" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" - -[[package]] -name = "arrayvec" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" - -[[package]] -name = "as-raw-xcb-connection" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" - -[[package]] -name = "as-slice" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" -dependencies = [ - "stable_deref_trait", -] - -[[package]] -name = "ash" -version = "0.38.0+1.3.281" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" -dependencies = [ - "libloading", -] - -[[package]] -name = "ashpd" -version = "0.13.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb8421aaa9644a5faf26735f258b669b15f063313ef8f8e2bdb28912a1a6f111" -dependencies = [ - "enumflags2", - "futures-channel", - "futures-util", - "getrandom 0.4.3", - "serde", - "serde_repr", - "wayland-backend", - "wayland-client", - "wayland-protocols", - "zbus 5.19.0", -] - -[[package]] -name = "async-broadcast" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" -dependencies = [ - "event-listener", - "event-listener-strategy", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-channel" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" -dependencies = [ - "concurrent-queue", - "event-listener-strategy", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-executor" -version = "1.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" -dependencies = [ - "async-task", - "concurrent-queue", - "fastrand", - "futures-lite", - "pin-project-lite", - "slab", -] - -[[package]] -name = "async-fs" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5" -dependencies = [ - "async-lock", - "blocking", - "futures-lite", -] - -[[package]] -name = "async-io" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" -dependencies = [ - "autocfg", - "cfg-if", - "concurrent-queue", - "futures-io", - "futures-lite", - "parking", - "polling", - "rustix", - "slab", - "windows-sys 0.61.2", -] - -[[package]] -name = "async-lock" -version = "3.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" -dependencies = [ - "event-listener", - "event-listener-strategy", - "pin-project-lite", -] - -[[package]] -name = "async-net" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b948000fad4873c1c9339d60f2623323a0cfd3816e5181033c6a5cb68b2accf7" -dependencies = [ - "async-io", - "blocking", - "futures-lite", -] - -[[package]] -name = "async-process" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" -dependencies = [ - "async-channel", - "async-io", - "async-lock", - "async-signal", - "async-task", - "blocking", - "cfg-if", - "event-listener", - "futures-lite", - "rustix", -] - -[[package]] -name = "async-recursion" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "async-signal" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" -dependencies = [ - "async-io", - "async-lock", - "atomic-waker", - "cfg-if", - "futures-core", - "futures-io", - "rustix", - "signal-hook-registry", - "slab", - "windows-sys 0.61.2", -] - -[[package]] -name = "async-task" -version = "4.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" - -[[package]] -name = "async-trait" -version = "0.1.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "atk" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" -dependencies = [ - "atk-sys", - "glib", - "libc", -] - -[[package]] -name = "atk-sys" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" -dependencies = [ - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - -[[package]] -name = "atomic" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba" - -[[package]] -name = "atomic-waker" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" - -[[package]] -name = "atspi" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" -dependencies = [ - "atspi-common", - "atspi-proxies", -] - -[[package]] -name = "atspi-common" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" -dependencies = [ - "enumflags2", - "serde", - "static_assertions", - "zbus 5.19.0", - "zbus-lockstep", - "zbus-lockstep-macros", - "zbus_names", - "zvariant", -] - -[[package]] -name = "atspi-proxies" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" -dependencies = [ - "atspi-common", - "serde", - "zbus 5.19.0", -] - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "av-scenechange" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" -dependencies = [ - "aligned", - "anyhow", - "arg_enum_proc_macro", - "arrayvec", - "log", - "num-rational", - "num-traits", - "pastey 0.1.1", - "rayon", - "thiserror 2.0.21", - "v_frame", - "y4m", -] - -[[package]] -name = "av1-grain" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" -dependencies = [ - "anyhow", - "arrayvec", - "log", - "nom", - "num-rational", - "v_frame", -] - -[[package]] -name = "avif-serialize" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38" -dependencies = [ - "arrayvec", -] - -[[package]] -name = "backtrace" -version = "0.3.77" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42f4220217f3288537b83684130f42fad43320b1c3b805f1910d683d52ded24f" -dependencies = [ - "addr2line", - "cfg-if", - "libc", - "miniz_oxide 0.9.1", - "object", - "rustc-demangle", - "windows-link 0.2.1", -] - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "bench_metrics" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "anyhow", - "criterion", - "libc", - "perf-event2", -] - -[[package]] -name = "bit-set" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" -dependencies = [ - "borsh", - "serde", -] - -[[package]] -name = "bit_field" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" -dependencies = [ - "serde_core", -] - -[[package]] -name = "bitstream-io" -version = "4.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f" -dependencies = [ - "no_std_io2", -] - -[[package]] -name = "block" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "block-padding" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" -dependencies = [ - "generic-array", -] - -[[package]] -name = "block2" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" -dependencies = [ - "objc2 0.5.3", -] - -[[package]] -name = "block2" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" -dependencies = [ - "objc2 0.6.5", -] - -[[package]] -name = "blocking" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" -dependencies = [ - "async-channel", - "async-task", - "futures-io", - "futures-lite", - "piper", -] - -[[package]] -name = "borsh" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" -dependencies = [ - "borsh-derive", - "bytes", - "cfg_aliases", -] - -[[package]] -name = "borsh-derive" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" -dependencies = [ - "once_cell", - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "built" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9" - -[[package]] -name = "bumpalo" -version = "3.20.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" - -[[package]] -name = "bytemuck" -version = "1.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" -dependencies = [ - "bytemuck_derive", -] - -[[package]] -name = "bytemuck_derive" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "byteorder-lite" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" - -[[package]] -name = "bytes" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" - -[[package]] -name = "c-enum" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd17eb909a8c6a894926bfcc3400a4bb0e732f5a57d37b1f14e8b29e329bace8" - -[[package]] -name = "cairo-rs" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" -dependencies = [ - "bitflags 2.13.2", - "cairo-sys-rs", - "glib", - "libc", - "once_cell", - "thiserror 1.0.69", -] - -[[package]] -name = "cairo-sys-rs" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" -dependencies = [ - "glib-sys", - "libc", - "system-deps", -] - -[[package]] -name = "calloop" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" -dependencies = [ - "bitflags 2.13.2", - "polling", - "rustix", - "tracing", -] - -[[package]] -name = "calloop-wayland-source" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" -dependencies = [ - "calloop", - "rustix", - "wayland-backend", - "wayland-client", -] - -[[package]] -name = "cast" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" - -[[package]] -name = "cbc" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" -dependencies = [ - "cipher", -] - -[[package]] -name = "cbindgen" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eadd868a2ce9ca38de7eeafdcec9c7065ef89b42b32f0839278d55f35c54d1ff" -dependencies = [ - "heck 0.4.1", - "indexmap", - "log", - "proc-macro2", - "quote", - "serde", - "serde_json", - "syn 2.0.119", - "tempfile", - "toml 0.8.23", -] - -[[package]] -name = "cc" -version = "1.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" -dependencies = [ - "find-msvc-tools", - "jobserver", - "libc", - "shlex", -] - -[[package]] -name = "cfg-expr" -version = "0.15.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" -dependencies = [ - "smallvec", - "target-lexicon", -] - -[[package]] -name = "cfg-if" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" - -[[package]] -name = "cfg_aliases" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" - -[[package]] -name = "chacha20" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.1", - "rand_core 0.10.1", -] - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link 0.2.1", -] - -[[package]] -name = "ciborium" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" -dependencies = [ - "ciborium-io", - "ciborium-ll", - "serde", -] - -[[package]] -name = "ciborium-io" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" - -[[package]] -name = "ciborium-ll" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" -dependencies = [ - "ciborium-io", - "half", -] - -[[package]] -name = "cipher" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" -dependencies = [ - "crypto-common", - "inout", - "zeroize", -] - -[[package]] -name = "clap" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" -dependencies = [ - "clap_builder", -] - -[[package]] -name = "clap_builder" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" -dependencies = [ - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_lex" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" - -[[package]] -name = "cmake" -version = "0.1.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" -dependencies = [ - "cc", -] - -[[package]] -name = "cocoa" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6140449f97a6e97f9511815c5632d84c8aacf8ac271ad77c559218161a1373c" -dependencies = [ - "bitflags 1.3.2", - "block", - "cocoa-foundation", - "core-foundation 0.9.4", - "core-graphics 0.23.2", - "foreign-types", - "libc", - "objc", -] - -[[package]] -name = "cocoa-foundation" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c6234cbb2e4c785b456c0644748b1ac416dd045799740356f8363dfe00c93f7" -dependencies = [ - "bitflags 1.3.2", - "block", - "core-foundation 0.9.4", - "core-graphics-types 0.1.3", - "libc", - "objc", -] - -[[package]] -name = "codespan-reporting" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" -dependencies = [ - "serde", - "termcolor", - "unicode-width", -] - -[[package]] -name = "collections" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "gpui_util", - "indexmap", - "rustc-hash 2.1.3", -] - -[[package]] -name = "color_quant" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" - -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - -[[package]] -name = "concurrent-queue" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "console_error_panic_hook" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" -dependencies = [ - "cfg-if", - "wasm-bindgen", -] - -[[package]] -name = "const-random" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" -dependencies = [ - "const-random-macro", -] - -[[package]] -name = "const-random-macro" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" -dependencies = [ - "getrandom 0.2.17", - "once_cell", - "tiny-keccak", -] - -[[package]] -name = "convert_case" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" -dependencies = [ - "unicode-segmentation", -] - -[[package]] -name = "convert_case" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "affbf0190ed2caf063e3def54ff444b449371d55c58e513a95ab98eca50adb49" -dependencies = [ - "unicode-segmentation", -] - -[[package]] -name = "core-foundation" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "core-foundation" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "core-graphics" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" -dependencies = [ - "bitflags 1.3.2", - "core-foundation 0.9.4", - "core-graphics-types 0.1.3", - "foreign-types", - "libc", -] - -[[package]] -name = "core-graphics" -version = "0.24.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1" -dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.10.1", - "core-graphics-types 0.2.0", - "foreign-types", - "libc", -] - -[[package]] -name = "core-graphics-helmer-fork" -version = "0.24.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32eb7c354ae9f6d437a6039099ce7ecd049337a8109b23d73e48e8ffba8e9cd5" -dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.9.4", - "core-graphics-types 0.1.3", - "foreign-types", - "libc", -] - -[[package]] -name = "core-graphics-types" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" -dependencies = [ - "bitflags 1.3.2", - "core-foundation 0.9.4", - "libc", -] - -[[package]] -name = "core-graphics-types" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" -dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.10.1", - "libc", -] - -[[package]] -name = "core-text" -version = "21.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a593227b66cbd4007b2a050dfdd9e1d1318311409c8d600dc82ba1b15ca9c130" -dependencies = [ - "core-foundation 0.10.1", - "core-graphics 0.24.0", - "foreign-types", - "libc", -] - -[[package]] -name = "core_detect" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" - -[[package]] -name = "core_maths" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" -dependencies = [ - "libm", -] - -[[package]] -name = "cosmic-text" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be17b688510d934ce13f48a2beba700e11583e281e0fda99c22bb256a14eda73" -dependencies = [ - "bitflags 2.13.2", - "fontdb", - "harfrust", - "linebender_resource_handle", - "log", - "rangemap", - "rustc-hash 2.1.3", - "self_cell", - "skrifa 0.40.0", - "smol_str", - "swash", - "sys-locale", - "unicode-bidi", - "unicode-linebreak", - "unicode-script", - "unicode-segmentation", -] - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "cpufeatures" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" -dependencies = [ - "libc", -] - -[[package]] -name = "crc32fast" -version = "1.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "criterion" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "950046b2aa2492f9a536f5f4f9a3de7b9e2476e575e05bd6c333371add4d98f3" -dependencies = [ - "alloca", - "anes", - "cast", - "ciborium", - "clap", - "criterion-plot", - "itertools 0.13.0", - "num-traits", - "oorandom", - "page_size", - "plotters", - "rayon", - "regex", - "serde", - "serde_json", - "tinytemplate", - "walkdir", -] - -[[package]] -name = "criterion-plot" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8d80a2f4f5b554395e47b5d8305bc3d27813bacb73493eb1001e8f76dae29ea" -dependencies = [ - "cast", - "itertools 0.13.0", -] - -[[package]] -name = "crossbeam-channel" -version = "0.5.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" -dependencies = [ - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-queue" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" - -[[package]] -name = "crunchy" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" - -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "ctor" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea691ed9f36489d087419b8b2ba3ef27d89621380b4178c73e2445a379e4e0f4" -dependencies = [ - "link-section", - "linktime-proc-macro", -] - -[[package]] -name = "cxx" -version = "1.0.202" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13f6de320895f42e6e081abb5c7983bedcf0b6d0ff9323de0d33f620c8ac1199" -dependencies = [ - "cc", - "cxx-build", - "cxxbridge-cmd", - "cxxbridge-flags", - "cxxbridge-macro", - "foldhash 0.2.0", - "link-cplusplus", -] - -[[package]] -name = "cxx-build" -version = "1.0.202" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fde53ca86b9704a943fef0f1e1d836239a6aedca5de3c65fa9f97ec0bd46d39" -dependencies = [ - "cc", - "codespan-reporting", - "indexmap", - "proc-macro2", - "quote", - "scratch", - "syn 3.0.10", -] - -[[package]] -name = "cxxbridge-cmd" -version = "1.0.202" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bae89236c811fd4d08ed3441759ac4ac98d752cbfd3de341315ba16ad20ec3" -dependencies = [ - "clap", - "codespan-reporting", - "indexmap", - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "cxxbridge-flags" -version = "1.0.202" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49045042e5fced01b80742aba5508de82aa4f13677ed3fa2b4cda709c40c5918" - -[[package]] -name = "cxxbridge-macro" -version = "1.0.202" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b181252e2e3d3b5d183afbdc033a3958b445eb3e1a0ae65fc3d4f5259f5da6fd" -dependencies = [ - "indexmap", - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "data-encoding" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" - -[[package]] -name = "data-url" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" - -[[package]] -name = "deranged" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" - -[[package]] -name = "derive_more" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" -dependencies = [ - "derive_more-impl", -] - -[[package]] -name = "derive_more-impl" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" -dependencies = [ - "convert_case 0.10.0", - "proc-macro2", - "quote", - "rustc_version", - "syn 2.0.119", -] - -[[package]] -name = "derive_refineable" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "crypto-common", - "subtle", -] - -[[package]] -name = "dirs" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" -dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys 0.59.0", -] - -[[package]] -name = "dispatch" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" - -[[package]] -name = "dispatch2" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" -dependencies = [ - "bitflags 2.13.2", - "block2 0.6.2", - "objc2 0.6.5", -] - -[[package]] -name = "displaydoc" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "dlib" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" -dependencies = [ - "libloading", -] - -[[package]] -name = "document-features" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" -dependencies = [ - "litrs", -] - -[[package]] -name = "downcast-rs" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" - -[[package]] -name = "dpi" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" - -[[package]] -name = "dunce" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" - -[[package]] -name = "dwrote" -version = "0.11.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1b35532432acc8b19ceed096e35dfa088d3ea037fe4f3c085f1f97f33b4d02" -dependencies = [ - "lazy_static", - "libc", - "winapi", - "wio", -] - -[[package]] -name = "dyn-clone" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" - -[[package]] -name = "either" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" - -[[package]] -name = "embed-resource" -version = "3.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f" -dependencies = [ - "cc", - "memchr", - "rustc_version", - "toml 1.2.1+spec-1.1.0", - "vswhom", - "winreg", -] - -[[package]] -name = "encoding_rs" -version = "0.8.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" -dependencies = [ - "cfg-if", - "core_detect", - "multiversion_no_op", - "rustversion", - "scopeguard", - "simdutf8", -] - -[[package]] -name = "endi" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" - -[[package]] -name = "enumflags2" -version = "0.7.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" -dependencies = [ - "enumflags2_derive", - "serde", -] - -[[package]] -name = "enumflags2_derive" -version = "0.7.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "enumn" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "env_filter" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217" -dependencies = [ - "log", - "regex", -] - -[[package]] -name = "env_logger" -version = "0.11.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6" -dependencies = [ - "anstream", - "anstyle", - "env_filter", - "jiff", - "log", -] - -[[package]] -name = "equator" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" -dependencies = [ - "equator-macro", -] - -[[package]] -name = "equator-macro" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "equivalent" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" - -[[package]] -name = "errno" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" -dependencies = [ - "libc", - "windows-sys 0.59.0", -] - -[[package]] -name = "etagere" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc89bf99e5dc15954a60f707c1e09d7540e5cd9af85fa75caa0b510bc08c5342" -dependencies = [ - "euclid", - "svg_fmt", -] - -[[package]] -name = "euclid" -version = "0.22.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" -dependencies = [ - "num-traits", -] - -[[package]] -name = "event-listener" -version = "5.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" -dependencies = [ - "parking", - "pin-project-lite", -] - -[[package]] -name = "event-listener-strategy" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" -dependencies = [ - "event-listener", - "pin-project-lite", -] - -[[package]] -name = "exr" -version = "1.74.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" -dependencies = [ - "bit_field", - "half", - "lebe", - "miniz_oxide 0.8.9", - "multiversion", - "rayon-core", - "smallvec", - "zune-inflate", -] - -[[package]] -name = "fastrand" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" - -[[package]] -name = "fax" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" - -[[package]] -name = "fdeflate" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" -dependencies = [ - "simd-adler32", -] - -[[package]] -name = "field-offset" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" -dependencies = [ - "memoffset", - "rustc_version", -] - -[[package]] -name = "filedescriptor" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" -dependencies = [ - "libc", - "thiserror 1.0.69", - "winapi", -] - -[[package]] -name = "find-msvc-tools" -version = "0.1.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" - -[[package]] -name = "fixedbitset" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" - -[[package]] -name = "flate2" -version = "1.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" -dependencies = [ - "crc32fast", - "miniz_oxide 0.9.1", - "zlib-rs", -] - -[[package]] -name = "float-cmp" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" - -[[package]] -name = "float-ord" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ce81f49ae8a0482e4c55ea62ebbd7e5a686af544c00b9d090bba3ff9be97b3d" - -[[package]] -name = "float_next_after" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8" - -[[package]] -name = "flume" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" -dependencies = [ - "futures-core", - "futures-sink", - "spin 0.9.9", -] - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "foldhash" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" - -[[package]] -name = "foldhash" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" - -[[package]] -name = "font-types" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7" -dependencies = [ - "bytemuck", -] - -[[package]] -name = "font-types" -version = "0.12.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" -dependencies = [ - "bytemuck", -] - -[[package]] -name = "fontconfig-parser" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646" -dependencies = [ - "roxmltree 0.20.0", -] - -[[package]] -name = "fontdb" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905" -dependencies = [ - "fontconfig-parser", - "log", - "memmap2", - "slotmap", - "tinyvec", - "ttf-parser", -] - -[[package]] -name = "fontdue" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e796cb6894e6418daacea84b28dd4f98d3b32c74d5bb452ba1ecfbf5ad8e84ca" -dependencies = [ - "hashbrown 0.15.5", - "ttf-parser", -] - -[[package]] -name = "foreign-types" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" -dependencies = [ - "foreign-types-macros", - "foreign-types-shared", -] - -[[package]] -name = "foreign-types-macros" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "foreign-types-shared" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" - -[[package]] -name = "form_urlencoded" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "freetype-sys" -version = "0.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e7edc5b9669349acfda99533e9e0bcf26a51862ab43b08ee7745c55d28eb134" -dependencies = [ - "cc", - "libc", - "pkg-config", -] - -[[package]] -name = "futures" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-concurrency" -version = "7.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "175cd8cca9e1d45b87f18ffa75088f2099e3c4fe5e2f83e42de112560bea8ea6" -dependencies = [ - "fixedbitset", - "futures-core", - "futures-lite", - "pin-project", - "smallvec", -] - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-executor" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" - -[[package]] -name = "futures-lite" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" -dependencies = [ - "fastrand", - "futures-core", - "futures-io", - "parking", - "pin-project-lite", -] - -[[package]] -name = "futures-macro" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "futures-sink" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "slab", -] - -[[package]] -name = "gdk" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691" -dependencies = [ - "cairo-rs", - "gdk-pixbuf", - "gdk-sys", - "gio", - "glib", - "libc", - "pango", -] - -[[package]] -name = "gdk-pixbuf" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" -dependencies = [ - "gdk-pixbuf-sys", - "gio", - "glib", - "libc", - "once_cell", -] - -[[package]] -name = "gdk-pixbuf-sys" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" -dependencies = [ - "gio-sys", - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - -[[package]] -name = "gdk-sys" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" -dependencies = [ - "cairo-sys-rs", - "gdk-pixbuf-sys", - "gio-sys", - "glib-sys", - "gobject-sys", - "libc", - "pango-sys", - "pkg-config", - "system-deps", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "gethostname" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" -dependencies = [ - "rustix", - "windows-link 0.2.1", -] - -[[package]] -name = "getrandom" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "r-efi 5.3.0", - "wasip2", - "wasm-bindgen", -] - -[[package]] -name = "getrandom" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" -dependencies = [ - "cfg-if", - "libc", - "r-efi 6.0.0", - "rand_core 0.10.1", -] - -[[package]] -name = "gif" -version = "0.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" -dependencies = [ - "color_quant", - "weezl", -] - -[[package]] -name = "gimli" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1033caf0b349c518623b5396bfb2cf0bddf44f0306d543a250e5743297aafd10" - -[[package]] -name = "gio" -version = "0.18.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-util", - "gio-sys", - "glib", - "libc", - "once_cell", - "pin-project-lite", - "smallvec", - "thiserror 1.0.69", -] - -[[package]] -name = "gio-sys" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" -dependencies = [ - "glib-sys", - "gobject-sys", - "libc", - "system-deps", - "winapi", -] - -[[package]] -name = "gl_generator" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" -dependencies = [ - "khronos_api", - "log", - "xml-rs", -] - -[[package]] -name = "glib" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5" -dependencies = [ - "bitflags 2.13.2", - "futures-channel", - "futures-core", - "futures-executor", - "futures-task", - "futures-util", - "gio-sys", - "glib-macros", - "glib-sys", - "gobject-sys", - "libc", - "memchr", - "once_cell", - "smallvec", - "thiserror 1.0.69", -] - -[[package]] -name = "glib-macros" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc" -dependencies = [ - "heck 0.4.1", - "proc-macro-crate 2.0.0", - "proc-macro-error", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "glib-sys" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" -dependencies = [ - "libc", - "system-deps", -] - -[[package]] -name = "global-hotkey" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adda8c76a5139df3bae0eb0413c2cd746f66594e0bb66231a4daa0be3172da70" -dependencies = [ - "crossbeam-channel", - "keyboard-types 0.8.3", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", - "once_cell", - "thiserror 2.0.21", - "windows-sys 0.59.0", - "x11rb", - "xkeysym", -] - -[[package]] -name = "glow" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "263218b0ba2b0715c3370fb04674f5f8aa331594b521c94ff0a8e4a8472d1386" -dependencies = [ - "js-sys", - "slotmap", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "glutin_wgl_sys" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" -dependencies = [ - "gl_generator", -] - -[[package]] -name = "gobject-sys" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" -dependencies = [ - "glib-sys", - "libc", - "system-deps", -] - -[[package]] -name = "gpu-allocator" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" -dependencies = [ - "ash", - "hashbrown 0.16.1", - "log", - "presser", - "thiserror 2.0.21", - "windows 0.62.2", -] - -[[package]] -name = "gpui" -version = "0.2.2" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "accesskit", - "anyhow", - "async-channel", - "async-task", - "backtrace", - "bench_metrics", - "bitflags 2.13.2", - "chrono", - "collections", - "derive_more", - "embed-resource", - "etagere", - "futures", - "futures-concurrency", - "getrandom 0.3.4", - "gpui_macros", - "gpui_shared_string", - "gpui_util", - "hdrhistogram", - "heapless", - "http_client", - "icu_segmenter", - "image", - "inventory", - "itertools 0.14.0", - "libc", - "log", - "lyon", - "num_cpus", - "objc2-core-foundation", - "objc2-core-video", - "parking", - "parking_lot", - "pin-project", - "pollster 0.4.0", - "postage", - "profiling", - "proptest", - "rand 0.9.5", - "raw-window-handle", - "refineable", - "regex", - "resvg", - "scheduler", - "schemars", - "seahash", - "serde", - "serde_json", - "slotmap", - "smallvec", - "spin 0.10.1", - "strum", - "sum_tree", - "taffy", - "thiserror 2.0.21", - "ttf-parser", - "unicode-segmentation", - "url", - "usvg", - "uuid", - "waker-fn", - "web-time", - "windows 0.62.2", - "zed-scap", -] - -[[package]] -name = "gpui_apple" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "anyhow", - "async-task", - "block2 0.6.2", - "cbindgen", - "collections", - "core-foundation 0.10.1", - "core-foundation-sys", - "core-graphics 0.24.0", - "core-text", - "dispatch2", - "etagere", - "futures", - "gpui", - "gpui_util", - "image", - "libc", - "log", - "mach2", - "objc2 0.6.5", - "objc2-core-foundation", - "objc2-core-graphics", - "objc2-core-text", - "objc2-core-video", - "objc2-foundation 0.3.2", - "objc2-metal 0.3.2", - "objc2-quartz-core 0.3.2", - "objc2-security", - "parking_lot", - "pathfinder_geometry", - "smallvec", - "thiserror 2.0.21", - "zed-font-kit", -] - -[[package]] -name = "gpui_cpu_renderer" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "anyhow", - "gpui", - "image", - "log", - "rayon", - "tiny-skia", -] - -[[package]] -name = "gpui_ios" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "anyhow", - "block2 0.6.2", - "futures", - "gpui", - "gpui_apple", - "log", - "objc2 0.6.5", - "objc2-core-foundation", - "objc2-foundation 0.3.2", - "objc2-quartz-core 0.3.2", - "objc2-ui-kit", - "parking_lot", - "raw-window-handle", - "uuid", -] - -[[package]] -name = "gpui_linux" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "accesskit", - "accesskit_unix", - "anyhow", - "as-raw-xcb-connection", - "ashpd", - "bytemuck", - "calloop", - "calloop-wayland-source", - "collections", - "filedescriptor", - "futures", - "gpui", - "gpui_util", - "gpui_wgpu", - "http_client", - "image", - "libc", - "log", - "notify-rust", - "oo7", - "open", - "parking_lot", - "raw-window-handle", - "smallvec", - "smol", - "strum", - "url", - "uuid", - "wayland-backend", - "wayland-client", - "wayland-cursor", - "wayland-protocols", - "wayland-protocols-plasma", - "wayland-protocols-wlr", - "x11rb", - "xkbcommon", - "zed-scap", - "zed-xim", -] - -[[package]] -name = "gpui_macos" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "accesskit", - "accesskit_macos", - "anyhow", - "block2 0.6.2", - "collections", - "core-foundation 0.10.1", - "core-foundation-sys", - "core-graphics 0.24.0", - "ctor", - "dispatch2", - "foreign-types", - "futures", - "gpui", - "gpui_apple", - "gpui_util", - "image", - "itertools 0.14.0", - "log", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", - "objc2-core-graphics", - "objc2-core-video", - "objc2-foundation 0.3.2", - "objc2-quartz-core 0.3.2", - "objc2-uniform-type-identifiers", - "objc2-user-notifications", - "parking_lot", - "raw-window-handle", - "scheduler", - "semver", - "smallvec", - "strum", - "uuid", -] - -[[package]] -name = "gpui_macros" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "gpui_platform" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "anyhow", - "console_error_panic_hook", - "gpui", - "gpui_apple", - "gpui_cpu_renderer", - "gpui_ios", - "gpui_linux", - "gpui_macos", - "gpui_web", - "gpui_wgpu", - "gpui_windows", - "log", -] - -[[package]] -name = "gpui_shared_string" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "schemars", - "serde", - "smol_str", -] - -[[package]] -name = "gpui_util" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "anyhow", - "log", - "which", -] - -[[package]] -name = "gpui_web" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "anyhow", - "async-channel", - "console_error_panic_hook", - "futures", - "gpui", - "gpui_wgpu", - "http_client", - "js-sys", - "log", - "parking_lot", - "raw-window-handle", - "scheduler", - "smallvec", - "unicode-properties", - "unicode-script", - "unicode-segmentation", - "uuid", - "wasm-bindgen", - "wasm-bindgen-futures", - "wasm_thread", - "web-sys", - "web-time", -] - -[[package]] -name = "gpui_wgpu" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "anyhow", - "ash", - "bytemuck", - "collections", - "cosmic-text", - "etagere", - "gpui", - "gpui_util", - "image", - "itertools 0.14.0", - "log", - "parking_lot", - "profiling", - "raw-window-handle", - "smallvec", - "swash", - "unicode-bidi", - "unicode-segmentation", - "web-sys", - "wgpu", - "zed-font-kit", -] - -[[package]] -name = "gpui_windows" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "accesskit", - "accesskit_windows", - "anyhow", - "collections", - "dunce", - "etagere", - "futures", - "gpui", - "gpui_util", - "image", - "itertools 0.14.0", - "log", - "parking_lot", - "rand 0.9.5", - "raw-window-handle", - "scheduler", - "smallvec", - "uuid", - "windows 0.62.2", - "windows-core 0.62.2", - "windows-numerics 0.3.1", - "windows-registry", -] - -[[package]] -name = "gtk" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a" -dependencies = [ - "atk", - "cairo-rs", - "field-offset", - "futures-channel", - "gdk", - "gdk-pixbuf", - "gio", - "glib", - "gtk-sys", - "gtk3-macros", - "libc", - "pango", - "pkg-config", -] - -[[package]] -name = "gtk-sys" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414" -dependencies = [ - "atk-sys", - "cairo-sys-rs", - "gdk-pixbuf-sys", - "gdk-sys", - "gio-sys", - "glib-sys", - "gobject-sys", - "libc", - "pango-sys", - "system-deps", -] - -[[package]] -name = "gtk3-macros" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d" -dependencies = [ - "proc-macro-crate 1.3.1", - "proc-macro-error", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "half" -version = "2.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" -dependencies = [ - "cfg-if", - "crunchy", - "num-traits", - "zerocopy", -] - -[[package]] -name = "harfrust" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9da2e5ae821f6e96664977bf974d6d6a2d6682f9ccee23e62ec1d134246845f9" -dependencies = [ - "bitflags 2.13.2", - "bytemuck", - "core_maths", - "read-fonts 0.37.0", - "smallvec", -] - -[[package]] -name = "hash32" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" -dependencies = [ - "byteorder", -] - -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" - -[[package]] -name = "hashbrown" -version = "0.15.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" -dependencies = [ - "allocator-api2", - "equivalent", - "foldhash 0.1.5", -] - -[[package]] -name = "hashbrown" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" -dependencies = [ - "allocator-api2", - "equivalent", - "foldhash 0.2.0", -] - -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" -dependencies = [ - "foldhash 0.2.0", -] - -[[package]] -name = "hdrhistogram" -version = "7.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "765c9198f173dd59ce26ff9f95ef0aafd0a0fe01fb9d72841bc5066a4c06511d" -dependencies = [ - "byteorder", - "num-traits", -] - -[[package]] -name = "heapless" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25ba4bd83f9415b58b4ed8dc5714c76e626a105be4646c02630ad730ad3b5aa4" -dependencies = [ - "hash32", - "stable_deref_trait", -] - -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "hermit-abi" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "hkdf" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" -dependencies = [ - "hmac", -] - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest", -] - -[[package]] -name = "http" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" -dependencies = [ - "bytes", - "itoa", -] - -[[package]] -name = "http-body" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" -dependencies = [ - "bytes", - "http", -] - -[[package]] -name = "http_client" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "anyhow", - "bytes", - "futures", - "http", - "http-body", - "log", - "parking_lot", - "serde", - "serde_json", - "serde_urlencoded", - "url", -] - -[[package]] -name = "httparse" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core 0.62.2", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "icu_collections" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" -dependencies = [ - "displaydoc", - "litemap", - "serde", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_locale_fallback" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" -dependencies = [ - "icu_locale_core", - "icu_locale_fallback_data", - "icu_provider", - "potential_utf", - "tinystr", - "zerovec", -] - -[[package]] -name = "icu_locale_fallback_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" - -[[package]] -name = "icu_normalizer" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" - -[[package]] -name = "icu_properties" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" -dependencies = [ - "displaydoc", - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" - -[[package]] -name = "icu_provider" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" -dependencies = [ - "displaydoc", - "icu_locale_core", - "serde", - "stable_deref_trait", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_segmenter" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" -dependencies = [ - "icu_collections", - "icu_locale_fallback", - "icu_provider", - "icu_segmenter_data", - "potential_utf", - "smallvec", - "utf8_iter", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_segmenter_data" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "image" -version = "0.25.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" -dependencies = [ - "bytemuck", - "byteorder-lite", - "color_quant", - "exr", - "gif", - "image-webp", - "moxcms", - "num-traits", - "png 0.18.1", - "qoi", - "ravif", - "rayon", - "rgb", - "tiff", - "zune-core", - "zune-jpeg", -] - -[[package]] -name = "image-webp" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" -dependencies = [ - "byteorder-lite", - "quick-error 2.0.1", -] - -[[package]] -name = "imagesize" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c" - -[[package]] -name = "imgref" -version = "1.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" - -[[package]] -name = "indexmap" -version = "2.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" -dependencies = [ - "equivalent", - "hashbrown 0.17.1", - "serde", - "serde_core", -] - -[[package]] -name = "inout" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" -dependencies = [ - "block-padding", - "generic-array", -] - -[[package]] -name = "interpolate_name" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "inventory" -version = "0.3.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c" -dependencies = [ - "rustversion", -] - -[[package]] -name = "is-docker" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" -dependencies = [ - "once_cell", -] - -[[package]] -name = "is-wsl" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" -dependencies = [ - "is-docker", - "once_cell", -] - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - -[[package]] -name = "itertools" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" -dependencies = [ - "either", -] - -[[package]] -name = "itertools" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" - -[[package]] -name = "jiff" -version = "0.2.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" -dependencies = [ - "jiff-core", - "jiff-static", - "log", - "portable-atomic", - "portable-atomic-util", - "serde_core", -] - -[[package]] -name = "jiff-core" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" -dependencies = [ - "log", -] - -[[package]] -name = "jiff-static" -version = "0.2.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" -dependencies = [ - "jiff-core", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "jni-sys" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" -dependencies = [ - "jni-sys 0.4.1", -] - -[[package]] -name = "jni-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" -dependencies = [ - "jni-sys-macros", -] - -[[package]] -name = "jni-sys-macros" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" -dependencies = [ - "quote", - "syn 2.0.119", -] - -[[package]] -name = "jobserver" -version = "0.1.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" -dependencies = [ - "getrandom 0.4.3", - "libc", -] - -[[package]] -name = "js-sys" -version = "0.3.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "keyboard-types" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a" -dependencies = [ - "bitflags 2.13.2", - "serde", - "unicode-segmentation", -] - -[[package]] -name = "keyboard-types" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" -dependencies = [ - "bitflags 2.13.2", - "serde", -] - -[[package]] -name = "khronos-egl" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" -dependencies = [ - "libc", - "libloading", - "pkg-config", -] - -[[package]] -name = "khronos_api" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" - -[[package]] -name = "ksni" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bcc1cb43797140f74b711f1c4a49f48a7a7429f211c5fb78264e7bcd1e99caf" -dependencies = [ - "arc-swap", - "async-executor", - "async-io", - "async-lock", - "crossbeam-queue", - "futures-channel", - "futures-lite", - "futures-util", - "pastey 0.2.3", - "serde", - "task-local", - "zbus 5.19.0", -] - -[[package]] -name = "kurbo" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" -dependencies = [ - "arrayvec", - "euclid", - "polycool", - "smallvec", -] - -[[package]] -name = "lazy_static" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" - -[[package]] -name = "lebe" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" - -[[package]] -name = "libc" -version = "0.2.191" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" - -[[package]] -name = "libfuzzer-sys" -version = "0.4.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" -dependencies = [ - "arbitrary", - "cc", -] - -[[package]] -name = "libloading" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" -dependencies = [ - "cfg-if", - "windows-link 0.2.1", -] - -[[package]] -name = "libm" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" - -[[package]] -name = "libredox" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" -dependencies = [ - "libc", -] - -[[package]] -name = "libxdo" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00333b8756a3d28e78def82067a377de7fa61b24909000aeaa2b446a948d14db" -dependencies = [ - "libxdo-sys", -] - -[[package]] -name = "libxdo-sys" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db23b9e7e2b7831bbd8aac0bbeeeb7b68cbebc162b227e7052e8e55829a09212" -dependencies = [ - "libc", - "x11", -] - -[[package]] -name = "linebender_resource_handle" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" - -[[package]] -name = "link-cplusplus" -version = "1.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82" -dependencies = [ - "cc", -] - -[[package]] -name = "link-section" -version = "0.19.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d9aae57673c1a235149777a74d152f3210ebd3e3b13346d2cdb6809e566bd3c" - -[[package]] -name = "linktime-proc-macro" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e57c38c1e860fd37c604281cdfb1dd2216977fd76a50f85ba2f388ef3219616" - -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - -[[package]] -name = "litemap" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" - -[[package]] -name = "litrs" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" - -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" -dependencies = [ - "serde_core", -] - -[[package]] -name = "loop9" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" -dependencies = [ - "imgref", -] - -[[package]] -name = "lyon" -version = "1.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd0578bdecb7d6d88987b8b2b1e3a4e2f81df9d0ece1078623324a567904e7b7" -dependencies = [ - "lyon_algorithms", - "lyon_tessellation", -] - -[[package]] -name = "lyon_algorithms" -version = "1.0.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3a6b9d4e8b48acd531fbf1241ad9b270df6e60b6b92bdea1469f4f40899d805" -dependencies = [ - "lyon_path", - "num-traits", -] - -[[package]] -name = "lyon_geom" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d82dd26aa4dc0b5b70b9115de59824842bcb43cf4a28e1b1e6d0ad148c93f93e" -dependencies = [ - "arrayvec", - "euclid", - "num-traits", -] - -[[package]] -name = "lyon_path" -version = "1.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c463f9c428b7fc5ec885dcd39ce4aa61e29111d0e33483f6f98c74e89d8621e" -dependencies = [ - "lyon_geom", - "num-traits", -] - -[[package]] -name = "lyon_tessellation" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd4872650e70dc907dd4f7ebc449d7d657a0d2658e423b2e724970870bbbf75b" -dependencies = [ - "float_next_after", - "lyon_path", - "num-traits", -] - -[[package]] -name = "mac-notification-sys" -version = "0.6.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca" -dependencies = [ - "cc", - "log", - "objc2 0.6.5", - "objc2-foundation 0.3.2", - "time", - "uuid", -] - -[[package]] -name = "mach2" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b" - -[[package]] -name = "macro_rules_attribute" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3ae8f6d608c795738406608304d30a2dfbdc8e58e44f7ba43236da5208ded3c" -dependencies = [ - "macro_rules_attribute-proc_macro", - "pastey 0.2.3", -] - -[[package]] -name = "macro_rules_attribute-proc_macro" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c" - -[[package]] -name = "malloc_buf" -version = "0.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" -dependencies = [ - "libc", -] - -[[package]] -name = "maybe-rayon" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" -dependencies = [ - "cfg-if", - "rayon", -] - -[[package]] -name = "md-5" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" -dependencies = [ - "cfg-if", - "digest", -] - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "memmap2" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" -dependencies = [ - "libc", -] - -[[package]] -name = "memoffset" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" -dependencies = [ - "autocfg", -] - -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "moxcms" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" -dependencies = [ - "num-traits", - "pxfm", -] - -[[package]] -name = "muda" -version = "0.15.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdae9c00e61cc0579bcac625e8ad22104c60548a025bfc972dc83868a28e1484" -dependencies = [ - "crossbeam-channel", - "dpi", - "gtk", - "keyboard-types 0.7.0", - "libxdo", - "objc2 0.5.3", - "objc2-app-kit 0.2.2", - "objc2-foundation 0.2.2", - "once_cell", - "png 0.17.16", - "thiserror 1.0.69", - "windows-sys 0.59.0", -] - -[[package]] -name = "muda" -version = "0.21.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4340e89c178916e62879c5c36b7f699019369be413e496178a6983ce91b8bc03" -dependencies = [ - "crossbeam-channel", - "dpi", - "keyboard-types 0.8.3", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", - "objc2-core-foundation", - "objc2-foundation 0.3.2", - "png 0.18.1", - "thiserror 2.0.21", - "windows-sys 0.61.2", -] - -[[package]] -name = "multiversion" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" -dependencies = [ - "multiversion-macros", - "target-features", -] - -[[package]] -name = "multiversion-macros" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", - "target-features", -] - -[[package]] -name = "multiversion_no_op" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" - -[[package]] -name = "naga" -version = "30.0.0" -source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" -dependencies = [ - "arrayvec", - "bit-set", - "bitflags 2.13.2", - "cfg-if", - "cfg_aliases", - "codespan-reporting", - "half", - "hashbrown 0.17.1", - "indexmap", - "libm", - "log", - "naga-types", - "num-traits", - "once_cell", - "rustc-hash 1.1.0", - "spirv", - "thiserror 2.0.21", - "unicode-ident", -] - -[[package]] -name = "naga-types" -version = "30.0.0" -source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" -dependencies = [ - "hashbrown 0.17.1", - "indexmap", - "rustc-hash 1.1.0", - "thiserror 2.0.21", -] - -[[package]] -name = "ndk-sys" -version = "0.6.0+11769913" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" -dependencies = [ - "jni-sys 0.3.1", -] - -[[package]] -name = "new_debug_unreachable" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" - -[[package]] -name = "no_std_io2" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003" -dependencies = [ - "memchr", -] - -[[package]] -name = "nom" -version = "8.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" -dependencies = [ - "memchr", -] - -[[package]] -name = "noop_proc_macro" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" - -[[package]] -name = "notify-rust" -version = "4.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57da5b5d3b7809bf71858da5a2818c3404ca4688c02c8abecdda0fcdec235df3" -dependencies = [ - "futures-lite", - "log", - "mac-notification-sys", - "serde", - "tauri-winrt-notification", - "zbus 6.3.0", -] - -[[package]] -name = "ntapi" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" -dependencies = [ - "winapi", -] - -[[package]] -name = "num" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" -dependencies = [ - "num-bigint", - "num-complex", - "num-integer", - "num-iter", - "num-rational", - "num-traits", -] - -[[package]] -name = "num-bigint" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" -dependencies = [ - "num-integer", - "num-traits", -] - -[[package]] -name = "num-bigint-dig" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7f9a86e097b0d187ad0e65667c2f58b9254671e86e7dbb78036b16692eae099" -dependencies = [ - "libm", - "num-integer", - "num-iter", - "num-traits", - "once_cell", - "rand 0.9.5", - "serde", - "smallvec", - "zeroize", -] - -[[package]] -name = "num-complex" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" -dependencies = [ - "num-traits", -] - -[[package]] -name = "num-conv" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" - -[[package]] -name = "num-derive" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "num-integer" -version = "0.1.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" -dependencies = [ - "num-traits", -] - -[[package]] -name = "num-iter" -version = "0.1.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" -dependencies = [ - "num-integer", - "num-traits", -] - -[[package]] -name = "num-rational" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" -dependencies = [ - "num-bigint", - "num-integer", - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", - "libm", -] - -[[package]] -name = "num_cpus" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "objc" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" -dependencies = [ - "malloc_buf", - "objc_exception", -] - -[[package]] -name = "objc-foundation" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9" -dependencies = [ - "block", - "objc", - "objc_id", -] - -[[package]] -name = "objc-sys" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" - -[[package]] -name = "objc2" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" -dependencies = [ - "objc-sys", - "objc2-encode", -] - -[[package]] -name = "objc2" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" -dependencies = [ - "objc2-encode", -] - -[[package]] -name = "objc2-app-kit" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" -dependencies = [ - "bitflags 2.13.2", - "block2 0.5.1", - "libc", - "objc2 0.5.3", - "objc2-core-data", - "objc2-core-image", - "objc2-foundation 0.2.2", - "objc2-quartz-core 0.2.2", -] - -[[package]] -name = "objc2-app-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" -dependencies = [ - "bitflags 2.13.2", - "block2 0.6.2", - "objc2 0.6.5", - "objc2-core-foundation", - "objc2-foundation 0.3.2", - "objc2-uniform-type-identifiers", -] - -[[package]] -name = "objc2-core-data" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" -dependencies = [ - "bitflags 2.13.2", - "block2 0.5.1", - "objc2 0.5.3", - "objc2-foundation 0.2.2", -] - -[[package]] -name = "objc2-core-foundation" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" -dependencies = [ - "bitflags 2.13.2", - "block2 0.6.2", - "dispatch2", - "libc", - "objc2 0.6.5", -] - -[[package]] -name = "objc2-core-graphics" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" -dependencies = [ - "bitflags 2.13.2", - "dispatch2", - "objc2 0.6.5", - "objc2-core-foundation", - "objc2-io-surface", -] - -[[package]] -name = "objc2-core-image" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" -dependencies = [ - "block2 0.5.1", - "objc2 0.5.3", - "objc2-foundation 0.2.2", - "objc2-metal 0.2.2", -] - -[[package]] -name = "objc2-core-text" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" -dependencies = [ - "bitflags 2.13.2", - "objc2-core-foundation", -] - -[[package]] -name = "objc2-core-video" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" -dependencies = [ - "bitflags 2.13.2", - "objc2 0.6.5", - "objc2-core-foundation", - "objc2-core-graphics", - "objc2-io-surface", - "objc2-metal 0.3.2", -] - -[[package]] -name = "objc2-encode" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" - -[[package]] -name = "objc2-foundation" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" -dependencies = [ - "bitflags 2.13.2", - "block2 0.5.1", - "libc", - "objc2 0.5.3", -] - -[[package]] -name = "objc2-foundation" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" -dependencies = [ - "bitflags 2.13.2", - "block2 0.6.2", - "libc", - "objc2 0.6.5", - "objc2-core-foundation", -] - -[[package]] -name = "objc2-io-surface" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" -dependencies = [ - "bitflags 2.13.2", - "objc2 0.6.5", - "objc2-core-foundation", -] - -[[package]] -name = "objc2-metal" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" -dependencies = [ - "bitflags 2.13.2", - "block2 0.5.1", - "objc2 0.5.3", - "objc2-foundation 0.2.2", -] - -[[package]] -name = "objc2-metal" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" -dependencies = [ - "bitflags 2.13.2", - "block2 0.6.2", - "dispatch2", - "objc2 0.6.5", - "objc2-foundation 0.3.2", -] - -[[package]] -name = "objc2-quartz-core" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" -dependencies = [ - "bitflags 2.13.2", - "block2 0.5.1", - "objc2 0.5.3", - "objc2-foundation 0.2.2", - "objc2-metal 0.2.2", -] - -[[package]] -name = "objc2-quartz-core" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" -dependencies = [ - "bitflags 2.13.2", - "objc2 0.6.5", - "objc2-core-foundation", - "objc2-core-graphics", - "objc2-foundation 0.3.2", - "objc2-metal 0.3.2", -] - -[[package]] -name = "objc2-security" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a" -dependencies = [ - "objc2-core-foundation", -] - -[[package]] -name = "objc2-ui-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" -dependencies = [ - "bitflags 2.13.2", - "block2 0.6.2", - "objc2 0.6.5", - "objc2-core-foundation", - "objc2-foundation 0.3.2", - "objc2-quartz-core 0.3.2", -] - -[[package]] -name = "objc2-uniform-type-identifiers" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7902ac02859fc1f7045f8b598c63f1ae0cc7efeaa06a9bc9f3d9a3c955974fa4" -dependencies = [ - "objc2 0.6.5", - "objc2-foundation 0.3.2", -] - -[[package]] -name = "objc2-user-notifications" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e" -dependencies = [ - "bitflags 2.13.2", - "block2 0.6.2", - "objc2 0.6.5", - "objc2-foundation 0.3.2", -] - -[[package]] -name = "objc_exception" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad970fb455818ad6cba4c122ad012fae53ae8b4795f86378bce65e4f6bab2ca4" -dependencies = [ - "cc", -] - -[[package]] -name = "objc_id" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c92d4ddb4bd7b50d730c215ff871754d0da6b2178849f8a2a2ab69712d0c073b" -dependencies = [ - "objc", -] - -[[package]] -name = "object" -version = "0.40.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" -dependencies = [ - "memchr", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - -[[package]] -name = "oo7" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78f2bfed90f1618b4b48dcad9307f25e14ae894e2949642c87c351601d62cebd" -dependencies = [ - "aes", - "ashpd", - "async-fs", - "async-io", - "async-lock", - "blocking", - "cbc", - "cipher", - "digest", - "endi", - "futures-lite", - "futures-util", - "getrandom 0.4.3", - "hkdf", - "hmac", - "md-5", - "num", - "num-bigint-dig", - "pbkdf2", - "serde", - "serde_bytes", - "sha2", - "subtle", - "zbus 5.19.0", - "zbus_macros 5.19.0", - "zeroize", - "zvariant", -] - -[[package]] -name = "oorandom" -version = "11.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" - -[[package]] -name = "open" -version = "5.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95" -dependencies = [ - "is-wsl", - "libc", -] - -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - -[[package]] -name = "ordered-float" -version = "5.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" -dependencies = [ - "num-traits", -] - -[[package]] -name = "ordered-stream" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" -dependencies = [ - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "page_size" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "pango" -version = "0.18.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" -dependencies = [ - "gio", - "glib", - "libc", - "once_cell", - "pango-sys", -] - -[[package]] -name = "pango-sys" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" -dependencies = [ - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - -[[package]] -name = "parking" -version = "2.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" - -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-link 0.2.1", -] - -[[package]] -name = "paste" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" - -[[package]] -name = "pastey" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" - -[[package]] -name = "pastey" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" - -[[package]] -name = "pathfinder_geometry" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b7e7b4ea703700ce73ebf128e1450eb69c3a8329199ffbfb9b2a0418e5ad3" -dependencies = [ - "log", - "pathfinder_simd", -] - -[[package]] -name = "pathfinder_simd" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4500030c302e4af1d423f36f3b958d1aecb6c04184356ed5a833bf6b60435777" -dependencies = [ - "rustc_version", -] - -[[package]] -name = "pbkdf2" -version = "0.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" -dependencies = [ - "digest", - "hmac", -] - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "perf-event-data" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "575828d9d7d205188048eb1508560607a03d21eafdbba47b8cade1736c1c28e1" -dependencies = [ - "bitflags 2.13.2", - "c-enum", - "perf-event-open-sys2", -] - -[[package]] -name = "perf-event-open-sys2" -version = "5.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c25955321465255e437600b54296983fab1feac2cd0c38958adeb26dbae49e" -dependencies = [ - "libc", - "memoffset", -] - -[[package]] -name = "perf-event2" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0939b8fad77dfaeb29ebbd35faaeaadbf833167f30975f1b8993bbba09ea0a0f" -dependencies = [ - "bitflags 2.13.2", - "c-enum", - "libc", - "memmap2", - "perf-event-data", - "perf-event-open-sys2", -] - -[[package]] -name = "phf" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" -dependencies = [ - "phf_macros", - "phf_shared", - "serde", -] - -[[package]] -name = "phf_generator" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" -dependencies = [ - "fastrand", - "phf_shared", -] - -[[package]] -name = "phf_macros" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "phf_shared" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pico-args" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" - -[[package]] -name = "pin-project" -version = "1.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "piper" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" -dependencies = [ - "atomic-waker", - "fastrand", - "futures-io", -] - -[[package]] -name = "pkg-config" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" - -[[package]] -name = "plotters" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" -dependencies = [ - "num-traits", - "plotters-backend", - "plotters-svg", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "plotters-backend" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" - -[[package]] -name = "plotters-svg" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" -dependencies = [ - "plotters-backend", -] - -[[package]] -name = "png" -version = "0.17.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" -dependencies = [ - "bitflags 1.3.2", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide 0.8.9", -] - -[[package]] -name = "png" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" -dependencies = [ - "bitflags 2.13.2", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide 0.8.9", -] - -[[package]] -name = "polling" -version = "3.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" -dependencies = [ - "cfg-if", - "concurrent-queue", - "hermit-abi", - "pin-project-lite", - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "pollster" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7" - -[[package]] -name = "pollster" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" - -[[package]] -name = "polycool" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" -dependencies = [ - "arrayvec", -] - -[[package]] -name = "portable-atomic" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" - -[[package]] -name = "portable-atomic-util" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" -dependencies = [ - "portable-atomic", -] - -[[package]] -name = "postage" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af3fb618632874fb76937c2361a7f22afd393c982a2165595407edc75b06d3c1" -dependencies = [ - "atomic", - "crossbeam-queue", - "parking_lot", - "pin-project", - "pollster 0.2.5", - "static_assertions", - "thiserror 1.0.69", -] - -[[package]] -name = "potential_utf" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" -dependencies = [ - "serde_core", - "writeable", - "zerovec", -] - -[[package]] -name = "powerfmt" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" - -[[package]] -name = "ppv-lite86" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - -[[package]] -name = "presser" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" - -[[package]] -name = "proc-macro-crate" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" -dependencies = [ - "once_cell", - "toml_edit 0.19.15", -] - -[[package]] -name = "proc-macro-crate" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e8366a6159044a37876a2b9817124296703c586a5c92e2c53751fa06d8d43e8" -dependencies = [ - "toml_edit 0.20.7", -] - -[[package]] -name = "proc-macro-crate" -version = "3.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" -dependencies = [ - "toml_edit 0.25.19+spec-1.1.0", -] - -[[package]] -name = "proc-macro-error" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" -dependencies = [ - "proc-macro-error-attr", - "proc-macro2", - "quote", - "syn 1.0.109", - "version_check", -] - -[[package]] -name = "proc-macro-error-attr" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" -dependencies = [ - "proc-macro2", - "quote", - "version_check", -] - -[[package]] -name = "proc-macro2" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "profiling" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" -dependencies = [ - "profiling-procmacros", -] - -[[package]] -name = "profiling-procmacros" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" -dependencies = [ - "quote", - "syn 2.0.119", -] - -[[package]] -name = "proptest" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" -dependencies = [ - "bit-set", - "bit-vec", - "bitflags 2.13.2", - "chacha20", - "core_detect", - "num-traits", - "proptest-macro", - "rand 0.10.4", - "rand_xorshift", - "regex-syntax", - "rusty-fork", - "tempfile", - "unarray", -] - -[[package]] -name = "proptest-macro" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e99782ea31698c2206c6887c1220d2f594b291c26cb9ec5b6d7cf175320bc212" -dependencies = [ - "convert_case 0.11.0", - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "pxfm" -version = "0.1.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" - -[[package]] -name = "qoi" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" -dependencies = [ - "bytemuck", -] - -[[package]] -name = "quick-error" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" - -[[package]] -name = "quick-error" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" - -[[package]] -name = "quick-xml" -version = "0.41.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" -dependencies = [ - "memchr", -] - -[[package]] -name = "quote" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - -[[package]] -name = "rand" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - -[[package]] -name = "rand" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" -dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.5", -] - -[[package]] -name = "rand" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" -dependencies = [ - "getrandom 0.4.3", - "rand_core 0.10.1", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.4", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.5", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.17", -] - -[[package]] -name = "rand_core" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom 0.3.4", -] - -[[package]] -name = "rand_core" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" - -[[package]] -name = "rand_xorshift" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" -dependencies = [ - "rand_core 0.10.1", -] - -[[package]] -name = "range-alloc" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" - -[[package]] -name = "rangemap" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" - -[[package]] -name = "rav1e" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" -dependencies = [ - "aligned-vec", - "arbitrary", - "arg_enum_proc_macro", - "arrayvec", - "av-scenechange", - "av1-grain", - "bitstream-io", - "built", - "cfg-if", - "interpolate_name", - "itertools 0.14.0", - "libc", - "libfuzzer-sys", - "log", - "maybe-rayon", - "new_debug_unreachable", - "noop_proc_macro", - "num-derive", - "num-traits", - "paste", - "profiling", - "rand 0.9.5", - "rand_chacha 0.9.0", - "simd_helpers", - "thiserror 2.0.21", - "v_frame", - "wasm-bindgen", -] - -[[package]] -name = "ravif" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45" -dependencies = [ - "avif-serialize", - "imgref", - "loop9", - "quick-error 2.0.1", - "rav1e", - "rayon", - "rgb", -] - -[[package]] -name = "raw-window-handle" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" - -[[package]] -name = "raw-window-metal" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" -dependencies = [ - "objc2 0.6.5", - "objc2-core-foundation", - "objc2-foundation 0.3.2", - "objc2-quartz-core 0.3.2", -] - -[[package]] -name = "rayon" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" -dependencies = [ - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", -] - -[[package]] -name = "react-native-gpui" -version = "0.1.0" -dependencies = [ - "anyhow", - "async-channel", - "base64", - "block", - "cocoa", - "cxx", - "env_logger", - "fontdue", - "futures", - "global-hotkey", - "gpui", - "gpui_platform", - "http_client", - "image", - "libc", - "log", - "muda 0.15.3", - "objc", - "raw-window-handle", - "rn-gpui-module", - "rn-gpui-module-build", - "rn-gpui-sys", - "serde_json", - "sys-locale", - "tray-icon", - "tungstenite", - "windows 0.62.2", - "windows-sys 0.59.0", - "x11-dl", - "zbus 5.19.0", -] - -[[package]] -name = "read-fonts" -version = "0.37.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b634fabf032fab15307ffd272149b622260f55974d9fad689292a5d33df02e5" -dependencies = [ - "bytemuck", - "core_maths", - "font-types 0.11.3", -] - -[[package]] -name = "read-fonts" -version = "0.41.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" -dependencies = [ - "bytemuck", - "font-types 0.12.7", - "once_cell", -] - -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags 2.13.2", -] - -[[package]] -name = "redox_users" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" -dependencies = [ - "libredox", - "thiserror 2.0.21", -] - -[[package]] -name = "ref-cast" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" -dependencies = [ - "ref-cast-impl", -] - -[[package]] -name = "ref-cast-impl" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "refineable" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "derive_refineable", -] - -[[package]] -name = "regex" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" - -[[package]] -name = "renderdoc-sys" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" - -[[package]] -name = "resvg" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b563218631706d614e23059436526d005b50ab5f2d506b55a17eb65c5eb83419" -dependencies = [ - "gif", - "image-webp", - "log", - "pico-args", - "rgb", - "svgtypes", - "tiny-skia", - "usvg", - "zune-jpeg", -] - -[[package]] -name = "rgb" -version = "0.8.53" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" -dependencies = [ - "bytemuck", -] - -[[package]] -name = "rn-gpui-module" -version = "0.1.0" -dependencies = [ - "futures", -] - -[[package]] -name = "rn-gpui-module-build" -version = "0.1.0" - -[[package]] -name = "rn-gpui-module-generated-test" -version = "0.1.0" -dependencies = [ - "futures", - "rn-gpui-module", - "rn-gpui-module-build", -] - -[[package]] -name = "rn-gpui-sys" -version = "0.1.0" -dependencies = [ - "cmake", - "cxx", - "cxx-build", - "log", - "rn-gpui-module", - "serde_json", -] - -[[package]] -name = "roxmltree" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" - -[[package]] -name = "roxmltree" -version = "0.21.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" -dependencies = [ - "memchr", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - -[[package]] -name = "rustc-hash" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" - -[[package]] -name = "rustc_version" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" -dependencies = [ - "semver", -] - -[[package]] -name = "rustix" -version = "1.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" -dependencies = [ - "bitflags 2.13.2", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.59.0", -] - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "rusty-fork" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" -dependencies = [ - "fnv", - "quick-error 1.2.3", - "tempfile", - "wait-timeout", -] - -[[package]] -name = "rustybuzz" -version = "0.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702" -dependencies = [ - "bitflags 2.13.2", - "bytemuck", - "core_maths", - "log", - "smallvec", - "ttf-parser", - "unicode-bidi-mirroring", - "unicode-ccc", - "unicode-properties", - "unicode-script", -] - -[[package]] -name = "ryu" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" - -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "scheduler" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "async-task", - "backtrace", - "chrono", - "flume", - "futures", - "parking_lot", - "rand 0.9.5", - "wasm_thread", - "web-time", -] - -[[package]] -name = "schemars" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" -dependencies = [ - "dyn-clone", - "indexmap", - "ref-cast", - "schemars_derive", - "serde", - "serde_json", -] - -[[package]] -name = "schemars_derive" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" -dependencies = [ - "proc-macro2", - "quote", - "serde_derive_internals", - "syn 3.0.10", -] - -[[package]] -name = "scoped-tls" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "scratch" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2" - -[[package]] -name = "screencapturekit" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a5eeeb57ac94960cfe5ff4c402be6585ae4c8d29a2cf41b276048c2e849d64e" -dependencies = [ - "screencapturekit-sys", -] - -[[package]] -name = "screencapturekit-sys" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22411b57f7d49e7fe08025198813ee6fd65e1ee5eff4ebc7880c12c82bde4c60" -dependencies = [ - "block", - "dispatch", - "objc", - "objc-foundation", - "objc_id", - "once_cell", -] - -[[package]] -name = "seahash" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" - -[[package]] -name = "self_cell" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" -dependencies = [ - "serde", - "serde_core", -] - -[[package]] -name = "serde" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_bytes" -version = "0.11.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" -dependencies = [ - "serde", - "serde_core", -] - -[[package]] -name = "serde_core" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "serde_derive_internals" -version = "0.30.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "foldhash 0.2.0", - "indexmap", - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_repr" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "serde_spanned" -version = "0.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" -dependencies = [ - "serde", -] - -[[package]] -name = "serde_spanned" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" -dependencies = [ - "serde_core", -] - -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "sha1" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest", -] - -[[package]] -name = "sha1_smol" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest", -] - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "signal-hook-registry" -version = "1.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" -dependencies = [ - "errno", - "libc", -] - -[[package]] -name = "simd-adler32" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" - -[[package]] -name = "simd_helpers" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" -dependencies = [ - "quote", -] - -[[package]] -name = "simdutf8" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" - -[[package]] -name = "simplecss" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" -dependencies = [ - "log", -] - -[[package]] -name = "siphasher" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" - -[[package]] -name = "skrifa" -version = "0.40.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fbdfe3d2475fbd7ddd1f3e5cf8288a30eb3e5f95832829570cd88115a7434ac" -dependencies = [ - "bytemuck", - "read-fonts 0.37.0", -] - -[[package]] -name = "skrifa" -version = "0.44.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" -dependencies = [ - "bytemuck", - "read-fonts 0.41.0", -] - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "slotmap" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" -dependencies = [ - "version_check", -] - -[[package]] -name = "smallvec" -version = "1.16.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" - -[[package]] -name = "smol" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a33bd3e260892199c3ccfc487c88b2da2265080acb316cd920da72fdfd7c599f" -dependencies = [ - "async-channel", - "async-executor", - "async-fs", - "async-io", - "async-lock", - "async-net", - "async-process", - "blocking", - "futures-lite", -] - -[[package]] -name = "smol_str" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eeb7109d23f319619d4cc0de5464613c8b7b1a09db2774a58101459cf6be2f10" -dependencies = [ - "serde_core", -] - -[[package]] -name = "socket2" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "spin" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" -dependencies = [ - "lock_api", -] - -[[package]] -name = "spin" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" -dependencies = [ - "lock_api", -] - -[[package]] -name = "spirv" -version = "0.4.0+sdk-1.4.341.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" -dependencies = [ - "bitflags 2.13.2", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "static_assertions" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" - -[[package]] -name = "strict-num" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" -dependencies = [ - "float-cmp", -] - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "strum" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" -dependencies = [ - "strum_macros", -] - -[[package]] -name = "strum_macros" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - -[[package]] -name = "sum_tree" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "heapless", - "rayon", - "tracing", - "ztracing", -] - -[[package]] -name = "svg_fmt" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0193cc4331cfd2f3d2011ef287590868599a2f33c3e69bc22c1a3d3acf9e02fb" - -[[package]] -name = "svgtypes" -version = "0.16.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e" -dependencies = [ - "kurbo", - "siphasher", -] - -[[package]] -name = "swash" -version = "0.2.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e" -dependencies = [ - "skrifa 0.44.0", - "yazi", - "zeno", -] - -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "2.0.119" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "synstructure" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "sys-locale" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" -dependencies = [ - "libc", -] - -[[package]] -name = "sysinfo" -version = "0.31.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "355dbe4f8799b304b05e1b0f05fc59b2a18d36645cf169607da45bde2f69a1be" -dependencies = [ - "core-foundation-sys", - "libc", - "memchr", - "ntapi", - "rayon", - "windows 0.57.0", -] - -[[package]] -name = "system-deps" -version = "6.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" -dependencies = [ - "cfg-expr", - "heck 0.5.0", - "pkg-config", - "toml 0.8.23", - "version-compare", -] - -[[package]] -name = "taffy" -version = "0.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c8480887e8803986d96a7173729565520d4bbb721ad6b7ad6941a22897207aa" -dependencies = [ - "serde", - "slotmap", - "smallvec", -] - -[[package]] -name = "tao-core-video-sys" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "271450eb289cb4d8d0720c6ce70c72c8c858c93dd61fc625881616752e6b98f6" -dependencies = [ - "cfg-if", - "core-foundation-sys", - "libc", - "objc", -] - -[[package]] -name = "target-features" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" - -[[package]] -name = "target-lexicon" -version = "0.12.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" - -[[package]] -name = "task-local" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2972044a9e5e448a506a7ff6f0d03b566d8ef4cd6918a58fc59835a0f8666626" -dependencies = [ - "pin-project-lite", -] - -[[package]] -name = "tauri-winrt-notification" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f37a6c354fd28fc9e322ed9bd47e3959576dad28c9d58ea1cf888cce1c7ccb36" -dependencies = [ - "thiserror 2.0.21", - "windows 0.62.2", - "windows-version", -] - -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom 0.4.3", - "once_cell", - "rustix", - "windows-sys 0.59.0", -] - -[[package]] -name = "termcolor" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl 1.0.69", -] - -[[package]] -name = "thiserror" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" -dependencies = [ - "thiserror-impl 2.0.21", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "tiff" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" -dependencies = [ - "fax", - "flate2", - "half", - "quick-error 2.0.1", - "weezl", - "zune-jpeg", -] - -[[package]] -name = "time" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" -dependencies = [ - "deranged", - "num-conv", - "powerfmt", - "serde_core", - "time-core", -] - -[[package]] -name = "time-core" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" - -[[package]] -name = "tiny-keccak" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" -dependencies = [ - "crunchy", -] - -[[package]] -name = "tiny-skia" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" -dependencies = [ - "arrayref", - "arrayvec", - "bytemuck", - "cfg-if", - "log", - "png 0.17.16", - "tiny-skia-path", -] - -[[package]] -name = "tiny-skia-path" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" -dependencies = [ - "arrayref", - "bytemuck", - "strict-num", -] - -[[package]] -name = "tinystr" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" -dependencies = [ - "displaydoc", - "serde_core", - "zerovec", -] - -[[package]] -name = "tinytemplate" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "tinyvec" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" - -[[package]] -name = "tokio" -version = "1.54.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" -dependencies = [ - "pin-project-lite", -] - -[[package]] -name = "toml" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" -dependencies = [ - "serde", - "serde_spanned 0.6.9", - "toml_datetime 0.6.11", - "toml_edit 0.22.27", -] - -[[package]] -name = "toml" -version = "1.2.1+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" -dependencies = [ - "indexmap", - "serde_core", - "serde_spanned 1.1.3", - "toml_datetime 1.1.3+spec-1.1.0", - "toml_parser", - "toml_writer", - "winnow 1.0.5", -] - -[[package]] -name = "toml_datetime" -version = "0.6.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" -dependencies = [ - "serde", -] - -[[package]] -name = "toml_datetime" -version = "1.1.3+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" -dependencies = [ - "serde_core", -] - -[[package]] -name = "toml_edit" -version = "0.19.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" -dependencies = [ - "indexmap", - "toml_datetime 0.6.11", - "winnow 0.5.40", -] - -[[package]] -name = "toml_edit" -version = "0.20.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81" -dependencies = [ - "indexmap", - "toml_datetime 0.6.11", - "winnow 0.5.40", -] - -[[package]] -name = "toml_edit" -version = "0.22.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" -dependencies = [ - "indexmap", - "serde", - "serde_spanned 0.6.9", - "toml_datetime 0.6.11", - "toml_write", - "winnow 0.7.15", -] - -[[package]] -name = "toml_edit" -version = "0.25.19+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" -dependencies = [ - "indexmap", - "toml_datetime 1.1.3+spec-1.1.0", - "toml_parser", - "winnow 1.0.5", -] - -[[package]] -name = "toml_parser" -version = "1.1.5+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" -dependencies = [ - "winnow 1.0.5", -] - -[[package]] -name = "toml_write" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" - -[[package]] -name = "toml_writer" -version = "1.2.0+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" - -[[package]] -name = "tracing" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" -dependencies = [ - "log", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "tracing-core" -version = "0.1.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" -dependencies = [ - "once_cell", -] - -[[package]] -name = "tray-icon" -version = "0.26.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f5cc5858ecf9574ddd8f0032a2ff7ffd6f7724d2b81e48b9374984b3fd6ddc9" -dependencies = [ - "crossbeam-channel", - "ksni", - "muda 0.21.2", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", - "objc2-core-foundation", - "objc2-core-graphics", - "objc2-foundation 0.3.2", - "once_cell", - "png 0.18.1", - "thiserror 2.0.21", - "windows-sys 0.61.2", -] - -[[package]] -name = "ttf-parser" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" -dependencies = [ - "core_maths", -] - -[[package]] -name = "tungstenite" -version = "0.26.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13" -dependencies = [ - "bytes", - "data-encoding", - "http", - "httparse", - "log", - "rand 0.9.5", - "sha1", - "thiserror 2.0.21", - "utf-8", -] - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "uds_windows" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" -dependencies = [ - "memoffset", - "tempfile", - "windows-sys 0.61.2", -] - -[[package]] -name = "unarray" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" - -[[package]] -name = "unicode-bidi" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" - -[[package]] -name = "unicode-bidi-mirroring" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe" - -[[package]] -name = "unicode-ccc" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e" - -[[package]] -name = "unicode-ident" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" - -[[package]] -name = "unicode-linebreak" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" - -[[package]] -name = "unicode-properties" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e70f2a8b45122e719eb623c01822704c4e0907e7e426a05927e1a1cfff5b75d0" - -[[package]] -name = "unicode-script" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf" - -[[package]] -name = "unicode-segmentation" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" - -[[package]] -name = "unicode-vo" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" - -[[package]] -name = "unicode-width" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" - -[[package]] -name = "url" -version = "2.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "usvg" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e419dff010bb12512b0ae9e3d2f318dfbdf0167fde7eb05465134d4e8756076f" -dependencies = [ - "base64", - "data-url", - "flate2", - "fontdb", - "imagesize", - "kurbo", - "log", - "pico-args", - "roxmltree 0.21.2", - "rustybuzz", - "simplecss", - "siphasher", - "strict-num", - "svgtypes", - "tiny-skia-path", - "unicode-bidi", - "unicode-script", - "unicode-vo", - "xmlwriter", -] - -[[package]] -name = "utf-8" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" - -[[package]] -name = "utf8_iter" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" -dependencies = [ - "utf_types", -] - -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "utf_types" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" - -[[package]] -name = "uuid" -version = "1.29.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" -dependencies = [ - "getrandom 0.4.3", - "js-sys", - "serde_core", - "sha1_smol", - "wasm-bindgen", -] - -[[package]] -name = "v_frame" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" -dependencies = [ - "aligned-vec", - "num-traits", - "wasm-bindgen", -] - -[[package]] -name = "version-compare" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "vswhom" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" -dependencies = [ - "libc", - "vswhom-sys", -] - -[[package]] -name = "vswhom-sys" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150" -dependencies = [ - "cc", - "libc", -] - -[[package]] -name = "wait-timeout" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" -dependencies = [ - "libc", -] - -[[package]] -name = "waker-fn" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7" - -[[package]] -name = "walkdir" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" -dependencies = [ - "same-file", - "winapi-util", -] - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasip2" -version = "1.0.4+wasi-0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" -dependencies = [ - "wit-bindgen", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" -dependencies = [ - "cfg-if", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.80" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" -dependencies = [ - "js-sys", - "tokio", - "wasm-bindgen", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 3.0.10", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "wasm_thread" -version = "0.3.3" -source = "git+https://github.com/zed-industries/wasm_thread?rev=0cf96c7708dfb97ccf3da50347e25edcf75d6937#0cf96c7708dfb97ccf3da50347e25edcf75d6937" -dependencies = [ - "futures", - "js-sys", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "wayland-backend" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" -dependencies = [ - "cc", - "downcast-rs", - "log", - "rustix", - "scoped-tls", - "smallvec", - "wayland-sys", -] - -[[package]] -name = "wayland-client" -version = "0.31.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" -dependencies = [ - "bitflags 2.13.2", - "rustix", - "wayland-backend", - "wayland-scanner", -] - -[[package]] -name = "wayland-cursor" -version = "0.31.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" -dependencies = [ - "rustix", - "wayland-client", - "xcursor", -] - -[[package]] -name = "wayland-protocols" -version = "0.32.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" -dependencies = [ - "bitflags 2.13.2", - "wayland-backend", - "wayland-client", - "wayland-scanner", -] - -[[package]] -name = "wayland-protocols-plasma" -version = "0.3.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" -dependencies = [ - "bitflags 2.13.2", - "wayland-backend", - "wayland-client", - "wayland-protocols", - "wayland-scanner", -] - -[[package]] -name = "wayland-protocols-wlr" -version = "0.3.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" -dependencies = [ - "bitflags 2.13.2", - "wayland-backend", - "wayland-client", - "wayland-protocols", - "wayland-scanner", -] - -[[package]] -name = "wayland-scanner" -version = "0.31.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" -dependencies = [ - "proc-macro2", - "quick-xml", - "quote", -] - -[[package]] -name = "wayland-sys" -version = "0.31.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" -dependencies = [ - "dlib", - "log", - "once_cell", - "pkg-config", -] - -[[package]] -name = "web-sys" -version = "0.3.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "weezl" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" - -[[package]] -name = "wgpu" -version = "30.0.0" -source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" -dependencies = [ - "arrayvec", - "bitflags 2.13.2", - "bytemuck", - "cfg-if", - "cfg_aliases", - "document-features", - "hashbrown 0.17.1", - "js-sys", - "log", - "naga", - "profiling", - "raw-window-handle", - "smallvec", - "static_assertions", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "wgpu-core", - "wgpu-hal", - "wgpu-sync", - "wgpu-types", -] - -[[package]] -name = "wgpu-core" -version = "30.0.0" -source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" -dependencies = [ - "arrayvec", - "bit-set", - "bit-vec", - "bitflags 2.13.2", - "bytemuck", - "cfg_aliases", - "document-features", - "hashbrown 0.17.1", - "indexmap", - "log", - "naga", - "naga-types", - "num-traits", - "profiling", - "raw-window-handle", - "rustc-hash 1.1.0", - "scopeguard", - "smallvec", - "thiserror 2.0.21", - "wgpu-core-deps-apple", - "wgpu-core-deps-emscripten", - "wgpu-core-deps-linux-android-bsd", - "wgpu-core-deps-wasm", - "wgpu-core-deps-windows", - "wgpu-hal", - "wgpu-naga-bridge", - "wgpu-sync", - "wgpu-types", -] - -[[package]] -name = "wgpu-core-deps-apple" -version = "30.0.0" -source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" -dependencies = [ - "wgpu-hal", -] - -[[package]] -name = "wgpu-core-deps-emscripten" -version = "30.0.0" -source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" -dependencies = [ - "wgpu-hal", -] - -[[package]] -name = "wgpu-core-deps-linux-android-bsd" -version = "30.0.0" -source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" -dependencies = [ - "wgpu-hal", -] - -[[package]] -name = "wgpu-core-deps-wasm" -version = "30.0.0" -source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" -dependencies = [ - "wgpu-hal", -] - -[[package]] -name = "wgpu-core-deps-windows" -version = "30.0.0" -source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" -dependencies = [ - "wgpu-hal", -] - -[[package]] -name = "wgpu-hal" -version = "30.0.0" -source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" -dependencies = [ - "android_system_properties", - "arrayvec", - "ash", - "bit-set", - "bitflags 2.13.2", - "block2 0.6.2", - "bytemuck", - "cfg-if", - "cfg_aliases", - "glow", - "glutin_wgl_sys", - "gpu-allocator", - "hashbrown 0.17.1", - "js-sys", - "khronos-egl", - "libc", - "libloading", - "log", - "naga", - "naga-types", - "ndk-sys", - "objc2 0.6.5", - "objc2-core-foundation", - "objc2-core-graphics", - "objc2-foundation 0.3.2", - "objc2-metal 0.3.2", - "objc2-quartz-core 0.3.2", - "ordered-float", - "profiling", - "range-alloc", - "raw-window-handle", - "raw-window-metal", - "renderdoc-sys", - "smallvec", - "static_assertions", - "thiserror 2.0.21", - "wasm-bindgen", - "wayland-sys", - "web-sys", - "wgpu-naga-bridge", - "wgpu-sync", - "wgpu-types", - "windows 0.62.2", - "windows-core 0.62.2", - "windows-result 0.4.1", -] - -[[package]] -name = "wgpu-naga-bridge" -version = "30.0.0" -source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" -dependencies = [ - "naga", - "wgpu-types", -] - -[[package]] -name = "wgpu-sync" -version = "30.0.0" -source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" -dependencies = [ - "cfg-if", - "lock_api", - "once_cell", - "parking_lot", - "portable-atomic", - "portable-atomic-util", -] - -[[package]] -name = "wgpu-types" -version = "30.0.0" -source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" -dependencies = [ - "bitflags 2.13.2", - "bytemuck", - "js-sys", - "log", - "macro_rules_attribute", - "naga-types", - "raw-window-handle", - "static_assertions", - "web-sys", -] - -[[package]] -name = "which" -version = "8.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bae2f2b2b816647a1cab1acc91f5bd20812d53cb344382635ec2181940c8034f" -dependencies = [ - "libc", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" -dependencies = [ - "windows-sys 0.59.0", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows" -version = "0.57.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143" -dependencies = [ - "windows-core 0.57.0", - "windows-targets", -] - -[[package]] -name = "windows" -version = "0.61.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" -dependencies = [ - "windows-collections 0.2.0", - "windows-core 0.61.2", - "windows-future 0.2.1", - "windows-link 0.1.3", - "windows-numerics 0.2.0", -] - -[[package]] -name = "windows" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" -dependencies = [ - "windows-collections 0.3.2", - "windows-core 0.62.2", - "windows-future 0.3.2", - "windows-numerics 0.3.1", -] - -[[package]] -name = "windows-capture" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a4df73e95feddb9ec1a7e9c2ca6323b8c97d5eeeff78d28f1eccdf19c882b24" -dependencies = [ - "parking_lot", - "rayon", - "thiserror 2.0.21", - "windows 0.61.3", - "windows-future 0.2.1", -] - -[[package]] -name = "windows-collections" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" -dependencies = [ - "windows-core 0.61.2", -] - -[[package]] -name = "windows-collections" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" -dependencies = [ - "windows-core 0.62.2", -] - -[[package]] -name = "windows-core" -version = "0.57.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d" -dependencies = [ - "windows-implement 0.57.0", - "windows-interface 0.57.0", - "windows-result 0.1.2", - "windows-targets", -] - -[[package]] -name = "windows-core" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" -dependencies = [ - "windows-implement 0.60.2", - "windows-interface 0.59.3", - "windows-link 0.1.3", - "windows-result 0.3.4", - "windows-strings 0.4.2", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement 0.60.2", - "windows-interface 0.59.3", - "windows-link 0.2.1", - "windows-result 0.4.1", - "windows-strings 0.5.1", -] - -[[package]] -name = "windows-future" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" -dependencies = [ - "windows-core 0.61.2", - "windows-link 0.1.3", - "windows-threading 0.1.0", -] - -[[package]] -name = "windows-future" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" -dependencies = [ - "windows-core 0.62.2", - "windows-link 0.2.1", - "windows-threading 0.2.1", -] - -[[package]] -name = "windows-implement" -version = "0.57.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.57.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-link" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-numerics" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" -dependencies = [ - "windows-core 0.61.2", - "windows-link 0.1.3", -] - -[[package]] -name = "windows-numerics" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" -dependencies = [ - "windows-core 0.62.2", - "windows-link 0.2.1", -] - -[[package]] -name = "windows-registry" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" -dependencies = [ - "windows-link 0.2.1", - "windows-result 0.4.1", - "windows-strings 0.5.1", -] - -[[package]] -name = "windows-result" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-result" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" -dependencies = [ - "windows-link 0.1.3", -] - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link 0.2.1", -] - -[[package]] -name = "windows-strings" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" -dependencies = [ - "windows-link 0.1.3", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link 0.2.1", -] - -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link 0.2.1", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows-threading" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" -dependencies = [ - "windows-link 0.1.3", -] - -[[package]] -name = "windows-threading" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" -dependencies = [ - "windows-link 0.2.1", -] - -[[package]] -name = "windows-version" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631" -dependencies = [ - "windows-link 0.2.1", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "winnow" -version = "0.5.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" -dependencies = [ - "memchr", -] - -[[package]] -name = "winnow" -version = "0.7.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" -dependencies = [ - "memchr", -] - -[[package]] -name = "winnow" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" -dependencies = [ - "memchr", -] - -[[package]] -name = "winreg" -version = "0.56.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" -dependencies = [ - "cfg-if", - "windows-sys 0.59.0", -] - -[[package]] -name = "wio" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d129932f4644ac2396cb456385cbf9e63b5b30c6e8dc4820bdca4eb082037a5" -dependencies = [ - "winapi", -] - -[[package]] -name = "wit-bindgen" -version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" - -[[package]] -name = "writeable" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" - -[[package]] -name = "x11" -version = "2.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" -dependencies = [ - "libc", - "pkg-config", -] - -[[package]] -name = "x11-dl" -version = "2.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" -dependencies = [ - "libc", - "once_cell", - "pkg-config", -] - -[[package]] -name = "x11rb" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" -dependencies = [ - "as-raw-xcb-connection", - "gethostname", - "libc", - "rustix", - "x11rb-protocol", - "xcursor", -] - -[[package]] -name = "x11rb-protocol" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" - -[[package]] -name = "xcb" -version = "1.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566" -dependencies = [ - "bitflags 2.13.2", - "libc", - "quick-xml", - "x11", -] - -[[package]] -name = "xcursor" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" - -[[package]] -name = "xim-ctext" -version = "0.3.0" -source = "git+https://github.com/zed-industries/xim-rs.git?rev=16f35a2c881b815a2b6cdfd6687988e84f8447d8#16f35a2c881b815a2b6cdfd6687988e84f8447d8" -dependencies = [ - "encoding_rs", -] - -[[package]] -name = "xim-parser" -version = "0.2.1" -source = "git+https://github.com/zed-industries/xim-rs.git?rev=16f35a2c881b815a2b6cdfd6687988e84f8447d8#16f35a2c881b815a2b6cdfd6687988e84f8447d8" -dependencies = [ - "bitflags 2.13.2", -] - -[[package]] -name = "xkbcommon" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d66ca9352cbd4eecbbc40871d8a11b4ac8107cfc528a6e14d7c19c69d0e1ac9" -dependencies = [ - "as-raw-xcb-connection", - "libc", - "memmap2", - "xkeysym", -] - -[[package]] -name = "xkeysym" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" - -[[package]] -name = "xml-rs" -version = "0.8.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" - -[[package]] -name = "xmlwriter" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" - -[[package]] -name = "y4m" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" - -[[package]] -name = "yazi" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac366ea532fa8ee6a992cec9dea525b1dc284e69702f36c2ab5fbebadc81ec86" - -[[package]] -name = "yeslogic-fontconfig-sys" -version = "6.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d8b8abf912b9a29ff112e1671c97c33636903d13a69712037190e6805af4f76" -dependencies = [ - "dlib", - "once_cell", - "pkg-config", -] - -[[package]] -name = "yoke" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", - "synstructure", -] - -[[package]] -name = "zbus" -version = "5.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" -dependencies = [ - "async-broadcast", - "async-executor", - "async-io", - "async-lock", - "async-process", - "async-recursion", - "async-task", - "async-trait", - "blocking", - "enumflags2", - "event-listener", - "futures-core", - "futures-lite", - "hex", - "libc", - "ordered-stream", - "rustix", - "serde", - "serde_repr", - "tracing", - "uds_windows", - "uuid", - "windows-sys 0.61.2", - "winnow 1.0.5", - "zbus_macros 5.19.0", - "zbus_names", - "zvariant", -] - -[[package]] -name = "zbus" -version = "6.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b4aae740b23927ceabed962431abab2cdefb9f7f885e5bbab062da09bf580e4" -dependencies = [ - "async-trait", - "bitflags 2.13.2", - "endi", - "futures-core", - "hex", - "libc", - "ordered-stream", - "rustix", - "serde", - "serde_repr", - "socket2", - "uds_windows", - "uuid", - "windows-sys 0.61.2", - "winnow 1.0.5", - "zbus_macros 6.3.0", - "zbus_utils", - "zcheapstr", - "zruntime", -] - -[[package]] -name = "zbus-lockstep" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" -dependencies = [ - "zbus_xml", - "zvariant", -] - -[[package]] -name = "zbus-lockstep-macros" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", - "zbus-lockstep", - "zbus_xml", - "zvariant", -] - -[[package]] -name = "zbus_macros" -version = "5.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" -dependencies = [ - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 3.0.10", - "zbus_names", - "zvariant", - "zvariant_utils", -] - -[[package]] -name = "zbus_macros" -version = "6.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37c9dd4beaf145c16fcb2902862f50da86e54aed13dd368ddf64a1d17e6b8529" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", - "zbus_utils", -] - -[[package]] -name = "zbus_names" -version = "4.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" -dependencies = [ - "serde", - "winnow 1.0.5", - "zvariant", -] - -[[package]] -name = "zbus_utils" -version = "6.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7" -dependencies = [ - "proc-macro2", - "quote", - "serde", - "syn 3.0.10", - "winnow 1.0.5", -] - -[[package]] -name = "zbus_xml" -version = "5.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" -dependencies = [ - "serde", - "winnow 1.0.5", - "zbus_names", - "zvariant", -] - -[[package]] -name = "zcheapstr" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920" -dependencies = [ - "serde", -] - -[[package]] -name = "zed-font-kit" -version = "0.14.1-zed" -source = "git+https://github.com/zed-industries/font-kit?rev=94b0f28166665e8fd2f53ff6d268a14955c82269#94b0f28166665e8fd2f53ff6d268a14955c82269" -dependencies = [ - "bitflags 2.13.2", - "byteorder", - "core-foundation 0.10.1", - "core-graphics 0.24.0", - "core-text", - "dirs", - "dwrote", - "float-ord", - "freetype-sys", - "lazy_static", - "libc", - "log", - "pathfinder_geometry", - "pathfinder_simd", - "walkdir", - "winapi", - "yeslogic-fontconfig-sys", -] - -[[package]] -name = "zed-scap" -version = "0.0.8-zed" -source = "git+https://github.com/zed-industries/scap?rev=4afea48c3b002197176fb19cd0f9b180dd36eaac#4afea48c3b002197176fb19cd0f9b180dd36eaac" -dependencies = [ - "anyhow", - "cocoa", - "core-graphics-helmer-fork", - "log", - "objc", - "rand 0.8.8", - "screencapturekit", - "screencapturekit-sys", - "sysinfo", - "tao-core-video-sys", - "windows 0.61.3", - "windows-capture", - "x11", - "xcb", -] - -[[package]] -name = "zed-xim" -version = "0.4.0-zed" -source = "git+https://github.com/zed-industries/xim-rs.git?rev=16f35a2c881b815a2b6cdfd6687988e84f8447d8#16f35a2c881b815a2b6cdfd6687988e84f8447d8" -dependencies = [ - "ahash", - "hashbrown 0.14.5", - "log", - "x11rb", - "xim-ctext", - "xim-parser", -] - -[[package]] -name = "zeno" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" - -[[package]] -name = "zerocopy" -version = "0.8.63" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.63" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "zerofrom" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", - "synstructure", -] - -[[package]] -name = "zeroize" -version = "1.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" -dependencies = [ - "zeroize_derive", -] - -[[package]] -name = "zeroize_derive" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "zerotrie" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "zerovec" -version = "0.11.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" -dependencies = [ - "serde", - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "zlib-rs" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" - -[[package]] -name = "zruntime" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6a55d4f521760475a30f7b96779508fe8c40dc834478709454dd1d5f0ebc72" -dependencies = [ - "futures-core", - "futures-io", - "rustix", - "socket2", - "windows-sys 0.61.2", -] - -[[package]] -name = "ztracing" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" -dependencies = [ - "tracing", - "ztracing_macro", -] - -[[package]] -name = "ztracing_macro" -version = "0.1.0" -source = "git+https://github.com/streetwriters/gpui-fast?rev=1ad3cc3#1ad3cc360b37b97449a54e21aa3ac4fe781cfd53" - -[[package]] -name = "zune-core" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" - -[[package]] -name = "zune-inflate" -version = "0.2.54" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" -dependencies = [ - "simd-adler32", -] - -[[package]] -name = "zune-jpeg" -version = "0.5.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" -dependencies = [ - "zune-core", -] - -[[package]] -name = "zvariant" -version = "5.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" -dependencies = [ - "endi", - "enumflags2", - "serde", - "serde_bytes", - "winnow 1.0.5", - "zcheapstr", - "zvariant_derive", - "zvariant_utils", -] - -[[package]] -name = "zvariant_derive" -version = "5.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" -dependencies = [ - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 3.0.10", - "zvariant_utils", -] - -[[package]] -name = "zvariant_utils" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" -dependencies = [ - "proc-macro2", - "quote", - "serde", - "syn 3.0.10", - "winnow 1.0.5", -] diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/Cargo.toml b/vendor/react-native-gpui/packages/core/ReactGpui/Cargo.toml deleted file mode 100644 index 313cc18ee2..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/Cargo.toml +++ /dev/null @@ -1,62 +0,0 @@ -[workspace] -resolver = "2" -members = [ - "rn-gpui-sys", - "rn-gpui", - "rn-gpui-module", - "rn-gpui-module-build", - "rn-gpui-module/tests/generated", -] - -# Set CARGO_PROFILE_DEV_DEBUG=full to opt into full debug information. -[profile.dev] -debug = "line-tables-only" -split-debuginfo = "packed" - -# The same dev profile as every other workspace root in the checkout (the tester's -# and each module's): they all build into the one root `target/`, and a profile -# that differs gives the same dependency a different hash, so it is compiled and -# stored once per variant. -[profile.dev.package."*"] -debug = false -opt-level = 3 - -# Here rn-gpui-sys is a workspace member, which `"*"` does not cover; in the -# tester and in apps it is a dependency, which it does. Its build script hands -# `DEBUG` to CMake, so without `debug = false` the C++ build of `test:rust` and -# the tester's would differ and each would reconfigure and recompile all of it. -[profile.dev.package.rn-gpui-sys] -debug = false -opt-level = 0 - -[profile.release] -# Line tables, not `false`: a release crash is worth symbolizing, and with -# `split-debuginfo` the debug info lives in a separate dSYM rather than the -# binary, so it costs the package nothing. -debug = "line-tables-only" -# Strip the symbol table: nothing reads it at run time. -## Keep the symbols Cargo's link step produces: `strip = "symbols"` runs in the -## linker, so `dsymutil` runs afterwards on an already-stripped binary and writes -## an empty dSYM. The stripping happens in `package-desktop` instead, after the -## dSYM exists. -strip = "none" -split-debuginfo = "packed" -# Full LTO: measured on the tester, 27.3 MB with thin and 25.3 MB with fat, at -# 112 s and 161 s for a clean build. 1.4x the time for 2 MB less is worth it. -lto = "fat" -codegen-units = 1 - -[workspace.dependencies] -gpui = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3" } -gpui_platform = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3" } -cxx = "=1.0.202" -cxx-build = "=1.0.202" -cmake = "0.1" -async-channel = "2" -anyhow = "1" -log = "0.4" -env_logger = "0.11" -serde_json = "1" -futures = "0.3" -http_client = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3" } -fontdue = "0.9" diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/GPUI_PIN.md b/vendor/react-native-gpui/packages/core/ReactGpui/GPUI_PIN.md deleted file mode 100644 index b1f387bd25..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/GPUI_PIN.md +++ /dev/null @@ -1,295 +0,0 @@ -# GPUI pin - -We build on the `streetwriters/gpui-fast` fork: GPUI extracted from the Zed -monorepo, with a retained-mode layout engine (unchanged views are replayed, -layout nodes reused). It keeps upstream GPUI's API; fork code lives in `fast/` -dirs with small hooks. Experimental, git-only (no crates.io releases or tags), -so we pin by commit SHA and bump on purpose. - -## Pinned - -- Repository: https://github.com/streetwriters/gpui-fast -- Branch: `rn-gpui-linux` (tracks upstream `main` with Linux fixes on top so each one can become an - upstream pull request, plus fixes for content drawn under a transform and allocation cuts) -- Commit: `1ad3cc3` (2026-11-21: `de5ebfa` plus browser-like nested and axis scrolling and faster CPU screenshots, with `Window::render_region_to_image` (test-support) drawing one device-pixel region of a frame, which the test driver's element screenshots use. `de5ebfa` (2026-11-19: `8ddec44` plus a CPU renderer (tiny-skia) for headless tests, which `gpui_platform::test_rendering` falls back to where no GPU renderer can be made; the test driver's headless runs draw with it. `8ddec44` (2026-11-19) is `57efe10` plus a held window that can draw outside the frame request without presenting, which native roots use to settle a new page's size within the tick. `57efe10` is `9125f46` plus headless test screenshots. `9125f46` is `70f968b` with the commit after it reverted, so the same tree. `70f968b` (2026-11-18): `bdecaba` plus testing windows by role and visible text over the accessibility tree. `bdecaba` is `bcfa3e3` plus a window that can hold back presenting while its content settles, which native roots use so a new page is shown at its final layout. `bcfa3e3` is `3f7a51a` plus a button drawn again from the last frame keeping its - own accessibility label instead of the text inside it. `3f7a51a` is `3efc3d0` plus a change of input modality (mouse, keyboard or - touch) building only the views that read it, and accessibility nodes replayed for a retained - stretch pushed with the role they had, so a view built again inside a scroll view drawn from - the last frame is still known to be inside it. `3efc3d0` is `93193d4` plus nested views sharing their retained layouts - instead of copying them, so a view's cost does not grow with its depth, and a retained record's - frame indices kept in 32 bits. `93193d4` is `74dcd1f` plus memory cuts: the element arena frees the chunks the - last two frames did not use and keeps at most eight; global element ids are interned as a parent - link and the last id instead of a copy of the whole path; retained records share what they - inherit, their text styles and their rebuild text style stack, and keep a cached style boxed; a - drawn frame's lists are fitted to it; a window idle for a second frees its spare frame's lists - and the arena's chunks; the windows an entity invalidates are a short list rather than a map. - `74dcd1f` is `3bd25f1` plus a change of focus building only the views that read it; `3bd25f1` is - `af2bd3a` plus text in an effect group drawn without subpixel rendering and a view that paints an - effect group rebuilt rather than spliced. `af2bd3a` (2026-11-16) is `3ad00a0` plus a destination-in blend mode and effect groups that - cover their bounds, used to mask children by another element's alpha, and scroll containers exposed - as scroll areas to accessibility. `3ad00a0` (2026-11-11) is `355baeb` plus macOS windows keeping the frame they were given - while a test driver runs the app in the background, so a test window larger than a small CI display - is not shrunk to it. `355baeb` is Abdullah Atta's accessibility commits on `rn-gpui-linux` (unlabelled - buttons, links and tabs named by their painted text, clickable elements without a role as buttons, - hover and tooltips through the accessibility API) and macOS test windows that open behind the user's - and never activate, plus Windows restoring a zoomed window when it is zoomed again. Before them, - `11fd570`: `b015e2b` plus Windows honouring the test scale factor - (`RN_GPUI_TEST_SCALE_FACTOR`) and letting a window outgrow the display for it. `b015e2b` is `9087620` plus windows reporting themselves active on Linux while the - test driver runs the app, as macOS already did, so focus and blur reach elements of a test window - that is never mapped or focused. `9087620` is `d5041b0` plus two commits for react-native-gpui. `d5041b0` is Longbridge's - gpui-fast `main` merged into `rn-gpui-linux`, with upstream's public API kept for `ContentMask`, - `Hitbox` and `paint_svg`, GPUI Kit 0.9.1 and gpui-pre 0.3.12 tracked, and the hover freeze (the end - of a freeze draws the window again without refreshing it). The two commits: a key the focused input - takes as text is not offered to the key listeners of its ancestors (`fast::text_keys`, with the - platform insertion untouched), and `test-support` methods that drive the focused input handler as an - input method would (`Window::simulate_marked_text` and `simulate_committed_text`). It still has - `5392403`'s test hooks: a window scale factor a test run asks for (`RN_GPUI_TEST_SCALE_FACTOR`) and - windows reporting themselves active while the test driver runs the app in the background)) -- Toolchain: Rust 1.98 or newer (gpui-fast pins 1.98.1 and uses `Option::map_or_default`) -- Every manifest that names gpui-fast uses this commit: `packages/core/ReactGpui`, - `packages/rn-gpui-tester/desktop` and - `packages/rn-gpui-tester/host-components-module/desktop`. The modules in - react-native-gpui-modules follow the same commit; see AGENTS.md -- Pinned in: `Cargo.toml` `[workspace.dependencies] gpui.rev` - -## Startup deferrals - -- `c380367` `gpui_macos: defer work the first frame does not read` - - `MacKeyboardLayout::new` runs on first key use rather than at platform - creation. It cost about 30 ms — `platform created` fell from 43 ms to 12 ms - once it was lazy, and nothing in the first frame reads a keyboard layout. - - `NSWindow.setAllowsAutomaticWindowTabbing(false)` is set once at platform - start instead of per window, so `NSWindow.tabGroup` is nil from the outset - and `tab_bar_visible` answers without asking AppKit. A window that asks for - a tabbing identifier re-enables it in its own initialiser. - -## Carried patches on top of upstream - -- `7338a98` `gpui: map X11 windows only when shown` (honour `show: false`) -- `2895a8f` `gpui_linux: apply resizes to unmapped X11 windows` -- `09a45a7` `gpui_linux: log a missing XInput pointer as a warning` -- `8034d63` `gpui_linux: implement render_to_image for X11 and Wayland` -- `f8edd01` `gpui: expose accessibility identifiers and states in the debug tree` -- `f1abf86` `gpui_linux: track the X11 map state from map and unmap events` -- `1db8564` `gpui_windows: deliver hover callbacks outside the window procedure` - — the commit message says "hover and resize", but only hover is deferred in it: - `WM_SIZE` and `WM_MOVE` still invoked their callbacks inline, so the earlier - pin compensated in shared `window.rs` instead. `172d79f` finishes the job in - the backend and that compensation is gone. -- `8e846d2` `gpui_windows: skip windows that are already gone` -- `ebf3ced` `gpui: ignore platform callbacks for a window that has been removed` - — amended in effect by `394557f`: that commit made five callbacks discard their - `update` result, which also silenced a failed `App` borrow. The removed-window - case is now a typed `WindowRemoved` error that only that case ignores; every - other failure is logged again. -- `172d79f` `gpui_windows: defer resize and move out of the window procedure` -- `394557f` `gpui: log a failed borrow in the platform callbacks again` -- `ffc9655` `gpui: defer the move callback so a synchronous move cannot re-enter -App` — a move performed from inside an `App` update (a JS `set_position`, - which AppKit implements with `setFrameTopLeftPoint:`) is notified before that - call returns, so `on_moved` ran `handle.update` while the caller still held - the `App` and logged `ERROR gpui::window] RefCell already borrowed`. It now - defers through the foreground executor, as `on_appearance_changed` already - does. macOS-only in practice, but the callback is shared, so Windows and Linux - re-run their window tests against this pin. - -### Carried patch: `on_hit_test_window_control` order - -- `a72b326` `gpui: answer the control hit-test for the frontmost element` - - The callback answered with the first entry of `window_control_hitboxes` under - the pointer. That list is in paint order, and an element inserts its own - control hitbox before its children paint, so an ancestor always won — a drag - region covering a title bar matched before every button inside it. On Windows - the whole bar therefore answered `HTCAPTION`, and a press on a caption button - or any interactive child became a non-client message: the window started - moving instead of the button receiving a mouse-down. - - It now walks the real hit test front to back, the order pointer dispatch uses. - A frontmost hitbox that is not a control area returns `None` rather than - continuing the walk, because every hitbox in that list belongs to an element - that takes the mouse, focus, scroll or a cursor, so it owns the press. - - It was fixed in the fork rather than worked around in `rn-gpui` because the - alternative — not marking the drag region at all on Windows — would lose - `HTCAPTION` and with it snap layouts, double-click maximise and the system - move loop (`start_window_move()` is a no-op in `gpui_windows`). - -### Carried patch: every window callback ignores a removed window - -- `40700ec` `gpui: ignore a window removed before a platform callback arrives` - - `ebf3ced` routed five platform callbacks through `ignore_if_window_removed`; - the rest (`on_resize`, `on_moved`, `on_visual_viewport_changed`, - `on_insets_changed`, `on_appearance_changed`, `on_button_layout_changed`, the - frame request and the input callbacks) still ended in `.log_err()`. A macOS - popup that was dismissed could receive a resize or move after it was removed, - and the e2e `opening and closing a popup repeatedly logs no errors` caught - `ERROR gpui::window] window not found` on CI. Every - `handle.update(...).log_err()` in `Window::new` now goes through the same - helper, so only the removed-window case is ignored and any other failure is - still logged. - -### Carried patch: no error for a cursor message to a closed window - -- `7bf381d` `gpui_windows: do not log a cursor message posted to a window that just closed` - - `set_cursor_style` posts a message to every tracked window, and a window that - has just been destroyed is still in the list for a moment. `PostMessageW` then - fails with `ERROR_INVALID_WINDOW_HANDLE`, which was logged at ERROR and failed - the e2e `a second window opens with its own surface and closes again` on - Windows CI. That one code is now ignored; every other failure is still logged. - -### Carried patch: hidden overflow clipped to rounded corners - -- `8da7d89` `gpui: clip hidden overflow to rounded corners` - - A content mask was a rectangle, so `overflow: hidden` with a border radius - clipped children square, where iOS and Android clip them to the rounded - corners. The mask now also carries one rounded rectangle, which every - renderer (Metal, Direct3D, wgpu) applies per fragment to quads, shadows, - underlines, glyphs, images and paths; scroll layers keep it when they are - composited. Elements opt in with `overflow_clips_corners()`, which `rn-gpui` - sets wherever React Native clips (`overflow: hidden` and scroll views); other - GPUI code keeps a rectangular clip. - - The patch adds API: `ContentMask` has two more fields, so a struct literal - must become `ContentMask::new(bounds)`, and `overflow_clips_corners` is new. - Surfaces and external textures stay rectangular, and nested rounded clips - keep only the innermost one. - -> **Cargo does not notice edits to a git checkout**, which matters only if you -> edit one by hand without bumping the pin. It fingerprints the checkout by -> revision, so after editing `window.rs` it still reports `Fresh gpui` and links -> the old rlib — the change looks like it does nothing. Verified by injecting a -> `compile_error!` and watching the build succeed anyway. If you ever do this, -> `rm -rf target/debug/.fingerprint/gpui-*` and look for a -> `Compiling gpui v0.2.2 (…?rev=…)` line as proof it took. - -`on_hit_test_window_control` used to answer with the first entry of -`rendered_frame.window_control_hitboxes` whose hitbox was under the pointer. -That list is in _paint_ order, and an ancestor paints its own control hitbox -before its children paint theirs, so a drag region covering a title bar always -matched before a button inside it. On Windows the whole bar therefore answered -`HTCAPTION`: a press on a button in the bar moved the window instead of pressing -the button. - -The callback now walks `rendered_frame.hit_test(mouse_position).ids` — front to -back, the same order pointer dispatch uses — and returns the first hitbox's -control area, or `None` if the frontmost hitbox belongs to an element that is not -a control area. Only hitboxes whose elements listen for the mouse, take focus, -scroll or set a cursor are inserted at all, so "frontmost is not a control area" -means "an interactive element owns this press", which is exactly the case where -the window must not be moved. The hit test is computed inside the callback rather -than read from `mouse_hit_test`, because that field is only refreshed when a mouse -event is dispatched and the first `WM_NCHITTEST` arrives before any pointer event. - -To reproduce it on a fresh checkout, apply this to -`crates/gpui/src/window.rs` and remember that **cargo does not notice edits to a -git checkout on its own** — `cargo clean -p gpui` (or a full rebuild) is needed -or the old rlib is reused silently. - -## Upstream (from the repo's `UPSTREAM` file at that commit) - -- Zed repository: https://github.com/zed-industries/zed -- Zed commit: `a1b71072e5b43faef437b471e988fbb5f972c99c` -- gpui-fast import commit holding that import unchanged: - `8848cdcf22eb7479a07a17d8ca627dc8144e4f38` (branch `sync/zed-a1b7107`, - merged as gpui-fast#38) - -`git show :` in gpui-fast gives upstream's version of a -tracked path without a Zed checkout. - -## Policy - -- `rn-gpui` uses only upstream GPUI APIs. gpui-fast promises that upstream code - compiles against its fork unchanged. -- Until gpui-fast lands window composition (zed#62379), carry that patch on our - own branch of gpui-fast if we need it (design doc §5). -- Bump the SHA deliberately; record the new SHA + UPSTREAM Zed commit here. - -## Known limitation: retained views under accessibility - -The retained-view fast path is disabled while a screen reader is active: - -- `crates/gpui/src/fast/retained.rs:544` (`self.a11y.is_active()`) -- `crates/gpui/src/fast/splice.rs:297` (`self.a11y.is_active()`) -- `crates/gpui/src/fast/layers/mod.rs:121` (`!window.a11y.is_active()`) - -With it disabled, a visible window rebuilds its element tree on every refresh, -so the `retained static siblings do not render with changing siblings` e2e check -expects 5 recorded paints but sees every subsequent paint as well. Hidden -(offscreen) windows do not refresh from events, which is why the offscreen e2e -runs pass with the accessibility bus on. - -Because of that, the Linux e2e runner leaves the AT-SPI bus off for **headed** -runs (`packages/rn-gpui-tester/scripts/run-e2e.mjs`), so the native -accessibility assertions skip there. Offscreen runs still enable the bus. -Setting `RN_GPUI_TEST_NATIVE_A11Y=1` forces the bus on even when headed. - -Windows is not affected, and needs no equivalent rule. Activation there is -per process: `gpui_windows` only starts publishing when a client asks the window -for its accessibility provider (`WM_GETOBJECT`), and the test driver asks on -behalf of the assertions, so only the process running an accessibility test has -`a11y.is_active()` set. A headed run was measured with accessibility active and -the `retained static siblings` check passed; each test launches its own app -process, so the activation cannot leak between them. - -Fixing this properly means replaying accessibility subtree updates for retained -views; that is out of scope for now. - -## Transforms - -- `590f2bb`, `a678e91`, `8dab27d`, `81357fc`, `3a4e87e`: a per-frame table of 2D affine matrices and - an index on every primitive (`Quad`'s packs it above its border style). - `Window::with_transformation` and `with_transformation_about` draw and - hit-test a subtree under a matrix; hit boxes keep theirs. The Metal shaders - evaluate corners, borders, masks and shadows in the primitive's own space. - The wgpu shaders read the table from a storage buffer at group 0 binding 2 - (16384 entries; the WebGL transport has none and draws untransformed). The - DirectX shaders read it from a structured buffer at `t2`. -- `d58e7e2`..`464a119`: glyph and SVG sprites no longer carry an inline matrix; an `Svg` - with a `Transformation` draws under `Window::with_transformation` (so its clip is in the - svg's own space and it bypasses tile layers). Mono and subpixel sprites are 24 bytes - smaller, and the WebGL record stride for them is 30 words. A hit box keeps an `Rc` of its - matrix (none for the identity), so layers and retained frames can carry it. - Replay skips the table for identity primitives. -- `934adc1`: `Window::composed_scene_layers` reports how the last frame is split across - GPUI composition surfaces, so a test can see which surface a view painted onto. -- `48ef745`: effect groups (`Window::with_effect_group`): a subtree painted into a texture of its own and - composited with group opacity, a blur or drop shadow of its picture, and a CSS blend mode against a copy of what is beneath it, on Metal, wgpu and Direct3D 11. `Scene::finish` moves each group's primitives - into a scene of its own, in the texture's space. A group's texture is its bounds rounded out to device pixels - and clipped to the window (wgpu and Direct3D round the texture up to 64 px so frames reuse it). A scroll view whose content holds a group is not cached as a layer (the node counts it); - a group inside layer content, were there one, would fade each shape on its own. -- `549d4cd`: a native surface on Windows is hidden by an empty clip; a visual from a plain - DirectComposition device has no `IDCompositionVisual3` opacity. - Against `8da7d89` on `randomized_element_tree` (18 cases): foreground instructions +0.4%, - wall time median about +1%, the smallest frames (110-210 us) still 5-10% slower. - -## Rendering - -- `df99de6`: the Metal layer is tagged sRGB, so a wide-gamut display shows a React - Native colour the way AppKit shows the same sRGB value. -- `956427e`: blurred shadows are dithered on every backend (interleaved gradient noise, - scaled by the alpha so a zero stays zero), and the wgpu linear gradient is dithered like - the Metal and DirectX ones. The noise is keyed to the primitive's own origin, so a tile - rasterised at another offset gets the same pixels. -- `bdc7e62`..`e2a4638`: colour filters. `Window::with_color_filter` composes a 4x5 colour matrix into - the same per-frame table as transforms (the wgpu storage buffer holds both; DirectX reads - the matrices at `t3`; Metal binds them at fragment buffer 9). Each primitive is filtered on its - own, so overlapping content is not filtered as a group. Paths and surfaces are not filtered. - -## API changes at `93193d4` - -- `GlobalElementId` no longer dereferences to `[ElementId]`: it is the last id and a link to the - id of the path above it. `Display` and `Debug` still print the whole path. - -## API changes at `807f4e5` - -- `Keystroke::parse` takes a `&'static str` with explicit modifiers; dynamic text, and the - `secondary-` alias, goes through `Keystroke::parse_with_os` and `KeyBinding::load(.., cx)`. - `Keystroke` has no `Display`; use `unparse(os)`. `Modifiers::secondary` takes `&App`. -- `PlatformInput::ScrollWheel` and `ScrollWheelEvent` are `PlatformInput::Scroll` and - `ScrollEvent` (with a `source`); `on_scroll_wheel` is `on_scroll`. -- Effect groups use atlas texture ids from `0xE000_0000` and dynamic textures from `0xE800_0000`. -- Dynamic textures carry their version in `AtlasTile::padding`. diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/LOOM_PIN.md b/vendor/react-native-gpui/packages/core/ReactGpui/LOOM_PIN.md deleted file mode 100644 index d6cd3558c9..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/LOOM_PIN.md +++ /dev/null @@ -1,20 +0,0 @@ -# Loom pin - -The [Loom](https://github.com/ammarahm-ed/Loom) renderer is not on npm, so we pin it by commit, as gpui-fast is, and bump it on purpose. `loom-pin.json` is what the build reads; this file says what it names. - -## Pinned - -- Repository: https://github.com/ammarahm-ed/Loom -- Branch: `0.87-stable` -- Commit: `f89ca4d81ab2ad3756d91d4dae73fd7e79967a7d`, `packages/react-native-loom` 0.87.0, for React Native 0.87.1 -- Archive: `https://codeload.github.com/ammarahm-ed/Loom/tar.gz/`, SHA-256 `d99dcbe242f0c6f8d0a60c55f52387c7fb237ef947c660e4d87f311131223df8` - -## How it is used - -`renderer.js` downloads the archive into the native-dependency cache (`native-deps/loom`), checks the digest, and runs the package's own `bin/loom.js materialize` against the app's `react-native`. The result, under `native-deps/loom/trees`, is what Metro, autolink, the codegen and the C++ build read when `desktop/desktop.json` selects `"renderer": "loom"`. - -## Moving the pin - -1. Change `commit`, `version` and `archiveUrl` in `loom-pin.json`, and put the SHA-256 of the archive in `sha256`. -2. Run `npm run check:loom-overrides` in `packages/core`. It fails for every Loom variant in `ReactCommonOverrides.loom` whose source file changed; carry the change over and update `loomBaseHash` in `overrides.json`. -3. Update this file. diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/loom-pin.json b/vendor/react-native-gpui/packages/core/ReactGpui/loom-pin.json deleted file mode 100644 index e8c5ebae22..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/loom-pin.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "repository": "https://github.com/ammarahm-ed/Loom", - "commit": "4245aca0a7d869a09ce7298b13fb6003a6559346", - "branch": "0.87-stable", - "packagePath": "packages/react-native-loom", - "version": "0.87.0", - "archiveUrl": "https://codeload.github.com/ammarahm-ed/Loom/tar.gz/4245aca0a7d869a09ce7298b13fb6003a6559346", - "sha256": "e65fb1a37970afee4d716a442eeff1742b7b499612ff353c2a92979b5949aff5" -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module-build/Cargo.toml b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module-build/Cargo.toml deleted file mode 100644 index 179113aca8..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module-build/Cargo.toml +++ /dev/null @@ -1,8 +0,0 @@ -[package] -name = "rn-gpui-module-build" -version = "0.1.0" -edition = "2021" -description = "Build script helper that generates Rust TurboModule glue from TypeScript specs" - -[lib] -path = "src/lib.rs" diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module-build/src/lib.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module-build/src/lib.rs deleted file mode 100644 index 44927794d6..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module-build/src/lib.rs +++ /dev/null @@ -1,165 +0,0 @@ -//! Runs the Rust TurboModule generator for a crate's TypeScript specs. -//! -//! ```no_run -//! fn main() { -//! rn_gpui_module_build::generate(&["../src/NativeFixture.ts"]); -//! } -//! ``` - -use std::path::{Path, PathBuf}; -use std::process::Command; - -/// Generates `$OUT_DIR/rn_gpui_specs.rs` from `specs`, relative to the crate's -/// manifest directory, and rebuilds when a spec or the generator changes. -pub fn generate(specs: &[&str]) { - let manifest_dir = PathBuf::from( - std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo"), - ); - let out_dir = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR is set by cargo")); - let generator = generator_script(&manifest_dir); - println!("cargo:rerun-if-changed={}", generator.display()); - let mut paths = Vec::with_capacity(specs.len()); - for spec in specs { - let path = manifest_dir.join(spec); - if !path.exists() { - panic!( - "rn-gpui-module-build: no spec file at {} (specs are relative to {})", - path.display(), - manifest_dir.display() - ); - } - println!("cargo:rerun-if-changed={}", path.display()); - paths.push(path); - } - let output = out_dir.join("rn_gpui_specs.rs"); - // With no specs the generator would be invoked as `node generator `, - // and it requires at least one spec plus the output, so it exits 2 with its - // usage line. A template app declares no modules, so this is the common - // case for a fresh project: write the empty module list instead of running - // the generator at all. - if paths.is_empty() { - std::fs::write( - &output, - "// Generated by rn-gpui-module-build: no specs were declared.\n", - ) - .unwrap_or_else(|error| { - panic!( - "rn-gpui-module-build: could not write {}: {error}", - output.display() - ) - }); - return; - } - let mut command = Command::new("node"); - command.arg(&generator).args(&paths).arg(&output); - let result = command - .output() - .unwrap_or_else(|error| panic!("rn-gpui-module-build: could not run Node.js: {error}")); - if !result.status.success() { - panic!( - "rn-gpui-module-build: {} failed with {}\nstderr:\n{}\nNode.js and @react-native-gpui/codegen must be installed in the app.", - generator.display(), - result.status, - String::from_utf8_lossy(&result.stderr).trim_end() - ); - } -} - -/// Resolves the generator from the app, so a library inside an app finds the -/// app's copy. -fn generator_script(manifest_dir: &Path) -> PathBuf { - let script = "process.stdout.write(require.resolve('@react-native-gpui/codegen/generate-rust-spec', {paths: [process.argv[1]]}))"; - let result = Command::new("node") - .arg("-e") - .arg(script) - .arg(manifest_dir) - .output() - .unwrap_or_else(|error| panic!("rn-gpui-module-build: could not run Node.js: {error}")); - if !result.status.success() || result.stdout.is_empty() { - panic!( - "rn-gpui-module-build: @react-native-gpui/codegen is not installed for {}\nstderr:\n{}\nAdd it to the app's dependencies.", - manifest_dir.display(), - String::from_utf8_lossy(&result.stderr).trim_end() - ); - } - PathBuf::from(String::from_utf8_lossy(&result.stdout).trim()) -} - -/// Forwards every Node-API symbol the engine exports out of the app's -/// executable, so a stock `.node` addon can resolve them on Windows. -/// -/// Windows has no global symbol lookup: a DLL import names the function *and* -/// the file it comes from. Addons reach Node-API in two ways and both end at the -/// host process's executable — a `node-gyp` addon as a delay-loaded import from -/// `node.exe`, which its `win_delay_load_hook.cc` replaces with the current -/// process image, and a napi-rs addon by probing the host executable first. Our -/// Node-API functions live in the engine's DLL and the executable exports -/// nothing, so each name is re-exported as a forwarder to that DLL. -/// -/// This lives in one place because two build scripts need it — -/// `rn-gpui-tester/desktop/build.rs` and the app template's — and a module -/// definition that disagrees between them is an addon that loads in one app and -/// not the other. -/// -/// Does nothing unless the target is Windows/MSVC and the engine supplied a -/// list. A Windows GNU target gets a warning instead: MinGW's `.def` handling -/// and its `--enable-auto-import` are not what an MSVC-built addon expects, and -/// a silently unforwarded binary is worse than a warning. -pub fn forward_node_api_exports() { - if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { - return; - } - let list = std::env::var("DEP_RN_GPUI_RUNTIME_NODE_API_EXPORTS") - .ok() - .filter(|value| !value.is_empty()); - if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() != Ok("msvc") { - if list.is_some() { - println!( - "cargo:warning=Node-API addons on Windows need the MSVC toolchain; \ - the engine's exports are not forwarded for this target" - ); - } - return; - } - let Some(list) = list else { - // No engine list: either an engine without Node-API or a build that - // never resolved one. Not an error, so a plain app still links. - return; - }; - let library = std::env::var("DEP_RN_GPUI_RUNTIME_NODE_API_LIBRARY") - .ok() - .filter(|value| !value.is_empty()) - .unwrap_or_else(|| { - panic!( - "rn-gpui-module-build: the engine exports a Node-API list without a library name" - ) - }); - - let names = std::fs::read_to_string(&list) - .unwrap_or_else(|error| panic!("rn-gpui-module-build: read {list}: {error}")); - // The list is one name per line; a blank line or a stray comment must not - // become an export (a malformed `.def` fails the link with a message that - // does not name the file). - let names: Vec<&str> = names - .lines() - .map(str::trim) - .filter(|line| !line.is_empty() && !line.starts_with(';')) - .collect(); - if names.is_empty() { - panic!("rn-gpui-module-build: the Node-API export list {list} is empty"); - } - - let out_dir = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR is set by cargo")); - let def = out_dir.join("node_api_exports.def"); - let mut text = String::from("EXPORTS\n"); - for name in &names { - // A forwarder: the executable exports `name` and the loader resolves it - // from the named DLL. No `@ordinal`, so the name stays usable. - text.push_str(&format!(" {name}={library}.{name}\n")); - } - std::fs::write(&def, text) - .unwrap_or_else(|error| panic!("rn-gpui-module-build: write {}: {error}", def.display())); - - println!("cargo:rerun-if-changed={list}"); - println!("cargo:rustc-link-arg-bins=/DEF:{}", def.display()); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/Cargo.toml b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/Cargo.toml deleted file mode 100644 index 91b3b802eb..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/Cargo.toml +++ /dev/null @@ -1,7 +0,0 @@ -[package] -name = "rn-gpui-module" -version = "0.1.0" -edition = "2021" - -[dependencies] -futures = { workspace = true } diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/error.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/error.rs deleted file mode 100644 index 30d9664a68..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/error.rs +++ /dev/null @@ -1,45 +0,0 @@ -use std::fmt; - -/// A rejected call: the message reaches JS as the error's message, the code as -/// its `code` property. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ModuleError { - pub code: Option, - pub message: String, -} - -impl ModuleError { - pub fn new(message: impl Into) -> Self { - Self { - code: None, - message: message.into(), - } - } - - pub fn with_code(code: impl Into, message: impl Into) -> Self { - Self { - code: Some(code.into()), - message: message.into(), - } - } -} - -impl fmt::Display for ModuleError { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str(&self.message) - } -} - -impl std::error::Error for ModuleError {} - -impl From for ModuleError { - fn from(message: String) -> Self { - Self::new(message) - } -} - -impl From<&str> for ModuleError { - fn from(message: &str) -> Self { - Self::new(message) - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/host.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/host.rs deleted file mode 100644 index c376809c91..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/host.rs +++ /dev/null @@ -1,208 +0,0 @@ -use std::any::Any; -use std::sync::{Mutex, OnceLock}; - -use crate::{ModuleError, Value}; - -/// A JS function passed as an argument, which appears as `Value::Callback` and -/// never in a result. Calling it consumes it, so it can be called at most once; -/// dropping it without calling releases the JS function. -pub struct RawCallback { - id: u64, -} - -impl RawCallback { - pub fn new(id: u64) -> Self { - Self { id } - } - - pub fn id(&self) -> u64 { - self.id - } - - pub fn invoke(self, args: Vec) { - let this = std::mem::ManuallyDrop::new(self); - (hooks().invoke_callback)(this.id, args); - } -} - -impl std::fmt::Debug for RawCallback { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - formatter - .debug_tuple("RawCallback") - .field(&self.id) - .finish() - } -} - -impl Drop for RawCallback { - fn drop(&mut self) { - (hooks().drop_callback)(self.id); - } -} - -/// Emits one module instance's typed and device events. Cheap to clone and -/// usable from any thread; emitting before JS subscribes, or after a reload, -/// does nothing. -#[derive(Clone, Debug)] -pub struct EventEmitter { - module: u64, -} - -impl EventEmitter { - pub fn new(module: u64) -> Self { - Self { module } - } - - pub fn emit(&self, event: &str, value: Option) { - (hooks().emit_event)(self.module, event, value); - } - - pub fn send_event(&self, name: &str, body: Value) { - (hooks().send_event)(self.module, name, body); - } -} - -/// What the host installs so the crate can reach JS; without hooks the calls -/// are recorded in the sink instead. -#[derive(Clone, Copy)] -pub struct HostHooks { - pub invoke_callback: fn(u64, Vec), - pub drop_callback: fn(u64), - pub emit_event: fn(u64, &str, Option), - pub send_event: fn(u64, &str, Value), - /// Reports a failure with nowhere else to go, such as a `void` method that - /// failed on the module thread. - pub log: fn(&str), -} - -static HOST_HOOKS: OnceLock = OnceLock::new(); - -pub fn set_host_hooks(hooks: HostHooks) { - let _ = HOST_HOOKS.set(hooks); -} - -fn hooks() -> HostHooks { - *HOST_HOOKS.get().unwrap_or(&HostHooks { - invoke_callback: sink_invoke_callback, - drop_callback: sink_drop_callback, - emit_event: sink_emit_event, - send_event: sink_send_event, - log: sink_log, - }) -} - -#[derive(Debug)] -pub enum SinkCall { - InvokeCallback { - id: u64, - args: Vec, - }, - DropCallback { - id: u64, - }, - EmitEvent { - module: u64, - event: String, - value: Option, - }, - SendEvent { - module: u64, - name: String, - body: Value, - }, - Log { - message: String, - }, -} - -static SINK: OnceLock>> = OnceLock::new(); - -fn sink() -> &'static Mutex> { - SINK.get_or_init(|| Mutex::new(Vec::new())) -} - -pub fn sink_calls() -> Vec { - let mut calls = sink() - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - std::mem::take(&mut *calls) -} - -fn sink_invoke_callback(id: u64, args: Vec) { - sink() - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .push(SinkCall::InvokeCallback { id, args }); -} - -fn sink_drop_callback(id: u64) { - sink() - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .push(SinkCall::DropCallback { id }); -} - -fn sink_emit_event(module: u64, event: &str, value: Option) { - sink() - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .push(SinkCall::EmitEvent { - module, - event: event.to_string(), - value, - }); -} - -fn sink_send_event(module: u64, name: &str, body: Value) { - sink() - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .push(SinkCall::SendEvent { - module, - name: name.to_string(), - body, - }); -} - -fn sink_log(message: &str) { - sink() - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .push(SinkCall::Log { - message: message.to_string(), - }); -} - -pub fn log_error(location: &str, error: &ModuleError) { - (hooks().log)(&format!("{location}: {error}")); -} - -/// Runs a queued `void` call, turning a panic or an error into a log line. -pub fn run_void(location: &str, body: impl FnOnce()) { - if let Err(error) = catch(body) { - log_error(location, &error); - } -} - -/// Turns a caught panic into an error, so it never unwinds into C++ or kills a -/// module thread. -pub fn panic_error(payload: Box) -> ModuleError { - let message = payload - .downcast_ref::<&str>() - .map(|text| (*text).to_string()) - .or_else(|| payload.downcast_ref::().cloned()) - .unwrap_or_else(|| "panicked".to_string()); - ModuleError::new(format!("the module panicked: {message}")) -} - -pub fn catch(body: impl FnOnce() -> T) -> Result { - std::panic::catch_unwind(std::panic::AssertUnwindSafe(body)).map_err(panic_error) -} - -pub async fn catch_async(future: F) -> Result { - use futures::FutureExt; - std::panic::AssertUnwindSafe(future) - .catch_unwind() - .await - .map_err(panic_error) -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/lib.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/lib.rs deleted file mode 100644 index 9309c80006..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/lib.rs +++ /dev/null @@ -1,44 +0,0 @@ -//! The runtime a Rust TurboModule is written against: the value tree, errors, -//! events and threads the generated glue uses. It depends on nothing but -//! `futures`, so it needs no C++ toolchain and no JS runtime to test. - -mod error; -mod host; -mod private; -mod queue; -mod registry; -mod value; - -pub use error::ModuleError; -pub use host::{ - log_error, run_void, set_host_hooks, sink_calls, EventEmitter, HostHooks, RawCallback, SinkCall, -}; -pub use private::Path; -pub use queue::{ - is_main_thread, note_main_thread, set_main_spawner, spawn_main, Job, LocalBoxFuture, - ModuleQueue, -}; -pub use registry::{ - descriptor, descriptors, register, EventInfo, MethodInfo, MethodKind, ModuleDescriptor, - ModuleInstance, ModuleThread, -}; -pub use value::{ArrayBuffer, FromValue, IntoValue, Value}; - -#[doc(hidden)] -pub mod __private { - pub use crate::private::{ - catch, catch_async, field, location, log_error, panic_error, run_void, Args, FieldMap, Path, - }; -} - -/// Includes what `rn-gpui-module-build` generated from the crate's specs. -#[macro_export] -macro_rules! include_specs { - () => { - #[allow(clippy::all, unused)] - pub mod rn_gpui_specs { - include!(concat!(env!("OUT_DIR"), "/rn_gpui_specs.rs")); - } - pub use rn_gpui_specs::*; - }; -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/private.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/private.rs deleted file mode 100644 index a51e5a6743..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/private.rs +++ /dev/null @@ -1,119 +0,0 @@ -//! Helpers the generated glue calls; anything here can change with the -//! generator. -#![doc(hidden)] - -use crate::{FromValue, ModuleError, Value}; - -pub use crate::value::Path; - -/// The cursor over one call's arguments, converted on the thread that received -/// them. -pub struct Args { - module: &'static str, - method: &'static str, - values: Vec, - index: usize, -} - -impl Args { - pub fn new(module: &'static str, method: &'static str, values: Vec) -> Self { - Self { - module, - method, - values, - index: 0, - } - } - - pub fn next_callback(&mut self, name: &'static str) -> Result { - let index = self.index; - self.index += 1; - let value = match self.values.get_mut(index) { - Some(slot) => std::mem::replace(slot, Value::Null), - None => { - return Err(ModuleError::new(format!( - "{}.{}: argument {index} ({name}) is missing", - self.module, self.method - ))) - } - }; - let path = Path::argument(self.module, self.method, index, name); - match value { - Value::Callback(callback) => Ok(callback), - other => Err(path.error(format!("expected function, got {}", other.type_name()))), - } - } - - pub fn next(&mut self, name: &'static str) -> Result { - let index = self.index; - self.index += 1; - let value = match self.values.get_mut(index) { - Some(slot) => std::mem::replace(slot, Value::Null), - None => { - return Err(ModuleError::new(format!( - "{}.{}: argument {index} ({name}) is missing", - self.module, self.method - ))) - } - }; - let mut path = Path::argument(self.module, self.method, index, name); - T::from_value(value, &mut path) - } -} - -/// The fields of one object, so a generated struct can take them by name and -/// report a missing or mistyped one. -pub struct FieldMap { - fields: Vec<(String, Value)>, -} - -impl FieldMap { - pub fn new(fields: Vec<(String, Value)>) -> Self { - Self { fields } - } - - pub fn take(&mut self, path: &mut Path, name: &str) -> Result { - match self.remove(name) { - Some(value) => field(path, name, value), - None => { - path.push_field(name); - let error = path.error("missing field"); - path.pop_field(); - Err(error) - } - } - } - - pub fn take_optional( - &mut self, - path: &mut Path, - name: &str, - ) -> Result, ModuleError> { - match self.remove(name) { - Some(Value::Null) => Ok(None), - Some(value) => field(path, name, value).map(Some), - None => Ok(None), - } - } - - fn remove(&mut self, name: &str) -> Option { - let index = self - .fields - .iter() - .position(|(key, _)| key.as_str() == name)?; - Some(self.fields.remove(index).1) - } -} - -pub fn field(path: &mut Path, name: &str, value: Value) -> Result { - path.push_field(name); - let converted = T::from_value(value, path); - path.pop_field(); - converted -} - -pub fn location(module: &'static str, method: &'static str) -> String { - format!("{module}.{method}") -} - -pub use crate::host::{catch, catch_async, log_error, panic_error, run_void}; diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/queue.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/queue.rs deleted file mode 100644 index c15b171dc4..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/queue.rs +++ /dev/null @@ -1,105 +0,0 @@ -use std::future::Future; -use std::pin::Pin; -use std::sync::OnceLock; -use std::thread::JoinHandle; - -use futures::channel::mpsc; -use futures::executor::LocalPool; -use futures::task::LocalSpawnExt; -use futures::StreamExt; - -pub type LocalBoxFuture = Pin + 'static>>; - -/// A job is built on the calling thread and turned into a future on the thread -/// that polls it, so the future itself never crosses threads. -pub type Job = Box LocalBoxFuture<()> + Send + 'static>; - -/// A serial executor for one module: one thread and one `LocalPool`, so a job -/// that awaits does not hold up the next job. -pub struct ModuleQueue { - sender: Option>, - thread: Option>, -} - -impl ModuleQueue { - pub fn new(name: &str) -> Self { - let (sender, mut receiver) = mpsc::unbounded::(); - let thread = std::thread::Builder::new() - .name(format!("rn.module.{name}")) - .spawn(move || { - let mut pool = LocalPool::new(); - let spawner = pool.spawner(); - pool.run_until(async move { - while let Some(job) = receiver.next().await { - let _ = spawner.spawn_local(job()); - } - }); - }) - .expect("spawn a module thread"); - Self { - sender: Some(sender), - thread: Some(thread), - } - } - - pub fn post(&self, job: Job) { - if let Some(sender) = &self.sender { - // The receiver only goes away when the queue is dropped, and - // `post` cannot outlive it. - let _ = sender.unbounded_send(job); - } - } -} - -impl Drop for ModuleQueue { - fn drop(&mut self) { - // Closing the channel ends `run_until`, which drops unfinished futures. - self.sender = None; - let Some(thread) = self.thread.take() else { - return; - }; - if thread.thread().id() == std::thread::current().id() { - // A job dropped the queue that owns this thread; joining would - // deadlock on itself. - return; - } - let _ = thread.join(); - } -} - -static MAIN_THREAD: OnceLock = OnceLock::new(); - -/// Records the calling thread as the GPUI main thread. The host calls this when -/// the main loop starts. -pub fn note_main_thread() { - let _ = MAIN_THREAD.set(std::thread::current().id()); -} - -pub fn is_main_thread() -> bool { - MAIN_THREAD - .get() - .is_some_and(|id| *id == std::thread::current().id()) -} - -static MAIN_SPAWNER: OnceLock> = OnceLock::new(); - -/// Installed once by the host so `ModuleThread::Main` jobs reach the main -/// thread. -pub fn set_main_spawner(spawn: impl Fn(Job) + Send + Sync + 'static) { - let _ = MAIN_SPAWNER.set(Box::new(spawn)); -} - -/// Runs `job` on the main thread, or drops it when no spawner is installed. -pub fn spawn_main(job: Job) { - match MAIN_SPAWNER.get() { - Some(spawn) => spawn(job), - None => { - static WARNED: std::sync::Once = std::sync::Once::new(); - WARNED.call_once(|| { - eprintln!( - "rn_gpui_module::spawn_main: no main-thread spawner installed; job dropped" - ); - }); - } - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/registry.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/registry.rs deleted file mode 100644 index cb1c762e52..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/registry.rs +++ /dev/null @@ -1,104 +0,0 @@ -use std::sync::{Arc, Mutex, OnceLock}; - -use crate::{EventEmitter, LocalBoxFuture, ModuleError, Value}; - -/// Where a module's `void` and `Promise` methods run; value methods always run -/// on the JS thread. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum ModuleThread { - Own, - Main, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum MethodKind { - Value, - Void, - Promise, -} - -pub struct MethodInfo { - pub name: &'static str, - pub arg_count: usize, - /// How many arguments JS has to pass: the parameters up to the last one - /// that is not `Option<_>`, since an optional parameter may be left out. - pub required_args: usize, - pub kind: MethodKind, - /// Whether the spec returns `void`, which makes a promise resolve with - /// `undefined` rather than `null`. - pub returns_void: bool, - /// Positions that hold a callback, which the host replaces with a - /// `RawCallback` id before converting the arguments. - pub callback_args: &'static [usize], -} - -pub struct EventInfo { - pub name: &'static str, - pub has_value: bool, -} - -/// Implemented for the author's type by the generated glue. -pub trait ModuleInstance: Send + Sync + 'static { - fn call_value(&self, method: usize, args: Vec) -> Result; - - /// Converts the arguments and returns the call for the host to run on the - /// module's thread, so a conversion failure reaches JS before anything is - /// queued. - fn prepare_void( - self: Arc, - method: usize, - args: Vec, - ) -> Result, ModuleError>; - - /// Called on the JS thread; the future it returns is polled on the module's - /// thread. - fn call_promise( - self: Arc, - method: usize, - args: Vec, - ) -> Result>, ModuleError>; -} - -pub struct ModuleDescriptor { - pub name: &'static str, - pub thread: ModuleThread, - pub methods: &'static [MethodInfo], - pub events: &'static [EventInfo], - pub create: fn(EventEmitter) -> Arc, -} - -static REGISTRY: OnceLock>> = OnceLock::new(); - -fn registry() -> &'static Mutex> { - REGISTRY.get_or_init(|| Mutex::new(Vec::new())) -} - -/// Registering a duplicate panics, which would otherwise poison the lock and -/// fail every later lookup: the list itself is left unchanged by that panic, so -/// recovering it is safe. -fn modules() -> std::sync::MutexGuard<'static, Vec<&'static ModuleDescriptor>> { - registry() - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) -} - -/// Registers a module, panicking on a duplicate name. -pub fn register(descriptor: ModuleDescriptor) { - let descriptor: &'static ModuleDescriptor = Box::leak(Box::new(descriptor)); - let mut modules = modules(); - if modules.iter().any(|module| module.name == descriptor.name) { - panic!( - "a Rust TurboModule named {} is already registered", - descriptor.name - ); - } - modules.push(descriptor); -} - -pub fn descriptor(name: &str) -> Option<&'static ModuleDescriptor> { - modules().iter().find(|module| module.name == name).copied() -} - -pub fn descriptors() -> Vec<&'static ModuleDescriptor> { - modules().clone() -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/value.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/value.rs deleted file mode 100644 index 955f886c5e..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/src/value.rs +++ /dev/null @@ -1,297 +0,0 @@ -use std::fmt; - -use crate::{ModuleError, RawCallback}; - -/// A JS value detached from the JS runtime. `Callback` is the one member that -/// is not data; it is consumed by calling it. -#[derive(Debug)] -pub enum Value { - Null, - Bool(bool), - Number(f64), - String(String), - /// The bytes of an `ArrayBuffer`. - Buffer(Vec), - Array(Vec), - Object(Vec<(String, Value)>), - Callback(RawCallback), -} - -impl Value { - pub fn object(fields: impl IntoIterator, Value)>) -> Self { - Self::Object( - fields - .into_iter() - .map(|(key, value)| (key.into(), value)) - .collect(), - ) - } - - pub fn type_name(&self) -> &'static str { - match self { - Self::Null => "null", - Self::Bool(_) => "boolean", - Self::Number(_) => "number", - Self::String(_) => "string", - Self::Buffer(_) => "ArrayBuffer", - Self::Array(_) => "array", - Self::Object(_) => "object", - Self::Callback(_) => "function", - } - } -} - -/// The bytes of an `ArrayBuffer`, which the spec's `ArrayBuffer` maps to. A -/// `Vec` cannot: it already converts as an array of numbers. -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub struct ArrayBuffer(pub Vec); - -impl ArrayBuffer { - pub fn as_slice(&self) -> &[u8] { - &self.0 - } - - pub fn into_vec(self) -> Vec { - self.0 - } -} - -impl std::ops::Deref for ArrayBuffer { - type Target = [u8]; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl From> for ArrayBuffer { - fn from(bytes: Vec) -> Self { - Self(bytes) - } -} - -impl From for Vec { - fn from(buffer: ArrayBuffer) -> Self { - buffer.0 - } -} - -impl FromValue for ArrayBuffer { - fn from_value(value: Value, path: &mut Path) -> Result { - match value { - Value::Buffer(bytes) => Ok(Self(bytes)), - other => Err(path.error(format!("expected ArrayBuffer, got {}", other.type_name()))), - } - } -} - -impl IntoValue for ArrayBuffer { - fn into_value(self) -> Value { - Value::Buffer(self.0) - } -} - -/// Where a conversion is, for error messages: -/// `NativeFixture.summarize: argument 1 (options).label`. -pub struct Path { - module: &'static str, - method: &'static str, - argument: Option<(&'static str, usize)>, - fields: Vec, -} - -impl Path { - pub fn argument( - module: &'static str, - method: &'static str, - index: usize, - name: &'static str, - ) -> Self { - Self { - module, - method, - argument: Some((name, index)), - fields: Vec::new(), - } - } - - /// For a value a method converts itself, such as JSON a lower layer built. - pub fn result(module: &'static str, method: &'static str) -> Self { - Self { - module, - method, - argument: None, - fields: Vec::new(), - } - } - - pub fn location(&self) -> String { - let mut location = format!("{}.{}", self.module, self.method); - if let Some((name, index)) = self.argument { - location.push_str(&format!(": argument {index} ({name})")); - } - for field in &self.fields { - location.push('.'); - location.push_str(field); - } - location - } - - pub fn error(&self, detail: impl fmt::Display) -> ModuleError { - ModuleError::new(format!("{}: {detail}", self.location())) - } - - pub fn push_field(&mut self, name: impl fmt::Display) { - self.fields.push(name.to_string()); - } - - pub fn pop_field(&mut self) { - self.fields.pop(); - } -} - -/// A Rust type a `Value` can be read as; generated structs and enums implement -/// it field by field. -pub trait FromValue: Sized { - fn from_value(value: Value, path: &mut Path) -> Result; -} - -pub trait IntoValue { - fn into_value(self) -> Value; -} - -impl FromValue for Value { - fn from_value(value: Value, _path: &mut Path) -> Result { - Ok(value) - } -} - -impl IntoValue for Value { - fn into_value(self) -> Value { - self - } -} - -impl FromValue for String { - fn from_value(value: Value, path: &mut Path) -> Result { - match value { - Value::String(text) => Ok(text), - other => Err(path.error(format!("expected string, got {}", other.type_name()))), - } - } -} - -impl IntoValue for String { - fn into_value(self) -> Value { - Value::String(self) - } -} - -impl FromValue for f64 { - fn from_value(value: Value, path: &mut Path) -> Result { - match value { - Value::Number(number) => Ok(number), - other => Err(path.error(format!("expected number, got {}", other.type_name()))), - } - } -} - -impl IntoValue for f64 { - fn into_value(self) -> Value { - Value::Number(self) - } -} - -impl FromValue for i32 { - fn from_value(value: Value, path: &mut Path) -> Result { - match value { - Value::Number(number) - if number.fract() == 0.0 - && number >= f64::from(i32::MIN) - && number <= f64::from(i32::MAX) => - { - Ok(number as i32) - } - Value::Number(number) => Err(path.error(format!("expected Int32, got {number}"))), - other => Err(path.error(format!("expected Int32, got {}", other.type_name()))), - } - } -} - -impl IntoValue for i32 { - fn into_value(self) -> Value { - Value::Number(f64::from(self)) - } -} - -impl FromValue for bool { - fn from_value(value: Value, path: &mut Path) -> Result { - match value { - Value::Bool(flag) => Ok(flag), - other => Err(path.error(format!("expected boolean, got {}", other.type_name()))), - } - } -} - -impl IntoValue for bool { - fn into_value(self) -> Value { - Value::Bool(self) - } -} - -impl FromValue for () { - fn from_value(value: Value, path: &mut Path) -> Result { - match value { - Value::Null => Ok(()), - other => Err(path.error(format!("expected null, got {}", other.type_name()))), - } - } -} - -impl IntoValue for () { - fn into_value(self) -> Value { - Value::Null - } -} - -impl FromValue for Option { - fn from_value(value: Value, path: &mut Path) -> Result { - match value { - Value::Null => Ok(None), - value => T::from_value(value, path).map(Some), - } - } -} - -impl IntoValue for Option { - fn into_value(self) -> Value { - match self { - Some(value) => value.into_value(), - None => Value::Null, - } - } -} - -impl FromValue for Vec { - fn from_value(value: Value, path: &mut Path) -> Result { - match value { - Value::Array(items) => items - .into_iter() - .enumerate() - .map(|(index, item)| { - path.push_field(index); - let converted = T::from_value(item, path); - path.pop_field(); - converted - }) - .collect(), - other => Err(path.error(format!("expected array, got {}", other.type_name()))), - } - } -} - -impl IntoValue for Vec { - fn into_value(self) -> Value { - Value::Array(self.into_iter().map(IntoValue::into_value).collect()) - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/generated/Cargo.toml b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/generated/Cargo.toml deleted file mode 100644 index 1afa17c247..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/generated/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "rn-gpui-module-generated-test" -version = "0.1.0" -edition = "2021" -publish = false - -[lib] -path = "src/lib.rs" - -[dependencies] -rn-gpui-module = { path = "../.." } -futures = { workspace = true } - -[build-dependencies] -rn-gpui-module-build = { path = "../../../rn-gpui-module-build" } diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/generated/build.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/generated/build.rs deleted file mode 100644 index 75fff811bf..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/generated/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - rn_gpui_module_build::generate(&["specs/NativeProbe.ts"]); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/generated/specs/NativeProbe.ts b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/generated/specs/NativeProbe.ts deleted file mode 100644 index fb7315777d..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/generated/specs/NativeProbe.ts +++ /dev/null @@ -1,62 +0,0 @@ -import type { CodegenTypes, TurboModule } from 'react-native'; -import { TurboModuleRegistry } from 'react-native'; - -export type Mode = 'left' | 'right'; - -export type Meta = { - name: string; - extra?: Object; - list?: Array; -}; - -export type Options = { - type: string; - label?: string; - count: Int32; - mode: Mode; - ratio?: number | null; - nested: { flag: boolean; names: Array }; -}; - -export enum Level { - Low = 'low', - High = 'high', -} - -export enum Rank { - Low = 0, - High = 1, -} - -export interface Spec extends TurboModule { - scalar(text: string, count: number, whole: Int32, flag: boolean): boolean; - optionalValue(maybe?: string, nullable: string | null): string | null; - lists( - items: Array, - readonlyItems: ReadonlyArray, - ): Array; - options(value: Options, again: Options): Options; - meta(value: Meta): Meta; - level(level: Level): Mode; - rank(value: Rank): Rank; - match(text: string): string; - anything(value: Object): UnsafeObject; - nothing(): void; - inline(value: { x: number; y?: string }): void; - later(text: string): Promise; - done(): Promise; - lookup(key: string, callback: (value: string, found: boolean) => void): void; - lookupLater( - key: string, - callback: (value: string, found: boolean) => void, - ): Promise; - sum(data: ArrayBuffer): number; - reversed(data: ArrayBuffer): ArrayBuffer; - start(steps: number): void; - readonly onProgress: CodegenTypes.EventEmitter; - readonly onDone: CodegenTypes.EventEmitter; - addListener(eventName: string): void; - removeListeners(count: number): void; -} - -export default TurboModuleRegistry.getEnforcing('NativeProbe'); diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/generated/src/lib.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/generated/src/lib.rs deleted file mode 100644 index 4450ad110d..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/generated/src/lib.rs +++ /dev/null @@ -1,509 +0,0 @@ -//! Compiles the generator's output for a spec that uses every type in the -//! mapping table and calls each method through the descriptor. - -rn_gpui_module::include_specs!(); - -use rn_gpui_module::{ArrayBuffer, ModuleError, ModuleThread, Value}; - -pub struct Probe { - events: NativeProbeEvents, - recorded: std::sync::Mutex>, -} - -impl NativeProbeSpec for Probe { - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(events: NativeProbeEvents) -> Self { - Self { - events, - recorded: std::sync::Mutex::new(Vec::new()), - } - } - - fn scalar( - &self, - text: String, - count: f64, - whole: i32, - flag: bool, - ) -> Result { - Ok(!text.is_empty() && count > 0.0 && whole == 1 && flag) - } - - fn optional_value( - &self, - maybe: Option, - nullable: Option, - ) -> Result, ModuleError> { - Ok(match (maybe, nullable) { - (Some(maybe), Some(nullable)) => Some(format!("{maybe}/{nullable}")), - (Some(maybe), None) => Some(maybe), - (None, Some(nullable)) => Some(nullable), - (None, None) => None, - }) - } - - fn lists(&self, items: Vec, readonly_items: Vec) -> Result, ModuleError> { - Ok(items - .iter() - .map(|item| item.len() as i32 + readonly_items.len() as i32) - .collect()) - } - - fn options(&self, value: Options, again: Options) -> Result { - Ok(Options { - r#type: value.r#type, - label: value.label.or(again.label), - count: value.count + again.count, - mode: value.mode, - ratio: value.ratio.or(again.ratio), - nested: value.nested, - }) - } - - fn meta(&self, value: Meta) -> Result { - Ok(value) - } - - fn rank(&self, value: Rank) -> Result { - Ok(value) - } - - fn r#match(&self, text: String) -> Result { - Ok(format!("matched {text}")) - } - - fn level(&self, level: Level) -> Result { - Ok(match level { - Level::Low => LevelResult::Left, - Level::High => LevelResult::Right, - }) - } - - fn anything(&self, value: Value) -> Result { - Ok(value) - } - - fn nothing(&self) {} - - fn inline(&self, value: InlineValue) { - self.recorded.lock().unwrap().push(format!( - "inline {} {}", - value.x, - value.y.unwrap_or_default() - )); - } - - async fn later(&self, text: String) -> Result { - Ok(format!("later {text}")) - } - - async fn done(&self) -> Result<(), ModuleError> { - self.events.on_done(); - Ok(()) - } - - fn lookup(&self, key: String, callback: Box) { - callback(format!("value of {key}"), key == "gpui"); - } - - async fn lookup_later( - &self, - key: String, - callback: Box, - ) -> Result { - let found = key == "gpui"; - if found { - callback(format!("later value of {key}"), true); - } - Ok(if found { "called" } else { "dropped" }.to_string()) - } - - fn sum(&self, data: ArrayBuffer) -> Result { - Ok(data.iter().map(|byte| f64::from(*byte)).sum()) - } - - fn reversed(&self, data: ArrayBuffer) -> Result { - let mut bytes = data.into_vec(); - bytes.reverse(); - Ok(bytes.into()) - } - - fn start(&self, steps: f64) { - for step in 1..=(steps as i32) { - self.events.on_progress(f64::from(step)); - } - self.events.send_event( - "fixtureTick", - Value::Object(vec![("n".into(), Value::Number(1.0))]), - ); - } - - fn add_listener(&self, _event_name: String) {} - - fn remove_listeners(&self, _count: f64) {} -} - -#[cfg(test)] -/// The sink is process-wide, so tests that read it take turns. -#[cfg(test)] -static SINK_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); - -#[cfg(test)] -fn probe() -> std::sync::Arc { - (native_probe_module::().create)(rn_gpui_module::EventEmitter::new(7)) -} - -#[cfg(test)] -fn index(name: &str) -> usize { - native_probe_module::() - .methods - .iter() - .position(|method| method.name == name) - .expect("the spec has this method") -} - -#[cfg(test)] -fn call(name: &str, args: Vec) -> Result { - probe().call_value(index(name), args) -} - -#[test] -fn the_descriptor_describes_the_spec() { - let descriptor = native_probe_module::(); - assert_eq!(descriptor.name, "NativeProbe"); - assert_eq!(descriptor.thread, ModuleThread::Main); - assert_eq!(descriptor.methods.len(), 20); - assert_eq!(descriptor.events.len(), 2); - assert_eq!(descriptor.events[0].name, "onProgress"); - assert!(descriptor.events[0].has_value); - assert!(!descriptor.events[1].has_value); - let lookup = &descriptor.methods[index("lookup")]; - assert_eq!(lookup.callback_args, &[1]); - assert_eq!(lookup.kind, rn_gpui_module::MethodKind::Void); - let done = &descriptor.methods[index("done")]; - assert!(done.returns_void, "Promise resolves with undefined"); - let optional = &descriptor.methods[index("optionalValue")]; - assert_eq!(optional.arg_count, 2); - assert_eq!(optional.required_args, 2); - let nothing = &descriptor.methods[index("nothing")]; - assert_eq!(nothing.arg_count, 0); - assert_eq!(nothing.required_args, 0); -} - -#[test] -fn value_methods_convert_arguments_and_results() { - let value = call( - "scalar", - vec![ - Value::String("text".into()), - Value::Number(2.5), - Value::Number(1.0), - Value::Bool(true), - ], - ) - .expect("scalar works"); - assert!(matches!(value, Value::Bool(true))); - - let value = call( - "optionalValue", - vec![Value::Null, Value::String("here".into())], - ) - .expect("optionalValue works"); - assert!(matches!(value, Value::String(text) if text == "here")); - let value = call( - "optionalValue", - vec![Value::String("a".into()), Value::Null], - ) - .expect("optionalValue works"); - assert!(matches!(value, Value::String(text) if text == "a")); - - let value = call( - "lists", - vec![ - Value::Array(vec![Value::String("ab".into())]), - Value::Array(vec![Value::Number(1.0), Value::Number(2.0)]), - ], - ) - .expect("lists works"); - assert!(matches!(value, Value::Array(items) if items.len() == 1)); - - let options = Value::Object(vec![ - ("type".into(), Value::String("first".into())), - ("label".into(), Value::String("first".into())), - ("count".into(), Value::Number(2.0)), - ("mode".into(), Value::String("right".into())), - ("ratio".into(), Value::Null), - ( - "nested".into(), - Value::Object(vec![ - ("flag".into(), Value::Bool(true)), - ( - "names".into(), - Value::Array(vec![Value::String("n".into())]), - ), - ]), - ), - ]); - let second = Value::Object(vec![ - ("type".into(), Value::String("second".into())), - ("count".into(), Value::Number(3.0)), - ("mode".into(), Value::String("left".into())), - ( - "nested".into(), - Value::Object(vec![ - ("flag".into(), Value::Bool(false)), - ("names".into(), Value::Array(Vec::new())), - ]), - ), - ]); - let value = call("options", vec![options, second]).expect("options works"); - let Value::Object(fields) = &value else { - panic!("options returns an object"); - }; - let field = |name: &str| { - fields - .iter() - .find(|(key, _)| key == name) - .map(|(_, value)| value) - .expect("field") - }; - assert!(matches!(field("label"), Value::String(text) if text == "first")); - assert!(matches!(field("count"), Value::Number(count) if *count == 5.0)); - assert!(matches!(field("mode"), Value::String(mode) if mode == "right")); - - let value = call("level", vec![Value::String("high".into())]).expect("level works"); - assert!(matches!(value, Value::String(mode) if mode == "right")); - - let value = call( - "anything", - vec![Value::Object(vec![("a".into(), Value::Number(1.0))])], - ) - .expect("anything works"); - assert!(matches!(value, Value::Object(fields) if fields.len() == 1)); -} - -#[test] -fn void_and_promise_methods_go_through_their_own_entry_points() { - let _guard = SINK_LOCK.lock().unwrap(); - let _ = rn_gpui_module::sink_calls(); - let module = probe(); - module - .clone() - .prepare_void(index("nothing"), Vec::new()) - .expect("nothing converts")(); - module - .clone() - .prepare_void( - index("inline"), - vec![Value::Object(vec![ - ("x".into(), Value::Number(1.5)), - ("y".into(), Value::String("why".into())), - ])], - ) - .expect("inline converts")(); - - let future = module - .clone() - .call_promise(index("later"), vec![Value::String("gpui".into())]) - .expect("later builds a future"); - let value = futures::executor::block_on(future).expect("later resolves"); - assert!(matches!(value, Value::String(text) if text == "later gpui")); - - let future = module - .clone() - .call_promise(index("done"), Vec::new()) - .expect("done builds a future"); - let value = futures::executor::block_on(future).expect("done resolves"); - assert!(matches!(value, Value::Null), "Promise resolves null"); - let events = rn_gpui_module::sink_calls(); - assert!( - events.iter().any(|call| matches!( - call, - rn_gpui_module::SinkCall::EmitEvent { - event, - value: None, - .. - } if event == "onDone" - )), - "an event without a payload reaches the host" - ); -} - -#[test] -fn callbacks_and_events_reach_the_host() { - let _guard = SINK_LOCK.lock().unwrap(); - let _ = rn_gpui_module::sink_calls(); - let module = probe(); - module - .clone() - .prepare_void( - index("lookup"), - vec![ - Value::String("gpui".into()), - Value::Callback(rn_gpui_module::RawCallback::new(21)), - ], - ) - .expect("lookup converts")(); - module - .clone() - .prepare_void(index("start"), vec![Value::Number(2.0)]) - .expect("start converts")(); - - let calls = rn_gpui_module::sink_calls(); - let invoked = calls.iter().find_map(|call| match call { - rn_gpui_module::SinkCall::InvokeCallback { id, args } => Some((*id, args)), - _ => None, - }); - let (id, args) = invoked.expect("the callback was invoked"); - assert_eq!(id, 21); - assert!(matches!(&args[0], Value::String(text) if text == "value of gpui")); - assert!(matches!(&args[1], Value::Bool(true))); - let progress: Vec = calls - .iter() - .filter_map(|call| match call { - rn_gpui_module::SinkCall::EmitEvent { event, value, .. } if event == "onProgress" => { - match value { - Some(Value::Number(number)) => Some(*number), - _ => None, - } - } - _ => None, - }) - .collect(); - assert_eq!(progress, vec![1.0, 2.0]); - assert!(calls.iter().any(|call| matches!( - call, - rn_gpui_module::SinkCall::SendEvent { name, .. } if name == "fixtureTick" - ))); -} - -#[test] -fn an_array_buffer_crosses_as_bytes() { - let value = call("sum", vec![Value::Buffer(vec![1, 2, 3, 250])]).expect("sum reads the bytes"); - assert!(matches!(value, Value::Number(total) if total == 256.0)); - - let value = - call("reversed", vec![Value::Buffer(vec![1, 2, 3])]).expect("reversed builds a buffer"); - assert!(matches!(value, Value::Buffer(bytes) if bytes == vec![3, 2, 1])); - - let error = - call("sum", vec![Value::Array(Vec::new())]).expect_err("an array is not an ArrayBuffer"); - assert_eq!( - error.message, - "NativeProbe.sum: argument 0 (data): expected ArrayBuffer, got array" - ); -} - -#[test] -fn a_callback_on_a_promise_method_is_invoked_while_it_runs() { - let _guard = SINK_LOCK.lock().unwrap(); - let _ = rn_gpui_module::sink_calls(); - let module = probe(); - - let future = module - .clone() - .call_promise( - index("lookupLater"), - vec![ - Value::String("gpui".into()), - Value::Callback(rn_gpui_module::RawCallback::new(31)), - ], - ) - .expect("lookupLater builds a future"); - let value = futures::executor::block_on(future).expect("lookupLater resolves"); - assert!(matches!(value, Value::String(text) if text == "called")); - - // A callback the method does not call is released without being invoked. - let future = module - .clone() - .call_promise( - index("lookupLater"), - vec![ - Value::String("missing".into()), - Value::Callback(rn_gpui_module::RawCallback::new(32)), - ], - ) - .expect("lookupLater builds a future"); - let value = futures::executor::block_on(future).expect("lookupLater resolves"); - assert!(matches!(value, Value::String(text) if text == "dropped")); - - let calls = rn_gpui_module::sink_calls(); - let invoked: Vec = calls - .iter() - .filter_map(|call| match call { - rn_gpui_module::SinkCall::InvokeCallback { id, args } - if matches!(&args[0], Value::String(text) if text == "later value of gpui") => - { - Some(*id) - } - _ => None, - }) - .collect(); - assert_eq!(invoked, vec![31], "only the found key invokes its callback"); - let dropped: Vec = calls - .iter() - .filter_map(|call| match call { - rn_gpui_module::SinkCall::DropCallback { id } => Some(*id), - _ => None, - }) - .collect(); - assert_eq!(dropped, vec![32], "the other callback is dropped"); -} - -#[test] -fn a_wrong_argument_reports_the_module_method_and_field() { - let error = call("options", vec![Value::Number(1.0), Value::Number(1.0)]) - .expect_err("a wrong argument type is an error"); - assert_eq!( - error.message, - "NativeProbe.options: argument 0 (value): expected object, got number" - ); - - let error = call( - "options", - vec![ - Value::Object(vec![ - ("type".into(), Value::String("first".into())), - ("count".into(), Value::String("nope".into())), - ("mode".into(), Value::String("left".into())), - ( - "nested".into(), - Value::Object(vec![ - ("flag".into(), Value::Bool(true)), - ("names".into(), Value::Array(Vec::new())), - ]), - ), - ]), - Value::Object(vec![ - ("type".into(), Value::String("second".into())), - ("count".into(), Value::Number(1.0)), - ("mode".into(), Value::String("left".into())), - ( - "nested".into(), - Value::Object(vec![ - ("flag".into(), Value::Bool(true)), - ("names".into(), Value::Array(Vec::new())), - ]), - ), - ]), - ], - ) - .expect_err("a wrong field type is an error"); - assert_eq!( - error.message, - "NativeProbe.options: argument 0 (value).count: expected Int32, got string" - ); - - let error = call("level", vec![Value::String("sideways".into())]).expect_err("bad enum"); - assert_eq!( - error.message, - "NativeProbe.level: argument 0 (level): expected one of \"low\", \"high\", got \"sideways\"" - ); - - let error = call("scalar", Vec::new()).expect_err("missing argument"); - assert_eq!( - error.message, - "NativeProbe.scalar: argument 0 (text) is missing" - ); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/module.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/module.rs deleted file mode 100644 index cc9614bcae..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-module/tests/module.rs +++ /dev/null @@ -1,419 +0,0 @@ -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; -use std::time::Duration; - -use rn_gpui_module::{ - descriptor, register, sink_calls, spawn_main, EventEmitter, EventInfo, FromValue, IntoValue, - Job, MethodInfo, MethodKind, ModuleDescriptor, ModuleError, ModuleInstance, ModuleQueue, - ModuleThread, Path, RawCallback, SinkCall, Value, -}; - -/// The sink is process-wide, so tests that read it take turns. -static SINK_LOCK: Mutex<()> = Mutex::new(()); - -fn read(value: Value, module: &'static str, method: &'static str) -> T { - let mut path = Path::argument(module, method, 0, "value"); - T::from_value(value, &mut path).expect("value converts") -} - -fn read_err(value: Value) -> ModuleError { - let mut path = Path::argument("Fixture", "summarize", 1, "options"); - match T::from_value(value, &mut path) { - Ok(_) => panic!("expected a conversion error"), - Err(error) => error, - } -} - -#[test] -fn values_round_trip_through_every_type() { - assert_eq!(read::(Value::String("hi".into()), "M", "m"), "hi"); - assert_eq!(read::(Value::Number(1.5), "M", "m"), 1.5); - assert_eq!(read::(Value::Number(7.0), "M", "m"), 7); - assert!(read::(Value::Bool(true), "M", "m")); - assert_eq!(read::<()>(Value::Null, "M", "m"), ()); - assert_eq!(read::>(Value::Null, "M", "m"), None); - assert_eq!( - read::>(Value::String("x".into()), "M", "m"), - Some("x".to_string()) - ); - assert_eq!( - read::>( - Value::Array(vec![Value::Number(1.0), Value::Number(2.0)]), - "M", - "m" - ), - vec![1, 2] - ); - let nested = Value::Object(vec![( - "tags".to_string(), - Value::Array(vec![Value::String("a".into())]), - )]); - let Value::Object(fields) = nested else { - unreachable!() - }; - assert_eq!(fields.len(), 1); - - assert_eq!(String::from("s").into_value().type_name(), "string"); - assert_eq!(1.5f64.into_value().type_name(), "number"); - assert_eq!(3i32.into_value().type_name(), "number"); - assert_eq!(true.into_value().type_name(), "boolean"); - assert_eq!(().into_value().type_name(), "null"); - assert_eq!(None::.into_value().type_name(), "null"); - assert_eq!( - vec![1i32, 2].into_value().type_name(), - "array", - "Vec converts to an array" - ); - assert_eq!(Value::Null.into_value().type_name(), "null"); -} - -#[test] -fn conversion_errors_name_the_argument_and_field() { - let error = read_err::(Value::Number(1.0)); - assert_eq!( - error.message, - "Fixture.summarize: argument 1 (options): expected string, got number" - ); - - let mut path = Path::argument("Fixture", "summarize", 1, "options"); - let error = rn_gpui_module::__private::field::(&mut path, "label", Value::Number(1.0)) - .expect_err("expected a conversion error"); - assert_eq!( - error.message, - "Fixture.summarize: argument 1 (options).label: expected string, got number" - ); - - let error = read_err::>(Value::Array(vec![Value::Number(2.0)])); - assert_eq!( - error.message, - "Fixture.summarize: argument 1 (options).0: expected string, got number" - ); - - let error = read_err::>(Value::Null); - assert_eq!( - error.message, - "Fixture.summarize: argument 1 (options): expected array, got null" - ); - - let error = read_err::(Value::Number(1.5)); - assert_eq!( - error.message, - "Fixture.summarize: argument 1 (options): expected Int32, got 1.5" - ); - - let error = ModuleError::with_code("E_X", "bad"); - assert_eq!(error.code.as_deref(), Some("E_X")); - assert_eq!(error.to_string(), "bad"); - assert_eq!(ModuleError::from("plain").message, "plain"); - assert_eq!(ModuleError::from(String::from("owned")).message, "owned"); -} - -#[test] -fn callbacks_and_events_reach_the_sink() { - let _guard = SINK_LOCK.lock().unwrap(); - let _ = sink_calls(); - let callback = RawCallback::new(11); - assert_eq!(callback.id(), 11); - callback.invoke(vec![Value::String("value".into()), Value::Bool(true)]); - let dropped = RawCallback::new(12); - drop(dropped); - let events = EventEmitter::new(3); - events.emit("onProgress", Some(Value::Number(1.0))); - events.emit("onDone", None); - events.send_event( - "fixtureTick", - Value::Object(vec![("n".into(), Value::Number(1.0))]), - ); - - let calls = sink_calls(); - assert_eq!(calls.len(), 5, "unexpected calls: {calls:?}"); - match &calls[0] { - SinkCall::InvokeCallback { id, args } => { - assert_eq!(*id, 11); - assert_eq!(args.len(), 2); - assert!(matches!(&args[0], Value::String(text) if text == "value")); - assert!(matches!(&args[1], Value::Bool(true))); - } - other => panic!("expected an invoke, got {other:?}"), - } - assert!(matches!(&calls[1], SinkCall::DropCallback { id } if *id == 12)); - assert!( - matches!(&calls[2], SinkCall::EmitEvent { module, event, value } if *module == 3 && event == "onProgress" && matches!(value, Some(Value::Number(_)))) - ); - assert!( - matches!(&calls[3], SinkCall::EmitEvent { event, value, .. } if event == "onDone" && value.is_none()) - ); - assert!(matches!(&calls[4], SinkCall::SendEvent { name, .. } if name == "fixtureTick")); -} - -struct Fixture { - _events: EventEmitter, - calls: Arc, -} - -impl Fixture { - fn greet(&self, name: String) -> Result { - self.calls.fetch_add(1, Ordering::SeqCst); - Ok(format!("hi {name}")) - } - - fn boom(&self) { - panic!("boom"); - } -} - -impl ModuleInstance for Fixture { - fn call_value(&self, method: usize, args: Vec) -> Result { - match method { - 0 => { - let mut args = rn_gpui_module::__private::Args::new("Fixture", "greet", args); - let name: String = args.next("name")?; - let greeting = rn_gpui_module::__private::catch(|| self.greet(name))??; - Ok(greeting.into_value()) - } - _ => Err(ModuleError::new("Fixture: unknown method")), - } - } - - fn prepare_void( - self: Arc, - method: usize, - _args: Vec, - ) -> Result, ModuleError> { - match method { - 1 => Ok(Box::new(move || { - rn_gpui_module::__private::run_void("Fixture.boom", move || self.boom()) - })), - _ => Err(ModuleError::new("Fixture: unknown method")), - } - } - - fn call_promise( - self: Arc, - _method: usize, - _args: Vec, - ) -> Result>, ModuleError> { - Err(ModuleError::new("Fixture: no promise method")) - } -} - -static FIXTURE_CALLS: Mutex>> = Mutex::new(None); - -fn create_fixture(events: EventEmitter) -> Arc { - let calls = Arc::new(AtomicUsize::new(0)); - *FIXTURE_CALLS.lock().unwrap() = Some(calls.clone()); - Arc::new(Fixture { - _events: events, - calls, - }) -} - -const METHODS: &[MethodInfo] = &[ - MethodInfo { - name: "greet", - arg_count: 1, - required_args: 1, - kind: MethodKind::Value, - returns_void: false, - callback_args: &[], - }, - MethodInfo { - name: "boom", - arg_count: 0, - required_args: 0, - kind: MethodKind::Void, - returns_void: true, - callback_args: &[], - }, -]; - -const EVENTS: &[EventInfo] = &[EventInfo { - name: "onProgress", - has_value: true, -}]; - -#[test] -fn the_registry_finds_a_module_and_rejects_a_duplicate() { - register(ModuleDescriptor { - name: "Fixture", - thread: ModuleThread::Own, - methods: METHODS, - events: EVENTS, - create: create_fixture, - }); - let found = descriptor("Fixture").expect("registered"); - assert_eq!(found.methods.len(), 2); - assert_eq!(found.methods[0].name, "greet"); - assert_eq!(found.thread, ModuleThread::Own); - assert!(descriptor("Missing").is_none()); - - let duplicate = std::panic::catch_unwind(|| { - register(ModuleDescriptor { - name: "Fixture", - thread: ModuleThread::Own, - methods: METHODS, - events: EVENTS, - create: create_fixture, - }) - }); - assert!(duplicate.is_err(), "a duplicate name must panic"); -} - -#[test] -fn a_module_instance_converts_arguments_and_turns_panics_into_errors() { - register(ModuleDescriptor { - name: "FixtureCalls", - thread: ModuleThread::Main, - methods: METHODS, - events: EVENTS, - create: create_fixture, - }); - let module = (descriptor("FixtureCalls").expect("registered").create)(EventEmitter::new(9)); - let value = module - .call_value(0, vec![Value::String("gpui".into())]) - .expect("greet works"); - assert!(matches!(value, Value::String(text) if text == "hi gpui")); - - let error = module - .call_value(0, Vec::new()) - .expect_err("missing argument"); - let _ = &error; - assert_eq!( - error.message, "Fixture.greet: argument 0 (name) is missing", - "the generated glue names the argument" - ); - - let work = module - .clone() - .prepare_void(1, Vec::new()) - .expect("prepared"); - work(); - let calls = sink_calls(); - assert!( - calls.iter().any(|call| matches!( - call, - SinkCall::Log { message } if message == "Fixture.boom: the module panicked: boom" - )), - "unexpected calls: {calls:?}" - ); -} - -#[test] -fn a_panic_becomes_an_error() { - let error = rn_gpui_module::__private::catch(|| panic!("boom")).expect_err("caught"); - assert_eq!(error.message, "the module panicked: boom"); - let ok = rn_gpui_module::__private::catch(|| 7).expect("no panic"); - assert_eq!(ok, 7); - - let error = futures::executor::block_on(async { - rn_gpui_module::__private::catch_async(async { panic!("async boom") }) - .await - .expect_err("caught") - }); - assert_eq!(error.message, "the module panicked: async boom"); -} - -#[test] -fn the_queue_runs_jobs_in_order_on_one_other_thread() { - let queue = ModuleQueue::new("FixtureQueue"); - let caller = std::thread::current().id(); - let threads = Arc::new(Mutex::new(Vec::new())); - let order = Arc::new(Mutex::new(Vec::new())); - let done = Arc::new(AtomicUsize::new(0)); - for index in 0..8 { - let threads = threads.clone(); - let order = order.clone(); - let done = done.clone(); - queue.post(Box::new(move || { - threads.lock().unwrap().push(std::thread::current().id()); - order.lock().unwrap().push(index); - done.fetch_add(1, Ordering::SeqCst); - Box::pin(async {}) - })); - } - let awaited = Arc::new(AtomicUsize::new(0)); - let awaited_job = awaited.clone(); - queue.post(Box::new(move || { - Box::pin(async move { - futures::future::ready(()).await; - std::thread::sleep(Duration::from_millis(20)); - awaited_job.fetch_add(1, Ordering::SeqCst); - }) - })); - let after = awaited.clone(); - queue.post(Box::new(move || { - Box::pin(async move { - assert_eq!( - after.load(Ordering::SeqCst), - 1, - "the awaiting job ran first" - ); - }) - })); - for _ in 0..500 { - if done.load(Ordering::SeqCst) == 8 && awaited.load(Ordering::SeqCst) == 1 { - break; - } - std::thread::sleep(Duration::from_millis(10)); - } - assert_eq!(done.load(Ordering::SeqCst), 8); - assert_eq!(awaited.load(Ordering::SeqCst), 1); - assert_eq!(*order.lock().unwrap(), (0..8).collect::>()); - assert!( - threads.lock().unwrap().iter().all(|id| *id != caller), - "jobs must not run on the caller's thread" - ); - assert_eq!(threads.lock().unwrap().len(), 8); - assert!( - threads - .lock() - .unwrap() - .windows(2) - .all(|pair| pair[0] == pair[1]), - "every job must run on the same thread" - ); -} - -#[test] -fn dropping_the_queue_with_pending_jobs_does_not_hang() { - let queue = ModuleQueue::new("FixtureDrop"); - let started = Arc::new(AtomicUsize::new(0)); - for _ in 0..4 { - let started = started.clone(); - queue.post(Box::new(move || { - Box::pin(async move { - started.fetch_add(1, Ordering::SeqCst); - std::thread::sleep(Duration::from_millis(10)); - }) - })); - } - queue.post(Box::new(|| { - Box::pin(async { - futures::future::pending::<()>().await; - }) - })); - drop(queue); - assert!(started.load(Ordering::SeqCst) <= 4); -} - -#[test] -fn spawn_main_without_a_spawner_drops_the_job() { - let ran = Arc::new(AtomicUsize::new(0)); - let job_ran = ran.clone(); - let job: Job = Box::new(move || { - Box::pin(async move { - job_ran.fetch_add(1, Ordering::SeqCst); - }) - }); - spawn_main(job); - assert_eq!(ran.load(Ordering::SeqCst), 0); -} - -#[test] -fn a_value_callback_is_debug_only() { - let _guard = SINK_LOCK.lock().unwrap(); - let value = Value::Callback(RawCallback::new(1)); - let text = format!("{value:?}"); - assert!(text.contains("RawCallback"), "{text}"); - drop(value); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/Cargo.toml b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/Cargo.toml deleted file mode 100644 index 54daf29498..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "rn-gpui-sys" -version = "0.1.0" -edition = "2021" -links = "rn_gpui_core" - -[dependencies] -cxx = { workspace = true } -log = { workspace = true } -rn-gpui-module = { path = "../rn-gpui-module" } - -[build-dependencies] -cxx-build = { workspace = true } -cmake = { workspace = true } -serde_json = { workspace = true } diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/build.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/build.rs deleted file mode 100644 index 6795ab3475..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/build.rs +++ /dev/null @@ -1,1810 +0,0 @@ -//! The cxx bridge is generated first: the C++ glue CMake compiles includes -//! its header. - -use std::env; -use std::fs::{self, OpenOptions}; -use std::path::{Path, PathBuf}; -use std::process::Command; - -/// Bumped whenever the shape of `.configure-inputs` changes, so an upgrade -/// forces exactly one reconfigure instead of leaving a stale build. -const STAMP_VERSION: &str = "4"; - -/// Environment variables the `cmake` and `cc` crates read while generating the -/// build system, and which they resolve through a target-prefixed name first. -/// The `cmake` crate (`cmake-0.1.58/src/lib.rs`) resolves these in -/// `getenv_target_os` as `_`, `_`, then `TARGET_`/`HOST_`, then ``; the `cc` crate -/// (`cc-1.5.1/src/lib.rs`, `target_envs`) resolves `CC`/`CXX`/flag variables the -/// same way. `configure_env_names` expands every base listed here to all those -/// forms. -const CONFIGURE_ENV_VAR_BASES: &[&str] = &[ - // Compilers and flags the generated project is handed. - "CC", - "CXX", - "CFLAGS", - "CXXFLAGS", - "CMAKE_PREFIX_PATH", - "CMAKE_GENERATOR", - "CMAKE_TOOLCHAIN_FILE", - // Programs the `cmake` crate may invoke. - "CMAKE", - "EMCMAKE", - "EMMAKE", - // Apple SDK selection (read by `cc`, then handed to CMake). - "MACOSX_DEPLOYMENT_TARGET", - "SDKROOT", -]; - -/// Cargo-provided variables the `cmake` crate reads directly at configure time -/// (`cmake-0.1.58/src/lib.rs` lines 134-170, 442-460). These have no useful -/// target-prefixed form, so only the plain name goes into the stamp. -const CONFIGURE_CARGO_VARS: &[&str] = &[ - "OPT_LEVEL", - "DEBUG", - "PROFILE", - "HOST", - "CARGO_CFG_TARGET_OS", - "CARGO_CFG_TARGET_ARCH", - "CARGO_CFG_TARGET_ENV", -]; - -fn main() { - println!("cargo:rerun-if-changed=src/lib.rs"); - println!("cargo:rerun-if-changed=build.rs"); - for var in [ - "RN_GPUI_PREBUILT_DIR", - "RN_GPUI_BUILD_FROM_SOURCE", - "RN_GPUI_PREBUILT_CACHE", - "RN_GPUI_NATIVE_DEPS_CACHE", - "XDG_CACHE_HOME", - "LOCALAPPDATA", - "RN_GPUI_PREBUILT_OFFLINE", - "CARGO_NET_OFFLINE", - "GITHUB_TOKEN", - "GH_TOKEN", - ] { - println!("cargo:rerun-if-env-changed={var}"); - } - watch_configure_envs(); - - let manifest_dir = - PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")); - watch_cpp_tree(&manifest_dir.join("cpp"), &[]); - let react_gpui_dir = manifest_dir.parent().expect("ReactGpui dir").to_path_buf(); - let package_dir = react_gpui_dir - .parent() - .expect("the platform package dir") - .to_path_buf(); - - // Counting parent directories can only be right in one of the two layouts - // this crate builds in: a repository checkout, or `node_modules` in an app. - // Look the dependency up instead. - let react_native_dir = find_node_module(&package_dir, "react-native").unwrap_or_else(|| { - panic!( - "react-native was not found in any node_modules at or above {}", - package_dir.display() - ) - }); - let react_cxx_platform_dir = package_dir.join("ReactCxxPlatform"); - // The app root: the directory that holds `node_modules`. Found from where - // react-native was installed, which is the only anchor that holds in a - // repository checkout and in an app alike. - let node_modules_dir = react_native_dir - .parent() - .expect("react-native lives in a node_modules directory") - .to_path_buf(); - let app_root = node_modules_dir - .parent() - .expect("node_modules has a parent directory") - .to_path_buf(); - for changed_platform_source in [ - "react/io/ImageLoaderModule.cpp", - "react/io/ImageLoaderModule.h", - "react/io/WebSocketModule.cpp", - "react/io/WebSocketModule.h", - "react/runtime/ReactCxxTurboModuleProvider.cpp", - "react/runtime/ReactCxxTurboModuleProvider.h", - "react/runtime/ReactHost.cpp", - "react/runtime/PlatformTimerRegistryImpl.cpp", - ] { - println!( - "cargo:rerun-if-changed={}", - react_cxx_platform_dir - .join(changed_platform_source) - .display() - ); - } - // Tests and the Android/iOS/JNI platform code here are never compiled. - watch_cpp_tree( - &react_cxx_platform_dir, - &["tests", "__tests__", "android", "ios", "jni"], - ); - let overrides_dir = package_dir.join("ReactCommonOverrides"); - println!("cargo:rerun-if-changed={}", overrides_dir.display()); - - let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is set")); - let target_triple = env::var("TARGET").expect("TARGET is set"); - let cargo_target_dir = cargo_target_dir(&out_dir, &target_triple); - let cmake_build_type = cmake_build_type(); - let cmake_out_dir = cargo_target_dir - .join("rn-gpui-cmake") - .join(cmake_triple_dir(&target_triple)) - .join(cmake_build_type); - - let autolink_manifest = env::var_os("RN_GPUI_AUTOLINK_MANIFEST") - .map(PathBuf::from) - .unwrap_or_else(|| app_root.join("desktop/autolink/autolink.json")); - // The renderer is chosen in desktop/desktop.json and recorded by autolink, - // together with the React Native tree its C++ and codegen read. - let renderer = RendererSelection::read(&autolink_manifest); - // Fixed at build time, as Loom's other platforms do. A different value - // rebuilds Rust only; the C++ is the same for both. - println!( - "cargo:rustc-env=RN_GPUI_JS_THREAD_BUILT={}", - if renderer.js_thread.is_empty() { - "background" - } else { - &renderer.js_thread - } - ); - println!( - "cargo:rustc-env=RN_GPUI_LOOM_RENDERER_BUILT={}", - if renderer.loom { "1" } else { "0" } - ); - let react_native_dir = match &renderer.react_native_dir { - Some(dir) if renderer.loom => { - assert!( - dir.join("package.json").is_file(), - "the loom renderer's React Native tree {} does not exist; run `npx react-native-gpui autolink`", - dir.display() - ); - println!( - "cargo:rerun-if-changed={}", - dir.join(".loom-stamp.json").display() - ); - dir.clone() - } - _ => react_native_dir, - }; - let react_common_dir = react_native_dir.join("ReactCommon"); - // Generated sources live beside the CMake build tree instead of Cargo's - // OUT_DIR. The OUT_DIR hash changes with the workspace and feature set, and - // a changed include path would make CMake rebuild every C++ file. - let renderer_name = if renderer.loom { "loom" } else { "fabric" }; - let prebuilt_dir = select_prebuilt_dir( - &package_dir, - &target_triple, - &prebuilt_mode(&autolink_manifest), - renderer_name, - ); - // A prebuilt build keeps its own CMake directory. Sharing one with source - // builds leaves their librn_gpui_core.a on the linker search path, where it - // shadows the prebuilt archive and mixes two React Native ABIs. - let cmake_out_dir = if prebuilt_dir.is_some() { - let suffix = if renderer.loom { - "loom-prebuilt" - } else { - "prebuilt" - }; - cmake_out_dir.with_file_name(format!("{cmake_build_type}-{suffix}")) - } else if renderer.loom { - // Loom's headers change the layout of React Native's classes, so a - // Loom build and a Fabric build must not share objects. - cmake_out_dir.with_file_name(format!("{cmake_build_type}-loom")) - } else { - cmake_out_dir - }; - let generated_dir = cmake_out_dir.join("generated"); - let generated_rncore = generated_dir.join("fbreactnativespec"); - let generated_rncore_scratch = generated_dir.join("fbreactnativespec.tmp"); - let cxxbridge_include = generated_dir.join("cxxbridge-include"); - - fs::create_dir_all(&cmake_out_dir).expect("create shared CMake output directory"); - // Two cargo invocations in one tree write the same generated directories - // now, so the lock covers codegen as well as the CMake build. - let cmake_lock = OpenOptions::new() - .read(true) - .write(true) - .create(true) - .open(cmake_out_dir.join(".configure-build.lock")) - .expect("open shared CMake build lock"); - cmake_lock - .lock() - .expect("lock shared CMake build directory"); - - let fb_spec_codegen = manifest_dir.join("scripts/generate-fbreactnativespec.cjs"); - println!("cargo:rerun-if-changed={}", fb_spec_codegen.display()); - println!( - "cargo:rerun-if-changed={}", - package_dir.join("package.json").display() - ); - println!( - "cargo:rerun-if-changed={}", - react_native_dir.join("package.json").display() - ); - // Usually a sibling of react-native; a hoisting package manager can put it - // higher, which the lookup covers. - let codegen_package = find_node_module(&package_dir, "@react-native/codegen") - .unwrap_or_else(|| node_modules_dir.join("@react-native/codegen")); - println!( - "cargo:rerun-if-changed={}", - codegen_package.join("package.json").display() - ); - let codegen_inputs = fb_spec_codegen_inputs( - &fb_spec_codegen, - &package_dir, - &react_native_dir, - &codegen_package, - ); - for (_, file) in &codegen_inputs { - println!("cargo:rerun-if-changed={}", file.display()); - } - // The codegen takes seconds and its inputs only change with a React Native - // or codegen upgrade, so it runs when their contents changed. The digest - // names files relative to their package, so a copied target dir in another - // checkout still matches. - let codegen_stamp = generated_dir.join(".fbreactnativespec-inputs"); - let codegen_inputs_digest = files_digest(&codegen_inputs); - if !generated_rncore.is_dir() - || !fs::read_to_string(&codegen_stamp).is_ok_and(|stamp| stamp == codegen_inputs_digest) - { - // Codegen recreates its output directory, so generate into a scratch - // dir and sync. Rewriting unchanged headers would recompile most of RN. - let status = Command::new("node") - .arg(&fb_spec_codegen) - .arg(&react_native_dir) - .arg(&generated_rncore_scratch) - .status() - .expect("run React Native core Codegen; Node.js must be installed"); - assert!( - status.success(), - "React Native FBReactNativeSpec Codegen failed" - ); - sync_tree(&generated_rncore_scratch, &generated_rncore); - fs::write(&codegen_stamp, &codegen_inputs_digest).expect("write codegen inputs stamp"); - } - - // The app root: the directory that holds `node_modules`. When autolink ran - // it named the manifest, whose location is the app's `desktop/autolink/`; - // otherwise the `node_modules` that holds react-native is the anchor. - let autolink_cmake = env::var_os("RN_GPUI_AUTOLINK_CMAKE") - .map(PathBuf::from) - .unwrap_or_else(|| app_root.join("desktop/autolink/autolink.cmake")); - let project_root = autolink_cmake - .parent() - .and_then(Path::parent) - .and_then(Path::parent) - .unwrap_or(&app_root) - .to_path_buf(); - println!("cargo:rerun-if-env-changed=RN_GPUI_AUTOLINK_MANIFEST"); - println!("cargo:rerun-if-env-changed=RN_GPUI_AUTOLINK_CMAKE"); - watch_generated_file(&autolink_cmake); - // Autolinked CMake projects live outside this crate, so Cargo does not see - // edits to them unless each directory is named here. - for line in fs::read_to_string(&autolink_cmake) - .unwrap_or_default() - .lines() - { - if let Some(directory) = line - .strip_prefix("add_subdirectory(\"") - .and_then(|rest| rest.split('"').next()) - { - println!("cargo:rerun-if-changed={directory}"); - } - } - // The C++ the app contributes: the sources and the headers it includes, - // among them the host component glue autolink generates. - for line in fs::read_to_string(&autolink_cmake) - .unwrap_or_default() - .lines() - { - let sources = line.contains("RN_GPUI_APP_CPP_SOURCES"); - let includes = line.contains("RN_GPUI_APP_CPP_INCLUDE_DIRS"); - if !sources && !includes { - continue; - } - for quoted in line.split('"').skip(1).step_by(2) { - let path = PathBuf::from(quoted); - if sources { - println!("cargo:rerun-if-changed={}", path.display()); - } else { - watch_cpp_tree(&path, &[]); - } - } - } - let cpp_provider = autolink_cmake - .parent() - .unwrap_or(&autolink_cmake) - .join("CppTurboModules.generated.cpp"); - watch_generated_file(&cpp_provider); - watch_generated_file(&autolink_manifest); - if let Ok(manifest) = fs::read_to_string(&autolink_manifest) { - if let Ok(manifest) = serde_json::from_str::(&manifest) { - if let Some(modules) = manifest - .get("cppTurboModules") - .and_then(|value| value.as_array()) - { - // The C++ sources, the specs and the headers generated from - // them: a spec edit only reaches the build through its header. - for key in ["sources", "specs", "headers"] { - for source in modules - .iter() - .filter_map(|module| module.get(key)) - .filter_map(serde_json::Value::as_array) - .flatten() - .filter_map(serde_json::Value::as_str) - { - println!("cargo:rerun-if-changed={source}"); - } - } - } - if let Some(projects) = manifest - .get("cmakeProjects") - .and_then(|value| value.as_array()) - { - for project in projects.iter().filter_map(serde_json::Value::as_str) { - println!( - "cargo:rerun-if-changed={}", - PathBuf::from(project).join("CMakeLists.txt").display() - ); - } - } - // The active engine's Node-API export list, if it ships one. On - // Windows the app's executable has to re-export every Node-API - // function, forwarded to the engine's DLL, because an addon's import - // names the file it comes from and there is no global lookup. Only - // the path and the library name travel here; generating the module - // definition is the app build script's job, because linker arguments - // for an executable only take effect from the crate that builds it. - emit_node_api_exports(&manifest); - } - } - // ccache for the C++ this build compiles. React Native's own - // `ReactNative-application.cmake` sets the launcher for the app build, but - // this crate configures CMake itself and never includes that file, so - // without this the object cache is unused — CI measured 0 cacheable calls. - let use_ccache = env::var_os("RN_GPUI_DISABLE_CCACHE").is_none() && ccache_available(); - let mut prefix_map_flags = Vec::new(); - if use_ccache { - // ccache only hits across checkouts when neither the command line nor - // the object names the checkout's path. - let source_roots = [&package_dir, &app_root, &project_root].map(PathBuf::as_path); - if !msvc_target() { - prefix_map_flags = - prefix_map_flags_for(common_ancestor(&source_roots).as_deref(), &cmake_out_dir); - } - configure_ccache_env( - canonical_common_ancestor(&source_roots).as_deref(), - &cmake_out_dir, - ); - } - - let mut cxx_bridge = cxx_build::bridge("src/lib.rs"); - cxx_bridge.std("c++20").include("cpp"); - // The bridge compiles on every run of this script, so it goes through - // ccache too, with its sources in OUT_DIR mapped like the CMake build's. - let bridge_ccache_var = if use_ccache && !msvc_target() { - for flag in &prefix_map_flags { - cxx_bridge.flag(flag); - } - // Last, as OUT_DIR can sit inside the checkout. - let out_dir_path = cmake_path(&out_dir); - if !prefix_map_flags.is_empty() && !out_dir_path.contains(char::is_whitespace) { - cxx_bridge.flag(format!("-ffile-prefix-map={out_dir_path}=/rn-gpui/out")); - } - cxx_bridge.try_get_compiler().ok().and_then(|compiler| { - // A wrapper already in place (sccache through RUSTC_WRAPPER) stays. - let wrapped = compiler.to_command().get_program() != compiler.path().as_os_str(); - (!wrapped) - .then(|| launch_bridge_through_ccache(compiler.path(), &target_triple)) - .flatten() - }) - } else { - None - }; - cxx_bridge.compile("rn_gpui_cxx_bridge"); - if let Some(variable) = bridge_ccache_var { - // The `cmake` crate reads the same variable to pick its compiler. - env::remove_var(variable); - } - - let cxxbridge_generated = out_dir.join("cxxbridge").join("include"); - assert!( - cxxbridge_generated.join("rust").join("cxx.h").is_file(), - "cxx_build did not produce {}", - cxxbridge_generated.join("rust/cxx.h").display() - ); - // cxx_build rewrites its headers every run (copies on Windows), so CMake - // reads a mirror that only changes when the header contents do. - sync_tree(&cxxbridge_generated, &cxxbridge_include); - - let mut defines: Vec<(&str, String)> = vec![ - ("REACT_COMMON_DIR", cmake_path(&react_common_dir)), - ( - "REACT_CXX_PLATFORM_DIR", - cmake_path(&react_cxx_platform_dir), - ), - ("RN_GPUI_OVERRIDES_DIR", cmake_path(&overrides_dir)), - ( - "RN_GPUI_CXXBRIDGE_INCLUDE_DIR", - cmake_path(&cxxbridge_include), - ), - ( - "RN_GPUI_GENERATED_RNCORE_DIR", - cmake_path(&generated_rncore), - ), - ("RN_GPUI_PROJECT_ROOT", cmake_path(&project_root)), - ("RN_GPUI_AUTOLINK_CMAKE", cmake_path(autolink_cmake.clone())), - ( - "RN_GPUI_NATIVE_DEPS_CACHE", - cmake_path(native_deps_cache_dir(&cargo_target_dir)), - ), - ]; - if renderer.loom { - defines.push(("RN_GPUI_REACT_NATIVE_DIR", cmake_path(&react_native_dir))); - defines.push(("LOOM_RENDERER", "1".to_string())); - } - let codegen_digest = autolink_codegen_digest( - &autolink_cmake - .parent() - .unwrap_or(&autolink_cmake) - .join("codegen"), - ); - // CMake deletes its cache when the compiler path changes, and the configure - // it then re-runs has lost every -D argument and fails. Shells disagree on - // the path (the /usr/bin shim or the Xcode toolchain binary behind it), so - // name the shim unless the user chose a compiler. - if cfg!(target_os = "macos") && target_triple.contains("apple") { - // CMake otherwise defaults to the installed SDK, independently of - // Cargo's deployment target (including when reusing its cache). - if let Ok(minimum) = env::var("MACOSX_DEPLOYMENT_TARGET") { - defines.push(("CMAKE_OSX_DEPLOYMENT_TARGET", minimum)); - } - for (variable, tool, env_name) in [ - ("CMAKE_C_COMPILER", "/usr/bin/cc", "CC"), - ("CMAKE_CXX_COMPILER", "/usr/bin/c++", "CXX"), - ] { - println!("cargo:rerun-if-env-changed={env_name}"); - if env::var_os(env_name).is_none() { - defines.push((variable, tool.to_string())); - } - } - } - if use_ccache { - for variable in ["CMAKE_C_COMPILER_LAUNCHER", "CMAKE_CXX_COMPILER_LAUNCHER"] { - defines.push((variable, "ccache".to_string())); - } - // The `cmake` crate hands C and C++ flags over, but not Objective-C++ - // ones (the `.mm` sources on macOS). - if target_triple.contains("apple") && !prefix_map_flags.is_empty() { - let mut objcxx_flags = env::var("OBJCXXFLAGS").unwrap_or_default(); - for flag in &prefix_map_flags { - objcxx_flags.push(' '); - objcxx_flags.push_str(flag); - } - defines.push(("CMAKE_OBJCXX_FLAGS", objcxx_flags.trim().to_string())); - } - } - let generator = cmake_generator(use_ccache); - if msvc_target() { - // Rust always links the release CRT (msvcrt). CMake's Debug config - // would compile with /MDd and the final link then fails on - // _CrtDbgReport / _calloc_dbg, so pin every target, including - // subprojects that declare an older cmake_minimum_required, to /MD. - defines.push(("CMAKE_POLICY_DEFAULT_CMP0091", "NEW".to_string())); - defines.push(("CMAKE_MSVC_RUNTIME_LIBRARY", "MultiThreadedDLL".to_string())); - // ccache cannot cache /Zi (the compiler writes a shared PDB), so embed - // the debug info in each object (/Z7), in every subproject too. - defines.push(("CMAKE_POLICY_DEFAULT_CMP0141", "NEW".to_string())); - defines.push(( - "CMAKE_MSVC_DEBUG_INFORMATION_FORMAT", - "$<$:Embedded>".to_string(), - )); - } - if let Some(dir) = &prebuilt_dir { - defines.push(("RN_GPUI_PREBUILT_DIR", cmake_path(dir))); - // find_package caches the directory it found, so a new pin would - // otherwise keep linking the previous runtime. - defines.push(( - "react-native-gpui-prebuilt_DIR", - cmake_path(&dir.join("cmake")), - )); - defines.push(( - "RN_GPUI_OVERRIDES_SHA256", - overrides_sha256(&package_dir, renderer_name), - )); - } - - // A configure rewrites flags.make, and every object depends on it, so - // configuring on each build-script run would rebuild the whole C++ tree. - // Configure only when the inputs changed; otherwise run the build, whose - // own check still re-runs CMake when a CMakeLists or the cache changed. - // `RN_GPUI_FORCE_CMAKE_CONFIGURE=1` is the escape hatch when the stamp - // misses an input a future toolchain adds. - let build_dir = cmake_out_dir.join("build"); - let stamp = configure_stamp( - &defines, - cmake_build_type, - &target_triple, - &codegen_digest, - generator.unwrap_or_default(), - &prefix_map_flags, - ); - let stamp_path = cmake_out_dir.join(".configure-inputs"); - // The Visual Studio generators (MSVC's default) write `ALL_BUILD.vcxproj` - // rather than a Makefile; without it here every MSVC build reconfigured, and - // a configure that hands CMake other `cc` flags rebuilt all of the C++. - let generator_output_exists = build_dir.join("Makefile").is_file() - || build_dir.join("build.ninja").is_file() - || build_dir.join("ALL_BUILD.vcxproj").is_file(); - let configure = env_flag("RN_GPUI_FORCE_CMAKE_CONFIGURE") - || !fs::read_to_string(&stamp_path).is_ok_and(|previous| previous == stamp) - || !build_dir.join("CMakeCache.txt").is_file() - || !generator_output_exists; - - let dst = if configure { - let source_dir = manifest_dir.join("cpp"); - reuse_build_dir(&build_dir, &source_dir, generator); - let mut cmake_config = cmake::Config::new(&source_dir); - cmake_config - .out_dir(&cmake_out_dir) - .profile(cmake_build_type); - if let Some(generator) = generator { - cmake_config.generator(generator); - } - for flag in &prefix_map_flags { - cmake_config.cflag(flag).cxxflag(flag); - } - for (name, value) in &defines { - cmake_config.define(name, value); - } - // rn_gpui_modules links PUBLIC to rn_gpui_core, so this builds core too. - let dst = cmake_config.build_target("rn_gpui_modules").build(); - fs::write(&stamp_path, &stamp).expect("write configure inputs stamp"); - dst - } else { - run_cmake_build(&build_dir, cmake_build_type); - cmake_out_dir - }; - drop(cmake_lock); - - let cmake_build_dir = dst.join("build"); - println!( - "cargo:rustc-link-search=native={}", - cmake_build_dir.display() - ); - println!("cargo:rustc-link-lib=static:-bundle=rn_gpui_core"); - - let link_libs = cmake_manifest(&cmake_build_dir, "link_libs", cmake_build_type); - emit_link_libs(&link_libs, &out_dir); - - // Libraries with an `@rpath/...` install name cannot be found from - // `rustc-link-search` alone, and `cargo:rustc-link-arg` from this package - // would not reach the dependent binary. The directories are therefore - // exported as `links` metadata (DEP_RN_GPUI_CORE_RPATHS) for the rn-gpui - // package's build script, which turns them into linker rpath flags. - let rpath_dirs = cmake_manifest(&cmake_build_dir, "rpath_dirs", cmake_build_type); - emit_rpaths(&rpath_dirs); - // The CMake build above rewrites these when they change, which made Cargo - // re-run this script on the next build. Dated back to when Cargo started - // this run, the write is not taken for a change, and a later one still is. - if let Some(invoked) = out_dir - .parent() - .and_then(|dir| fs::metadata(dir.join("invoked.timestamp")).ok()) - .and_then(|metadata| metadata.modified().ok()) - { - for manifest in [&link_libs, &rpath_dirs] { - if fs::metadata(manifest) - .and_then(|metadata| metadata.modified()) - .is_ok_and(|modified| modified > invoked) - { - if let Ok(file) = OpenOptions::new().write(true).open(manifest) { - let _ = file.set_modified(invoked); - } - } - } - } - - match ( - env::var("CARGO_CFG_TARGET_OS").as_deref(), - env::var("CARGO_CFG_TARGET_ENV").as_deref(), - ) { - (Ok("macos"), _) => println!("cargo:rustc-link-lib=c++"), - (Ok("linux"), _) | (Ok("windows"), Ok("gnu")) => { - println!("cargo:rustc-link-lib=stdc++") - } - _ => {} - } - // The static OpenSSL and curl archives call into the Windows cryptography - // and event-log APIs without naming the import libraries (their `.drectve` - // sections are written for a build that links through `nmake`, not through - // CMake's imported targets). An *application* links these anyway because - // its Rust dependency tree brings them in (`ring`, `reqwest`), so the gap - // only shows up when a test binary links this crate on its own — - // `LNK2019: unresolved external symbol __imp_CryptGenRandom`, and so on. - // The CMake targets declare them (OpenSSL::Crypto's interface, `ws2_32` on - // folly), but `emit_link_libs` only understands archives this build - // produced, so the system libraries are named here. - if msvc_target() { - for library in [ - "crypt32", "advapi32", "userenv", "ws2_32", "bcrypt", "dbghelp", - ] { - println!("cargo:rustc-link-lib={library}"); - } - } - if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") { - for framework in [ - "Foundation", - "CoreFoundation", - "CoreGraphics", - "AppKit", - "Metal", - "QuartzCore", - // libcurl reads the system proxy settings on macOS through - // `SCDynamicStoreCopyProxies`. Nothing linked this framework until - // the Rust HTTP stack was removed: reqwest had pulled it in - // transitively, and without it the link fails on curl's macos.c. - "SystemConfiguration", - ] { - println!("cargo:rustc-link-lib=framework={framework}"); - } - } -} - -/// What `renderer` in `desktop/desktop.json` selected, as autolink recorded it. -struct RendererSelection { - loom: bool, - js_thread: String, - react_native_dir: Option, -} - -impl RendererSelection { - fn read(autolink_manifest: &Path) -> Self { - let renderer = fs::read_to_string(autolink_manifest) - .ok() - .and_then(|text| serde_json::from_str::(&text).ok()) - .and_then(|manifest| manifest.get("renderer").cloned()); - let text = |key: &str| { - renderer - .as_ref() - .and_then(|renderer| renderer.get(key)) - .and_then(serde_json::Value::as_str) - .map(str::to_owned) - }; - Self { - loom: text("name").as_deref() == Some("loom"), - js_thread: text("jsThread").unwrap_or_default(), - react_native_dir: text("reactNativeDir").map(PathBuf::from), - } - } -} - -fn sync_tree(src: &Path, dst: &Path) { - fs::create_dir_all(dst).expect("create generated output directory"); - let mut seen = std::collections::HashSet::new(); - for entry in fs::read_dir(src).expect("read generated directory") { - let entry = entry.expect("read generated entry"); - let name = entry.file_name(); - let from = entry.path(); - let to = dst.join(&name); - seen.insert(name); - // metadata() follows cxx_build's symlinks on Unix. - if fs::metadata(&from).expect("stat generated entry").is_dir() { - sync_tree(&from, &to); - continue; - } - let bytes = fs::read(&from).expect("read generated file"); - if to.is_dir() { - fs::remove_dir_all(&to).expect("replace generated directory"); - } - if fs::read(&to).ok().as_deref() != Some(&bytes[..]) { - fs::write(&to, &bytes).expect("write generated file"); - } - } - for entry in fs::read_dir(dst).expect("read generated mirror") { - let entry = entry.expect("read generated mirror entry"); - if !seen.contains(&entry.file_name()) { - let path = entry.path(); - if path.is_dir() { - fs::remove_dir_all(&path).expect("remove stale generated directory"); - } else { - fs::remove_file(&path).expect("remove stale generated file"); - } - } - } -} - -/// The files FBReactNativeSpec codegen reads, each with a name relative to its -/// package: the generator script and the pins it checks, the spec files in -/// react-native's `src` (codegen's own filter, `filterJSFile` in -/// `@react-native/codegen/lib/cli/combine/combine-utils.js`, widened to every -/// platform suffix), and the JavaScript of react-native's codegen scripts and -/// of `@react-native/codegen`. -fn fb_spec_codegen_inputs( - script: &Path, - package_dir: &Path, - react_native_dir: &Path, - codegen_package: &Path, -) -> Vec<(String, PathBuf)> { - let mut inputs = vec![ - ("script".to_string(), script.to_path_buf()), - ( - "core/package.json".to_string(), - package_dir.join("package.json"), - ), - ( - "react-native/package.json".to_string(), - react_native_dir.join("package.json"), - ), - ( - "codegen/package.json".to_string(), - codegen_package.join("package.json"), - ), - ]; - let is_js = |path: &Path| { - let name = path - .file_name() - .and_then(|name| name.to_str()) - .unwrap_or(""); - !name.ends_with(".d.ts") - && matches!( - path.extension().and_then(|ext| ext.to_str()), - Some("js" | "ts" | "tsx") - ) - }; - let is_spec = |path: &Path| { - let name = path - .file_name() - .and_then(|name| name.to_str()) - .unwrap_or(""); - is_js(path) && (name.starts_with("Native") || name.contains("NativeComponent")) - }; - for (label, root, filter) in [ - ( - "react-native", - react_native_dir.join("src"), - &is_spec as &dyn Fn(&Path) -> bool, - ), - ( - "react-native", - react_native_dir.join("scripts/codegen"), - &is_js, - ), - ("codegen", codegen_package.join("lib"), &is_js), - ] { - let mut files = Vec::new(); - collect_files(&root, filter, &mut files); - files.sort(); - let base = root.parent().unwrap_or(&root); - for file in files { - let relative = file.strip_prefix(base).unwrap_or(&file); - inputs.push(( - format!("{label}/{}", relative.to_string_lossy().replace('\\', "/")), - file, - )); - } - } - inputs -} - -fn collect_files(root: &Path, filter: &dyn Fn(&Path) -> bool, files: &mut Vec) { - let Ok(entries) = fs::read_dir(root) else { - return; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - if !matches!( - path.file_name().and_then(|name| name.to_str()), - Some("__tests__" | "__mocks__" | "__fixtures__") - ) { - collect_files(&path, filter, files); - } - } else if filter(&path) { - files.push(path); - } - } -} - -/// A digest of the files' names and contents. A missing file hashes as empty. -fn files_digest(files: &[(String, PathBuf)]) -> String { - use std::hash::{Hash, Hasher}; - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - STAMP_VERSION.hash(&mut hasher); - for (name, file) in files { - name.hash(&mut hasher); - fs::read(file).unwrap_or_default().hash(&mut hasher); - } - format!("{:016x}", hasher.finish()) -} - -fn watch_cpp_tree(root: &Path, skip_dirs: &[&str]) { - if !root.is_dir() { - return; - } - for entry in fs::read_dir(root).expect("read C++ source directory") { - let path = entry.expect("read C++ source entry").path(); - if path.is_dir() { - let name = path.file_name().and_then(|name| name.to_str()); - if matches!(name, Some("build" | "target")) - || name.is_some_and(|name| skip_dirs.contains(&name)) - { - continue; - } - watch_cpp_tree(&path, skip_dirs); - continue; - } - - let is_source = matches!( - path.extension().and_then(|ext| ext.to_str()), - Some("c" | "cc" | "cpp" | "cxx" | "m" | "mm" | "h" | "hh" | "hpp" | "hxx" | "cmake") - ) || path - .file_name() - .is_some_and(|name| name == "CMakeLists.txt"); - if is_source { - println!("cargo:rerun-if-changed={}", path.display()); - } - } -} - -/// Everything that changes what CMake configures. When it all matches the -/// previous run, the configure step is skipped: a reconfigure rewrites -/// `flags.make`, and make would then rebuild every object in the tree. -/// -/// This only lists inputs the `cmake` crate reads. `cc` resolves the compiler -/// variables through `target_envs` (see `configure_env_names`), and the values -/// inside `cc`'s own cache depend on `OPT_LEVEL`/`DEBUG`, which Cargo rewrites -/// for the whole build, not just this crate. -fn configure_stamp( - defines: &[(&str, String)], - profile: &str, - target: &str, - autolink_codegen: &str, - generator: &str, - compiler_flags: &[String], -) -> String { - let mut stamp = String::new(); - stamp.push_str("STAMP_VERSION="); - stamp.push_str(STAMP_VERSION); - stamp.push('\n'); - for (name, value) in defines { - stamp.push_str(name); - stamp.push('='); - stamp.push_str(value); - stamp.push('\n'); - } - for name in configure_env_names(target) { - stamp.push_str(&name); - stamp.push('='); - stamp.push_str(&env::var(name).unwrap_or_default()); - stamp.push('\n'); - } - stamp.push_str("profile="); - stamp.push_str(profile); - stamp.push('\n'); - stamp.push_str("target="); - stamp.push_str(target); - stamp.push('\n'); - stamp.push_str("autolink_codegen="); - stamp.push_str(autolink_codegen); - stamp.push('\n'); - stamp.push_str("cmake_version="); - stamp.push_str(&cmake_version()); - stamp.push('\n'); - stamp.push_str("generator="); - stamp.push_str(generator); - stamp.push('\n'); - stamp.push_str("compiler_flags="); - stamp.push_str(&compiler_flags.join(" ")); - stamp.push('\n'); - stamp -} - -/// The generator to hand CMake: Ninja when it is on `PATH`, unless the user -/// chose one through `CMAKE_GENERATOR` (in any form the `cmake` crate reads). -/// MSVC keeps the Visual Studio generator: Ninja there needs a developer -/// prompt's environment for every `cmake --build`, and the unity build and -/// `/MP` in `cpp/CMakeLists.txt` are tuned for MSBuild. -fn cmake_generator(use_ccache: bool) -> Option<&'static str> { - let target = env::var("TARGET").unwrap_or_default(); - let user_chose = configure_env_names(&target) - .iter() - .filter(|name| name.ends_with("CMAKE_GENERATOR") || name.starts_with("CMAKE_GENERATOR_")) - .any(|name| env::var_os(name).is_some_and(|value| !value.is_empty())); - if user_chose { - return None; - } - // MSVC keeps the Visual Studio generator, which ignores the compiler - // launcher, unless ccache can actually be used: then Ninja, which needs the - // compiler environment (vcvars) of the shell, so `cl.exe` must be on PATH. - if msvc_target() && !(use_ccache && program_on_path("cl")) { - return None; - } - program_on_path("ninja").then_some("Ninja") -} - -/// Keeps a build directory whose source or build path moved (another checkout, -/// or a target dir copied from one) instead of letting the `cmake` crate wipe -/// it: its `maybe_clear` deletes the whole directory when the cache names -/// another source dir, and CMake refuses a cache made in another build dir. -/// Only the cache goes, so the configure that follows starts clean while the -/// objects and downloaded dependencies stay for the build to reuse. A changed -/// generator also drops `CMakeFiles`, whose layout is generator-specific. -fn reuse_build_dir(build_dir: &Path, source_dir: &Path, generator: Option<&str>) { - let cache = build_dir.join("CMakeCache.txt"); - let Ok(contents) = fs::read_to_string(&cache) else { - return; - }; - let entry = |name: &str| { - contents.lines().find_map(|line| { - let (key, value) = line.split_once('=')?; - (key.split(':').next() == Some(name)).then(|| value.to_string()) - }) - }; - let same_dir = |cached: Option, current: &Path| { - let current = current - .canonicalize() - .unwrap_or_else(|_| current.to_path_buf()); - cached - .and_then(|cached| Path::new(&cached).canonicalize().ok()) - .is_some_and(|cached| cached == current) - }; - let generator_changed = - generator.is_some_and(|generator| entry("CMAKE_GENERATOR").as_deref() != Some(generator)); - let moved = !same_dir(entry("CMAKE_HOME_DIRECTORY"), source_dir) - || !same_dir(entry("CMAKE_CACHEFILE_DIR"), build_dir); - if !moved && !generator_changed { - return; - } - println!( - "rn-gpui-sys: {} changed; reconfiguring {} in place", - if generator_changed { - "CMake generator" - } else { - "source or build path" - }, - build_dir.display() - ); - fs::remove_file(&cache).expect("remove stale CMakeCache.txt"); - if generator_changed { - let _ = fs::remove_dir_all(build_dir.join("CMakeFiles")); - } -} - -/// The deepest directory that holds every one of `paths` (as given, and with -/// symlinks resolved), or `None` when that is the filesystem root. -fn common_ancestor(paths: &[&Path]) -> Option { - common_ancestor_of(paths.iter().map(|path| path.to_path_buf()).collect()) -} - -fn canonical_common_ancestor(paths: &[&Path]) -> Option { - common_ancestor_of( - paths - .iter() - .map(|path| path.canonicalize().unwrap_or_else(|_| path.to_path_buf())) - .collect(), - ) -} - -fn common_ancestor_of(paths: Vec) -> Option { - let first = paths.first()?; - let ancestor = first - .ancestors() - .find(|ancestor| paths.iter().all(|path| path.starts_with(ancestor)))?; - (ancestor.parent().is_some()).then(|| ancestor.to_path_buf()) -} - -/// `-ffile-prefix-map` flags (GCC 8+, Clang 10+) for the checkout (the -/// directory holding the package and the app's `node_modules`, spelled as the -/// build names it and with symlinks resolved) and the CMake output dir, mapped -/// to fixed names so objects and their debug info do not depend on where the -/// checkout lives. The build dir comes last because it can sit inside the -/// checkout, and the last matching map wins. They travel in CMake's -/// space-separated flag strings, so a path with whitespace is left unmapped. -/// The flags are not in `cpp/`, whose contents key the prebuilt runtime. -fn prefix_map_flags_for(source_root: Option<&Path>, cmake_out_dir: &Path) -> Vec { - let mut maps: Vec = Vec::new(); - let mut add = |path: &Path, name: &str| { - let path = cmake_path(path); - if path.contains(char::is_whitespace) { - return; - } - let map = format!("-ffile-prefix-map={path}={name}"); - if !maps.contains(&map) { - maps.push(map); - } - }; - if let Some(root) = source_root { - add(root, "/rn-gpui/src"); - if let Ok(canonical) = root.canonicalize() { - add(&canonical, "/rn-gpui/src"); - } - } - add(cmake_out_dir, "/rn-gpui/build"); - if let Ok(canonical) = cmake_out_dir.canonicalize() { - add(&canonical, "/rn-gpui/build"); - } - maps -} - -/// Points ccache at the paths the build uses, unless the user configured it: -/// `base_dir` makes it hash the checkout's paths relative to the build dir, and -/// `hash_dir` off stops it hashing the working directory, which the prefix maps -/// already keep out of the objects. -fn configure_ccache_env(source_root: Option<&Path>, cmake_out_dir: &Path) { - let ccache_config = |key: &str| { - Command::new("ccache") - .args(["-k", key]) - .output() - .ok() - .filter(|output| output.status.success()) - .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string()) - .unwrap_or_default() - }; - let mut vars = Vec::new(); - // MSVC is left without `base_dir`: the relative include paths it makes ccache - // write exceed `MAX_PATH` from the build dir. - if !msvc_target() - && env::var_os("CCACHE_BASEDIR").is_none() - && ccache_config("base_dir").is_empty() - { - if let Some(base) = - source_root.and_then(|root| canonical_common_ancestor(&[root, cmake_out_dir])) - { - vars.push(("CCACHE_BASEDIR", base.into_os_string())); - } - } - if !msvc_target() - && env::var_os("CCACHE_NOHASHDIR").is_none() - && env::var_os("CCACHE_HASHDIR").is_none() - { - vars.push(("CCACHE_NOHASHDIR", "1".into())); - } - for (name, value) in vars { - // The build script is single-threaded here; every CMake and compiler - // process it starts from now on inherits these. - env::set_var(name, value); - } -} - -/// A digest of the headers React Native's codegen made for the app's specs. The -/// configure step runs the codegen again for the libraries that read it, so a -/// changed spec has to configure again, and an unchanged one must not. -fn autolink_codegen_digest(root: &Path) -> String { - use std::hash::{Hash, Hasher}; - let mut files = Vec::new(); - collect_headers(root, &mut files); - files.sort(); - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - for file in files { - file.hash(&mut hasher); - fs::read(&file).unwrap_or_default().hash(&mut hasher); - println!("cargo:rerun-if-changed={}", file.display()); - } - format!("{:016x}", hasher.finish()) -} - -fn collect_headers(root: &Path, files: &mut Vec) { - let Ok(entries) = fs::read_dir(root) else { - return; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - collect_headers(&path, files); - } else if path.extension().is_some_and(|ext| ext == "h") { - files.push(path); - } - } -} - -/// Declares, once, every environment variable that `configure_stamp` reads, so -/// Cargo re-runs the build script when one changes. The target forms are -/// declared for every variable too: `configure_env_names` decides which one -/// actually lands in the stamp, but Cargo only needs to know that the script -/// depends on it. -fn watch_configure_envs() { - println!("cargo:rerun-if-env-changed=RN_GPUI_FORCE_CMAKE_CONFIGURE"); - for name in configure_env_names(&env::var("TARGET").unwrap_or_default()) { - println!("cargo:rerun-if-env-changed={name}"); - } -} - -/// The environment variable names that can change a CMake configure: each base -/// name, plus the target-specific forms the `cmake` and `cc` crates resolve, in -/// the same order they try them (`cmake::Config::getenv_target_os`). Duplicates -/// are removed and the list is sorted so the stamp is stable. -fn configure_env_names(target: &str) -> Vec { - if target.is_empty() { - return Vec::new(); - } - // `cc` replaces both `-` and `.` with `_`. - let target_underscored = target.replace(['-', '.'], "_"); - let kind = if target == env::var("HOST").unwrap_or_default() { - "HOST" - } else { - "TARGET" - }; - let mut names = Vec::new(); - for base in CONFIGURE_ENV_VAR_BASES { - for name in [ - format!("{base}_{target}"), - format!("{base}_{target_underscored}"), - format!("{kind}_{base}"), - (*base).to_string(), - ] { - if !names.contains(&name) { - names.push(name); - } - } - } - for name in CONFIGURE_CARGO_VARS { - let name = (*name).to_string(); - if !names.contains(&name) { - names.push(name); - } - } - names.sort(); - names -} - -/// The first line of `cmake --version`. A different CMake can accept or reject -/// different `-D` arguments, so it belongs in the stamp. Any failure yields an -/// empty string: version parsing never fails the build. -fn cmake_version() -> String { - let executable = env::var("CMAKE").unwrap_or_else(|_| "cmake".to_string()); - Command::new(executable) - .arg("--version") - .output() - .ok() - .filter(|output| output.status.success()) - .and_then(|output| { - String::from_utf8_lossy(&output.stdout) - .lines() - .next() - .map(str::to_string) - }) - .unwrap_or_default() -} - -/// Builds without configuring. CMake's own staleness check re-runs the -/// configure when a CMakeLists or the cache changed, so this is safe as long -/// as the configure inputs match `configure_stamp`. -fn run_cmake_build(build_dir: &Path, profile: &str) { - let mut command = Command::new("cmake"); - command - .arg("--build") - .arg(build_dir) - .arg("--target") - .arg("rn_gpui_modules") - .arg("--config") - .arg(profile); - if let Some(makeflags) = env::var_os("CARGO_MAKEFLAGS") { - command.env("MAKEFLAGS", makeflags); - } else if let Ok(jobs) = env::var("NUM_JOBS") { - command.arg("--parallel").arg(jobs); - } - let status = command - .status() - .expect("run cmake --build; cmake must be on PATH"); - assert!(status.success(), "CMake build of rn_gpui_modules failed"); -} - -/// The app's `project.desktop.prebuilt` option (`auto`, `always` or `never`), which -/// autolink copies into its manifest. A missing manifest or field means `auto`. -fn prebuilt_mode(autolink_manifest: &Path) -> String { - fs::read_to_string(autolink_manifest) - .ok() - .and_then(|text| serde_json::from_str::(&text).ok()) - .and_then(|manifest| manifest.get("prebuilt")?.as_str().map(str::to_owned)) - .unwrap_or_else(|| "auto".to_string()) -} - -/// Order: `RN_GPUI_BUILD_FROM_SOURCE=1` or mode `never` -> source; -/// `RN_GPUI_PREBUILT_DIR` -> use it; otherwise `prebuilt-binaries.mjs ensure` -/// downloads (or reads the cache) the pinned runtime. The pin is used only -/// while the C++ inputs still hash to the pinned input hash, wherever this -/// package is installed. Any failure falls back to source with one warning, -/// and mode `always` turns that failure into a panic. -fn select_prebuilt_dir( - package_dir: &Path, - target: &str, - mode: &str, - renderer: &str, -) -> Option { - let dir = select_prebuilt_dir_inner(package_dir, target, mode, renderer)?; - match prebuilt_version(&dir) { - Some(version) => println!( - "cargo:warning=rn-gpui-sys: using prebuilt {renderer} runtime {version} ({target})" - ), - None => println!( - "cargo:warning=rn-gpui-sys: using prebuilt {renderer} runtime {} ({target})", - dir.display() - ), - } - Some(dir) -} -/// The archive's own version, so the build output and the CI report can name -/// the runtime that was linked instead of just its cache directory. -fn prebuilt_version(dir: &Path) -> Option { - let text = fs::read_to_string(dir.join("manifest.json")).ok()?; - let manifest: serde_json::Value = serde_json::from_str(&text).ok()?; - manifest - .get("version") - .and_then(|value| value.as_str()) - .map(str::to_owned) -} - -fn select_prebuilt_dir_inner( - package_dir: &Path, - target: &str, - mode: &str, - renderer: &str, -) -> Option { - if env_flag("RN_GPUI_BUILD_FROM_SOURCE") || mode == "never" { - return None; - } - let require = mode == "always"; - if let Some(dir) = env::var_os("RN_GPUI_PREBUILT_DIR") { - let dir = PathBuf::from(dir); - return match check_prebuilt_react_native(&dir, package_dir, renderer) { - Ok(()) => Some(dir), - Err(reason) => { - fallback_or_panic(require, &reason); - None - } - }; - } - // Always compare the local C++ inputs with the pin, in a repository checkout - // and under `node_modules` alike. A consumer whose own C++ inputs differ - // must not link an archive those inputs did not build, and the hash is - // computed from paths relative to this package, so it is the same value in - // both layouts. - if let Err(reason) = check_pinned_inputs(package_dir, renderer) { - fallback_or_panic(require, &reason); - return None; - } - - let script = package_dir.join("scripts").join("prebuilt-binaries.mjs"); - let output = Command::new("node") - .arg(&script) - .arg("ensure") - .arg("--triple") - .arg(target) - .arg("--renderer") - .arg(renderer) - .output(); - match output { - Ok(out) if out.status.success() => { - let dir = String::from_utf8_lossy(&out.stdout).trim().to_string(); - if dir.is_empty() { - fallback_or_panic(require, "prebuilt-binaries.mjs printed no directory"); - return None; - } - let dir = PathBuf::from(dir); - match check_prebuilt_react_native(&dir, package_dir, renderer) { - Ok(()) => Some(dir), - Err(reason) => { - fallback_or_panic(require, &reason); - None - } - } - } - Ok(out) => { - let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); - fallback_or_panic( - require, - &format!( - "prebuilt-binaries.mjs ensure exited {}: {stderr}", - out.status - ), - ); - None - } - Err(error) => { - fallback_or_panic(require, &format!("could not run node: {error}")); - None - } - } -} - -/// The archive's ReactCommon and react-native headers come from the consumer's -/// own react-native install, so that install must be the version the archive -/// was built against. Compares manifest.json `reactNative` with the installed -/// react-native package.json `version`. Any mismatch (or unreadable input) is an -/// error, which the caller turns into a source fallback. -fn check_prebuilt_react_native( - dir: &Path, - package_dir: &Path, - renderer: &str, -) -> Result<(), String> { - let manifest_path = dir.join("manifest.json"); - let manifest: serde_json::Value = fs::read_to_string(&manifest_path) - .map_err(|error| format!("cannot read {}: {error}", manifest_path.display())) - .and_then(|text| { - serde_json::from_str(&text) - .map_err(|error| format!("invalid {}: {error}", manifest_path.display())) - })?; - let built_for = manifest - .get("reactNative") - .and_then(|value| value.as_str()) - .ok_or_else(|| format!("{} has no reactNative version", manifest_path.display()))?; - - let installed_pkg = find_node_module(package_dir, "react-native") - .map(|dir| dir.join("package.json")) - .filter(|path| path.is_file()) - .ok_or_else(|| { - "no react-native install found at or above the platform package".to_string() - })?; - let installed: serde_json::Value = serde_json::from_str( - &fs::read_to_string(&installed_pkg) - .map_err(|error| format!("cannot read {}: {error}", installed_pkg.display()))?, - ) - .map_err(|error| format!("invalid {}: {error}", installed_pkg.display()))?; - let installed_version = installed - .get("version") - .and_then(|value| value.as_str()) - .unwrap_or(""); - - if installed_version != built_for { - return Err(format!( - "prebuilt runtime was built for react-native {built_for}, installed react-native is {installed_version}" - )); - } - if renderer == "loom" { - let built_with = manifest.get("loom").and_then(|value| value.as_str()); - let pinned = fs::read_to_string(package_dir.join("ReactGpui").join("loom-pin.json")) - .ok() - .and_then(|text| serde_json::from_str::(&text).ok()) - .and_then(|pin| pin.get("commit")?.as_str().map(str::to_owned)); - if built_with.is_none() || built_with != pinned.as_deref() { - return Err(format!( - "prebuilt runtime was built with Loom {}, this package pins Loom {}", - built_with.unwrap_or("none"), - pinned.as_deref().unwrap_or("none") - )); - } - } - Ok(()) -} - -/// A repository checkout may have C++ edits the pinned archive does not -/// contain, so its inputs must hash to the pin's `inputHash`. -fn check_pinned_inputs(package_dir: &Path, renderer: &str) -> Result<(), String> { - let pin_path = package_dir.join("prebuilt-binaries.json"); - println!("cargo:rerun-if-changed={}", pin_path.display()); - let pinned = fs::read_to_string(&pin_path) - .ok() - .and_then(|text| serde_json::from_str::(&text).ok()) - .and_then(|pin| { - let section = if renderer == "loom" { - pin.get("loom")? - } else { - &pin - }; - section.get("inputHash")?.as_str().map(str::to_owned) - }) - .ok_or_else(|| format!("{} has no {renderer} inputHash", pin_path.display()))?; - let output = Command::new("node") - .arg(package_dir.join("scripts").join("prebuilt-inputs.mjs")) - .arg("--renderer") - .arg(renderer) - .output() - .map_err(|error| format!("could not run node: {error}"))?; - let local = String::from_utf8_lossy(&output.stdout).trim().to_string(); - if !output.status.success() || local.is_empty() { - return Err("prebuilt-inputs.mjs failed".to_string()); - } - if local != pinned { - return Err(format!( - "local C++ inputs hash to {local}, the pinned prebuilt was built from {pinned}" - )); - } - Ok(()) -} - -fn fallback_or_panic(require: bool, reason: &str) { - if require { - panic!( - "rn-gpui-sys: project.desktop.prebuilt is 'always' and no prebuilt runtime: {reason}" - ); - } - println!("cargo:warning=rn-gpui-sys: no prebuilt runtime ({reason}); building from source"); -} - -/// The folder the C++ build keeps the downloaded, extracted and built native -/// dependencies (Boost, folly, OpenSSL, curl...) in. It is shared by every build -/// of every checkout, so a new target folder or worktree does not fetch and -/// compile them again. Order: `RN_GPUI_NATIVE_DEPS_CACHE`; `native-deps` in -/// `RN_GPUI_PREBUILT_CACHE` when that is set; `native-deps` in the per-user -/// `react-native-gpui` cache folder the prebuilt runtime uses -/// (`scripts/prebuilt-binaries.mjs`); and, where the machine has no user cache -/// folder, a folder in the Cargo target dir. -fn native_deps_cache_dir(cargo_target_dir: &Path) -> PathBuf { - let set = |name: &str| env::var_os(name).filter(|value| !value.is_empty()); - let absolute = |path: PathBuf| { - if path.is_absolute() { - path - } else { - env::current_dir() - .expect("read build-script working directory") - .join(path) - } - }; - if let Some(dir) = set("RN_GPUI_NATIVE_DEPS_CACHE") { - return absolute(PathBuf::from(dir)); - } - if let Some(dir) = set("RN_GPUI_PREBUILT_CACHE") { - return absolute(PathBuf::from(dir)).join("native-deps"); - } - let home = env::home_dir().filter(|dir| !dir.as_os_str().is_empty()); - // The build script runs on the host, so these are the host's cache folders. - let user_cache = if cfg!(target_os = "macos") { - home.map(|home| home.join("Library").join("Caches")) - } else if cfg!(windows) { - set("LOCALAPPDATA") - .map(PathBuf::from) - .or_else(|| home.map(|home| home.join("AppData").join("Local"))) - } else { - set("XDG_CACHE_HOME") - .map(PathBuf::from) - .filter(|dir| dir.is_absolute()) - .or_else(|| home.map(|home| home.join(".cache"))) - }; - match user_cache { - Some(dir) => dir.join("react-native-gpui").join("native-deps"), - None => cargo_target_dir.join("rn-gpui-native-deps"), - } -} - -fn env_flag(name: &str) -> bool { - matches!(env::var(name).as_deref(), Ok("1") | Ok("true")) -} - -fn overrides_sha256(package_dir: &Path, renderer: &str) -> String { - let output = Command::new("node") - .arg(package_dir.join("scripts").join("prebuilt-inputs.mjs")) - .arg("--overrides-sha256") - .arg("--renderer") - .arg(renderer) - .output() - .expect("run node for overridesSha256"); - assert!( - output.status.success(), - "overridesSha256 failed: {}", - String::from_utf8_lossy(&output.stderr) - ); - String::from_utf8_lossy(&output.stdout).trim().to_string() -} - -fn cmake_path(path: impl AsRef) -> String { - path.as_ref().to_string_lossy().replace('\\', "/") -} - -/// CMake writes these manifests per configuration because their content names -/// target file directories, and those differ between configurations on -/// multi-config generators (Visual Studio). Fall back to the unsuffixed name so -/// a build directory generated by an older layout still works. -fn cmake_manifest(cmake_build_dir: &Path, stem: &str, build_type: &str) -> PathBuf { - let per_config = cmake_build_dir.join(format!("{stem}-{build_type}.txt")); - if per_config.is_file() { - return per_config; - } - cmake_build_dir.join(format!("{stem}.txt")) -} - -fn emit_rpaths(path: &Path) { - println!("cargo:rerun-if-changed={}", path.display()); - let text = match std::fs::read_to_string(path) { - Ok(text) => text, - Err(error) => { - println!( - "cargo:warning=rn-gpui-sys: could not read {}: {error}", - path.display() - ); - return; - } - }; - - let dirs: Vec<&str> = text - .lines() - .map(str::trim) - .filter(|line| !line.is_empty()) - .collect(); - if dirs.is_empty() { - return; - } - println!("cargo:rpaths={}", dirs.join("|")); -} - -/// The installed `` package, found by walking up from `start` for a -/// `node_modules` directory that holds it. -/// -/// A package's location must never be derived by counting parent directories: -/// this repository keeps its own packages at different depths (`packages/core`, -/// `packages/hermes`), while an app has every one of them in `node_modules`. -/// Walking up is the only rule that holds in both, and it also covers a package -/// hoisted to an ancestor `node_modules` by a workspace. -fn find_node_module(start: &Path, name: &str) -> Option { - for ancestor in start.ancestors() { - let candidate = ancestor.join("node_modules").join(name); - if candidate.join("package.json").is_file() { - return Some(candidate); - } - } - None -} - -/// Exports the active engine's Node-API export list as link metadata. -/// -/// `cargo:node_api_exports` and `cargo:node_api_library` become -/// `DEP_RN_GPUI_CORE_NODE_API_EXPORTS` / `..._NODE_API_LIBRARY` for a dependent -/// `links = "rn_gpui_core"` crate. Nothing is emitted when the engine ships no -/// list (a platform with global symbol lookup, or an engine without Node-API), -/// which is how the app build script tells the two apart. -fn emit_node_api_exports(manifest: &serde_json::Value) { - let Some(engine) = manifest - .get("jsEngines") - .and_then(|value| value.as_array()) - .and_then(|engines| engines.first()) - else { - return; - }; - let Some(exports) = engine.get("nodeApiExports").and_then(|v| v.as_str()) else { - return; - }; - let Some(library) = engine.get("nodeApiLibrary").and_then(|v| v.as_str()) else { - println!( - "cargo:warning=rn-gpui-sys: the JS engine declares nodeApiExports without a nodeApiLibrary; Windows addons will not load" - ); - return; - }; - if !Path::new(exports).is_file() { - println!( - "cargo:warning=rn-gpui-sys: the JS engine's Node-API export list is missing: {exports}" - ); - return; - } - println!("cargo:rerun-if-changed={exports}"); - println!("cargo:node_api_exports={exports}"); - println!("cargo:node_api_library={library}"); -} - -/// Watches a file autolink writes. Cargo reruns a build script on every build -/// while a watched path is missing, so a missing file is watched through its -/// directory, and not at all without one (a build without autolink): the CLI -/// names the files through `RN_GPUI_AUTOLINK_*`, which are watched themselves. -fn watch_generated_file(path: &Path) { - if path.exists() { - println!("cargo:rerun-if-changed={}", path.display()); - } else if let Some(dir) = path.parent().filter(|dir| dir.is_dir()) { - println!("cargo:rerun-if-changed={}", dir.display()); - } -} - -/// Has `cc` compile the cxx bridge through ccache: `cc` takes `ccache ` -/// in `CXX_` as a wrapper, and has no other way to be given one. Returns -/// the variable to clear afterwards, or `None` when the user named a C++ -/// compiler, which is left alone. -fn launch_bridge_through_ccache(compiler: &Path, target: &str) -> Option { - let target_underscored = target.replace(['-', '.'], "_"); - let user_set = [ - format!("CXX_{target}"), - format!("CXX_{target_underscored}"), - "HOST_CXX".to_string(), - "TARGET_CXX".to_string(), - "CXX".to_string(), - ] - .iter() - .any(|name| env::var_os(name).is_some()); - let compiler = compiler.to_str()?; - if user_set || compiler.contains(char::is_whitespace) { - return None; - } - let variable = format!("CXX_{target}"); - // The build script is single-threaded here. - env::set_var(&variable, format!("ccache {compiler}")); - Some(variable) -} - -/// Whether a `ccache` binary is on `PATH`. -/// -/// Only used to decide whether to hand CMake the compiler launcher: setting it -/// to a binary that is not there fails the configure, and a machine without -/// ccache has to build without it. -fn ccache_available() -> bool { - program_on_path("ccache") -} - -fn program_on_path(name: &str) -> bool { - let path = match env::var_os("PATH") { - Some(path) => path, - None => return false, - }; - let exe = if cfg!(windows) { - format!("{name}.exe") - } else { - name.to_string() - }; - env::split_paths(&path).any(|dir| dir.join(&exe).is_file()) -} - -/// The directory a target's CMake tree is named after. cl.exe cannot write an -/// object file whose absolute path reaches MAX_PATH (260), and the longest -/// ReactCommon objects sit about 170 characters below the tree, so the Windows -/// directories are short. -fn cmake_triple_dir(triple: &str) -> &str { - match triple { - "x86_64-pc-windows-msvc" => "x64", - "aarch64-pc-windows-msvc" => "arm64", - other => other, - } -} - -fn msvc_target() -> bool { - matches!(std::env::var("CARGO_CFG_TARGET_ENV").as_deref(), Ok("msvc")) -} - -/// Translates `link_libs.txt` (written by CMake) into cargo directives. -/// -/// Line forms: -/// * `name:` — a library file name; `-l` takes it stripped of its -/// `lib` prefix and extension, `dylib=` for shared, `static=` for archives. -/// * `search:` — a directory to add to the link search path. -/// -/// Off MSVC, third-party archives are linked through uniquely named symlinks -/// (`librngpui_ssl.a` for `libssl.a`). A crate that finds a system library -/// through pkg-config adds a directory such as `/usr/lib/x86_64-linux-gnu` to -/// the search path ahead of ours, and `-lssl` would then pick up the system's -/// static OpenSSL instead of the one this build's curl was compiled against. -fn emit_link_libs(path: &Path, out_dir: &Path) { - println!("cargo:rerun-if-changed={}", path.display()); - let text = match std::fs::read_to_string(path) { - Ok(text) => text, - Err(error) => { - println!( - "cargo:warning=rn-gpui-sys: could not read {}: {error}", - path.display() - ); - return; - } - }; - - let link_dir = out_dir.join("rn-gpui-link"); - let mut seen = std::collections::HashSet::new(); - let mut last_search: Option<&str> = None; - for line in text.lines() { - let line = line.trim(); - if line.is_empty() { - continue; - } - if let Some(dir) = line.strip_prefix("search:") { - last_search = Some(dir); - if seen.insert(format!("search:{dir}")) { - println!("cargo:rustc-link-search=native={dir}"); - } - } else if let Some(file) = line.strip_prefix("name:") { - let file = Path::new(file); - let stem = file - .file_name() - .and_then(|name| name.to_str()) - .unwrap_or_default(); - // link.exe only appends `.lib`, so on MSVC the `lib` prefix that - // some libraries really carry (libcurl-d.lib, libssl.lib) must be - // kept; stripping it fails with LNK1181. - let stem = if msvc_target() { - stem - } else { - stem.strip_prefix("lib").unwrap_or(stem) - }; - let is_archive = stem.ends_with(".a") || stem.ends_with(".lib"); - let name = if is_archive { - stem.trim_end_matches(".a").trim_end_matches(".lib") - } else { - stem.split('.').next().unwrap_or(stem) - }; - if name.is_empty() { - continue; - } - // The main archive is emitted before this transitive manifest so - // Cargo does not see conflicting link modifiers for the same lib. - if name == "rn_gpui_core" { - continue; - } - let directive = if is_archive { - let source = last_search.map(|dir| Path::new(dir).join(file)); - match source.and_then(|source| link_unique_archive(&link_dir, name, &source)) { - Some(unique) => { - if seen.insert(format!("search:{}", link_dir.display())) { - println!("cargo:rustc-link-search=native={}", link_dir.display()); - } - format!("static:-bundle={unique}") - } - None => format!("static:-bundle={name}"), - } - } else { - format!("dylib={name}") - }; - if seen.insert(directive.clone()) { - println!("cargo:rustc-link-lib={directive}"); - } - } else { - // A bare name is a static archive. - let directive = format!("static:-bundle={line}"); - if seen.insert(directive.clone()) { - println!("cargo:rustc-link-lib={directive}"); - } - } - } -} - -/// Symlinks `source` into `link_dir` as `librngpui_.a` and returns the -/// `-l` name to use. Returns `None` (link by the original name) on MSVC, for -/// this build's own `rn_gpui_*` archives, or when the archive is not found. -fn link_unique_archive(link_dir: &Path, name: &str, source: &Path) -> Option { - if msvc_target() || name.starts_with("rn_gpui") || !source.is_file() { - return None; - } - #[cfg(unix)] - { - let unique = format!("rngpui_{name}"); - fs::create_dir_all(link_dir).ok()?; - let link = link_dir.join(format!("lib{unique}.a")); - if fs::read_link(&link).ok().as_deref() != Some(source) { - let _ = fs::remove_file(&link); - std::os::unix::fs::symlink(source, &link).ok()?; - } - Some(unique) - } - #[cfg(not(unix))] - { - let _ = link_dir; - None - } -} - -fn cargo_target_dir(out_dir: &Path, target_triple: &str) -> PathBuf { - if let Some(target_dir) = env::var_os("CARGO_TARGET_DIR") { - let target_dir = PathBuf::from(target_dir); - return if target_dir.is_absolute() { - target_dir - } else { - env::current_dir() - .expect("read build-script working directory") - .join(target_dir) - }; - } - - let profile = env::var("PROFILE").expect("PROFILE is set"); - let profile_dir = out_dir - .ancestors() - .find(|path| { - path.file_name() - .is_some_and(|name| name.to_string_lossy() == profile) - }) - .expect("find Cargo profile directory above OUT_DIR"); - let target_or_profile_dir = profile_dir - .parent() - .expect("Cargo profile directory has a parent"); - if target_or_profile_dir - .file_name() - .is_some_and(|name| name == target_triple) - { - target_or_profile_dir - .parent() - .expect("Cargo target triple directory has a parent") - .to_path_buf() - } else { - target_or_profile_dir.to_path_buf() - } -} - -fn cmake_build_type() -> &'static str { - match env::var("OPT_LEVEL").as_deref() { - Ok("0") => "Debug", - Ok("s" | "z") => "MinSizeRel", - _ if env::var("DEBUG").as_deref() == Ok("false") => "Release", - _ => "RelWithDebInfo", - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/CMakeLists.txt b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/CMakeLists.txt deleted file mode 100644 index 4e964a277b..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/CMakeLists.txt +++ /dev/null @@ -1,1351 +0,0 @@ -cmake_minimum_required(VERSION 3.18) -# ccache cannot cache MSVC's default /Zi (a PDB written by the compiler), so -# embed the debug info in the objects (/Z7). The policy must be set before -# project(), which seeds the compiler flags; it needs CMake 3.25. build.rs also -# sets the policy default and the format for the subprojects. -if(NOT CMAKE_VERSION VERSION_LESS 3.25) - cmake_policy(SET CMP0141 NEW) - if(NOT DEFINED CMAKE_MSVC_DEBUG_INFORMATION_FORMAT) - set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT - "$<$:Embedded>") - endif() -endif() -project(rn_gpui_core CXX C) -if(APPLE) - enable_language(OBJCXX) -endif() -set(CMAKE_CXX_STANDARD 20) -set(CMAKE_POSITION_INDEPENDENT_CODE ON) -if(MSVC) - # React Native, folly and several bundled third-party projects carry - # clang/gcc assumptions. MSVC needs its own spellings: /utf-8 because fmt and - # ReactCommon contain non-ASCII string literals (fmt asserts with "Unicode - # support requires compiling with /utf-8"), and /EHsc because RN throws and - # catches exceptions while cl.exe leaves exception handling off by default. - add_compile_options( - "$<$:/utf-8>" - "$<$:/EHsc>" - "$<$:/GR>") - # folly and fmt inspect __cplusplus, which MSVC reports as 199711L unless - # /Zc:__cplusplus is given. - add_compile_options("$<$:/Zc:__cplusplus>") - # MSBuild hands each project's sources to a single cl.exe, which compiles - # them one at a time unless /MP is given; project dependencies leave only - # one or two projects building at once. Half the cores per cl.exe keeps the - # machine busy without exhausting memory (each compiler can use ~1 GB). - # Ninja starts one cl.exe per source and already runs one per core, and - # ccache does not take a multi-file /MP command line, so /MP is for the - # Visual Studio generator only. - if(NOT CMAKE_GENERATOR MATCHES "Ninja") - cmake_host_system_information(RESULT _rn_gpui_cores QUERY NUMBER_OF_LOGICAL_CORES) - math(EXPR _rn_gpui_mp "(${_rn_gpui_cores} + 1) / 2") - add_compile_options("$<$:/MP${_rn_gpui_mp}>") - endif() - # ReactCommon headers do `#ifndef RN_EXPORT / #define RN_EXPORT - # __attribute__((visibility("default")))`, which cl.exe cannot parse. The - # guard means defining it empty here is enough. - add_compile_definitions(RN_EXPORT=) - # glog's headers declare every symbol __declspec(dllimport) on Windows unless - # GOOGLE_GLOG_DLL_DECL is already defined, while this build links glog - # statically. Its own `#ifndef` guard lets the static spelling win here. - add_compile_definitions(GOOGLE_GLOG_DLL_DECL=) - # ReactCommon relies on libc++'s transitive includes; force the common - # standard headers into every C++ translation unit on MSVC. - add_compile_options( - "$<$:/FI${CMAKE_CURRENT_SOURCE_DIR}/cmake/msvc-preinclude.h>") - # defines min/max macros that break std::min/std::max in - # ReactCommon and folly, and both expect the Windows 10 API surface. - add_compile_definitions(NOMINMAX) - add_compile_definitions(_WIN32_WINNT=0x0A00) - # Mirrors react-native-windows: __unused is an Apple attribute, JSI_EXPORT - # marks the dllimport storage class in jsi's headers (jsi exports come from - # WINDOWS_EXPORT_ALL_SYMBOLS below), - # _CRT_SECURE_NO_WARNINGS silences CRT deprecation warnings, and - # _DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR avoids the MSVC 14.4x constexpr - # std::mutex problem. BOOST_ALL_NO_LIB stops boost headers from asking the - # linker for boost libraries we do not build. - add_compile_definitions("__unused=[[maybe_unused]]") - add_compile_definitions(JSI_EXPORT=) - add_compile_definitions(_CRT_SECURE_NO_WARNINGS) - add_compile_definitions(_DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR) - add_compile_definitions(BOOST_ALL_NO_LIB=1) - # Lets boost compile its error_code/system facilities header-only so that - # nothing asks the linker for boost_system.lib; react-native-windows - # defines the same set. - add_compile_definitions(BOOST_ERROR_CODE_HEADER_ONLY) - add_compile_definitions(BOOST_SYSTEM_SOURCE) - add_compile_definitions(BOOST_NO_RTTI) - add_compile_definitions(BOOST_NO_TYPEID) - # pulls in wingdi.h, whose BLACK and TRANSPARENT macros collide - # with the names bundled libraries use for colour constants (one defines - # `const std::array BLACK` in its interpolator registry), and - # WIN32_LEAN_AND_MEAN keeps the rest of the Win32 surface out of reach. - add_compile_definitions(WIN32_LEAN_AND_MEAN) - add_compile_definitions(NOGDI) -endif() -if(CMAKE_SYSTEM_NAME STREQUAL "Linux") - # One force-included header stands in for the libc++ headers Android's build - # gets transitively (see the file). It is a single `-include` because CMake - # de-duplicates repeated options: two `-include
` pairs collapse into - # `-include `, and the second header is then read as a stray - # linker input. - add_compile_options( - "$<$:-include;${CMAKE_CURRENT_LIST_DIR}/rn_gpui_linux_prefix.h>") -endif() -if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") - # ReactCommon writes both `class RN_EXPORT [[deprecated(...)]] X`, which GCC - # before 13 rejects with RN_EXPORT's `__attribute__` spelling, and - # `extern RN_EXPORT T x`, which rejects the `[[gnu::]]` spelling. Nothing here - # builds with hidden visibility and ReactCommon links statically, so the - # attribute is a no-op; define it empty as on Windows. - add_compile_definitions(RN_EXPORT=) - if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 14) - # ConcreteShadowNode.h redeclares names it already used ("changes meaning"), - # a hard error before GCC 14 and a warning since; -fpermissive matches 14. - add_compile_options("$<$:-fpermissive>") - endif() -endif() - -# --- Windows unity build ------------------------------------------------- -# -# MSBuild hands a project's sources to one cl.exe, which compiles them one at a -# time unless /MP is given, and ReactCommon splits into ~76 projects of ~4 -# sources each while project dependencies leave only one or two building at -# once (see the /MP comment above). Nearly all of that time goes into parsing -# the shared ReactCommon, folly and boost headers, once per source file. A unity -# build merges a target's sources into one translation unit, so those headers -# are parsed once per target instead of once per source. -# -# This is Windows-only and opt-out. MSVC is the only compiler here that is -# driven by MSBuild at project granularity; the Linux and macOS builds already -# compile at target granularity in parallel, where a unity build would only take -# parallelism away and change nothing else. -# -# To turn it off, pass the define through to CMake — `build.rs` does not forward -# arbitrary `RN_GPUI_*` environment variables, so a bare -# `RN_GPUI_UNITY_BUILD=OFF` never reaches this file: -# -# CMAKE_ARGS=-DRN_GPUI_UNITY_BUILD=OFF cargo build (with a reconfigure) -# -# or configure `cpp/` by hand with the same -D. -# -# A unity build changes what the compiler sees in one translation unit, so file -# scope names and macros from one source become visible to the next. The -# vendored third-party targets that cannot tolerate that are switched back off -# with `UNITY_BUILD OFF` in the MSVC section at the end of this file, once every -# target exists. -option(RN_GPUI_UNITY_BUILD - "Merge each MSVC target's sources into unity translation units" ON) -if(MSVC AND RN_GPUI_UNITY_BUILD) - set(CMAKE_UNITY_BUILD ON) - # Merge a target's sources in batches of this size. Most ReactCommon targets - # have fewer sources than this, so they collapse into a single compilation; - # /MP still spreads the batches of the larger targets across cores. - set(CMAKE_UNITY_BUILD_BATCH_SIZE 8) - # A merged translation unit holds the code and debug info of every source in - # its batch, which overflows the COFF section limit on the app's generated - # TurboModule specs ("error C1128: number of sections exceeded object file - # format limit"). /bigobj raises the limit; it is a no-op for units that stay - # under it, so it is set for the whole unity build rather than per target. - add_compile_options("$<$:/bigobj>") -endif() - -# Paths to this package's own trees, published for the autolinked library -# CMakeLists files. They are derived from this file's location, so they stay -# right wherever the package is installed: a library must never count folders -# up to reach core, because the two sit at different depths in an app -# (`node_modules/@react-native-gpui/`) and in this repository. -set(RN_GPUI_CORE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../..") -set(RN_GPUI_SYS_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}") -set(RN_GPUI_REACT_CXX_PLATFORM_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../ReactCxxPlatform") - -include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/NodeModules.cmake) - -# The renderer picks the React Native tree: the installed package for Fabric, -# Loom's materialized copy of it for Loom (build.rs passes its path). Every -# header and source below, and the autolinked modules, read from that one tree. -if(RN_GPUI_REACT_NATIVE_DIR) - set(_rn_gpui_react_native_dir "${RN_GPUI_REACT_NATIVE_DIR}") -else() - rn_gpui_find_node_module(react-native _rn_gpui_react_native_dir) -endif() -if(LOOM_RENDERER) - # Loom's headers change the layout of React Native classes, so every target - # of this build, modules included, compiles with the same switches. - add_compile_definitions(LOOM_RENDERER=1) -endif() -set(REACT_COMMON_DIR "${_rn_gpui_react_native_dir}/ReactCommon") -if(NOT RN_GPUI_GENERATED_RNCORE_DIR) - message(FATAL_ERROR - "RN_GPUI_GENERATED_RNCORE_DIR is required; generate FBReactNativeSpec into the shared CMake output directory") -endif() -set(REACT_CXX_PLATFORM_DIR "${RN_GPUI_REACT_CXX_PLATFORM_DIR}") -if(NOT RN_GPUI_OVERRIDES_DIR) - set(RN_GPUI_OVERRIDES_DIR - "${CMAKE_CURRENT_SOURCE_DIR}/../../../ReactCommonOverrides") -endif() - -# The jsinspector-modern CMakeLists includes SoMerging-utils.cmake from the -# Android tree. That helper defines target_merge_so(), which is a no-op on -# non-Android platforms; the shim contains only that CMake helper, not Android -# runtime code. See android-shim/README.md. -set(REACT_ANDROID_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android-shim") - -# RN Android stores source archives and prepared third-party sources under its -# Gradle build directory. Mirror that layout under this target's CMake build -# cache so independent desktop builds do not rely on host package managers. -# Both modes download and prepare the pinned native-dep sources. Only source -# mode builds OpenSSL and curl (cmake/DownloadNativeDeps.cmake guards those). -set(REACT_ANDROID_SOURCE_DIR "${REACT_COMMON_DIR}/../ReactAndroid") -include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/DownloadNativeDeps.cmake) - -# React Native's own CMake projects are added from here in both modes: a source -# build adds the ones core needs, and either mode adds the ones a JS engine -# package declares (RN_GPUI_JS_ENGINE_SUBDIRECTORIES). -function(add_react_common_subdir relative_path) - add_subdirectory(${REACT_COMMON_DIR}/${relative_path} - ReactCommon/${relative_path}) -endfunction() - -function(add_react_cxx_platform_subdir relative_path) - add_subdirectory(${REACT_CXX_PLATFORM_DIR}/${relative_path} - ReactCxxPlatform/${relative_path}) -endfunction() - -if(RN_GPUI_PREBUILT_DIR) - # Prebuilt mode: rn_gpui_core, ReactCommon and third-party come from the - # archive. Only the app-side targets below are compiled here. - set(_rn_gpui_prebuilt_manifest "${RN_GPUI_PREBUILT_DIR}/manifest.json") - if(NOT EXISTS "${_rn_gpui_prebuilt_manifest}") - message(FATAL_ERROR "RN_GPUI_PREBUILT_DIR has no manifest.json: ${RN_GPUI_PREBUILT_DIR}") - endif() - file(READ "${_rn_gpui_prebuilt_manifest}" _rn_gpui_prebuilt_json) - string(JSON _rn_gpui_prebuilt_bridge_sha GET "${_rn_gpui_prebuilt_json}" cxxBridgeHeaderSha256) - string(JSON _rn_gpui_prebuilt_triple GET "${_rn_gpui_prebuilt_json}" triple) - if(RN_GPUI_CXXBRIDGE_INCLUDE_DIR AND EXISTS "${RN_GPUI_CXXBRIDGE_INCLUDE_DIR}/rn-gpui-sys/src/lib.rs.h") - file(SHA256 "${RN_GPUI_CXXBRIDGE_INCLUDE_DIR}/rn-gpui-sys/src/lib.rs.h" _rn_gpui_bridge_sha) - if(NOT _rn_gpui_bridge_sha STREQUAL _rn_gpui_prebuilt_bridge_sha) - message(FATAL_ERROR - "RN_GPUI_PREBUILT_DIR was built for a different cxx bridge (manifest ${_rn_gpui_prebuilt_bridge_sha}, " - "current ${_rn_gpui_bridge_sha}). Rebuild the prebuilt or unset RN_GPUI_PREBUILT_DIR.") - endif() - endif() - # The archive is Release, so its ReactCommon headers select the production - # ABI (Sealable without a debug constructor). Consumers must compile the same - # way or they reference symbols the archive never exports. - string(JSON _rn_gpui_prebuilt_rn_debug ERROR_VARIABLE _rn_gpui_json_err GET "${_rn_gpui_prebuilt_json}" defines REACT_NATIVE_DEBUG) - if(NOT _rn_gpui_json_err AND _rn_gpui_prebuilt_rn_debug STREQUAL "0") - add_compile_definitions(REACT_NATIVE_PRODUCTION) - endif() - # The app's own C++ is compiled by this configure, in whatever Cargo profile - # the caller used, while the archive is fixed Release (/MD, iterator debug - # level 0). A Cargo debug build configures CMake as Debug, which defines - # _DEBUG; MSVC's STL then expands that to _ITERATOR_DEBUG_LEVEL=2 and selects - # the debug CRT, and the link dies on LNK2038 with - # mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '2' doesn't match '0' - # mismatch detected for 'RuntimeLibrary': 'MDd_DynamicDebug' vs 'MD_DynamicRelease' - # So match the runtime library recorded in the manifest whatever the profile, - # the same way REACT_NATIVE_PRODUCTION is taken from the manifest above. - # `build.rs` already pins CMAKE_MSVC_RUNTIME_LIBRARY to MultiThreadedDLL; the - # iterator level and _DEBUG are what is left. - if(MSVC) - string(JSON _rn_gpui_prebuilt_iterator ERROR_VARIABLE _rn_gpui_iterator_err - GET "${_rn_gpui_prebuilt_json}" flags msvcIteratorDebugLevel) - if(_rn_gpui_iterator_err) - set(_rn_gpui_prebuilt_iterator 0) - endif() - # /U_DEBUG: without it the STL header sees _DEBUG and raises the level again - # even when _ITERATOR_DEBUG_LEVEL is defined. /DNDEBUG keeps assert() off, as - # in the archive; the definition is conditional so a Release consumer does - # not warn about redefining it. - add_compile_options( - "/U_DEBUG" - "$<$>:/DNDEBUG>") - add_compile_definitions(_ITERATOR_DEBUG_LEVEL=${_rn_gpui_prebuilt_iterator}) - endif() - # ReactCommonOverrides is compiled into the archive. build.rs computes the - # current hash (CMake strings cannot hold the NUL separator) and passes it in - # as RN_GPUI_OVERRIDES_SHA256; a mismatch means the archive is stale. - string(JSON _rn_gpui_prebuilt_overrides_sha GET "${_rn_gpui_prebuilt_json}" overridesSha256) - if(RN_GPUI_OVERRIDES_SHA256 AND NOT RN_GPUI_OVERRIDES_SHA256 STREQUAL _rn_gpui_prebuilt_overrides_sha) - message(FATAL_ERROR - "RN_GPUI_PREBUILT_DIR was built from different ReactCommonOverrides (manifest " - "${_rn_gpui_prebuilt_overrides_sha}, current ${RN_GPUI_OVERRIDES_SHA256}). Rebuild the " - "prebuilt or unset RN_GPUI_PREBUILT_DIR.") - endif() - # Headers are not in the archive. Point each root the archive names at the - # tree this build already uses (the same variables source mode compiles with). - set(RN_GPUI_PREBUILT_ROOT_react_native_gpui "${CMAKE_CURRENT_SOURCE_DIR}") - set(RN_GPUI_PREBUILT_ROOT_react_common_overrides "${RN_GPUI_OVERRIDES_DIR}") - set(RN_GPUI_PREBUILT_ROOT_react_common "${REACT_COMMON_DIR}") - set(RN_GPUI_PREBUILT_ROOT_react_cxx_platform "${REACT_CXX_PLATFORM_DIR}") - set(RN_GPUI_PREBUILT_ROOT_generated_rncore "${RN_GPUI_GENERATED_RNCORE_DIR}/jni") - set(RN_GPUI_PREBUILT_ROOT_cxxbridge "${RN_GPUI_CXXBRIDGE_INCLUDE_DIR}") - set(RN_GPUI_PREBUILT_ROOT_folly "${RN_GPUI_NATIVE_DEPS_PREPARED}/folly") - set(RN_GPUI_PREBUILT_ROOT_glog "${RN_GPUI_NATIVE_DEPS_PREPARED}/glog/exported") - set(RN_GPUI_PREBUILT_ROOT_fmt "${RN_GPUI_NATIVE_DEPS_PREPARED}/fmt/include") - set(RN_GPUI_PREBUILT_ROOT_double_conversion "${RN_GPUI_NATIVE_DEPS_PREPARED}/double-conversion") - set(RN_GPUI_PREBUILT_ROOT_fast_float "${RN_GPUI_NATIVE_DEPS_PREPARED}/fast_float/include") - set(RN_GPUI_PREBUILT_ROOT_nlohmann_json "${RN_GPUI_NATIVE_DEPS_PREPARED}/nlohmann_json/include") - set(RN_GPUI_PREBUILT_ROOT_boost "${RN_GPUI_NATIVE_DEPS_PREPARED}/boost/boost_1_83_0") - set(RN_GPUI_PREBUILT_ROOT_curl "${RN_GPUI_CURL_SOURCE_DIR}/include") - message(STATUS "rn_gpui_core: using prebuilt runtime ${RN_GPUI_PREBUILT_DIR} (${_rn_gpui_prebuilt_triple})") - find_package(react-native-gpui-prebuilt CONFIG REQUIRED - PATHS "${RN_GPUI_PREBUILT_DIR}/cmake" NO_DEFAULT_PATH) -else() - -# GpuiHttpClient uses libcurl. Build curl from its pinned source archive against -# the OpenSSL copy prepared in the same CMake cache above. -set(BUILD_CURL_EXE OFF CACHE BOOL "" FORCE) -set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) -set(CURL_USE_OPENSSL ON CACHE BOOL "" FORCE) -set(CURL_DISABLE_LDAP ON CACHE BOOL "" FORCE) -set(CURL_USE_LIBPSL OFF CACHE BOOL "" FORCE) -set(CURL_USE_LIBSSH2 OFF CACHE BOOL "" FORCE) -set(CURL_ZLIB OFF CACHE STRING "" FORCE) -set(USE_NGHTTP2 OFF CACHE BOOL "" FORCE) -set(USE_LIBIDN2 OFF CACHE BOOL "" FORCE) -set(CURL_USE_BROTLI OFF CACHE BOOL "" FORCE) -set(CURL_USE_ZSTD OFF CACHE BOOL "" FORCE) -set(CURL_DISABLE_TESTS ON CACHE BOOL "" FORCE) -add_subdirectory("${RN_GPUI_CURL_SOURCE_DIR}" "${RN_GPUI_NATIVE_DEPS_BUILD}/curl") - -include(${REACT_COMMON_DIR}/cmake-utils/react-native-flags.cmake) - -include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules/ThirdParty.cmake) - -# The cxx-generated bridge header carries the flat -# structs and the `rn_gpui_*` entry point declarations. build.rs runs -# `cxx_build::bridge` *before* configuring CMake and passes the directory here. -# When CMake is driven by hand (the 1.3 workflow) the variable is unset, so fall -# back to the include directory of the most recent cargo build. -# -# This has to happen before the ReactCommon subdirectories are added: the -# rn_gpui_core glue (GpuiHost.cpp, MountBatchBuilder.cpp) needs the bridge -# header. The ReactCommon override does not; it uses GpuiTextMeasure.h. -if(NOT RN_GPUI_CXXBRIDGE_INCLUDE_DIR) - file(GLOB RN_GPUI_CXXBRIDGE_CANDIDATES - "${CMAKE_CURRENT_SOURCE_DIR}/../../target/*/build/rn-gpui-sys-*/out/cxxbridge/include/rust/cxx.h") - set(_newest_stamp "") - foreach(_candidate IN LISTS RN_GPUI_CXXBRIDGE_CANDIDATES) - file(TIMESTAMP "${_candidate}" _stamp "%Y%m%d%H%M%S") - if(_stamp STRGREATER _newest_stamp) - set(_newest_stamp "${_stamp}") - get_filename_component(RN_GPUI_CXXBRIDGE_INCLUDE_DIR "${_candidate}" DIRECTORY) - get_filename_component(RN_GPUI_CXXBRIDGE_INCLUDE_DIR "${RN_GPUI_CXXBRIDGE_INCLUDE_DIR}" DIRECTORY) - endif() - endforeach() - if(RN_GPUI_CXXBRIDGE_INCLUDE_DIR) - message(STATUS "rn_gpui_core: cxx bridge headers found at ${RN_GPUI_CXXBRIDGE_INCLUDE_DIR}") - endif() -endif() - -# Shared glue headers for every ReactCommon subdirectory: the TextLayoutManager -# override includes GpuiTextMeasure.h from here. This is fixed platform glue, -# not an app or Cargo input, so it stays directory-wide. The cxx bridge header -# is not added directory-wide; only rn_gpui_core consumes it (see below), so -# the ReactCommon targets build without RN_GPUI_CXXBRIDGE_INCLUDE_DIR. -include_directories(${CMAKE_CURRENT_SOURCE_DIR}) - -# Header overrides. Must come before the ReactCommon subdirectories -# below: this directory holds a replacement for -# (a -# platform header that RN finds through the platform include directory), and -# directory-level include dirs are emitted ahead of a target's own ones. -include_directories(${RN_GPUI_OVERRIDES_DIR}) -if(LOOM_RENDERER) - # Files both this platform and Loom replace have a Loom variant that wins. - set(RN_GPUI_LOOM_OVERRIDES_DIR "${RN_GPUI_OVERRIDES_DIR}.loom") - include_directories(BEFORE ${RN_GPUI_LOOM_OVERRIDES_DIR}) -endif() - -# Adding a replacement header changes include resolution without changing the -# upstream header already recorded in compiler dependencies. Recompile every -# target when the override inventory changes to keep RN prop classes ABI-safe. -file(GLOB_RECURSE RN_GPUI_OVERRIDE_HEADERS CONFIGURE_DEPENDS - RELATIVE "${RN_GPUI_OVERRIDES_DIR}" "${RN_GPUI_OVERRIDES_DIR}/*.h") -if(LOOM_RENDERER) - file(GLOB_RECURSE _rn_gpui_loom_override_headers CONFIGURE_DEPENDS - RELATIVE "${RN_GPUI_LOOM_OVERRIDES_DIR}" "${RN_GPUI_LOOM_OVERRIDES_DIR}/*.h") - list(TRANSFORM _rn_gpui_loom_override_headers PREPEND "loom/") - list(APPEND RN_GPUI_OVERRIDE_HEADERS ${_rn_gpui_loom_override_headers}) -endif() -list(SORT RN_GPUI_OVERRIDE_HEADERS) -string(SHA256 RN_GPUI_OVERRIDE_HEADER_SET "${RN_GPUI_OVERRIDE_HEADERS}") -add_compile_definitions("RN_GPUI_HEADER_OVERRIDES_${RN_GPUI_OVERRIDE_HEADER_SET}=1") - -add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/jni react_codegen_rncore) - -add_react_common_subdir(yoga) - -# Compile our copy of Yoga's CalculateLayout.cpp -# (ReactCommonOverrides/yoga/algorithm/CalculateLayout.cpp) and YGEnums.cpp in -# place of the upstream sources: they add the FlexBasisAsIntrinsicSize errata. -# See ReactCommonOverrides/README.md for what changed and the React Native -# version the copies came from. -if(TARGET yogacore) - get_target_property(_rn_gpui_yoga_sources yogacore SOURCES) - foreach(_rn_gpui_yoga_file algorithm/CalculateLayout YGEnums) - set(_rn_gpui_yoga_override - "${RN_GPUI_OVERRIDES_DIR}/yoga/${_rn_gpui_yoga_file}.cpp") - if(EXISTS "${_rn_gpui_yoga_override}") - list(FILTER _rn_gpui_yoga_sources EXCLUDE - REGEX "yoga/${_rn_gpui_yoga_file}\\.cpp$") - list(APPEND _rn_gpui_yoga_sources "${_rn_gpui_yoga_override}") - else() - message(WARNING - "rn_gpui_core: Yoga override not found (${_rn_gpui_yoga_override})") - endif() - endforeach() - set_property(TARGET yogacore PROPERTY SOURCES "${_rn_gpui_yoga_sources}") -endif() - -# On Android the `yoga` target (JNI bindings over yogacore) is defined -# in ReactAndroid/src/main/jni/first-party/yogajni, and RN targets link -# it by name to get yogacore's public include directories. The gpui -# build has no JNI layer, so provide a bare target that carries -# yogacore's includes (and links it at final link time). -if(NOT TARGET yoga) - add_library(yoga INTERFACE) - target_link_libraries(yoga INTERFACE yogacore) -endif() -add_react_common_subdir(runtimeexecutor) -add_react_common_subdir(reactperflogger) -add_react_common_subdir(logger) -add_react_common_subdir(jsiexecutor) -add_react_common_subdir(jsitooling) -add_react_common_subdir(cxxreact) -add_react_common_subdir(jsi) -add_react_common_subdir(callinvoker) -add_react_common_subdir(oscompat) -add_react_common_subdir(jsinspector-modern) -add_react_common_subdir(jsinspector-modern/cdp) -add_react_common_subdir(jsinspector-modern/network) -add_react_common_subdir(jsinspector-modern/tracing) -add_react_common_subdir(react/cxxstableapi) -add_react_common_subdir(react/renderer/runtimescheduler) -add_react_common_subdir(react/debug) -add_react_common_subdir(react/featureflags) -add_react_common_subdir(react/performance/cdpmetrics) -add_react_common_subdir(react/performance/timeline) -add_react_common_subdir(react/renderer/animated) -add_react_common_subdir(react/renderer/animationbackend) -add_react_common_subdir(react/renderer/animations) -add_react_common_subdir(react/renderer/attributedstring) -add_react_common_subdir(react/renderer/componentregistry) -add_react_common_subdir(react/renderer/mounting) -add_react_common_subdir(react/renderer/scheduler) -add_react_common_subdir(react/renderer/telemetry) -add_react_common_subdir(react/renderer/viewtransition) -if(LOOM_RENDERER) - add_react_common_subdir(react/renderer/loom) -endif() -add_react_common_subdir(react/renderer/uimanager) -add_react_common_subdir(react/renderer/bridging) -add_react_common_subdir(react/renderer/core) -add_react_common_subdir(react/renderer/consistency) -add_react_common_subdir(react/renderer/css) -add_react_common_subdir(react/renderer/uimanager/consistency) -add_react_common_subdir(react/renderer/dom) -add_react_common_subdir(react/renderer/element) -add_react_common_subdir(react/renderer/debug) -add_react_common_subdir(react/renderer/graphics) -add_react_common_subdir(react/renderer/imagemanager) -add_react_common_subdir(react/renderer/components/view) -# GPUI uses RN's shared text-input state/event implementation with the -# platform-neutral TextInput shadow node props. Do not build React Native's -# Android target here: that target glob includes JNI-only sources. -set(RN_GPUI_TEXTINPUT_DIR - "${REACT_COMMON_DIR}/react/renderer/components/textinput") -set(RN_GPUI_IOS_TEXTINPUT_DIR - "${RN_GPUI_TEXTINPUT_DIR}/platform/ios/react/renderer/components/iostextinput") -add_library(rrc_textinput_gpui OBJECT - "${RN_GPUI_TEXTINPUT_DIR}/BaseTextInputProps.cpp" - "${RN_GPUI_TEXTINPUT_DIR}/TextInputEventEmitter.cpp" - "${RN_GPUI_IOS_TEXTINPUT_DIR}/TextInputProps.cpp" - "${RN_GPUI_IOS_TEXTINPUT_DIR}/TextInputShadowNode.cpp") -target_include_directories(rrc_textinput_gpui PUBLIC - "${RN_GPUI_TEXTINPUT_DIR}" - "${RN_GPUI_TEXTINPUT_DIR}/platform/ios" - "${RN_GPUI_IOS_TEXTINPUT_DIR}") -target_link_libraries(rrc_textinput_gpui PUBLIC - react_renderer_attributedstring - react_renderer_componentregistry - react_renderer_core - react_renderer_graphics - react_renderer_mounting - react_renderer_textlayoutmanager - react_renderer_uimanager - react_utils - rrc_text - rrc_view - yoga) -target_compile_reactnative_options(rrc_textinput_gpui PRIVATE) -target_compile_options(rrc_textinput_gpui PRIVATE -Wpedantic) -# react/renderer/components/switch is Android-only (its sole -# source is the fbjni-based AndroidSwitchMeasurementsManager; -# nothing links rrc_switch and the generated FBReactNativeSpec -# code does not reference it) — not built on the gpui platform. -# react/renderer/components/textinput and -# react/renderer/components/progressbar ship only android (fbjni) -# and ios (CocoaPods) platform sources; the generated -# FBReactNativeSpec code is self-contained and nothing links -# rrc_textinput/rrc_progressbar — not built on the gpui platform. -add_react_common_subdir(react/renderer/components/root) -add_react_common_subdir(react/renderer/components/image) -add_react_common_subdir(react/renderer/components/legacyviewmanagerinterop) -add_react_common_subdir(react/renderer/componentregistry/native) -add_react_common_subdir(react/renderer/components/text) -add_react_common_subdir(react/renderer/components/unimplementedview) -add_react_common_subdir(react/renderer/components/modal) -add_react_common_subdir(react/renderer/components/scrollview) -add_react_common_subdir(react/renderer/components/safeareaview) -add_react_common_subdir(react/renderer/leakchecker) -add_react_common_subdir(react/renderer/observers/events) -add_react_common_subdir(react/renderer/observers/intersection) -add_react_common_subdir(react/renderer/observers/mutation) -add_react_common_subdir(react/renderer/textlayoutmanager) - -# Upstream's cxx `TextLayoutManager::measure` returns the Yoga minimum size, so -# every paragraph collapses to zero height. Compile our copy override -# (ReactCommonOverrides/.../TextLayoutManager.cpp) in place of the upstream -# platform/cxx source; overrides.json tracks it so upstream drift is caught by -# `react-native-platform-override validate`. -set(RN_GPUI_TEXT_LAYOUT_MANAGER_OVERRIDE - "${RN_GPUI_OVERRIDES_DIR}/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.cpp") -if(TARGET react_renderer_textlayoutmanager AND EXISTS "${RN_GPUI_TEXT_LAYOUT_MANAGER_OVERRIDE}") - get_target_property(_rn_gpui_tlm_sources react_renderer_textlayoutmanager SOURCES) - # The platform selector resolves to absolute paths, the fallback to relative - # ones: match either. CONFIGURE_DEPENDS re-globs on reconfigure, so the - # upstream entry is re-added and has to be filtered out again every time. - list(FILTER _rn_gpui_tlm_sources EXCLUDE - REGEX "textlayoutmanager/platform/cxx/.*TextLayoutManager\\.cpp$") - list(APPEND _rn_gpui_tlm_sources "${RN_GPUI_TEXT_LAYOUT_MANAGER_OVERRIDE}") - set_property(TARGET react_renderer_textlayoutmanager - PROPERTY SOURCES "${_rn_gpui_tlm_sources}") - message(STATUS "rn_gpui_core: TextLayoutManager override: ${RN_GPUI_TEXT_LAYOUT_MANAGER_OVERRIDE}") -else() - message(WARNING - "rn_gpui_core: TextLayoutManager override not found (${RN_GPUI_TEXT_LAYOUT_MANAGER_OVERRIDE}); " - "paragraphs will measure to zero height") -endif() -# Upstream's cxx `ImageManager::requestImage` never completes, so Image sends -# no load events. Compile our copy override -# (ReactCommonOverrides/.../ImageManager.cpp) in place of the upstream source. -set(RN_GPUI_IMAGE_MANAGER_OVERRIDE - "${RN_GPUI_OVERRIDES_DIR}/react/renderer/imagemanager/platform/cxx/react/renderer/imagemanager/ImageManager.cpp") -if(TARGET react_renderer_imagemanager AND EXISTS "${RN_GPUI_IMAGE_MANAGER_OVERRIDE}") - get_target_property(_rn_gpui_im_sources react_renderer_imagemanager SOURCES) - list(FILTER _rn_gpui_im_sources EXCLUDE - REGEX "imagemanager/platform/cxx/.*ImageManager\\.cpp$") - list(APPEND _rn_gpui_im_sources "${RN_GPUI_IMAGE_MANAGER_OVERRIDE}") - set_property(TARGET react_renderer_imagemanager - PROPERTY SOURCES "${_rn_gpui_im_sources}") - message(STATUS "rn_gpui_core: ImageManager override: ${RN_GPUI_IMAGE_MANAGER_OVERRIDE}") -else() - message(WARNING - "rn_gpui_core: ImageManager override not found (${RN_GPUI_IMAGE_MANAGER_OVERRIDE}); " - "Image will send no load events") -endif() -add_react_common_subdir(react/utils) -add_react_common_subdir(react/bridging) -add_react_common_subdir(react/renderer/mapbuffer) -add_react_common_subdir(react/nativemodule/core) -add_react_common_subdir(react/nativemodule/defaults) -add_react_common_subdir(react/nativemodule/dom) -add_react_common_subdir(react/nativemodule/featureflags) -add_react_common_subdir(react/nativemodule/microtasks) -add_react_common_subdir(react/nativemodule/idlecallbacks) -add_react_common_subdir(react/nativemodule/intersectionobserver) -add_react_common_subdir(react/nativemodule/mutationobserver) -add_react_common_subdir(react/nativemodule/viewtransition) -add_react_common_subdir(react/nativemodule/webperformance) -add_react_common_subdir(react/networking) -add_react_common_subdir(jserrorhandler) -add_react_common_subdir(react/runtime) -add_react_common_subdir(react/runtime/nativeviewconfig) -add_react_common_subdir(react/timing) - -add_react_cxx_platform_subdir(react/coremodules) -add_react_cxx_platform_subdir(react/devsupport) - -# --- DevServerHelper patch override ---------- -# -# Upstream hardcodes the Android platform string, so Metro would be asked for -# the Android JS surface. Compile the copy override that passes -# `platform=desktop` in place of the vendored source; overrides.json tracks it so -# upstream drift is caught by `react-native-platform-override validate`. -set(RN_GPUI_DEV_SERVER_HELPER_OVERRIDE - "${RN_GPUI_OVERRIDES_DIR}/react/devsupport/DevServerHelper.cpp") -if(TARGET react_cxx_platform_react_devsupport AND EXISTS "${RN_GPUI_DEV_SERVER_HELPER_OVERRIDE}") - get_target_property(_rn_gpui_dsh_sources react_cxx_platform_react_devsupport SOURCES) - # The upstream glob is CONFIGURE_DEPENDS, so the vendored entry is re-added on - # every reconfigure and has to be filtered out again. - list(FILTER _rn_gpui_dsh_sources EXCLUDE - REGEX "devsupport/DevServerHelper\\.cpp$") - list(APPEND _rn_gpui_dsh_sources "${RN_GPUI_DEV_SERVER_HELPER_OVERRIDE}") - set_property(TARGET react_cxx_platform_react_devsupport - PROPERTY SOURCES "${_rn_gpui_dsh_sources}") - message(STATUS "rn_gpui_core: DevServerHelper override: ${RN_GPUI_DEV_SERVER_HELPER_OVERRIDE}") -else() - message(WARNING - "rn_gpui_core: DevServerHelper override not found (${RN_GPUI_DEV_SERVER_HELPER_OVERRIDE}); " - "the dev server will be asked for the Android bundle") -endif() - -# NativeDOM.cpp includes "NativeDOM.h" by quoted path, which always resolves to -# the sibling upstream header, so the header override alone is not enough. The -# copy override drops the backticks in its `#pragma mark` lines (MSVC rejects -# them with C2018) and includes the header through the override include path. -set(RN_GPUI_NATIVE_DOM_OVERRIDE - "${RN_GPUI_OVERRIDES_DIR}/react/nativemodule/dom/NativeDOM.cpp") -if(LOOM_RENDERER) - set(RN_GPUI_NATIVE_DOM_OVERRIDE - "${RN_GPUI_LOOM_OVERRIDES_DIR}/react/nativemodule/dom/NativeDOM.cpp") -endif() -if(TARGET react_nativemodule_dom) - get_target_property(_rn_gpui_dom_sources react_nativemodule_dom SOURCES) - list(FILTER _rn_gpui_dom_sources EXCLUDE REGEX "dom/NativeDOM\\.cpp$") - list(APPEND _rn_gpui_dom_sources "${RN_GPUI_NATIVE_DOM_OVERRIDE}") - set_property(TARGET react_nativemodule_dom - PROPERTY SOURCES "${_rn_gpui_dom_sources}") -endif() - -add_react_cxx_platform_subdir(react/http) - -# Upstream's ReactCxxPlatform/react/http/CMakeLists.txt globs only *.cpp, so it -# misses platform/cxx/WebSocketClient.cpp (the boost.beast cross-platform -# WebSocket client, which also needs ReactCommon headers). Patch the target from -# here rather than editing the vendored tree: ReactCxxPlatform is a byte-for-byte -# copy override, so a local edit would fail -# `react-native-platform-override validate`. -if(TARGET react_cxx_platform_react_http) - file(GLOB _rn_gpui_http_platform_cxx_SRC CONFIGURE_DEPENDS - "${REACT_CXX_PLATFORM_DIR}/react/http/platform/cxx/*.cpp") - target_sources(react_cxx_platform_react_http PRIVATE ${_rn_gpui_http_platform_cxx_SRC}) - target_include_directories(react_cxx_platform_react_http PUBLIC ${REACT_COMMON_DIR}) - if(APPLE) - find_library(RN_GPUI_SECURITY_FRAMEWORK Security REQUIRED) - target_link_libraries(react_cxx_platform_react_http ${RN_GPUI_SECURITY_FRAMEWORK}) - elseif(WIN32) - target_link_libraries(react_cxx_platform_react_http Crypt32) - endif() -endif() -add_react_cxx_platform_subdir(react/io) -target_include_directories(react_cxx_platform_react_io PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}") -target_link_libraries(react_cxx_platform_react_io OpenSSL::SSL) -add_react_cxx_platform_subdir(react/logging) -add_react_cxx_platform_subdir(react/nativemodule) -add_react_cxx_platform_subdir(react/profiling) -add_react_cxx_platform_subdir(react/renderer/scheduler) -add_react_cxx_platform_subdir(react/renderer/uimanager) -add_react_cxx_platform_subdir(react/threading) -add_react_cxx_platform_subdir(react/utils) -add_react_cxx_platform_subdir(react/runtime) -# PlatformConstantsModule reports the active engine as -# `Platform.constants.jsEngine`, so it includes GpuiJsEngine.h from here. -target_include_directories(react_cxx_platform_react_coremodules PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}") - -enable_testing() -add_executable(gpui_js_engine_test - test/gpui_js_engine_test.cpp - GpuiJsEngine.cpp) -target_include_directories(gpui_js_engine_test PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}" - "${REACT_COMMON_DIR}") -target_link_libraries(gpui_js_engine_test PRIVATE jsi) -add_test(NAME gpui_js_engine_selection COMMAND gpui_js_engine_test) - -# GpuiTurboModule.cpp logs through glog, which a prebuilt configure only has as -# an imported target when it is in the runtime's link closure. -if(TARGET jsi AND TARGET glog) - add_executable(gpui_turbo_module_test - test/gpui_turbo_module_test.cpp - GpuiTurboModule.cpp) - target_include_directories(gpui_turbo_module_test PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}" - "${REACT_COMMON_DIR}" - "${REACT_COMMON_DIR}/callinvoker" - "${REACT_COMMON_DIR}/react/nativemodule/core" - "${RN_GPUI_CXXBRIDGE_INCLUDE_DIR}") - target_link_libraries(gpui_turbo_module_test PRIVATE jsi glog) - add_test(NAME gpui_turbo_module_queue COMMAND gpui_turbo_module_test) -endif() - -# The engine packages' own smoke tests (for example a VM smoke test) are -# added by their desktop/CMakeLists.txt, which autolink includes below. - -add_library(rn_gpui_core STATIC - GpuiDynamic.cpp - # The Rust TurboModule provider is registered at run time, so it is always - # part of the platform: it looks a module up by name when JS asks for one. - GpuiRustTurboModules.cpp - GpuiHost.cpp - GpuiHttpClient.cpp - GpuiHttpBridge.cpp - GpuiNetworkConfig.cpp - GpuiStartupSignpost.cpp - GpuiJsEngine.cpp - GpuiLogBoxSurfaceDelegate.cpp - GpuiMountingManager.cpp - # The C++ half of the host component API: one generic props class, one - # shadow node with a state-driven measure function, and a descriptor per - # registered component name. - GpuiHostComponent.cpp - GpuiCppHostComponent.cpp - # Stock Node-API addon loading: the `_requireNodeLibrary` JSI global, path - # resolution, the cache and the error messages. Compiled on every platform — - # it is one small source file with no extra library — and it talks to the VM - # only through the active engine's NodeAddons capability. The Windows half - # (`GetModuleFileNameW` and `;` as the list separator) is live there now that - # the app's executable forwards the VM's Node-API exports. - GpuiNodeAddons.cpp - GpuiTurboModule.cpp - MountBatchBuilder.cpp - # A built-in component's props extraction. It registers by component name, so - # the mounting manager names no component. - builtins/image/GpuiImageProps.cpp - builtins/modal/GpuiModalProps.cpp - builtins/scrollview/GpuiScrollViewProps.cpp - builtins/textinput/GpuiTextInputProps.cpp - GpuiModules.cpp) -if(APPLE) - set_source_files_properties(GpuiAccessibilityMac.mm PROPERTIES - COMPILE_FLAGS "-fobjc-arc") - target_sources(rn_gpui_core PRIVATE GpuiAccessibilityMac.mm) - target_link_libraries(rn_gpui_core PUBLIC "-framework AppKit") -elseif(WIN32 OR (UNIX AND NOT ANDROID)) - target_sources(rn_gpui_core PRIVATE GpuiAccessibilityDesktop.cpp) -endif() -target_include_directories(rn_gpui_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) -target_include_directories(rn_gpui_core PUBLIC "${REACT_CXX_PLATFORM_DIR}") -target_sources(rn_gpui_core PRIVATE - "${REACT_CXX_PLATFORM_DIR}/react/renderer/components/windowcontrol/WindowControl.cpp" - "${REACT_CXX_PLATFORM_DIR}/react/renderer/components/desktopswitch/DesktopSwitch.cpp" - "${REACT_CXX_PLATFORM_DIR}/react/renderer/components/desktopcontextmenuview/DesktopContextMenuView.cpp" - "${REACT_CXX_PLATFORM_DIR}/react/renderer/components/shortcutscope/ShortcutScope.cpp" - "${REACT_CXX_PLATFORM_DIR}/react/renderer/components/nativeroot/NativeRoot.cpp" - "${REACT_CXX_PLATFORM_DIR}/react/renderer/components/nativeslot/NativeSlot.cpp" - "${REACT_CXX_PLATFORM_DIR}/react/renderer/components/desktopscrollbar/DesktopScrollBar.cpp" - builtins/window_control/GpuiWindowControlProps.cpp - builtins/switch/GpuiSwitchProps.cpp - builtins/activity_indicator/GpuiActivityIndicatorProps.cpp - builtins/context_menu_view/GpuiContextMenuViewProps.cpp - builtins/shortcut_scope/GpuiShortcutScopeProps.cpp - builtins/native_root/GpuiNativeRootProps.cpp - builtins/native_slot/GpuiNativeSlotProps.cpp - builtins/desktop_scroll_bar/GpuiDesktopScrollBarProps.cpp) -if(RN_GPUI_AUTOLINK_LIBRARIES) - target_link_libraries(rn_gpui_core PUBLIC ${RN_GPUI_AUTOLINK_LIBRARIES}) -endif() -if(LOOM_RENDERER) - target_sources(rn_gpui_core PRIVATE GpuiLoomHost.cpp LoomViewProps.cpp LoomComponentProps.cpp) -endif() - -# The cxx-generated bridge header is located above, -# before the ReactCommon subdirectories. rn_gpui_core consumes it directly. -if(RN_GPUI_CXXBRIDGE_INCLUDE_DIR AND EXISTS "${RN_GPUI_CXXBRIDGE_INCLUDE_DIR}/rust/cxx.h") - target_include_directories(rn_gpui_core PUBLIC "${RN_GPUI_CXXBRIDGE_INCLUDE_DIR}") -else() - message(WARNING - "rn_gpui_core: cxx bridge headers not found — run `cargo build -p rn-gpui-sys` first, " - "or pass -DRN_GPUI_CXXBRIDGE_INCLUDE_DIR=<.../out/cxxbridge/include>") -endif() - -# The glue includes headers from many RN libraries, so give it the union of -# their interface include directories. OBJECT libraries forward those to -# consumers, and their objects reach the final link through the consuming -# binary — which is exactly how the Rust cdylib will consume this static -# library. Targets listed in Fantom's tester build that do not -# exist here are guard-skipped with a warning rather than dropped silently. -set(RN_GPUI_CORE_DEPS - CURL::libcurl - jsi - jserrorhandler - jsitooling - oscompat - jsinspector - # jsinspector is an OBJECT library; a dependency on the parent does not - # archive the children's objects, so they are named explicitly (otherwise - # cdp::jsonRequest/NetworkHandler stay undefined). An engine package names its - # own OBJECT libraries the same way in RN_GPUI_JS_ENGINE_DEPS. - jsinspector_cdp - jsinspector_network - jsinspector_tracing - logger - react_bridging - react_codegen_rncore - react_cxxreact - react_debug - react_featureflags - react_nativemodule_core - react_nativemodule_defaults - react_nativemodule_dom - react_nativemodule_featureflags - react_nativemodule_idlecallbacks - react_nativemodule_intersectionobserver - react_nativemodule_microtasks - react_nativemodule_mutationobserver - react_nativemodule_viewtransition - react_nativemodule_webperformance - react_networking - react_performance_cdpmetrics - react_performance_timeline - react_utils - reactperflogger - bridgeless - react_renderer_animated - react_renderer_animationbackend - react_renderer_animations - react_renderer_attributedstring - react_renderer_componentregistry - react_renderer_consistency - react_renderer_core - react_renderer_css - react_renderer_debug - react_renderer_dom - react_renderer_element - react_renderer_graphics - react_renderer_imagemanager - react_renderer_leakchecker - react_renderer_mapbuffer - react_renderer_mounting - react_renderer_observers_events - react_renderer_observers_intersection - react_renderer_observers_mutation - react_renderer_runtimescheduler - react_renderer_scheduler - react_renderer_telemetry - react_renderer_textlayoutmanager - react_renderer_uimanager - react_renderer_uimanager_consistency - react_renderer_viewtransition - rrc_image - rrc_legacyviewmanagerinterop - rrc_modal - rrc_native - rrc_root - rrc_safeareaview - rrc_scrollview - rrc_text - rrc_textinput_gpui - rrc_unimplementedview - rrc_view - yoga - react_cxx_platform_react_coremodules - react_cxx_platform_react_devsupport - react_cxx_platform_react_http - react_cxx_platform_react_io - react_cxx_platform_react_logging - react_cxx_platform_react_nativemodule - react_cxx_platform_react_profiling - react_cxx_platform_react_renderer_scheduler - react_cxx_platform_react_renderer_uimanager - react_cxx_platform_react_runtime - react_cxx_platform_react_threading - react_cxx_platform_react_utils) -if(LOOM_RENDERER) - list(APPEND RN_GPUI_CORE_DEPS react_renderer_loom) -endif() -foreach(dep IN LISTS RN_GPUI_CORE_DEPS) - if(TARGET ${dep}) - target_link_libraries(rn_gpui_core PUBLIC ${dep}) - else() - message(WARNING "rn_gpui_core: target '${dep}' does not exist in this build") - endif() -endforeach() - -endif() # NOT RN_GPUI_PREBUILT_DIR (source build of rn_gpui_core and its deps) - -# Autolinked app packages are needed in both modes: they only add sources to -# global properties and app-side targets. -if(RN_GPUI_AUTOLINK_CMAKE AND EXISTS "${RN_GPUI_AUTOLINK_CMAKE}") - include("${RN_GPUI_AUTOLINK_CMAKE}") -endif() - -# JS engine packages (GpuiJsEngine.h) declare the React Native glue they need and -# the targets the app must link. The glue is added here, in core's scope, so its -# targets can be linked into rn_gpui_core (source builds archive their objects). -get_property(RN_GPUI_JS_ENGINE_SUBDIRECTORIES GLOBAL PROPERTY RN_GPUI_JS_ENGINE_SUBDIRECTORIES) -foreach(_rn_gpui_engine_subdir IN LISTS RN_GPUI_JS_ENGINE_SUBDIRECTORIES) - add_react_common_subdir(${_rn_gpui_engine_subdir}) -endforeach() - -# With a prebuilt runtime rn_gpui_core is imported, so the engine targets go to -# rn_gpui_modules instead (see below). In a source build they join -# RN_GPUI_CORE_DEPS so every consumer of core's dependency list — the app archive -# and the modules archive — also sees the engine's include directories. -get_property(RN_GPUI_JS_ENGINE_DEPS GLOBAL PROPERTY RN_GPUI_JS_ENGINE_DEPS) -if(RN_GPUI_JS_ENGINE_DEPS AND NOT RN_GPUI_PREBUILT_DIR) - list(APPEND RN_GPUI_CORE_DEPS ${RN_GPUI_JS_ENGINE_DEPS}) - target_link_libraries(rn_gpui_core PUBLIC ${RN_GPUI_JS_ENGINE_DEPS}) -endif() - -# App TurboModules are generated under desktop/autolink and linked as a -# separate archive. The platform runtime only owns the registration hook. -if(RN_GPUI_APP_CPP_PROVIDER_SOURCE AND EXISTS "${RN_GPUI_APP_CPP_PROVIDER_SOURCE}") - get_property(RN_GPUI_CMAKE_APP_CPP_SOURCES GLOBAL PROPERTY RN_GPUI_APP_CPP_SOURCES) - get_property(RN_GPUI_CMAKE_APP_CPP_INCLUDE_DIRS GLOBAL PROPERTY RN_GPUI_APP_CPP_INCLUDE_DIRS) - get_property(RN_GPUI_CMAKE_APP_CPP_DEFINITIONS GLOBAL PROPERTY RN_GPUI_APP_CPP_DEFINITIONS) - get_property(RN_GPUI_CMAKE_APP_CPP_COMPILE_OPTIONS GLOBAL PROPERTY RN_GPUI_APP_CPP_COMPILE_OPTIONS) - list(APPEND RN_GPUI_APP_CPP_SOURCES ${RN_GPUI_CMAKE_APP_CPP_SOURCES}) - # `extern "C" void f()` functions modules append to RN_GPUI_APP_CPP_INIT_FUNCTIONS - # run once, in order, at the end of the generated app initialization. - get_property(RN_GPUI_CMAKE_APP_CPP_INIT_FUNCTIONS GLOBAL PROPERTY RN_GPUI_APP_CPP_INIT_FUNCTIONS) - set(RN_GPUI_APP_CPP_INIT_DECLARATIONS "") - set(RN_GPUI_APP_CPP_INIT_CALLS "") - foreach(_rn_gpui_init IN LISTS RN_GPUI_CMAKE_APP_CPP_INIT_FUNCTIONS) - string(APPEND RN_GPUI_APP_CPP_INIT_DECLARATIONS "extern \"C\" void ${_rn_gpui_init}();\n") - string(APPEND RN_GPUI_APP_CPP_INIT_CALLS " ${_rn_gpui_init}();\n") - endforeach() - set(RN_GPUI_APP_CPP_INIT_SOURCE "${CMAKE_BINARY_DIR}/rn_gpui_app_cpp_init.generated.cpp") - file(CONFIGURE OUTPUT "${RN_GPUI_APP_CPP_INIT_SOURCE}" CONTENT -"// Generated by rn-gpui-sys; do not edit. -@RN_GPUI_APP_CPP_INIT_DECLARATIONS@extern \"C\" void rn_gpui_run_app_cpp_init_functions() { -@RN_GPUI_APP_CPP_INIT_CALLS@} -" @ONLY) - list(APPEND RN_GPUI_APP_CPP_SOURCES "${RN_GPUI_APP_CPP_INIT_SOURCE}") - add_library(rn_gpui_app_turbo_modules STATIC - "${RN_GPUI_APP_CPP_PROVIDER_SOURCE}" - ${RN_GPUI_APP_CPP_SOURCES}) - target_include_directories(rn_gpui_app_turbo_modules PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}" - "${RN_GPUI_CXXBRIDGE_INCLUDE_DIR}" - ${RN_GPUI_CMAKE_APP_CPP_INCLUDE_DIRS}) - target_compile_definitions(rn_gpui_app_turbo_modules PRIVATE ${RN_GPUI_CMAKE_APP_CPP_DEFINITIONS}) - target_compile_options(rn_gpui_app_turbo_modules PRIVATE ${RN_GPUI_CMAKE_APP_CPP_COMPILE_OPTIONS}) - if(RN_GPUI_PREBUILT_DIR) - # The imported rn_gpui_core already carries ReactCommon, folly and the rest; - # it cannot be given a link to this archive, so the link order comes from - # link_libs-.txt instead (see the link_libs section). - target_link_libraries(rn_gpui_app_turbo_modules PRIVATE rn_gpui_core) - # App sources may use the active engine's headers (a package that binds the - # Hermes runtime needs them), which the archive does not ship. The engine - # targets carry them. - if(RN_GPUI_JS_ENGINE_DEPS) - target_link_libraries(rn_gpui_app_turbo_modules PRIVATE ${RN_GPUI_JS_ENGINE_DEPS}) - endif() - else() - target_link_libraries(rn_gpui_app_turbo_modules PRIVATE ${RN_GPUI_CORE_DEPS}) - target_link_libraries(rn_gpui_core PUBLIC rn_gpui_app_turbo_modules) - endif() -endif() - -# --- rn_gpui_modules: optional library glue (cpp/GpuiModules.h) ------- -# -# Glue for an optional package is compiled here, in the app's build, rather than -# into rn_gpui_core, so rn_gpui_core compiles the same files with the same flags -# for every app. The package that needs the glue ships it in its own `gpui/cpp/` -# and declares it through the `RN_GPUI_PACKAGE_MODULE_*` properties below; -# what stays here is the platform's own glue, which no package owns. -# rn_gpui_install_modules() (generated below) calls each installer once, and -# GpuiHost calls it from its constructor. -set(RN_GPUI_MODULE_SOURCES) -set(RN_GPUI_MODULE_INSTALLERS) -set(RN_GPUI_MODULE_INCLUDE_DIRS) -set(RN_GPUI_MODULE_DEFINITIONS) - -get_property(RN_GPUI_PACKAGE_MODULE_SOURCES GLOBAL PROPERTY RN_GPUI_PACKAGE_MODULE_SOURCES) -get_property(RN_GPUI_PACKAGE_MODULE_INSTALLERS GLOBAL PROPERTY RN_GPUI_PACKAGE_MODULE_INSTALLERS) -get_property(RN_GPUI_PACKAGE_MODULE_INCLUDE_DIRS GLOBAL PROPERTY RN_GPUI_PACKAGE_MODULE_INCLUDE_DIRS) -list(APPEND RN_GPUI_MODULE_SOURCES ${RN_GPUI_PACKAGE_MODULE_SOURCES}) -list(APPEND RN_GPUI_MODULE_INSTALLERS ${RN_GPUI_PACKAGE_MODULE_INSTALLERS}) -list(APPEND RN_GPUI_MODULE_INCLUDE_DIRS ${RN_GPUI_PACKAGE_MODULE_INCLUDE_DIRS}) -# A module reads its library's Fabric props, which the app's codegen produced. -get_property(RN_GPUI_APP_CPP_INCLUDE_DIRS GLOBAL PROPERTY RN_GPUI_APP_CPP_INCLUDE_DIRS) -list(APPEND RN_GPUI_MODULE_INCLUDE_DIRS ${RN_GPUI_APP_CPP_INCLUDE_DIRS}) - -# JS engine packages (GpuiJsEngine.h): the registration shim is compiled into -# this archive, and the generated installer below calls its symbol before the -# other installers so the registry is populated before the host selects an -# engine. -get_property(RN_GPUI_JS_ENGINE_SOURCES GLOBAL PROPERTY RN_GPUI_JS_ENGINE_SOURCES) -get_property(RN_GPUI_JS_ENGINE_INCLUDE_DIRS GLOBAL PROPERTY RN_GPUI_JS_ENGINE_INCLUDE_DIRS) -get_property(RN_GPUI_JS_ENGINE_DEFINITIONS GLOBAL PROPERTY RN_GPUI_JS_ENGINE_DEFINITIONS) -get_property(RN_GPUI_JS_ENGINE_REGISTRATIONS GLOBAL PROPERTY RN_GPUI_JS_ENGINE_REGISTRATIONS) -list(APPEND RN_GPUI_MODULE_SOURCES ${RN_GPUI_JS_ENGINE_SOURCES}) -list(APPEND RN_GPUI_MODULE_INCLUDE_DIRS ${RN_GPUI_JS_ENGINE_INCLUDE_DIRS}) -list(APPEND RN_GPUI_MODULE_DEFINITIONS ${RN_GPUI_JS_ENGINE_DEFINITIONS}) - -# Core's own built-in modules register their renderers through the same -# generated installer, so a built-in is wired exactly like a package module. -list(APPEND RN_GPUI_MODULE_INSTALLERS activity_indicator context_menu_view desktop_scroll_bar image modal native_root native_slot scroll_view shortcut_scope switch text_input window_control) - -# The generated installer list depends on which packages are present, so it is -# written at configure time. file(CONFIGURE) only rewrites it when it changes. -set(RN_GPUI_MODULE_DECLARATIONS "") -set(RN_GPUI_MODULE_CALLS "") -foreach(_rn_gpui_installer IN LISTS RN_GPUI_MODULE_INSTALLERS) - string(APPEND RN_GPUI_MODULE_DECLARATIONS "void rn_gpui_install_${_rn_gpui_installer}_module();\n") - string(APPEND RN_GPUI_MODULE_CALLS " rn_gpui_install_${_rn_gpui_installer}_module();\n") -endforeach() -set(RN_GPUI_ENGINE_DECLARATIONS "") -set(RN_GPUI_ENGINE_CALLS "") -foreach(_rn_gpui_engine IN LISTS RN_GPUI_JS_ENGINE_REGISTRATIONS) - string(APPEND RN_GPUI_ENGINE_DECLARATIONS "extern \"C\" void ${_rn_gpui_engine}();\n") - string(APPEND RN_GPUI_ENGINE_CALLS " ${_rn_gpui_engine}();\n") -endforeach() -set(RN_GPUI_INSTALL_MODULES_CPP "${CMAKE_BINARY_DIR}/generated/rn_gpui_install_modules.cpp") -file(CONFIGURE OUTPUT "${RN_GPUI_INSTALL_MODULES_CPP}" CONTENT [=[ -// Generated by rn-gpui-sys cpp/CMakeLists.txt. Do not edit. -#include "GpuiModules.h" - -#include - -namespace rngpui { -@RN_GPUI_ENGINE_DECLARATIONS@ -@RN_GPUI_MODULE_DECLARATIONS@ -void rn_gpui_install_modules() { - static std::once_flag installed; - std::call_once(installed, [] { - // Engine packages first: the host selects an engine from the registry right - // after this call, and module installers may also register one. -@RN_GPUI_ENGINE_CALLS@@RN_GPUI_MODULE_CALLS@ }); -} - -} // namespace rngpui -]=]) - -# Always defined, even when no package is present, so link_libs.txt is stable. -add_library(rn_gpui_modules STATIC - "${RN_GPUI_INSTALL_MODULES_CPP}" - ${RN_GPUI_MODULE_SOURCES}) -target_compile_definitions(rn_gpui_modules PRIVATE ${RN_GPUI_MODULE_DEFINITIONS}) -target_include_directories(rn_gpui_modules PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}" - "${REACT_CXX_PLATFORM_DIR}" - ${RN_GPUI_MODULE_INCLUDE_DIRS}) -if(RN_GPUI_CXXBRIDGE_INCLUDE_DIR AND EXISTS "${RN_GPUI_CXXBRIDGE_INCLUDE_DIR}/rust/cxx.h") - target_include_directories(rn_gpui_modules PRIVATE "${RN_GPUI_CXXBRIDGE_INCLUDE_DIR}") -endif() -target_link_libraries(rn_gpui_modules PRIVATE ${RN_GPUI_CORE_DEPS}) -target_link_libraries(rn_gpui_modules PUBLIC rn_gpui_core) -# The app archive is not linked into rn_gpui_core in prebuilt mode, so make the -# build produce it explicitly; link_libs-.txt still references it. -if(RN_GPUI_PREBUILT_DIR AND TARGET rn_gpui_app_turbo_modules) - add_dependencies(rn_gpui_modules rn_gpui_app_turbo_modules) -endif() -# Out-of-tree addons can require native build targets without linking into -# core. They hang off this archive because it is built in both modes; an -# imported rn_gpui_core cannot carry build dependencies. -get_property(RN_GPUI_APP_NATIVE_TARGETS GLOBAL PROPERTY RN_GPUI_APP_NATIVE_TARGETS) -foreach(_rn_gpui_native_target IN LISTS RN_GPUI_APP_NATIVE_TARGETS) - add_dependencies(rn_gpui_modules ${_rn_gpui_native_target}) -endforeach() - -# With a prebuilt runtime rn_gpui_core is imported, so the engine glue targets -# cannot be linked into it; they are archived into this archive instead. The -# registration shim lives here too, so the objects reach the executable through -# the archive the app already links. -if(RN_GPUI_PREBUILT_DIR AND RN_GPUI_JS_ENGINE_DEPS) - target_link_libraries(rn_gpui_modules PRIVATE ${RN_GPUI_JS_ENGINE_DEPS}) -endif() - -# --- link_libs.txt for build.rs -------------------------- -# -# Cargo propagates `rustc-link-search` / `rustc-link-lib` from a build script -# that declares `links = "..."` to every dependent crate, whereas -# `cargo:rustc-link-arg` would not leave an rlib. The list is therefore written -# as linker file *names* plus their directories, never as absolute paths. On -# Windows the linker file for a shared target is its import library, while its -# runtime target file is the DLL; TARGET_LINKER_FILE selects the right artifact. -# -# The objects of every OBJECT library linked into rn_gpui_core are already -# archived inside librn_gpui_core.a, so only real archives and dylibs are listed. - -function(rn_gpui_collect_link_targets root out_var) - set(_queue "${root}") - set(_seen "") - while(_queue) - list(POP_FRONT _queue _entry) - if(_entry IN_LIST _seen) - continue() - endif() - if(NOT TARGET "${_entry}") - continue() - endif() - get_target_property(_type "${_entry}" TYPE) - if(NOT _type MATCHES "LIBRARY$") - continue() - endif() - list(APPEND _seen "${_entry}") - get_target_property(_links "${_entry}" LINK_LIBRARIES) - get_target_property(_interface_links "${_entry}" INTERFACE_LINK_LIBRARIES) - foreach(_more IN LISTS _links _interface_links) - if(TARGET "${_more}" AND NOT _more IN_LIST _seen) - list(APPEND _queue "${_more}") - endif() - endforeach() - endwhile() - set(${out_var} "${_seen}" PARENT_SCOPE) -endfunction() - -rn_gpui_collect_link_targets(rn_gpui_core RN_GPUI_LINK_TARGETS) -# An imported rn_gpui_core only names the archive's own libraries in its -# interface, so the active engine's shared libraries (its VM) are added to the -# roots the linker directives are collected from. Their OBJECT libraries are -# skipped by the loop below; those objects are archived into rn_gpui_modules. -if(RN_GPUI_PREBUILT_DIR AND RN_GPUI_JS_ENGINE_DEPS) - list(APPEND RN_GPUI_LINK_TARGETS ${RN_GPUI_JS_ENGINE_DEPS}) -endif() - -if(NOT RN_GPUI_PREBUILT_DIR) - include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules/PrebuiltInstall.cmake) -endif() - -set(RN_GPUI_LINK_LIBS "") -# Directories that must end up on the executable's rpath: Rust does not turn -# `rustc-link-search` into an rpath. build.rs forwards this list to rn-gpui, -# whose build script emits the platform-specific linker flags. -set(RN_GPUI_RPATH_DIRS "") - -# Shared libraries an engine package adds (its VM, for example) are ordinary -# imported targets: the loop below finds them by walking rn_gpui_core's link -# interfaces and emits both the linker directive and the rpath. No engine is -# special-cased here. -# -# rn_gpui_modules appears before and after rn_gpui_core (see below). -string(APPEND RN_GPUI_LINK_LIBS "search:$\nname:$\n") -foreach(_target IN LISTS RN_GPUI_LINK_TARGETS) - get_target_property(_type "${_target}" TYPE) - get_target_property(_is_framework "${_target}" FRAMEWORK) - if(_is_framework) - get_target_property(_framework_output_name "${_target}" OUTPUT_NAME) - if(NOT _framework_output_name) - set(_framework_output_name "${_target}") - endif() - get_target_property(_framework_search_dir "${_target}" LIBRARY_OUTPUT_DIRECTORY) - string(APPEND RN_GPUI_LINK_LIBS "framework-search:${_framework_search_dir}\nframework-name:${_framework_output_name}\n") - string(APPEND RN_GPUI_RPATH_DIRS "${_framework_search_dir}\n") - continue() - endif() - # UNKNOWN_LIBRARY covers imported libraries found by find_package() (e.g. - # OpenSSL::Crypto from FindOpenSSL); they still have a usable TARGET_FILE. - if(_type STREQUAL "STATIC_LIBRARY" OR _type STREQUAL "SHARED_LIBRARY" OR _type STREQUAL "UNKNOWN_LIBRARY") - string(APPEND RN_GPUI_LINK_LIBS "search:$\nname:$\n") - if(_type STREQUAL "SHARED_LIBRARY" OR _type STREQUAL "UNKNOWN_LIBRARY") - string(APPEND RN_GPUI_RPATH_DIRS "$\n") - endif() - endif() - # Static libraries hide their link-only dependencies behind generator - # expressions, so rn_gpui_collect_link_targets cannot discover this archive - # by walking rn_gpui_core's interface links. Put it directly after the core - # archive and before the ReactCommon archives it depends on. - if(_target STREQUAL "rn_gpui_core" AND TARGET rn_gpui_app_turbo_modules) - string(APPEND RN_GPUI_LINK_LIBS "search:$\nname:$\n") - endif() - # Installers read rn_gpui_core's hook storage and call into the app archive, - # so the modules archive comes after both (static archives resolve left - # to right). - if(_target STREQUAL "rn_gpui_core" AND TARGET rn_gpui_modules) - string(APPEND RN_GPUI_LINK_LIBS "search:$\nname:$\n") - endif() -endforeach() - -if(CMAKE_SYSTEM_NAME STREQUAL "Linux") - # libstdc++ emits these helpers for lock-free 16-byte atomics on x86_64. - # Place it after the static RN archives so the final Rust link resolves them. - string(APPEND RN_GPUI_LINK_LIBS "name:atomic\n") -endif() - -# The content names target file directories, which differ per configuration on -# multi-config generators (Visual Studio), so file(GENERATE) requires the -# configuration in the file name. build.rs reads the one matching its profile. -file(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/link_libs-$.txt" CONTENT "${RN_GPUI_LINK_LIBS}") -file(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/rpath_dirs-$.txt" CONTENT "${RN_GPUI_RPATH_DIRS}") - -# --- C++ standard for C++ only ------------------------------------------- -# The same flag list passes -std=c++20 on to every target that links a -# ReactCommon target, and clang rejects it for C sources ("invalid argument -# '-std=c++20' not allowed with 'C'"), such as sqlite3.c in an app's TurboModule. -# The flag is kept for C++ sources only. -if(NOT MSVC) - function(rn_gpui_cxx_standard_for_cxx_only directory) - get_property(_targets DIRECTORY "${directory}" PROPERTY BUILDSYSTEM_TARGETS) - foreach(_target IN LISTS _targets) - foreach(_property IN ITEMS COMPILE_OPTIONS INTERFACE_COMPILE_OPTIONS) - get_target_property(_options "${_target}" "${_property}") - if(NOT _options) - continue() - endif() - set(_rewritten "") - set(_changed FALSE) - foreach(_option IN LISTS _options) - if(_option MATCHES "^-std=(c|gnu)\\+\\+") - list(APPEND _rewritten "$<$:${_option}>") - set(_changed TRUE) - else() - list(APPEND _rewritten "${_option}") - endif() - endforeach() - if(_changed) - set_target_properties("${_target}" PROPERTIES "${_property}" "${_rewritten}") - endif() - endforeach() - endforeach() - get_property(_subdirectories DIRECTORY "${directory}" PROPERTY SUBDIRECTORIES) - foreach(_subdirectory IN LISTS _subdirectories) - rn_gpui_cxx_standard_for_cxx_only("${_subdirectory}") - endforeach() - endfunction() - - rn_gpui_cxx_standard_for_cxx_only("${CMAKE_CURRENT_BINARY_DIR}") -endif() - -# --- MSVC compile-flag cleanup ------------------------------------------- -# React Native's shared flag list (cmake-utils/react-native-flags.cmake) is -# written for clang/gcc and is applied to every ReactCommon target as -# -Wall -Werror -fexceptions -frtti -std=c++20, and the bundled third-party -# projects add more of the same (-Wwrite-strings, -Wno-unused-variable, -# -Wpedantic). cl.exe reads those as /W options with non-numeric arguments and -# aborts the build with, for example, -# cl : command line error D8021: invalid numeric argument '/Werror' -# Every RN subdirectory includes that file itself, so the list cannot be -# overridden from this file; the GCC-only spellings are removed from the -# targets once they all exist, and the MSVC equivalents are added instead. -if(MSVC) - function(rn_gpui_strip_gcc_only_flags directory) - get_property(_targets DIRECTORY "${directory}" PROPERTY BUILDSYSTEM_TARGETS) - foreach(_target IN LISTS _targets) - foreach(_property IN ITEMS COMPILE_OPTIONS INTERFACE_COMPILE_OPTIONS) - get_target_property(_options "${_target}" "${_property}") - if(NOT _options) - continue() - endif() - set(_kept "") - set(_stripped FALSE) - foreach(_option IN LISTS _options) - # -W... is a clang/gcc warning flag (MSVC spells its own /W0-/W4, - # /Wall and /WX, which do not match this pattern); -f..., -std=..., - # -m... and -pthread have MSVC equivalents or are meaningless there. - if(_option MATCHES "^-W[a-zA-Z]" OR _option MATCHES "^-f" - OR _option MATCHES "^-std=" OR _option MATCHES "^-m[a-z]" - OR _option MATCHES "^-pthread" - # RN's glog CMakeLists hardcodes -g -O2, and cl rejects /O2 next - # to the /RTC1 of a Debug build; the build type sets both. - OR _option STREQUAL "-g" OR _option MATCHES "^-O[0-3sz]?$" - # RN's glog CMakeLists hardcodes -DHAVE_PREAD=1 for Android. - OR _option MATCHES "^-DHAVE_PREAD") - set(_stripped TRUE) - else() - list(APPEND _kept "${_option}") - endif() - endforeach() - if(_stripped) - set_target_properties("${_target}" PROPERTIES "${_property}" "${_kept}") - endif() - endforeach() - - # ReactCommon components glob their per-platform sources alongside the - # portable ones; the ios/android/apple trees only compile for those - # toolchains (our platform implementation lives in platform/cxx). - # rrc_textinput_gpui compiles RN's iostextinput shadow node and props on - # purpose (see its definition), so it keeps its platform/ios sources. - get_target_property(_of_sources "${_target}" SOURCES) - if(_of_sources AND NOT _target STREQUAL "rrc_textinput_gpui") - list(FILTER _of_sources EXCLUDE REGEX "/platform/(ios|android|apple)/") - set_target_properties("${_target}" PROPERTIES SOURCES "${_of_sources}") - endif() - endforeach() - get_property(_subdirectories DIRECTORY "${directory}" PROPERTY SUBDIRECTORIES) - foreach(_subdirectory IN LISTS _subdirectories) - rn_gpui_strip_gcc_only_flags("${_subdirectory}") - endforeach() - endfunction() - - rn_gpui_strip_gcc_only_flags("${CMAKE_CURRENT_BINARY_DIR}") - - # A unity build is what makes the build fast (each target's shared headers are - # parsed once instead of once per source) and also what makes it unsafe for - # code that was never compiled that way: merging sources makes file-scope - # names and macros from one source visible to the next. The vendored - # third-party trees are exactly that — curl defines same-named file-local - # helpers in several sources, and folly's portability shims pick one - # implementation per file — so they keep the translation-unit layout their - # upstreams expect, and the win comes from ReactCommon and the gpui platform - # targets that this repository builds and tests. - # - # Selection is by source directory, not by target name: the vendored trees - # define hundreds of targets whose names differ per version, and a name list - # silently stops matching when one is renamed. - # - # `yoga` lives under ReactCommon but is a vendored upstream of its own whose - # Node.cpp cannot be merged with its siblings ("error C2872: 'Node': ambiguous - # symbol"), so both roots are matched. - # - # `rrc_view` and `rrc_legacyviewmanagerinterop` are ReactCommon targets that - # also cannot be merged, for two different upstream reasons: - # - # * `rrc_view` defines a `toString` overload per props class (Filter.h, - # BackgroundImage.h) while DebugStringConvertible.h's - # `toString(std::vector)` template is instantiated in the same unit. - # Resolution depends on which source precedes which, and merging puts - # `toString(BackgroundImage)` after the instantiation ("error C2665: no - # overloaded function could convert all the argument types"). - # * `rrc_legacyviewmanagerinterop` includes - # LegacyViewManagerInteropViewProps.h, which has no include guard at all — - # it is wrapped in `#ifndef RCT_REMOVE_LEGACY_COMPONENT_INTEROP`, a build - # feature rather than a guard — so merging redefines its classes ("error - # C2011: 'LegacyViewManagerInteropViewProps': 'class' type redefinition"). - # - # Both are ~4 sources each, so leaving them unmerged costs almost nothing and - # needs no edit to vendored React Native. - # - # OpenSSL is not a CMake target at all (it builds through its own Configure + - # Make), so it is unaffected. - function(rn_gpui_disable_unity_for_vendored directory) - get_property(_targets DIRECTORY "${directory}" PROPERTY BUILDSYSTEM_TARGETS) - foreach(_target IN LISTS _targets) - # Aliases (double_conversion, yoga, ...) reject set_target_properties, and - # the real target they name is visited by this same walk. - get_target_property(_aliased "${_target}" ALIASED_TARGET) - if(_aliased) - continue() - endif() - if(_target STREQUAL "rrc_view" - OR _target STREQUAL "rrc_legacyviewmanagerinterop" - OR _target STREQUAL "react_renderer_mounting") - set_target_properties("${_target}" PROPERTIES UNITY_BUILD OFF) - continue() - endif() - get_target_property(_source_dir "${_target}" SOURCE_DIR) - # curl builds from the shared cache, which RN_GPUI_NATIVE_DEPS_CACHE may - # place anywhere; the prepared sources are under this build's native-deps. - string(FIND "${_source_dir}" "${RN_GPUI_NATIVE_DEPS_CACHE}/" _in_native_deps_cache) - if(_source_dir AND (_in_native_deps_cache EQUAL 0 - OR _source_dir MATCHES "native-deps" - OR _source_dir MATCHES "/ReactCommon/yoga/")) - set_target_properties("${_target}" PROPERTIES UNITY_BUILD OFF) - endif() - endforeach() - get_property(_subdirectories DIRECTORY "${directory}" PROPERTY SUBDIRECTORIES) - foreach(_subdirectory IN LISTS _subdirectories) - rn_gpui_disable_unity_for_vendored("${_subdirectory}") - endforeach() - endfunction() - - if(RN_GPUI_UNITY_BUILD) - rn_gpui_disable_unity_for_vendored("${CMAKE_CURRENT_BINARY_DIR}") - # The app's library sources come from several packages, whose file-scope - # names can collide once merged into one translation unit. - if(TARGET rn_gpui_app_turbo_modules) - set_target_properties(rn_gpui_app_turbo_modules PROPERTIES UNITY_BUILD OFF) - endif() - endif() - - # RN's jsi CMakeLists globs every jsi/*.cpp, which drags in the POSIX memory - # mapping implementation; Windows has jsilib-windows.cpp instead. - if(TARGET jsi) - get_target_property(_rn_gpui_jsi_sources jsi SOURCES) - if(_rn_gpui_jsi_sources) - list(FILTER _rn_gpui_jsi_sources EXCLUDE REGEX "jsilib-posix\\.cpp$") - set_target_properties(jsi PROPERTIES SOURCES "${_rn_gpui_jsi_sources}") - endif() - # jsi is a shared library, but JSI_EXPORT is empty above, so nothing is - # marked dllexport. Without exports link.exe writes no jsi.lib and the - # final Rust link fails with LNK1181. Export every jsi symbol instead. - set_target_properties(jsi PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON) - endif() -endif() diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiAccessibilityDesktop.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiAccessibilityDesktop.cpp deleted file mode 100644 index 29162a82b2..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiAccessibilityDesktop.cpp +++ /dev/null @@ -1,219 +0,0 @@ -// Accessibility settings on Windows and Linux: the same C entry points -// GpuiAccessibilityMac.mm provides, backed by SystemParametersInfo and the -// registry on Windows, and gsettings on Linux. Neither OS pushes a change to -// an application that is not a window, so a thread re-reads the settings. - -#include -#include -#include -#include -#include -#include -#include - -#if defined(_WIN32) -#include -#endif - -extern "C" void rn_gpui_accessibility_setting_changed( - const char* eventName, - bool enabled); - -namespace { - -#if defined(_WIN32) - -bool systemParameterFlag(UINT action) { - BOOL value = FALSE; - return SystemParametersInfoW(action, 0, &value, 0) && value; -} - -bool readReduceMotion() { - BOOL animations = TRUE; - if (!SystemParametersInfoW(SPI_GETCLIENTAREAANIMATION, 0, &animations, 0)) { - return false; - } - return !animations; -} - -bool readScreenReader() { - return systemParameterFlag(SPI_GETSCREENREADER); -} - -bool readIncreaseContrast() { - HIGHCONTRASTW contrast{}; - contrast.cbSize = sizeof(contrast); - return SystemParametersInfoW( - SPI_GETHIGHCONTRAST, sizeof(contrast), &contrast, 0) && - (contrast.dwFlags & HCF_HIGHCONTRASTON) != 0; -} - -bool readReduceTransparency() { - DWORD enabled = 1; - DWORD size = sizeof(enabled); - const LSTATUS status = RegGetValueW( - HKEY_CURRENT_USER, - L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", - L"EnableTransparency", - RRF_RT_REG_DWORD, - nullptr, - &enabled, - &size); - return status == ERROR_SUCCESS && enabled == 0; -} - -#else - -// `gsettings get ` printed without the trailing newline, or an -// empty string when gsettings or the key is missing. -std::string gsettings(const char* schema, const char* key) { - const std::string command = - std::string("gsettings get ") + schema + " " + key + " 2>/dev/null"; - FILE* pipe = popen(command.c_str(), "r"); - if (pipe == nullptr) { - return {}; - } - std::string output; - char buffer[64]; - while (fgets(buffer, sizeof(buffer), pipe) != nullptr) { - output += buffer; - } - pclose(pipe); - while (!output.empty() && (output.back() == '\n' || output.back() == ' ')) { - output.pop_back(); - } - return output; -} - -bool readReduceMotion() { - return gsettings("org.gnome.desktop.interface", "enable-animations") == - "false"; -} - -bool readScreenReader() { - return gsettings( - "org.gnome.desktop.a11y.applications", "screen-reader-enabled") == - "true"; -} - -bool readIncreaseContrast() { - return gsettings("org.gnome.desktop.a11y.interface", "high-contrast") == - "true"; -} - -bool readReduceTransparency() { - return false; -} - -#endif - -struct Observer { - std::mutex mutex; - std::condition_variable wake; - std::thread thread; - bool stopping = false; - bool running = false; -}; - -Observer& observer() { - static Observer instance; - return instance; -} - -void observe() { - auto& state = observer(); - bool reduceMotion = readReduceMotion(); - bool screenReader = readScreenReader(); - bool increaseContrast = readIncreaseContrast(); - bool reduceTransparency = readReduceTransparency(); - const auto changed = [](const char* name, bool& last, bool now) { - if (now != last) { - last = now; - rn_gpui_accessibility_setting_changed(name, now); - } - }; - std::unique_lock lock(state.mutex); - while (!state.stopping) { - if (state.wake.wait_for( - lock, std::chrono::seconds(2), [&] { return state.stopping; })) { - break; - } - lock.unlock(); - changed("reduceMotionChanged", reduceMotion, readReduceMotion()); - changed("screenReaderChanged", screenReader, readScreenReader()); - changed( - "darkerSystemColorsChanged", increaseContrast, readIncreaseContrast()); - changed( - "reduceTransparencyChanged", - reduceTransparency, - readReduceTransparency()); - lock.lock(); - } -} - -} // namespace - -extern "C" bool rn_gpui_get_reduce_motion() { - return readReduceMotion(); -} - -extern "C" bool rn_gpui_get_reduce_transparency() { - return readReduceTransparency(); -} - -extern "C" bool rn_gpui_get_increase_contrast() { - return readIncreaseContrast(); -} - -extern "C" bool rn_gpui_get_invert_colors() { - return false; -} - -extern "C" bool rn_gpui_get_voice_over() { - return readScreenReader(); -} - -namespace { -std::atomic announceHandler{nullptr}; -} // namespace - -// The application shows an announcement as a live region of its own window, so -// the screen reader reads it as it reads any other live region change. -extern "C" void rn_gpui_set_announce_handler( - void (*handler)(const char*, int)) { - announceHandler.store(handler); -} - -extern "C" void rn_gpui_announce_accessibility(const char* text, int priority) { - if (auto handler = announceHandler.load()) { - handler(text, priority); - } -} - -extern "C" void rn_gpui_start_accessibility_observing() { - auto& state = observer(); - std::lock_guard lock(state.mutex); - if (state.running) { - return; - } - state.running = true; - state.stopping = false; - state.thread = std::thread(observe); -} - -extern "C" void rn_gpui_stop_accessibility_observing() { - auto& state = observer(); - { - std::lock_guard lock(state.mutex); - if (!state.running) { - return; - } - state.stopping = true; - } - state.wake.notify_all(); - if (state.thread.joinable()) { - state.thread.join(); - } - std::lock_guard lock(state.mutex); - state.running = false; -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiAccessibilityMac.mm b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiAccessibilityMac.mm deleted file mode 100644 index 90b10ef0ce..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiAccessibilityMac.mm +++ /dev/null @@ -1,167 +0,0 @@ -#import -#import - -extern "C" void rn_gpui_accessibility_setting_changed( - const char *eventName, - bool enabled); - -static id accessibilityOptionsObserver = nil; -static bool lastReduceMotion = false; -static bool lastReduceTransparency = false; -static bool lastIncreaseContrast = false; -static bool lastInvertColors = false; - -@interface GpuiVoiceOverObserver : NSObject -@end - -@implementation GpuiVoiceOverObserver -- (void)observeValueForKeyPath:(NSString *)keyPath - ofObject:(id)object - change:(NSDictionary *)change - context:(void *)context -{ - if ([keyPath isEqualToString:@"voiceOverEnabled"]) { - const bool enabled = NSWorkspace.sharedWorkspace.isVoiceOverEnabled; - dispatch_async(dispatch_get_main_queue(), ^{ - rn_gpui_accessibility_setting_changed("screenReaderChanged", enabled); - }); - } else { - [super observeValueForKeyPath:keyPath - ofObject:object - change:change - context:context]; - } -} -@end - -static GpuiVoiceOverObserver *voiceOverObserver = nil; - -extern "C" bool rn_gpui_get_voice_over() -{ - return NSWorkspace.sharedWorkspace.isVoiceOverEnabled; -} - -extern "C" bool rn_gpui_get_invert_colors() -{ - return NSWorkspace.sharedWorkspace.accessibilityDisplayShouldInvertColors; -} - -extern "C" bool rn_gpui_get_reduce_motion() -{ - return NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion; -} - -extern "C" bool rn_gpui_get_reduce_transparency() -{ - return NSWorkspace.sharedWorkspace - .accessibilityDisplayShouldReduceTransparency; -} - -extern "C" bool rn_gpui_get_increase_contrast() -{ - return NSWorkspace.sharedWorkspace.accessibilityDisplayShouldIncreaseContrast; -} - -extern "C" void rn_gpui_start_accessibility_observing() -{ - dispatch_block_t start = ^{ - if (accessibilityOptionsObserver != nil) { - return; - } - NSWorkspace *workspace = NSWorkspace.sharedWorkspace; - lastReduceMotion = workspace.accessibilityDisplayShouldReduceMotion; - lastReduceTransparency = - workspace.accessibilityDisplayShouldReduceTransparency; - lastIncreaseContrast = workspace.accessibilityDisplayShouldIncreaseContrast; - lastInvertColors = workspace.accessibilityDisplayShouldInvertColors; - voiceOverObserver = [GpuiVoiceOverObserver new]; - [workspace addObserver:voiceOverObserver - forKeyPath:@"voiceOverEnabled" - options:NSKeyValueObservingOptionNew - context:nullptr]; - accessibilityOptionsObserver = [workspace.notificationCenter - addObserverForName: - NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification - object:nil - queue:NSOperationQueue.mainQueue - usingBlock:^(__unused NSNotification *notification) { - NSWorkspace *workspace = NSWorkspace.sharedWorkspace; - const bool reduceMotion = - workspace.accessibilityDisplayShouldReduceMotion; - const bool reduceTransparency = - workspace.accessibilityDisplayShouldReduceTransparency; - const bool increaseContrast = - workspace.accessibilityDisplayShouldIncreaseContrast; - const bool invertColors = - workspace.accessibilityDisplayShouldInvertColors; - if (invertColors != lastInvertColors) { - lastInvertColors = invertColors; - rn_gpui_accessibility_setting_changed( - "invertColorsChanged", invertColors); - } - if (reduceMotion != lastReduceMotion) { - lastReduceMotion = reduceMotion; - rn_gpui_accessibility_setting_changed( - "reduceMotionChanged", reduceMotion); - } - if (reduceTransparency != lastReduceTransparency) { - lastReduceTransparency = reduceTransparency; - rn_gpui_accessibility_setting_changed( - "reduceTransparencyChanged", reduceTransparency); - } - if (increaseContrast != lastIncreaseContrast) { - lastIncreaseContrast = increaseContrast; - rn_gpui_accessibility_setting_changed( - "darkerSystemColorsChanged", increaseContrast); - } - }]; - }; - if (NSThread.isMainThread) { - start(); - } else { - dispatch_sync(dispatch_get_main_queue(), start); - } -} - -extern "C" void rn_gpui_stop_accessibility_observing() -{ - dispatch_block_t stop = ^{ - if (accessibilityOptionsObserver != nil) { - [NSWorkspace.sharedWorkspace.notificationCenter - removeObserver:accessibilityOptionsObserver]; - accessibilityOptionsObserver = nil; - [NSWorkspace.sharedWorkspace removeObserver:voiceOverObserver - forKeyPath:@"voiceOverEnabled"]; - voiceOverObserver = nil; - } - }; - if (NSThread.isMainThread) { - stop(); - } else { - dispatch_sync(dispatch_get_main_queue(), stop); - } -} - -extern "C" void rn_gpui_announce_accessibility( - const char *message, - int priorityLevel) -{ - if (message == nullptr || message[0] == '\0') { - return; - } - NSString *announcement = [[NSString alloc] initWithUTF8String:message]; - if (announcement == nil) { - return; - } - const auto priority = priorityLevel == 2 ? NSAccessibilityPriorityHigh - : priorityLevel == 0 ? NSAccessibilityPriorityLow - : NSAccessibilityPriorityMedium; - NSDictionary *info = @{ - NSAccessibilityAnnouncementKey : announcement, - NSAccessibilityPriorityKey : @(priority), - }; - dispatch_async(dispatch_get_main_queue(), ^{ - NSAccessibilityPostNotificationWithUserInfo( - NSApp, NSAccessibilityAnnouncementRequestedNotification, info); - }); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiCppHostBridge.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiCppHostBridge.h deleted file mode 100644 index 6117f159a1..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiCppHostBridge.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#include -#include - -namespace rngpui { - -/// Creates the C++ view of the node of component `index` and gives it its -/// first props (`props` is a props handle's address). Returns 0 when no C++ -/// implementation is registered for the index. -uint64_t -rn_gpui_cpp_host_create(uint32_t index, int32_t tag, std::size_t props); - -void rn_gpui_cpp_host_update(uint64_t id, std::size_t props); - -/// Creates the node's native view. The result's kind is 0 for a composited -/// view, 1 for an NSView (the returned value) and 2 for an X11 window. -uint64_t rn_gpui_cpp_host_create_view( - uint64_t id, - std::size_t windows_visual, - bool wayland, - uint32_t x11_window, - std::size_t xcb_connection, - std::size_t wayland_display, - std::size_t wayland_surface, - uint8_t& kind); - -void rn_gpui_cpp_host_destroy(uint64_t id); - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiCppHostComponent.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiCppHostComponent.cpp deleted file mode 100644 index 7dfb12912b..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiCppHostComponent.cpp +++ /dev/null @@ -1,194 +0,0 @@ -#include "GpuiCppHostComponent.h" - -#include "GpuiCppHostBridge.h" -#include "GpuiHostComponentsCpp.h" - -#include - -#include -#include -#include -#include - -namespace rngpui { -namespace { -struct Declaration { - uint32_t index; - std::string name; - bool nativeSurface; -}; - -struct Registry { - std::mutex mutex; - std::vector declarations; - std::deque names; - std::vector(int32_t)>> - creators; -}; - -Registry& registry() { - static Registry registry; - return registry; -} - -struct LiveView { - std::unique_ptr view; - std::shared_ptr lastProps; -}; - -std::unordered_map& liveViews() { - static std::unordered_map views; - return views; -} - -uint64_t& nextId() { - static uint64_t id = 1; - return id; -} - -std::shared_ptr propsOf(std::size_t handle) { - if (handle == 0) { - return nullptr; - } - return reinterpret_cast(handle)->props; -} - -void markChanged( - const facebook::react::Props&, - const facebook::react::Props&, - uint64_t* words) { - words[0] |= 1; -} - -bool noCommand(int32_t, const std::string&, const folly::dynamic&) { - return false; -} -} // namespace - -namespace extension { -void declareCppHostComponent( - uint32_t index, - const char* name, - bool nativeSurface) { - auto& reg = registry(); - std::lock_guard lock(reg.mutex); - reg.declarations.push_back({index, name, nativeSurface}); -} - -void registerCppHostComponent(CppHostComponent component) { - auto& reg = registry(); - std::lock_guard lock(reg.mutex); - const Declaration* found = nullptr; - for (const auto& declaration : reg.declarations) { - if (declaration.name == component.name) { - found = &declaration; - break; - } - } - if (found == nullptr) { - LOG(ERROR) << "[host-component] " << component.name - << " is a C++ host component but is not declared with cpp: true " - "under platforms.desktop.hostComponents; ignored"; - return; - } - reg.names.push_back(component.name); - HostComponentEntry entry; - entry.index = found->index; - entry.name = reg.names.back().c_str(); - entry.handle = component.handle; - entry.nativeSurface = found->nativeSurface; - entry.provider = component.provider; - entry.changed = &markChanged; - entry.changeWords = 1; - entry.command = &noCommand; - if (reg.creators.size() <= found->index) { - reg.creators.resize(found->index + 1); - } - reg.creators[found->index] = std::move(component.create); - registerHostComponentEntry(entry); -} -} // namespace extension - -uint64_t -rn_gpui_cpp_host_create(uint32_t index, int32_t tag, std::size_t props) { - std::function(int32_t)> create; - { - auto& reg = registry(); - std::lock_guard lock(reg.mutex); - if (index < reg.creators.size()) { - create = reg.creators[index]; - } - } - if (!create) { - LOG_FIRST_N(ERROR, 1) - << "[host-component] no C++ implementation is registered for host " - "component index " - << index; - return 0; - } - auto view = create(tag); - if (!view) { - return 0; - } - auto current = propsOf(props); - view->update(current, nullptr); - const uint64_t id = nextId()++; - liveViews().emplace(id, LiveView{std::move(view), std::move(current)}); - return id; -} - -void rn_gpui_cpp_host_update(uint64_t id, std::size_t props) { - auto found = liveViews().find(id); - if (found == liveViews().end()) { - return; - } - auto current = propsOf(props); - found->second.view->update(current, found->second.lastProps); - found->second.lastProps = std::move(current); -} - -uint64_t rn_gpui_cpp_host_create_view( - uint64_t id, - std::size_t windows_visual, - bool wayland, - uint32_t x11_window, - std::size_t xcb_connection, - std::size_t wayland_display, - std::size_t wayland_surface, - uint8_t& kind) { - kind = 0; - auto found = liveViews().find(id); - if (found == liveViews().end()) { - return 0; - } - extension::NativeViewParent parent; - parent.windowsVisual = reinterpret_cast(windows_visual); - parent.wayland = wayland; - parent.x11Window = x11_window; - parent.xcbConnection = reinterpret_cast(xcb_connection); - parent.waylandDisplay = reinterpret_cast(wayland_display); - parent.waylandSurface = reinterpret_cast(wayland_surface); - const auto view = found->second.view->createNativeView(parent); - switch (view.kind) { - case extension::NativeView::Kind::NSView: - kind = 1; - return reinterpret_cast(view.nsView); - case extension::NativeView::Kind::X11Window: - kind = 2; - return view.x11Window; - case extension::NativeView::Kind::Composited: - break; - } - return 0; -} - -void rn_gpui_cpp_host_destroy(uint64_t id) { - auto found = liveViews().find(id); - if (found == liveViews().end()) { - return; - } - auto live = std::move(found->second); - liveViews().erase(found); - live.view->unmount(); -} -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiCppHostComponent.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiCppHostComponent.h deleted file mode 100644 index 0946a9d348..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiCppHostComponent.h +++ /dev/null @@ -1,76 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include -#include -#include - -namespace rngpui::extension { - -/// Where a native view is created: the composition surface core made for the -/// node. -struct NativeViewParent { - /// Windows: the node's IDCompositionVisual, as IUnknown*. Null elsewhere. - void* windowsVisual = nullptr; - /// Linux: X11 (xcb) or Wayland. Unused on macOS. - bool wayland = false; - uint32_t x11Window = 0; - void* xcbConnection = nullptr; - void* waylandDisplay = nullptr; - void* waylandSurface = nullptr; -}; - -/// The native view of a component, as `createNativeView` returns it. -struct NativeView { - enum class Kind { Composited, NSView, X11Window }; - Kind kind = Kind::Composited; - /// A +1 retained NSView*; core takes ownership. - void* nsView = nullptr; - /// A child window the view keeps owning. - uint32_t x11Window = 0; -}; - -/// One mounted node of a C++ host component. Every method runs on the main -/// thread. -class CppHostView { - public: - virtual ~CppHostView() = default; - /// The props changed. `oldProps` is null on the first call. - virtual void update( - const std::shared_ptr& props, - const std::shared_ptr& oldProps) = 0; - /// Once, when the node is first painted. Only for `nativeSurface` - /// components. - virtual NativeView createNativeView(const NativeViewParent& parent) { - return {}; - } - /// The node unmounts; called before destruction. - virtual void unmount() {} -}; - -struct CppHostComponent { - /// The Fabric component name, as `hostComponents` declares it. - std::string name; - /// `ShadowNode::Handle()` of the component's shadow node. - facebook::react::ComponentHandle handle = 0; - facebook::react::ComponentDescriptorProvider (*provider)() = nullptr; - std::function(int32_t tag)> create; -}; - -/// Declares a `cpp: true` entry of `hostComponents`. Called by the autolink -/// generated code, before any module's init function runs. -void declareCppHostComponent( - uint32_t index, - const char* name, - bool nativeSurface); - -/// Registers the implementation of a declared component, matched by name. An -/// undeclared component, or one registered after the registry froze, is logged -/// and ignored. -void registerCppHostComponent(CppHostComponent component); - -} // namespace rngpui::extension diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiDynamic.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiDynamic.cpp deleted file mode 100644 index f5b38c1177..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiDynamic.cpp +++ /dev/null @@ -1,196 +0,0 @@ -#include "GpuiDynamic.h" - -#include -#include -#include -#include -#include - -namespace rngpui { - -namespace { - -/// One node of a value: scalars, or children with the key that names them in an -/// object. -struct Node { - uint8_t kind = DynamicNull; - // Holds a number, or a bool as 0 or 1. - double number = 0.0; - std::string text; - std::vector bytes; - std::vector> children; -}; - -struct Scope { - std::vector nodes; -}; - -std::mutex& scopesMutex() { - static std::mutex mutex; - return mutex; -} - -std::unordered_map& scopes() { - static std::unordered_map map; - return map; -} - -std::atomic& nextScopeId() { - static std::atomic next{1}; - return next; -} - -Node& nodeAt(uint32_t scope, uint32_t node) { - std::lock_guard lock(scopesMutex()); - auto found = scopes().find(scope); - if (found == scopes().end()) { - throw std::runtime_error("dynamic scope is gone"); - } - if (node >= found->second.nodes.size()) { - throw std::runtime_error("dynamic node is gone"); - } - return found->second.nodes[node]; -} - -void checkKind(const Node& node, uint8_t kind, const char* what) { - if (node.kind != kind) { - throw std::runtime_error(std::string("expected ") + what); - } -} - -/// Adds an empty node and returns its id. Callers must not hold a reference to -/// another node across this, since the vector may move. -uint32_t appendNode(Scope& scope) { - scope.nodes.emplace_back(); - return static_cast(scope.nodes.size() - 1); -} - -} // namespace - -uint32_t dynamic_scope_open() { - const uint32_t id = nextScopeId().fetch_add(1); - std::lock_guard lock(scopesMutex()); - scopes().emplace(id, Scope{}); - return id; -} - -void dynamic_scope_close(uint32_t scope) { - std::lock_guard lock(scopesMutex()); - scopes().erase(scope); -} - -uint32_t dynamic_node_new(uint32_t scope, uint8_t kind) { - std::lock_guard lock(scopesMutex()); - auto found = scopes().find(scope); - if (found == scopes().end()) { - throw std::runtime_error("dynamic scope is gone"); - } - found->second.nodes.emplace_back(); - Node& node = found->second.nodes.back(); - node.kind = kind; - return static_cast(found->second.nodes.size() - 1); -} - -void dynamic_node_set_bool(uint32_t scope, uint32_t node, bool value) { - Node& target = nodeAt(scope, node); - checkKind(target, DynamicBool, "a boolean"); - target.number = value ? 1.0 : 0.0; -} - -void dynamic_node_set_number(uint32_t scope, uint32_t node, double value) { - Node& target = nodeAt(scope, node); - checkKind(target, DynamicNumber, "a number"); - target.number = value; -} - -void dynamic_node_set_buffer( - uint32_t scope, - uint32_t node, - rust::Slice bytes) { - Node& target = nodeAt(scope, node); - checkKind(target, DynamicBuffer, "an ArrayBuffer"); - target.bytes.assign(bytes.begin(), bytes.end()); -} - -void dynamic_node_set_text(uint32_t scope, uint32_t node, rust::Str text) { - Node& target = nodeAt(scope, node); - checkKind(target, DynamicString, "a string"); - target.text = std::string(text); -} - -void dynamic_node_append( - uint32_t scope, - uint32_t parent, - uint32_t child, - rust::Str key) { - Node& target = nodeAt(scope, parent); - if (target.kind != DynamicArray && target.kind != DynamicObject) { - throw std::runtime_error("expected an array or an object"); - } - target.children.emplace_back(std::string(key), child); -} - -uint8_t dynamic_node_kind(uint32_t scope, uint32_t node) { - return nodeAt(scope, node).kind; -} - -bool dynamic_node_bool(uint32_t scope, uint32_t node) { - const Node& target = nodeAt(scope, node); - checkKind(target, DynamicBool, "a boolean"); - return target.number != 0.0; -} - -double dynamic_node_number(uint32_t scope, uint32_t node) { - const Node& target = nodeAt(scope, node); - checkKind(target, DynamicNumber, "a number"); - return target.number; -} - -rust::String dynamic_node_text(uint32_t scope, uint32_t node) { - const Node& target = nodeAt(scope, node); - checkKind(target, DynamicString, "a string"); - return rust::String(target.text); -} - -size_t dynamic_node_buffer_len(uint32_t scope, uint32_t node) { - const Node& target = nodeAt(scope, node); - checkKind(target, DynamicBuffer, "an ArrayBuffer"); - return target.bytes.size(); -} - -rust::Vec dynamic_node_buffer(uint32_t scope, uint32_t node) { - const Node& target = nodeAt(scope, node); - checkKind(target, DynamicBuffer, "an ArrayBuffer"); - rust::Vec bytes; - bytes.reserve(target.bytes.size()); - for (const uint8_t byte : target.bytes) { - bytes.push_back(byte); - } - return bytes; -} - -size_t dynamic_node_len(uint32_t scope, uint32_t node) { - const Node& target = nodeAt(scope, node); - if (target.kind != DynamicArray && target.kind != DynamicObject) { - throw std::runtime_error("expected an array or an object"); - } - return target.children.size(); -} - -uint32_t dynamic_node_child(uint32_t scope, uint32_t node, size_t index) { - const Node& target = nodeAt(scope, node); - if (index >= target.children.size()) { - throw std::runtime_error("child index out of range"); - } - return target.children[index].second; -} - -rust::String dynamic_node_key(uint32_t scope, uint32_t node, size_t index) { - const Node& target = nodeAt(scope, node); - if (index >= target.children.size()) { - throw std::runtime_error("child index out of range"); - } - return rust::String(target.children[index].first); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiDynamic.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiDynamic.h deleted file mode 100644 index 99a3b9e391..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiDynamic.h +++ /dev/null @@ -1,54 +0,0 @@ -#pragma once - -#include -#include -#include - -#include - -namespace rngpui { - -/// A value crosses the cxx bridge as nodes in a C++-owned arena, one scope per -/// call, so nothing is serialised to text and ownership stays on one side. The -/// side that opens a scope closes it. -enum DynamicKind : uint8_t { - DynamicNull = 0, - DynamicBool = 1, - DynamicNumber = 2, - DynamicString = 3, - DynamicArray = 4, - DynamicObject = 5, - DynamicBuffer = 6, -}; - -constexpr uint32_t kDynamicNoNode = 0xffffffffu; - -uint32_t dynamic_scope_open(); -void dynamic_scope_close(uint32_t scope); - -/// `key` names an object member; an array child has none. -uint32_t dynamic_node_new(uint32_t scope, uint8_t kind); -void dynamic_node_set_bool(uint32_t scope, uint32_t node, bool value); -void dynamic_node_set_number(uint32_t scope, uint32_t node, double value); -void dynamic_node_set_text(uint32_t scope, uint32_t node, rust::Str text); -void dynamic_node_set_buffer( - uint32_t scope, - uint32_t node, - rust::Slice bytes); -void dynamic_node_append( - uint32_t scope, - uint32_t parent, - uint32_t child, - rust::Str key); - -uint8_t dynamic_node_kind(uint32_t scope, uint32_t node); -bool dynamic_node_bool(uint32_t scope, uint32_t node); -double dynamic_node_number(uint32_t scope, uint32_t node); -rust::String dynamic_node_text(uint32_t scope, uint32_t node); -size_t dynamic_node_len(uint32_t scope, uint32_t node); -size_t dynamic_node_buffer_len(uint32_t scope, uint32_t node); -rust::Vec dynamic_node_buffer(uint32_t scope, uint32_t node); -uint32_t dynamic_node_child(uint32_t scope, uint32_t node, size_t index); -rust::String dynamic_node_key(uint32_t scope, uint32_t node, size_t index); - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHost.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHost.cpp deleted file mode 100644 index e6c1992010..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHost.cpp +++ /dev/null @@ -1,1379 +0,0 @@ -#include "GpuiHost.h" -#include - -#include -#include -#include -#include "GpuiHttpClient.h" -#include "GpuiJsEngine.h" -#include "GpuiLogBoxSurfaceDelegate.h" -#include "GpuiLoomHost.h" -#include "GpuiMainMessageQueue.h" -#include "GpuiModules.h" -#include "GpuiMountingManager.h" -#include "GpuiNodeAddons.h" -#include "GpuiRustTurboModules.h" -#include "MountBatchBuilder.h" -#include "rn-gpui-sys/src/lib.rs.h" // cxx bridge - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if LOOM_RENDERER -#include -#include -#endif -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rngpui { -#if LOOM_RENDERER -// Loom takes a surface's constraints and the text scale from the host, next to -// the Fabric surface handler that still carries the surface's lifecycle. -void setLoomSurfaceConstraints( - GpuiLoomHost& host, - int32_t surfaceId, - const facebook::react::LayoutConstraints& constraints, - float scale) { - host.setPointScaleFactor(scale); - facebook::react::LoomBinding::setSurfaceConstraints( - surfaceId, - constraints.minimumSize.width, - constraints.minimumSize.height, - constraints.maximumSize.width, - constraints.maximumSize.height, - constraints.layoutDirection == - facebook::react::LayoutDirection::RightToLeft, - 0.f, - 0.f); -} -#endif -} // namespace rngpui - -namespace { -facebook::react::LayoutDirection surfaceLayoutDirection() { - return rngpui::rn_gpui_layout_direction_rtl() - ? facebook::react::LayoutDirection::RightToLeft - : facebook::react::LayoutDirection::LeftToRight; -} - -std::atomic nativeAnimationActive{false}; -} // namespace - -extern "C" uint64_t rn_gpui_native_animations_active() noexcept { - return nativeAnimationActive.load() ? 1 : 0; -} - -namespace rngpui { -void updateFrameDemand() { - rn_gpui_set_animated_active( - nativeAnimationActive.load() || anyFrameRequested()); -} -} // namespace rngpui - -extern "C" uint64_t rn_gpui_frame_demand() noexcept { - return rngpui::anyFrameRequested() ? 1 : 0; -} - -extern "C" uint64_t rn_gpui_pending_work() noexcept { - return rngpui::pendingWork(); -} - -extern "C" bool rn_gpui_accessibility_active(); -#if defined(_MSC_VER) -// This hook lives in the rn-gpui Rust crate, which rn-gpui-sys does not depend -// on. An application links both, but rn-gpui-sys's own test binaries link only -// this crate, and MSVC has no weak symbols, so the reference would be -// unresolved (LNK2019). `alternatename` names a fallback used only while the -// symbol is otherwise undefined, so a real definition still wins wherever the -// crate is present. -extern "C" bool rn_gpui_accessibility_active_default() { - return false; -} -#pragma comment( \ - linker, \ - "/alternatename:rn_gpui_accessibility_active=rn_gpui_accessibility_active_default") -#endif - -#if defined(__APPLE__) || defined(_WIN32) || defined(__linux__) -#define RN_GPUI_ACCESSIBILITY_SETTINGS 1 -#endif - -#if defined(RN_GPUI_ACCESSIBILITY_SETTINGS) -extern "C" bool rn_gpui_get_reduce_motion(); -extern "C" bool rn_gpui_get_reduce_transparency(); -extern "C" bool rn_gpui_get_increase_contrast(); -extern "C" bool rn_gpui_get_invert_colors(); -extern "C" bool rn_gpui_get_voice_over(); -extern "C" void rn_gpui_announce_accessibility( - const char* message, - int priorityLevel); -extern "C" void rn_gpui_start_accessibility_observing(); -extern "C" void rn_gpui_stop_accessibility_observing(); -#endif - -using namespace facebook::react; - -namespace rngpui { -namespace { -std::mutex pointerEventMutex; -extension::RawPointerEvent lastPointerEvent{}; -} // namespace - -namespace { -std::atomic activeGpuiHost{nullptr}; - -namespace jsi = facebook::jsi; -using AppCppTurboModuleProvider = std::shared_ptr (*)( - const std::string&, - std::shared_ptr); -std::atomic appCppTurboModuleProvider{nullptr}; - -std::mutex appearanceMutex; -std::string systemAppearance{"light"}; -std::optional appearanceOverride; - -class GpuiAppearanceModule final - : public NativeAppearanceCxxSpec { - public: - explicit GpuiAppearanceModule(std::shared_ptr jsInvoker) - : NativeAppearanceCxxSpec(std::move(jsInvoker)) {} - - facebook::jsi::String getColorScheme(facebook::jsi::Runtime& runtime) { - std::lock_guard lock(appearanceMutex); - return facebook::jsi::String::createFromUtf8( - runtime, appearanceOverride.value_or(systemAppearance)); - } - - void setColorScheme(facebook::jsi::Runtime&, std::string scheme) { - std::string before; - std::string after; - { - std::lock_guard lock(appearanceMutex); - before = appearanceOverride.value_or(systemAppearance); - if (scheme == "light" || scheme == "dark") { - appearanceOverride = std::move(scheme); - } else { - appearanceOverride.reset(); - } - after = appearanceOverride.value_or(systemAppearance); - } - if (before != after) { - for (const auto& observer : - rngpui::gpuiExtensionHooks().colorSchemeObservers) { - observer(after); - } - } - } - - void addListener(facebook::jsi::Runtime&, std::string) {} - void removeListeners(facebook::jsi::Runtime&, double) {} -}; - -class GpuiAccessibilityManagerModule final - : public NativeAccessibilityManagerCxxSpec { - public: - explicit GpuiAccessibilityManagerModule( - std::shared_ptr jsInvoker) - : NativeAccessibilityManagerCxxSpec(std::move(jsInvoker)) {} - - void getCurrentBoldTextState( - jsi::Runtime& /*runtime*/, - AsyncCallback onSuccess, - AsyncCallback /*onError*/) { - onSuccess(false); - } - void getCurrentGrayscaleState( - jsi::Runtime& /*runtime*/, - AsyncCallback onSuccess, - AsyncCallback /*onError*/) { - onSuccess(false); - } - void getCurrentInvertColorsState( - jsi::Runtime& /*runtime*/, - AsyncCallback onSuccess, - AsyncCallback /*onError*/) { -#if defined(RN_GPUI_ACCESSIBILITY_SETTINGS) - onSuccess(rn_gpui_get_invert_colors()); -#else - onSuccess(false); -#endif - } - void getCurrentReduceMotionState( - jsi::Runtime& /*runtime*/, - AsyncCallback onSuccess, - AsyncCallback /*onError*/) { -#if defined(RN_GPUI_ACCESSIBILITY_SETTINGS) - onSuccess(rn_gpui_get_reduce_motion()); -#else - onSuccess(false); -#endif - } - void getCurrentDarkerSystemColorsState( - jsi::Runtime& /*runtime*/, - AsyncCallback onSuccess, - AsyncCallback /*onError*/) { -#if defined(RN_GPUI_ACCESSIBILITY_SETTINGS) - onSuccess(rn_gpui_get_increase_contrast()); -#else - onSuccess(false); -#endif - } - void getCurrentPrefersCrossFadeTransitionsState( - jsi::Runtime& /*runtime*/, - AsyncCallback onSuccess, - AsyncCallback /*onError*/) { - onSuccess(false); - } - void getCurrentReduceTransparencyState( - jsi::Runtime& /*runtime*/, - AsyncCallback onSuccess, - AsyncCallback /*onError*/) { -#if defined(RN_GPUI_ACCESSIBILITY_SETTINGS) - onSuccess(rn_gpui_get_reduce_transparency()); -#else - onSuccess(false); -#endif - } - void getCurrentVoiceOverState( - jsi::Runtime& /*runtime*/, - AsyncCallback onSuccess, - AsyncCallback /*onError*/) { -#if defined(__APPLE__) - onSuccess(rn_gpui_get_voice_over()); -#elif defined(RN_GPUI_ACCESSIBILITY_SETTINGS) - onSuccess(rn_gpui_get_voice_over() || rn_gpui_accessibility_active()); -#else - onSuccess(rn_gpui_accessibility_active()); -#endif - } - void setAccessibilityContentSizeMultipliers( - jsi::Runtime& /*runtime*/, - jsi::Object /*multipliers*/) {} - void setAccessibilityFocus(jsi::Runtime& /*runtime*/, double reactTag) { - rn_gpui_request_accessibility_focus(static_cast(reactTag)); - } - void announceForAccessibility( - jsi::Runtime& runtime, - jsi::String announcement) { -#if defined(RN_GPUI_ACCESSIBILITY_SETTINGS) - auto text = announcement.utf8(runtime); - rn_gpui_announce_accessibility(text.c_str(), 1); -#endif - } - void announceForAccessibilityWithOptions( - jsi::Runtime& runtime, - jsi::String announcement, - jsi::Object options) { -#if defined(RN_GPUI_ACCESSIBILITY_SETTINGS) - auto text = announcement.utf8(runtime); - const auto queue = options.getProperty(runtime, "queue"); - int priorityLevel = queue.isBool() && queue.getBool() ? 0 : 1; - const auto priority = options.getProperty(runtime, "priority"); - if (priority.isString()) { - const auto name = priority.asString(runtime).utf8(runtime); - if (name == "high") - priorityLevel = 2; - else if (name == "low") - priorityLevel = 0; - else if (name == "default") - priorityLevel = 1; - } - rn_gpui_announce_accessibility(text.c_str(), priorityLevel); -#endif - } -}; - -class GpuiAccessibilityInfoModule final - : public NativeAccessibilityInfoCxxSpec { - public: - explicit GpuiAccessibilityInfoModule(std::shared_ptr jsInvoker) - : NativeAccessibilityInfoCxxSpec(std::move(jsInvoker)) {} - - void isReduceMotionEnabled(jsi::Runtime&, AsyncCallback callback) { -#if defined(RN_GPUI_ACCESSIBILITY_SETTINGS) - callback(rn_gpui_get_reduce_motion()); -#else - callback(false); -#endif - } - void isInvertColorsEnabled(jsi::Runtime&, AsyncCallback callback) { -#if defined(RN_GPUI_ACCESSIBILITY_SETTINGS) - callback(rn_gpui_get_invert_colors()); -#else - callback(false); -#endif - } - void isHighTextContrastEnabled(jsi::Runtime&, AsyncCallback callback) { -#if defined(RN_GPUI_ACCESSIBILITY_SETTINGS) - callback(rn_gpui_get_increase_contrast()); -#else - callback(false); -#endif - } - void isTouchExplorationEnabled(jsi::Runtime&, AsyncCallback callback) { - // Desktop pointer/keyboard accessibility is not equivalent to touch - // exploration; AccessKit currently has no portable screen-reader query. - callback(false); - } - void isAccessibilityServiceEnabled( - jsi::Runtime&, - AsyncCallback callback) { - callback(false); - } - void setAccessibilityFocus(jsi::Runtime&, double reactTag) { - rn_gpui_request_accessibility_focus(static_cast(reactTag)); - } - void announceForAccessibility(jsi::Runtime& runtime, jsi::String text) { -#if defined(RN_GPUI_ACCESSIBILITY_SETTINGS) - const auto announcement = text.utf8(runtime); - rn_gpui_announce_accessibility(announcement.c_str(), 1); -#endif - } - void getRecommendedTimeoutMillis( - jsi::Runtime&, - double timeout, - AsyncCallback callback) { - callback(timeout); - } - void isGrayscaleEnabled(jsi::Runtime&, AsyncCallback callback) { - callback(false); - } -}; - -extern "C" void rn_gpui_request_reload(); - -/// Thin C shim so the vendored `DevSettingsModule` (ReactCxxPlatform) can reach -/// the same Rust handler without depending on the cxx bridge header. -extern "C" void rn_gpui_dev_settings_changed(const char* name, bool enabled) { - if (name != nullptr) { - rn_gpui_dev_setting(rust::String(name), enabled); - } -} - -extern "C" void rn_gpui_set_app_cpp_turbo_module_provider( - AppCppTurboModuleProvider provider) { - appCppTurboModuleProvider.store(provider, std::memory_order_release); -} - -TurboModuleProviders gpui_turbo_module_providers() { - return { - [](const std::string& name, const std::shared_ptr& jsInvoker) - -> std::shared_ptr { - if (auto provider = - appCppTurboModuleProvider.load(std::memory_order_acquire)) { - if (auto appModule = provider(name, jsInvoker)) { - return appModule; - } - } - for (const auto& extensionProvider : - rngpui::gpuiModuleHooks().turboModules) { - if (auto extensionModule = extensionProvider(name, jsInvoker)) { - return extensionModule; - } - } - if (name == - NativeAppearanceCxxSpec::kModuleName) { - return std::make_shared(jsInvoker); - } - if (name == - NativeAccessibilityManagerCxxSpec< - GpuiAccessibilityManagerModule>::kModuleName) { - return std::make_shared(jsInvoker); - } - if (name == - NativeAccessibilityInfoCxxSpec< - GpuiAccessibilityInfoModule>::kModuleName) { - return std::make_shared(jsInvoker); - } - return nullptr; - }}; -} - -// Installs the OSS stable feature flags, which is what an OSS app on the new -// (bridgeless) architecture does. `enableBridgelessArchitecture` is load -// bearing for us: ReactHost here IS the bridgeless host, and an engine is -// expected to enable its microtask queue when that flag is on; without it, -// React's rendering path fails with "Could not enqueue microtask because they -// are disabled in this runtime". -void install_feature_flags() { - static std::once_flag once; - std::call_once(once, [] { - // An engine that needs flags of its own returns an overrides object - // deriving from rngpui::GpuiFeatureFlagsOverrides, so core's survive. - const auto& engine = rngpui::activeJsEngine(); - std::unique_ptr overrides; - if (engine.makeFeatureFlagsOverrides) { - overrides = engine.makeFeatureFlagsOverrides(); - } - if (!overrides) { - overrides = std::make_unique(); - } - ReactNativeFeatureFlags::override(std::move(overrides)); - }); -} -} // namespace - -std::unique_ptr new_gpui_host( - rust::Str appId, - rust::Str devHost, - uint32_t devPort, - rust::Str jsEngine, - rust::Str jsThread, - bool devMode) { - return std::make_unique( - appId, devHost, devPort, jsEngine, jsThread, devMode); -} - -GpuiHost::GpuiHost( - rust::Str appId, - rust::Str devHost, - uint32_t devPort, - rust::Str jsEngine, - rust::Str jsThread, - bool devMode) { - // Engine packages register themselves here (the generated - // rn_gpui_install_modules()), so the registry is populated before the - // app's choice (`RN_GPUI_JS_ENGINE` / DesktopAppConfig::js_engine) is applied - // and before anything asks for the active engine. The Rust TurboModule - // provider is always present, so it installs its hook alongside them. - rngpui::install_rust_turbo_modules(); - rngpui::rn_gpui_install_modules(); - rngpui::selectJsEngine(std::string(jsEngine)); -#if LOOM_RENDERER - rngpui::sharedAnimatedBackend().store(true, std::memory_order_release); -#endif - install_feature_flags(); - rngpui::installGpuiTextMeasureTable(); - rngpui::installGpuiImageLoadTable(); - - ReactInstanceConfig config; - config.appId = std::string(appId); - config.deviceName = "rn-gpui"; - config.devServerHost = std::string(devHost); - config.devServerPort = devPort; - // Dev mode is decided at runtime by the caller (the app's Cargo profile, or - // RN_GPUI_DEV_MODE), not by REACT_NATIVE_DEBUG. The prebuilt runtime is built - // in Release, so a macro default here would send every debug app that links - // it to the on-disk bundle instead of Metro. - config.enableDevMode = devMode; - config.enableInspector = devMode; - if (std::getenv("RN_GPUI_TEST_DRIVER")) { - const auto* mode = std::getenv("RN_GPUI_TEST_MODE"); - if (mode && std::string_view(mode) == "metro") - config.enableDevMode = true; - } - config.platformTimerRegistryFactory = [] { - return std::make_unique(); - }; - config.jsRuntimeFactory = rngpui::activeJsEngine().makeRuntimeFactory(); - -#if LOOM_RENDERER - // Loom keeps the surface tree itself: nothing mounts through the shadow tree, - // so there is no mount to report and the root's size is Loom's to answer. - mountingManager_ = std::make_shared( - nullptr, [this](SurfaceId surfaceId) { - return loomHost_->surfaceContentSize(surfaceId); - }); -#else - mountingManager_ = std::make_shared( - [this](SurfaceId surfaceId) { - reactHost_->runOnScheduler([surfaceId](Scheduler& scheduler) { - scheduler.reportMount(surfaceId); - }); - }, - [this](SurfaceId surfaceId) { - return reactHost_->surfaceContentSize(surfaceId); - }); -#endif - - rngpui::setHostComponentStateManager(mountingManager_); - - // ReactHost's constructor throws unless both factories are in the - // ContextContainer. - auto contextContainer = std::make_shared(); - contextContainer->insert(HttpClientFactoryKey, gpui_http_client_factory()); - contextContainer->insert( - WebSocketClientFactoryKey, getWebSocketClientFactory()); - contextContainer->insert( - "RCTImageLoader", - std::static_pointer_cast(mountingManager_->getImageLoader())); - -#if LOOM_RENDERER - // Fixed before the runtime scheduler or any binding reads it; unset, Loom - // runs JavaScript on the UI thread. - const bool jsOnMain = std::string(jsThread) == "main"; - LoomHost::setJavaScriptOnUIThread(jsOnMain); - // Registered before the JS runtime installs its binding, which reads it. - loomHost_ = std::make_shared( - mountingManager_, - contextContainer, - [this](std::function&& task) { - if (reactHost_) { - reactHost_->runOnScheduler(std::move(task)); - } - }, - [this](std::function&& task) { - if (reactHost_) { - reactHost_->runOnRuntimeScheduler( - [task = std::move(task)](facebook::jsi::Runtime&) { task(); }); - } - }); - loomHost_->connect(); - LoomHost::registerIn(*contextContainer, loomHost_); - loomHost_->installSizeHints(); - mountingManager_->setInstanceHook([this](bool up) { - if (up) { - loomHost_->begin(); - } else { - loomHost_->reset(); - } - }); - if (jsOnMain) { - contextContainer->insert( - MessageQueueThreadFactoryKey, MessageQueueThreadFactory([] { - return std::make_shared(); - })); - } -#endif - - runLoopObserverManager_ = std::make_shared(); - - config.animatedNodesManagerProviderFactory = [this] { - return std::make_shared( - [this](std::function&& callback, bool /*isAsync*/) { - if (gpuiDebugAnimationEnabled()) { - LOG(INFO) << "[native-animated] frame callback started"; - } - { - std::lock_guard lock(animatedFrameMutex_); - animatedFrameCallback_ = std::move(callback); - } - nativeAnimationActive.store(true); - rngpui::updateFrameDemand(); - }, - [this](bool /*isAsync*/) { - if (gpuiDebugAnimationEnabled()) { - LOG(INFO) << "[native-animated] frame callback stopped"; - } - { - std::lock_guard lock(animatedFrameMutex_); - animatedFrameCallback_ = nullptr; - } - nativeAnimationActive.store(false); - rngpui::updateFrameDemand(); - }); - }; - config.beforeInstanceDestroy = [this] { - // Wait for a frame already executing on GPUI, then prevent callbacks into - // the old graph while ReactHost tears down its runtime and UIManager. - std::lock_guard lock(animatedFrameMutex_); - animatedFrameCallback_ = nullptr; - nativeAnimationActive.store(false); -#if LOOM_RENDERER - if (loomHost_) { - loomHost_->animationFrameSource()->pause(); - } -#endif - rngpui::updateFrameDemand(); - }; - - // The LogBox surface. ReactHost hands this to - // `ReactCxxTurboModuleProvider`, which builds `LogBoxModule` only when the - // delegate is set (`ReactCxxTurboModuleProvider.cpp`); without it the JS side - // logs "Failed to load TurboModule: LogBox" and no red box appears. - logBoxDelegate_ = std::make_shared(*this); - - reactHost_ = std::make_unique( - config, - mountingManager_, - runLoopObserverManager_, - std::move(contextContainer), - /* onJsError */ - [](facebook::jsi::Runtime&, const JsErrorHandler::ProcessedError& error) { - rn_gpui_log(3, error.message); - for (const auto& frame : error.stack) { - std::string entry = " at " + frame.methodName; - if (frame.file) - entry += " (" + *frame.file; - if (frame.lineNumber) - entry += ":" + std::to_string(*frame.lineNumber); - if (frame.column) - entry += ":" + std::to_string(*frame.column); - if (frame.file) - entry += ")"; - rn_gpui_log(3, entry); - } - }, - /* logger */ - [](const std::string& message, unsigned int level) { - rn_gpui_log(static_cast(level), message); - }, - /* devUIDelegate */ nullptr, - /* turboModuleProviders */ gpui_turbo_module_providers(), - /* logBoxSurfaceDelegate */ logBoxDelegate_, - /* animatedNodesManagerProvider */ animatedNodesManagerProvider_, - /* bindingsInstallFunc */ - [this](facebook::jsi::Runtime& runtime) { -#if LOOM_RENDERER - // A new instance has a new animation backend that has started nothing: - // an animation of the old one that resumed the frame source as it was - // torn down is not running any more. - if (loomHost_) { - loomHost_->animationFrameSource()->pause(); - } -#endif - runtime.global().setProperty( - runtime, "__gpuiScrollerLegacy", rn_gpui_scroller_legacy()); - // A native tree's batch of operations, from the second reconciler. - runtime.global().setProperty( - runtime, - "__gpuiNativeRootApply", - facebook::jsi::Function::createFromHostFunction( - runtime, - facebook::jsi::PropNameID::forAscii( - runtime, "__gpuiNativeRootApply"), - 2, - [](facebook::jsi::Runtime& rt, - const facebook::jsi::Value&, - const facebook::jsi::Value* args, - size_t count) -> facebook::jsi::Value { - if (count >= 2 && args[0].isNumber() && args[1].isString()) { - rn_gpui_native_root_ops( - static_cast(args[0].asNumber()), - args[1].asString(rt).utf8(rt)); - } - return facebook::jsi::Value::undefined(); - })); - // `_requireNodeLibrary` must exist before the app bundle runs, and a - // reload creates a new runtime, so it is installed here rather than at - // module-registration time. ReactInstance installs the - // RuntimeSchedulerBinding just before calling this, which is the same - // CallInvoker the TurboModules get; a fresh one per runtime is correct, - // because the engine's host callbacks belong to that runtime. - auto binding = - facebook::react::RuntimeSchedulerBinding::getBinding(runtime); - if (!binding) { - return; - } - rngpui::installNodeAddons( - runtime, - std::make_shared( - binding->getRuntimeScheduler())); - }, -#if LOOM_RENDERER - /* animationChoreographer */ loomHost_->animationFrameSource() -#else - /* animationChoreographer */ nullptr -#endif - ); - activeGpuiHost.store(this, std::memory_order_release); -#if defined(RN_GPUI_ACCESSIBILITY_SETTINGS) - rn_gpui_start_accessibility_observing(); -#endif -} - -GpuiHost::~GpuiHost() { -#if defined(RN_GPUI_ACCESSIBILITY_SETTINGS) - rn_gpui_stop_accessibility_observing(); -#endif - reactHost_->stopAllSurfaces(); - for (const auto& listener : eventListeners_) { - reactHost_->runOnScheduler([&listener](Scheduler& scheduler) { - scheduler.removeEventListener(listener); - }); - } - auto* expected = this; - activeGpuiHost.compare_exchange_strong( - expected, nullptr, std::memory_order_acq_rel); -} - -std::shared_ptr GpuiHost::ui_manager() const { - std::shared_ptr result; - reactHost_->runOnScheduler( - [&result](Scheduler& scheduler) { result = scheduler.getUIManager(); }); - return result; -} - -void GpuiHost::synchronously_update_props( - int32_t tag, - const folly::dynamic& props) const { - mountingManager_->synchronouslyUpdateViewOnUIThread(tag, props); -} - -void GpuiHost::add_event_listener( - std::shared_ptr listener) { - reactHost_->runOnScheduler([&listener](Scheduler& scheduler) { - scheduler.addEventListener(listener); - }); - eventListeners_.push_back(std::move(listener)); -} - -std::shared_ptr get_gpui_ui_manager() { - auto* host = activeGpuiHost.load(std::memory_order_acquire); - return host ? host->ui_manager() : nullptr; -} - -void gpui_synchronously_update_props(int32_t tag, const folly::dynamic& props) { - if (auto* host = activeGpuiHost.load(std::memory_order_acquire)) { - host->synchronously_update_props(tag, props); - } -} - -void register_gpui_event_listener( - std::shared_ptr listener) { - if (auto* host = activeGpuiHost.load(std::memory_order_acquire)) { - host->add_event_listener(std::move(listener)); - } -} - -bool GpuiHost::load_script(rust::Str bundlePath, rust::Str sourceUrl) { - scriptLoaded_ = - reactHost_->loadScript(std::string(bundlePath), std::string(sourceUrl)); - return scriptLoaded_; -} - -namespace { -/// Fabric asserts on an undefined constraint, so every bound is a real number -/// and the pair is ordered: a caller that asks for a range wider than its -/// content still gets a valid constraint. -facebook::react::LayoutConstraints constraintsFrom( - float minWidth, - float minHeight, - float maxWidth, - float maxHeight, - float /*scale*/) { - facebook::react::LayoutConstraints constraints; - const float minW = std::max(0.f, minWidth); - const float minH = std::max(0.f, minHeight); - const float maxW = std::max(minW, maxWidth); - const float maxH = std::max(minH, maxHeight); - constraints.minimumSize = {minW, minH}; - constraints.maximumSize = {maxW, maxH}; - constraints.layoutDirection = surfaceLayoutDirection(); - return constraints; -} -} // namespace - -void GpuiHost::start_surface( - int32_t id, - rust::Str module, - float w, - float h, - float scale) { - start_surface_with_props(id, module, rust::Str("{}"), w, h, scale); -} - -void GpuiHost::start_surface_with_props( - int32_t id, - rust::Str module, - rust::Str propsJson, - float w, - float h, - float scale) { - LayoutConstraints constraints; - constraints.minimumSize = {w, h}; - constraints.maximumSize = {w, h}; - // SurfaceHandler asserts on Undefined. - constraints.layoutDirection = surfaceLayoutDirection(); - LayoutContext context; - context.pointScaleFactor = scale; - context.fontSizeMultiplier = DeviceInfoModule::fontScale(); - context.swapLeftAndRightInRTL = rngpui::rn_gpui_swap_left_and_right_in_rtl(); - if (id == kAppSurfaceId) { - surfaceWidth_ = w; - surfaceHeight_ = h; - surfaceScale_ = scale; - mountingManager_->setWindowSize(w, h); - } - folly::dynamic initialProps = folly::dynamic::object(); - const auto props = std::string(propsJson); - if (!props.empty()) { - auto parsed = folly::parseJson(props); - if (!parsed.isObject()) - throw std::invalid_argument("Surface initialProps must be an object"); - initialProps = std::move(parsed); - } - if (id == kAppSurfaceId && std::getenv("RN_GPUI_TEST_DRIVER")) { - if (const char* value = std::getenv("RN_GPUI_TEST_INITIAL_PROPS")) { - initialProps = folly::parseJson(value); - if (!initialProps.isObject()) - throw std::invalid_argument("Test initialProps must be an object"); - } - } -#if LOOM_RENDERER - setLoomSurfaceConstraints(*loomHost_, id, constraints, scale); -#endif - reactHost_->startSurface( - id, std::string(module), initialProps, constraints, context); -} - -void GpuiHost::start_surface_with_constraints( - int32_t id, - rust::Str module, - rust::Str propsJson, - float minWidth, - float minHeight, - float maxWidth, - float maxHeight, - float scale) { - LayoutConstraints constraints = - constraintsFrom(minWidth, minHeight, maxWidth, maxHeight, scale); - LayoutContext context; - context.pointScaleFactor = scale; - context.fontSizeMultiplier = DeviceInfoModule::fontScale(); - context.swapLeftAndRightInRTL = rngpui::rn_gpui_swap_left_and_right_in_rtl(); - if (id == kAppSurfaceId) { - surfaceWidth_ = maxWidth; - surfaceHeight_ = maxHeight; - surfaceScale_ = scale; - mountingManager_->setWindowSize(maxWidth, maxHeight); - } - folly::dynamic initialProps = folly::dynamic::object(); - const auto props = std::string(propsJson); - if (!props.empty()) { - auto parsed = folly::parseJson(props); - if (!parsed.isObject()) - throw std::invalid_argument("Surface initialProps must be an object"); - initialProps = std::move(parsed); - } -#if LOOM_RENDERER - setLoomSurfaceConstraints(*loomHost_, id, constraints, scale); -#endif - reactHost_->startSurface( - id, std::string(module), initialProps, constraints, context); -} - -void GpuiHost::set_surface_constraints( - int32_t id, - float minWidth, - float minHeight, - float maxWidth, - float maxHeight, - float scale) { - LayoutConstraints constraints = - constraintsFrom(minWidth, minHeight, maxWidth, maxHeight, scale); - LayoutContext context; - context.pointScaleFactor = scale; - context.fontSizeMultiplier = DeviceInfoModule::fontScale(); - context.swapLeftAndRightInRTL = rngpui::rn_gpui_swap_left_and_right_in_rtl(); - if (id == kAppSurfaceId) { - surfaceWidth_ = maxWidth; - surfaceHeight_ = maxHeight; - surfaceScale_ = scale; - mountingManager_->setWindowSize(maxWidth, maxHeight); - } -#if LOOM_RENDERER - setLoomSurfaceConstraints(*loomHost_, id, constraints, scale); -#endif - reactHost_->setSurfaceConstraints(id, constraints, context); -} - -void GpuiHost::set_surface_size(int32_t id, float w, float h, float scale) { - LayoutConstraints constraints; - constraints.minimumSize = {w, h}; - constraints.maximumSize = {w, h}; - constraints.layoutDirection = surfaceLayoutDirection(); - LayoutContext context; - context.pointScaleFactor = scale; - context.fontSizeMultiplier = DeviceInfoModule::fontScale(); - context.swapLeftAndRightInRTL = rngpui::rn_gpui_swap_left_and_right_in_rtl(); - if (id == kAppSurfaceId) { - surfaceWidth_ = w; - surfaceHeight_ = h; - surfaceScale_ = scale; - mountingManager_->setWindowSize(w, h); - } -#if LOOM_RENDERER - setLoomSurfaceConstraints(*loomHost_, id, constraints, scale); -#endif - reactHost_->setSurfaceConstraints(id, constraints, context); - if (id == kAppSurfaceId) { - set_window_metrics(w, h, scale); - } -} - -void GpuiHost::set_window_top_inset(float top) { - mountingManager_->setWindowTopInset(top); -} - -void GpuiHost::set_window_metrics(float w, float h, float scale) { - if (!DeviceInfoModule::setWindowMetrics(w, h, scale)) { - return; - } - for (const auto& observer : gpuiExtensionHooks().windowMetricsObservers) { - observer(); - } - if (!scriptLoaded_) { - return; - } - emitDimensions(); -} - -void GpuiHost::emitDimensions() const { - const auto windowSize = DeviceInfoModule::windowSize(); - const auto screenSize = DeviceInfoModule::screenSize(); - const double scale = surfaceScale_; - const double fontScale = DeviceInfoModule::fontScale(); - const folly::dynamic window = - folly::dynamic::object("width", windowSize.width)( - "height", windowSize.height)("scale", scale)("fontScale", fontScale); - const folly::dynamic screen = - folly::dynamic::object("width", screenSize.width)( - "height", screenSize.height)("scale", scale)("fontScale", fontScale); - folly::dynamic payload = - folly::dynamic::object("window", window)("screen", screen); - reactHost_->emitDeviceEvent( - folly::dynamic::array("didUpdateDimensions", std::move(payload))); -} - -void GpuiHost::set_display_metrics( - float screenWidth, - float screenHeight, - float fontScale) { - const bool fontScaleChanged = DeviceInfoModule::fontScale() != fontScale; - if (!DeviceInfoModule::setDisplayMetrics( - screenWidth, screenHeight, fontScale)) { - return; - } - for (const auto& observer : gpuiExtensionHooks().windowMetricsObservers) { - observer(); - } - if (!scriptLoaded_) { - return; - } - if (fontScaleChanged && surfaceWidth_ > 0.f) { - set_surface_size( - kAppSurfaceId, surfaceWidth_, surfaceHeight_, surfaceScale_); - } - emitDimensions(); -} - -void GpuiHost::emit_device_event(rust::Str eventName) const { - if (!scriptLoaded_) - return; - const auto timestamp = - std::chrono::duration( - std::chrono::steady_clock::now().time_since_epoch()) - .count(); - reactHost_->emitDeviceEvent(folly::dynamic::array( - std::string(eventName), folly::dynamic::object("timeStamp", timestamp))); -} - -void GpuiHost::emit_device_event_bool(rust::Str eventName, bool value) const { - if (scriptLoaded_) { - reactHost_->emitDeviceEvent( - folly::dynamic::array(std::string(eventName), value)); - } -} - -void GpuiHost::emit_device_event_json( - rust::Str eventName, - rust::Str payloadJson) const { - if (!scriptLoaded_) - return; - folly::dynamic payload = folly::dynamic::object(); - try { - auto parsed = folly::parseJson(std::string(payloadJson)); - if (parsed.isObject()) { - payload = std::move(parsed); - } - } catch (const std::exception& error) { - LOG(WARNING) << "emit_device_event_json(" << std::string(eventName) - << "): invalid payload: " << error.what(); - } - reactHost_->emitDeviceEvent( - folly::dynamic::array(std::string(eventName), std::move(payload))); -} - -void GpuiHost::set_app_state(rust::Str state) { - const std::string next(state); - const std::string previous = AppStateModule::state(); - if (next == previous) { - return; - } - AppStateModule::setState(next); - if (!scriptLoaded_) { - return; - } - reactHost_->emitDeviceEvent(folly::dynamic::array( - "appStateDidChange", folly::dynamic::object("app_state", next))); - if ((next == "active") != (previous == "active")) { - reactHost_->emitDeviceEvent( - folly::dynamic::array("appStateFocusChange", next == "active")); - } -} - -void GpuiHost::emit_memory_warning() const { - if (scriptLoaded_) { - reactHost_->emitDeviceEvent(folly::dynamic::array("memoryWarning")); - } -} - -void GpuiHost::emit_accessibility_setting_event( - const std::string& eventName, - bool enabled) const { - if (scriptLoaded_) { - reactHost_->emitDeviceEvent(folly::dynamic::array(eventName, enabled)); - } -} - -#if defined(RN_GPUI_ACCESSIBILITY_SETTINGS) -extern "C" void rn_gpui_accessibility_setting_changed( - const char* eventName, - bool enabled) { - auto* host = activeGpuiHost.load(std::memory_order_acquire); - if (host != nullptr && eventName != nullptr) { - host->emit_accessibility_setting_event(eventName, enabled); - } -} -#endif - -void GpuiHost::set_system_appearance(rust::Str appearance) { - bool shouldNotify = false; - bool effectiveChanged = false; - std::string nextAppearance; - { - std::lock_guard lock(appearanceMutex); - nextAppearance = std::string(appearance) == "dark" ? "dark" : "light"; - if (systemAppearance == nextAppearance) - return; - systemAppearance = nextAppearance; - effectiveChanged = !appearanceOverride.has_value(); - shouldNotify = effectiveChanged && scriptLoaded_; - } - if (effectiveChanged) { - for (const auto& observer : gpuiExtensionHooks().colorSchemeObservers) { - observer(nextAppearance); - } - } - if (shouldNotify) { - folly::dynamic preferences = - folly::dynamic::object("colorScheme", nextAppearance); - reactHost_->emitDeviceEvent( - folly::dynamic::array("appearanceChanged", std::move(preferences))); - } -} - -void GpuiHost::open_debugger() const { - reactHost_->openDebugger(); -} - -namespace { -// Static, so a probe that outlives a reload or the host touches nothing that -// has been destroyed. -std::atomic jsHeapBytes{0}; - -/// The engine's own figure for "bytes allocated on the JS heap". JSI leaves -/// the keys of `getHeapInfo` to each engine, which prefix them with their -/// name, so this goes by the suffix instead of naming an engine. -uint64_t sampleJsHeapBytes(facebook::jsi::Runtime& runtime) { - uint64_t allocated = 0; - uint64_t size = 0; - try { - for (const auto& [key, value] : - runtime.instrumentation().getHeapInfo(false)) { - if (value <= 0) { - continue; - } - if (key.ends_with("allocatedBytes")) { - allocated = static_cast(value); - } else if (key.ends_with("heapSize")) { - size = static_cast(value); - } - } - } catch (...) { - } - return allocated != 0 ? allocated : size; -} -} // namespace - -uint64_t GpuiHost::js_frame_probe() const { - static std::atomic completed{0}; - static std::atomic pending{false}; - if (scriptLoaded_ && !reactHost_->isReloading() && !pending.exchange(true)) { - reactHost_->runOnRuntimeScheduler([](facebook::jsi::Runtime& runtime) { - static std::chrono::steady_clock::time_point sampledAt{}; - const auto now = std::chrono::steady_clock::now(); - if (now - sampledAt >= std::chrono::milliseconds(500)) { - sampledAt = now; - jsHeapBytes.store( - sampleJsHeapBytes(runtime), std::memory_order_relaxed); - } - completed.fetch_add(1, std::memory_order_relaxed); - pending.store(false); - }); - } - return completed.load(std::memory_order_relaxed); -} - -uint64_t GpuiHost::js_heap_bytes() const { - return jsHeapBytes.load(std::memory_order_relaxed); -} - -void GpuiHost::stop_surface(int32_t id) { -#if LOOM_RENDERER - LoomBinding::releaseSurface(id); -#endif - reactHost_->stopSurface(id); - // Fabric emits no Delete mutations for a surface that is torn down, so the - // store has to drop it explicitly. - rn_gpui_on_surface_stopped(id); -} - -void GpuiHost::request_reload() { - reactHost_->requestReload(); -} -bool GpuiHost::set_dev_server(rust::Str host, uint32_t port) { - return reactHost_->setDevServer(std::string(host), port); -} -rust::String GpuiHost::dev_server_address() const { - return rust::String(reactHost_->devServerAddress()); -} -bool GpuiHost::reload_in_progress() const { - return reactHost_->isReloading(); -} -uint64_t GpuiHost::instance_generation() const { - return reactHost_->instanceGeneration(); -} -extern "C" void rn_gpui_request_reload() { - if (auto* host = activeGpuiHost.load()) - host->request_reload(); -} -extern "C" bool rn_gpui_reload_in_progress() { - if (auto* host = activeGpuiHost.load()) - return host->reload_in_progress(); - return false; -} -extern "C" uint64_t rn_gpui_instance_generation() { - if (auto* host = activeGpuiHost.load()) - return host->instance_generation(); - return 0; -} - -void GpuiHost::start_log_box_surface() { - LayoutConstraints constraints; - constraints.minimumSize = {surfaceWidth_, surfaceHeight_}; - constraints.maximumSize = {surfaceWidth_, surfaceHeight_}; - constraints.layoutDirection = surfaceLayoutDirection(); - LayoutContext context; - context.pointScaleFactor = surfaceScale_; - context.fontSizeMultiplier = DeviceInfoModule::fontScale(); - context.swapLeftAndRightInRTL = rngpui::rn_gpui_swap_left_and_right_in_rtl(); -#if LOOM_RENDERER - setLoomSurfaceConstraints( - *loomHost_, kLogBoxSurfaceId, constraints, surfaceScale_); -#endif - reactHost_->startSurface( - kLogBoxSurfaceId, - "LogBox", - folly::dynamic::object(), - constraints, - context); -} - -/// Stop the LogBox surface again: `hide()` is what keeps a closed -/// LogBox from covering the app surface with an empty full-size overlay. -void GpuiHost::stop_log_box_surface() { -#if LOOM_RENDERER - LoomBinding::releaseSurface(kLogBoxSurfaceId); -#endif - reactHost_->stopSurface(kLogBoxSurfaceId); - rn_gpui_on_surface_stopped(kLogBoxSurfaceId); -} - -void GpuiHost::on_render() const { - std::lock_guard lock(animatedFrameMutex_); - if (reactHost_->isReloading()) - return; - runLoopObserverManager_->onRender(); -} - -namespace { -void dispatchPointerTick( - GpuiMountingManager& mountingManager, - double eventTimestampMs) { - if (gpuiExtensionHooks().pointerObservers.empty()) - return; - extension::RawPointerEvent tick; - { - std::lock_guard lock(pointerEventMutex); - tick = lastPointerEvent; - } - tick.phase = 4; // native time tick for duration-based recognizers - tick.timestamp = eventTimestampMs; - for (const auto& observer : gpuiExtensionHooks().pointerObservers) { - for (const auto& recognized : observer(tick)) { - mountingManager.dispatchEvent( - recognized.targetTag, - recognized.eventType, - folly::parseJson(recognized.payloadJson)); - } - } -} -} // namespace - -void GpuiHost::on_pointer_frame(double eventTimestampMs) const { - std::lock_guard lock(animatedFrameMutex_); - if (reactHost_->isReloading()) - return; - dispatchPointerTick(*mountingManager_, eventTimestampMs); -} - -void GpuiHost::on_frame(double eventTimestampMs) const { - std::lock_guard lock(animatedFrameMutex_); - if (reactHost_->isReloading()) - return; - dispatchPointerTick(*mountingManager_, eventTimestampMs); -#if LOOM_RENDERER - // Animation props collected since the last frame reach the screen with it. - loomHost_->animationFrameSource()->tick(); - GpuiLoomHost::runOnUIThread([] { LoomBinding::flushAnimationFrames(); }); -#endif - on_render(); - if (const auto& frame = rngpui::gpuiModuleHooks().frame) { - const auto frameTimestampMs = - std::chrono::duration( - std::chrono::steady_clock::now().time_since_epoch()) - .count(); - frame(frameTimestampMs); - } - { - const auto frameTimestampMs = - std::chrono::duration( - std::chrono::steady_clock::now().time_since_epoch()) - .count(); - for (const auto& frame : rngpui::gpuiExtensionHooks().frameCallbacks) { - frame(frameTimestampMs); - } - } - std::function animationFrame; - { - std::lock_guard lock(animatedFrameMutex_); - animationFrame = animatedFrameCallback_; - } - if (animationFrame) { - if (gpuiDebugAnimationEnabled()) { - static std::atomic frames{0}; - const auto frame = ++frames; - if (frame % 60 == 0) { - LOG(INFO) << "[native-animated] GPUI delivered frame " << frame; - } - } - animationFrame(); - } -} - -void GpuiHost::dispatch_event( - int32_t tag, - rust::Str type, - rust::Str payloadJson) const { - mountingManager_->dispatchEvent( - tag, std::string(type), folly::parseJson(std::string(payloadJson))); -} - -void GpuiHost::dispatch_wheel(int32_t tag, uint64_t id, rust::Str payloadJson) - const { - mountingManager_->dispatchWheel( - tag, id, folly::parseJson(std::string(payloadJson))); -} - -void GpuiHost::dispatch_pointer_event( - rust::Str targetChainJson, - float x, - float y, - int32_t phase, - double timestamp) const { - extension::RawPointerEvent event; - try { - const auto targetChain = folly::parseJson(std::string(targetChainJson)); - if (!targetChain.isArray()) - return; - event.targetChain.reserve(targetChain.size()); - for (const auto& tag : targetChain) { - if (tag.isInt()) - event.targetChain.push_back(static_cast(tag.asInt())); - } - } catch (const std::exception& error) { - LOG(WARNING) << "[pointer] invalid target chain: " << error.what(); - return; - } - event.x = x; - event.y = y; - event.phase = phase; - event.timestamp = timestamp; - { - std::lock_guard lock(pointerEventMutex); - lastPointerEvent = event; - } - - for (const auto& observer : gpuiExtensionHooks().pointerObservers) { - for (const auto& recognized : observer(event)) { - mountingManager_->dispatchEvent( - recognized.targetTag, - recognized.eventType, - folly::parseJson(recognized.payloadJson)); - } - } -} - -void GpuiHost::set_scroll_offset(int32_t tag, float x, float y) const { -#if LOOM_RENDERER - loomHost_->setScrollOffset(tag, x, y); - return; -#endif - mountingManager_->setScrollOffset(tag, x, y); -} -} // namespace rngpui - -namespace rngpui { - -std::shared_ptr createTurboModule( - const std::string& name, - const std::shared_ptr& jsInvoker) { - static const auto providers = gpui_turbo_module_providers(); - for (const auto& provider : providers) { - if (auto module = provider(name, jsInvoker)) { - return module; - } - } - return nullptr; -} - -} // namespace rngpui - -namespace rngpui { - -std::string currentColorScheme() { - std::lock_guard lock(appearanceMutex); - return appearanceOverride.value_or(systemAppearance); -} - -double windowScale() { - return DeviceInfoModule::scale(); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHost.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHost.h deleted file mode 100644 index 5548cfe860..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHost.h +++ /dev/null @@ -1,176 +0,0 @@ -// cxx compares the exact signature of each member function, so `&str` -// parameters must be `rust::Str`; a `const std::string&` fails with -// "type mismatch at 1st parameter". -#pragma once - -#include "rust/cxx.h" - -#include -#include -#include -#include -#include -#include - -namespace facebook::react { -class ReactHost; -class RunLoopObserverManager; -class NativeAnimatedNodesManagerProvider; -class UIManager; -struct RawEvent; -using EventListener = std::function; -} // namespace facebook::react - -namespace folly { -// folly defines `dynamic` as a struct. MSVC puts the class/struct key into the -// mangled name (`V` vs `U`), so forward-declaring it as a class here mangles -// `gpui_synchronously_update_props` differently from the definition in -// GpuiHost.cpp, and the app-side archive fails to link with LNK2019. -struct dynamic; -} // namespace folly - -namespace rngpui { -class GpuiMountingManager; -class GpuiLoomHost; -class GpuiLogBoxSurfaceDelegate; - -constexpr int32_t kAppSurfaceId = 1; -constexpr int32_t kLogBoxSurfaceId = 2; -constexpr int32_t kAllSurfacesStopped = -1; - -class GpuiHost { - public: - GpuiHost( - rust::Str appId, - rust::Str devHost, - uint32_t devPort, - rust::Str jsEngine, - rust::Str jsThread, - bool devMode); - ~GpuiHost(); - - bool load_script(rust::Str bundlePath, rust::Str sourceUrl); - void start_surface( - int32_t surfaceId, - rust::Str moduleName, - float w, - float h, - float scale); - void start_surface_with_props( - int32_t surfaceId, - rust::Str moduleName, - rust::Str propsJson, - float w, - float h, - float scale); - void set_surface_size(int32_t surfaceId, float w, float h, float scale); - /// Starts a surface whose size is a range rather than a point: `FitContent`. - /// Fabric lays the root out against these constraints and the - /// resulting size comes back in every mount batch as `content_width` / - /// `content_height`. - void start_surface_with_constraints( - int32_t surfaceId, - rust::Str moduleName, - rust::Str propsJson, - float minWidth, - float minHeight, - float maxWidth, - float maxHeight, - float scale); - /// Changes an existing surface's constraints, which is what a resize of an - /// embedded surface does. - void set_surface_constraints( - int32_t surfaceId, - float minWidth, - float minHeight, - float maxWidth, - float maxHeight, - float scale); - void set_window_metrics(float w, float h, float scale); - void - set_display_metrics(float screenWidth, float screenHeight, float fontScale); - void emitDimensions() const; - void set_app_state(rust::Str state); - void emit_memory_warning() const; - void set_window_top_inset(float top); - void set_system_appearance(rust::Str appearance); - void stop_surface(int32_t surfaceId); - void open_debugger() const; - uint64_t js_frame_probe() const; - uint64_t js_heap_bytes() const; - void on_render() const; - void on_frame(double eventTimestampMs) const; - void on_pointer_frame(double eventTimestampMs) const; - void dispatch_event(int32_t tag, rust::Str type, rust::Str payloadJson) const; - void dispatch_wheel(int32_t tag, uint64_t id, rust::Str payloadJson) const; - void emit_device_event(rust::Str event_name) const; - void emit_device_event_bool(rust::Str event_name, bool value) const; - void emit_device_event_json(rust::Str event_name, rust::Str payload_json) - const; - void emit_accessibility_setting_event( - const std::string& event_name, - bool enabled) const; - void dispatch_pointer_event( - rust::Str targetChainJson, - float x, - float y, - int32_t phase, - double timestamp) const; - void set_scroll_offset(int32_t tag, float x, float y) const; - std::shared_ptr ui_manager() const; - void synchronously_update_props(int32_t tag, const folly::dynamic& props) - const; - void add_event_listener( - std::shared_ptr listener); - - void request_reload(); - bool set_dev_server(rust::Str host, uint32_t port); - rust::String dev_server_address() const; - bool reload_in_progress() const; - /// Counts the React instances created so far; see - /// `ReactHost::instanceGeneration`. - uint64_t instance_generation() const; - void start_log_box_surface(); - void stop_log_box_surface(); - - private: - std::shared_ptr mountingManager_; - /// The Loom renderer's host, when the app runs it. Declared before - /// `reactHost_` so the React instance goes first. - std::shared_ptr loomHost_; - std::shared_ptr - runLoopObserverManager_; - /// Passed to ReactHost as its `logBoxSurfaceDelegate`. Created - /// before the host because ReactHost takes it in its constructor. - std::shared_ptr logBoxDelegate_; - /// Passed to ReactHost as its `animatedNodesManagerProvider`. It - /// is what makes `AnimatedModule` load; without it LogBox's inspector throws - /// "Native animated module is not available" and no red box renders. - std::shared_ptr - animatedNodesManagerProvider_; - mutable std::recursive_mutex animatedFrameMutex_; - mutable std::function animatedFrameCallback_; - std::unique_ptr reactHost_; - std::vector> - eventListeners_; - float surfaceWidth_{0.}; - float surfaceHeight_{0.}; - float surfaceScale_{1.}; - bool scriptLoaded_{false}; -}; - -std::unique_ptr new_gpui_host( - rust::Str appId, - rust::Str devHost, - uint32_t devPort, - rust::Str jsEngine, - rust::Str jsThread, - bool devMode); -std::shared_ptr get_gpui_ui_manager(); -void gpui_synchronously_update_props(int32_t tag, const folly::dynamic& props); -void register_gpui_event_listener( - std::shared_ptr listener); -/// Runs the task a module posted with `rngpui::dispatchMain`. Called on the -/// GPUI main thread. -void rn_gpui_run_main_task(uint64_t id); -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHostComponent.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHostComponent.cpp deleted file mode 100644 index e00e178af5..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHostComponent.cpp +++ /dev/null @@ -1,218 +0,0 @@ - -#include "GpuiHostComponentsCpp.h" - -#include "rn-gpui-sys/src/lib.rs.h" // cxx bridge - -#include -#include - -#include - -#include -#include - -namespace rngpui { -namespace { -/// What is registered while the app starts. Written by the generated files' -/// registration functions, then frozen into `FrozenTable` and never written -/// again. -struct PendingEntries { - std::mutex mutex; - std::vector entries; -}; - -PendingEntries& pending() { - static PendingEntries pending; - return pending; -} - -/// Set by the first registration, before anything can ask for a component, so a -/// hot path skips everything below with one relaxed load. -std::atomic& anyFlag() { - static std::atomic flag{false}; - return flag; -} - -/// The frozen lookup: entries sorted by handle, found by binary search. A few -/// entries, one cache line or two, no hashing and no lock. -struct FrozenTable { - std::vector entries; - std::vector> byHandle; -}; - -std::atomic& lookupCount() { - static std::atomic count{0}; - return count; -} - -std::atomic& frozenTable() { - static std::atomic table{nullptr}; - return table; -} -} // namespace - -void registerHostComponentEntry(const HostComponentEntry& entry) { - if (frozenTable().load(std::memory_order_acquire) != nullptr) { - LOG(ERROR) << "[host-component] " << entry.name - << " registered after the registry froze; ignored"; - return; - } - auto& reg = pending(); - std::lock_guard lock(reg.mutex); - if (reg.entries.size() <= entry.index) { - reg.entries.resize(entry.index + 1); - } - reg.entries[entry.index] = entry; - anyFlag().store(true, std::memory_order_release); -} - -bool anyHostComponents() { - return anyFlag().load(std::memory_order_relaxed); -} - -uint64_t hostEntryLookups() { - return lookupCount().load(std::memory_order_relaxed); -} - -void resetHostEntryLookups() { - lookupCount().store(0, std::memory_order_relaxed); -} - -const HostComponentEntry* hostComponentEntry( - facebook::react::ComponentHandle handle) { - lookupCount().fetch_add(1, std::memory_order_relaxed); - const FrozenTable* table = frozenTable().load(std::memory_order_acquire); - if (table == nullptr) { - return nullptr; - } - const auto& keys = table->byHandle; - auto found = std::lower_bound( - keys.begin(), keys.end(), handle, [](const auto& key, auto value) { - return key.first < value; - }); - if (found == keys.end() || found->first != handle) { - return nullptr; - } - return &table->entries[found->second]; -} - -void registerHostComponentDescriptors( - facebook::react::ComponentDescriptorProviderRegistry& registry) { - if (frozenTable().load(std::memory_order_acquire) != nullptr) { - return; - } - auto table = std::make_unique(); - { - auto& reg = pending(); - std::lock_guard lock(reg.mutex); - table->entries = reg.entries; - } - for (uint32_t index = 0; index < table->entries.size(); ++index) { - const auto& entry = table->entries[index]; - if (entry.provider == nullptr) { - continue; - } - registry.add(entry.provider()); - table->byHandle.emplace_back(entry.handle, index); - } - std::sort(table->byHandle.begin(), table->byHandle.end()); - frozenTable().store(table.release(), std::memory_order_release); -} - -void releaseHostPropsHandle(std::size_t handle) { - delete reinterpret_cast(handle); -} - -void releaseHostEmitterHandle(std::size_t handle) { - delete reinterpret_cast(handle); -} - -uint32_t hostComponentIndex(facebook::react::ComponentHandle handle) { - const auto* entry = hostComponentEntry(handle); - return entry ? entry->index : 0; -} - -bool hostMeasure( - uint32_t index, - const void* props, - float minWidth, - float minHeight, - float maxWidth, - float maxHeight, - float* width, - float* height) { - const auto result = rn_gpui_host_measure( - index, - reinterpret_cast(props), - minWidth, - minHeight, - maxWidth, - maxHeight); - if (!result.measured) { - return false; - } - *width = result.width; - *height = result.height; - return true; -} - -void dispatchHostCommand( - int32_t tag, - uint32_t command, - std::vector&& args) { - rust::Vec converted; - converted.reserve(args.size()); - for (auto& value : args) { - HostCommandArg arg; - arg.kind = static_cast(value.kind); - arg.number = value.number; - arg.text = rust::String(value.text); - for (double number : value.numbers) { - arg.numbers.push_back(number); - } - for (const auto& text : value.texts) { - arg.texts.push_back(rust::String(text)); - } - converted.push_back(std::move(arg)); - } - rn_gpui_on_host_command(tag, command, std::move(converted)); -} -} // namespace rngpui - -namespace { -using ImageSource = facebook::react::ImageSource; - -RnGpuiStr borrow(const std::string& text) { - return RnGpuiStr{reinterpret_cast(text.data()), text.size()}; -} -} // namespace - -extern "C" { -RnGpuiStr rn_gpui_image_source_uri(const void* image) { - return borrow(static_cast(image)->uri); -} - -RnGpuiStr rn_gpui_image_source_bundle(const void* image) { - return borrow(static_cast(image)->bundle); -} - -float rn_gpui_image_source_scale(const void* image) { - return static_cast(image)->scale; -} - -float rn_gpui_image_source_width(const void* image) { - return static_cast(image)->size.width; -} - -float rn_gpui_image_source_height(const void* image) { - return static_cast(image)->size.height; -} - -RnGpuiStr rn_gpui_image_source_body(const void* image) { - return borrow(static_cast(image)->body); -} - -RnGpuiStr rn_gpui_image_source_method(const void* image) { - return borrow(static_cast(image)->method); -} -} // extern "C" diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHostComponent.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHostComponent.h deleted file mode 100644 index cb460d0e7b..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHostComponent.h +++ /dev/null @@ -1,64 +0,0 @@ -#pragma once - -#include "rust/cxx.h" - -#include -#include -#include - -namespace rngpui { -class GpuiMountingManager; - -/// Names the mounting manager host component reports are pushed through. -void setHostComponentStateManager(std::weak_ptr manager); - -/// Pushes the size a host component measured into its shadow node's state, -/// which is what Yoga's measure function reads, and asks for the commit that -/// re-measures it. A size the state already holds is dropped there. -void reportHostComponentSize(int32_t tag, float width, float height); - -/// Pushes the size a native root laid its tree out at into its shadow node's -/// state, where `adopt` applies it to Yoga's style, and asks for the commit -/// that lays the siblings out again. `minWidth` and `width` count only with -/// `hasWidth`. Whether the node is known; a size reported before its mount is -/// not kept. -bool reportNativeRootSize( - int32_t tag, - float height, - bool hasWidth, - float width, - float minWidth); - -/// Pushes the size the native layout gave a slot's placeholder into the slot's -/// shadow node's state, where `adopt` makes it the content's width (and, with -/// `hasHeight`, height). Whether the node is known. -bool reportNativeSlotSize( - int32_t tag, - bool hasWidth, - float width, - bool hasHeight, - float height); - -/// Pushes the insets a container reported for its chrome into its shadow node's -/// state, where `adopt` turns them into Yoga padding around the React children. -/// Insets the state already holds are dropped there. -void reportHostComponentInsets( - int32_t tag, - float top, - float right, - float bottom, - float left); - -/// Releases a props handle a mount op gave Rust. A handle is a heap -/// `shared_ptr` holder, so releasing it drops one reference. -void releaseHostPropsHandle(std::size_t handle); - -/// Releases an event emitter handle a `Create` op gave Rust. -void releaseHostEmitterHandle(std::size_t handle); - -/// How many times the registry was asked for a component, for the test driver's -/// counters. Counted only on the path an app with host components takes: an app -/// without any never reaches the lookup. -uint64_t hostEntryLookups(); -void resetHostEntryLookups(); -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHostComponentsCpp.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHostComponentsCpp.h deleted file mode 100644 index 49618686fc..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHostComponentsCpp.h +++ /dev/null @@ -1,321 +0,0 @@ -#pragma once - -#include "GpuiHostComponent.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include - -namespace facebook::react { -class ComponentDescriptorProviderRegistry; -} - -/// A borrowed C++ `std::string`: bytes and an explicit length. -struct RnGpuiStr { - const uint8_t* data; - size_t len; -}; - -/// A borrowed C++ `std::vector` of plain data. -struct RnGpuiSlice { - const void* data; - size_t len; -}; - -/// A C++ `SharedColor`: `present` is false when React left the color unset. -struct RnGpuiOptU32 { - uint32_t value; - bool present; -}; - -static_assert(sizeof(RnGpuiStr) == 2 * sizeof(void*)); -static_assert(offsetof(RnGpuiStr, data) == 0); -static_assert(offsetof(RnGpuiStr, len) == sizeof(void*)); -static_assert(sizeof(RnGpuiSlice) == 2 * sizeof(void*)); -static_assert(offsetof(RnGpuiSlice, data) == 0); -static_assert(offsetof(RnGpuiSlice, len) == sizeof(void*)); -static_assert(sizeof(RnGpuiOptU32) == 8); -static_assert(offsetof(RnGpuiOptU32, value) == 0); -static_assert(offsetof(RnGpuiOptU32, present) == 4); - -namespace rngpui { -/// The state every host component keeps: its intrinsic size, and the insets a -/// container reports for its chrome. -struct GpuiHostStateData { - float width = 0.f; - float height = 0.f; - /// Whether a size was ever reported. A component that never measures keeps - /// Yoga's own sizing. - bool measured = false; - /// Padding the component's chrome needs around React's children, reported - /// by a container host component. - float insetLeft = 0.f; - float insetTop = 0.f; - float insetRight = 0.f; - float insetBottom = 0.f; -}; - -/// What a props handle owns: one reference to the node's Fabric props. -struct HostPropsHandle { - std::shared_ptr props; -}; - -/// What an emitter handle owns: one reference to the node's event emitter. -struct HostEmitterHandle { - std::shared_ptr emitter; -}; - -/// The handle for `props`, as the address Rust owns. Zero for a null pointer. -inline std::size_t makeHostPropsHandle( - const std::shared_ptr& props) { - return props ? reinterpret_cast(new HostPropsHandle{props}) : 0; -} - -/// The handle for `emitter`, as the address Rust owns. Zero for a null pointer. -inline std::size_t makeHostEmitterHandle( - const std::shared_ptr& emitter) { - return emitter ? reinterpret_cast(new HostEmitterHandle{emitter}) - : 0; -} - -/// The props a generated accessor reads: the handle's props, as the component's -/// own generated props class. The handle was made from a node of that component -/// (the registry index on the op says so), so the downcast is exact. -template -inline const P& hostProps(const void* handle) { - return static_cast( - *static_cast(handle)->props); -} - -/// The emitter a generated event shim dispatches through. -template -inline const E& hostEmitter(const void* handle) { - return static_cast( - *static_cast(handle)->emitter); -} - -/// One command argument, already validated against the spec by the generated -/// dispatcher. Mirrors `HostCommandArg` in the bridge, without cxx types, so -/// the generated file does not need the bridge header. -struct HostCommandValue { - enum Kind : uint8_t { - Number = 0, - Bool = 1, - String = 2, - Numbers = 3, - Bools = 4, - Strings = 5, - }; - Kind kind = Number; - double number = 0; - std::string text; - std::vector numbers; - std::vector texts; -}; - -/// Sends a validated command to the Rust host component of node `tag`, as the -/// `command`-th entry of its spec's `COMMANDS`. -void dispatchHostCommand( - int32_t tag, - uint32_t command, - std::vector&& args); - -/// The registry index of the component with this handle. -uint32_t hostComponentIndex(facebook::react::ComponentHandle handle); - -/// Asks the Rust half to measure a node under a constraint, on the layout -/// thread. `props` is the address of a `HostPropsHandle`. Returns whether the -/// component measures; the size is in `width` and `height`. -bool hostMeasure( - uint32_t index, - const void* props, - float minWidth, - float minHeight, - float maxWidth, - float maxHeight, - float* width, - float* height); - -/// A leaf host component: its measure function asks the component for the size -/// under the constraint, or returns the size in its state, when it declares -/// itself `measured`. -template -class GpuiHostLeafShadowNode final - : public facebook::react:: - ConcreteViewShadowNode { - using Base = - facebook::react::ConcreteViewShadowNode; - - public: - static facebook::react::ShadowNodeTraits BaseTraits() { - auto traits = Base::BaseTraits(); - traits.set(facebook::react::ShadowNodeTraits::Trait::LeafYogaNode); - if constexpr (Measured) { - traits.set(facebook::react::ShadowNodeTraits::Trait::MeasurableYogaNode); - } - return traits; - } - - GpuiHostLeafShadowNode( - const facebook::react::ShadowNodeFragment& fragment, - const facebook::react::ShadowNodeFamily::Shared& family, - facebook::react::ShadowNodeTraits traits) - : Base(fragment, family, traits) { - initialize(); - } - - GpuiHostLeafShadowNode( - const facebook::react::ShadowNode& sourceShadowNode, - const facebook::react::ShadowNodeFragment& fragment) - : Base(sourceShadowNode, fragment) { - initialize(); - } - - /// The size the node's state holds, clamped to the constraints. - facebook::react::Size measureContent( - const facebook::react::LayoutContext& /*layoutContext*/, - const facebook::react::LayoutConstraints& layoutConstraints) - const override { - if constexpr (Measured) { - HostPropsHandle propsHandle{this->getProps()}; - float measuredWidth = 0.f; - float measuredHeight = 0.f; - if (hostMeasure( - hostComponentIndex(this->getComponentHandle()), - &propsHandle, - layoutConstraints.minimumSize.width, - layoutConstraints.minimumSize.height, - layoutConstraints.maximumSize.width, - layoutConstraints.maximumSize.height, - &measuredWidth, - &measuredHeight)) { - return facebook::react::Size{measuredWidth, measuredHeight}; - } - } - const auto& stateData = this->getStateData(); - float width = stateData.width; - float height = stateData.height; - if (!stateData.measured) { - width = layoutConstraints.minimumSize.width; - height = layoutConstraints.minimumSize.height; - } - width = std::clamp( - width, - layoutConstraints.minimumSize.width, - layoutConstraints.maximumSize.width); - height = std::clamp( - height, - layoutConstraints.minimumSize.height, - layoutConstraints.maximumSize.height); - return facebook::react::Size{width, height}; - } - - private: - void initialize() noexcept { - if constexpr (Measured) { - this->enableMeasurement(); - } - } -}; - -/// A container host component: it draws chrome *around* React children. -template -class GpuiHostContainerShadowNode final - : public facebook::react:: - ConcreteViewShadowNode { - public: - using facebook::react::ConcreteViewShadowNode:: - ConcreteViewShadowNode; -}; - -/// The descriptor of a container: applies the insets the component reported for -/// its chrome as real Yoga padding, so its React children are laid out inside -/// it. -template -class GpuiHostContainerDescriptor final - : public facebook::react::ConcreteComponentDescriptor { - public: - using facebook::react::ConcreteComponentDescriptor< - ShadowNodeT>::ConcreteComponentDescriptor; - - void adopt(facebook::react::ShadowNode& shadowNode) const override { - auto& layoutable = - static_cast(shadowNode); - const auto& state = - static_cast&>( - *shadowNode.getState()); - const auto& data = state.getData(); - layoutable.setPadding(facebook::react::RectangleEdges{ - data.insetLeft, data.insetTop, data.insetRight, data.insetBottom}); - facebook::react::ConcreteComponentDescriptor::adopt( - shadowNode); - } -}; - -/// What the generated C++ file knows about one component, registered at -/// startup. -struct HostComponentEntry { - uint32_t index = 0; - const char* name = ""; - /// `Name::Handle()` of the component's shadow node: what a `ShadowView` - /// carries, and the key of the table lookup. - facebook::react::ComponentHandle handle = 0; - bool measured = false; - bool container = false; - bool nativeSurface = false; - /// Builds the Fabric descriptor provider for the component. - facebook::react::ComponentDescriptorProvider (*provider)() = nullptr; - /// Compares two props objects of this component and sets one bit per changed - /// prop in `words`, which holds `changeWords` zeroed words. - void (*changed)( - const facebook::react::Props& before, - const facebook::react::Props& after, - uint64_t* words) = nullptr; - uint32_t changeWords = 1; - /// Validates a command's arguments against the spec and dispatches it. - /// Returns whether the name is one of the spec's commands. - bool (*command)( - int32_t tag, - const std::string& name, - const folly::dynamic& args) = nullptr; -}; - -/// Registers a component. Called from the generated file's -/// `rn_gpui_register_host_components_()`, before the first surface -/// starts. Registering after the registry froze is an error. -void registerHostComponentEntry(const HostComponentEntry& entry); - -/// Whether any host component was ever registered, as one relaxed load. Every -/// per-op check goes through this first, so an app with no host components pays -/// one predictable branch. -bool anyHostComponents(); - -/// The entry for the component `handle` names, or null. Lock-free: the table is -/// built once, when the descriptors are registered, and never changes. -const HostComponentEntry* hostComponentEntry( - facebook::react::ComponentHandle handle); - -/// Adds the descriptor provider of every registered component to Fabric's -/// provider registry, and freezes the registry. -void registerHostComponentDescriptors( - facebook::react::ComponentDescriptorProviderRegistry& registry); -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHttpBridge.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHttpBridge.cpp deleted file mode 100644 index 075c656eb3..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHttpBridge.cpp +++ /dev/null @@ -1,199 +0,0 @@ -#include "GpuiHttpBridge.h" - -#include - -// The completion callback's declaration, exactly as cxx emits it. -// -// Hand-writing it is what broke the Windows build: this file has to declare -// `rngpui::rn_gpui_http_complete` so the call below links, and a hand-written -// version without `noexcept` is a different function when MSVC sees both in one -// unity translation unit — C2382. macOS and Linux compile this file alone and -// never met the generated declaration, so only Windows refused. -#include "rn-gpui-sys/src/lib.rs.h" // rn_gpui_http_complete - -#include -#include -#include -#include -#include -#include -#include - -#include "GpuiHttpClient.h" - -namespace rngpui { - -namespace { - -/// The HTTP interface lives under `facebook::react`, like the rest of the C++ -/// runtime; the alias keeps the body readable. -namespace http = facebook::react::http; -using facebook::react::IHttpClient; - -/// One response, assembled from the client's callbacks. -struct Result { - int status{0}; - http::Headers headers; - std::string body; - std::string error; - bool done{false}; -}; - -/// The handle a cancelled request is found by. -struct InFlight { - std::atomic cancelled{false}; -}; - -std::mutex g_requestsMutex; -std::map> g_requests; - -/// "name: value" lines, newline separated. One string rather than a cxx struct: -/// header maps are small and this crosses the boundary rarely. -http::Headers parseHeaders(const std::string& text) { - http::Headers headers; - std::size_t start = 0; - while (start <= text.size() && !text.empty()) { - const auto end = text.find('\n', start); - const auto line = text.substr( - start, end == std::string::npos ? std::string::npos : end - start); - const auto colon = line.find(':'); - if (colon != std::string::npos) { - std::string value = line.substr(colon + 1); - while (!value.empty() && - (value.front() == ' ' || value.front() == '\t')) { - value.erase(value.begin()); - } - while (!value.empty() && (value.back() == '\r' || value.back() == ' ')) { - value.pop_back(); - } - // `Headers` is a vector of pairs, not a map: React Native preserves the - // order the server sent, and a map would sort them. - headers.emplace_back(line.substr(0, colon), std::move(value)); - } - if (end == std::string::npos) { - break; - } - start = end + 1; - } - return headers; -} - -std::string serializeHeaders(const http::Headers& headers) { - std::string text; - for (const auto& [name, value] : headers) { - if (!text.empty()) { - text.push_back('\n'); - } - text += name; - text += ": "; - text += value; - } - return text; -} - -} // namespace - -void rn_gpui_http_request( - std::uint64_t request_id, - ::rust::Str method, - ::rust::Str url, - ::rust::Str headers, - ::rust::Str body) { - auto state = std::make_shared(); - { - std::lock_guard lock(g_requestsMutex); - g_requests[request_id] = state; - } - - const std::string methodText(method.data(), method.size()); - const std::string urlText(url.data(), url.size()); - const std::string headersText(headers.data(), headers.size()); - const std::string bodyText(body.data(), body.size()); - - std::thread( - [request_id, state, methodText, urlText, headersText, bodyText]() { - auto result = std::make_shared(); - auto finished = std::make_shared(); - auto condition = std::make_shared(); - - http::NetworkCallbacks callbacks; - callbacks.onResponse = [result]( - uint16_t code, - http::Headers responseHeaders, - std::string /*responseUrl*/) { - result->status = code; - result->headers = std::move(responseHeaders); - }; - callbacks.onBody = [result](std::unique_ptr data) { - if (!data) { - return; - } - for (const auto& range : *data) { - result->body.append( - reinterpret_cast(range.data()), range.size()); - } - }; - callbacks.onResponseComplete = [result, finished, condition]( - std::string error, - bool /*timeoutError*/) { - result->error = std::move(error); - { - std::lock_guard lock(*finished); - result->done = true; - } - condition->notify_all(); - }; - - // One client per request: `CurlHttpClient` is stateless, and the - // cookies it shares live in a process-wide handle created on first use. - // An empty string body still sets CURLOPT_POSTFIELDS, which turns a - // GET into a POST. - http::Body requestBody; - if (!bodyText.empty()) { - requestBody.string = bodyText; - } - auto client = gpui_http_client_factory()(); - client->sendRequest( - std::move(callbacks), - methodText, - urlText, - parseHeaders(headersText), - std::move(requestBody)); - - // `sendRequest` returns as soon as the transfer has been started on its - // own thread, so the response is awaited here rather than assumed. - { - std::unique_lock lock(*finished); - condition->wait(lock, [&result] { return result->done; }); - } - { - std::lock_guard lock(g_requestsMutex); - g_requests.erase(request_id); - } - if (state->cancelled.load(std::memory_order_relaxed)) { - return; - } - const auto serialized = serializeHeaders(result->headers); - // `rust::Slice` for the body: it is raw response bytes, and an image - // response is not UTF-8. - rn_gpui_http_complete( - request_id, - result->status, - ::rust::Str(serialized.data(), serialized.size()), - ::rust::Slice( - reinterpret_cast(result->body.data()), - result->body.size()), - ::rust::Str(result->error.data(), result->error.size())); - }) - .detach(); -} - -void rn_gpui_http_request_cancel(std::uint64_t request_id) { - std::lock_guard lock(g_requestsMutex); - const auto it = g_requests.find(request_id); - if (it != g_requests.end()) { - it->second->cancelled.store(true, std::memory_order_relaxed); - } -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHttpBridge.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHttpBridge.h deleted file mode 100644 index 83d3d15056..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHttpBridge.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include -#include "rust/cxx.h" - -namespace rngpui { - -// One request, issued for GPUI's image, font and remote vector image loading. -// -// GPUI's `HttpClient` is synchronous from the caller's point of view: it -// returns a future that resolves when the response is complete. React Native's -// client is callback-shaped, so this runs the request on its own thread and -// reports the whole response at the end. `request_id` is echoed back on the -// Rust side. -// -// The request counts in `rn_gpui_http_requests_in_flight` for its lifetime, so -// the test driver's idle detection covers image and font loads too. -void rn_gpui_http_request( - std::uint64_t request_id, - rust::Str method, - rust::Str url, - rust::Str headers, - rust::Str body); - -// Cancels an in-flight request, if it is still running. -void rn_gpui_http_request_cancel(std::uint64_t request_id); - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHttpClient.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHttpClient.cpp deleted file mode 100644 index 30bbca3d75..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHttpClient.cpp +++ /dev/null @@ -1,574 +0,0 @@ -#include "GpuiHttpClient.h" -#include -#include "GpuiNetworkConfig.h" -#include "GpuiNetworkRequest.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rngpui { -namespace { -using namespace facebook::react; - -// curl_global_init() is not thread-safe and has to run before any other libcurl -// call, so every client construction goes through call_once(). -void ensureCurlInitialized() { - static std::once_flag once; - std::call_once(once, []() { curl_global_init(CURL_GLOBAL_DEFAULT); }); -} - -struct SharedCookies { - CURLSH* handle{curl_share_init()}; - std::mutex mutex; - - SharedCookies() { - curl_share_setopt(handle, CURLSHOPT_LOCKFUNC, lock); - curl_share_setopt(handle, CURLSHOPT_UNLOCKFUNC, unlock); - curl_share_setopt(handle, CURLSHOPT_USERDATA, this); - curl_share_setopt(handle, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE); - } - ~SharedCookies() { - curl_share_cleanup(handle); - } - - static void lock(CURL*, curl_lock_data, curl_lock_access, void* data) { - static_cast(data)->mutex.lock(); - } - static void unlock(CURL*, curl_lock_data, void* data) { - static_cast(data)->mutex.unlock(); - } -}; - -SharedCookies& sharedCookies() { - static SharedCookies cookies; - return cookies; -} - -// Shared by the worker thread and the token handed back to the caller: cancel() -// can be called from any thread at any time. -struct Cancellation { - std::atomic cancelled{false}; -}; - -std::atomic httpRequestsInFlight{0}; -std::mutex httpRequestsMutex; -std::unordered_map httpRequestUrlsInFlight; - -struct RequestActivity { - explicit RequestActivity(const std::string& url) : url_(url) { - httpRequestsInFlight.fetch_add(1, std::memory_order_relaxed); - std::lock_guard lock(httpRequestsMutex); - ++httpRequestUrlsInFlight[url_]; - } - ~RequestActivity() { - httpRequestsInFlight.fetch_sub(1, std::memory_order_relaxed); - std::lock_guard lock(httpRequestsMutex); - auto it = httpRequestUrlsInFlight.find(url_); - if (it != httpRequestUrlsInFlight.end() && --it->second == 0) { - httpRequestUrlsInFlight.erase(it); - } - } - - private: - std::string url_; -}; - -class CurlRequestToken final : public http::IRequestToken { - public: - explicit CurlRequestToken(std::shared_ptr cancellation) - : cancellation_(std::move(cancellation)) {} - - void cancel() noexcept override { - cancellation_->cancelled.store(true, std::memory_order_relaxed); - } - - private: - std::shared_ptr cancellation_; -}; - -struct Transfer { - std::shared_ptr cancellation; - http::NetworkCallbacks callbacks; - std::string body; - http::Headers responseHeaders; - int64_t receivedBytes{0}; - int64_t totalBytes{-1}; - int64_t uploadedBytes{0}; - int64_t totalUploadBytes{-1}; -}; - -bool isCancelled(const Transfer& transfer) { - return transfer.cancellation->cancelled.load(std::memory_order_relaxed); -} - -// Returning a short count makes libcurl abort the transfer with -// CURLE_WRITE_ERROR, which is how cancellation interrupts a download in -// progress. -size_t writeCallback(char* data, size_t size, size_t count, void* userData) { - auto& transfer = *static_cast(userData); - if (isCancelled(transfer)) { - return 0; - } - - const auto length = static_cast(size * count); - - // `sendIncrementalUpdates` asks for the body as it arrives instead of one - // buffer at the end; the two delivery styles are mutually exclusive. - if (transfer.callbacks.sendIncrementalUpdates && - transfer.callbacks.onBodyIncremental) { - const int64_t consumed = transfer.callbacks.onBodyIncremental( - transfer.receivedBytes, - transfer.totalBytes, - folly::IOBuf::copyBuffer(data, static_cast(length))); - if (consumed < length) { - return 0; - } - } else { - transfer.body.append(data, static_cast(length)); - } - - transfer.receivedBytes += length; - if (transfer.callbacks.sendProgressUpdates && - transfer.callbacks.onBodyProgress) { - transfer.callbacks.onBodyProgress( - transfer.receivedBytes, transfer.totalBytes); - } - return size * count; -} - -// libcurl hands the header block over one line at a time, status line first and -// a blank line last. -size_t headerCallback(char* data, size_t size, size_t count, void* userData) { - auto& transfer = *static_cast(userData); - const size_t length = size * count; - const std::string_view line(data, length); - - if (isCancelled(transfer)) { - return 0; - } - if (line.starts_with("HTTP/")) { - // libcurl reports each redirect/interim response header block. Only the - // final response headers belong on the Fetch Response. - transfer.responseHeaders.clear(); - } - if (line == "\r\n" || line == "\n") { - return length; // End of the response header block. - } - - const size_t colon = line.find(':'); - if (colon != std::string_view::npos) { - std::string_view name = line.substr(0, colon); - std::string_view value = line.substr(colon + 1); - while (!value.empty() && (value.front() == ' ' || value.front() == '\t')) { - value.remove_prefix(1); - } - while ( - !value.empty() && - (value.back() == '\r' || value.back() == '\n' || value.back() == ' ')) { - value.remove_suffix(1); - } - transfer.responseHeaders.emplace_back( - std::string(name), std::string(value)); - } - return length; -} - -// The callback that keeps cancellation responsive between writes and, as a -// side effect, tells us the expected body size for progress reporting. -int progressCallback( - void* userData, - curl_off_t dltotal, - curl_off_t /*dlnow*/, - curl_off_t ultotal, - curl_off_t ulnow) { - auto& transfer = *static_cast(userData); - if (dltotal > 0) { - transfer.totalBytes = static_cast(dltotal); - } - if (ultotal >= 0) { - transfer.totalUploadBytes = static_cast(ultotal); - } - if (ulnow >= 0 && static_cast(ulnow) != transfer.uploadedBytes) { - transfer.uploadedBytes = static_cast(ulnow); - if (transfer.callbacks.onUploadProgress) { - transfer.callbacks.onUploadProgress( - transfer.uploadedBytes, transfer.totalUploadBytes); - } - } - return isCancelled(transfer) ? 1 : 0; // Non-zero aborts the transfer. -} - -struct CurlHandle { - CURL* handle{nullptr}; - curl_slist* headers{nullptr}; - curl_mime* mime{nullptr}; - - ~CurlHandle() { - if (mime != nullptr) { - curl_mime_free(mime); - } - curl_slist_free_all(headers); - if (handle != nullptr) { - curl_easy_cleanup(handle); - } - } -}; - -std::optional decodeBase64(std::string_view input) { - static constexpr std::string_view alphabet = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - std::string result; - uint32_t value = 0; - int bits = -8; - for (char ch : input) { - if (ch == '=') { - break; - } - if (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t') { - continue; - } - const auto index = alphabet.find(ch); - if (index == std::string_view::npos) { - return std::nullopt; - } - value = (value << 6) | static_cast(index); - bits += 6; - if (bits >= 0) { - result.push_back(static_cast((value >> bits) & 0xff)); - bits -= 8; - } - } - return result; -} - -bool addFormData(curl_mime* mime, const http::FormData& fields) { - for (const auto& field : fields) { - auto* part = curl_mime_addpart(mime); - curl_mime_name(part, field.fieldName.c_str()); - std::string filename; - for (const auto& [name, value] : field.headers) { - if (name == "Content-Type" || name == "content-type") { - curl_mime_type(part, value.c_str()); - } else if ( - name == "Content-Disposition" || name == "content-disposition") { - const auto filenamePos = value.find("filename=\""); - if (filenamePos != std::string::npos) { - const auto start = filenamePos + 10; - const auto end = value.find('"', start); - if (end != std::string::npos) { - filename = value.substr(start, end - start); - } - } - } - } - if (field.string) { - curl_mime_data(part, field.string->data(), field.string->size()); - } else if (field.uri) { - std::string path = *field.uri; - if (path.starts_with("file://")) { - path.erase(0, 7); - } - if (curl_mime_filedata(part, path.c_str()) != CURLE_OK) { - return false; - } - if (!filename.empty()) { - curl_mime_filename(part, filename.c_str()); - } - } - } - return true; -} - -void performRequest( - Transfer transfer, - const std::string& method, - const std::string& url, - const http::Headers& requestHeaders, - const http::Body& requestBody, - uint32_t timeout) { - const RequestActivity activity(url); - const auto complete = [&transfer](std::string error, bool timeoutError) { - if (transfer.callbacks.onResponseComplete) { - transfer.callbacks.onResponseComplete(std::move(error), timeoutError); - } - }; - - if (url.starts_with("blob:")) { - try { - const folly::Uri uri(url); - auto path = uri.path(); - while (!path.empty() && path.front() == '/') { - path.erase(path.begin()); - } - uint64_t offset = 0; - uint64_t size = std::numeric_limits::max(); - const auto query = uri.query(); - const auto offsetKey = query.find("offset="); - if (offsetKey != std::string::npos) { - offset = std::stoull(query.substr(offsetKey + 7)); - } - const auto sizeKey = query.find("size="); - if (sizeKey != std::string::npos) { - size = std::stoull(query.substr(sizeKey + 5)); - } - auto data = readBlob(path, offset, size); - if (!data) { - if (transfer.callbacks.onResponse) { - transfer.callbacks.onResponse(404, {}, url); - } - complete("Blob URL is no longer available", false); - return; - } - if (transfer.callbacks.onResponse) { - transfer.callbacks.onResponse( - 200, - {{"Content-Length", std::to_string(data->size())}, - {"Content-Type", "application/octet-stream"}}, - url); - } - if (transfer.callbacks.sendIncrementalUpdates && - transfer.callbacks.onBodyIncremental) { - transfer.callbacks.onBodyIncremental( - 0, - static_cast(data->size()), - folly::IOBuf::copyBuffer(*data)); - } else if (transfer.callbacks.onBody) { - transfer.callbacks.onBody(folly::IOBuf::copyBuffer(*data)); - } - complete("", false); - } catch (const std::exception& error) { - complete(std::string("Invalid Blob URL: ") + error.what(), false); - } - return; - } - - CurlHandle curl; - curl.handle = curl_easy_init(); - if (curl.handle == nullptr) { - complete("libcurl: could not create an easy handle", false); - return; - } - - for (const auto& [name, value] : requestHeaders) { - const std::string line = name + ": " + value; - curl.headers = curl_slist_append(curl.headers, line.c_str()); - } - - curl_easy_setopt(curl.handle, CURLOPT_URL, url.c_str()); - curl_easy_setopt(curl.handle, CURLOPT_USERAGENT, "react-native-gpui/0.1"); - applyNetworkConfig(curl.handle, url); - curl_easy_setopt(curl.handle, CURLOPT_NOSIGNAL, 1L); - curl_easy_setopt(curl.handle, CURLOPT_FOLLOWLOCATION, 1L); - curl_easy_setopt(curl.handle, CURLOPT_ACCEPT_ENCODING, ""); - curl_easy_setopt(curl.handle, CURLOPT_SHARE, sharedCookies().handle); - if (requestBody.withCredentials) { - // Enables libcurl's in-memory cookie engine. Cookie data is shared between - // requests for the lifetime of the process and is never written to disk. - curl_easy_setopt(curl.handle, CURLOPT_COOKIEFILE, ""); - } - curl_easy_setopt(curl.handle, CURLOPT_WRITEFUNCTION, writeCallback); - curl_easy_setopt(curl.handle, CURLOPT_WRITEDATA, &transfer); - curl_easy_setopt(curl.handle, CURLOPT_HEADERFUNCTION, headerCallback); - curl_easy_setopt(curl.handle, CURLOPT_HEADERDATA, &transfer); - curl_easy_setopt(curl.handle, CURLOPT_NOPROGRESS, 0L); - curl_easy_setopt(curl.handle, CURLOPT_XFERINFOFUNCTION, progressCallback); - curl_easy_setopt(curl.handle, CURLOPT_XFERINFODATA, &transfer); - if (curl.headers != nullptr) { - curl_easy_setopt(curl.handle, CURLOPT_HTTPHEADER, curl.headers); - } - if (timeout > 0) { - // The interface documents a timeout in seconds, 0 meaning "no timeout". - curl_easy_setopt(curl.handle, CURLOPT_TIMEOUT, static_cast(timeout)); - } - if (method != "GET" && method != "get") { - curl_easy_setopt(curl.handle, CURLOPT_CUSTOMREQUEST, method.c_str()); - } - std::optional requestBodyBlob; - if (requestBody.formData) { - curl.mime = curl_mime_init(curl.handle); - if (curl.mime == nullptr || - !addFormData(curl.mime, *requestBody.formData)) { - complete("Invalid FormData request body", false); - return; - } - curl_easy_setopt(curl.handle, CURLOPT_MIMEPOST, curl.mime); - } else if (requestBody.blob) { - auto blob = readBlob( - requestBody.blob->blobId, - requestBody.blob->offset, - requestBody.blob->size); - if (!blob) { - complete("Blob request body is no longer available", false); - return; - } - requestBodyBlob = std::move(*blob); - curl_easy_setopt(curl.handle, CURLOPT_POSTFIELDS, requestBodyBlob->data()); - curl_easy_setopt( - curl.handle, - CURLOPT_POSTFIELDSIZE_LARGE, - static_cast(requestBodyBlob->size())); - } else if (requestBody.base64) { - auto decoded = decodeBase64(*requestBody.base64); - if (!decoded) { - complete("Invalid base64 request body", false); - return; - } - curl_easy_setopt(curl.handle, CURLOPT_POSTFIELDS, decoded->data()); - curl_easy_setopt( - curl.handle, - CURLOPT_POSTFIELDSIZE_LARGE, - static_cast(decoded->size())); - } else if (requestBody.string.has_value()) { - curl_easy_setopt( - curl.handle, CURLOPT_POSTFIELDS, requestBody.string->data()); - curl_easy_setopt( - curl.handle, - CURLOPT_POSTFIELDSIZE_LARGE, - static_cast(requestBody.string->size())); - } - - CURLcode result = curl_easy_perform(curl.handle); - // A name the DNS-over-HTTPS server could not give goes to the next server, - // then to the system resolver, as long as nothing has come back yet. - for (size_t resolverAttempt = 0; result == CURLE_COULDNT_RESOLVE_HOST && - transfer.responseHeaders.empty() && transfer.body.empty() && - !isCancelled(transfer) && - fallBackResolver(curl.handle, resolverAttempt);) { - result = curl_easy_perform(curl.handle); - } - - long responseCode = 0; - char* effectiveUrlValue = nullptr; - curl_easy_getinfo(curl.handle, CURLINFO_RESPONSE_CODE, &responseCode); - curl_easy_getinfo(curl.handle, CURLINFO_EFFECTIVE_URL, &effectiveUrlValue); - const std::string effectiveUrl = - effectiveUrlValue == nullptr ? url : effectiveUrlValue; - curl_easy_cleanup(curl.handle); - curl.handle = nullptr; - - if (isCancelled(transfer)) { - complete("Request cancelled", false); - return; - } - if (result != CURLE_OK) { - const auto error = curl_easy_strerror(result); - LOG(ERROR) << "[gpui-http] " << method << " " << url - << " failed: " << error; - complete(error, result == CURLE_OPERATION_TIMEDOUT); - return; - } - - const auto statusCode = static_cast(responseCode); - if (transfer.callbacks.onResponse) { - transfer.callbacks.onResponse( - statusCode, transfer.responseHeaders, effectiveUrl); - } - if (transfer.callbacks.onBody && !transfer.callbacks.sendIncrementalUpdates) { - transfer.callbacks.onBody(folly::IOBuf::copyBuffer(transfer.body)); - } - complete("", false); -} - -class CurlHttpClient final : public IHttpClient { - public: - std::unique_ptr sendRequest( - http::NetworkCallbacks&& callbacks, - const std::string& method, - const std::string& url, - const http::Headers& headers = {}, - const http::Body& body = {}, - uint32_t timeout = 0, - std::optional /*loggingId*/ = std::nullopt) override { - ensureCurlInitialized(); - - auto cancellation = std::make_shared(); - Transfer transfer; - transfer.cancellation = cancellation; - transfer.callbacks = std::move(callbacks); - - // The request runs to completion on its own thread: callers block on a - // future that these callbacks resolve, so the request must not occupy the - // calling thread. - std::thread( - performRequest, - std::move(transfer), - method, - url, - headers, - body, - timeout) - .detach(); - - return std::make_unique(std::move(cancellation)); - } -}; - -} // namespace - -extern "C" uint64_t rn_gpui_http_requests_in_flight() noexcept { - return httpRequestsInFlight.load(std::memory_order_relaxed); -} - -extern "C" uint64_t rn_gpui_http_requests_not_ignored( - const char* newline_separated_patterns) noexcept { - std::lock_guard lock(httpRequestsMutex); - uint64_t count = 0; - for (const auto& [url, active] : httpRequestUrlsInFlight) { - bool ignored = false; - if (newline_separated_patterns != nullptr) { - const std::string patterns(newline_separated_patterns); - size_t start = 0; - while (start <= patterns.size()) { - const auto end = patterns.find('\n', start); - const auto pattern = patterns.substr(start, end - start); - if (!pattern.empty() && url.find(pattern) != std::string::npos) { - ignored = true; - break; - } - if (end == std::string::npos) - break; - start = end + 1; - } - } - if (!ignored) - count += active; - } - return count; -} - -HttpClientFactory gpui_http_client_factory() { - return []() -> std::unique_ptr { - return std::make_unique(); - }; -} - -bool gpui_http_client_clear_cookies() { - ensureCurlInitialized(); - CURL* handle = curl_easy_init(); - if (handle == nullptr) { - return false; - } - curl_easy_setopt(handle, CURLOPT_SHARE, sharedCookies().handle); - curl_easy_setopt(handle, CURLOPT_COOKIEFILE, ""); - const auto result = curl_easy_setopt(handle, CURLOPT_COOKIELIST, "ALL"); - curl_easy_cleanup(handle); - return result == CURLE_OK; -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHttpClient.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHttpClient.h deleted file mode 100644 index 9208426170..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiHttpClient.h +++ /dev/null @@ -1,15 +0,0 @@ -// ReactHost's constructor throws unless an HttpClientFactory is in the -// ContextContainer. -#pragma once - -#include -#include - -namespace rngpui { -facebook::react::HttpClientFactory gpui_http_client_factory(); -bool gpui_http_client_clear_cookies(); -extern "C" uint64_t rn_gpui_http_requests_in_flight() noexcept; -extern "C" uint64_t rn_gpui_http_requests_not_ignored( - const char* newline_separated_patterns) noexcept; - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiImageLoad.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiImageLoad.h deleted file mode 100644 index 9031587aca..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiImageLoad.h +++ /dev/null @@ -1,30 +0,0 @@ -// The ImageManager override is compiled as part of ReactCommon, which must not -// see the cxx bridge headers, so it starts loads through this plain -// function-pointer table. -#pragma once - -#include -#include -#include - -namespace rngpui { -using GpuiImageProgress = std::function< - void(float progress, std::int64_t loaded, std::int64_t total)>; -using GpuiImageDone = std::function< - void(double imageWidth, double imageHeight, const char* errorMessage)>; - -struct GpuiImageLoadTable { - // Starts loading `uri`. `progress` may be called any number of times first; - // `done` is called once, with an error message on failure. - void (*start)( - const std::string& uri, - GpuiImageProgress progress, - GpuiImageDone done); -}; - -// Defined in ReactCommonOverrides/.../ImageManager.cpp. Installed once by -// GpuiHost before any surface is started. Without a table a request never -// completes, as before. -void setGpuiImageLoadTable(const GpuiImageLoadTable& table); -const GpuiImageLoadTable* gpuiImageLoadTable(); -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiImageLoader.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiImageLoader.h deleted file mode 100644 index 3e23419d3d..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiImageLoader.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include -#include "rust/cxx.h" - -namespace rngpui { -void rn_gpui_on_image_load_result( - std::uint64_t request_id, - double width, - double height, - rust::String error); -void rn_gpui_on_image_progress( - std::uint64_t request_id, - std::int64_t loaded, - std::int64_t total); -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiJsEngine.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiJsEngine.cpp deleted file mode 100644 index 346ceb96d9..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiJsEngine.cpp +++ /dev/null @@ -1,125 +0,0 @@ -#include "GpuiJsEngine.h" - -#include - -namespace rngpui { -namespace { -std::mutex& registryMutex() { - static std::mutex mutex; - return mutex; -} - -std::vector& registry() { - static std::vector engines; - return engines; -} - -std::string& selection() { - static std::string name; - return name; -} - -std::string joinNames(const std::vector& engines) { - std::string joined; - for (const auto& engine : engines) { - if (!joined.empty()) { - joined += ", "; - } - joined += engine.info.name; - } - return joined; -} - -[[noreturn]] void throwNoEngine() { - throw std::runtime_error( - "no JS engine installed; add @react-native-gpui/hermes (or another " - "engine package) to the app's dependencies"); -} - -[[noreturn]] void throwUnknownEngine( - const std::string& name, - const std::vector& engines) { - throw std::runtime_error( - "unknown JS engine '" + name + - "'; registered engines: " + joinNames(engines)); -} - -[[noreturn]] void throwAmbiguousEngine( - const std::vector& engines) { - throw std::runtime_error( - "several JS engines are installed (" + joinNames(engines) + - "); choose one with RN_GPUI_JS_ENGINE or DesktopAppConfig::js_engine"); -} - -const GpuiJsEngine* findEngine( - const std::vector& engines, - std::string_view name) { - for (const auto& engine : engines) { - if (engine.info.name == name) { - return &engine; - } - } - return nullptr; -} - -} // namespace - -void registerJsEngine(GpuiJsEngine engine) { - if (engine.info.name.empty()) { - throw std::invalid_argument("a JS engine must report a name"); - } - if (engine.makeRuntimeFactory == nullptr) { - throw std::invalid_argument( - "JS engine '" + engine.info.name + "' has no runtime factory"); - } - std::lock_guard lock(registryMutex()); - if (findEngine(registry(), engine.info.name) != nullptr) { - throw std::invalid_argument( - "duplicate JS engine '" + engine.info.name + "'"); - } - registry().push_back(std::move(engine)); -} - -void selectJsEngine(std::string_view name) { - std::lock_guard lock(registryMutex()); - if (name.empty()) { - selection().clear(); - return; - } - if (findEngine(registry(), name) == nullptr) { - throwUnknownEngine(std::string(name), registry()); - } - selection() = std::string(name); -} - -const GpuiJsEngine& activeJsEngine() { - std::lock_guard lock(registryMutex()); - const auto& engines = registry(); - if (engines.empty()) { - throwNoEngine(); - } - if (!selection().empty()) { - if (const auto* engine = findEngine(engines, selection())) { - return *engine; - } - // The selection can only go stale if the registry changed after startup; - // report it rather than silently running a different engine. - throwUnknownEngine(selection(), engines); - } - if (engines.size() == 1) { - return engines.front(); - } - throwAmbiguousEngine(engines); -} - -std::vector registeredJsEngines() { - std::lock_guard lock(registryMutex()); - std::vector infos; - infos.reserve(registry().size()); - for (const auto& engine : registry()) { - infos.push_back(engine.info); - } - return infos; -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiJsEngine.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiJsEngine.h deleted file mode 100644 index c10aaa004e..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiJsEngine.h +++ /dev/null @@ -1,127 +0,0 @@ -// Core has no built-in JS engine: an engine is an installed package that -// registers itself here. -#pragma once - -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace facebook::react { -class CallInvoker; -class JSRuntimeFactory; -class TurboModule; -} // namespace facebook::react - -namespace rngpui { -// Set by core when the renderer provides a frame source for the backend. -inline std::atomic& sharedAnimatedBackend() { - static std::atomic enabled{false}; - return enabled; -} - -class GpuiFeatureFlagsOverrides - : public facebook::react::ReactNativeFeatureFlagsOverridesOSSStable { - public: - // React Native's C++ AnimatedModule queues operations until - // finishOperationBatch(). GPUI is neither Android nor iOS, so RN's JS helper - // only sends those batch boundaries when this flag is enabled. - bool cxxNativeAnimatedEnabled() override { - return true; - } - - // Pressability's onHoverIn/onHoverOut ride on pointer enter and leave, which - // GPUI delivers. The mouse-event path it otherwise takes is for web. - bool shouldPressibilityUseW3CPointerEventsForHover() override { - return true; - } - - // Events without a priority of their own, such as onLayout, render at - // default priority instead of synchronously. A live resize fires them every - // frame, and as sync work they keep React committing until it trips its - // nested update limit. - bool fixMappingOfEventPrioritiesBetweenFabricAndReact() override { - return true; - } - - // `ref.focus()` and `ref.blur()` on a View send a command to the host - // instead of doing nothing, as `HTMLElement.focus()` moves focus. - bool enableImperativeFocus() override { - return true; - } - - // The shared animation backend needs a platform frame source: only the Loom - // renderer provides one. - bool useSharedAnimatedBackend() override { - return sharedAnimatedBackend().load(std::memory_order_acquire); - } -}; - -struct GpuiJsEngineInfo { - std::string name; - std::string version; -}; - -// Every capability an engine may provide. Only `info` and `makeRuntimeFactory` -// are required; core checks the optional members before use. -struct GpuiJsEngine { - GpuiJsEngineInfo info; - - // Required. Creates the factory ReactHost uses for every (re)load. - std::function()> - makeRuntimeFactory; - - // Optional. Loading stock Node-API `.node` addons. Creating a napi_env for a - // runtime and loading a shared library into it are VM-specific, so the - // engine supplies a loader; everything else (path resolution, the cache, - // error messages) is core's. When missing, `_requireNodeLibrary` still - // exists and throws an error naming the engine. - struct NodeAddons { - // Called once per runtime, on the JS thread, before the app bundle runs. - // `jsInvoker` schedules work on that same JS thread. Returns a function - // that loads the addon at an absolute path and returns its exports, or - // throws a jsi::JSError with a readable message. - std::function( - std::shared_ptr jsInvoker)> - makeLoader; - }; - std::optional nodeAddons; - - // Optional. Returns the feature-flag overrides core installs. An engine that - // needs flags of its own derives from GpuiFeatureFlagsOverrides and - // overrides only those flags, so core's survive. When unset, core installs - // GpuiFeatureFlagsOverrides itself. - std::function()> - makeFeatureFlagsOverrides; -}; - -// Called by engine packages from their registration function. Throws -// std::invalid_argument for an empty name, a duplicate name, or a missing -// runtime factory. -void registerJsEngine(GpuiJsEngine engine); - -// Used by core. Throws std::runtime_error when no engine is registered, when -// several are registered and none was selected, or when the selected name is -// not registered. -const GpuiJsEngine& activeJsEngine(); - -std::vector registeredJsEngines(); - -// Chooses the engine for this run, before the host starts. An empty name -// returns to the default: the only registered engine, or an error when several -// are registered. -void selectJsEngine(std::string_view name); - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiLogBoxSurfaceDelegate.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiLogBoxSurfaceDelegate.cpp deleted file mode 100644 index 49dac96337..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiLogBoxSurfaceDelegate.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include "GpuiLogBoxSurfaceDelegate.h" - -#include "GpuiHost.h" -#include "rn-gpui-sys/src/lib.rs.h" // cxx bridge - -#include - -namespace rngpui { -void GpuiLogBoxSurfaceDelegate::createContentView(std::string appKey) { - appKey_ = std::move(appKey); - ready_ = true; - rn_gpui_log(1, "LogBox content view created (appKey=" + appKey_ + ")"); -} - -bool GpuiLogBoxSurfaceDelegate::isContentViewReady() { - return ready_; -} - -void GpuiLogBoxSurfaceDelegate::destroyContentView() { - if (showing_) { - hide(); - } - ready_ = false; - rn_gpui_log(1, "LogBox content view destroyed"); -} - -void GpuiLogBoxSurfaceDelegate::show() { - if (!ready_ || showing_) { - return; - } - showing_ = true; - rn_gpui_log(1, "LogBox shown"); - host_.start_log_box_surface(); -} - -void GpuiLogBoxSurfaceDelegate::hide() { - if (!showing_) { - return; - } - showing_ = false; - rn_gpui_log(1, "LogBox hidden"); - host_.stop_log_box_surface(); -} - -bool GpuiLogBoxSurfaceDelegate::isShowing() { - return showing_; -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiLogBoxSurfaceDelegate.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiLogBoxSurfaceDelegate.h deleted file mode 100644 index 90d103b006..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiLogBoxSurfaceDelegate.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include - -#include - -namespace rngpui { -class GpuiHost; - -/// React renders LogBox into a second React surface (app key `"LogBox"`). It -/// is shown as an overlay in the main window; `hide()` stops the surface so -/// nothing covers the app while LogBox is closed. -class GpuiLogBoxSurfaceDelegate : public facebook::react::SurfaceDelegate { - public: - explicit GpuiLogBoxSurfaceDelegate(GpuiHost& host) : host_(host) {} - - void createContentView(std::string appKey) override; - bool isContentViewReady() override; - void destroyContentView() override; - void show() override; - void hide() override; - bool isShowing() override; - - private: - GpuiHost& host_; - std::string appKey_; - bool ready_{false}; - bool showing_{false}; -}; - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiLoomHost.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiLoomHost.cpp deleted file mode 100644 index 546b9ef79f..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiLoomHost.cpp +++ /dev/null @@ -1,2047 +0,0 @@ -#if LOOM_RENDERER - -#include "GpuiLoomHost.h" - -#include "GpuiTurboModule.h" -#include "MountBatchBuilder.h" -#include "react/coremodules/DeviceInfoModule.h" -#include "rn-gpui-sys/src/lib.rs.h" // cxx bridge - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rngpui { - -using namespace facebook::react; - -namespace { - -// Loom's UI thread when JavaScript runs on its own thread: commit results are -// turned into mount batches here, and the GPUI main thread only applies them, -// so a frame being drawn never delays a commit and a commit never delays a -// frame. With JavaScript on the main thread, the GPUI main thread is Loom's UI -// thread. -class MountThread { - public: - static MountThread& shared() { - static auto* thread = new MountThread(); - return *thread; - } - - void post(std::function task) { - { - std::lock_guard lock(mutex_); - tasks_.push_back(std::move(task)); - } - wake_.notify_one(); - } - - bool isCurrent() const { - return std::this_thread::get_id() == id_.load(std::memory_order_acquire); - } - - private: - MountThread() { - std::thread([this] { - folly::setThreadName("loom-mount"); - id_.store(std::this_thread::get_id(), std::memory_order_release); - for (;;) { - std::function task; - { - std::unique_lock lock(mutex_); - wake_.wait(lock, [this] { return !tasks_.empty(); }); - task = std::move(tasks_.front()); - tasks_.pop_front(); - } - try { - task(); - } catch (const std::exception& error) { - LOG(ERROR) << "Loom mount task failed: " << error.what(); - } - } - }).detach(); - } - - std::mutex mutex_; - std::condition_variable wake_; - std::deque> tasks_; - std::atomic id_{}; -}; - -bool loomUIIsMountThread() { - return !loomJavaScriptOnUIThread(); -} - -void postToLoomUI(std::function task) { - if (loomUIIsMountThread()) { - MountThread::shared().post(std::move(task)); - } else { - dispatchMain(std::move(task)); - } -} - -// Threads for Loom's parallel text measurement -// (`LoomPlatformTraits::parallelFor`). One job at a time; the calling thread -// works on it too. -class TextPool { - public: - static TextPool& shared() { - static auto* pool = new TextPool(); - return *pool; - } - - void run(size_t count, const std::function& body) { - std::lock_guard serial(runMutex_); - { - std::lock_guard lock(mutex_); - body_ = &body; - count_ = count; - next_ = 0; - pending_ = count; - ++generation_; - } - wake_.notify_all(); - work(); - std::unique_lock lock(mutex_); - done_.wait(lock, [this] { return pending_ == 0; }); - body_ = nullptr; - } - - private: - TextPool() { - const unsigned cores = std::thread::hardware_concurrency(); - const unsigned threads = cores > 3 ? std::min(cores / 2, 4u) : 1u; - for (unsigned index = 0; index < threads; ++index) { - std::thread([this] { - folly::setThreadName("loom-text"); - loop(); - }).detach(); - } - } - - void loop() { - uint64_t seen = 0; - for (;;) { - { - std::unique_lock lock(mutex_); - wake_.wait(lock, [&] { return generation_ != seen; }); - seen = generation_; - } - work(); - } - } - - void work() { - for (;;) { - size_t index; - const std::function* body; - { - std::lock_guard lock(mutex_); - if (body_ == nullptr || next_ >= count_) { - return; - } - index = next_++; - body = body_; - } - try { - (*body)(index); - } catch (...) { - // That paragraph stays unmeasured; the layout pass measures it. - } - std::lock_guard lock(mutex_); - if (--pending_ == 0) { - done_.notify_all(); - } - } - } - - std::mutex runMutex_; - std::mutex mutex_; - std::condition_variable wake_; - std::condition_variable done_; - const std::function* body_{nullptr}; - size_t count_{0}; - size_t next_{0}; - size_t pending_{0}; - uint64_t generation_{0}; -}; - -constexpr size_t kWorkerStackSize = 2 * 1024 * 1024; - -void logLoom(LoomLogLevel level, const char* tag, const char* message) { - const auto line = std::string(tag) + ": " + message; - rn_gpui_log(level == LoomLogLevel::Warn ? 2 : 1, line); -} - -} // namespace - -GpuiLoomTextServices::GpuiLoomTextServices( - std::shared_ptr contextContainer, - std::shared_ptr layoutManager) - : LoomTextLayoutManagerServices( - contextContainer, - layoutManager, - /*measurableOnWorker=*/true), - layoutManager_(std::move(layoutManager)), - contextContainer_(contextContainer) {} - -TextAttributes GpuiLoomTextServices::parseTextAttributes( - SurfaceId surfaceId, - const std::string& componentName, - const folly::dynamic& props, - const TextAttributes& inherited, - ParagraphAttributes& outParagraphAttributes) { - // The shadow tree takes the text scale from the layout context; here it is - // the one input the attributes still lack. - auto adjusted = inherited; - adjusted.fontSizeMultiplier = DeviceInfoModule::fontScale(); - if (componentNameByReactViewName(componentName) == "TextInput") { - // The input's font comes from its own props, as its shadow node reads them. - static const RawPropsParser parser = [] { - RawPropsParser prepared; - prepared.prepare(); - return prepared; - }(); - const PropsParserContext context{surfaceId, *contextContainer_}; - RawProps rawProps{props}; - rawProps.parse(parser); - const TextInputProps parsed{context, TextInputProps{}, rawProps}; - adjusted.apply( - parsed.getEffectiveTextAttributes(adjusted.fontSizeMultiplier)); - outParagraphAttributes = parsed.paragraphAttributes; - return adjusted; - } - return LoomTextLayoutManagerServices::parseTextAttributes( - surfaceId, componentName, props, adjusted, outParagraphAttributes); -} - -LoomTextMeasurement GpuiLoomTextServices::prepareText( - SurfaceId /*surfaceId*/, - const AttributedString& attributedString, - const ParagraphAttributes& paragraphAttributes, - const Size& minimumSize, - const Size& maximumSize) { - const auto& fragments = attributedString.getFragments(); - if (fragments.empty() || - std::any_of(fragments.begin(), fragments.end(), [](const auto& fragment) { - return fragment.isAttachment(); - })) { - return {}; - } - const auto flat = - flattenParagraphText(attributedString, paragraphAttributes, false); - const auto prepared = rn_gpui_prepare_text(flat, maximumSize.width); - if (prepared.handle == 0) { - return {}; - } - LoomTextMeasurement measurement; - measurement.preparedLayout = std::shared_ptr( - reinterpret_cast(prepared.handle), [](void* handle) { - rn_gpui_release_prepared(reinterpret_cast(handle)); - }); - LayoutConstraints constraints; - constraints.minimumSize = minimumSize; - constraints.maximumSize = maximumSize; - measurement.size = - constraints.clamp({.width = prepared.width, .height = prepared.height}); - measurement.valid = true; - return measurement; -} - -LoomTextMeasurement GpuiLoomTextServices::prepareTextForMount( - SurfaceId surfaceId, - const AttributedString& attributedString, - const ParagraphAttributes& paragraphAttributes, - const Size& minimumSize, - const Size& maximumSize) { - return prepareText( - surfaceId, - attributedString, - paragraphAttributes, - minimumSize, - maximumSize); -} - -GpuiLoomHost::GpuiLoomHost( - std::shared_ptr mountingManager, - std::shared_ptr contextContainer, - SchedulerAccess schedulerAccess, - JsAccess jsAccess) - : mountingManager_(std::move(mountingManager)), - contextContainer_(contextContainer), - schedulerAccess_(std::move(schedulerAccess)), - jsAccess_(std::move(jsAccess)), - text_( - contextContainer, - std::make_shared(contextContainer)), - imageManager_(std::make_shared(contextContainer)) { - active_.store(this, std::memory_order_release); - setMountPendingProbe(&GpuiLoomHost::pending); - LoomSettings::configurePlatform(kLoomPlatformDesktop); - if (std::getenv("RN_GPUI_LOOM_PROFILE") != nullptr) { - LoomSettings::set(LoomSettingId::ProfileWorker, 1); - } -} - -void GpuiLoomHost::connect() { - GpuiMountingManager::Routes routes; - routes.event = - [weak = weak_from_this()]( - Tag tag, const std::string& type, folly::dynamic&& payload) { - if (const auto self = weak.lock()) { - self->dispatchNativeEvent(tag, type, std::move(payload)); - } - }; - routes.wheel = [weak = weak_from_this()]( - Tag tag, uint64_t id, folly::dynamic&& payload) { - if (const auto self = weak.lock()) { - self->dispatchNativeWheel(tag, id, std::move(payload)); - } else { - rn_gpui_on_wheel_done(id, false); - } - }; - routes.geometry = [weak = weak_from_this()](Tag tag) { - const auto self = weak.lock(); - return self ? self->animatedGeometry(tag) - : std::optional{}; - }; - mountingManager_->setRoutes(std::move(routes)); -} - -GpuiLoomHost::~GpuiLoomHost() { - auto* expected = this; - active_.compare_exchange_strong(expected, nullptr); -} - -std::uint64_t GpuiLoomHost::pending() { - std::uint64_t count = pendingUiTasks_.load(std::memory_order_relaxed); - auto* host = active_.load(std::memory_order_acquire); - if (host == nullptr) { - return count; - } - // A read never blocks and finds nothing while a commit is being computed. - if (const auto runtime = loom::Runtime::from(*host->contextContainer_)) { - runtime->forEachSurface([&](SurfaceId surfaceId) { - if (!runtime->latest().surfaceSize(surfaceId)) { - ++count; - } - }); - } - return count; -} - -namespace { -// React names components by their view manager (`RCTText`); the descriptor -// registry knows them by Fabric name. The core classifies by the name a node -// was created with, so both spellings are listed. -LoomComponentTable componentTable() { - using Role = LoomComponentTable::Role; - auto table = LoomComponentTable::fabric(); - const auto add = [&](const char* name, - uint16_t roles, - LoomTextStateKind kind = LoomTextStateKind::Other) { - table.entries[name] = LoomComponentTable::Entry{roles, kind}; - }; - add("RCTView", Role::Box); - add("RCTText", Role::Paragraph, LoomTextStateKind::Paragraph); - add("RCTSelectableText", - Role::Paragraph, - LoomTextStateKind::SelectableParagraph); - add("RCTVirtualText", Role::VirtualText); - add("RCTRawText", Role::RawText); - add("RCTScrollView", Role::GenericStateWrapper); - // The core asks for a Fabric name's counterpart among the names JavaScript - // creates nodes with. - auto& host = table.hostNames; - host["View"] = "RCTView"; - host["Image"] = "RCTImageView"; - host["ScrollView"] = "RCTScrollView"; - host["Paragraph"] = "RCTText"; - host["SelectableParagraph"] = "RCTSelectableText"; - host["RawText"] = "RCTRawText"; - table.rawTextHostName = "RCTRawText"; - return table; -} -} // namespace - -LoomPlatformTraits GpuiLoomHost::traits() const { - LoomPlatformTraits traits; - traits.components = componentTable(); - traits.isUIThread = [] { - return loomUIIsMountThread() ? MountThread::shared().isCurrent() - : rn_gpui_is_main_thread(); - }; - traits.workerStackSize = kWorkerStackSize; - traits.workerThreadName = "loom-worker"; - // `sendsPropDiffs` stays null: an update carries every prop, and this host - // rebuilds a view from `operation.props` and clones compat props from - // nothing, which a diff would break. - traits.hasPreparedTextLayout = true; - traits.liveReadsOnAnyThread = true; - traits.insertsCarryInitialLayout = true; - traits.removesSubtreeRootOnly = true; - traits.parallelFor = [](size_t count, - const std::function& body) { - TextPool::shared().run(count, body); - }; - traits.setCurrentThreadName = [](const char* name) { - folly::setThreadName(name); - }; - traits.log = logLoom; - return traits; -} - -std::function)> GpuiLoomHost::uiExecutor() { - return [weak = weak_from_this()](std::function task) { - pendingUiTasks_.fetch_add(1, std::memory_order_relaxed); - postToLoomUI([weak, task = std::move(task)] { - if (const auto self = weak.lock()) { - std::shared_lock alive(self->lifetimeMutex_); - if (self->alive_) { - task(); - } - } - pendingUiTasks_.fetch_sub(1, std::memory_order_relaxed); - }); - }; -} - -bool GpuiLoomHost::ensureScheduler() { - if (registry_ != nullptr && eventManager_ != nullptr) { - return true; - } - schedulerAccess_([this](Scheduler& scheduler) { - registry_ = scheduler.getComponentDescriptorRegistry(); - if (auto dispatcher = scheduler.getEventDispatcher()) { - std::lock_guard events(eventMutex_); - eventDispatcher_ = dispatcher; - eventManager_ = std::make_shared(std::move(dispatcher)); - } - }); - return registry_ != nullptr; -} - -GpuiLoomHost::Node* GpuiLoomHost::find(Tag tag) { - const auto found = nodes_.find(tag); - return found == nodes_.end() ? nullptr : &found->second; -} - -const GpuiLoomHost::ComponentInfo* GpuiLoomHost::componentInfo( - const std::string& name) { - const auto found = components_.find(name); - if (found != components_.end()) { - return found->second.descriptor != nullptr ? &found->second : nullptr; - } - ComponentInfo info; - try { - const auto& descriptor = registry_->at(name); - info.descriptor = &descriptor; - info.name = descriptor.getComponentName(); - info.opName = componentNameStr(info.name); - info.handle = descriptor.getComponentHandle(); - info.traits = descriptor.getTraits(); - const std::string_view fabricName = info.name; - info.kind = fabricName == "View" ? Kind::View - : fabricName == "Paragraph" ? Kind::Paragraph - : fabricName == "Image" ? Kind::Image - : fabricName == "ScrollView" ? Kind::ScrollView - : fabricName == "TextInput" ? Kind::TextInput - : fabricName == "ModalHostView" ? Kind::Modal - : Kind::Compat; - if (info.kind == Kind::Compat) { - if (rngpui::anyHostComponents()) { - info.host = rngpui::hostComponentEntry(info.handle); - } - const auto& hooks = gpuiExtensionHooks().componentProps; - if (const auto hook = hooks.find(std::string(fabricName)); - hook != hooks.end()) { - info.hook = &hook->second; - } - } - } catch (const std::exception& error) { - LOG(ERROR) << "Loom: no component descriptor for " << name << ": " - << error.what(); - } - const auto inserted = components_.emplace(name, info).first; - return info.descriptor != nullptr ? &inserted->second : nullptr; -} - -void GpuiLoomHost::markDirty(Node& node, Tag tag, std::uint8_t bits) { - node.dirty |= bits; - if ((node.dirty & kQueued) == 0) { - node.dirty |= kQueued; - dirtyTags_.push_back(tag); - } -} - -EventEmitter::Shared GpuiLoomHost::makeEmitter(const Node& node, Tag tag) { - InstanceHandle::Shared handle; - { - std::lock_guard events(eventMutex_); - const auto found = instanceHandles_.find(tag); - if (found == instanceHandles_.end()) { - return nullptr; - } - handle = found->second.handle; - } - auto family = node.info->descriptor->createFamily( - ShadowNodeFamilyFragment{tag, node.surfaceId, std::move(handle)}); - auto emitter = family->getEventEmitter(); - emitter->getEventTarget()->setEnabled(true); - families_[tag] = std::move(family); - return emitter; -} - -// What a mount observer or a prop extractor reads of a node: its identity, -// geometry and, for a compat component, its typed props and state. -ShadowView GpuiLoomHost::lightView(const Node& node, Tag tag) const { - ShadowView view; - view.componentName = node.info->name; - view.componentHandle = node.info->handle; - view.traits = node.info->traits; - view.surfaceId = node.surfaceId; - view.tag = tag; - auto& metrics = view.layoutMetrics; - metrics.frame = { - {node.frame[0], node.frame[1]}, {node.frame[2], node.frame[3]}}; - metrics.displayType = static_cast(node.displayType); - metrics.layoutDirection = node.direction == 2 ? LayoutDirection::RightToLeft - : LayoutDirection::LeftToRight; - metrics.pointScaleFactor = pointScaleFactor_; - metrics.contentInsets = { - node.insets[0], node.insets[1], node.insets[2], node.insets[3]}; - if (node.compat) { - view.props = node.compat->props; - view.state = node.compat->state; - } - return view; -} - -namespace { -// Turns what an image request reports into the Image component's events. -class LoomImageObserver final : public ImageResponseObserver { - public: - LoomImageObserver( - std::weak_ptr host, - Tag tag, - ImageSource source) - : host_(std::move(host)), tag_(tag), source_(std::move(source)) {} - - void didReceiveProgress(float progress, int64_t loaded, int64_t total) - const override { - send( - "topProgress", - folly::dynamic::object("progress", progress)( - "loaded", static_cast(loaded))( - "total", static_cast(total))); - } - - void didReceiveImage(const ImageResponse& response) const override { - auto source = source_; - if (auto size = std::static_pointer_cast(response.getImage())) { - source.size = *size; - source.scale = 1; - } - send( - "topLoad", - folly::dynamic::object( - "source", - folly::dynamic::object("uri", source.uri)( - "width", source.size.width * source.scale)( - "height", source.size.height * source.scale))); - send("topLoadEnd", folly::dynamic::object()); - } - - void didReceiveFailure(const ImageLoadError& error) const override { - folly::dynamic payload = folly::dynamic::object(); - if (auto message = std::static_pointer_cast(error.getError()); - message && !message->empty()) { - payload["error"] = *message; - } - send("topError", std::move(payload)); - send("topLoadEnd", folly::dynamic::object()); - } - - private: - void send(const char* type, folly::dynamic&& payload) const { - if (const auto host = host_.lock()) { - host->dispatchTargetEvent(tag_, type, std::move(payload)); - } - } - - std::weak_ptr host_; - Tag tag_; - ImageSource source_; -}; -} // namespace - -// An Image asks for its picture at the size it was laid out at, and again when -// the size or the source changes. -void GpuiLoomHost::syncImage(Node& node, Tag tag) { - auto& ext = *node.ext; - const Size contentSize{ - std::max(0.f, node.frame[2] - node.insets[0] - node.insets[2]), - std::max(0.f, node.frame[3] - node.insets[1] - node.insets[3])}; - const auto scale = pointScaleFactor_; - ImageSource source{ImageSource::Type::Invalid}; - if (ext.sources.size() == 1) { - source = ext.sources.front(); - source.size = contentSize; - source.scale = scale; - } else if (!ext.sources.empty()) { - const auto targetArea = - contentSize.width * contentSize.height * scale * scale; - auto bestFit = std::numeric_limits::infinity(); - for (const auto& candidate : ext.sources) { - const auto candidateScale = - candidate.scale == 0 ? scale : candidate.scale; - const auto candidateArea = candidate.size.width * candidate.size.height * - candidateScale * candidateScale; - const auto fit = std::abs(1 - candidateArea / targetArea); - if (fit < bestFit) { - bestFit = fit; - source = candidate; - } - } - source.size = contentSize; - source.scale = scale; - } - const ImageRequestParams params{ext.blurRadius}; - if (ext.requested && *ext.requested == source && - ext.requestedParams == params) { - return; - } - if (const auto found = imageObservations_.find(tag); - found != imageObservations_.end()) { - found->second.coordinator->removeObserver(found->second.observer); - imageObservations_.erase(found); - } - ext.request = std::make_unique( - imageManager_->requestImage(source, node.surfaceId, params, tag)); - ext.requested = source; - ext.requestedParams = params; - auto coordinator = ext.request->getSharedObserverCoordinator(); - auto observer = - std::make_shared(weak_from_this(), tag, source); - if (source.type != ImageSource::Type::Invalid) { - dispatchTargetEvent(tag, "topLoadStart", folly::dynamic::object()); - } - coordinator->addObserver(observer); - imageObservations_[tag] = {std::move(coordinator), std::move(observer)}; -} - -void GpuiLoomHost::reportModal(Node& node, Tag tag, bool visible) { - if (node.ext->shown == visible) { - return; - } - node.ext->shown = visible; - dispatchTargetEvent( - tag, visible ? "topShow" : "topDismiss", folly::dynamic::object()); -} - -void GpuiLoomHost::drop(Tag tag) { - { - std::lock_guard events(eventMutex_); - earlyLayouts_.erase(tag); - pendingEvents_.erase(tag); - } - decltype(nodes_)::node_type node; - { - std::lock_guard scroll(scrollMutex_); - node = nodes_.extract(tag); - scrollOffsets_.erase(tag); - } - viewless_.erase(tag); - pendingEffects_.erase(tag); - mountingManager_->clearComponentState(tag); - if (const auto found = imageObservations_.find(tag); - found != imageObservations_.end()) { - found->second.coordinator->removeObserver(found->second.observer); - imageObservations_.erase(found); - } -} - -// A node that goes away while the mounting side still holds it is deleted -// there first. -void GpuiLoomHost::retire(Tag tag) { - auto* node = find(tag); - if (node != nullptr && node->created) { - if (node->ext && node->info->kind == Kind::Modal) { - reportModal(*node, tag, false); - } - structural_.push_back( - {Structural::Delete, - node->surfaceId, - tag, - -1, - -1, - node->info, - node->ext ? node->ext->sent : std::string{}}); - } - drop(tag); -} - -void GpuiLoomHost::parseView( - const PropsParserContext& context, - Node& node, - const folly::dynamic& props) { - const bool wasSelectable = node.flags.selectable; - node.deps.reset(); - node.flags = {}; - auto view = std::make_unique(); - initLoomView(*view); - parseLoomViewProps(context, props, *view, node.flags, node.deps); - node.parsed = std::move(view); - if (node.created && wasSelectable != node.flags.selectable) { - node.dirty |= kSelectable; - } - switch (node.info->kind) { - case Kind::Image: { - auto image = parseLoomImage(context, props); - node.ext->body = std::move(image.body); - node.ext->sources = std::move(image.sources); - node.ext->blurRadius = image.blurRadius; - break; - } - case Kind::ScrollView: - node.ext->body = parseLoomScrollView(context, props); - break; - case Kind::TextInput: { - auto input = parseLoomTextInput(context, props); - node.ext->body = std::move(input.body); - // An empty input has no fragment, so the placeholder and the caret would - // not know the font and color the typed text will have. - ParagraphAttributes attributes; - auto attrs = text_.parseTextAttributes( - node.surfaceId, "TextInput", props, TextAttributes{}, attributes); - attrs.fontSizeMultiplier = 1.f; - node.ext->fallback = flattenTextFragment(attrs, ""); - break; - } - case Kind::Modal: { - node.ext->visible = parseLoomModalVisible(props); - JsonBody json; - json.boolean("visible", node.ext->visible); - node.ext->body = json.body(); - break; - } - default: - break; - } -} - -void GpuiLoomHost::onCreate( - const PropsParserContext& context, - const DirectCreateOperation& operation) { - const auto tag = operation.tag; - if (find(tag) != nullptr) { - retire(tag); - } - viewless_.erase(tag); - if (!operation.layoutable) { - viewless_.insert(tag); - pendingEffects_.erase(tag); - return; - } - const auto* info = componentInfo(operation.componentName); - if (info == nullptr) { - viewless_.insert(tag); - pendingEffects_.erase(tag); - return; - } - Node node; - node.surfaceId = context.surfaceId; - node.info = info; - PendingEffects pending; - bool hasPending = false; - if (const auto found = pendingEffects_.find(tag); - found != pendingEffects_.end()) { - pending = std::move(found->second); - pendingEffects_.erase(found); - hasPending = true; - } - const bool carriesExt = info->kind != Kind::View && - info->kind != Kind::Paragraph && - (info->kind != Kind::Compat || info->hook != nullptr); - if (carriesExt) { - node.ext = std::make_unique(); - } - if (info->kind == Kind::Compat) { - node.compat = std::make_unique(); - node.compat->props = operation.parsedProps != nullptr - ? operation.parsedProps - : info->descriptor->cloneProps( - context, nullptr, RawProps(operation.props)); - if (hasPending) { - node.compat->state = pending.state; - } - node.compat->emitter = makeEmitter(node, tag); - } - if (hasPending && pending.state) { - mountingManager_->setComponentState( - tag, info->name, info->handle, pending.state); - } - parseView(context, node, operation.props); - if (hasPending) { - if (pending.text) { - node.text = std::move(pending.text); - } - if (node.ext && pending.hasScrollState) { - node.ext->hasScrollState = true; - node.ext->offset = pending.offset; - node.ext->content = pending.content; - } - } - Node* stored = nullptr; - { - std::lock_guard scroll(scrollMutex_); - stored = &nodes_.emplace(tag, std::move(node)).first->second; - } - markDirty(*stored, tag, 0); -} - -void GpuiLoomHost::onUpdateProps( - const PropsParserContext& context, - const DirectUpdatePropsOperation& operation) { - auto* node = find(operation.tag); - if (node == nullptr) { - return; - } - if (node->compat) { - node->compat->props = operation.parsedProps != nullptr - ? operation.parsedProps - : node->info->descriptor->cloneProps( - context, nullptr, RawProps(operation.props)); - } - parseView(context, *node, operation.props); - markDirty(*node, operation.tag, 0); -} - -void GpuiLoomHost::applyBatch(SurfaceId surfaceId, LoomMountBatch batch) { - std::lock_guard lock(mutex_); - if (!ensureScheduler()) { - return; - } - const PropsParserContext context{surfaceId, *contextContainer_}; - - // A tag deleted and created again in one batch: the old node goes first, and - // the delete that follows must leave the new one alone. - std::unordered_set replaced; - if (batch.requiresTagReplacement) { - std::unordered_set deleted; - for (const auto index : - batch.phaseOperationIndexes[LoomMountBatch::Deletes]) { - deleted.insert( - std::get(batch.operations[index]).tag); - } - for (const auto index : - batch.phaseOperationIndexes[LoomMountBatch::CreateAndProps]) { - if (const auto* created = - std::get_if(&batch.operations[index])) { - if (deleted.count(created->tag) != 0) { - replaced.insert(created->tag); - } - } - } - for (const auto tag : replaced) { - retire(tag); - } - } - - const auto layout = [&](Tag tag, - Tag parent, - int displayType, - int layoutDirection, - float x, - float y, - float width, - float height) { - auto* node = find(tag); - if (node == nullptr) { - return; - } - const std::array frame{x, y, width, height}; - std::uint8_t bits = 0; - { - std::lock_guard scroll(scrollMutex_); - if (node->frame != frame) { - node->frame = frame; - bits |= kFrame; - } - node->parent = parent; - node->laidOut = true; - } - if (node->displayType != displayType) { - node->displayType = static_cast(displayType); - bits |= kDisplay; - } - if (node->direction != layoutDirection) { - node->direction = static_cast(layoutDirection); - bits |= kDirection; - } - if (bits != 0) { - markDirty(*node, tag, bits); - } - }; - - auto apply = [&](const auto& operation) { - using Operation = std::decay_t; - if constexpr (std::is_same_v) { - onCreate(context, operation); - } else if constexpr (std:: - is_same_v) { - onUpdateProps(context, operation); - } else if constexpr (std::is_same_v) { - if (auto* node = find(operation.tag); node != nullptr && node->created) { - structural_.push_back( - {Structural::Remove, - node->surfaceId, - operation.tag, - operation.parentTag, - static_cast(operation.index), - node->info, - {}}); - } - } else if constexpr (std::is_same_v) { - if (auto* node = find(operation.tag)) { - { - std::lock_guard scroll(scrollMutex_); - node->parent = operation.parentTag; - } - if (operation.hasLayout) { - layout( - operation.tag, - operation.parentTag, - operation.displayType, - operation.layoutDirection, - operation.x, - operation.y, - operation.width, - operation.height); - if (node->created) { - node->layoutBits |= kInsertLayout; - } - } - structural_.push_back( - {Structural::Insert, - node->surfaceId, - operation.tag, - operation.parentTag, - static_cast(operation.index), - node->info, - {}}); - } - } else if constexpr (std::is_same_v) { - if (auto* node = find(operation.tag); - node != nullptr && node->insets != operation.insets) { - node->insets = operation.insets; - markDirty(*node, operation.tag, kInsets); - } - } else if constexpr (std::is_same_v) { - layout( - operation.tag, - operation.parentTag, - operation.displayType, - operation.layoutDirection, - operation.x, - operation.y, - operation.width, - operation.height); - } else if constexpr (std::is_same_v) { - if (replaced.count(operation.tag) == 0) { - retire(operation.tag); - } - } - // Overflow insets do not reach the Rust store. - }; - - for (const auto& phase : batch.phaseOperationIndexes) { - for (const auto index : phase) { - std::visit(apply, batch.operations[index]); - } - } - flushLocked(); -} - -namespace { - -// Keeps a scratch vector's capacity for the next flush, unless a much larger -// past flush left it: a large mount must not pin its peak. -template -void releaseScratch(std::vector& scratch) { - constexpr size_t kKeep = 4096; - if (scratch.capacity() > kKeep && scratch.size() * 8 < scratch.capacity()) { - std::vector smaller; - smaller.reserve(std::max(kKeep, scratch.size() * 2)); - std::move(scratch.begin(), scratch.end(), std::back_inserter(smaller)); - scratch = std::move(smaller); - } -} - -} // namespace - -// Delivers the tree changes the operations recorded, then a create or an update -// for every node that changed, as one batch per surface. -void GpuiLoomHost::flushLocked() { - flushScheduled_ = false; - // Taken out of the members, so a flush that runs inside this one (an event - // delivered synchronously) gets its own. - auto batches = std::move(batches_); - auto updates = std::move(updates_); - auto insertLayouts = std::move(insertLayouts_); - batches.clear(); - updates.clear(); - insertLayouts.clear(); - const auto batchOf = [&](SurfaceId surfaceId) -> MountBatch& { - for (auto& [id, batch] : batches) { - if (id == surfaceId) { - return batch; - } - } - auto& batch = - batches.emplace_back(surfaceId, mountingManager_->beginBatch(surfaceId)) - .second; - // At most one op per tree change and per changed node; sized once so a - // large mount does not grow the vector (and copy its ops) a dozen times. - if (batches.size() == 1) { - batch.ops.reserve(structural_.size() + dirtyTags_.size()); - } - return batch; - }; - const bool observed = !gpuiExtensionHooks().mountObservers.empty(); - - const auto structuralOp = [&](Structural& entry) { - auto& ops = batchOf(entry.surfaceId).ops; - ops.emplace_back(); - auto& op = ops.back(); - op.kind = entry.kind == Structural::Remove ? MountKind::Remove - : entry.kind == Structural::Insert ? MountKind::Insert - : MountKind::Delete; - op.tag = entry.tag; - op.parent_tag = entry.parent; - op.index = entry.index; - op.component = entry.info->opName; - op.host_index = -1; - if (entry.kind == Structural::Insert) { - if (auto* node = find(entry.tag)) { - op.frame = { - node->frame[0], node->frame[1], node->frame[2], node->frame[3]}; - if (node->ext) { - op.extension_props_json = node->ext->sent; - } - if ((node->layoutBits & kInsertLayoutQueued) != 0) { - const auto dirty = node->dirty; - node->dirty = 0; - node->layoutBits &= kWaited; - op.layout_changed = (dirty & kFrame) != 0; - buildViewOp(*node, dirty, op); - } - if (observed) { - mountingManager_->notifyFrameChanged( - entry.surfaceId, lightView(*node, entry.tag)); - } - } - } else if (entry.kind == Structural::Delete) { - op.extension_props_json = std::move(entry.json); - mountingManager_->notifyDeleted(entry.tag); - } - }; - - for (auto& entry : structural_) { - if (entry.kind == Structural::Remove) { - structuralOp(entry); - } - } - for (auto& entry : structural_) { - if (entry.kind == Structural::Delete) { - structuralOp(entry); - } - } - - constexpr std::uint8_t kLayoutBits = - kFrame | kInsets | kDisplay | kDirection | kQueued; - std::vector reports; - // The nodes that wait for their emitter stay queued, compacted to the front. - size_t held = 0; - for (size_t i = 0; i < dirtyTags_.size(); ++i) { - const auto tag = dirtyTags_[i]; - auto* node = find(tag); - if (node == nullptr) { - continue; - } - if (node->created) { - // A view whose only change is its first frame has it applied by its - // insert. - if ((node->layoutBits & kInsertLayout) != 0 && - node->info->kind == Kind::View && node->parsed == nullptr && - (node->dirty & ~kLayoutBits) == 0) { - node->layoutBits |= kInsertLayoutQueued; - insertLayouts.push_back(tag); - } else { - updates.push_back(tag); - } - } else if (awaitsEmitter(*node)) { - node->layoutBits |= kWaited; - dirtyTags_[held++] = tag; - } else { - flushNode(*node, tag, batchOf(node->surfaceId), reports); - } - } - dirtyTags_.resize(held); - releaseScratch(dirtyTags_); - - size_t carried = 0; - for (size_t i = 0; i < structural_.size(); ++i) { - auto& entry = structural_[i]; - if (entry.kind != Structural::Insert) { - continue; - } - const auto* inserted = find(entry.tag); - const auto* parent = find(entry.parent); - if ((inserted != nullptr && !inserted->created) || - (parent != nullptr && !parent->created)) { - if (carried != i) { - structural_[carried] = std::move(entry); - } - ++carried; - continue; - } - structuralOp(entry); - } - structural_.erase( - structural_.begin() + static_cast(carried), - structural_.end()); - releaseScratch(structural_); - // An insert that waits for its parent leaves the frame to an update. - for (const auto tag : insertLayouts) { - if (auto* node = find(tag); - node != nullptr && (node->layoutBits & kInsertLayoutQueued) != 0) { - node->layoutBits &= static_cast(~kInsertLayoutQueued); - updates.push_back(tag); - } - } - - for (const auto tag : updates) { - if (auto* node = find(tag)) { - flushNode(*node, tag, batchOf(node->surfaceId), reports); - } - } - - for (auto& [surfaceId, batch] : batches) { - if (!batch.ops.empty()) { - mountingManager_->submitBatch(surfaceId, std::move(batch)); - } - } - batches.clear(); - updates.clear(); - insertLayouts.clear(); - releaseScratch(updates); - releaseScratch(insertLayouts); - batches_ = std::move(batches); - updates_ = std::move(updates); - insertLayouts_ = std::move(insertLayouts); - for (const auto tag : reports) { - if (auto* node = find(tag)) { - reportTextLayout(*node, tag); - } - } -} - -// A host component is created with its event emitter, which needs the instance -// handle Loom registers; until it arrives the node, and what is inserted into -// it, wait for one flush. After that it mounts without, and gets the emitter -// with an update. -bool GpuiLoomHost::awaitsEmitter(const Node& node) const { - return node.compat && node.compat->emitter == nullptr && - node.info->host != nullptr && (node.layoutBits & kWaited) == 0; -} - -// The extension props of an image, a scroll view, an input or a modal: its own -// props and what the host knows of its state; for a compat component, what its -// registered extractor makes of the typed props. -std::string GpuiLoomHost::extensionJson(Node& node, Tag tag) { - if (node.info->kind == Kind::Compat) { - return (*node.info->hook)(node.info->name, lightView(node, tag)); - } - auto& ext = *node.ext; - std::string extra; - if (node.info->kind == Kind::ScrollView && ext.hasScrollState) { - JsonBody state; - state.number("contentWidth", ext.content[0]); - state.number("contentHeight", ext.content[1]); - state.number("offsetX", ext.offset[0]); - state.number("offsetY", ext.offset[1]); - extra = state.body(); - } - return closeJson(ext.body, extra); -} - -// What a node sends: the whole view when its props changed, else only the -// groups layout touched. -void GpuiLoomHost::buildViewOp(Node& node, std::uint8_t dirty, MountOp& op) { - const bool create = op.kind == MountKind::Create; - const Size frameSize{node.frame[2], node.frame[3]}; - const bool rtl = node.direction == 2; - const auto* deps = node.deps.get(); - if (node.parsed != nullptr) { - op.props_changed = true; - op.view = std::move(*node.parsed); - node.parsed.reset(); - op.view.content_insets = { - node.insets[0], node.insets[1], node.insets[2], node.insets[3]}; - op.view.display_none = node.displayType == 0; - resolveLoomViewLayout( - op.view, - deps, - frameSize, - rtl, - kPatchRadii | kPatchWidths | kPatchTransform); - } else if (!create) { - std::uint8_t patch = 0; - if ((dirty & (kInsets | kDisplay)) != 0) { - patch |= kPatchInsets; - op.view.content_insets = { - node.insets[0], node.insets[1], node.insets[2], node.insets[3]}; - op.view.display_none = node.displayType == 0; - } - if (deps != nullptr) { - std::uint8_t mask = 0; - if ((dirty & kFrame) != 0) { - mask |= (deps->radiiPercent ? kPatchRadii : 0) | - (deps->transform.operations.empty() && - !deps->transformOrigin.isSet() - ? 0 - : kPatchTransform); - } - if ((dirty & kDirection) != 0 && deps->widthsDirectional) { - mask |= kPatchWidths; - } - if (mask != 0) { - resolveLoomViewLayout(op.view, deps, frameSize, rtl, mask); - patch |= mask; - } - } - op.layout_patch = patch; - } -} - -void GpuiLoomHost::flushNode( - Node& node, - Tag tag, - MountBatch& batch, - std::vector& reports) { - const bool create = !node.created; - const bool frameChanged = (node.dirty & kFrame) != 0; - const auto dirty = node.dirty; - node.dirty = 0; - node.layoutBits &= kWaited; - node.created = true; - const auto kind = node.info->kind; - - batch.ops.emplace_back(); - auto& op = batch.ops.back(); - op.kind = create ? MountKind::Create : MountKind::Update; - op.tag = tag; - op.parent_tag = create ? -1 : node.parent; - op.index = -1; - op.component = node.info->opName; - op.host_index = -1; - op.frame = {node.frame[0], node.frame[1], node.frame[2], node.frame[3]}; - op.layout_changed = create || frameChanged; - // What the extension props are made from: the node's props (parsed into - // `ext->body`), its state, and for a component with an extractor the frame. - const bool extChanged = create || node.parsed != nullptr || - (dirty & kState) != 0 || - (kind == Kind::Compat && - ((dirty & kFrame) != 0 || node.compat->props != node.compat->sentProps || - node.compat->state != node.compat->sentState)); - buildViewOp(node, dirty, op); - - if (node.ext) { - if (kind == Kind::Image) { - syncImage(node, tag); - } - if (extChanged) { - auto json = extensionJson(node, tag); - // The mounting side takes the extension props with a changed view, or - // with this patch alone. - if (!op.props_changed && json != node.ext->sent) { - op.layout_patch |= 32; - } - op.extension_props_json = json; - node.ext->sent = std::move(json); - } else { - op.extension_props_json = node.ext->sent; - } - if (kind == Kind::Modal) { - reportModal(node, tag, node.ext->visible); - } - } - - if (kind == Kind::Paragraph) { - if (node.flags.onTextLayout) { - reports.push_back(tag); - } - if (create || (dirty & kText) != 0) { - op.has_paragraph = true; - if (node.text && node.text->string) { - op.paragraph = flattenParagraphText( - *node.text->string, node.text->attributes, node.flags.selectable); - } else { - op.paragraph.selectable = node.flags.selectable; - } - if (node.text && node.text->prepared) { - op.paragraph.prepared = rn_gpui_retain_prepared( - reinterpret_cast(node.text->prepared.get())); - op.paragraph.prepared_width = node.text->preparedWidth; - } - if (!node.flags.onTextLayout) { - node.text.reset(); - } - } else if ((dirty & kSelectable) != 0) { - op.layout_patch |= 16; - op.paragraph.selectable = node.flags.selectable; - } - } else if (kind == Kind::TextInput) { - if (create || (dirty & kText) != 0 || op.props_changed) { - op.has_paragraph = true; - if (node.text && node.text->string) { - op.paragraph = flattenInputText(*node.text->string); - } - if (op.paragraph.fragments.empty()) { - op.paragraph.fragments.push_back(node.ext->fallback); - } - } - } else if (kind == Kind::Compat) { - auto& compat = *node.compat; - if (node.info->host != nullptr) { - const auto& entry = *node.info->host; - op.host_index = static_cast(entry.index); - if (create && compat.emitter == nullptr) { - compat.lateEmitter = true; - op.host_props_handle = rngpui::makeHostPropsHandle(compat.props); - rn_gpui_log( - 2, - "loom: " + std::string(node.info->name) + " (tag " + - std::to_string(tag) + - ") mounts before its event target registered; it gets its " - "emitter when it does"); - } else if (create) { - op.host_props_handle = rngpui::makeHostPropsHandle(compat.props); - op.host_emitter_handle = rngpui::makeHostEmitterHandle(compat.emitter); - } else if (compat.lateEmitter && compat.emitter != nullptr) { - compat.lateEmitter = false; - op.host_props_handle = rngpui::makeHostPropsHandle(compat.props); - op.host_emitter_handle = rngpui::makeHostEmitterHandle(compat.emitter); - op.host_changed = ~uint64_t{0}; - } else if ( - compat.sentProps && compat.props && - compat.sentProps.get() != compat.props.get()) { - uint64_t inlineWords[2] = {0, 0}; - std::vector heapWords; - uint64_t* words = inlineWords; - if (entry.changeWords > 2) { - heapWords.assign(entry.changeWords, 0); - words = heapWords.data(); - } - entry.changed(*compat.sentProps, *compat.props, words); - bool any = false; - for (uint32_t word = 0; word < entry.changeWords; ++word) { - any = any || words[word] != 0; - } - if (any) { - op.host_props_handle = rngpui::makeHostPropsHandle(compat.props); - op.host_changed = words[0]; - for (uint32_t word = 1; word < entry.changeWords; ++word) { - op.host_changed_more.push_back(words[word]); - } - } - } - } - compat.sentProps = compat.props; - compat.sentState = compat.state; - } - if (!create && frameChanged && !gpuiExtensionHooks().mountObservers.empty()) { - mountingManager_->notifyFrameChanged(node.surfaceId, lightView(node, tag)); - } -} - -// Fabric's paragraph reports its wrapped lines after each layout. -void GpuiLoomHost::reportTextLayout(Node& node, Tag tag) { - if (!node.text || !node.text->string) { - return; - } - auto& text = *node.text; - const Size size{node.frame[2], node.frame[3]}; - if (text.reportedString == text.string && text.reportedSize == size) { - return; - } - text.reportedString = text.string; - text.reportedSize = size; - folly::dynamic lines = folly::dynamic::array(); - for (const auto& line : text_.layoutManager()->measureLines( - AttributedStringBox{*text.string}, text.attributes, size)) { - lines.push_back(folly::dynamic::object("text", line.text)( - "x", line.frame.origin.x)("y", line.frame.origin.y)( - "width", line.frame.size.width)("height", line.frame.size.height)( - "descender", line.descender)("capHeight", line.capHeight)( - "ascender", line.ascender)("xHeight", line.xHeight)); - } - dispatchTargetEvent( - tag, "topTextLayout", folly::dynamic::object("lines", std::move(lines))); -} - -void GpuiLoomHost::scheduleFlush() { - if (flushScheduled_) { - return; - } - flushScheduled_ = true; - postToLoomUI([weak = weak_from_this()] { - if (auto self = weak.lock()) { - std::lock_guard lock(self->mutex_); - if (self->flushScheduled_) { - self->flushLocked(); - } - } - }); -} - -void GpuiLoomHost::runOnUIThread(std::function task) { - if (loomUIIsMountThread()) { - MountThread::shared().post(std::move(task)); - } else { - task(); - } -} - -void GpuiLoomHost::failSurface(SurfaceId surfaceId, const std::string& reason) { - LOG(ERROR) << "Loom stopped surface " << surfaceId << ": " << reason; -} - -void GpuiLoomHost::updateViewProps(Tag tag, const folly::dynamic& props) { - LoomBinding::recordNativeProps(tag, props); - mountingManager_->synchronouslyUpdateViewOnUIThread(tag, props); -} - -std::optional -GpuiLoomHost::animatedGeometry(Tag tag) { - std::lock_guard lock(mutex_); - const auto* node = find(tag); - if (node == nullptr) { - return std::nullopt; - } - GpuiMountingManager::AnimatedGeometry geometry{ - {node->frame[2], node->frame[3]}, {}}; - if (node->deps) { - geometry.transformOrigin = node->deps->transformOrigin; - } - return geometry; -} - -void GpuiLoomHost::registerEventTarget( - SurfaceId surfaceId, - Tag tag, - InstanceHandle::Shared instanceHandle) { - if (!instanceHandle) { - return; - } - std::lock_guard lock(mutex_); - if (!ensureScheduler()) { - return; - } - std::shared_ptr manager; - { - std::lock_guard events(eventMutex_); - instanceHandles_[tag] = {surfaceId, instanceHandle}; - manager = eventManager_; - } - manager->registerTarget(surfaceId, tag, instanceHandle); - std::optional early; - std::vector> pending; - { - std::lock_guard events(eventMutex_); - if (const auto found = earlyLayouts_.find(tag); - found != earlyLayouts_.end()) { - early = found->second; - earlyLayouts_.erase(found); - } - if (const auto found = pendingEvents_.find(tag); - found != pendingEvents_.end()) { - pending = std::move(found->second); - pendingEvents_.erase(found); - } - } - for (auto& [type, payload] : pending) { - manager->dispatch( - surfaceId, - tag, - type, - std::move(payload), - RawEvent::Category::Unspecified, - false, - HighResTimeStamp::now()); - } - if (early) { - manager->dispatch( - surfaceId, - tag, - "topLayout", - folly::dynamic::object( - "layout", - folly::dynamic::object("x", early->x)("y", early->y)( - "width", early->width)("height", early->height)), - RawEvent::Category::Unspecified, - false, - HighResTimeStamp::now()); - } - if (auto* node = find(tag); node != nullptr && node->compat) { - node->compat->emitter = makeEmitter(*node, tag); - markDirty(*node, tag, 0); - scheduleFlush(); - } -} - -// A node's instance handle wraps a weak JavaScript object, which JSI only lets -// go of on the JavaScript thread. The emitters the Rust store holds can outlive -// the node, so they are disabled (which drops their event target), and the -// references this host holds are released on the JavaScript thread. -void GpuiLoomHost::unregisterEventTarget(SurfaceId surfaceId, Tag tag) { - unregisterEventTargets(surfaceId, {tag}); -} - -void GpuiLoomHost::unregisterEventTargets( - SurfaceId surfaceId, - const std::vector& tags) { - struct Released { - Tag tag; - InstanceHandle::Shared handle; - ShadowNodeFamily::Shared family; - std::shared_ptr wheelTarget; - }; - std::vector released; - released.reserve(tags.size()); - std::shared_ptr manager; - { - std::lock_guard lock(mutex_); - std::lock_guard events(eventMutex_); - manager = eventManager_; - for (const auto tag : tags) { - pendingEvents_.erase(tag); - Released target{tag, nullptr, nullptr, nullptr}; - if (const auto found = instanceHandles_.find(tag); - found != instanceHandles_.end()) { - target.handle = std::move(found->second.handle); - instanceHandles_.erase(found); - } - if (const auto found = wheelTargets_.find(tag); - found != wheelTargets_.end()) { - target.wheelTarget = std::move(found->second); - wheelTargets_.erase(found); - } - if (const auto found = families_.find(tag); found != families_.end()) { - target.family = std::move(found->second); - families_.erase(found); - target.family->getEventEmitter()->setEnabled(false); - } - released.push_back(std::move(target)); - } - } - jsAccess_([surfaceId, - manager = std::move(manager), - released = std::move(released)] { - if (manager) { - for (const auto& target : released) { - manager->unregisterTarget(surfaceId, target.tag); - } - } - }); -} - -void GpuiLoomHost::dispatchEvent( - SurfaceId surfaceId, - Tag tag, - const std::string& eventName, - folly::dynamic payload, - RawEvent::Category category, - bool unique) { - std::shared_ptr manager; - { - std::lock_guard events(eventMutex_); - manager = eventManager_; - } - if (manager) { - manager->dispatch( - surfaceId, - tag, - eventName, - std::move(payload), - category, - unique, - HighResTimeStamp::now()); - } -} - -// An event from the GPUI side goes the way Loom's own events do, to the target -// registered for the tag. -void GpuiLoomHost::dispatchTargetEvent( - Tag tag, - const std::string& type, - folly::dynamic&& payload) { - std::shared_ptr manager; - SurfaceId surfaceId; - { - std::lock_guard events(eventMutex_); - const auto found = instanceHandles_.find(tag); - if (!eventManager_) { - return; - } - if (found == instanceHandles_.end()) { - auto& queue = pendingEvents_[tag]; - if (queue.size() < 16) { - queue.emplace_back(type, std::move(payload)); - } - return; - } - surfaceId = found->second.surfaceId; - manager = eventManager_; - } - manager->dispatch( - surfaceId, - tag, - type, - std::move(payload), - RawEvent::Category::Unspecified, - false, - HighResTimeStamp::now()); -} - -// An event from the GPUI side goes the way Loom's own events do, to the target -// registered for the tag. -void GpuiLoomHost::dispatchNativeEvent( - Tag tag, - const std::string& type, - folly::dynamic&& payload) { - std::shared_ptr manager; - SurfaceId surfaceId; - { - std::lock_guard events(eventMutex_); - const auto found = instanceHandles_.find(tag); - if (found == instanceHandles_.end() || !eventManager_) { - // The node mounts before Loom registers its target; the layout it was - // given at mount is what React is waiting for. - if (type == "topLayout" && payload.isObject()) { - if (const auto* layout = payload.get_ptr("layout"); - layout != nullptr && layout->isObject()) { - const auto number = [&](const char* key) { - const auto* value = layout->get_ptr(key); - return value != nullptr && value->isNumber() - ? static_cast(value->asDouble()) - : 0.f; - }; - earlyLayouts_[tag] = { - number("x"), number("y"), number("width"), number("height")}; - } - } - return; - } - surfaceId = found->second.surfaceId; - manager = eventManager_; - } - // Only the latest scroll position matters: a queued scroll event that JS has - // not handled yet is replaced rather than piled up behind. - manager->dispatch( - surfaceId, - tag, - EventEmitter::normalizeEventType(type), - std::move(payload), - RawEvent::Category::Unspecified, - type == "topScroll", - HighResTimeStamp::now()); -} - -void GpuiLoomHost::dispatchNativeWheel( - Tag tag, - std::uint64_t id, - folly::dynamic&& payload) { - std::shared_ptr target; - EventDispatcher::Weak dispatcher; - { - std::lock_guard events(eventMutex_); - const auto entry = instanceHandles_.find(tag); - if (entry == instanceHandles_.end()) { - rn_gpui_on_wheel_done(id, false); - return; - } - auto& wheel = wheelTargets_[tag]; - if (!wheel) { - wheel = std::make_shared( - entry->second.handle, entry->second.surfaceId); - wheel->setEnabled(true); - } - target = wheel; - dispatcher = eventDispatcher_; - } - GpuiMountingManager::dispatchWheelTo( - EventEmitter(std::move(target), std::move(dispatcher)), - id, - std::move(payload)); -} - -void GpuiLoomHost::updateComponentState( - SurfaceId /*surfaceId*/, - Tag tag, - const std::shared_ptr& state) { - std::lock_guard lock(mutex_); - if (viewless_.count(tag) != 0) { - return; - } - if (auto* node = find(tag)) { - mountingManager_->setComponentState( - tag, node->info->name, node->info->handle, state); - if (node->compat) { - node->compat->state = state; - markDirty(*node, tag, kState); - scheduleFlush(); - } - } else { - pendingEffects_[tag].state = state; - } -} - -void GpuiLoomHost::updateTextState(const LoomTextStateUpdate& update) { - if (update.attributedString == nullptr) { - return; - } - if (update.kind != LoomTextStateKind::Text && - update.kind != LoomTextStateKind::Paragraph && - update.kind != LoomTextStateKind::SelectableParagraph && - update.kind != LoomTextStateKind::TextInput) { - return; - } - std::lock_guard lock(mutex_); - if (viewless_.count(update.tag) != 0) { - return; - } - auto text = std::make_unique(); - text->string = update.attributedString; - text->attributes = update.paragraphAttributes; - if (update.prepared.valid && update.prepared.preparedLayout) { - text->prepared = update.prepared.preparedLayout; - text->preparedWidth = update.prepared.size.width; - } - auto* node = find(update.tag); - if (node == nullptr) { - pendingEffects_[update.tag].text = std::move(text); - return; - } - const auto kind = node->info->kind; - if (kind != Kind::Paragraph && kind != Kind::TextInput) { - return; - } - if (node->text) { - text->reportedString = std::move(node->text->reportedString); - text->reportedSize = node->text->reportedSize; - } - node->text = std::move(text); - markDirty(*node, update.tag, kText); - scheduleFlush(); -} - -void GpuiLoomHost::updateScrollContentBounds( - SurfaceId /*surfaceId*/, - Tag tag, - const folly::dynamic& props, - const Rect& bounds) { - std::lock_guard lock(mutex_); - std::array offset{}; - std::optional> live; - { - std::lock_guard scroll(scrollMutex_); - if (const auto found = scrollOffsets_.find(tag); - found != scrollOffsets_.end()) { - live = found->second; - } - } - if (live) { - offset = {live->first, live->second}; - } else if (props.isObject() && props.count("contentOffset") != 0) { - const auto& requested = props["contentOffset"]; - if (requested.isObject()) { - const auto* x = requested.get_ptr("x"); - const auto* y = requested.get_ptr("y"); - if (x != nullptr && x->isNumber()) { - offset[0] = static_cast(x->asDouble()); - } - if (y != nullptr && y->isNumber()) { - offset[1] = static_cast(y->asDouble()); - } - } - } - const auto content = - ScrollViewState{{offset[0], offset[1]}, bounds, 0}.getContentSize(); - const std::array size{content.width, content.height}; - if (auto* node = find(tag)) { - if (node->ext) { - node->ext->hasScrollState = true; - node->ext->offset = offset; - node->ext->content = size; - markDirty(*node, tag, kState); - scheduleFlush(); - } - } else { - auto& pending = pendingEffects_[tag]; - pending.hasScrollState = true; - pending.offset = offset; - pending.content = size; - } -} - -void GpuiLoomHost::dispatchCommand( - SurfaceId /*surfaceId*/, - Tag tag, - const std::string& commandName, - const folly::dynamic& args) { - std::string_view name; - ComponentHandle handle{}; - { - std::lock_guard lock(mutex_); - const auto* node = find(tag); - if (node == nullptr) { - return; - } - name = node->info->name; - handle = node->info->handle; - } - mountingManager_->dispatchCommand(tag, name, handle, commandName, args); -} - -std::pair GpuiLoomHost::getScrollOffset( - SurfaceId /*surfaceId*/, - Tag tag) { - std::lock_guard scroll(scrollMutex_); - const auto found = scrollOffsets_.find(tag); - return found == scrollOffsets_.end() ? std::pair{0, 0} - : found->second; -} - -std::optional> GpuiLoomHost::getViewLocationInSurface( - SurfaceId /*surfaceId*/, - Tag tag) { - std::lock_guard lock(scrollMutex_); - const auto placed = [&](Tag at) -> const Node* { - const auto found = nodes_.find(at); - return found != nodes_.end() && found->second.laidOut ? &found->second - : nullptr; - }; - const auto* node = placed(tag); - if (node == nullptr) { - return std::nullopt; - } - float x = 0; - float y = 0; - // The frames are relative to the parent; a scrolled ancestor moves what it - // holds by its offset. - for (int depth = 0; node != nullptr && depth < 4096; ++depth) { - x += node->frame[0]; - y += node->frame[1]; - const auto parent = node->parent; - if (const auto offset = scrollOffsets_.find(parent); - offset != scrollOffsets_.end()) { - x -= offset->second.first; - y -= offset->second.second; - } - node = placed(parent); - } - return std::pair{x, y}; -} - -void GpuiLoomHost::setScrollOffset(Tag tag, float x, float y) { - std::lock_guard lock(mutex_); - { - std::lock_guard scroll(scrollMutex_); - scrollOffsets_[tag] = {x, y}; - } - if (auto* node = find(tag); - node != nullptr && node->ext && node->ext->hasScrollState) { - node->ext->offset = {x, y}; - markDirty(*node, tag, kState); - scheduleFlush(); - } -} - -void GpuiLoomHost::setPointScaleFactor(float scale) { - std::lock_guard lock(mutex_); - pointScaleFactor_ = scale; - text_.setPointScaleFactor(scale); - LoomBinding::setPointScaleFactor(scale); -} - -bool GpuiLoomHost::writeMeasuredSize( - Tag tag, - std::optional width, - std::optional height, - std::optional minWidth, - folly::dynamic layout) { - auto* host = active_.load(std::memory_order_acquire); - if (host == nullptr) { - return false; - } - const auto runtime = loom::Runtime::from(*host->contextContainer_); - if (!runtime) { - return false; - } - const loom::MeasuredSize size{width, height, minWidth}; - bool written = false; - runtime->forEachSurface([&](SurfaceId surfaceId) { - if (written || !runtime->setMeasuredSize(surfaceId, tag, size)) { - return; - } - written = true; - if (!layout.empty()) { - runtime->updateNativeProps(surfaceId, tag, std::move(layout)); - } - }); - return written; -} - -void AnimationFrameSource::resume() { - running_.store(true, std::memory_order_release); - requestFrames("animation-backend", true); - reportPendingWork("animation-backend", 1); -} - -void AnimationFrameSource::pause() { - running_.store(false, std::memory_order_release); - requestFrames("animation-backend", false); - reportPendingWork("animation-backend", 0); -} - -void AnimationFrameSource::tick() const { - if (running_.load(std::memory_order_acquire)) { - onAnimationFrame(now()); - } -} - -void GpuiLoomHost::installSizeHints() { - const auto runtime = loom::Runtime::from(*contextContainer_); - if (!runtime) { - return; - } - sizeHints_ = runtime->setInitialMeasuredSize( - "DesktopNativeRoot", - [](const folly::dynamic& props) -> std::optional { - const auto read = [&props](const char* key) -> std::optional { - const auto it = props.find(key); - if (it == props.items().end() || !it->second.isNumber() || - it->second.asDouble() < 0) { - return std::nullopt; - } - return static_cast(it->second.asDouble()); - }; - loom::MeasuredSize size; - size.height = read("hintHeight"); - if (const auto width = read("hintWidth")) { - if (const auto minWidth = read("hintMinWidth")) { - size.width = width; - size.minWidth = minWidth; - } - } - if (!size.height && !size.width) { - return std::nullopt; - } - return size; - }); -} - -std::optional GpuiLoomHost::surfaceContentSize(SurfaceId surfaceId) { - const auto runtime = loom::Runtime::from(*contextContainer_); - if (!runtime) { - return std::nullopt; - } - return runtime->latest().surfaceSize(surfaceId); -} - -void GpuiLoomHost::begin() { - std::unique_lock alive(lifetimeMutex_); - alive_ = true; -} - -// Called with the JavaScript thread stopped and its runtime still alive: the -// Rust store holds typed emitters until it drops the old tree, which is after -// the runtime is gone, so they let go of their event targets here. -void GpuiLoomHost::reset() { - { - std::unique_lock alive(lifetimeMutex_); - alive_ = false; - } - std::lock_guard lock(mutex_); - for (const auto& [tag, family] : families_) { - family->getEventEmitter()->setEnabled(false); - } - for (const auto& [tag, observation] : imageObservations_) { - observation.coordinator->removeObserver(observation.observer); - } - imageObservations_.clear(); - for (const auto& [tag, node] : nodes_) { - mountingManager_->clearComponentState(tag); - } - registry_ = nullptr; - components_.clear(); - { - std::lock_guard events(eventMutex_); - pendingEvents_.clear(); - eventManager_ = nullptr; - eventDispatcher_.reset(); - instanceHandles_.clear(); - wheelTargets_.clear(); - earlyLayouts_.clear(); - } - decltype(nodes_) nodes; - { - std::lock_guard scroll(scrollMutex_); - nodes.swap(nodes_); - scrollOffsets_.clear(); - } - nodes.clear(); - viewless_.clear(); - dirtyTags_ = {}; - structural_ = {}; - batches_ = {}; - updates_ = {}; - insertLayouts_ = {}; - families_.clear(); - pendingEffects_.clear(); - flushScheduled_ = false; -} - -} // namespace rngpui - -#endif // LOOM_RENDERER diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiLoomHost.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiLoomHost.h deleted file mode 100644 index 75a2829def..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiLoomHost.h +++ /dev/null @@ -1,467 +0,0 @@ -// The Loom renderer's host: it turns Loom's mount batches and per-node effects -// straight into the mount ops the Rust node store applies, and answers Loom's -// live queries. Compiled only with LOOM_RENDERER. -// -// A view or a paragraph is a node of a few words: Loom's raw props become the -// flat view props when the node is created or updated, and are not kept. Any -// other component keeps React Native's typed props, state and event emitter, -// because the code that reads them (host components, the per-component prop -// extractors) is written against those types. -#pragma once - -#if LOOM_RENDERER - -#include "GpuiMountingManager.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "LoomComponentProps.h" -#include "LoomViewProps.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rngpui { - -using facebook::react::LoomHost; - -/// The frame source of React Native's shared animation backend: it asks core -/// for frames while an animation runs, and delivers one animation frame with -/// each of them. -class AnimationFrameSource final - : public facebook::react::AnimationChoreographer { - public: - void resume() override; - void pause() override; - /// Called once per display frame on the main thread. - void tick() const; - - private: - std::atomic running_{false}; -}; - -/// Text measurement over core's TextLayoutManager, with the text scale the -/// shadow tree would have applied. -class GpuiLoomTextServices final - : public facebook::react::LoomTextLayoutManagerServices { - public: - GpuiLoomTextServices( - std::shared_ptr contextContainer, - std::shared_ptr layoutManager); - - facebook::react::TextAttributes parseTextAttributes( - facebook::react::SurfaceId surfaceId, - const std::string& componentName, - const folly::dynamic& props, - const facebook::react::TextAttributes& inherited, - facebook::react::ParagraphAttributes& outParagraphAttributes) override; - - /// Shapes on the calling thread and keeps the layout, which the paragraph's - /// mount op then carries to the view. - facebook::react::LoomTextMeasurement prepareText( - facebook::react::SurfaceId surfaceId, - const facebook::react::AttributedString& attributedString, - const facebook::react::ParagraphAttributes& paragraphAttributes, - const facebook::react::Size& minimumSize, - const facebook::react::Size& maximumSize) override; - facebook::react::LoomTextMeasurement prepareTextForMount( - facebook::react::SurfaceId surfaceId, - const facebook::react::AttributedString& attributedString, - const facebook::react::ParagraphAttributes& paragraphAttributes, - const facebook::react::Size& minimumSize, - const facebook::react::Size& maximumSize) override; - - const std::shared_ptr& - layoutManager() const { - return layoutManager_; - } - - private: - std::shared_ptr layoutManager_; - std::shared_ptr contextContainer_; -}; - -class GpuiLoomHost final : public LoomHost, - public std::enable_shared_from_this { - public: - /// Reads the scheduler of the running React instance, or does nothing when - /// there is none (a reload is in progress). - using SchedulerAccess = - std::function&&)>; - /// Runs a function on the JavaScript thread (the calling one when - /// JavaScript runs on the UI thread), or drops it when no instance is up. - using JsAccess = std::function&&)>; - - ~GpuiLoomHost() override; - GpuiLoomHost( - std::shared_ptr mountingManager, - std::shared_ptr contextContainer, - SchedulerAccess schedulerAccess, - JsAccess jsAccess); - - facebook::react::LoomPlatformTraits traits() const override; - std::function)> uiExecutor() override; - void applyBatch( - facebook::react::SurfaceId surfaceId, - facebook::react::LoomMountBatch batch) override; - void failSurface( - facebook::react::SurfaceId surfaceId, - const std::string& reason) override; - void updateViewProps(facebook::react::Tag tag, const folly::dynamic& props) - override; - void registerEventTarget( - facebook::react::SurfaceId surfaceId, - facebook::react::Tag tag, - facebook::react::InstanceHandle::Shared instanceHandle) override; - void unregisterEventTarget( - facebook::react::SurfaceId surfaceId, - facebook::react::Tag tag) override; - void unregisterEventTargets( - facebook::react::SurfaceId surfaceId, - const std::vector& tags) override; - void dispatchEvent( - facebook::react::SurfaceId surfaceId, - facebook::react::Tag tag, - const std::string& eventName, - folly::dynamic payload, - facebook::react::RawEvent::Category category, - bool unique) override; - /// Sets the size the runtime measured for a native root or slot as the - /// node's Loom measured size, with `layout` (one-shot layout props) beside - /// it. False when no running surface has the node. - static bool writeMeasuredSize( - facebook::react::Tag tag, - std::optional width, - std::optional height, - std::optional minWidth, - folly::dynamic layout); - /// Gives a new native root its remembered size (its hint props) before its - /// first layout. Needs the host registered in the context container. - void installSizeHints(); - const std::shared_ptr& animationFrameSource() const { - return animationFrameSource_; - } - void updateComponentState( - facebook::react::SurfaceId surfaceId, - facebook::react::Tag tag, - const std::shared_ptr& state) override; - void updateTextState( - const facebook::react::LoomTextStateUpdate& update) override; - void updateScrollContentBounds( - facebook::react::SurfaceId surfaceId, - facebook::react::Tag tag, - const folly::dynamic& props, - const facebook::react::Rect& bounds) override; - void dispatchCommand( - facebook::react::SurfaceId surfaceId, - facebook::react::Tag tag, - const std::string& commandName, - const folly::dynamic& args) override; - std::pair getScrollOffset( - facebook::react::SurfaceId surfaceId, - facebook::react::Tag tag) override; - std::optional> getViewLocationInSurface( - facebook::react::SurfaceId surfaceId, - facebook::react::Tag tag) override; - facebook::react::LoomTextServices* textServices() override { - return &text_; - } - - /// Points the mounting manager's events, wheel events and animated - /// geometry at this host's nodes. Call once, after the host is owned by a - /// `shared_ptr`. - void connect(); - - /// Delivers an event to the target registered for `tag`. - void dispatchTargetEvent( - facebook::react::Tag tag, - const std::string& type, - folly::dynamic&& payload); - - /// Runs `task` on Loom's UI thread: the mount thread when JavaScript runs on - /// its own thread (posted), else the calling GPUI main thread (now). - static void runOnUIThread(std::function task); - - /// A scroll position GPUI reports, kept for `getScrollOffset`. - void setScrollOffset(facebook::react::Tag tag, float x, float y); - void setPointScaleFactor(float scale); - /// The size a surface's root was laid out at. - std::optional surfaceContentSize( - facebook::react::SurfaceId surfaceId); - /// A React instance came up: Loom's callbacks may run again. - void begin(); - /// Forgets every node: the React instance is going. Waits for a callback of - /// the old instance that is running, and drops the ones not yet run, which - /// would otherwise reach into a renderer that is being destroyed. - void reset(); - /// Commits Loom is still computing, and tasks posted to the UI thread that - /// have not run: work that will mount without anything having been queued. - static std::uint64_t pending(); - - private: - enum class Kind : std::uint8_t { - View, - Paragraph, - Image, - ScrollView, - TextInput, - Modal, - /// A component whose code reads React Native's typed props (host - /// components, the per-component prop extractors, third-party libraries). - Compat, - }; - - /// What a component name resolves to, once. - struct ComponentInfo { - const facebook::react::ComponentDescriptor* descriptor{nullptr}; - facebook::react::ComponentName name{nullptr}; - /// `name` as the mount ops carry it. - rust::Str opName; - facebook::react::ComponentHandle handle{0}; - facebook::react::ShadowNodeTraits traits; - Kind kind{Kind::Compat}; - const rngpui::HostComponentEntry* host{nullptr}; - const rngpui::extension::ComponentPropsFn* hook{nullptr}; - }; - - enum Dirty : std::uint8_t { - kFrame = 1, - kInsets = 2, - kDisplay = 4, - kDirection = 8, - kText = 16, - kSelectable = 32, - kState = 64, - kQueued = 128, - }; - - /// The text a paragraph or an input was last given, held until the next - /// flush (and for good by a paragraph that reports its lines and by an - /// input). - struct TextData { - std::shared_ptr string; - facebook::react::ParagraphAttributes attributes; - std::shared_ptr reportedString; - facebook::react::Size reportedSize{}; - /// The layout shaped for this text, and the content width it fits. - std::shared_ptr prepared; - float preparedWidth{0}; - }; - - /// What an image, a scroll view, an input or a modal needs beyond its view - /// props. - struct Ext { - /// The component's props as JSON, between the braces. - std::string body; - /// What the Rust store last received. - std::string sent; - std::vector sources; - float blurRadius{0}; - std::optional requested; - facebook::react::ImageRequestParams requestedParams{}; - std::unique_ptr request; - bool hasScrollState{false}; - std::array offset{}; - std::array content{}; - TextFragmentFlat fallback; - bool visible{true}; - bool shown{false}; - }; - - /// The typed props, state and emitter of a compat component, and the ones - /// the Rust store last received. - struct Compat { - facebook::react::Props::Shared props; - facebook::react::Props::Shared sentProps; - facebook::react::State::Shared state; - facebook::react::State::Shared sentState; - facebook::react::EventEmitter::Shared emitter; - /// Mounted without its emitter: the component gets it with a later update. - bool lateEmitter{false}; - }; - - struct Node { - facebook::react::SurfaceId surfaceId{0}; - facebook::react::Tag parent{-1}; - const ComponentInfo* info{nullptr}; - std::array frame{}; - std::array insets{}; - std::uint8_t displayType{1}; - std::uint8_t direction{0}; - std::uint8_t dirty{0}; - bool created{false}; - /// `kInsertLayout`: the node's first frame arrived with its insert, after - /// its create. `kInsertLayoutQueued`: this flush applies it with the - /// insert. `kWaited`: a host component's flush waited for its emitter. - std::uint8_t layoutBits{0}; - /// The node has a frame. Written with `scrollMutex_` held too. - bool laidOut{false}; - LoomViewFlags flags; - /// The props of the node, parsed and waiting for the flush. - std::unique_ptr parsed; - std::unique_ptr deps; - std::unique_ptr text; - std::unique_ptr ext; - std::unique_ptr compat; - }; - - /// A change to the tree, kept in the order Loom made it. - struct Structural { - enum Op : std::uint8_t { Remove, Insert, Delete } kind; - facebook::react::SurfaceId surfaceId; - facebook::react::Tag tag; - facebook::react::Tag parent; - std::int32_t index; - const ComponentInfo* info; - /// The extension props the node last had, which a portal's insertion and - /// removal are decided by. - std::string json; - }; - - static constexpr std::uint8_t kInsertLayout = 1; - static constexpr std::uint8_t kInsertLayoutQueued = 2; - static constexpr std::uint8_t kWaited = 4; - - struct PendingEffects { - facebook::react::State::Shared state; - std::unique_ptr text; - bool hasScrollState{false}; - std::array offset{}; - std::array content{}; - }; - - struct EarlyLayout { - float x, y, width, height; - }; - - bool ensureScheduler(); - Node* find(facebook::react::Tag tag); - const ComponentInfo* componentInfo(const std::string& name); - void markDirty(Node& node, facebook::react::Tag tag, std::uint8_t bits); - void onCreate( - const facebook::react::PropsParserContext& context, - const facebook::react::DirectCreateOperation& operation); - void onUpdateProps( - const facebook::react::PropsParserContext& context, - const facebook::react::DirectUpdatePropsOperation& operation); - void parseView( - const facebook::react::PropsParserContext& context, - Node& node, - const folly::dynamic& props); - void retire(facebook::react::Tag tag); - facebook::react::EventEmitter::Shared makeEmitter( - const Node& node, - facebook::react::Tag tag); - void syncImage(Node& node, facebook::react::Tag tag); - void reportModal(Node& node, facebook::react::Tag tag, bool visible); - std::string extensionJson(Node& node, facebook::react::Tag tag); - facebook::react::ShadowView lightView( - const Node& node, - facebook::react::Tag tag) const; - void flushLocked(); - bool awaitsEmitter(const Node& node) const; - void flushNode( - Node& node, - facebook::react::Tag tag, - MountBatch& batch, - std::vector& reports); - void buildViewOp(Node& node, std::uint8_t dirty, MountOp& op); - void reportTextLayout(Node& node, facebook::react::Tag tag); - void scheduleFlush(); - void drop(facebook::react::Tag tag); - void dispatchNativeEvent( - facebook::react::Tag tag, - const std::string& type, - folly::dynamic&& payload); - void dispatchNativeWheel( - facebook::react::Tag tag, - std::uint64_t id, - folly::dynamic&& payload); - std::optional animatedGeometry( - facebook::react::Tag tag); - - std::shared_ptr mountingManager_; - std::shared_ptr contextContainer_; - SchedulerAccess schedulerAccess_; - JsAccess jsAccess_; - GpuiLoomTextServices text_; - std::shared_ptr imageManager_; - - std::recursive_mutex mutex_; - std::shared_mutex lifetimeMutex_; - bool alive_{true}; - std::shared_ptr registry_; - std::unordered_map components_; - /// Changed with `scrollMutex_` held too, so JavaScript-thread reads of a - /// node's place (`getViewLocationInSurface`) can take that lock alone. - facebook::react::TagMap nodes_; - facebook::react::TagHashSet viewless_; - std::vector dirtyTags_; - std::vector structural_; - /// Scratch of `flushLocked`, kept between flushes. - std::vector> batches_; - std::vector updates_; - std::vector insertLayouts_; - facebook::react::TagMap pendingEffects_; - /// Keeps the event emitter of a node that needs a typed one alive; the - /// emitter does not own its family. - facebook::react::TagMap families_; - struct ImageObservation { - std::shared_ptr - coordinator; - std::shared_ptr observer; - }; - facebook::react::TagMap imageObservations_; - /// Guards `eventManager_`, `eventDispatcher_`, `instanceHandles_` and - /// `wheelTargets_`, which - /// events from the GPUI main thread read without `mutex_`. - mutable std::mutex eventMutex_; - std::shared_ptr eventManager_; - facebook::react::EventDispatcher::Weak eventDispatcher_; - struct EventTarget { - facebook::react::SurfaceId surfaceId; - facebook::react::InstanceHandle::Shared handle; - }; - facebook::react::TagMap instanceHandles_; - /// What a node's wheel events are delivered through, made on the first one. - facebook::react::TagMap> - wheelTargets_; - /// Events of a node whose target is not registered yet (an image's load - /// events, a modal's show), delivered when it is. - facebook::react::TagMap>> - pendingEvents_; - /// The layout event of a node that mounted before its target registered. - facebook::react::TagMap earlyLayouts_; - /// Guards `scrollOffsets_`, and is held with `mutex_` where `nodes_` changes - /// and where a node's frame, parent and `laidOut` are written. - mutable std::mutex scrollMutex_; - facebook::react::TagMap> scrollOffsets_; - bool flushScheduled_{false}; - static inline std::atomic pendingUiTasks_{0}; - static inline std::atomic active_{nullptr}; - float pointScaleFactor_{1.f}; - facebook::react::loom::Subscription sizeHints_; - std::shared_ptr animationFrameSource_ = - std::make_shared(); -}; - -} // namespace rngpui - -#endif // LOOM_RENDERER diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiMainMessageQueue.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiMainMessageQueue.h deleted file mode 100644 index e96bdedfae..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiMainMessageQueue.h +++ /dev/null @@ -1,78 +0,0 @@ -// A MessageQueueThread that runs React Native's JavaScript on the GPUI main -// thread, which is what Loom's `jsThread: "main"` selects. -#pragma once - -#if LOOM_RENDERER - -#include "GpuiTurboModule.h" -#include "rn-gpui-sys/src/lib.rs.h" - -#include -#include - -#include -#include -#include -#include -#include - -namespace rngpui { - -class GpuiMainMessageQueue final : public facebook::react::MessageQueueThread { - public: - void runOnQueue(std::function&& task) override { - dispatchMain( - [state = state_, - task = facebook::react::trackJsTask(std::move(task))]() mutable { - if (!state->quit.load()) { - task(); - } - }); - } - - /// Runs `task` inline on the main thread. From another thread it waits for - /// the main thread to run it, so it is for initialization only. - void runOnQueueSync(std::function&& task) override { - if (rn_gpui_is_main_thread()) { - task(); - return; - } - auto done = std::make_shared>(); - auto finished = done->get_future(); - dispatchMain([state = state_, task = std::move(task), done]() mutable { - if (!state->quit.load()) { - try { - task(); - } catch (...) { - done->set_exception(std::current_exception()); - return; - } - } - done->set_value(); - }); - finished.get(); - } - - /// Once this returns no further work runs: queued tasks see the flag, and a - /// task already running on the main thread has finished. - void quitSynchronous() override { - state_->quit.store(true); - if (rn_gpui_is_main_thread()) { - return; - } - auto done = std::make_shared>(); - auto finished = done->get_future(); - dispatchMain([done] { done->set_value(); }); - finished.wait(); - } - - private: - struct State { - std::atomic quit{false}; - }; - std::shared_ptr state_ = std::make_shared(); -}; - -} // namespace rngpui - -#endif diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiModules.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiModules.cpp deleted file mode 100644 index e4bcb54488..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiModules.cpp +++ /dev/null @@ -1,88 +0,0 @@ -#include "GpuiModules.h" - -#include - -namespace rngpui { -namespace { -std::mutex frameRequestsMutex; -std::mutex pendingWorkMutex; -std::unordered_map& pendingWorkByOwner() { - static std::unordered_map work; - return work; -} -} // namespace - -GpuiModuleHooks& gpuiModuleHooks() { - static GpuiModuleHooks hooks; - return hooks; -} - -GpuiExtensionHooks& gpuiExtensionHooks() { - static GpuiExtensionHooks hooks; - return hooks; -} - -void registerComponentProps( - const std::string& componentName, - extension::ComponentPropsFn fn) { - gpuiExtensionHooks().componentProps[componentName] = std::move(fn); -} - -void registerMountObserver(extension::MountObserver observer) { - gpuiExtensionHooks().mountObservers.push_back(std::move(observer)); -} - -void registerWindowInsetsObserver(extension::WindowInsetsFn fn) { - gpuiExtensionHooks().windowInsetsObservers.push_back(std::move(fn)); -} - -void registerColorSchemeObserver(std::function fn) { - gpuiExtensionHooks().colorSchemeObservers.push_back(std::move(fn)); -} - -void registerWindowMetricsObserver(std::function fn) { - gpuiExtensionHooks().windowMetricsObservers.push_back(std::move(fn)); -} - -void registerFrameCallback(GpuiFrameFn fn) { - gpuiExtensionHooks().frameCallbacks.push_back(std::move(fn)); -} - -void requestFrames(const std::string& owner, bool needsFrames) { - { - std::lock_guard lock(frameRequestsMutex); - gpuiExtensionHooks().frameRequests[owner] = needsFrames; - } - updateFrameDemand(); -} - -bool anyFrameRequested() { - std::lock_guard lock(frameRequestsMutex); - for (const auto& [owner, needsFrames] : gpuiExtensionHooks().frameRequests) { - if (needsFrames) - return true; - } - return false; -} - -void reportPendingWork(const std::string& owner, uint64_t count) { - std::lock_guard lock(pendingWorkMutex); - if (count == 0) - pendingWorkByOwner().erase(owner); - else - pendingWorkByOwner()[owner] = count; -} - -uint64_t pendingWork() { - std::lock_guard lock(pendingWorkMutex); - uint64_t total = 0; - for (const auto& [owner, count] : pendingWorkByOwner()) - total += count; - return total; -} - -void registerPointerObserver(extension::PointerObserverFn fn) { - gpuiExtensionHooks().pointerObservers.push_back(std::move(fn)); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiModules.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiModules.h deleted file mode 100644 index 880ca08e15..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiModules.h +++ /dev/null @@ -1,187 +0,0 @@ -// Code that depends on an optional package is a module: it lives in the -// package itself, under `desktop/cpp/`, and is compiled only when that package -// is installed. A module declares itself under `platforms.desktop` in its -// react-native.config.js. The platform's own modules live in cpp/modules/. A -// module sets the hooks it needs; an unset hook means core does what it does -// when the library is absent. -// -// The extension API below is what a module uses. It is generic, keyed by name, -// and names no library. -// -// registerComponentProps(name, fn): JSON props for one component name. -// MountBatchBuilder calls it for that component and stores the result in -// MountOp.extension_props_json. -// registerMountObserver(observer): per-view mount callbacks. The observer owns -// its state; core hands it the view and nothing else. -// registerWindowInsetsObserver(fn): the window's insets, on change. -// currentWindowInsets(...): the insets last reported to those observers. -// currentColorScheme(): the effective colour scheme, "light" or "dark": -// Appearance.setColorScheme's override when set, else the system's. -// registerColorSchemeObserver(fn): the new effective scheme, on change, from -// the system or from Appearance.setColorScheme. Register before the first -// surface starts. -// registerWindowMetricsObserver(fn): after the main window's size or scale, or -// the font scale, changed. -// windowScale(): the main window's backing scale factor. -// registerFrameCallback(fn): called once per frame. A list, not one slot. -// requestFrames(owner, needsFrames): asks core to keep delivering frames while -// that owner needs them. Core stops when no owner asks. A request is not -// "busy": a library may keep a heartbeat running while it has nothing to do. -// reportPendingWork(owner, count): how much work an owner still has queued -// (callbacks waiting for a frame, say). Idle detection waits for every owner -// to report zero; it never waits on frame requests alone. -// registerPointerObserver(fn): raw pointer events before React Native dispatch. -// Each returns the gestures it recognised, which core dispatches to the -// target tag. -// argb(color): a Fabric colour as 0xAARRGGBB, or 0 when unset. Declared here so -// a module's props extraction does not need core's private -// MountBatchBuilder.h. -// turboModules: extra TurboModules, asked in registration order. -#pragma once - -#include "rn-gpui-sys/src/lib.rs.h" // MountOp - -#include -#include -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rngpui { - -// Extra TurboModules (the active JS engine's, Rust string modules). Asked in -// registration order, after the app's own provider and before the core -// modules; each returns nullptr when the module is not provided there. -using GpuiTurboModuleFn = - std::function( - const std::string& name, - const std::shared_ptr& jsInvoker)>; - -// Called once per frame with a steady-clock timestamp in ms. -using GpuiFrameFn = std::function; - -namespace extension { - -using ComponentPropsFn = std::function; - -// What an observer sees about a mounted view. Core fills only these fields; -// the observer keeps any state of its own. -struct MountObserver { - std::function - onFrameChanged; - std::function onDeleted; - std::function afterBatch; -}; - -using WindowInsetsFn = - std::function; - -// A raw pointer event, before React Native dispatch. `targetChain` is the hit -// chain from the target outward; `phase` follows RN's pointer phases. -struct RawPointerEvent { - std::vector targetChain; - float x; - float y; - int32_t phase; - double timestamp; -}; - -// A gesture the observer recognised in a pointer event. Core dispatches each -// one back to its target tag. -struct RecognizedGesture { - int32_t targetTag; - std::string eventType; - std::string payloadJson; -}; - -using PointerObserverFn = - std::function(const RawPointerEvent&)>; - -} // namespace extension - -struct GpuiModuleHooks { - std::vector turboModules; - GpuiFrameFn frame; -}; - -// The extension registries. Modules write these; core reads them. -struct GpuiExtensionHooks { - std::unordered_map componentProps; - std::vector mountObservers; - std::vector windowInsetsObservers; - std::vector> colorSchemeObservers; - std::vector> windowMetricsObservers; - std::vector frameCallbacks; - std::vector pointerObservers; - std::unordered_map frameRequests; -}; - -uint32_t argb(const facebook::react::SharedColor& color); - -// Hooks are set by the installers at startup, before any surface starts. -GpuiModuleHooks& gpuiModuleHooks(); - -// Resolves a TurboModule by name the way the main runtime does: the app's C++ -// provider, then the extension providers (Rust modules), then core's own. The -// module is made for `jsInvoker`, so a library that runs another JS runtime -// (a worker) passes that runtime's invoker. Null when no module has the name. -std::shared_ptr createTurboModule( - const std::string& name, - const std::shared_ptr& jsInvoker); - -// JSON props for one component name. `componentName` is the Fabric component -// name; the ShadowView carries the props and layout. -void registerComponentProps( - const std::string& componentName, - extension::ComponentPropsFn fn); - -// Appends an observer; registration order is call order. -void registerMountObserver(extension::MountObserver observer); - -void registerWindowInsetsObserver(extension::WindowInsetsFn fn); -// Any thread. -void currentWindowInsets(float& top, float& right, float& bottom, float& left); - -// Any thread. -std::string currentColorScheme(); -void registerColorSchemeObserver(std::function fn); -void registerWindowMetricsObserver(std::function fn); -double windowScale(); - -void registerFrameCallback(GpuiFrameFn fn); - -// Records whether `owner` still needs frames. Core stops delivering them once -// no owner asks. -void requestFrames(const std::string& owner, bool needsFrames); -// Whether any owner asked for frames right now. -bool anyFrameRequested(); -void reportPendingWork(const std::string& owner, uint64_t count); -uint64_t pendingWork(); - -// Re-evaluates the frame chain from every demand source: native animations, -// and any module that asked through `requestFrames`. Defined in GpuiHost.cpp. -void updateFrameDemand(); - -void registerPointerObserver(extension::PointerObserverFn fn); - -GpuiExtensionHooks& gpuiExtensionHooks(); - -void rn_gpui_install_modules(); - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiMountingManager.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiMountingManager.cpp deleted file mode 100644 index 52c20a3709..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiMountingManager.cpp +++ /dev/null @@ -1,1115 +0,0 @@ -#include "GpuiMountingManager.h" -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "GpuiHost.h" // KAllSurfacesStopped -#include "GpuiHostComponentsCpp.h" -#include "MountBatchBuilder.h" -#if LOOM_RENDERER -#include "GpuiLoomHost.h" -#endif -#include "react/coremodules/DeviceInfoModule.h" -#include "rn-gpui-sys/src/lib.rs.h" // cxx bridge - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace rngpui { -class GpuiModalHostViewComponentDescriptor final - : public ConcreteComponentDescriptor { - public: - using ConcreteComponentDescriptor::ConcreteComponentDescriptor; - - State::Shared createInitialState( - const Props::Shared& /*props*/, - const ShadowNodeFamily::Shared& family) const override { - return std::make_shared( - std::make_shared( - DeviceInfoModule::windowSize()), - family); - } - - protected: - void adopt(ShadowNode& shadowNode) const override { - auto& layoutableShadowNode = - static_cast(shadowNode); - auto& stateData = - static_cast( - *shadowNode.getState()) - .getData(); - layoutableShadowNode.setSize(stateData.screenSize); - layoutableShadowNode.setPositionType(YGPositionTypeAbsolute); - ConcreteComponentDescriptor::adopt(shadowNode); - } -}; - -void GpuiImageLoader::loadImage( - const std::string& uri, - const IImageLoaderOnLoadCallback&& onLoad) { - const auto requestId = nextRequestId_.fetch_add(1); - { - std::lock_guard lock(mutex_); - callbacks_.emplace(requestId, std::move(onLoad)); - } - rn_gpui_load_image(uri, requestId); -} - -void GpuiImageLoader::loadWithProgress( - const std::string& uri, - GpuiImageProgress&& progress, - GpuiImageDone&& done) { - const auto requestId = nextRequestId_.fetch_add(1); - { - std::lock_guard lock(mutex_); - callbacks_.emplace(requestId, std::move(done)); - progressCallbacks_.emplace(requestId, std::move(progress)); - } - rn_gpui_load_image(uri, requestId); -} - -void GpuiImageLoader::reportProgress( - std::uint64_t requestId, - std::int64_t loaded, - std::int64_t total) { - GpuiImageProgress callback; - { - std::lock_guard lock(mutex_); - auto found = progressCallbacks_.find(requestId); - if (found == progressCallbacks_.end()) - return; - callback = found->second; - } - callback( - total > 0 ? static_cast(loaded) / static_cast(total) : 0.f, - loaded, - total); -} - -IImageLoader::CacheStatus GpuiImageLoader::getCacheStatus( - const std::string& uri) { - return rn_gpui_image_is_cached(uri) ? CacheStatus::Memory : CacheStatus::None; -} - -void GpuiImageLoader::completeRequest( - std::uint64_t requestId, - double width, - double height, - const std::string& error) { - IImageLoaderOnLoadCallback callback; - { - std::lock_guard lock(mutex_); - auto found = callbacks_.find(requestId); - if (found == callbacks_.end()) - return; - callback = std::move(found->second); - callbacks_.erase(found); - progressCallbacks_.erase(requestId); - } - callback(width, height, error.empty() ? nullptr : error.c_str()); -} - -void rn_gpui_on_image_load_result( - std::uint64_t requestId, - double width, - double height, - rust::String error) { - GpuiImageLoader::completeRequest( - requestId, width, height, std::string(error.data(), error.size())); -} - -void rn_gpui_on_image_progress( - std::uint64_t requestId, - std::int64_t loaded, - std::int64_t total) { - GpuiImageLoader::reportProgress(requestId, loaded, total); -} - -void installGpuiImageLoadTable() { - setGpuiImageLoadTable(GpuiImageLoadTable{ - .start = [](const std::string& uri, - GpuiImageProgress progress, - GpuiImageDone done) { - GpuiImageLoader::loadWithProgress( - uri, std::move(progress), std::move(done)); - }}); -} - -namespace { -// Turns what an image request reports into the Image component's events. -class GpuiImageObserver final : public ImageResponseObserver { - public: - GpuiImageObserver( - std::shared_ptr emitter, - ImageSource source) - : emitter_(std::move(emitter)), source_(std::move(source)) {} - - void didReceiveProgress(float progress, int64_t loaded, int64_t total) - const override { - emitter_->onProgress(progress, loaded, total); - } - - void didReceiveImage(const ImageResponse& response) const override { - auto source = source_; - if (auto size = std::static_pointer_cast(response.getImage())) { - source.size = *size; - source.scale = 1; - } - emitter_->onLoad(source); - emitter_->onLoadEnd(); - } - - void didReceiveFailure(const ImageLoadError& error) const override { - ImageErrorInfo info; - if (auto message = - std::static_pointer_cast(error.getError())) { - info.error = *message; - } - emitter_->onError(info); - emitter_->onLoadEnd(); - } - - private: - std::shared_ptr emitter_; - ImageSource source_; -}; - -std::atomic mountBatchesInFlight{0}; - -const char* kindName(MountKind kind) { - switch (kind) { - case MountKind::Create: - return "Create"; - case MountKind::Delete: - return "Delete"; - case MountKind::Insert: - return "Insert"; - case MountKind::Remove: - return "Remove"; - case MountKind::Update: - return "Update"; - } - return "?"; -} - -std::string describeOp(const MountOp& op) { - std::string out = std::string(" ") + kindName(op.kind) + - " tag=" + std::to_string(op.tag) + - " parent=" + std::to_string(op.parent_tag) + - " index=" + std::to_string(op.index) + " " + std::string(op.component); - if (!op.frame.w && !op.frame.h && !op.frame.x && !op.frame.y) { - return out; - } - out += " frame=(" + std::to_string(op.frame.x) + "," + - std::to_string(op.frame.y) + " " + std::to_string(op.frame.w) + "x" + - std::to_string(op.frame.h) + ")"; - if (op.has_paragraph) { - out += " fragments=" + std::to_string(op.paragraph.fragments.size()); - } - if (!op.extension_props_json.empty()) { - out += " props=" + std::string(op.extension_props_json); - } - return out; -} -} // namespace - -void GpuiMountingManager::executeMount( - SurfaceId surfaceId, - MountingTransaction&& transaction) { - applyMutations(surfaceId, transaction.getMutations()); -} - -void GpuiMountingManager::setComponentState( - Tag tag, - std::string_view componentName, - ComponentHandle componentHandle, - const State::Shared& state) { - std::lock_guard lock(emittersMutex_); - if (componentName == "ModalHostView") { - if (auto typed = - std::dynamic_pointer_cast>( - state)) { - modalStates_[tag] = std::move(typed); - } - } else if ( - rngpui::anyHostComponents() && - rngpui::hostComponentEntry(componentHandle) != nullptr) { - if (auto typed = - std::dynamic_pointer_cast>( - state)) { - hostStates_[tag] = std::move(typed); - } - } -} - -void GpuiMountingManager::clearComponentState(Tag tag) { - std::lock_guard lock(emittersMutex_); - modalStates_.erase(tag); - hostStates_.erase(tag); -} - -void GpuiMountingManager::notifyFrameChanged( - SurfaceId surfaceId, - const ShadowView& view) { - for (const auto& observer : gpuiExtensionHooks().mountObservers) { - if (observer.onFrameChanged) - observer.onFrameChanged(surfaceId, view); - } -} - -void GpuiMountingManager::notifyDeleted(Tag tag) { - for (const auto& observer : gpuiExtensionHooks().mountObservers) { - if (observer.onDeleted) - observer.onDeleted(tag); - } -} - -MountBatch GpuiMountingManager::beginBatch(SurfaceId surfaceId) { - MountBatch batch; - batch.surface_id = surfaceId; - if (contentSize_) { - if (auto size = contentSize_(surfaceId)) { - if (size->width > 0.f || size->height > 0.f) { - batch.content_width = size->width; - batch.content_height = size->height; - batch.has_content_size = true; - } - } - } - return batch; -} - -void GpuiMountingManager::applyMutations( - SurfaceId surfaceId, - const ShadowViewMutationList& mutations) { - auto batch = beginBatch(surfaceId); - batch.ops.reserve(mutations.size()); - for (const auto& mutation : mutations) { - batch.ops.push_back(buildMountOp(mutation)); - observeMutation(surfaceId, mutation); - } - submitBatch(surfaceId, std::move(batch)); -} - -void GpuiMountingManager::observeMutation( - SurfaceId surfaceId, - const ShadowViewMutation& mutation) { - std::lock_guard lock(emittersMutex_); - { - if (mutation.type == ShadowViewMutation::Insert || - (mutation.type == ShadowViewMutation::Update && - mutation.oldChildShadowView.layoutMetrics.frame != - mutation.newChildShadowView.layoutMetrics.frame)) { - for (const auto& observer : gpuiExtensionHooks().mountObservers) { - if (observer.onFrameChanged) - observer.onFrameChanged(surfaceId, mutation.newChildShadowView); - } - } - auto isVisible = [](const ShadowView& shadowView) { - auto props = - std::dynamic_pointer_cast(shadowView.props); - return props && props->visible; - }; - if (mutation.type == ShadowViewMutation::Insert && - std::string_view(mutation.newChildShadowView.componentName) == - "ModalHostView" && - isVisible(mutation.newChildShadowView)) { - auto emitter = std::dynamic_pointer_cast( - mutation.newChildShadowView.eventEmitter); - if (emitter) - emitter->onShow({}); - } else if ( - mutation.type == ShadowViewMutation::Update && - std::string_view(mutation.oldChildShadowView.componentName) == - "ModalHostView" && - isVisible(mutation.oldChildShadowView) != - isVisible(mutation.newChildShadowView)) { - auto emitter = std::dynamic_pointer_cast( - mutation.newChildShadowView.eventEmitter); - if (emitter) { - if (isVisible(mutation.newChildShadowView)) - emitter->onShow({}); - else - emitter->onDismiss({}); - } - } else if ( - mutation.type == ShadowViewMutation::Delete && - std::string_view(mutation.oldChildShadowView.componentName) == - "ModalHostView" && - isVisible(mutation.oldChildShadowView)) { - auto emitter = std::dynamic_pointer_cast( - mutation.oldChildShadowView.eventEmitter); - if (emitter) - emitter->onDismiss({}); - } - if (mutation.type == ShadowViewMutation::Create || - mutation.type == ShadowViewMutation::Update) { - if (!routes_.event) { - animatedViews_[mutation.newChildShadowView.tag] = - mutation.newChildShadowView; - emitters_[mutation.newChildShadowView.tag] = - mutation.newChildShadowView.eventEmitter; - } - const auto componentName = - std::string(mutation.newChildShadowView.componentName); - if (componentName == "ScrollView") { - auto state = - std::dynamic_pointer_cast>( - mutation.newChildShadowView.state); - if (state) - scrollStates_[mutation.newChildShadowView.tag] = std::move(state); - } else if ( - rngpui::anyHostComponents() && - rngpui::hostComponentEntry( - mutation.newChildShadowView.componentHandle) != nullptr) { - auto state = - std::dynamic_pointer_cast>( - mutation.newChildShadowView.state); - if (state) { - hostStates_[mutation.newChildShadowView.tag] = std::move(state); - } - } else if (componentName == "DesktopNativeRoot") { - auto state = - std::dynamic_pointer_cast>( - mutation.newChildShadowView.state); - if (state) - nativeRootStates_[mutation.newChildShadowView.tag] = std::move(state); - } else if (componentName == "DesktopNativeSlot") { - auto state = - std::dynamic_pointer_cast>( - mutation.newChildShadowView.state); - if (state) - nativeSlotStates_[mutation.newChildShadowView.tag] = std::move(state); - } else if (componentName == "ModalHostView") { - auto state = - std::dynamic_pointer_cast>( - mutation.newChildShadowView.state); - if (state) - modalStates_[mutation.newChildShadowView.tag] = std::move(state); - } else if (componentName == "Image") { - auto state = std::dynamic_pointer_cast>( - mutation.newChildShadowView.state); - auto emitter = std::dynamic_pointer_cast( - mutation.newChildShadowView.eventEmitter); - if (state && emitter) { - const auto& data = state->getData(); - auto coordinator = - data.getImageRequest().getSharedObserverCoordinator(); - auto& entry = imageObservations_[mutation.newChildShadowView.tag]; - if (entry.coordinator != coordinator) { - if (entry.coordinator && entry.observer) - entry.coordinator->removeObserver(entry.observer); - entry.coordinator = coordinator; - entry.observer = std::make_shared( - emitter, data.getImageSource()); - if (data.getImageSource().type != ImageSource::Type::Invalid) - emitter->onLoadStart(); - coordinator->addObserver(entry.observer); - } - } - } - } else if (mutation.type == ShadowViewMutation::Delete) { - for (const auto& observer : gpuiExtensionHooks().mountObservers) { - if (observer.onDeleted) - observer.onDeleted(mutation.oldChildShadowView.tag); - } - animatedViews_.erase(mutation.oldChildShadowView.tag); - const auto tag = mutation.oldChildShadowView.tag; - emitters_.erase(tag); - scrollStates_.erase(mutation.oldChildShadowView.tag); - modalStates_.erase(mutation.oldChildShadowView.tag); - hostStates_.erase(mutation.oldChildShadowView.tag); - nativeRootStates_.erase(mutation.oldChildShadowView.tag); - nativeSlotStates_.erase(mutation.oldChildShadowView.tag); - if (auto found = imageObservations_.find(tag); - found != imageObservations_.end()) { - if (found->second.coordinator && found->second.observer) - found->second.coordinator->removeObserver(found->second.observer); - imageObservations_.erase(found); - } - } - } -} - -void GpuiMountingManager::submitBatch(SurfaceId surfaceId, MountBatch&& batch) { - if (rn_gpui_log_enabled(0)) { - rn_gpui_log( - 0, - "executeMount surface=" + std::to_string(surfaceId) + - " ops=" + std::to_string(batch.ops.size())); - for (const auto& op : batch.ops) { - rn_gpui_log(0, describeOp(op)); - } - } - - mountBatchesInFlight.fetch_add(1, std::memory_order_relaxed); - rn_gpui_on_mount(std::move(batch)); - for (const auto& observer : gpuiExtensionHooks().mountObservers) { - if (observer.afterBatch) - observer.afterBatch(); - } - - if (onAfterMount_) { - onAfterMount_(surfaceId); - } -} - -namespace { -std::atomic mountPendingProbe{nullptr}; -} // namespace - -void setMountPendingProbe(uint64_t (*probe)()) { - mountPendingProbe.store(probe, std::memory_order_release); -} - -extern "C" uint64_t rn_gpui_mount_batches_in_flight() noexcept { - const auto probe = mountPendingProbe.load(std::memory_order_acquire); - return mountBatchesInFlight.load(std::memory_order_relaxed) + - (probe != nullptr ? probe() : 0); -} - -extern "C" void rn_gpui_mount_batch_applied() noexcept { - mountBatchesInFlight.fetch_sub(1, std::memory_order_relaxed); -} - -void GpuiMountingManager::synchronouslyUpdateViewOnUIThread( - Tag tag, - const folly::dynamic& props) { - if (gpuiDebugAnimationEnabled()) { - static std::atomic calls{0}; - const auto call = ++calls; - if (call <= 5 || call % 60 == 0) { - LOG(INFO) << "[animated-props] sync tag=" << tag << " call=" << call - << " props=" << folly::toJson(props); - } - } - // Animation libraries hand colors over as signed 32-bit integers, so a color - // with a high alpha byte is negative; converting the double straight to - // unsigned is undefined for those. - const auto argb = [](const folly::dynamic& value) { - return static_cast( - value.isInt() ? value.asInt() : static_cast(value.asDouble())); - }; - AnimatedPropsFlat update{}; - update.tag = tag; - if (props.isObject()) { - const auto* opacity = props.get_ptr("opacity"); - if (opacity != nullptr && opacity->isNumber()) { - update.opacity = static_cast(opacity->asDouble()); - update.has_opacity = true; - } - const auto* backgroundColor = props.get_ptr("backgroundColor"); - if (backgroundColor != nullptr && backgroundColor->isNumber()) { - update.background_color = argb(*backgroundColor); - update.has_background_color = true; - } - const auto* textColor = props.get_ptr("color"); - if (textColor != nullptr && textColor->isNumber()) { - update.text_color = argb(*textColor); - update.has_text_color = true; - } - const auto* transform = props.get_ptr("transform"); - if (transform != nullptr && transform->isArray()) { - // Use RN's parser and matrix composition, including operation order, - // layout-dependent translations and transformOrigin. Extracting scalar - // operations independently loses repeated operations and scale/translate - // order. - std::optional geometry; - if (routes_.geometry) { - geometry = routes_.geometry(tag); - } else { - std::lock_guard lock(emittersMutex_); - auto it = animatedViews_.find(tag); - if (it != animatedViews_.end()) { - if (auto baseProps = std::dynamic_pointer_cast( - it->second.props)) { - geometry = AnimatedGeometry{ - it->second.layoutMetrics.frame.size, - baseProps->transformOrigin}; - } - } - } - if (!geometry) - return; - ContextContainer contextContainer; - PropsParserContext context(0, contextContainer); - Transform parsed; - fromRawValue(context, RawValue(*transform), parsed); - update.transform = BaseViewProps::resolveTransform( - geometry->size, parsed, geometry->transformOrigin) - .matrix; - update.has_transform = true; - } else if (props.empty()) { - update.reset_transform = true; - } - } - if (update.has_opacity || update.has_transform || update.reset_transform || - update.has_background_color || update.has_text_color) { - if (gpuiDebugAnimationEnabled()) { - static std::atomic updates{0}; - const auto updateNumber = ++updates; - if (updateNumber % 60 == 0) { - LOG(INFO) - << "[native-animated] applied animated props through Fabric: tag=" - << tag << " count=" << updateNumber << " opacity=" << update.opacity - << " transform=" << update.has_transform << " scale=(" - << update.transform[0] << ',' << update.transform[5] - << ") translate=(" << update.transform[12] << ',' - << update.transform[13] << ')'; - } - } - rn_gpui_on_animated_props(std::move(update)); - } -} - -namespace { -/// The manager host component reports go to. Set once, when the host makes its -/// manager; the two report functions below read it on the main thread. -std::weak_ptr& hostComponentStateManager() { - static std::weak_ptr manager; - return manager; -} -} // namespace - -void setHostComponentStateManager(std::weak_ptr manager) { - hostComponentStateManager() = std::move(manager); -} - -void reportHostComponentSize(int32_t tag, float width, float height) { - if (auto manager = hostComponentStateManager().lock()) { - manager->setHostComponentSize(tag, width, height); - } -} - -bool reportNativeRootSize( - int32_t tag, - float height, - bool hasWidth, - float width, - float minWidth) { -#if LOOM_RENDERER - if (!hasWidth) { - return GpuiLoomHost::writeMeasuredSize( - tag, std::nullopt, height, std::nullopt, folly::dynamic::object()); - } - return GpuiLoomHost::writeMeasuredSize( - tag, - width, - height, - minWidth, - folly::dynamic::object("maxWidth", "100%")("flexShrink", 1)); -#else - if (auto manager = hostComponentStateManager().lock()) { - return manager->setNativeRootSize(tag, height, hasWidth, width, minWidth); - } - return false; -#endif -} - -bool reportNativeSlotSize( - int32_t tag, - bool hasWidth, - float width, - bool hasHeight, - float height) { -#if LOOM_RENDERER - return GpuiLoomHost::writeMeasuredSize( - tag, - hasWidth ? std::optional(width) : std::nullopt, - hasHeight ? std::optional(height) : std::nullopt, - std::nullopt, - folly::dynamic::object()); -#else - if (auto manager = hostComponentStateManager().lock()) { - return manager->setNativeSlotSize(tag, hasWidth, width, hasHeight, height); - } - return false; -#endif -} - -void reportHostComponentInsets( - int32_t tag, - float top, - float right, - float bottom, - float left) { - if (auto manager = hostComponentStateManager().lock()) { - manager->setHostComponentInsets(tag, top, right, bottom, left); - } -} - -void GpuiMountingManager::setHostComponentSize( - Tag tag, - float width, - float height) { - std::shared_ptr> state; - { - std::lock_guard lock(emittersMutex_); - auto it = hostStates_.find(tag); - if (it == hostStates_.end()) { - return; - } - state = it->second; - } - const auto& data = state->getData(); - if (data.measured && data.width == width && data.height == height) { - return; - } - GpuiHostStateData next = data; - next.width = width; - next.height = height; - next.measured = true; - state->updateState(std::move(next)); -} - -bool GpuiMountingManager::setNativeRootSize( - Tag tag, - float height, - bool hasWidth, - float width, - float minWidth) { - std::shared_ptr> state; - { - std::lock_guard lock(emittersMutex_); - auto it = nativeRootStates_.find(tag); - if (it == nativeRootStates_.end()) { - return false; - } - state = it->second; - } - NativeRootState next{height, true, width, minWidth, hasWidth}; - const auto& data = state->getData(); - if (data.hasHeight == next.hasHeight && data.height == next.height && - data.hasWidth == next.hasWidth && data.width == next.width && - data.minWidth == next.minWidth) { - return true; - } - state->updateState(std::move(next)); - return true; -} - -bool GpuiMountingManager::setNativeSlotSize( - Tag tag, - bool hasWidth, - float width, - bool hasHeight, - float height) { - std::shared_ptr> state; - { - std::lock_guard lock(emittersMutex_); - auto it = nativeSlotStates_.find(tag); - if (it == nativeSlotStates_.end()) { - return false; - } - state = it->second; - } - NativeSlotState next{width, hasWidth, height, hasHeight}; - const auto& data = state->getData(); - if (data.hasWidth == next.hasWidth && data.width == next.width && - data.hasHeight == next.hasHeight && data.height == next.height) { - return true; - } - state->updateState(std::move(next)); - return true; -} - -void GpuiMountingManager::setHostComponentInsets( - Tag tag, - float top, - float right, - float bottom, - float left) { - std::shared_ptr> state; - { - std::lock_guard lock(emittersMutex_); - auto it = hostStates_.find(tag); - if (it == hostStates_.end()) { - return; - } - state = it->second; - } - const auto& data = state->getData(); - if (data.insetTop == top && data.insetRight == right && - data.insetBottom == bottom && data.insetLeft == left) { - return; - } - GpuiHostStateData next = data; - next.insetTop = top; - next.insetRight = right; - next.insetBottom = bottom; - next.insetLeft = left; - state->updateState(std::move(next)); -} - -void GpuiMountingManager::setScrollOffset(Tag tag, float x, float y) { - std::shared_ptr> state; - { - std::lock_guard lock(emittersMutex_); - auto it = scrollStates_.find(tag); - if (it == scrollStates_.end()) - return; - state = it->second; - } - const auto& data = state->getData(); - state->updateState(ScrollViewState( - {x, y}, data.contentBoundingRect, data.scrollAwayPaddingTop)); -} - -void GpuiMountingManager::setWindowSize(float width, float height) { - std::vector>> states; - { - std::lock_guard lock(emittersMutex_); - states.reserve(modalStates_.size()); - for (const auto& [_, state] : modalStates_) { - states.push_back(state); - } - } - for (const auto& state : states) { - state->updateState(ModalHostViewState(Size{width, height})); - } -} - -namespace { -std::mutex windowInsetsMutex; -std::array lastWindowInsets{}; -} // namespace - -void currentWindowInsets(float& top, float& right, float& bottom, float& left) { - std::lock_guard lock(windowInsetsMutex); - top = lastWindowInsets[0]; - right = lastWindowInsets[1]; - bottom = lastWindowInsets[2]; - left = lastWindowInsets[3]; -} - -void GpuiMountingManager::setWindowTopInset(float top) { - { - std::lock_guard lock(windowInsetsMutex); - lastWindowInsets = {top, 0.0f, 0.0f, 0.0f}; - } - for (const auto& observer : gpuiExtensionHooks().windowInsetsObservers) { - observer(top, 0.0f, 0.0f, 0.0f); - } -} - -void GpuiMountingManager::dispatchEvent( - Tag tag, - const std::string& type, - folly::dynamic&& payload) { - if (routes_.event) { - routes_.event(tag, type, std::move(payload)); - return; - } - SharedEventEmitter emitter; - { - std::lock_guard lock(emittersMutex_); - auto it = emitters_.find(tag); - if (it != emitters_.end()) { - emitter = it->second; - } else { - // A JS-driven pop has already unmounted its Fabric listener. Keep the - // outgoing pixels for animation, but never enqueue events for a dead - // EventTarget. Native dismissals announce their lifecycle before unmount. - return; - } - } - if (!emitter) { - return; - } - if (type == "topScroll") { - // Only the latest scroll position matters: a queued scroll event that JS - // has not handled yet is replaced rather than piled up behind. - emitter->dispatchUniqueEvent(type, std::move(payload)); - return; - } - emitter->dispatchEvent(type, std::move(payload)); -} - -void GpuiMountingManager::dispatchWheel( - Tag tag, - uint64_t id, - folly::dynamic&& payload) { - if (routes_.wheel) { - routes_.wheel(tag, id, std::move(payload)); - return; - } - SharedEventEmitter emitter; - { - std::lock_guard lock(emittersMutex_); - auto it = emitters_.find(tag); - if (it != emitters_.end()) { - emitter = it->second; - } - } - if (!emitter) { - rn_gpui_on_wheel_done(id, false); - return; - } - dispatchWheelTo(*emitter, id, std::move(payload)); -} - -void GpuiMountingManager::dispatchWheelTo( - const EventEmitter& emitter, - uint64_t id, - folly::dynamic&& payload) { - auto prevented = std::make_shared>(false); - auto shared = std::make_shared(std::move(payload)); - emitter.dispatchEvent( - "topWheel", - ValueFactory{ - [shared, - prevented](facebook::jsi::Runtime& runtime) -> facebook::jsi::Value { - auto value = facebook::jsi::valueFromDynamic(runtime, *shared); - auto event = value.asObject(runtime); - auto stop = [prevented]( - facebook::jsi::Runtime&, - const facebook::jsi::Value&, - const facebook::jsi::Value*, - size_t) -> facebook::jsi::Value { - prevented->store(true); - return facebook::jsi::Value::undefined(); - }; - for (const char* name : {"preventDefault", "stopPropagation"}) { - event.setProperty( - runtime, - name, - facebook::jsi::Function::createFromHostFunction( - runtime, - facebook::jsi::PropNameID::forAscii(runtime, name), - 0, - stop)); - } - return value; - }}); - emitter.dispatchEvent( - "topWheelEnd", - ValueFactory{ - [id, - prevented](facebook::jsi::Runtime& runtime) -> facebook::jsi::Value { - rn_gpui_on_wheel_done(id, prevented->load()); - return facebook::jsi::Object(runtime); - }}); -} - -void GpuiMountingManager::setAccessibilityFocusedView(Tag viewTag) { - rn_gpui_request_accessibility_focus(viewTag); -} - -void GpuiMountingManager::accessibleClickAction(Tag viewTag) { - dispatchEvent(viewTag, "click", folly::dynamic::object("target", viewTag)); -} - -void GpuiMountingManager::dispatchCommand( - const ShadowView& view, - const std::string& name, - const folly::dynamic& args) { - dispatchCommand( - view.tag, view.componentName, view.componentHandle, name, args); -} - -void GpuiMountingManager::dispatchCommand( - Tag tag, - std::string_view componentName, - ComponentHandle componentHandle, - const std::string& name, - const folly::dynamic& args) { - if (componentName == "TextInput") { - if (name == "focus") { - rn_gpui_on_text_input_command(tag, true); - } else if (name == "blur") { - rn_gpui_on_text_input_command(tag, false); - } else if (name == "clear") { - rn_gpui_on_text_input_clear(tag); - } - return; - } - if (componentName == "View" && (name == "focus" || name == "blur")) { - rn_gpui_on_text_input_command(tag, name == "focus"); - return; - } - const folly::dynamic argsArray = - args.isArray() ? args : folly::dynamic::array(args); - rn_gpui_on_builtin_command( - tag, std::string(componentName), name, folly::toJson(argsArray).c_str()); - if (!rngpui::anyHostComponents()) { - return; - } - const auto* entry = rngpui::hostComponentEntry(componentHandle); - if (entry == nullptr || entry->command == nullptr) { - return; - } - if (!entry->command(tag, name, argsArray)) { - LOG(ERROR) << "[host-component] " << entry->name << " has no command '" - << name << "'"; - } -} - -void GpuiMountingManager::setSchedulerTaskExecutor( - SchedulerTaskExecutor&& executor) noexcept { - // ReactHost calls this with a real executor when an instance is up - // (`ReactHost.cpp` createReactInstance) and with `nullptr` when it tears the - // instance down (destroyReactInstance, which every reload runs through - // `reloadReactInstance`). Teardown is the only signal the C++ platform gets: - // `SurfaceManager::stopSurface` → `Scheduler::unregisterSurface` emits no - // Delete mutations, so the Rust store is told to drop the whole tree itself. - if (!executor) { - { - std::lock_guard lock(emittersMutex_); - animatedViews_.clear(); - modalStates_.clear(); - nativeRootStates_.clear(); - nativeSlotStates_.clear(); - } - if (instanceHook_) { - instanceHook_(false); - } - rn_gpui_on_surface_stopped(kAllSurfacesStopped); - } else if (instanceHook_) { - instanceHook_(true); - } -} - -namespace { - -std::mutex& knownComponentsMutex() { - static std::mutex mutex; - return mutex; -} - -std::unordered_set& knownComponents() { - static std::unordered_set names; - return names; -} - -void addProvider( - ComponentDescriptorProviderRegistry& registry, - const ComponentDescriptorProvider& provider) { - { - std::lock_guard lock(knownComponentsMutex()); - knownComponents().insert(provider.name); - } - registry.add(provider); -} - -} // namespace - -// What `UIManager.hasViewManagerConfig` asks: React Native picks the stable -// `VirtualView` over its experimental twin when the component is registered. -bool GpuiMountingManager::hasComponent(const std::string& name) { - std::lock_guard lock(knownComponentsMutex()); - return knownComponents().count(name) > 0; -} - -ComponentRegistryFactory GpuiMountingManager::getComponentRegistryFactory() { - return [](const EventDispatcher::Weak& eventDispatcher, - const std::shared_ptr& contextContainer) { - static auto registry = [] { - auto result = std::make_shared(); - addProvider( - *result, - concreteComponentDescriptorProvider()); - addProvider( - *result, - concreteComponentDescriptorProvider< - LayoutConformanceComponentDescriptor>()); - addProvider( - *result, - concreteComponentDescriptorProvider()); - addProvider( - *result, - concreteComponentDescriptorProvider()); - addProvider( - *result, - concreteComponentDescriptorProvider()); - addProvider( - *result, - concreteComponentDescriptorProvider()); - addProvider( - *result, - concreteComponentDescriptorProvider()); - addProvider( - *result, - concreteComponentDescriptorProvider()); - addProvider( - *result, - concreteComponentDescriptorProvider< - GpuiModalHostViewComponentDescriptor>()); - addProvider( - *result, - concreteComponentDescriptorProvider< - WindowControlComponentDescriptor>()); - addProvider( - *result, - concreteComponentDescriptorProvider< - DesktopSwitchComponentDescriptor>()); - addProvider( - *result, - concreteComponentDescriptorProvider< - ActivityIndicatorViewComponentDescriptor>()); - addProvider( - *result, - concreteComponentDescriptorProvider< - DesktopContextMenuViewComponentDescriptor>()); - addProvider( - *result, - concreteComponentDescriptorProvider< - ShortcutScopeComponentDescriptor>()); - addProvider( - *result, - concreteComponentDescriptorProvider()); - addProvider( - *result, - concreteComponentDescriptorProvider()); - addProvider( - *result, - concreteComponentDescriptorProvider< - DesktopScrollBarComponentDescriptor>()); - addProvider( - *result, - concreteComponentDescriptorProvider< - VirtualViewComponentDescriptor>()); - result->setComponentDescriptorProviderRequest([](ComponentName name) { - LOG(ERROR) << "Fabric component " << name - << " is not implemented on gpui"; - }); - rn_gpui_register_app_components(*result); - registerHostComponentDescriptors(*result); - return result; - }(); - return registry->createComponentDescriptorRegistry( - {eventDispatcher, contextContainer, nullptr}); - }; -} -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiMountingManager.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiMountingManager.h deleted file mode 100644 index b2fbf15f31..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiMountingManager.h +++ /dev/null @@ -1,232 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "GpuiHostComponentsCpp.h" -#include "GpuiImageLoad.h" -#include "GpuiImageLoader.h" -#include "GpuiModules.h" -#include "rn-gpui-sys/src/lib.rs.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rngpui { -extern "C" uint64_t rn_gpui_mount_batches_in_flight() noexcept; -extern "C" void rn_gpui_mount_batch_applied() noexcept; - -/// Counts what is on its way to the mount batch counter the test driver reads: -/// a renderer that computes commits off the mounting path reports them here. -void setMountPendingProbe(uint64_t (*probe)()); - -void rn_gpui_register_app_components( - facebook::react::ComponentDescriptorProviderRegistry& registry); - -using namespace facebook::react; - -class GpuiImageLoader final : public IImageLoader { - public: - void loadImage( - const std::string& uri, - const IImageLoaderOnLoadCallback&& onLoad) override; - CacheStatus getCacheStatus(const std::string& uri) override; - static void - completeRequest(std::uint64_t, double, double, const std::string&); - static void loadWithProgress( - const std::string& uri, - GpuiImageProgress&& progress, - GpuiImageDone&& done); - static void reportProgress(std::uint64_t, std::int64_t, std::int64_t); - - private: - inline static std::atomic nextRequestId_{1}; - inline static std::mutex mutex_; - inline static std::unordered_map - callbacks_; - inline static std::unordered_map - progressCallbacks_; -}; - -class GpuiMountingManager : public IMountingManager { - public: - /// `contentSize` returns the size a surface's root was laid out at, or - /// nothing when the surface is not running. It is asked once per mount batch, - /// which is what a `FitContent` surface reports back to GPUI. - explicit GpuiMountingManager( - std::function&& onAfterMount, - std::function(SurfaceId)>&& - contentSize = nullptr) - : onAfterMount_(std::move(onAfterMount)), - contentSize_(std::move(contentSize)) {} - - void executeMount(SurfaceId surfaceId, MountingTransaction&& tx) override; - /// What `executeMount` does with a transaction's mutations. The Loom host - /// describes its batches as mutations and applies them through this. - void applyMutations( - SurfaceId surfaceId, - const ShadowViewMutationList& mutations); - /// What a host that keeps its own node bookkeeping (the Loom host) builds a - /// mount batch with: `beginBatch` for the surface, ops pushed by the caller, - /// `observeMutation` for each typed Fabric mutation it described, and - /// `submitBatch` to hand the result to the Rust store. - MountBatch beginBatch(SurfaceId surfaceId); - void submitBatch(SurfaceId surfaceId, MountBatch&& batch); - void observeMutation(SurfaceId surfaceId, const ShadowViewMutation& mutation); - /// The state a host component or a modal reports sizes into, which Rust - /// updates by tag; forgotten with `clearComponentState`. - void setComponentState( - Tag tag, - std::string_view componentName, - ComponentHandle componentHandle, - const State::Shared& state); - void clearComponentState(Tag tag); - void notifyFrameChanged(SurfaceId surfaceId, const ShadowView& view); - void notifyDeleted(Tag tag); - - /// A node's size and transform origin, which resolve an animated transform. - struct AnimatedGeometry { - facebook::react::Size size; - facebook::react::TransformOrigin transformOrigin; - }; - /// Where a host that keeps its own nodes takes events, wheel events and - /// animated geometry from, in place of the emitters and views this manager - /// records from Fabric mutations. - struct Routes { - std::function event; - std::function wheel; - std::function(Tag)> geometry; - }; - void setRoutes(Routes routes) { - routes_ = std::move(routes); - } - /// Called with true when a React instance comes up and with false when it is - /// torn down, before a reload. - void setInstanceHook(std::function hook) { - instanceHook_ = std::move(hook); - } - void synchronouslyUpdateViewOnUIThread(Tag tag, const folly::dynamic& props) - override; - void dispatchCommand( - const ShadowView& view, - const std::string& name, - const folly::dynamic& args) override; - void dispatchCommand( - Tag tag, - std::string_view componentName, - ComponentHandle componentHandle, - const std::string& name, - const folly::dynamic& args); - ComponentRegistryFactory getComponentRegistryFactory() override; - bool hasComponent(const std::string& name) override; - std::shared_ptr getImageLoader() noexcept override { - return imageLoader_; - } - - // ReactHost calls this with a real executor once a fresh instance - // is up (`ReactHost.cpp`, createReactInstance) and with `nullptr` when it - // tears the instance down (destroyReactInstance, i.e. every reload). The - // teardown call is the only surface-lifecycle signal the C++ platform gets: - // stopping a surface emits no Delete mutations (`SurfaceManager::stopSurface` - // → `Scheduler::unregisterSurface`), so it is where the Rust store is told to - // drop the whole tree before the reloaded instance mounts over it. - void setSchedulerTaskExecutor( - SchedulerTaskExecutor&& executor) noexcept override; - - // Called from the GPUI main thread via GpuiHost::dispatch_event. - void - dispatchEvent(Tag tag, const std::string& type, folly::dynamic&& payload); - void dispatchWheel(Tag tag, uint64_t id, folly::dynamic&& payload); - /// Delivers a wheel event through `emitter` and reports whether JavaScript - /// prevented it. - static void dispatchWheelTo( - const EventEmitter& emitter, - uint64_t id, - folly::dynamic&& payload); - void setScrollOffset(Tag tag, float x, float y); - - /// Pushes a size a host component reported into its shadow node's state, - /// which is what `measureContent` reads, and asks for a commit so Yoga - /// re-measures. A size equal to the state's current one is dropped here, by - /// comparing against the state data rather than a second copy of it. - void setHostComponentSize(Tag tag, float width, float height); - - /// Pushes a container's reported insets into its shadow node's state, where - /// `adopt` applies them as Yoga padding. Insets equal to the state's current - /// ones are dropped here, for the same reason. - void setHostComponentInsets( - Tag tag, - float top, - float right, - float bottom, - float left); - /// Pushes the size a native root measured into its shadow node's state, where - /// `adopt` applies it to Yoga's style. A size the state already holds is - /// dropped here. Whether the node is known. - bool setNativeRootSize( - Tag tag, - float height, - bool hasWidth, - float width, - float minWidth); - /// Pushes the size a slot's placeholder was laid out at into the slot's - /// shadow node's state. Whether the node is known. - bool setNativeSlotSize( - Tag tag, - bool hasWidth, - float width, - bool hasHeight, - float height); - void setWindowSize(float width, float height); - void setWindowTopInset(float top); - void setAccessibilityFocusedView(Tag viewTag) override; - void accessibleClickAction(Tag viewTag) override; - - private: - std::function onAfterMount_; - std::function instanceHook_; - std::function(SurfaceId)> contentSize_; - std::shared_ptr imageLoader_ = - std::make_shared(); - Routes routes_; - std::mutex emittersMutex_; - std::unordered_map animatedViews_; - std::unordered_map - emitters_; // written on JS thread, read on main - std::unordered_map>> - scrollStates_; - std::unordered_map< - Tag, - std::shared_ptr>> - modalStates_; - std::unordered_map< - Tag, - std::shared_ptr>> - hostStates_; - std::unordered_map>> - nativeRootStates_; - std::unordered_map>> - nativeSlotStates_; - struct ImageObservation { - std::shared_ptr coordinator; - std::shared_ptr observer; - }; - std::unordered_map imageObservations_; -}; -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNetworkConfig.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNetworkConfig.cpp deleted file mode 100644 index e9b5238742..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNetworkConfig.cpp +++ /dev/null @@ -1,562 +0,0 @@ -#include "GpuiNetworkConfig.h" -#include "GpuiNetworkRequest.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(__APPLE__) -#include -#include -#endif - -namespace rngpui { - -namespace { - -struct Endpoint { - bool direct{false}; - std::string url; // for curl: scheme://host:port -}; - -struct BypassRule { - std::string scheme; - std::string host; // a glob, lower case - int port{0}; - bool simpleHostnames{false}; - bool cidr{false}; - std::string address; - int prefix{0}; -}; - -struct Rules { - std::map bySchemeKey; // "http", "https", "*", "socks" - std::vector bypass; -}; - -enum class Mode { System, Direct, Fixed }; - -struct Config { - Mode mode{Mode::System}; - Rules fixed; - std::vector doh; -}; - -std::mutex configMutex; -Config config; - -std::string lower(std::string value) { - std::transform( - value.begin(), value.end(), value.begin(), [](unsigned char c) { - return static_cast(std::tolower(c)); - }); - return value; -} - -std::string trim(const std::string& value) { - const auto first = value.find_first_not_of(" \t\r\n"); - if (first == std::string::npos) { - return ""; - } - const auto last = value.find_last_not_of(" \t\r\n"); - return value.substr(first, last - first + 1); -} - -std::vector split( - const std::string& text, - const char* separators) { - std::vector parts; - std::string current; - for (const char c : text) { - if (std::string(separators).find(c) != std::string::npos) { - parts.push_back(current); - current.clear(); - } else { - current += c; - } - } - parts.push_back(current); - return parts; -} - -// "[scheme://]host[:port]" as a curl proxy URL. Chromium's "socks" is SOCKS4 -// and both SOCKS versions resolve names at the proxy. -std::optional parseProxyUri(const std::string& text) { - std::string rest = trim(text); - std::string scheme = "http"; - const auto marker = rest.find("://"); - if (marker != std::string::npos) { - scheme = lower(rest.substr(0, marker)); - rest = rest.substr(marker + 3); - } - while (!rest.empty() && rest.back() == '/') { - rest.pop_back(); - } - if (scheme == "direct") { - return Endpoint{true, ""}; - } - if (rest.empty()) { - return std::nullopt; - } - std::string curlScheme; - int defaultPort = 80; - if (scheme == "http") { - curlScheme = "http"; - } else if (scheme == "https") { - curlScheme = "https"; - defaultPort = 443; - } else if (scheme == "socks5") { - curlScheme = "socks5h"; - defaultPort = 1080; - } else if (scheme == "socks4" || scheme == "socks") { - curlScheme = "socks4a"; - defaultPort = 1080; - } else { - return std::nullopt; - } - const bool hasPort = rest.find(':') != std::string::npos && - (rest.front() != '[' || rest.find("]:") != std::string::npos); - return Endpoint{ - false, - curlScheme + "://" + rest + - (hasPort ? "" : ":" + std::to_string(defaultPort))}; -} - -std::optional parseBypass(std::string pattern) { - pattern = trim(pattern); - if (pattern.empty()) { - return std::nullopt; - } - BypassRule rule; - if (lower(pattern) == "") { - rule.simpleHostnames = true; - return rule; - } - const auto marker = pattern.find("://"); - if (marker != std::string::npos) { - rule.scheme = lower(pattern.substr(0, marker)); - pattern = pattern.substr(marker + 3); - } - const auto slash = pattern.find('/'); - if (slash != std::string::npos) { - rule.cidr = true; - rule.address = pattern.substr(0, slash); - rule.prefix = std::atoi(pattern.substr(slash + 1).c_str()); - return rule; - } - const auto colon = pattern.rfind(':'); - if (colon != std::string::npos && pattern.find(']') == std::string::npos && - pattern.find(':') == colon) { - rule.port = std::atoi(pattern.substr(colon + 1).c_str()); - pattern = pattern.substr(0, colon); - } - pattern = lower(pattern); - if (!pattern.empty() && pattern.front() == '.') { - pattern = "*" + pattern; - } - rule.host = pattern; - return rule; -} - -bool globMatch(const std::string& pattern, const std::string& text) { - size_t p = 0, t = 0, star = std::string::npos, mark = 0; - while (t < text.size()) { - if (p < pattern.size() && (pattern[p] == text[t])) { - ++p; - ++t; - } else if (p < pattern.size() && pattern[p] == '*') { - star = p++; - mark = t; - } else if (star != std::string::npos) { - p = star + 1; - t = ++mark; - } else { - return false; - } - } - while (p < pattern.size() && pattern[p] == '*') { - ++p; - } - return p == pattern.size(); -} - -bool ipv4(const std::string& text, uint32_t& out) { - unsigned a, b, c, d; - char extra; - if (std::sscanf(text.c_str(), "%u.%u.%u.%u%c", &a, &b, &c, &d, &extra) != 4 || - a > 255 || b > 255 || c > 255 || d > 255) { - return false; - } - out = (a << 24) | (b << 16) | (c << 8) | d; - return true; -} - -struct Target { - std::string scheme; - std::string host; - int port{0}; -}; - -std::optional parseTarget(const std::string& url) { - const auto marker = url.find("://"); - if (marker == std::string::npos) { - return std::nullopt; - } - Target target; - target.scheme = lower(url.substr(0, marker)); - auto rest = url.substr(marker + 3); - rest = rest.substr(0, rest.find_first_of("/?#")); - const auto at = rest.rfind('@'); - if (at != std::string::npos) { - rest = rest.substr(at + 1); - } - if (!rest.empty() && rest.front() == '[') { - const auto close = rest.find(']'); - target.host = lower(rest.substr(1, close - 1)); - if (close + 1 < rest.size() && rest[close + 1] == ':') { - target.port = std::atoi(rest.substr(close + 2).c_str()); - } - } else { - const auto colon = rest.find(':'); - target.host = lower(rest.substr(0, colon)); - if (colon != std::string::npos) { - target.port = std::atoi(rest.substr(colon + 1).c_str()); - } - } - if (target.port == 0) { - target.port = target.scheme == "https" || target.scheme == "wss" ? 443 : 80; - } - return target; -} - -bool isBypassed(const BypassRule& rule, const Target& target) { - if (rule.simpleHostnames) { - uint32_t ignored; - return target.host.find('.') == std::string::npos && - target.host.find(':') == std::string::npos && - !ipv4(target.host, ignored); - } - if (!rule.scheme.empty() && rule.scheme != target.scheme) { - return false; - } - if (rule.cidr) { - uint32_t network, address; - if (!ipv4(rule.address, network) || !ipv4(target.host, address)) { - return false; - } - const uint32_t mask = rule.prefix <= 0 - ? 0 - : (rule.prefix >= 32 ? 0xFFFFFFFFu : ~((1u << (32 - rule.prefix)) - 1)); - return (network & mask) == (address & mask); - } - if (rule.port != 0 && rule.port != target.port) { - return false; - } - return globMatch(rule.host, target.host); -} - -bool isLoopback(const Target& target) { - uint32_t address; - return target.host == "localhost" || target.host == "::1" || - (target.host.size() > 10 && - target.host.compare(target.host.size() - 10, 10, ".localhost") == 0) || - (ipv4(target.host, address) && (address >> 24) == 127); -} - -// Parses Chromium proxy rules, or a single proxy URL. -std::string parseRules(const std::string& text, Rules& rules) { - for (const auto& piece : split(text, ";")) { - const auto entry = trim(piece); - if (entry.empty()) { - continue; - } - std::string key = "*"; - std::string list = entry; - const auto equals = entry.find('='); - const auto marker = entry.find("://"); - if (equals != std::string::npos && - (marker == std::string::npos || equals < marker)) { - key = lower(trim(entry.substr(0, equals))); - list = entry.substr(equals + 1); - if (key != "http" && key != "https" && key != "ftp" && key != "socks") { - return "unknown scheme \"" + key + "\" in the proxy rules"; - } - } - std::optional chosen; - for (const auto& candidate : split(list, ",")) { - if (trim(candidate).empty()) { - continue; - } - chosen = parseProxyUri(candidate); - if (!chosen) { - return "invalid proxy \"" + trim(candidate) + "\""; - } - break; - } - if (!chosen) { - return "no proxy in \"" + entry + "\""; - } - if (key == "socks" && !chosen->direct) { - // `socks=host:port` means SOCKS, not an HTTP proxy. - const auto bare = trim(list); - if (bare.find("://") == std::string::npos) { - chosen = parseProxyUri("socks4://" + bare); - } - } - rules.bySchemeKey[key] = *chosen; - } - return ""; -} - -void parseBypassList(const std::string& text, Rules& rules) { - for (const auto& pattern : split(text, ",;")) { - if (auto rule = parseBypass(pattern)) { - rules.bypass.push_back(*rule); - } - } -} - -#if defined(__APPLE__) -std::string stringValue(CFDictionaryRef dictionary, CFStringRef key) { - const auto value = - static_cast(CFDictionaryGetValue(dictionary, key)); - if (value == nullptr || CFGetTypeID(value) != CFStringGetTypeID()) { - return ""; - } - char buffer[512]; - return CFStringGetCString( - value, buffer, sizeof(buffer), kCFStringEncodingUTF8) - ? buffer - : ""; -} - -bool flag(CFDictionaryRef dictionary, CFStringRef key) { - const auto value = - static_cast(CFDictionaryGetValue(dictionary, key)); - int number = 0; - return value != nullptr && CFGetTypeID(value) == CFNumberGetTypeID() && - CFNumberGetValue(value, kCFNumberIntType, &number) && number != 0; -} - -int number(CFDictionaryRef dictionary, CFStringRef key) { - const auto value = - static_cast(CFDictionaryGetValue(dictionary, key)); - int result = 0; - if (value != nullptr && CFGetTypeID(value) == CFNumberGetTypeID()) { - CFNumberGetValue(value, kCFNumberIntType, &result); - } - return result; -} - -// The system's proxies, read at most every few seconds. -Rules systemRules() { - static std::mutex mutex; - static Rules cached; - static std::chrono::steady_clock::time_point readAt; - static bool haveCache = false; - std::lock_guard lock(mutex); - const auto now = std::chrono::steady_clock::now(); - if (haveCache && now - readAt < std::chrono::seconds(5)) { - return cached; - } - Rules rules; - if (const auto settings = SCDynamicStoreCopyProxies(nullptr)) { - const struct { - const char* key; - CFStringRef enable; - CFStringRef host; - CFStringRef port; - const char* scheme; - } kinds[] = { - {"http", - CFSTR("HTTPEnable"), - CFSTR("HTTPProxy"), - CFSTR("HTTPPort"), - "http"}, - {"https", - CFSTR("HTTPSEnable"), - CFSTR("HTTPSProxy"), - CFSTR("HTTPSPort"), - "http"}, - {"socks", - CFSTR("SOCKSEnable"), - CFSTR("SOCKSProxy"), - CFSTR("SOCKSPort"), - "socks5"}, - }; - for (const auto& kind : kinds) { - if (!flag(settings, kind.enable)) { - continue; - } - const auto host = stringValue(settings, kind.host); - const auto port = number(settings, kind.port); - if (host.empty()) { - continue; - } - if (auto endpoint = parseProxyUri( - std::string(kind.scheme) + "://" + host + - (port != 0 ? ":" + std::to_string(port) : ""))) { - rules.bySchemeKey[kind.key] = *endpoint; - } - } - if (flag(settings, CFSTR("ExcludeSimpleHostnames"))) { - parseBypassList("", rules); - } - if (const auto exceptions = static_cast( - CFDictionaryGetValue(settings, CFSTR("ExceptionsList")))) { - for (CFIndex i = 0; i < CFArrayGetCount(exceptions); ++i) { - const auto item = - static_cast(CFArrayGetValueAtIndex(exceptions, i)); - char buffer[512]; - if (CFStringGetCString( - item, buffer, sizeof(buffer), kCFStringEncodingUTF8)) { - parseBypassList(buffer, rules); - } - } - } - CFRelease(settings); - } - cached = rules; - readAt = now; - haveCache = true; - return rules; -} -#endif - -// The proxy for `url` under `rules`, or nullopt for none. -std::optional proxyFor( - const Rules& rules, - const std::string& url) { - const auto target = parseTarget(url); - if (!target) { - return std::nullopt; - } - if (isLoopback(*target)) { - return std::nullopt; - } - for (const auto& rule : rules.bypass) { - if (isBypassed(rule, *target)) { - return std::nullopt; - } - } - const std::string scheme = target->scheme == "wss" ? "https" - : target->scheme == "ws" ? "http" - : target->scheme; - for (const auto& key : {scheme, std::string("*"), std::string("socks")}) { - const auto found = rules.bySchemeKey.find(key); - if (found != rules.bySchemeKey.end()) { - if (found->second.direct) { - return std::nullopt; - } - return found->second.url; - } - } - return std::nullopt; -} - -std::optional resolveProxy(const std::string& url) { - Config snapshot; - { - std::lock_guard lock(configMutex); - snapshot = config; - } - switch (snapshot.mode) { - case Mode::Direct: - return std::nullopt; - case Mode::Fixed: - return proxyFor(snapshot.fixed, url); - case Mode::System: -#if defined(__APPLE__) - return proxyFor(systemRules(), url); -#else - // Elsewhere libcurl reads HTTP_PROXY, HTTPS_PROXY and NO_PROXY itself. - return std::nullopt; -#endif - } - return std::nullopt; -} - -// Whether libcurl's own reading of HTTP_PROXY, HTTPS_PROXY and NO_PROXY stands. -bool environmentProxy(const Config& snapshot) { - return snapshot.mode == Mode::System; -} - -} // namespace - -rust::String rn_gpui_network_configure( - rust::Str mode, - rust::Str rules, - rust::Str bypass, - rust::Str doh) { - Config next; - const std::string modeText(mode); - if (modeText == "system") { - next.mode = Mode::System; - } else if (modeText == "direct") { - next.mode = Mode::Direct; - } else if (modeText == "fixed") { - next.mode = Mode::Fixed; - const auto error = parseRules(std::string(rules), next.fixed); - if (!error.empty()) { - return error; - } - parseBypassList(std::string(bypass), next.fixed); - } else { - return "unknown proxy mode \"" + modeText + "\""; - } - next.doh = split(std::string(doh), "\n"); - std::lock_guard lock(configMutex); - config = std::move(next); - return ""; -} - -rust::String rn_gpui_network_proxy_for(rust::Str url) { - const auto proxy = resolveProxy(std::string(url)); - return proxy ? *proxy : "DIRECT"; -} - -void applyNetworkConfig(CURL* handle, const std::string& url) { - Config snapshot; - { - std::lock_guard lock(configMutex); - snapshot = config; - } - const auto proxy = resolveProxy(url); - if (proxy) { - curl_easy_setopt(handle, CURLOPT_PROXY, proxy->c_str()); - } else if (!environmentProxy(snapshot)) { - // An empty string turns proxies off, including the environment's. - curl_easy_setopt(handle, CURLOPT_PROXY, ""); - } - if (!snapshot.doh.empty()) { - curl_easy_setopt(handle, CURLOPT_DOH_URL, snapshot.doh.front().c_str()); - } -} - -bool fallBackResolver(CURL* handle, size_t& attempt) { - std::vector servers; - { - std::lock_guard lock(configMutex); - servers = config.doh; - } - if (servers.empty() || attempt >= servers.size()) { - return false; - } - attempt += 1; - if (attempt < servers.size()) { - curl_easy_setopt(handle, CURLOPT_DOH_URL, servers[attempt].c_str()); - } else { - // Every server failed: the system resolver is the last resort. - curl_easy_setopt(handle, CURLOPT_DOH_URL, nullptr); - } - return true; -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNetworkConfig.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNetworkConfig.h deleted file mode 100644 index 5ca2af02b4..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNetworkConfig.h +++ /dev/null @@ -1,24 +0,0 @@ -// The proxy and DNS settings the HTTP client applies to each request. -#pragma once - -#include -#include -#include "rust/cxx.h" - -namespace rngpui { - -// Replaces the settings. `mode` is "system", "direct" or "fixed"; `rules` is a -// proxy URL or Chromium proxy rules and `bypass` a Chromium bypass list, both -// read only in "fixed" mode; `doh` is a list of DNS-over-HTTPS URLs, one per -// line, empty for the system resolver. Returns an error message, or an empty -// string. -rust::String rn_gpui_network_configure( - rust::Str mode, - rust::Str rules, - rust::Str bypass, - rust::Str doh); - -// The proxy a request to `url` goes through, as "DIRECT" or the proxy's URL. -rust::String rn_gpui_network_proxy_for(rust::Str url); - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNetworkRequest.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNetworkRequest.h deleted file mode 100644 index 633676e960..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNetworkRequest.h +++ /dev/null @@ -1,20 +0,0 @@ -// The proxy and DNS settings applied to one curl request. Kept apart from -// GpuiNetworkConfig.h, which the Rust bridge compiles without curl's headers. -#pragma once - -#include -#include -#include - -namespace rngpui { - -// Sets the proxy and resolver options of one request. -void applyNetworkConfig(CURL* handle, const std::string& url); - -// After a request failed to resolve its host: moves it to the next -// DNS-over-HTTPS server, and after the last one to the system resolver. -// `attempt` counts the servers tried and starts at 0. Returns false when there -// is nothing left to try, or no server is set. -bool fallBackResolver(CURL* handle, size_t& attempt); - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNodeAddons.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNodeAddons.cpp deleted file mode 100644 index bad8f67266..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNodeAddons.cpp +++ /dev/null @@ -1,442 +0,0 @@ -// Core's half of stock Node-API addon loading: the `_requireNodeLibrary` JSI -// global, path resolution, the per-runtime cache and the error messages. -// -// The engine supplies the VM-specific half — creating a napi_env and dlopening -// the file — through the GpuiJsEngine::NodeAddons capability. Nothing here -// includes a Hermes header. -#include "GpuiNodeAddons.h" -#include "GpuiJsEngine.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(_WIN32) -#include -#elif defined(__APPLE__) -#include -#include -#elif defined(__linux__) -#include -#endif - -namespace rngpui { -namespace { - -constexpr const char* kAddonCacheProperty = "__rnGpuiNodeAddonCache"; - -/// The platform's list separator for RN_GPUI_NODE_ADDON_PATH. -#if defined(_WIN32) -constexpr char kPathListSeparator = ';'; -#else -constexpr char kPathListSeparator = ':'; -#endif - -/// The UTF-8 value of `RN_GPUI_NODE_ADDON_PATH`, or empty when unset. -/// -/// On Windows the variable is read as wide characters and converted, rather -/// than with `std::getenv`: `getenv` returns the bytes the process's ANSI code -/// page produces, which cannot represent a directory name outside that page — -/// the same problem `pathFromUtf8` solves for the strings that come from -/// JavaScript. POSIX uses `getenv` unchanged, where the bytes are the path. -std::string nodeAddonPathEnvironment() { -#if defined(_WIN32) - const wchar_t* wide = _wgetenv(L"RN_GPUI_NODE_ADDON_PATH"); - if (wide == nullptr || *wide == L'\0') - return {}; - const int length = - WideCharToMultiByte(CP_UTF8, 0, wide, -1, nullptr, 0, nullptr, nullptr); - if (length <= 0) - return {}; - // `length` includes the terminator when it is asked for with -1. - std::string utf8(static_cast(length - 1), '\0'); - WideCharToMultiByte( - CP_UTF8, 0, wide, -1, utf8.data(), length, nullptr, nullptr); - return utf8; -#else - const char* value = std::getenv("RN_GPUI_NODE_ADDON_PATH"); - return value == nullptr ? std::string() : std::string(value); -#endif -} - -/// Splits `value` on every character in `separators`, dropping empty entries. -std::vector splitList(const char* value, const char* separators) { - std::vector parts; - if (value == nullptr) - return parts; - std::string current; - for (const char* cursor = value; *cursor != '\0'; ++cursor) { - if (std::strchr(separators, *cursor) != nullptr) { - if (!current.empty()) - parts.push_back(current); - current.clear(); - } else { - current.push_back(*cursor); - } - } - if (!current.empty()) - parts.push_back(current); - return parts; -} - -/// The directory holding the running executable, or an empty path. A packaged -/// app keeps its addons beside the executable, which is what makes this -/// meaningful; a dev build falls through to the embedded absolute path. -std::filesystem::path executableDirectory() { -#if defined(_WIN32) - std::wstring buffer(MAX_PATH, L'\0'); - for (;;) { - const DWORD length = GetModuleFileNameW( - nullptr, buffer.data(), static_cast(buffer.size())); - if (length == 0) - return {}; - if (length < buffer.size()) { - buffer.resize(length); - return std::filesystem::path(buffer).parent_path(); - } - // Truncated: the path is longer than the buffer, so grow and retry. - buffer.resize(buffer.size() * 2); - } -#elif defined(__APPLE__) - uint32_t size = 0; - _NSGetExecutablePath(nullptr, &size); - if (size == 0) - return {}; - std::vector buffer(size); - if (_NSGetExecutablePath(buffer.data(), &size) != 0) - return {}; - std::error_code error; - // The path from _NSGetExecutablePath may be a symlink or contain `..`, so - // resolve it the same way /proc/self/exe is already resolved on Linux. - auto resolved = std::filesystem::canonical(buffer.data(), error); - if (error) - return std::filesystem::path(buffer.data()).parent_path(); - return resolved.parent_path(); -#elif defined(__linux__) - std::error_code error; - auto path = std::filesystem::read_symlink("/proc/self/exe", error); - if (error) - return {}; - return path.parent_path(); -#else - return {}; -#endif -} - -bool isRegularFile(const std::filesystem::path& path) { - std::error_code error; - const bool result = std::filesystem::is_regular_file(path, error); - return result && !error; -} - -/// A filesystem path as UTF-8. -/// -/// `path::string()` is wrong for this on Windows: it converts the native wide -/// form with the process's ANSI code page, so a path holding a character -/// outside that page comes back with `?` in it and the addon is not found (or, -/// worse, the wrong file is). Every consumer here — the JS error message, the -/// addon cache key, and the engine's `load_module` — speaks UTF-8, so convert -/// to that explicitly. -std::string pathToUtf8(const std::filesystem::path& path) { -#if defined(_WIN32) - const std::wstring wide = path.native(); - if (wide.empty()) - return {}; - const int length = WideCharToMultiByte( - CP_UTF8, - 0, - wide.data(), - static_cast(wide.size()), - nullptr, - 0, - nullptr, - nullptr); - if (length <= 0) - return {}; - std::string utf8(static_cast(length), '\0'); - WideCharToMultiByte( - CP_UTF8, - 0, - wide.data(), - static_cast(wide.size()), - utf8.data(), - length, - nullptr, - nullptr); - return utf8; -#else - // POSIX paths are bytes, and callers hand us UTF-8, so this is the identity. - return path.string(); -#endif -} - -/// The inverse of `pathToUtf8`: a `std::filesystem::path` for a path that came -/// from JavaScript, which is UTF-8. -/// -/// On Windows `std::filesystem::path(std::string)` decodes the bytes with the -/// process's ANSI code page, so a checkout under `C:\Users\José\` or any addon -/// directory with an accented character in its name produced a path that does -/// not name the file — the addon was then reported as missing, with the mangled -/// path in the message. On POSIX the bytes are the path, so this is the -/// identity, exactly as `pathToUtf8` is. -std::filesystem::path pathFromUtf8(const std::string& utf8) { -#if defined(_WIN32) - if (utf8.empty()) - return {}; - const int length = MultiByteToWideChar( - CP_UTF8, - MB_ERR_INVALID_CHARS, - utf8.data(), - static_cast(utf8.size()), - nullptr, - 0); - if (length <= 0) { - // Not valid UTF-8. Fall back to the narrow constructor rather than - // returning nothing: a caller that passed a byte string still gets the old - // behaviour instead of a silent miss. - return std::filesystem::path(utf8); - } - std::wstring wide(static_cast(length), L'\0'); - MultiByteToWideChar( - CP_UTF8, - MB_ERR_INVALID_CHARS, - utf8.data(), - static_cast(utf8.size()), - wide.data(), - length); - return std::filesystem::path(wide); -#else - return std::filesystem::path(utf8); -#endif -} - -/// First existing regular file wins, in the order section 3.4 of the plan -/// spells out. `tried` collects every location in the same order so the error -/// message can list them. -std::filesystem::path resolveAddonPath( - const std::string& key, - const std::optional& embeddedPath, - std::vector& tried) { - std::vector candidates; - // Every string here comes from JavaScript or from the environment, so every - // one of them is decoded from UTF-8. `key` is a relative path with `/` - // separators; joining it as a path keeps that meaning. - const auto keyPath = pathFromUtf8(key); - const std::string addonPath = nodeAddonPathEnvironment(); - for (const auto& directory : splitList( - addonPath.c_str(), std::string(1, kPathListSeparator).c_str())) { - candidates.emplace_back(pathFromUtf8(directory) / keyPath); - } - const auto exeDir = executableDirectory(); - if (!exeDir.empty()) { - candidates.push_back(exeDir / "node-addons" / keyPath); -#if defined(__APPLE__) - // A macOS .app bundle keeps resources beside the executable, inside - // Contents/Resources rather than next to the Mach-O in Contents/MacOS. - candidates.push_back(exeDir / ".." / "Resources" / "node-addons" / keyPath); -#endif - } - if (embeddedPath.has_value()) { - candidates.emplace_back(pathFromUtf8(*embeddedPath)); - } - for (const auto& candidate : candidates) { - tried.push_back(pathToUtf8(candidate)); - if (isRegularFile(candidate)) { - std::error_code error; - // The cache is keyed by the real path, so two keys that resolve to one - // file (a symlinked package, say) share one load. - auto canonical = std::filesystem::canonical(candidate, error); - return error ? candidate : canonical; - } - } - return {}; -} - -std::string missingAddonMessage( - const std::string& key, - const std::vector& tried) { - std::string message = "Cannot find Node-API addon '" + key + "'. Looked in:"; - for (const auto& location : tried) { - message += "\n " + location; - } - return message; -} - -/// Where a failed call leaves its message and code for the JS wrapper to throw. -constexpr const char* kAddonFailureProperty = "__rnGpuiNodeAddonFailure"; - -/// Records a failure for `_requireNodeLibrary` to turn into a thrown `Error`. -/// -/// The error deliberately is *not* thrown from here. A C++ `jsi::JSError` -/// thrown out of a host function does not reach JS intact: the runtime fails to -/// match it as a `JSError` and re-wraps it through its generic `std::exception` -/// path, which prefixes the message with "Exception in HostFunction" and -/// discards every property except the message string — `code` included. Leaving -/// the message and code on a global, and letting the JavaScript wrapper below -/// throw, keeps both and drops the prefix. -void setFailure( - facebook::jsi::Runtime& rt, - const std::string& message, - const char* code) { - auto failure = facebook::jsi::Object(rt); - failure.setProperty( - rt, "message", facebook::jsi::String::createFromUtf8(rt, message)); - if (code != nullptr) { - failure.setProperty( - rt, "code", facebook::jsi::String::createFromUtf8(rt, code)); - } - rt.global().setProperty(rt, kAddonFailureProperty, std::move(failure)); -} - -/// The cache of already-loaded exports, stored on the runtime's global object -/// so it lives exactly as long as the runtime — a reload gets a fresh one. -facebook::jsi::Object addonCache(facebook::jsi::Runtime& rt) { - auto global = rt.global(); - auto existing = global.getProperty(rt, kAddonCacheProperty); - if (existing.isObject()) { - return existing.asObject(rt); - } - auto cache = facebook::jsi::Object(rt); - global.setProperty(rt, kAddonCacheProperty, cache); - return cache; -} - -} // namespace - -void installNodeAddons( - facebook::jsi::Runtime& rt, - std::shared_ptr jsInvoker) { - const auto& engine = activeJsEngine(); - - // The loader is built once per runtime, from the engine's capability. When - // the engine has none, the global still exists and fails with a message - // naming the engine, so app code does not have to feature-detect. - std::shared_ptr> - loader; - if (engine.nodeAddons) { - loader = std::make_shared>( - engine.nodeAddons->makeLoader(std::move(jsInvoker))); - } - const std::string unsupportedMessage = - "Node addons are not supported by the " + engine.info.name + " JS engine"; - - auto requireNodeLibrary = facebook::jsi::Function::createFromHostFunction( - rt, - facebook::jsi::PropNameID::forAscii(rt, "_requireNodeLibraryNative"), - 2, - [loader, unsupportedMessage]( - facebook::jsi::Runtime& rt, - const facebook::jsi::Value&, - const facebook::jsi::Value* args, - size_t count) -> facebook::jsi::Value { - if (count < 1 || !args[0].isString()) { - setFailure( - rt, - "_requireNodeLibrary expects a key string as its first " - "argument", - "ERR_INVALID_ARG_TYPE"); - return facebook::jsi::Value::undefined(); - } - const std::string key = args[0].asString(rt).utf8(rt); - - std::optional embeddedPath; - if (count >= 2 && !args[1].isUndefined() && !args[1].isNull()) { - if (!args[1].isString()) { - setFailure( - rt, - "_requireNodeLibrary expects its second argument, when " - "present, to be a path string", - "ERR_INVALID_ARG_TYPE"); - return facebook::jsi::Value::undefined(); - } - embeddedPath = args[1].asString(rt).utf8(rt); - } - - std::vector tried; - const auto resolved = resolveAddonPath(key, embeddedPath, tried); - if (resolved.empty()) { - setFailure(rt, missingAddonMessage(key, tried), "MODULE_NOT_FOUND"); - return facebook::jsi::Value::undefined(); - } - const std::string resolvedPath = pathToUtf8(resolved); - - auto cache = addonCache(rt); - // Prefixed so a path can never collide with an Object.prototype name - // such as "__proto__". - const std::string cacheKey = "addon:" + resolvedPath; - auto cached = cache.getProperty(rt, cacheKey.c_str()); - if (!cached.isUndefined()) { - return cached; - } - - if (!loader) { - setFailure(rt, unsupportedMessage, "ERR_NODE_ADDONS_UNSUPPORTED"); - return facebook::jsi::Value::undefined(); - } - bool loadFailed = false; - auto exports = facebook::jsi::Value::undefined(); - try { - exports = (*loader)(rt, resolvedPath); - } catch (const facebook::jsi::JSError& error) { - // A failed load is reported the same way as a failed resolution: the - // engine's message (which carries `dlerror()`'s text, naming the - // missing symbol) is left for the JS wrapper to throw. Letting this - // exception cross the host-function boundary instead would prefix it - // with "Exception in HostFunction". - loadFailed = true; - setFailure(rt, error.getMessage(), "ERR_DLOPEN_FAILED"); - } - if (loadFailed) { - return facebook::jsi::Value::undefined(); - } - cache.setProperty(rt, cacheKey.c_str(), exports); - return exports; - }); - - // The JS-visible loader. It calls the native function and throws a genuine - // JavaScript `Error` when that recorded a failure, so the `code` property and - // the multi-line message reach the caller unchanged. See `setFailure`. - const std::string failureProperty = kAddonFailureProperty; - const std::string wrapperSource = - "(function (native) {\n" - " return function _requireNodeLibrary(key, path) {\n" - " const result = native(key, path);\n" - " const failure = globalThis." + - failureProperty + - ";\n" - " if (failure) {\n" - " delete globalThis." + - failureProperty + - ";\n" - " const error = new Error(failure.message);\n" - " if (failure.code) error.code = failure.code;\n" - " throw error;\n" - " }\n" - " return result;\n" - " };\n" - "})\n"; - auto wrapper = rt.evaluateJavaScript( - std::make_unique(wrapperSource), - "node-addons.js"); - // `Function` has no call operator; the runtime does the call. - auto requireNodeLibraryWithErrors = - wrapper.getObject(rt).getFunction(rt).call( - rt, std::move(requireNodeLibrary)); - - rt.global().setProperty( - rt, "_requireNodeLibrary", std::move(requireNodeLibraryWithErrors)); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNodeAddons.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNodeAddons.h deleted file mode 100644 index 92331b9a90..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiNodeAddons.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include - -#include - -namespace facebook::react { -class CallInvoker; -} // namespace facebook::react - -namespace rngpui { - -/// Installs the `_requireNodeLibrary(key, path)` JSI global on `runtime`. -/// -/// Called once per runtime, on the JS thread, before the app bundle runs — a -/// reload creates a new runtime and reinstalls it, so the addon cache (which -/// lives on that runtime's global object) starts empty, as Node does for a new -/// context. -/// -/// `jsInvoker` schedules work on this runtime's JS thread; it is handed to the -/// engine, which owns the Node-API host callbacks (async work, thread-safe -/// functions). -/// -/// Core owns everything else: resolving `key` to a file, the cache of loaded -/// exports, and the error messages, including the one used when the active -/// engine has no NodeAddons capability. -void installNodeAddons( - facebook::jsi::Runtime& runtime, - std::shared_ptr jsInvoker); - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiRustTurboModules.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiRustTurboModules.cpp deleted file mode 100644 index 41537add89..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiRustTurboModules.cpp +++ /dev/null @@ -1,685 +0,0 @@ -#include "GpuiRustTurboModules.h" -#include "GpuiDynamic.h" -#include "GpuiModules.h" -#include "GpuiTurboModule.h" -#include "rn-gpui-sys/src/lib.rs.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rngpui { -using namespace facebook::react; - -namespace { - -namespace jsi = facebook::jsi; - -/// A copy of one node tree, so a value built in a scope can cross to the JS -/// thread after the scope is closed. `folly::dynamic` cannot hold the bytes of -/// an `ArrayBuffer`. -struct NodeValue { - uint8_t kind{DynamicNull}; - bool flag{false}; - double number{0.0}; - std::string text; - std::vector bytes; - std::vector> children; -}; - -NodeValue nodeValueFromScope(uint32_t scope, uint32_t node) { - NodeValue value; - value.kind = dynamic_node_kind(scope, node); - switch (value.kind) { - case DynamicBool: - value.flag = dynamic_node_bool(scope, node); - break; - case DynamicNumber: - value.number = dynamic_node_number(scope, node); - break; - case DynamicString: { - const rust::String text = dynamic_node_text(scope, node); - value.text.assign(text.data(), text.size()); - break; - } - case DynamicBuffer: { - const rust::Vec bytes = dynamic_node_buffer(scope, node); - value.bytes.assign(bytes.data(), bytes.data() + bytes.size()); - break; - } - case DynamicArray: - case DynamicObject: { - const size_t length = dynamic_node_len(scope, node); - value.children.reserve(length); - for (size_t index = 0; index < length; ++index) { - const std::string key = value.kind == DynamicObject - ? std::string(dynamic_node_key(scope, node, index)) - : std::string(); - value.children.emplace_back( - key, - nodeValueFromScope(scope, dynamic_node_child(scope, node, index))); - } - break; - } - default: - break; - } - return value; -} - -jsi::Value jsiValueFromNodeValue(jsi::Runtime& rt, const NodeValue& value) { - switch (value.kind) { - case DynamicBool: - return jsi::Value(value.flag); - case DynamicNumber: - return jsi::Value(value.number); - case DynamicString: - return jsi::String::createFromUtf8(rt, value.text); - case DynamicBuffer: - return { - rt, - rt.createArrayBuffer( - std::make_shared( - value.bytes))}; - case DynamicArray: { - jsi::Array array(rt, value.children.size()); - for (size_t index = 0; index < value.children.size(); ++index) { - array.setValueAtIndex( - rt, index, jsiValueFromNodeValue(rt, value.children[index].second)); - } - return jsi::Value(rt, array); - } - case DynamicObject: { - jsi::Object object(rt); - for (const auto& child : value.children) { - object.setProperty( - rt, child.first.c_str(), jsiValueFromNodeValue(rt, child.second)); - } - return jsi::Value(rt, object); - } - default: - return jsi::Value::null(); - } -} - -/// Writes a JS value into a scope, following arrays and objects so an -/// `ArrayBuffer` nested in either keeps its bytes. -uint32_t -nodeFromJsValue(jsi::Runtime& rt, uint32_t scope, const jsi::Value& value) { - if (value.isNull() || value.isUndefined()) { - return dynamic_node_new(scope, DynamicNull); - } - if (value.isBool()) { - const uint32_t node = dynamic_node_new(scope, DynamicBool); - dynamic_node_set_bool(scope, node, value.getBool()); - return node; - } - if (value.isNumber()) { - const uint32_t node = dynamic_node_new(scope, DynamicNumber); - dynamic_node_set_number(scope, node, value.getNumber()); - return node; - } - if (value.isString()) { - const uint32_t node = dynamic_node_new(scope, DynamicString); - dynamic_node_set_text(scope, node, value.getString(rt).utf8(rt)); - return node; - } - if (value.isObject()) { - const jsi::Object object = value.getObject(rt); - if (object.isArrayBuffer(rt)) { - const jsi::ArrayBuffer buffer = object.getArrayBuffer(rt); - const uint8_t* data = buffer.data(rt); - const uint32_t node = dynamic_node_new(scope, DynamicBuffer); - dynamic_node_set_buffer( - scope, node, rust::Slice(data, buffer.size(rt))); - return node; - } - if (object.isFunction(rt)) { - // Only a parameter the spec declares as a callback is a JS function. - return dynamic_node_new(scope, DynamicNull); - } - if (object.isArray(rt)) { - const jsi::Array array = object.getArray(rt); - const uint32_t node = dynamic_node_new(scope, DynamicArray); - for (size_t index = 0; index < array.size(rt); ++index) { - dynamic_node_append( - scope, - node, - nodeFromJsValue(rt, scope, array.getValueAtIndex(rt, index)), - rust::Str()); - } - return node; - } - const uint32_t node = dynamic_node_new(scope, DynamicObject); - const jsi::Array names = object.getPropertyNames(rt); - for (size_t index = 0; index < names.size(rt); ++index) { - const std::string key = - names.getValueAtIndex(rt, index).asString(rt).utf8(rt); - dynamic_node_append( - scope, - node, - nodeFromJsValue(rt, scope, object.getProperty(rt, key.c_str())), - key); - } - return node; - } - return dynamic_node_new(scope, DynamicNull); -} - -/// A Rust promise result. A `Promise` resolves with `undefined`, which a -/// node cannot express on its own. -struct RustPromiseResult { - std::optional value; -}; - -struct PendingCall { - rngpui::Promise promise; - bool returnsVoid{false}; - std::chrono::steady_clock::time_point since; -}; - -std::mutex& pendingMutex() { - static std::mutex mutex; - return mutex; -} - -std::unordered_map& pendingCalls() { - static std::unordered_map calls; - return calls; -} - -std::atomic& nextRequestId() { - static std::atomic next{1}; - return next; -} - -std::mutex& callbacksMutex() { - static std::mutex mutex; - return mutex; -} - -std::unordered_map>& callbacks() { - static std::unordered_map> map; - return map; -} - -std::atomic& nextCallbackId() { - static std::atomic next{1}; - return next; -} - -std::mutex& modulesMutex() { - static std::mutex mutex; - return mutex; -} - -std::unordered_map>& modules() { - static std::unordered_map> map; - return map; -} - -/// One generic TurboModule serves every Rust module: the method list comes from -/// the Rust registry when JS first asks for the module. -class RustTurboModule final - : public TurboModule, - public std::enable_shared_from_this { - public: - RustTurboModule( - std::string name, - std::shared_ptr jsInvoker, - uint64_t handle, - rust::Vec methods, - rust::Vec events) - : TurboModule(std::move(name), std::move(jsInvoker)), handle_(handle) { - methods_.reserve(methods.size()); - for (const auto& method : methods) { - Method entry{ - .name = std::string(method.name), - .argCount = method.arg_count, - .requiredArgs = method.required_args, - .kind = method.kind, - .returnsVoid = method.returns_void, - .callbackArgs = std::vector( - method.callback_args.begin(), method.callback_args.end()), - }; - methodIndex_.emplace(entry.name, methods_.size()); - methods_.push_back(std::move(entry)); - } - for (const auto& event : events) { - const std::string name(event.name); - if (event.has_value) { - eventEmitterMap_[name] = - std::make_shared>(); - } else { - eventEmitterMap_[name] = std::make_shared>(); - } - } - } - - /// `weak_from_this` is empty inside the constructor, and events look the - /// module up by handle. - void start() { - std::lock_guard lock(modulesMutex()); - modules()[handle_] = weak_from_this(); - } - - ~RustTurboModule() override { - { - std::lock_guard lock(modulesMutex()); - modules().erase(handle_); - } - rn_gpui_rust_module_drop(handle_); - } - - std::vector getPropertyNames( - jsi::Runtime& runtime) override { - std::vector names; - names.reserve(methods_.size()); - for (const auto& method : methods_) { - names.push_back(jsi::PropNameID::forUtf8(runtime, method.name)); - } - return names; - } - - void emitValueEvent(const std::string& event, NodeValue value) { - auto found = eventEmitterMap_.find(event); - if (found == eventEmitterMap_.end()) { - return; - } - auto emitter = std::dynamic_pointer_cast>( - found->second); - if (!emitter) { - return; - } - emitter->emit([value = std::move(value)](jsi::Runtime& rt) -> jsi::Value { - return jsiValueFromNodeValue(rt, value); - }); - } - - void emitVoidEvent(const std::string& event) { - auto found = eventEmitterMap_.find(event); - if (found == eventEmitterMap_.end()) { - return; - } - auto emitter = - std::dynamic_pointer_cast>(found->second); - if (emitter) { - emitter->emit(); - } - } - - void sendDeviceEvent(const std::string& name, NodeValue body) { - emitDeviceEvent( - name, - [body = std::move(body)]( - jsi::Runtime& rt, std::vector& args) { - args.emplace_back(jsiValueFromNodeValue(rt, body)); - }); - } - - protected: - jsi::Value create(jsi::Runtime& runtime, const jsi::PropNameID& propName) - override { - const std::string name = propName.utf8(runtime); - auto found = methodIndex_.find(name); - if (found == methodIndex_.end()) { - return TurboModule::create(runtime, propName); - } - const size_t index = found->second; - return jsi::Function::createFromHostFunction( - runtime, - propName, - static_cast(methods_[index].argCount), - [this, index]( - jsi::Runtime& rt, - const jsi::Value&, - const jsi::Value* args, - size_t count) { return invoke(rt, index, args, count); }); - } - - private: - struct Method { - std::string name; - uint32_t argCount; - uint32_t requiredArgs; - uint8_t kind; - bool returnsVoid; - std::vector callbackArgs; - }; - - class ScopeGuard { - public: - explicit ScopeGuard(uint32_t scope) : scope_(scope) {} - ~ScopeGuard() { - dynamic_scope_close(scope_); - } - ScopeGuard(const ScopeGuard&) = delete; - ScopeGuard& operator=(const ScopeGuard&) = delete; - - private: - uint32_t scope_; - }; - - void throwError( - jsi::Runtime& rt, - const rust::String& code, - const rust::String& message) const { - auto error = jsi::Value(rt, jsi::JSError(rt, std::string(message)).value()); - if (!code.empty()) { - error.asObject(rt).setProperty( - rt, "code", jsi::String::createFromUtf8(rt, std::string(code))); - } - throw jsi::JSError(rt, std::move(error)); - } - - /// A JS function cannot be a value, so the id of a stored - /// `AsyncCallback` takes its place. - uint64_t storeCallback(jsi::Runtime& rt, const jsi::Value& value) { - auto callback = - AsyncCallback<>(rt, value.getObject(rt).getFunction(rt), jsInvoker_); - const uint64_t id = nextCallbackId().fetch_add(1); - std::lock_guard lock(callbacksMutex()); - callbacks().emplace(id, std::move(callback)); - return id; - } - - jsi::Value - invoke(jsi::Runtime& rt, size_t index, const jsi::Value* args, size_t count) { - const Method& method = methods_[index]; - if (count < method.requiredArgs) { - throw jsi::JSError( - rt, - name_ + "." + method.name + " expects " + - std::to_string(method.requiredArgs) + " arguments, got " + - std::to_string(count)); - } - const uint32_t scope = dynamic_scope_open(); - const ScopeGuard guard(scope); - const uint32_t array = dynamic_node_new(scope, DynamicArray); - for (uint32_t position = 0; position < method.argCount; ++position) { - if (position >= count) { - dynamic_node_append( - scope, array, dynamic_node_new(scope, DynamicNull), rust::Str()); - continue; - } - const bool isCallback = std::find( - method.callbackArgs.begin(), - method.callbackArgs.end(), - position) != method.callbackArgs.end(); - if (isCallback && args[position].isObject() && - args[position].getObject(rt).isFunction(rt)) { - const uint64_t id = storeCallback(rt, args[position]); - const uint32_t node = dynamic_node_new(scope, DynamicNumber); - dynamic_node_set_number(scope, node, static_cast(id)); - dynamic_node_append(scope, array, node, rust::Str()); - continue; - } - dynamic_node_append( - scope, - array, - nodeFromJsValue(rt, scope, args[position]), - rust::Str()); - } - - switch (method.kind) { - case 0: { - bool ok = false; - rust::String code; - rust::String message; - const uint32_t root = rn_gpui_rust_module_call_value( - handle_, - static_cast(index), - scope, - array, - ok, - code, - message); - if (!ok) { - throwError(rt, code, message); - } - return jsiValueFromNodeValue(rt, nodeValueFromScope(scope, root)); - } - case 1: { - bool ok = false; - rust::String code; - rust::String message; - rn_gpui_rust_module_call_void( - handle_, - static_cast(index), - scope, - array, - ok, - code, - message); - if (!ok) { - throwError(rt, code, message); - } - return jsi::Value::undefined(); - } - default: { - rngpui::Promise promise(rt, jsInvoker_); - const int32_t request = nextRequestId().fetch_add(1); - { - std::lock_guard lock(pendingMutex()); - pendingCalls().emplace( - request, - PendingCall{ - promise, - method.returnsVoid, - std::chrono::steady_clock::now()}); - } - rn_gpui_rust_module_call_promise( - handle_, static_cast(index), scope, array, request); - return promise.get(rt); - } - } - } - - uint64_t handle_; - std::vector methods_; - std::unordered_map methodIndex_; -}; - -std::shared_ptr moduleFor(uint64_t handle) { - std::lock_guard lock(modulesMutex()); - auto found = modules().find(handle); - if (found == modules().end()) { - return nullptr; - } - return found->second.lock(); -} - -std::vector arrayFromNode(uint32_t scope, uint32_t node) { - std::vector values; - const size_t length = dynamic_node_len(scope, node); - values.reserve(length); - for (size_t index = 0; index < length; ++index) { - values.push_back( - nodeValueFromScope(scope, dynamic_node_child(scope, node, index))); - } - return values; -} - -} // namespace - -} // namespace rngpui - -namespace facebook::react { - -template <> -struct Bridging { - static jsi::Value toJs( - jsi::Runtime& rt, - const rngpui::RustPromiseResult& result, - const std::shared_ptr&) { - if (!result.value) { - return jsi::Value::undefined(); - } - return jsiValueFromNodeValue(rt, *result.value); - } -}; - -} // namespace facebook::react - -namespace rngpui { - -void rn_gpui_rust_module_result( - int32_t request, - bool ok, - uint32_t scope, - uint32_t root, - rust::String code, - rust::String message) { - std::optional pending; - { - std::lock_guard lock(pendingMutex()); - auto found = pendingCalls().find(request); - if (found == pendingCalls().end()) { - // The JS promise is gone: the runtime was torn down by a reload. - dynamic_scope_close(scope); - return; - } - pending = std::move(found->second); - pendingCalls().erase(found); - } - if (ok) { - if (pending->returnsVoid || root == kDynamicNoNode) { - pending->promise.resolve(RustPromiseResult{std::nullopt}); - } else { - pending->promise.resolve( - RustPromiseResult{nodeValueFromScope(scope, root)}); - } - } else { - pending->promise.reject(std::string(code), std::string(message)); - } - dynamic_scope_close(scope); -} - -void rn_gpui_rust_callback_invoke(uint64_t id, uint32_t scope, uint32_t root) { - std::optional> callback; - { - std::lock_guard lock(callbacksMutex()); - auto found = callbacks().find(id); - if (found == callbacks().end()) { - dynamic_scope_close(scope); - return; - } - callback = std::move(found->second); - callbacks().erase(found); - } - auto args = - std::make_shared>(arrayFromNode(scope, root)); - dynamic_scope_close(scope); - callback->call([args](jsi::Runtime& rt, jsi::Function& function) { - std::vector values; - values.reserve(args->size()); - for (const auto& value : *args) { - values.push_back(jsiValueFromNodeValue(rt, value)); - } - const jsi::Value* first = values.data(); - function.call(rt, first, values.size()); - }); -} - -void rn_gpui_rust_callback_drop(uint64_t id) { - std::lock_guard lock(callbacksMutex()); - callbacks().erase(id); -} - -void rn_gpui_rust_module_emit( - uint64_t handle, - rust::Str event, - bool has_value, - uint32_t scope, - uint32_t root) { - auto module = moduleFor(handle); - if (!module) { - dynamic_scope_close(scope); - return; - } - const std::string name(event); - if (has_value) { - module->emitValueEvent(name, nodeValueFromScope(scope, root)); - } else { - module->emitVoidEvent(name); - } - dynamic_scope_close(scope); -} - -void rn_gpui_rust_module_send_event( - uint64_t handle, - rust::Str name, - uint32_t scope, - uint32_t root) { - auto module = moduleFor(handle); - if (!module) { - dynamic_scope_close(scope); - return; - } - module->sendDeviceEvent(std::string(name), nodeValueFromScope(scope, root)); - dynamic_scope_close(scope); -} - -// Promise calls to Rust modules not settled yet and made less than -// `younger_than_ms` ago. An older one is waiting on something outside the app, -// such as the user picking from a context menu. -extern "C" uint64_t rn_gpui_rust_promises_in_flight( - uint64_t younger_than_ms) noexcept { - const auto cutoff = std::chrono::steady_clock::now() - - std::chrono::milliseconds(younger_than_ms); - std::lock_guard lock(pendingMutex()); - uint64_t count = 0; - for (const auto& [request, call] : pendingCalls()) { - if (call.since > cutoff) { - ++count; - } - } - return count; -} - -void rn_gpui_rust_module_clear_pending() { - { - std::lock_guard lock(pendingMutex()); - pendingCalls().clear(); - } - { - std::lock_guard lock(callbacksMutex()); - callbacks().clear(); - } -} - -void install_rust_turbo_modules() { - gpuiModuleHooks().turboModules.push_back( - [](const std::string& name, const std::shared_ptr& jsInvoker) - -> std::shared_ptr { - const uint64_t handle = rn_gpui_rust_module_create(rust::Str(name)); - if (handle == 0) { - return nullptr; - } - auto module = std::make_shared( - name, - jsInvoker, - handle, - rn_gpui_rust_module_methods(handle), - rn_gpui_rust_module_events(handle)); - module->start(); - return module; - }); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiRustTurboModules.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiRustTurboModules.h deleted file mode 100644 index e0ecf5161f..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiRustTurboModules.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once - -#include - -#include - -namespace rngpui { - -/// Installs the provider that serves Rust TurboModules by name. Called once, -/// from the host, before any module is asked for. -void install_rust_turbo_modules(); - -/// Settles the JS promise of a Rust module call with the value built in -/// `scope` at `root`. `request` identifies the promise; an unknown request is -/// discarded, which is what a reload leaves behind. -void rn_gpui_rust_module_result( - int32_t request, - bool ok, - uint32_t scope, - uint32_t root, - rust::String code, - rust::String message); - -/// Calls a JS function a Rust module kept; `scope`/`root` hold its arguments. -void rn_gpui_rust_callback_invoke(uint64_t id, uint32_t scope, uint32_t root); - -void rn_gpui_rust_callback_drop(uint64_t id); - -/// Emits a typed spec event; `has_value` says whether `scope`/`root` carry a -/// payload. -void rn_gpui_rust_module_emit( - uint64_t handle, - rust::Str event, - bool has_value, - uint32_t scope, - uint32_t root); - -void rn_gpui_rust_module_send_event( - uint64_t handle, - rust::Str name, - uint32_t scope, - uint32_t root); - -/// Drops the promises and JS functions of the runtime that is going away. -void rn_gpui_rust_module_clear_pending(); - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiStartupSignpost.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiStartupSignpost.cpp deleted file mode 100644 index df82691383..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiStartupSignpost.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include "GpuiStartupSignpost.h" - -#if defined(__APPLE__) -#include -#include -#endif - -namespace rngpui { - -#if defined(__APPLE__) -namespace { - -/// One signpost log for every stage, created once. -os_log_t startupLog() { - static os_log_t log = os_log_create("org.reactnativegpui.startup", "startup"); - return log; -} - -} // namespace -#endif - -void rn_gpui_startup_signpost(::rust::Str stage, std::uint64_t elapsed_ms) { -#if defined(__APPLE__) - os_log_t log = startupLog(); - if (log == nullptr || !os_signpost_enabled(log)) { - return; - } - // One id, so every stage of a launch belongs to the same interval group. - static os_signpost_id_t id = os_signpost_id_generate(log); - // The name must be a string literal, and the format's arguments follow it. - // The stage goes in the format string with `%.*s`, bounded by its length, so - // it does not have to be constant and cannot run past its own bytes. - os_signpost_event_emit( - log, - id, - "startup stage", - "+%llu %.*s", - elapsed_ms, - static_cast(stage.size()), - stage.data()); -#else - (void)stage; - (void)elapsed_ms; -#endif -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiStartupSignpost.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiStartupSignpost.h deleted file mode 100644 index 73170854ee..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiStartupSignpost.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include -#include "rust/cxx.h" - -namespace rngpui { - -/// Emit an `os_signpost` point event for a startup stage. -/// -/// This lives in C++ because `os/signpost.h` declares its API as macros over a -/// variadic implementation function, and getting that ABI right by hand in Rust -/// is exactly the kind of thing that crashes on the first call. Here the macro -/// expands as Apple intends and there is nothing to transcribe. -/// -/// A no-op on platforms without signposts. -void rn_gpui_startup_signpost(::rust::Str stage, std::uint64_t elapsed_ms); - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiTextMeasure.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiTextMeasure.h deleted file mode 100644 index 1c1860d25d..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiTextMeasure.h +++ /dev/null @@ -1,49 +0,0 @@ -// The TextLayoutManager override is compiled as part of ReactCommon, which -// must not see the cxx bridge headers, so it calls through this plain -// function-pointer table. -#pragma once - -#include -#include - -#include -#include - -namespace rngpui { -struct GpuiTextSize { - float width; - float height; -}; - -struct GpuiTextLine { - std::string text; - float x; - float y; - float width; - float height; - float ascender; - float descender; - float capHeight; - float xHeight; -}; - -struct GpuiTextMeasureTable { - std::vector (*measureLines)( - const facebook::react::AttributedString& text, - const facebook::react::ParagraphAttributes& attributes, - float maxWidth); - GpuiTextSize (*measureParagraph)( - const facebook::react::AttributedString& text, - const facebook::react::ParagraphAttributes& attributes, - float maxWidth, - float maxHeight); -}; - -// Defined in ReactCommonOverrides/.../textlayoutmanager/platform/cxx/.../ -// TextLayoutManager.cpp. Installed once by GpuiHost before any surface is -// started. Measuring before that falls back to a zero-sized paragraph, as the -// Rust side does when no measure handler is registered. -void setGpuiTextMeasureTable(const GpuiTextMeasureTable& table); -const GpuiTextMeasureTable* gpuiTextMeasureTable(); - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiTurboModule.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiTurboModule.cpp deleted file mode 100644 index 6e0d4b5ff5..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiTurboModule.cpp +++ /dev/null @@ -1,171 +0,0 @@ -#include "GpuiTurboModule.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(_WIN32) -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include -#else -#include -#endif - -#include "rn-gpui-sys/src/lib.rs.h" // cxx bridge - -namespace rngpui { -namespace { - -/// Best-effort thread name: the platform truncates or rejects names it cannot -/// store, and a failure only costs a debugging aid. -void nameCurrentThread(const std::string& name) { -#if defined(_WIN32) - using SetThreadDescriptionFn = HRESULT(WINAPI*)(HANDLE, PCWSTR); - static const auto setThreadDescription = []() -> SetThreadDescriptionFn { - const auto module = GetModuleHandleW(L"kernel32.dll"); - return module != nullptr - ? reinterpret_cast( - GetProcAddress(module, "SetThreadDescription")) - : nullptr; - }(); - if (setThreadDescription == nullptr) { - return; - } - const auto size = - MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, nullptr, 0); - if (size <= 1) { - return; - } - std::wstring wide(static_cast(size), L'\0'); - MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, wide.data(), size); - setThreadDescription(GetCurrentThread(), wide.c_str()); -#elif defined(__APPLE__) - pthread_setname_np(name.c_str()); -#else - pthread_setname_np(pthread_self(), name.substr(0, 15).c_str()); -#endif -} - -std::mutex mainTasksMutex; -std::unordered_map> mainTasks; -std::atomic nextMainTaskId{1}; - -} // namespace - -struct ModuleQueue::State { - std::mutex mutex; - std::condition_variable ready; - std::deque> tasks; - bool started{false}; - bool stopped{false}; - std::thread worker; -}; - -ModuleQueue::ModuleQueue(std::string threadName) - : state_(std::make_shared()), threadName_(std::move(threadName)) {} - -ModuleQueue::~ModuleQueue() { - stop(); -} - -void ModuleQueue::stop() { - if (!state_) { - return; - } - auto state = std::move(state_); - { - std::lock_guard lock(state->mutex); - state->stopped = true; - state->tasks.clear(); - } - state->ready.notify_all(); - if (!state->worker.joinable()) { - return; - } - if (state->worker.get_id() == std::this_thread::get_id()) { - // A task stops the queue of a module the JS thread released while the call - // ran. The worker sees `stopped` and exits; joining would deadlock on - // itself. - state->worker.detach(); - return; - } - state->worker.join(); -} - -void ModuleQueue::post(std::function task) { - bool startWorker = false; - { - std::lock_guard lock(state_->mutex); - if (state_->stopped) { - return; - } - state_->tasks.push_back(std::move(task)); - if (!state_->started) { - state_->started = true; - startWorker = true; - } - } - if (startWorker) { - // The worker owns its state through the shared pointer, never through this. - state_->worker = std::thread([state = state_, name = threadName_] { - nameCurrentThread(name); - for (;;) { - std::function next; - { - std::unique_lock lock(state->mutex); - state->ready.wait(lock, [&state] { - return state->stopped || !state->tasks.empty(); - }); - if (state->stopped) { - return; - } - next = std::move(state->tasks.front()); - state->tasks.pop_front(); - } - try { - next(); - } catch (const std::exception& error) { - LOG(ERROR) << "module queue task failed: " << error.what(); - } - } - }); - } - state_->ready.notify_one(); -} - -void dispatchMain(std::function task) { - const auto id = nextMainTaskId.fetch_add(1, std::memory_order_relaxed); - { - std::lock_guard lock(mainTasksMutex); - mainTasks.emplace(id, std::move(task)); - } - rn_gpui_run_on_main(id); -} - -void rn_gpui_run_main_task(uint64_t id) { - std::function task; - { - std::lock_guard lock(mainTasksMutex); - auto entry = mainTasks.find(id); - if (entry == mainTasks.end()) { - return; - } - task = std::move(entry->second); - mainTasks.erase(entry); - } - try { - task(); - } catch (const std::exception& error) { - LOG(ERROR) << "main thread task failed: " << error.what(); - } -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiTurboModule.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiTurboModule.h deleted file mode 100644 index 8948454e6c..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/GpuiTurboModule.h +++ /dev/null @@ -1,635 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rngpui { - -namespace jsi = facebook::jsi; - -/// A JS function a module method may call from any thread. Call it at most -/// once, as an Objective-C response block is called. -template -using Callback = facebook::react::AsyncCallback; - -/// The thread a module's `void` and `Promise` methods run on; methods that -/// return a value always run on the JS thread. -enum class ModuleThread { - Own, - Main, - JS, -}; - -/// A serial task queue. `post` is callable from any thread; the worker starts -/// on the first post and stops when the queue is destroyed. -class ModuleQueue { - public: - explicit ModuleQueue(std::string threadName); - ~ModuleQueue(); - - ModuleQueue(const ModuleQueue&) = delete; - ModuleQueue& operator=(const ModuleQueue&) = delete; - - void stop(); - - void post(std::function task); - - private: - struct State; - std::shared_ptr state_; - std::string threadName_; -}; - -/// Runs `task` on the GPUI main thread. The task is dropped, with a warning -/// logged once, while no main-thread handler is installed. -void dispatchMain(std::function task); - -/// The promise a module-thread method settles. It is created on the JS thread -/// by the spec invoker, copyable, and `resolve`/`reject` may be called from any -/// thread; only the first settlement has an effect. -template -class Promise { - static_assert(sizeof...(T) <= 1, "Promise takes at most one value type"); - - public: - Promise( - jsi::Runtime& rt, - const std::shared_ptr& jsInvoker); - - void resolve(T... value); - - void reject(std::string message); - - /// The error carries `code` as its `code` property. - void reject(std::string code, std::string message); - - /// The JS promise; only call this on the JS thread, before the module method - /// can settle it. - jsi::Object get(jsi::Runtime& rt) const; - - private: - struct PromiseHolder : facebook::react::LongLivedObject { - PromiseHolder(jsi::Runtime& rt, jsi::Object p) - : LongLivedObject(rt), promise(std::move(p)) {} - - jsi::Object promise; - }; - - struct SharedState { - ~SharedState() { - if (auto holder = promiseHolder.lock()) { - holder->allowRelease(); - } - } - - std::mutex mutex; - std::weak_ptr promiseHolder; - std::optional> resolve; - std::optional> reject; - }; - - void settleReject(std::optional code, std::string message); - - std::shared_ptr state_; -}; - -template -Promise::Promise( - jsi::Runtime& rt, - const std::shared_ptr& jsInvoker) - : state_(std::make_shared()) { - auto constructor = rt.global().getPropertyAsFunction(rt, "Promise"); - auto promise = constructor.callAsConstructor( - rt, - facebook::react::bridging::toJs( - rt, - // The executor runs synchronously, so capturing `this` is safe. - [this]( - facebook::react::AsyncCallback resolve, - const facebook::react::AsyncCallback<>& reject) { - state_->resolve = std::move(resolve); - state_->reject = std::move(reject); - }, - jsInvoker)); - - auto holder = std::make_shared(rt, promise.asObject(rt)); - facebook::react::LongLivedObjectCollection::get(rt).add(holder); - state_->promiseHolder = holder; -} - -template -void Promise::resolve(T... value) { - std::optional> callback; - { - std::lock_guard lock(state_->mutex); - if (!state_->resolve) { - return; - } - callback = *state_->resolve; - state_->resolve.reset(); - state_->reject.reset(); - } - callback->call(std::forward(value)...); -} - -template -void Promise::reject(std::string message) { - settleReject(std::nullopt, std::move(message)); -} - -template -void Promise::reject(std::string code, std::string message) { - settleReject(std::move(code), std::move(message)); -} - -template -void Promise::settleReject( - std::optional code, - std::string message) { - std::optional> callback; - { - std::lock_guard lock(state_->mutex); - if (!state_->reject) { - return; - } - callback = *state_->reject; - state_->resolve.reset(); - state_->reject.reset(); - } - callback->call([code = std::move(code), message = std::move(message)]( - jsi::Runtime& rt, jsi::Function& reject) { - auto error = jsi::Value(rt, jsi::JSError(rt, message).value()); - if (code) { - error.asObject(rt).setProperty( - rt, "code", jsi::String::createFromUtf8(rt, *code)); - } - reject.call(rt, error); - }); -} - -template -jsi::Object Promise::get(jsi::Runtime& rt) const { - if (auto holder = state_->promiseHolder.lock()) { - return jsi::Value(rt, holder->promise).asObject(rt); - } - throw jsi::JSError(rt, "the promise was invalidated by a reload"); -} - -namespace detail { - -template -struct MethodTraits { - static_assert( - !std::is_same_v, - "a spec method must be a plain member function taking the spec's " - "arguments; const and noexcept qualifiers are not supported"); -}; - -template -struct MethodTraits { - using Class = ClassT; - using Return = ReturnT; - using Args = std::tuple; - static constexpr size_t kArity = sizeof...(ArgsT); - - template - using Arg = std::tuple_element_t>; -}; - -template -constexpr bool argsAreNotJsi(std::index_sequence) { - return ( - !facebook::react::bridging::is_jsi_v< - std::decay_t>> && - ...); -} - -} // namespace detail - -/// The base of every generated spec class. `T` is the implementation, which -/// declares one member function per spec method and may set `kThread`. -template -class TurboModuleBase : public facebook::react::TurboModule, - public std::enable_shared_from_this { - public: - static constexpr ModuleThread kThread = ModuleThread::Own; - - protected: - TurboModuleBase( - std::string name, - std::shared_ptr jsInvoker) - : facebook::react::TurboModule(std::move(name), std::move(jsInvoker)) {} - - /// A method declared as `R name(jsi::Runtime&, Args...)`, run on the JS - /// thread. - template - void valueMethod(const char* name) { - using Traits = detail::MethodTraits; - registerName(name); - methodMap_[name] = MethodMetadata{ - .argCount = Traits::kArity - 1, .invoker = &invokeValue}; - } - - /// A method declared as `void name(Args...)`, run on `T::kThread`. - template - void voidMethod(const char* name) { - using Traits = detail::MethodTraits; - constexpr bool kOnJs = T::kThread == ModuleThread::JS; - if constexpr (!kOnJs) { - static_assert( - detail::argsAreNotJsi( - std::make_index_sequence{}), - "a void method that does not run on the JS thread cannot take a JSI " - "type: convert the argument to a C++ type such as folly::dynamic"); - } - registerName(name); - methodMap_[name] = MethodMetadata{ - .argCount = Traits::kArity - (kOnJs ? 1 : 0), - .invoker = &invokeVoid}; - } - - /// A method declared as `void name(Args..., rngpui::Promise)`, run on - /// `T::kThread`. - template - void promiseMethod(const char* name) { - using Traits = detail::MethodTraits; - constexpr bool kOnJs = T::kThread == ModuleThread::JS; - if constexpr (!kOnJs) { - static_assert( - detail::argsAreNotJsi( - std::make_index_sequence{}), - "a promise method that does not run on the JS thread cannot take a " - "JSI type: convert the argument to a C++ type such as " - "folly::dynamic"); - } - registerName(name); - methodMap_[name] = MethodMetadata{ - .argCount = Traits::kArity - 1 - (kOnJs ? 1 : 0), - .invoker = &invokePromise}; - } - - /// `V...` is the emitter's payload: `jsi::Value` for an event that carries a - /// value, empty for one that does not. - template - void addEvent(const char* name) { - eventEmitterMap_[name] = - std::make_shared>(); - } - - template - void emitEvent(const char* name, V value) { - auto entry = eventEmitterMap_.find(name); - if (entry == eventEmitterMap_.end()) { - return; - } - // A hand-written module can pair a payload-less emitter with a value; a - // mismatched cast would be undefined, so the event is dropped instead. - auto emitter = std::dynamic_pointer_cast< - facebook::react::AsyncEventEmitter>(entry->second); - if (!emitter) { - return; - } - emitter->emit( - [jsInvoker = jsInvoker_, - value = std::move(value)](jsi::Runtime& rt) -> jsi::Value { - return facebook::react::bridging::toJs(rt, value, jsInvoker); - }); - } - - void emitEvent(const char* name) { - auto entry = eventEmitterMap_.find(name); - if (entry == eventEmitterMap_.end()) { - return; - } - auto emitter = - std::dynamic_pointer_cast>( - entry->second); - if (!emitter) { - return; - } - emitter->emit(); - } - - /// For a module used through `NativeEventEmitter`. - void sendEvent(std::string name, folly::dynamic body = nullptr) { - emitDeviceEvent( - name, - [body = std::move(body)]( - jsi::Runtime& rt, std::vector& args) { - if (!body.isNull()) { - args.emplace_back(jsi::valueFromDynamic(rt, body)); - } - }); - } - - private: - /// The method name for arity errors. Every instance of `T` registers the same - /// name, so the last write is the value every reader sees. - template - static std::atomic& registeredName() { - static std::atomic name{nullptr}; - return name; - } - - template - static void registerName(const char* name) { - registeredName().store(name, std::memory_order_relaxed); - } - - template - static std::string arityMessage( - const facebook::react::TurboModule& base, - size_t expected, - size_t count) { - const auto& self = static_cast&>(base); - const char* name = registeredName().load(std::memory_order_relaxed); - return self.name_ + "." + (name != nullptr ? name : "") + - " expects " + std::to_string(expected) + " arguments, got " + - std::to_string(count); - } - - /// The number of JS arguments the method needs: a parameter the - /// implementation declares as `std::optional` may be omitted, so the last - /// required parameter decides. - template - static constexpr size_t requiredCount(std::index_sequence) { - size_t required = 0; - ((required = facebook::react::bridging::is_optional_v< - std::decay_t>> - ? required - : I + 1), - ...); - return required; - } - - /// `jsIndex` is past the end when the spec marks the parameter optional and - /// JS omitted it. - template - static std::decay_t> convertArg( - jsi::Runtime& rt, - const jsi::Value* args, - size_t count, - const std::shared_ptr& jsInvoker, - size_t jsIndex) { - using Arg = std::decay_t>; - if (jsIndex >= count) { - if constexpr (facebook::react::bridging::is_optional_v) { - return Arg{}; - } else { - // Unreachable: requiredCount() rejected the call already. - throw jsi::JSError(rt, "a required argument is missing"); - } - } - return facebook::react::bridging::fromJs(rt, args[jsIndex], jsInvoker); - } - - /// Converts `Args[Offset..]`; the JS arguments start at `args[0]`. - template - static auto convertArgs( - jsi::Runtime& rt, - const facebook::react::TurboModule& base, - const jsi::Value* args, - size_t count, - const std::shared_ptr& jsInvoker, - std::index_sequence) { - constexpr size_t kRequired = - requiredCount(std::index_sequence{}); - if (count < kRequired) { - throw jsi::JSError(rt, arityMessage(base, kRequired, count)); - } - return std::make_tuple( - convertArg(rt, args, count, jsInvoker, I)...); - } - - template - static jsi::Value invokeValue( - jsi::Runtime& rt, - facebook::react::TurboModule& base, - const jsi::Value* args, - size_t count) { - using Traits = detail::MethodTraits; - auto& self = static_cast(base); - auto converted = convertArgs( - rt, - base, - args, - count, - self.jsInvoker_, - std::make_index_sequence{}); - return std::apply( - [&](auto&&... values) -> jsi::Value { - return facebook::react::bridging::toJs( - rt, - (self.*Method)(rt, std::forward(values)...), - self.jsInvoker_); - }, - std::move(converted)); - } - - template - static jsi::Value invokeVoid( - jsi::Runtime& rt, - facebook::react::TurboModule& base, - const jsi::Value* args, - size_t count) { - using Traits = detail::MethodTraits; - constexpr bool kOnJs = T::kThread == ModuleThread::JS; - constexpr size_t kOffset = kOnJs ? 1 : 0; - auto& self = static_cast(base); - auto converted = convertArgs( - rt, - base, - args, - count, - self.jsInvoker_, - std::make_index_sequence{}); - if constexpr (kOnJs) { - std::apply( - [&](auto&&... values) { - (self.*Method)(rt, std::forward(values)...); - }, - std::move(converted)); - } else { - auto task = [weak = std::weak_ptr(self.weak_from_this()), - converted = std::move(converted)]() mutable { - auto module = weak.lock(); - if (!module) { - return; - } - try { - std::apply( - [&](auto&&... values) { - (module.get()->*Method)( - std::forward(values)...); - }, - std::move(converted)); - } catch (const std::exception& error) { - LOG(ERROR) << module->name_ << ": " << error.what(); - } - releaseOnJsThread(std::move(module)); - }; - self.post(std::move(task)); - } - return jsi::Value::undefined(); - } - - template - static jsi::Value invokePromise( - jsi::Runtime& rt, - facebook::react::TurboModule& base, - const jsi::Value* args, - size_t count) { - using Traits = detail::MethodTraits; - using PromiseType = - std::decay_t>; - constexpr bool kOnJs = T::kThread == ModuleThread::JS; - constexpr size_t kOffset = kOnJs ? 1 : 0; - auto& self = static_cast(base); - auto converted = convertArgs( - rt, - base, - args, - count, - self.jsInvoker_, - std::make_index_sequence{}); - PromiseType promise(rt, self.jsInvoker_); - auto task = [weak = std::weak_ptr(self.weak_from_this()), - converted = std::move(converted), - promise]() mutable { - auto module = weak.lock(); - if (!module) { - promise.reject("the module was released before the call ran"); - return; - } - try { - std::apply( - [&](auto&&... values) { - (module.get()->*Method)( - std::forward(values)..., promise); - }, - std::move(converted)); - } catch (const std::exception& error) { - promise.reject(error.what()); - } - releaseOnJsThread(std::move(module)); - }; - if constexpr (kOnJs) { - task(); - } else { - self.post(std::move(task)); - } - return promise.get(rt); - } - - /// A module owns JSI state, so it has to be destroyed on the JS thread while - /// the runtime is alive. A task that holds the last reference means the JS - /// owner released the module while the call ran (a reload), so no JS thread - /// can destroy it any more. The queue is stopped first, so its worker thread - /// does not outlive the module, and the reference is then kept until the - /// process exits: releasing it here would release JSI state from a module - /// thread, after the runtime is gone. - static void releaseOnJsThread(std::shared_ptr module) { - if (module.use_count() > 1) { - return; - } - module->stopQueue(); - std::lock_guard lock(parkedModulesMutex()); - parkedModules().push_back(std::move(module)); - } - - // Both are leaked on purpose: destroying a parked module at exit would - // release its JSI state after the runtime is gone, which is the crash parking - // it avoids. - static std::mutex& parkedModulesMutex() { - static auto* mutex = new std::mutex(); - return *mutex; - } - - static std::vector>& parkedModules() { - static auto* parked = new std::vector>(); - return *parked; - } - - /// Stops this module's queue, if it has one. - void stopQueue() { - if (queue_) { - queue_->stop(); - } - } - - /// Runs `task` on `T::kThread`. JS-thread methods run inline in their - /// invoker, so they never reach this. - void post(std::function task) { - if constexpr (T::kThread == ModuleThread::Main) { - dispatchMain(std::move(task)); - } else { - if (!queue_) { - queue_ = std::make_unique("rn.module." + name_); - } - queue_->post(std::move(task)); - } - } - - std::unique_ptr queue_; -}; - -/// Returns a new Module when `name` is the module's registered name, otherwise -/// nullptr. -template -std::shared_ptr provideTurboModule( - const std::string& name, - std::shared_ptr jsInvoker) { - if (name != Module::kModuleName) { - return nullptr; - } - return std::make_shared(std::move(jsInvoker)); -} - -} // namespace rngpui - -namespace facebook::react { - -/// An `ArrayBuffer` spec type is `std::vector`, so a method that runs -/// off the JS thread gets bytes it owns rather than a runtime-bound object. -template <> -struct Bridging> { - static std::vector fromJs(jsi::Runtime& rt, const jsi::Object& obj) { - if (!obj.isArrayBuffer(rt)) { - throw jsi::JSError(rt, "expected an ArrayBuffer"); - } - const jsi::ArrayBuffer buffer = obj.getArrayBuffer(rt); - const uint8_t* data = buffer.data(rt); - return std::vector(data, data + buffer.size(rt)); - } - - static jsi::Value toJs(jsi::Runtime& rt, const std::vector& bytes) { - return { - rt, - rt.createArrayBuffer( - std::make_shared( - bytes))}; - } -}; - -} // namespace facebook::react diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomComponentProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomComponentProps.cpp deleted file mode 100644 index 2b9d571f78..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomComponentProps.cpp +++ /dev/null @@ -1,337 +0,0 @@ -#if LOOM_RENDERER - -#include "LoomComponentProps.h" - -#include "MountBatchBuilder.h" - -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include - -namespace rngpui { - -using namespace facebook::react; - -void JsonBody::begin(const char* key) { - if (!body_.empty()) { - body_ += ','; - } - body_ += '"'; - body_ += key; - body_ += "\":"; -} - -void JsonBody::number(const char* key, double value) { - begin(key); - if (!std::isfinite(value)) { - body_ += '0'; - return; - } - char text[40]; - if (value == std::floor(value) && std::fabs(value) < 1e15) { - std::snprintf(text, sizeof(text), "%lld", static_cast(value)); - } else { - std::snprintf(text, sizeof(text), "%.9g", value); - } - body_ += text; -} - -void JsonBody::boolean(const char* key, bool value) { - begin(key); - body_ += value ? "true" : "false"; -} - -void JsonBody::string(const char* key, const std::string& value) { - begin(key); - body_ += '"'; - for (const unsigned char byte : value) { - switch (byte) { - case '"': - body_ += "\\\""; - break; - case '\\': - body_ += "\\\\"; - break; - case '\n': - body_ += "\\n"; - break; - case '\r': - body_ += "\\r"; - break; - case '\t': - body_ += "\\t"; - break; - default: - if (byte < 0x20) { - char escaped[8]; - std::snprintf(escaped, sizeof(escaped), "\\u%04x", byte); - body_ += escaped; - } else { - body_ += static_cast(byte); - } - } - } - body_ += '"'; -} - -std::string closeJson(const std::string& body, const std::string& extra) { - std::string json = "{" + body; - if (!extra.empty()) { - if (!body.empty()) { - json += ','; - } - json += extra; - } - json += '}'; - return json; -} - -namespace { - -const folly::dynamic* find(const folly::dynamic& props, const char* key) { - if (!props.isObject()) { - return nullptr; - } - const auto* value = props.get_ptr(key); - return value == nullptr || value->isNull() ? nullptr : value; -} - -template -T read( - const PropsParserContext& context, - const folly::dynamic& props, - const char* key, - T fallback) { - const auto* value = find(props, key); - if (value == nullptr) { - return fallback; - } - try { - T result = fallback; - fromRawValue(context, RawValue(*value), result); - return result; - } catch (const std::exception& error) { - LOG(ERROR) << "Loom: cannot convert " << key << ": " << error.what(); - return fallback; - } -} - -// UTF-16 units of `text`, the unit the JavaScript selection is in. -int32_t utf16Length(const std::string& text) { - int32_t units = 0; - for (const unsigned char byte : text) { - if ((byte & 0xC0) != 0x80) { - units += byte >= 0xF0 ? 2 : 1; - } - } - return units; -} - -} // namespace - -LoomImage parseLoomImage( - const PropsParserContext& context, - const folly::dynamic& props) { - LoomImage image; - image.sources = read>(context, props, "source", {}); - image.blurRadius = read(context, props, "blurRadius", 0.f); - JsonBody json; - if (!image.sources.empty()) { - json.string("uri", image.sources[0].uri); - } - switch (read( - context, props, "resizeMode", ImageResizeMode::Stretch)) { - case ImageResizeMode::Contain: - json.string("resizeMode", "contain"); - break; - case ImageResizeMode::Cover: - json.string("resizeMode", "cover"); - break; - case ImageResizeMode::Center: - json.string("resizeMode", "center"); - break; - case ImageResizeMode::Repeat: - json.string("resizeMode", "repeat"); - break; - case ImageResizeMode::None: - json.string("resizeMode", "none"); - break; - default: - json.string("resizeMode", "stretch"); - break; - } - json.number( - "tintColor", - argb(read(context, props, "tintColor", SharedColor{}))); - json.number("blurRadius", image.blurRadius); - const auto defaultSource = - read(context, props, "defaultSource", ImageSource{}); - if (!defaultSource.uri.empty()) { - json.string("defaultSource", defaultSource.uri); - } - image.body = json.body(); - return image; -} - -std::string parseLoomScrollView( - const PropsParserContext& context, - const folly::dynamic& props) { - JsonBody json; - const bool horizontal = read(context, props, "horizontal", false); - const bool vertical = - read(context, props, "showsVerticalScrollIndicator", true); - const bool horizontalIndicator = - read(context, props, "showsHorizontalScrollIndicator", true); - if (const auto* maintain = find(props, "maintainVisibleContentPosition")) { - try { - ScrollViewMaintainVisibleContentPosition position; - fromRawValue(context, RawValue(*maintain), position); - json.number("maintainMinIndex", position.minIndexForVisible); - if (position.autoscrollToTopThreshold) { - json.number( - "maintainAutoscrollThreshold", *position.autoscrollToTopThreshold); - } - } catch (const std::exception& error) { - LOG(ERROR) << "Loom: cannot convert maintainVisibleContentPosition: " - << error.what(); - } - } - json.number( - "decelerationRate", - read(context, props, "decelerationRate", 0.998f)); - json.number( - "scrollEventThrottle", - read(context, props, "scrollEventThrottle", 0.f)); - json.boolean( - "pagingEnabled", read(context, props, "pagingEnabled", false)); - json.number( - "snapToInterval", read(context, props, "snapToInterval", 0.f)); - json.boolean("snapToStart", read(context, props, "snapToStart", true)); - json.boolean("snapToEnd", read(context, props, "snapToEnd", true)); - json.boolean( - "disableIntervalMomentum", - read(context, props, "disableIntervalMomentum", false)); - std::string offsets = "["; - for (const auto offset : - read>(context, props, "snapToOffsets", {})) { - if (offsets.size() > 1) { - offsets += ','; - } - char text[40]; - std::snprintf(text, sizeof(text), "%.9g", static_cast(offset)); - offsets += text; - } - offsets += ']'; - std::string body = json.body(); - body += ",\"snapToOffsets\":" + offsets; - JsonBody tail; - switch (read( - context, props, "snapToAlignment", ScrollViewSnapToAlignment::Start)) { - case ScrollViewSnapToAlignment::Center: - tail.string("snapToAlignment", "center"); - break; - case ScrollViewSnapToAlignment::End: - tail.string("snapToAlignment", "end"); - break; - default: - tail.string("snapToAlignment", "start"); - break; - } - tail.boolean("horizontal", horizontal); - tail.boolean("enabled", read(context, props, "scrollEnabled", true)); - tail.boolean("indicator", horizontal ? horizontalIndicator : vertical); - body += "," + tail.body(); - return body; -} - -LoomTextInput parseLoomTextInput( - const PropsParserContext& context, - const folly::dynamic& props) { - LoomTextInput input; - JsonBody json; - const auto text = read(context, props, "text", ""); - json.string("text", text); - json.string( - "placeholder", read(context, props, "placeholder", "")); - json.number( - "selectionColor", - argb(read(context, props, "selectionColor", SharedColor{}))); - json.boolean("multiline", read(context, props, "multiline", false)); - json.number( - "placeholderTextColor", - argb(read( - context, props, "placeholderTextColor", SharedColor{}))); - std::string submit = "default"; - if (const auto* value = find(props, "submitBehavior")) { - if (value->isString()) { - const auto& name = value->getString(); - if (name == "submit" || name == "blurAndSubmit" || name == "newline") { - submit = name; - } - } - } - json.string("submitBehavior", submit); - const auto maxLength = - read(context, props, "maxLength", std::numeric_limits::max()); - if (maxLength != std::numeric_limits::max()) { - json.number("maxLength", maxLength); - } - json.boolean( - "contextMenuHidden", - read(context, props, "contextMenuHidden", false)); - json.boolean("caretHidden", read(context, props, "caretHidden", false)); - json.boolean( - "selectTextOnFocus", - read(context, props, "selectTextOnFocus", false)); - json.boolean( - "editable", - read(context, props, "editable", true) && - !read(context, props, "readOnly", false)); - json.boolean("secure", read(context, props, "secureTextEntry", false)); - input.eventCount = read(context, props, "mostRecentEventCount", 0); - json.number("eventCount", static_cast(input.eventCount)); - int32_t start = 0; - int32_t end = 0; - bool selectionSet = false; - if (const auto* selection = find(props, "selection")) { - if (selection->isObject()) { - const auto* from = selection->get_ptr("start"); - const auto* to = selection->get_ptr("end"); - if (from != nullptr && from->isNumber()) { - start = static_cast(from->asInt()); - selectionSet = true; - } - if (to != nullptr && to->isNumber()) { - end = static_cast(to->asInt()); - selectionSet = true; - } - } - } - json.boolean("selectionSet", selectionSet); - if (!selectionSet) { - start = end = utf16Length(text); - } - json.number("selectionStart", start); - json.number("selectionEnd", end); - input.body = json.body(); - return input; -} - -bool parseLoomModalVisible(const folly::dynamic& props) { - const auto* visible = find(props, "visible"); - return visible == nullptr || !visible->isBool() || visible->asBool(); -} - -} // namespace rngpui - -#endif // LOOM_RENDERER diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomComponentProps.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomComponentProps.h deleted file mode 100644 index 222630dedd..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomComponentProps.h +++ /dev/null @@ -1,63 +0,0 @@ -// The props of the built-in components that carry more than view props -// (Image, ScrollView, TextInput, Modal), read from Loom's raw props into the -// JSON the Rust renderer reads and the few typed values the host needs. -#pragma once - -#if LOOM_RENDERER - -#include -#include -#include - -#include - -#include -#include -#include - -namespace rngpui { - -/// A JSON object assembled key by key; `body` is what lies between the braces. -class JsonBody { - public: - void number(const char* key, double value); - void boolean(const char* key, bool value); - void string(const char* key, const std::string& value); - const std::string& body() const { - return body_; - } - - private: - void begin(const char* key); - std::string body_; -}; - -struct LoomImage { - std::vector sources; - float blurRadius{0}; - std::string body; -}; - -struct LoomTextInput { - std::string body; - int64_t eventCount{0}; -}; - -LoomImage parseLoomImage( - const facebook::react::PropsParserContext& context, - const folly::dynamic& props); -std::string parseLoomScrollView( - const facebook::react::PropsParserContext& context, - const folly::dynamic& props); -LoomTextInput parseLoomTextInput( - const facebook::react::PropsParserContext& context, - const folly::dynamic& props); -/// Whether a Modal is visible (`true` when the prop is absent). -bool parseLoomModalVisible(const folly::dynamic& props); - -/// `{` + body + extra + `}`. -std::string closeJson(const std::string& body, const std::string& extra); - -} // namespace rngpui - -#endif // LOOM_RENDERER diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomViewProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomViewProps.cpp deleted file mode 100644 index 16e35da6f5..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomViewProps.cpp +++ /dev/null @@ -1,696 +0,0 @@ -#if LOOM_RENDERER - -#include "LoomViewProps.h" - -#include "MountBatchBuilder.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include - -namespace rngpui { - -using namespace facebook::react; -namespace yoga = facebook::yoga; - -namespace { - -struct ParseState { - const PropsParserContext& context; - ViewPropsFlat& view; - LoomViewFlags& flags; - std::unique_ptr& deps; - - CascadedBorderColors colors; - CascadedBorderStyles styles; - CascadedBorderRadii radii; - CascadedBorderWidths widths; - std::vector backgroundImage; - std::vector backgroundSize; - std::vector backgroundPosition; - std::vector backgroundRepeat; - std::optional accessibilityState; - AccessibilityValue accessibilityValue; - const folly::dynamic* accessibilityRole{nullptr}; - const folly::dynamic* role{nullptr}; - bool contextMenu{false}; - bool contextMenuCapture{false}; - bool wheel{false}; - bool wheelCapture{false}; - - LoomViewDeps& ensureDeps() { - if (!deps) { - deps = std::make_unique(); - } - return *deps; - } -}; - -using Handler = void (*)(ParseState&, const folly::dynamic&); - -template -bool convert(ParseState& state, const folly::dynamic& value, T& out) { - if (value.isNull()) { - return false; - } - try { - fromRawValue(state.context, RawValue(value), out); - return true; - } catch (const std::exception& error) { - LOG(ERROR) << "Loom: cannot convert a view prop: " << error.what(); - return false; - } -} - -template -T converted(ParseState& state, const folly::dynamic& value, T fallback = {}) { - T result = fallback; - if (!convert(state, value, result)) { - return fallback; - } - return result; -} - -void setOpacity(ParseState& state, const folly::dynamic& value) { - state.view.opacity = converted(state, value, 1.f); -} - -void setBackgroundColor(ParseState& state, const folly::dynamic& value) { - state.view.background_color = - argb(converted(state, value, SharedColor{})); -} - -void setBackgroundImage(ParseState& state, const folly::dynamic& value) { - state.backgroundImage = - converted>(state, value, {}); -} - -void setBackgroundSize(ParseState& state, const folly::dynamic& value) { - state.backgroundSize = - converted>(state, value, {}); -} - -void setBackgroundPosition(ParseState& state, const folly::dynamic& value) { - state.backgroundPosition = - converted>(state, value, {}); -} - -void setBackgroundRepeat(ParseState& state, const folly::dynamic& value) { - state.backgroundRepeat = - converted>(state, value, {}); -} - -void setBoxShadow(ParseState& state, const folly::dynamic& value) { - for (const auto& shadow : - converted>(state, value, {})) { - state.view.shadows.push_back( - {shadow.offsetX, - shadow.offsetY, - shadow.blurRadius, - shadow.spreadDistance, - argb(shadow.color), - shadow.inset}); - } -} - -void setFilter(ParseState& state, const folly::dynamic& value) { - auto json = - filterJson(converted>(state, value, {})); - if (!json.empty()) { - state.view.filter_json = rust::String(json); - } -} - -void setMixBlendMode(ParseState& state, const folly::dynamic& value) { - state.view.mix_blend_mode = static_cast( - converted(state, value, BlendMode::Normal)); -} - -void setIsolation(ParseState& state, const folly::dynamic& value) { - state.view.isolate = - converted(state, value, Isolation::Auto) == Isolation::Isolate; -} - -void setHitSlop(ParseState& state, const folly::dynamic& value) { - const auto slop = converted(state, value, {}); - state.view.hit_slop = {slop.left, slop.top, slop.right, slop.bottom}; -} - -void setBackfaceVisibility(ParseState& state, const folly::dynamic& value) { - state.view.backface_hidden = - converted(state, value, BackfaceVisibility::Auto) == - BackfaceVisibility::Hidden; -} - -void setOutlineColor(ParseState& state, const folly::dynamic& value) { - state.view.outline_color = - argb(converted(state, value, SharedColor{})); -} - -void setOutlineWidth(ParseState& state, const folly::dynamic& value) { - state.view.outline_width = converted(state, value, 0.f); -} - -void setOutlineOffset(ParseState& state, const folly::dynamic& value) { - state.view.outline_offset = converted(state, value, 0.f); -} - -void setOutlineStyle(ParseState& state, const folly::dynamic& value) { - state.view.outline_style = static_cast( - converted(state, value, OutlineStyle::Solid)); -} - -void setOverflow(ParseState& state, const folly::dynamic& value) { - state.view.overflow_hidden = - converted(state, value, yoga::Overflow::Visible) != - yoga::Overflow::Visible; -} - -void setPointerEvents(ParseState& state, const folly::dynamic& value) { - state.view.pointer_events = static_cast( - converted(state, value, PointerEventsMode::Auto)); -} - -void setCursor(ParseState& state, const folly::dynamic& value) { - state.view.cursor = - static_cast(converted(state, value, Cursor::Auto)); -} - -void setTransform(ParseState& state, const folly::dynamic& value) { - auto transform = converted(state, value, {}); - if (!transform.operations.empty()) { - state.ensureDeps().transform = std::move(transform); - } -} - -void setTransformOrigin(ParseState& state, const folly::dynamic& value) { - const auto origin = converted(state, value, {}); - if (origin.isSet()) { - state.ensureDeps().transformOrigin = origin; - } -} - -template -void setBorderColor(ParseState& state, const folly::dynamic& value) { - SharedColor color; - (state.colors.*Member) = convert(state, value, color) - ? std::optional(color) - : std::nullopt; -} - -template -void setBorderStyle(ParseState& state, const folly::dynamic& value) { - BorderStyle style{}; - (state.styles.*Member) = convert(state, value, style) - ? std::optional(style) - : std::nullopt; -} - -template -void setBorderRadius(ParseState& state, const folly::dynamic& value) { - ValueUnit unit; - (state.radii.*Member) = convert(state, value, unit) - ? std::optional(unit) - : std::nullopt; -} - -template -void setBorderWidth(ParseState& state, const folly::dynamic& value) { - yoga::Style::Length length; - (state.widths.*Member) = convert(state, value, length) - ? optionalFloatFromYogaValue(length) - : std::nullopt; -} - -void setBool(bool& field, ParseState& state, const folly::dynamic& value) { - field = converted(state, value, false); -} - -void setString( - rust::String& field, - ParseState& state, - const folly::dynamic& value) { - auto text = converted(state, value, std::string{}); - if (!text.empty()) { - field = rust::String(text); - } -} - -#define BOOL_FIELD(handler, field) \ - void handler(ParseState& state, const folly::dynamic& value) { \ - setBool(state.view.field, state, value); \ - } -#define STRING_FIELD(handler, field) \ - void handler(ParseState& state, const folly::dynamic& value) { \ - setString(state.view.field, state, value); \ - } - -BOOL_FIELD(setAccessible, accessible) -BOOL_FIELD(setAccessibilityViewIsModal, accessibility_modal) -BOOL_FIELD(setAccessibilityElementsHidden, accessibility_hidden) -BOOL_FIELD( - setAccessibilityIgnoresInvertColors, - accessibility_ignores_invert_colors) -BOOL_FIELD( - setAccessibilityShowsLargeContent, - accessibility_large_content_enabled) -BOOL_FIELD(setOnAccessibilityTap, accessibility_has_tap_listener) -BOOL_FIELD(setOnAccessibilityMagicTap, accessibility_has_magic_tap_listener) -BOOL_FIELD(setOnAccessibilityEscape, accessibility_has_escape_listener) -BOOL_FIELD(setOnAccessibilityAction, accessibility_has_action_listener) -BOOL_FIELD(setOnLayout, on_layout) -BOOL_FIELD(setFocusable, focusable) -BOOL_FIELD(setDesktopDragRegion, desktop_drag_region) -BOOL_FIELD(setAcceptsFiles, accepts_files) -BOOL_FIELD(setDraggable, draggable) -BOOL_FIELD(setDroppable, droppable) -STRING_FIELD(setTestId, test_id) -STRING_FIELD(setNativeId, accessibility_native_id) -STRING_FIELD(setAccessibilityLabel, accessibility_label) -STRING_FIELD(setAccessibilityHint, accessibility_hint) -STRING_FIELD(setAccessibilityLanguage, accessibility_language) -STRING_FIELD( - setAccessibilityLargeContentTitle, - accessibility_large_content_title) -STRING_FIELD(setGroup, group) -STRING_FIELD(setHoverStyle, hover_style) -STRING_FIELD(setActiveStyle, active_style) -STRING_FIELD(setFocusStyle, focus_style) -STRING_FIELD(setFocusVisibleStyle, focus_visible_style) -STRING_FIELD(setGroupHoverStyle, group_hover_style) -STRING_FIELD(setGroupActiveStyle, group_active_style) -STRING_FIELD(setDragOverStyle, drag_over_style) -STRING_FIELD(setTooltip, tooltip) - -void setAccessibilityRespondsToInteraction( - ParseState& state, - const folly::dynamic& value) { - state.view.accessibility_responds_to_interaction = - converted(state, value, true); -} - -void setOnContextMenu(ParseState& state, const folly::dynamic& value) { - state.contextMenu = converted(state, value, false); -} - -void setOnContextMenuCapture(ParseState& state, const folly::dynamic& value) { - state.contextMenuCapture = converted(state, value, false); -} - -void setOnWheel(ParseState& state, const folly::dynamic& value) { - state.wheel = converted(state, value, false); -} - -void setOnWheelCapture(ParseState& state, const folly::dynamic& value) { - state.wheelCapture = converted(state, value, false); -} - -void setAccessibilityState(ParseState& state, const folly::dynamic& value) { - AccessibilityState parsed; - state.accessibilityState = convert(state, value, parsed) - ? std::optional(parsed) - : std::nullopt; -} - -void setAccessibilityValue(ParseState& state, const folly::dynamic& value) { - state.accessibilityValue = converted(state, value, {}); -} - -void setAccessibilityActions(ParseState& state, const folly::dynamic& value) { - for (const auto& action : - converted>(state, value, {})) { - state.view.accessibility_actions.push_back( - {action.name, action.label.value_or("")}); - } -} - -void setAccessibilityOrder(ParseState& state, const folly::dynamic& value) { - for (const auto& tag : - converted>(state, value, {})) { - state.view.accessibility_order.push_back(tag); - } -} - -void setAccessibilityLabelledBy( - ParseState& state, - const folly::dynamic& value) { - for (const auto& nativeId : - converted(state, value, {}).value) { - state.view.accessibility_labelled_by.push_back(nativeId); - } -} - -void setAccessibilityLiveRegion( - ParseState& state, - const folly::dynamic& value) { - state.view.accessibility_live_region = - static_cast(converted( - state, value, AccessibilityLiveRegion::None)); -} - -void setImportantForAccessibility( - ParseState& state, - const folly::dynamic& value) { - state.view.accessibility_important = - static_cast(converted( - state, value, ImportantForAccessibility::Auto)); -} - -void setAccessibilityRole(ParseState& state, const folly::dynamic& value) { - state.accessibilityRole = value.isNull() ? nullptr : &value; -} - -void setRole(ParseState& state, const folly::dynamic& value) { - state.role = value.isNull() ? nullptr : &value; -} - -void setSelectable(ParseState& state, const folly::dynamic& value) { - state.flags.selectable = converted(state, value, false); -} - -void setOnTextLayout(ParseState& state, const folly::dynamic& value) { - state.flags.onTextLayout = converted(state, value, false); -} - -#define EDGE_ENTRIES(Fn, Type, Prefix, Suffix) \ - {Prefix "Left" Suffix, &Fn<&Type::left>}, \ - {Prefix "Right" Suffix, &Fn<&Type::right>}, \ - {Prefix "Top" Suffix, &Fn<&Type::top>}, \ - {Prefix "Bottom" Suffix, &Fn<&Type::bottom>}, \ - {Prefix "Start" Suffix, &Fn<&Type::start>}, \ - {Prefix "End" Suffix, &Fn<&Type::end>}, \ - {Prefix "Horizontal" Suffix, &Fn<&Type::horizontal>}, \ - {Prefix "Vertical" Suffix, &Fn<&Type::vertical>}, { \ - Prefix "" Suffix, &Fn<&Type::all> \ - } - -#define BLOCK_ENTRIES(Fn, Type, Prefix, Suffix) \ - {Prefix "Block" Suffix, &Fn<&Type::block>}, \ - {Prefix "BlockEnd" Suffix, &Fn<&Type::blockEnd>}, { \ - Prefix "BlockStart" Suffix, &Fn<&Type::blockStart> \ - } - -const std::unordered_map& handlers() { - static const std::unordered_map table = { - {"opacity", &setOpacity}, - {"backgroundColor", &setBackgroundColor}, - {"backgroundImage", &setBackgroundImage}, - {"experimental_backgroundImage", &setBackgroundImage}, - {"experimental_backgroundSize", &setBackgroundSize}, - {"experimental_backgroundPosition", &setBackgroundPosition}, - {"experimental_backgroundRepeat", &setBackgroundRepeat}, - {"boxShadow", &setBoxShadow}, - {"filter", &setFilter}, - {"mixBlendMode", &setMixBlendMode}, - {"isolation", &setIsolation}, - {"hitSlop", &setHitSlop}, - {"backfaceVisibility", &setBackfaceVisibility}, - {"outlineColor", &setOutlineColor}, - {"outlineWidth", &setOutlineWidth}, - {"outlineOffset", &setOutlineOffset}, - {"outlineStyle", &setOutlineStyle}, - {"overflow", &setOverflow}, - {"pointerEvents", &setPointerEvents}, - {"cursor", &setCursor}, - {"transform", &setTransform}, - {"transformOrigin", &setTransformOrigin}, - EDGE_ENTRIES(setBorderColor, CascadedBorderColors, "border", "Color"), - BLOCK_ENTRIES(setBorderColor, CascadedBorderColors, "border", "Color"), - EDGE_ENTRIES(setBorderStyle, CascadedBorderStyles, "border", "Style"), - BLOCK_ENTRIES(setBorderStyle, CascadedBorderStyles, "border", "Style"), - EDGE_ENTRIES(setBorderWidth, CascadedBorderWidths, "border", "Width"), - {"borderTopLeftRadius", &setBorderRadius<&CascadedBorderRadii::topLeft>}, - {"borderTopRightRadius", - &setBorderRadius<&CascadedBorderRadii::topRight>}, - {"borderBottomLeftRadius", - &setBorderRadius<&CascadedBorderRadii::bottomLeft>}, - {"borderBottomRightRadius", - &setBorderRadius<&CascadedBorderRadii::bottomRight>}, - {"borderTopStartRadius", - &setBorderRadius<&CascadedBorderRadii::topStart>}, - {"borderTopEndRadius", &setBorderRadius<&CascadedBorderRadii::topEnd>}, - {"borderBottomStartRadius", - &setBorderRadius<&CascadedBorderRadii::bottomStart>}, - {"borderBottomEndRadius", - &setBorderRadius<&CascadedBorderRadii::bottomEnd>}, - {"borderEndEndRadius", &setBorderRadius<&CascadedBorderRadii::endEnd>}, - {"borderEndStartRadius", - &setBorderRadius<&CascadedBorderRadii::endStart>}, - {"borderStartEndRadius", - &setBorderRadius<&CascadedBorderRadii::startEnd>}, - {"borderStartStartRadius", - &setBorderRadius<&CascadedBorderRadii::startStart>}, - {"borderRadius", &setBorderRadius<&CascadedBorderRadii::all>}, - {"accessible", &setAccessible}, - {"accessibilityViewIsModal", &setAccessibilityViewIsModal}, - {"accessibilityElementsHidden", &setAccessibilityElementsHidden}, - {"accessibilityIgnoresInvertColors", - &setAccessibilityIgnoresInvertColors}, - {"accessibilityShowsLargeContentViewer", - &setAccessibilityShowsLargeContent}, - {"accessibilityRespondsToUserInteraction", - &setAccessibilityRespondsToInteraction}, - {"onAccessibilityTap", &setOnAccessibilityTap}, - {"onAccessibilityMagicTap", &setOnAccessibilityMagicTap}, - {"onAccessibilityEscape", &setOnAccessibilityEscape}, - {"onAccessibilityAction", &setOnAccessibilityAction}, - {"accessibilityLabel", &setAccessibilityLabel}, - {"accessibilityHint", &setAccessibilityHint}, - {"accessibilityLanguage", &setAccessibilityLanguage}, - {"accessibilityLargeContentTitle", &setAccessibilityLargeContentTitle}, - {"accessibilityState", &setAccessibilityState}, - {"accessibilityValue", &setAccessibilityValue}, - {"accessibilityActions", &setAccessibilityActions}, - {"experimental_accessibilityOrder", &setAccessibilityOrder}, - {"accessibilityLabelledBy", &setAccessibilityLabelledBy}, - {"accessibilityLiveRegion", &setAccessibilityLiveRegion}, - {"importantForAccessibility", &setImportantForAccessibility}, - {"accessibilityRole", &setAccessibilityRole}, - {"role", &setRole}, - {"testID", &setTestId}, - {"nativeID", &setNativeId}, - {"focusable", &setFocusable}, - {"desktopDragRegion", &setDesktopDragRegion}, - {"group", &setGroup}, - {"hoverStyle", &setHoverStyle}, - {"activeStyle", &setActiveStyle}, - {"focusStyle", &setFocusStyle}, - {"focusVisibleStyle", &setFocusVisibleStyle}, - {"groupHoverStyle", &setGroupHoverStyle}, - {"groupActiveStyle", &setGroupActiveStyle}, - {"dragOverStyle", &setDragOverStyle}, - {"acceptsFiles", &setAcceptsFiles}, - {"tooltip", &setTooltip}, - {"draggable", &setDraggable}, - {"droppable", &setDroppable}, - {"onContextMenu", &setOnContextMenu}, - {"onContextMenuCapture", &setOnContextMenuCapture}, - {"onWheel", &setOnWheel}, - {"onWheelCapture", &setOnWheelCapture}, - {"onLayout", &setOnLayout}, - {"selectable", &setSelectable}, - {"onTextLayout", &setOnTextLayout}, - }; - return table; -} - -void finishAccessibility(ParseState& state) { - auto& view = state.view; - // `role` wins over `accessibilityRole` for both the trait and the name. - const auto* precedent = - state.role != nullptr ? state.role : state.accessibilityRole; - AccessibilityTraits traits = AccessibilityTraits::None; - if (precedent != nullptr) { - convert(state, *precedent, traits); - } - if (state.accessibilityRole != nullptr) { - view.accessibility_role = - converted(state, *state.accessibilityRole, std::string{}); - } - if (state.role != nullptr) { - const auto role = converted(state, *state.role, Role::None); - if (role != Role::None) { - view.accessibility_role = toString(role); - } - } - view.accessibility_traits = static_cast(traits); - view.accessibility_disabled = (view.accessibility_traits & (1u << 8)) != 0; - view.accessibility_selected = (view.accessibility_traits & (1u << 3)) != 0; - - const auto& value = state.accessibilityValue; - if (value.min) { - view.accessibility_has_value_min = true; - view.accessibility_value_min = *value.min; - } - if (value.max) { - view.accessibility_has_value_max = true; - view.accessibility_value_max = *value.max; - } - if (value.now) { - view.accessibility_has_value_now = true; - view.accessibility_value_now = *value.now; - } - if (value.text) { - view.accessibility_value_text = *value.text; - } - - if (state.accessibilityState) { - const auto& accessibilityState = *state.accessibilityState; - view.accessibility_disabled = - accessibilityState.disabled || view.accessibility_disabled; - view.accessibility_selected = - accessibilityState.selected || view.accessibility_selected; - view.accessibility_busy = accessibilityState.busy; - switch (accessibilityState.checked) { - case AccessibilityState::Unchecked: - view.accessibility_checked = 1; - break; - case AccessibilityState::Checked: - view.accessibility_checked = 2; - break; - case AccessibilityState::Mixed: - view.accessibility_checked = 3; - break; - case AccessibilityState::None: - break; - } - if (accessibilityState.expanded) { - view.accessibility_expanded = *accessibilityState.expanded ? 1 : 0; - } - } -} - -} // namespace - -void initLoomView(ViewPropsFlat& view) { - view.opacity = 1.f; - view.outline_style = static_cast(OutlineStyle::Solid); - view.accessibility_responds_to_interaction = true; - view.accessibility_expanded = -1; - view.transform = Transform::Identity().matrix; -} - -void parseLoomViewProps( - const PropsParserContext& context, - const folly::dynamic& props, - ViewPropsFlat& view, - LoomViewFlags& flags, - std::unique_ptr& deps) { - ParseState state{context, view, flags, deps}; - const auto& table = handlers(); - if (props.isObject()) { - for (const auto& [key, value] : props.items()) { - if (!key.isString()) { - continue; - } - const auto found = table.find(key.getString()); - if (found != table.end()) { - found->second(state, value); - } - } - } - - if (!state.backgroundImage.empty()) { - view.background_json = backgroundJson( - state.backgroundImage, - state.backgroundSize, - state.backgroundPosition, - state.backgroundRepeat); - } - - const auto colors = state.colors.resolve(false, SharedColor{}); - view.border_colors = { - argb(colors.left), - argb(colors.top), - argb(colors.right), - argb(colors.bottom)}; - const auto styles = state.styles.resolve(false, BorderStyle::Solid); - view.border_styles = { - static_cast(styles.left), - static_cast(styles.top), - static_cast(styles.right), - static_cast(styles.bottom)}; - - const auto widths = state.widths.resolve(false, 0); - view.border_widths = {widths.left, widths.top, widths.right, widths.bottom}; - if (state.widths.start || state.widths.end) { - auto& dependent = state.ensureDeps(); - dependent.widths = state.widths; - dependent.widthsDirectional = true; - } - - const auto radii = state.radii.resolve(false, ValueUnit{0, UnitType::Point}); - const auto point = [](const ValueUnit& unit) { return unit.resolve(0); }; - view.border_radii = { - point(radii.topLeft), - point(radii.topRight), - point(radii.bottomRight), - point(radii.bottomLeft)}; - for (const auto* corner : - {&radii.topLeft, - &radii.topRight, - &radii.bottomRight, - &radii.bottomLeft}) { - if (corner->unit == UnitType::Percent) { - auto& dependent = state.ensureDeps(); - dependent.radii = state.radii; - dependent.radiiPercent = true; - break; - } - } - - finishAccessibility(state); - view.on_context_menu = state.contextMenu || state.contextMenuCapture; - view.on_wheel = state.wheel || state.wheelCapture; - if (deps && deps->transformOrigin.isSet()) { - view.transform_origin_set = true; - } -} - -void resolveLoomViewLayout( - ViewPropsFlat& view, - const LoomViewDeps* deps, - const Size& frameSize, - bool rtl, - uint8_t mask) { - if (deps == nullptr) { - return; - } - if ((mask & kPatchRadii) != 0 && deps->radiiPercent) { - const auto radii = - deps->radii.resolve(false, ValueUnit{0, UnitType::Point}); - const auto side = std::min(frameSize.width, frameSize.height); - view.border_radii = { - radii.topLeft.resolve(side), - radii.topRight.resolve(side), - radii.bottomRight.resolve(side), - radii.bottomLeft.resolve(side)}; - } - if ((mask & kPatchWidths) != 0 && deps->widthsDirectional) { - const auto widths = deps->widths.resolve(rtl, 0); - view.border_widths = {widths.left, widths.top, widths.right, widths.bottom}; - } - if ((mask & kPatchTransform) != 0) { - const auto transform = BaseViewProps::resolveTransform( - frameSize, deps->transform, deps->transformOrigin); - view.transform = transform.matrix; - view.has_transform = !(transform == Transform::Identity()); - view.transform_origin_set = deps->transformOrigin.isSet(); - } -} - -} // namespace rngpui - -#endif // LOOM_RENDERER diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomViewProps.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomViewProps.h deleted file mode 100644 index 2364552d51..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/LoomViewProps.h +++ /dev/null @@ -1,71 +0,0 @@ -// Loom's raw view props turned into the flat props the Rust renderer reads, -// without a Fabric `Props` object: the parser visits only the keys a node has -// and converts each value with React Native's own conversions. -#pragma once - -#if LOOM_RENDERER - -#include "rn-gpui-sys/src/lib.rs.h" // cxx bridge - -#include -#include -#include -#include -#include -#include - -#include -#include - -namespace rngpui { - -/// What cannot be resolved until the node's frame and direction are known. -/// Allocated only for a node that has such a prop. -struct LoomViewDeps { - facebook::react::Transform transform; - facebook::react::TransformOrigin transformOrigin; - facebook::react::CascadedBorderRadii radii; - facebook::react::CascadedBorderWidths widths; - bool radiiPercent{false}; - bool widthsDirectional{false}; -}; - -struct LoomViewFlags { - /// `Text.selectable`. - bool selectable{false}; - /// A text node reports its wrapped lines. - bool onTextLayout{false}; -}; - -/// The groups of `ViewPropsFlat` that `resolveLoomViewLayout` rewrites. -enum LoomLayoutPatch : uint8_t { - kPatchInsets = 1, - kPatchWidths = 2, - kPatchRadii = 4, - kPatchTransform = 8, -}; - -/// Sets the props whose unset value is not zero on a value-initialized view: -/// what a node starts as. -void initLoomView(ViewPropsFlat& view); - -/// Fills `view` from every key of `props` (the node's whole prop set). -void parseLoomViewProps( - const facebook::react::PropsParserContext& context, - const folly::dynamic& props, - ViewPropsFlat& view, - LoomViewFlags& flags, - std::unique_ptr& deps); - -/// Writes what depends on layout into `view`: the groups in `mask` that `deps` -/// governs, and always the content insets and display. -void resolveLoomViewLayout( - ViewPropsFlat& view, - const LoomViewDeps* deps, - const facebook::react::Size& frameSize, - bool rtl, - uint8_t mask); - -} // namespace rngpui - -#endif // LOOM_RENDERER diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/MountBatchBuilder.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/MountBatchBuilder.cpp deleted file mode 100644 index 1893587c80..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/MountBatchBuilder.cpp +++ /dev/null @@ -1,781 +0,0 @@ -#include "MountBatchBuilder.h" -#include "GpuiHostComponentsCpp.h" -#include "GpuiModules.h" -#include "GpuiTextMeasure.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rngpui { -using namespace facebook::react; - -uint32_t argb(const SharedColor& color) { - if (!color) { - return 0; - } - auto components = colorComponentsFromColor(color); - auto to8 = [](float v) { - return static_cast(std::lround(v * 255.f)) & 0xFF; - }; - return (to8(components.alpha) << 24) | (to8(components.red) << 16) | - (to8(components.green) << 8) | to8(components.blue); -} - -// Shadow and fit settings: the shadow is the first fragment's, as alignment is. -static void applyParagraphExtras( - ParagraphFlat& out, - const AttributedString::Fragments& fragments, - const ParagraphAttributes& attributes) { - out.adjusts_to_fit = attributes.adjustsFontSizeToFit; - out.min_font_scale = std::isnan(attributes.minimumFontScale) - ? 0.f - : attributes.minimumFontScale; - if (fragments.empty()) { - return; - } - const auto& first = fragments.front().textAttributes; - if (first.textShadowColor) { - out.shadow_color = argb(first.textShadowColor); - if (first.textShadowOffset) { - out.shadow_dx = first.textShadowOffset->width; - out.shadow_dy = first.textShadowOffset->height; - } - out.shadow_radius = - std::isnan(first.textShadowRadius) ? 0.f : first.textShadowRadius; - } -} - -static folly::dynamic unitJson(const ValueUnit& unit) { - switch (unit.unit) { - case UnitType::Point: - return folly::dynamic::object("unit", "pt")("value", unit.value); - case UnitType::Percent: - return folly::dynamic::object("unit", "pct")("value", unit.value); - default: - return folly::dynamic::object("unit", "none")("value", 0); - } -} - -// A repeating gradient arrives with a first color stop far before the start. -static bool hasRepeatingMarker(const std::vector& stops) { - return !stops.empty() && stops.front().position.unit == UnitType::Point && - stops.front().position.value <= -99999999.f; -} - -static folly::dynamic stopsJson(const std::vector& stops) { - folly::dynamic array = folly::dynamic::array; - for (const auto& stop : stops) { - if (&stop == &stops.front() && hasRepeatingMarker(stops)) { - continue; - } - array.push_back(folly::dynamic::object("color", argb(stop.color))( - "position", unitJson(stop.position))); - } - return array; -} - -static folly::dynamic optionalUnitJson(const std::optional& unit) { - return unit ? unitJson(*unit) : folly::dynamic(nullptr); -} - -// The gradients, their size, position and repeat, as JSON the renderer reads. -std::string backgroundJson( - const std::vector& images, - const std::vector& backgroundSizes, - const std::vector& backgroundPositions, - const std::vector& backgroundRepeats) { - if (images.empty()) { - return {}; - } - folly::dynamic layers = folly::dynamic::array; - for (const auto& image : images) { - if (const auto* linear = std::get_if(&image)) { - folly::dynamic layer = folly::dynamic::object("kind", "linear"); - if (const auto* angle = std::get_if(&linear->direction)) { - layer["angle"] = *angle; - } else if ( - const auto* keyword = - std::get_if(&linear->direction)) { - switch (*keyword) { - case GradientKeyword::ToTopRight: - layer["keyword"] = "top-right"; - break; - case GradientKeyword::ToBottomRight: - layer["keyword"] = "bottom-right"; - break; - case GradientKeyword::ToTopLeft: - layer["keyword"] = "top-left"; - break; - case GradientKeyword::ToBottomLeft: - layer["keyword"] = "bottom-left"; - break; - } - } - layer["stops"] = stopsJson(linear->colorStops); - layer["repeating"] = hasRepeatingMarker(linear->colorStops); - layers.push_back(std::move(layer)); - } else if (const auto* radial = std::get_if(&image)) { - folly::dynamic layer = folly::dynamic::object("kind", "radial"); - layer["shape"] = - radial->shape == RadialGradientShape::Circle ? "circle" : "ellipse"; - if (const auto* keyword = std::get_if( - &radial->size.value)) { - switch (*keyword) { - case RadialGradientSize::SizeKeyword::ClosestSide: - layer["size"] = "closest-side"; - break; - case RadialGradientSize::SizeKeyword::FarthestSide: - layer["size"] = "farthest-side"; - break; - case RadialGradientSize::SizeKeyword::ClosestCorner: - layer["size"] = "closest-corner"; - break; - case RadialGradientSize::SizeKeyword::FarthestCorner: - layer["size"] = "farthest-corner"; - break; - } - } else if ( - const auto* dimensions = std::get_if( - &radial->size.value)) { - layer["size"] = folly::dynamic::object("x", unitJson(dimensions->x))( - "y", unitJson(dimensions->y)); - } - layer["position"] = - folly::dynamic::object("top", optionalUnitJson(radial->position.top))( - "left", optionalUnitJson(radial->position.left))( - "right", optionalUnitJson(radial->position.right))( - "bottom", optionalUnitJson(radial->position.bottom)); - layer["stops"] = stopsJson(radial->colorStops); - layer["repeating"] = hasRepeatingMarker(radial->colorStops); - layers.push_back(std::move(layer)); - } - } - folly::dynamic sizes = folly::dynamic::array; - for (const auto& size : backgroundSizes) { - if (const auto* keyword = std::get_if(&size)) { - sizes.push_back( - *keyword == BackgroundSizeKeyword::Cover ? "cover" : "contain"); - } else if ( - const auto* lengths = - std::get_if(&size)) { - sizes.push_back(folly::dynamic::object( - "x", - lengths->isXAuto() ? folly::dynamic(nullptr) - : unitJson(std::get(lengths->x)))( - "y", - lengths->isYAuto() ? folly::dynamic(nullptr) - : unitJson(std::get(lengths->y)))); - } - } - folly::dynamic positions = folly::dynamic::array; - for (const auto& position : backgroundPositions) { - positions.push_back( - folly::dynamic::object("top", optionalUnitJson(position.top))( - "left", optionalUnitJson(position.left))( - "right", optionalUnitJson(position.right))( - "bottom", optionalUnitJson(position.bottom))); - } - auto repeatName = [](BackgroundRepeatStyle style) { - switch (style) { - case BackgroundRepeatStyle::Space: - return "space"; - case BackgroundRepeatStyle::Round: - return "round"; - case BackgroundRepeatStyle::NoRepeat: - return "no-repeat"; - default: - return "repeat"; - } - }; - folly::dynamic repeats = folly::dynamic::array; - for (const auto& repeat : backgroundRepeats) { - repeats.push_back(folly::dynamic::object("x", repeatName(repeat.x))( - "y", repeatName(repeat.y))); - } - return folly::toJson(folly::dynamic::object("layers", layers)("sizes", sizes)( - "positions", positions)("repeats", repeats)); -} - -TextFragmentFlat flattenTextFragment( - const TextAttributes& attributes, - const std::string& text) { - TextFragmentFlat out{}; - out.text = text; - out.font_family = attributes.fontFamily; - // allowFontScaling and maxFontSizeMultiplier decide how much of the system - // text scale (carried in fontSizeMultiplier) this fragment follows. - float scale = std::isnan(attributes.fontSizeMultiplier) - ? 1.f - : attributes.fontSizeMultiplier; - if (attributes.allowFontScaling && !*attributes.allowFontScaling) { - scale = 1.f; - } else if ( - !std::isnan(attributes.maxFontSizeMultiplier) && - attributes.maxFontSizeMultiplier >= 1.f) { - scale = std::min(scale, attributes.maxFontSizeMultiplier); - } - out.font_size = - (std::isnan(attributes.fontSize) ? 14.f : attributes.fontSize) * scale; - if (attributes.textTransform) { - switch (*attributes.textTransform) { - case TextTransform::Uppercase: - out.text_transform = 1; - break; - case TextTransform::Lowercase: - out.text_transform = 2; - break; - case TextTransform::Capitalize: - out.text_transform = 3; - break; - default: - break; - } - } - out.background_color = argb(attributes.backgroundColor); - out.font_variant = attributes.fontVariant - ? static_cast(*attributes.fontVariant) - : 0; - out.font_weight = attributes.fontWeight - ? static_cast(*attributes.fontWeight) - : 400; - out.italic = - attributes.fontStyle && *attributes.fontStyle != FontStyle::Normal; - out.color = argb(attributes.foregroundColor); - out.line_height = - std::isnan(attributes.lineHeight) ? 0.f : attributes.lineHeight * scale; - out.letter_spacing = - std::isnan(attributes.letterSpacing) ? 0.f : attributes.letterSpacing; - if (attributes.textDecorationLineType) { - switch (*attributes.textDecorationLineType) { - case TextDecorationLineType::Underline: - out.underline = true; - break; - case TextDecorationLineType::Strikethrough: - out.strikethrough = true; - break; - case TextDecorationLineType::UnderlineStrikethrough: - out.underline = true; - out.strikethrough = true; - break; - case TextDecorationLineType::None: - break; - } - } - return out; -} - -// The `filter` functions in order, as `[[name, amount], ...]`; a `dropShadow` -// carries `{x, y, blur, color}` in place of the amount. -std::string filterJson(const std::vector& filter) { - if (filter.empty()) { - return {}; - } - folly::dynamic functions = folly::dynamic::array; - for (const auto& function : filter) { - if (const auto* amount = std::get_if(&function.parameters)) { - functions.push_back( - folly::dynamic::array(toString(function.type), *amount)); - } else if ( - const auto* shadow = - std::get_if(&function.parameters)) { - functions.push_back(folly::dynamic::array( - toString(function.type), - folly::dynamic::object("x", shadow->offsetX)("y", shadow->offsetY)( - "blur", shadow->standardDeviation)( - "color", static_cast(argb(shadow->color))))); - } - } - if (functions.empty()) { - return {}; - } - return folly::toJson(functions); -} - -static ViewPropsFlat flattenView(const ShadowView& shadowView) { - ViewPropsFlat out{}; - // Non-view components must remain opaque; a value-initialized flat struct - // otherwise silently turns an unrecognized props type fully transparent. - out.opacity = 1.f; - out.display_none = shadowView.layoutMetrics.displayType == DisplayType::None; - auto props = std::dynamic_pointer_cast(shadowView.props); - if (!props) { - return out; - } - - out.opacity = props->opacity; - out.background_color = argb(props->backgroundColor); - out.background_json = backgroundJson( - props->backgroundImage, - props->backgroundSize, - props->backgroundPosition, - props->backgroundRepeat); - out.filter_json = filterJson(props->filter); - out.mix_blend_mode = static_cast(props->mixBlendMode); - out.isolate = props->isolation == Isolation::Isolate; - out.hit_slop = { - props->hitSlop.left, - props->hitSlop.top, - props->hitSlop.right, - props->hitSlop.bottom}; - out.backface_hidden = props->backfaceVisibility == BackfaceVisibility::Hidden; - - // layoutMetrics.borderWidth is already fully resolved per edge; the cascaded - // props->getBorderWidths() would need the same resolve() dance as the colors. - const auto& layoutMetrics = shadowView.layoutMetrics; - out.border_widths = { - layoutMetrics.borderWidth.left, - layoutMetrics.borderWidth.top, - layoutMetrics.borderWidth.right, - layoutMetrics.borderWidth.bottom}; - out.content_insets = { - layoutMetrics.contentInsets.left, - layoutMetrics.contentInsets.top, - layoutMetrics.contentInsets.right, - layoutMetrics.contentInsets.bottom}; - - auto colors = props->borderColors.resolve(/*isRTL*/ false, SharedColor{}); - out.border_colors = { - argb(colors.left), - argb(colors.top), - argb(colors.right), - argb(colors.bottom)}; - auto borderStyles = props->borderStyles.resolve(false, BorderStyle::Solid); - out.border_styles = { - static_cast(borderStyles.left), - static_cast(borderStyles.top), - static_cast(borderStyles.right), - static_cast(borderStyles.bottom)}; - out.outline_color = argb(props->outlineColor); - out.outline_width = props->outlineWidth; - out.outline_offset = props->outlineOffset; - out.outline_style = static_cast(props->outlineStyle); - - // BorderRadii is RectangleCorners; each corner resolves to px - // against the frame's smaller side (percentage radii). - auto radii = props->borderRadii.resolve(false, ValueUnit{0, UnitType::Point}); - auto px = [&](const ValueUnit& v) { - return v.resolve(std::min( - layoutMetrics.frame.size.width, layoutMetrics.frame.size.height)); - }; - out.border_radii = { - px(radii.topLeft), - px(radii.topRight), - px(radii.bottomRight), - px(radii.bottomLeft)}; - - out.overflow_hidden = props->getClipsContentToBounds(); - out.pointer_events = static_cast(props->pointerEvents); - // `Cursor` is `enum class Cursor : uint8_t` in this exact order, starting at - // Auto = 0; `style::cursor_style` in `rn-gpui` spells the same ordinals out. - out.cursor = static_cast(props->cursor); - - for (const auto& shadow : props->boxShadow) { - out.shadows.push_back( - {shadow.offsetX, - shadow.offsetY, - shadow.blurRadius, - shadow.spreadDistance, - argb(shadow.color), - shadow.inset}); - } - - out.test_id = props->testId; - out.accessibility_native_id = props->nativeId; - out.accessible = props->accessible; - out.accessibility_label = props->accessibilityLabel; - out.accessibility_hint = props->accessibilityHint; - out.accessibility_language = props->accessibilityLanguage; - out.accessibility_role = props->accessibilityRole; - if (props->role != Role::None) { - out.accessibility_role = toString(props->role); - } - out.accessibility_traits = static_cast(props->accessibilityTraits); - for (const auto& tag : props->accessibilityOrder) { - out.accessibility_order.push_back(tag); - } - for (const auto& nativeId : props->accessibilityLabelledBy.value) { - out.accessibility_labelled_by.push_back(nativeId); - } - out.accessibility_hidden = props->accessibilityElementsHidden; - out.accessibility_modal = props->accessibilityViewIsModal; - out.accessibility_ignores_invert_colors = - props->accessibilityIgnoresInvertColors; - out.accessibility_large_content_enabled = - props->accessibilityShowsLargeContentViewer; - out.accessibility_large_content_title = props->accessibilityLargeContentTitle; - out.accessibility_responds_to_interaction = - props->accessibilityRespondsToUserInteraction; - out.accessibility_has_action_listener = props->onAccessibilityAction; - out.accessibility_has_tap_listener = props->onAccessibilityTap; - out.accessibility_has_escape_listener = props->onAccessibilityEscape; - out.accessibility_has_magic_tap_listener = props->onAccessibilityMagicTap; - out.on_layout = props->onLayout; - out.accessibility_important = - static_cast(props->importantForAccessibility); - out.accessibility_live_region = - static_cast(props->accessibilityLiveRegion); - for (const auto& action : props->accessibilityActions) { - out.accessibility_actions.push_back( - {action.name, action.label.value_or("")}); - } - out.accessibility_disabled = (out.accessibility_traits & (1u << 8)) != 0; - out.accessibility_selected = (out.accessibility_traits & (1u << 3)) != 0; - const auto& accessibilityValue = props->accessibilityValue; - if (accessibilityValue.min) { - out.accessibility_has_value_min = true; - out.accessibility_value_min = *accessibilityValue.min; - } - if (accessibilityValue.max) { - out.accessibility_has_value_max = true; - out.accessibility_value_max = *accessibilityValue.max; - } - if (accessibilityValue.now) { - out.accessibility_has_value_now = true; - out.accessibility_value_now = *accessibilityValue.now; - } - if (accessibilityValue.text) { - out.accessibility_value_text = *accessibilityValue.text; - } - if (props->accessibilityState) { - const auto& state = *props->accessibilityState; - out.accessibility_disabled = - state.disabled || (out.accessibility_traits & (1u << 8)) != 0; - out.accessibility_selected = - state.selected || (out.accessibility_traits & (1u << 3)) != 0; - out.accessibility_busy = state.busy; - switch (state.checked) { - case AccessibilityState::Unchecked: - out.accessibility_checked = 1; - break; - case AccessibilityState::Checked: - out.accessibility_checked = 2; - break; - case AccessibilityState::Mixed: - out.accessibility_checked = 3; - break; - case AccessibilityState::None: - break; - } - if (state.expanded) { - out.accessibility_expanded = *state.expanded ? 1 : 0; - } else { - out.accessibility_expanded = -1; - } - } else { - out.accessibility_expanded = -1; - } - if (auto platformProps = - std::dynamic_pointer_cast(shadowView.props)) { - out.focusable = platformProps->focusable; - out.desktop_drag_region = platformProps->desktopDragRegion; - out.on_context_menu = platformProps->onContextMenu; - out.on_wheel = platformProps->onWheel; - out.group = platformProps->group; - out.hover_style = platformProps->hoverStyle; - out.active_style = platformProps->activeStyle; - out.focus_style = platformProps->focusStyle; - out.focus_visible_style = platformProps->focusVisibleStyle; - out.group_hover_style = platformProps->groupHoverStyle; - out.group_active_style = platformProps->groupActiveStyle; - out.drag_over_style = platformProps->dragOverStyle; - out.accepts_files = platformProps->acceptsFiles; - out.tooltip = platformProps->tooltip; - out.draggable = platformProps->draggable; - out.droppable = platformProps->droppable; - } - - const auto transform = props->resolveTransform(layoutMetrics); - out.transform_origin_set = props->transformOrigin.isSet(); - out.transform = transform.matrix; - out.has_transform = !(transform == Transform::Identity()); - return out; -} - -ParagraphFlat flattenParagraphText( - const AttributedString& attributedString, - const ParagraphAttributes& attributes, - bool selectable) { - ParagraphFlat out{}; - const auto& fragments = attributedString.getFragments(); - out.fragments.reserve(fragments.size()); - for (const auto& fragment : fragments) { - out.fragments.push_back( - flattenTextFragment(fragment.textAttributes, fragment.string)); - } - - // Text alignment lives on TextAttributes, not on ParagraphAttributes: take - // it from the first fragment (they are homogeneous in practice). The - // TextAlignment enum values already match the ParagraphFlat encoding. - if (!fragments.empty() && fragments.front().textAttributes.alignment) { - out.text_align = - static_cast(*fragments.front().textAttributes.alignment); - } - - applyParagraphExtras(out, fragments, attributes); - out.selectable = selectable; - out.max_lines = attributes.maximumNumberOfLines; - // EllipsizeMode is {Clip=0, Head=1, Tail=2, Middle=3} but the GPUI slot - // encodes {0 tail, 1 head, 2 middle, 3 clip}. - switch (attributes.ellipsizeMode) { - case EllipsizeMode::Clip: - out.ellipsize = 3; - break; - case EllipsizeMode::Head: - out.ellipsize = 1; - break; - case EllipsizeMode::Tail: - out.ellipsize = 0; - break; - case EllipsizeMode::Middle: - out.ellipsize = 2; - break; - } - return out; -} - -static ParagraphFlat flattenParagraph(const ShadowView& shadowView) { - auto state = std::dynamic_pointer_cast>( - shadowView.state); - if (!state) { - return ParagraphFlat{}; - } - const auto paragraphProps = - std::dynamic_pointer_cast(shadowView.props); - const auto& data = state->getData(); - return flattenParagraphText( - data.attributedString, - data.paragraphAttributes, - paragraphProps && paragraphProps->isSelectable); -} - -ParagraphFlat flattenInputText(const AttributedString& attributedString) { - ParagraphFlat out{}; - for (const auto& fragment : attributedString.getFragments()) { - out.fragments.push_back( - flattenTextFragment(fragment.textAttributes, fragment.string)); - } - return out; -} - -rust::Str componentNameStr(const char* name) { - if (name == nullptr) { - return {}; - } - thread_local std::unordered_map cache; - if (const auto found = cache.find(name); found != cache.end() && - std::string_view(found->second.data(), found->second.size()) == name) { - return found->second; - } - static std::mutex mutex; - static std::unordered_set names; - std::string_view interned; - { - std::lock_guard lock(mutex); - interned = *names.emplace(name).first; - } - const rust::Str str(interned.data(), interned.size()); - cache.insert_or_assign(name, str); - return str; -} - -MountOp buildMountOp(const ShadowViewMutation& mutation) { - MountOp op{}; - op.kind = static_cast(mutation.type); - op.parent_tag = mutation.parentTag; - op.index = mutation.index; - - const ShadowView& shadowView = (mutation.type == ShadowViewMutation::Delete || - mutation.type == ShadowViewMutation::Remove) - ? mutation.oldChildShadowView - : mutation.newChildShadowView; - - op.tag = shadowView.tag; - op.component = componentNameStr(shadowView.componentName); - const std::string componentName(op.component.data(), op.component.size()); - { - const auto& registered = - gpuiExtensionHooks().componentProps.find(componentName); - if (registered != gpuiExtensionHooks().componentProps.end() && - shadowView.props) { - op.extension_props_json = registered->second(componentName, shadowView); - } - } - op.host_index = -1; - op.host_props_handle = 0; - op.host_emitter_handle = 0; - op.host_changed = 0; - if (rngpui::anyHostComponents() && - (mutation.type == ShadowViewMutation::Create || - mutation.type == ShadowViewMutation::Update)) { - if (const auto* entry = - rngpui::hostComponentEntry(shadowView.componentHandle)) { - op.host_index = static_cast(entry->index); - if (mutation.type == ShadowViewMutation::Create) { - op.host_props_handle = rngpui::makeHostPropsHandle(shadowView.props); - op.host_emitter_handle = - rngpui::makeHostEmitterHandle(shadowView.eventEmitter); - } else { - const auto& before = mutation.oldChildShadowView.props; - const auto& after = mutation.newChildShadowView.props; - if (before && after && before.get() != after.get()) { - uint64_t inlineWords[2] = {0, 0}; - std::vector heapWords; - uint64_t* words = inlineWords; - if (entry->changeWords > 2) { - heapWords.assign(entry->changeWords, 0); - words = heapWords.data(); - } - entry->changed(*before, *after, words); - bool any = false; - for (uint32_t word = 0; word < entry->changeWords; ++word) { - any = any || words[word] != 0; - } - if (any) { - op.host_props_handle = rngpui::makeHostPropsHandle(after); - op.host_changed = words[0]; - for (uint32_t word = 1; word < entry->changeWords; ++word) { - op.host_changed_more.push_back(words[word]); - } - } - } - } - } - } - const auto& frame = shadowView.layoutMetrics.frame; - op.frame = { - frame.origin.x, frame.origin.y, frame.size.width, frame.size.height}; - op.layout_changed = mutation.type == ShadowViewMutation::Create || - (mutation.type == ShadowViewMutation::Update && - mutation.oldChildShadowView.layoutMetrics.frame != - mutation.newChildShadowView.layoutMetrics.frame); - - if (mutation.type == ShadowViewMutation::Create || - mutation.type == ShadowViewMutation::Update) { - op.props_changed = mutation.type == ShadowViewMutation::Create || - mutation.oldChildShadowView.props != - mutation.newChildShadowView.props || - mutation.oldChildShadowView.state != mutation.newChildShadowView.state; - op.view = flattenView(shadowView); - if (op.component == "Paragraph") { - op.has_paragraph = true; - op.paragraph = flattenParagraph(shadowView); - } - if (op.component == "TextInput") { - if (auto state = - std::dynamic_pointer_cast>( - shadowView.state)) { - op.has_paragraph = true; - op.paragraph = - flattenInputText(state->getData().attributedStringBox.getValue()); - } - // An empty input has no fragment, so the placeholder and the caret would - // not know the font and color the typed text will have. - if (op.paragraph.fragments.empty()) { - if (auto inputProps = std::dynamic_pointer_cast( - shadowView.props)) { - op.has_paragraph = true; - op.paragraph.fragments.push_back(flattenTextFragment( - inputProps->getEffectiveTextAttributes(1.f), "")); - } - } - } - } - return op; -} - -namespace { -ParagraphFlat paragraphForMeasure( - const AttributedString& text, - const ParagraphAttributes& attributes) { - ParagraphFlat paragraph = flattenInputText(text); - if (paragraph.fragments.empty()) { - paragraph.fragments.push_back( - flattenTextFragment(text.getBaseTextAttributes(), "")); - paragraph.measure_empty_line = true; - } - - // Alignment lives on TextAttributes, not on ParagraphAttributes; the - // TextAlignment enum values already match the ParagraphFlat encoding. - const auto& fragments = text.getFragments(); - if (!fragments.empty() && fragments.front().textAttributes.alignment) { - paragraph.text_align = - static_cast(*fragments.front().textAttributes.alignment); - } - applyParagraphExtras(paragraph, fragments, attributes); - paragraph.max_lines = attributes.maximumNumberOfLines; - switch (attributes.ellipsizeMode) { - case EllipsizeMode::Clip: - paragraph.ellipsize = 3; - break; - case EllipsizeMode::Head: - paragraph.ellipsize = 1; - break; - case EllipsizeMode::Middle: - paragraph.ellipsize = 2; - break; - case EllipsizeMode::Tail: - paragraph.ellipsize = 0; - break; - } - - return paragraph; -} - -GpuiTextSize measureParagraphThroughRust( - const AttributedString& text, - const ParagraphAttributes& attributes, - float maxWidth, - float maxHeight) { - const auto result = rn_gpui_measure_text( - paragraphForMeasure(text, attributes), maxWidth, maxHeight); - return GpuiTextSize{.width = result.width, .height = result.height}; -} - -std::vector measureLinesThroughRust( - const AttributedString& text, - const ParagraphAttributes& attributes, - float maxWidth) { - std::vector lines; - for (const auto& line : - rn_gpui_measure_lines(paragraphForMeasure(text, attributes), maxWidth)) { - lines.push_back(GpuiTextLine{ - .text = std::string(line.text), - .x = line.x, - .y = line.y, - .width = line.width, - .height = line.height, - .ascender = line.ascender, - .descender = line.descender, - .capHeight = line.cap_height, - .xHeight = line.x_height}); - } - return lines; -} -} // namespace - -void installGpuiTextMeasureTable() { - setGpuiTextMeasureTable(GpuiTextMeasureTable{ - .measureLines = &measureLinesThroughRust, - .measureParagraph = &measureParagraphThroughRust}); -} -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/MountBatchBuilder.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/MountBatchBuilder.h deleted file mode 100644 index 336f31ac41..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/MountBatchBuilder.h +++ /dev/null @@ -1,54 +0,0 @@ -#pragma once - -#include "rn-gpui-sys/src/lib.rs.h" // cxx bridge - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace rngpui { -MountOp buildMountOp(const facebook::react::ShadowViewMutation& mutation); - -/// A component name as a mount op carries it: interned for the life of the -/// process, so an op names its component without allocating. -rust::Str componentNameStr(const char* name); - -// Shared flattening helpers. The text measurement override -// reuses these so React and GPUI describe text identically. -uint32_t argb(const facebook::react::SharedColor& color); -TextFragmentFlat flattenTextFragment( - const facebook::react::TextAttributes& attributes, - const std::string& text); - -ParagraphFlat flattenParagraphText( - const facebook::react::AttributedString& attributedString, - const facebook::react::ParagraphAttributes& attributes, - bool selectable); - -ParagraphFlat flattenInputText( - const facebook::react::AttributedString& attributedString); - -// The JSON the renderer reads for the gradient layers and the filter list. -std::string backgroundJson( - const std::vector& images, - const std::vector& sizes, - const std::vector& positions, - const std::vector& repeats); -std::string filterJson( - const std::vector& filter); - -void installGpuiTextMeasureTable(); -void installGpuiImageLoadTable(); - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/android-shim/README.md b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/android-shim/README.md deleted file mode 100644 index 167f1d210b..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/android-shim/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Android CMake helper shim - -This directory contains only `SoMerging-utils.cmake`, included by React -Native's `jsinspector-modern` CMake files through `REACT_ANDROID_DIR`. The -helper defines `target_merge_so()`, which is intentionally a no-op on GPUI's -non-Android desktop builds. No Android JNI, Java, or runtime implementation is -compiled or shipped from this directory. diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/android-shim/src/main/jni/first-party/jni-lib-merge/SoMerging-utils.cmake b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/android-shim/src/main/jni/first-party/jni-lib-merge/SoMerging-utils.cmake deleted file mode 100644 index 44c93592df..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/android-shim/src/main/jni/first-party/jni-lib-merge/SoMerging-utils.cmake +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -# This function should be invoked if the requested library is going to be merged -# with libreactnative.so as such: -# -# target_merge_so(react_newarchdefaults) -# -# This function will take care of forcefully including the jni_lib_merge.h header that takes -# care of redefining the JNI_OnLoad function to JNI_OnLoad_Weak. -function(target_merge_so target_name) - if(NOT ANDROID) - return() - endif() - - target_compile_options(${target_name} - PRIVATE - -DORIGINAL_SONAME=\"lib${target_name}.so\" - -include ${REACT_ANDROID_DIR}/src/main/jni/first-party/jni-lib-merge/jni_lib_merge.h - ) - target_link_options(${target_name} PRIVATE -Wl,--defsym=JNI_OnLoad=JNI_OnLoad_Weak) -endfunction() diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/activity_indicator/GpuiActivityIndicatorProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/activity_indicator/GpuiActivityIndicatorProps.cpp deleted file mode 100644 index ba99a13212..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/activity_indicator/GpuiActivityIndicatorProps.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// Props for `ActivityIndicatorView`, read by the Rust renderer as JSON. - -#include -#include - -#include - -#include "GpuiModules.h" - -namespace rngpui { -namespace { - -std::string activityIndicatorPropsJson( - const std::string& /*componentName*/, - const facebook::react::ShadowView& view) { - if (!view.props) { - return std::string("{}"); - } - const auto& props = *std::static_pointer_cast< - const facebook::react::ActivityIndicatorViewProps>(view.props); - folly::dynamic object = folly::dynamic::object; - object["animating"] = props.animating; - object["hidesWhenStopped"] = props.hidesWhenStopped; - object["color"] = argb(props.color); - object["size"] = facebook::react::toString(props.size); - return folly::toJson(object); -} - -} // namespace - -void rn_gpui_install_activity_indicator_module() { - registerComponentProps("ActivityIndicatorView", activityIndicatorPropsJson); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/context_menu_view/GpuiContextMenuViewProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/context_menu_view/GpuiContextMenuViewProps.cpp deleted file mode 100644 index 559eec86d0..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/context_menu_view/GpuiContextMenuViewProps.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// Props for the native context-menu view, read by the Rust renderer as JSON. -// -// Registered the way core's other built-ins are (see -// `window_control/GpuiWindowControlProps.cpp`): an installer listed in -// `cpp/CMakeLists.txt`, called once by the generated -// `rn_gpui_install_modules()`. -// -// `items` goes out as-is. It is the same `MenuItemSpec[]` shape -// `contextMenuShow` takes, so the Rust side parses both with one function and a -// menu cannot mean one thing from JS and another from this component. - -#include -#include - -#include "GpuiModules.h" -#include "react/renderer/components/desktopcontextmenuview/DesktopContextMenuView.h" - -namespace rngpui { -namespace { - -std::string contextMenuViewPropsJson( - const std::string& /*componentName*/, - const facebook::react::ShadowView& view) { - if (!view.props) { - return std::string("{}"); - } - const auto& props = *std::static_pointer_cast< - const facebook::react::DesktopContextMenuViewProps>(view.props); - folly::dynamic object = folly::dynamic::object; - object["items"] = props.items; - object["presentation"] = props.presentation; - object["disabled"] = props.disabled; - return folly::toJson(object); -} - -} // namespace - -void rn_gpui_install_context_menu_view_module() { - registerComponentProps("DesktopContextMenuView", contextMenuViewPropsJson); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/desktop_scroll_bar/GpuiDesktopScrollBarProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/desktop_scroll_bar/GpuiDesktopScrollBarProps.cpp deleted file mode 100644 index dc2ac35995..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/desktop_scroll_bar/GpuiDesktopScrollBarProps.cpp +++ /dev/null @@ -1,54 +0,0 @@ -// Props for the scrollbar component, read by the Rust renderer as JSON. -// -// Only what the app set is sent, so the scroll view keeps its defaults for the -// rest. Registered the way `shortcut_scope/GpuiShortcutScopeProps.cpp` is. - -#include -#include - -#include "GpuiModules.h" -#include "react/renderer/components/desktopscrollbar/DesktopScrollBar.h" - -namespace rngpui { -namespace { - -std::string desktopScrollBarPropsJson( - const std::string& /*componentName*/, - const facebook::react::ShadowView& view) { - if (!view.props) { - return std::string("{}"); - } - const auto& props = - *std::static_pointer_cast( - view.props); - folly::dynamic object = folly::dynamic::object; - const auto number = [&](const char* key, double value) { - if (value >= 0) { - object[key] = value; - } - }; - number("thickness", props.thickness); - number("minLength", props.minLength); - number("margin", props.margin); - number("radius", props.radius); - number("autoHideDelay", props.autoHideDelay); - if (argb(props.color) != 0) { - object["color"] = argb(props.color); - } - if (argb(props.trackColor) != 0) { - object["trackColor"] = argb(props.trackColor); - } - if (!props.visibility.empty()) { - object["visibility"] = props.visibility; - } - object["interactive"] = props.interactive; - return folly::toJson(object); -} - -} // namespace - -void rn_gpui_install_desktop_scroll_bar_module() { - registerComponentProps("DesktopScrollBar", desktopScrollBarPropsJson); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/image/GpuiImageProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/image/GpuiImageProps.cpp deleted file mode 100644 index 0191b58e42..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/image/GpuiImageProps.cpp +++ /dev/null @@ -1,58 +0,0 @@ - -#include - -#include -#include - -#include "GpuiModules.h" - -namespace rngpui { -namespace { - -std::string imagePropsJson( - const std::string& /*componentName*/, - const facebook::react::ShadowView& view) { - if (!view.props) { - return std::string("{}"); - } - const auto& props = - *std::static_pointer_cast(view.props); - folly::dynamic object = folly::dynamic::object; - if (!props.sources.empty()) { - object["uri"] = props.sources[0].uri; - } - switch (props.resizeMode) { - case facebook::react::ImageResizeMode::Contain: - object["resizeMode"] = "contain"; - break; - case facebook::react::ImageResizeMode::Cover: - object["resizeMode"] = "cover"; - break; - case facebook::react::ImageResizeMode::Center: - object["resizeMode"] = "center"; - break; - case facebook::react::ImageResizeMode::Repeat: - object["resizeMode"] = "repeat"; - break; - case facebook::react::ImageResizeMode::None: - object["resizeMode"] = "none"; - break; - default: - object["resizeMode"] = "stretch"; - break; - } - object["tintColor"] = static_cast(argb(props.tintColor)); - object["blurRadius"] = props.blurRadius; - if (!props.defaultSource.uri.empty()) { - object["defaultSource"] = props.defaultSource.uri; - } - return folly::toJson(object); -} - -} // namespace - -void rn_gpui_install_image_module() { - registerComponentProps("Image", imagePropsJson); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/modal/GpuiModalProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/modal/GpuiModalProps.cpp deleted file mode 100644 index fd3e270f32..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/modal/GpuiModalProps.cpp +++ /dev/null @@ -1,29 +0,0 @@ - -#include - -#include -#include - -#include "GpuiModules.h" - -namespace rngpui { -namespace { - -std::string modalPropsJson( - const std::string& /*componentName*/, - const facebook::react::ShadowView& view) { - const auto props = - std::dynamic_pointer_cast( - view.props); - folly::dynamic object = folly::dynamic::object; - object["visible"] = props ? props->visible : true; - return folly::toJson(object); -} - -} // namespace - -void rn_gpui_install_modal_module() { - registerComponentProps("ModalHostView", modalPropsJson); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/native_root/GpuiNativeRootProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/native_root/GpuiNativeRootProps.cpp deleted file mode 100644 index 089b2c9370..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/native_root/GpuiNativeRootProps.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// Props for the native root, read by the Rust renderer as JSON. Registered the -// way `shortcut_scope/GpuiShortcutScopeProps.cpp` is. - -#include -#include - -#include "GpuiModules.h" -#include "react/renderer/components/nativeroot/NativeRoot.h" - -namespace rngpui { -namespace { - -std::string nativeRootPropsJson( - const std::string& /*componentName*/, - const facebook::react::ShadowView& view) { - if (!view.props) { - return std::string("{}"); - } - const auto& props = - *std::static_pointer_cast( - view.props); - folly::dynamic object = folly::dynamic::object; - object["rootId"] = props.rootId; - object["hinted"] = props.hintHeight >= 0; - return folly::toJson(object); -} - -} // namespace - -void rn_gpui_install_native_root_module() { - registerComponentProps("DesktopNativeRoot", nativeRootPropsJson); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/native_slot/GpuiNativeSlotProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/native_slot/GpuiNativeSlotProps.cpp deleted file mode 100644 index 9dd7e73c66..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/native_slot/GpuiNativeSlotProps.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// Props for a native slot, read by the Rust renderer as JSON. Registered the -// way `shortcut_scope/GpuiShortcutScopeProps.cpp` is. - -#include -#include - -#include "GpuiModules.h" -#include "react/renderer/components/nativeslot/NativeSlot.h" - -namespace rngpui { -namespace { - -std::string nativeSlotPropsJson( - const std::string& /*componentName*/, - const facebook::react::ShadowView& view) { - if (!view.props) { - return std::string("{}"); - } - const auto& props = - *std::static_pointer_cast( - view.props); - folly::dynamic object = folly::dynamic::object; - object["rootId"] = props.rootId; - object["slotId"] = props.slotId; - return folly::toJson(object); -} - -} // namespace - -void rn_gpui_install_native_slot_module() { - registerComponentProps("DesktopNativeSlot", nativeSlotPropsJson); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/scrollview/GpuiScrollViewProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/scrollview/GpuiScrollViewProps.cpp deleted file mode 100644 index 0306ebbcf4..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/scrollview/GpuiScrollViewProps.cpp +++ /dev/null @@ -1,82 +0,0 @@ - -#include -#include -#include - -#include -#include - -#include "GpuiModules.h" - -namespace rngpui { -namespace { - -std::string scrollViewPropsJson( - const std::string& /*componentName*/, - const facebook::react::ShadowView& view) { - folly::dynamic object = folly::dynamic::object; - bool horizontal = false; - bool enabled = true; - bool indicator = true; - if (auto props = - std::dynamic_pointer_cast( - view.props)) { - horizontal = props->horizontal; - enabled = props->scrollEnabled; - indicator = props->horizontal ? props->showsHorizontalScrollIndicator - : props->showsVerticalScrollIndicator; - if (props->maintainVisibleContentPosition) { - object["maintainMinIndex"] = - props->maintainVisibleContentPosition->minIndexForVisible; - if (props->maintainVisibleContentPosition->autoscrollToTopThreshold) { - object["maintainAutoscrollThreshold"] = - *props->maintainVisibleContentPosition->autoscrollToTopThreshold; - } - } - object["decelerationRate"] = props->decelerationRate; - object["scrollEventThrottle"] = props->scrollEventThrottle; - object["pagingEnabled"] = props->pagingEnabled; - object["snapToInterval"] = props->snapToInterval; - object["snapToStart"] = props->snapToStart; - object["snapToEnd"] = props->snapToEnd; - object["disableIntervalMomentum"] = props->disableIntervalMomentum; - folly::dynamic offsets = folly::dynamic::array; - for (const auto offset : props->snapToOffsets) { - offsets.push_back(offset); - } - object["snapToOffsets"] = offsets; - switch (props->snapToAlignment) { - case facebook::react::ScrollViewSnapToAlignment::Center: - object["snapToAlignment"] = "center"; - break; - case facebook::react::ScrollViewSnapToAlignment::End: - object["snapToAlignment"] = "end"; - break; - default: - object["snapToAlignment"] = "start"; - break; - } - } - object["horizontal"] = horizontal; - object["enabled"] = enabled; - object["indicator"] = indicator; - if (auto state = - std::dynamic_pointer_cast>(view.state)) { - const auto& data = state->getData(); - const auto content = data.getContentSize(); - object["contentWidth"] = content.width; - object["contentHeight"] = content.height; - object["offsetX"] = data.contentOffset.x; - object["offsetY"] = data.contentOffset.y; - } - return folly::toJson(object); -} - -} // namespace - -void rn_gpui_install_scroll_view_module() { - registerComponentProps("ScrollView", scrollViewPropsJson); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/shortcut_scope/GpuiShortcutScopeProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/shortcut_scope/GpuiShortcutScopeProps.cpp deleted file mode 100644 index 0e665a3fea..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/shortcut_scope/GpuiShortcutScopeProps.cpp +++ /dev/null @@ -1,41 +0,0 @@ -// Props for the shortcut scope, read by the Rust renderer as JSON. -// -// Registered the way core's other built-ins are (see -// `window_control/GpuiWindowControlProps.cpp`): an installer listed in -// `cpp/CMakeLists.txt`, called once by the generated -// `rn_gpui_install_modules()`. -// -// The props are one string. Everything the component means is native — the -// `name` becomes a keymap context and GPUI resolves the precedence — so there -// is nothing else to send. - -#include -#include - -#include "GpuiModules.h" -#include "react/renderer/components/shortcutscope/ShortcutScope.h" - -namespace rngpui { -namespace { - -std::string shortcutScopePropsJson( - const std::string& /*componentName*/, - const facebook::react::ShadowView& view) { - if (!view.props) { - return std::string("{}"); - } - const auto& props = - *std::static_pointer_cast( - view.props); - folly::dynamic object = folly::dynamic::object; - object["name"] = props.name; - return folly::toJson(object); -} - -} // namespace - -void rn_gpui_install_shortcut_scope_module() { - registerComponentProps("DesktopShortcutScope", shortcutScopePropsJson); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/switch/GpuiSwitchProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/switch/GpuiSwitchProps.cpp deleted file mode 100644 index c6671f7002..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/switch/GpuiSwitchProps.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// Props for `Switch`, read by the Rust renderer as JSON. - -#include -#include - -#include "GpuiModules.h" -#include "react/renderer/components/desktopswitch/DesktopSwitch.h" - -namespace rngpui { -namespace { - -std::string switchPropsJson( - const std::string& /*componentName*/, - const facebook::react::ShadowView& view) { - if (!view.props) { - return std::string("{}"); - } - const auto& props = - *std::static_pointer_cast(view.props); - folly::dynamic object = folly::dynamic::object; - object["value"] = props.value; - object["disabled"] = props.disabled; - object["tintColor"] = argb(props.tintColor); - object["onTintColor"] = argb(props.onTintColor); - object["thumbTintColor"] = argb(props.thumbTintColor); - object["thumbColor"] = argb(props.thumbColor); - object["trackColorForFalse"] = argb(props.trackColorForFalse); - object["trackColorForTrue"] = argb(props.trackColorForTrue); - return folly::toJson(object); -} - -} // namespace - -void rn_gpui_install_switch_module() { - registerComponentProps("Switch", switchPropsJson); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/textinput/GpuiTextInputProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/textinput/GpuiTextInputProps.cpp deleted file mode 100644 index f1b4fb5ce6..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/textinput/GpuiTextInputProps.cpp +++ /dev/null @@ -1,91 +0,0 @@ - -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "GpuiModules.h" - -namespace rngpui { -namespace { - -uint32_t argb(const facebook::react::SharedColor& color) { - if (!color) { - return 0; - } - auto components = facebook::react::colorComponentsFromColor(color); - auto to8 = [](float value) { - return static_cast(std::lround(value * 255.f)) & 0xFF; - }; - return (to8(components.alpha) << 24) | (to8(components.red) << 16) | - (to8(components.green) << 8) | to8(components.blue); -} - -std::string textInputPropsJson( - const std::string& /*componentName*/, - const facebook::react::ShadowView& view) { - folly::dynamic object = folly::dynamic::object; - if (auto props = - std::dynamic_pointer_cast( - view.props)) { - object["text"] = props->text; - object["placeholder"] = props->placeholder; - object["selectionColor"] = static_cast(argb(props->selectionColor)); - object["multiline"] = props->multiline; - object["placeholderTextColor"] = - static_cast(argb(props->placeholderTextColor)); - switch (props->submitBehavior) { - case facebook::react::SubmitBehavior::Submit: - object["submitBehavior"] = "submit"; - break; - case facebook::react::SubmitBehavior::BlurAndSubmit: - object["submitBehavior"] = "blurAndSubmit"; - break; - case facebook::react::SubmitBehavior::Newline: - object["submitBehavior"] = "newline"; - break; - default: - object["submitBehavior"] = "default"; - break; - } - if (props->maxLength != std::numeric_limits::max()) { - object["maxLength"] = props->maxLength; - } - object["contextMenuHidden"] = props->traits.contextMenuHidden; - object["caretHidden"] = props->traits.caretHidden; - object["selectTextOnFocus"] = props->traits.selectTextOnFocus; - object["editable"] = props->editable && !props->readOnly; - object["secure"] = props->traits.secureTextEntry; - object["eventCount"] = props->mostRecentEventCount; - bool selection_set = props->selection.has_value(); - object["selectionSet"] = selection_set; - if (selection_set) { - object["selectionStart"] = props->selection->start; - object["selectionEnd"] = props->selection->end; - } else { - int32_t cursor = 0; - for (const auto byte : props->text) { - const auto value = static_cast(byte); - if ((value & 0xC0) != 0x80) { - cursor += value >= 0xF0 ? 2 : 1; - } - } - object["selectionStart"] = cursor; - object["selectionEnd"] = cursor; - } - } - return folly::toJson(object); -} - -} // namespace - -void rn_gpui_install_text_input_module() { - registerComponentProps("TextInput", textInputPropsJson); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/window_control/GpuiWindowControlProps.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/window_control/GpuiWindowControlProps.cpp deleted file mode 100644 index 883cfb02f0..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/builtins/window_control/GpuiWindowControlProps.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// Props for the caption button, read by the Rust renderer as JSON. -// -// Registered the way core's other built-ins are (see -// `image/GpuiImageProps.cpp`): an installer listed in `cpp/CMakeLists.txt`, -// called once by the generated `rn_gpui_install_modules()`. - -#include -#include - -#include "GpuiModules.h" -#include "react/renderer/components/windowcontrol/WindowControl.h" - -namespace rngpui { -namespace { - -std::string windowControlPropsJson( - const std::string& /*componentName*/, - const facebook::react::ShadowView& view) { - if (!view.props) { - return std::string("{}"); - } - const auto& props = - *std::static_pointer_cast( - view.props); - folly::dynamic object = folly::dynamic::object; - switch (props.action) { - case facebook::react::WindowControlAction::Minimize: - object["action"] = "minimize"; - break; - case facebook::react::WindowControlAction::Maximize: - object["action"] = "maximize"; - break; - default: - object["action"] = "close"; - break; - } - object["disabled"] = props.disabled; - return folly::toJson(object); -} - -} // namespace - -void rn_gpui_install_window_control_module() { - registerComponentProps("DesktopWindowControl", windowControlPropsJson); -} - -} // namespace rngpui diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/DownloadNativeDeps.cmake b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/DownloadNativeDeps.cmake deleted file mode 100644 index 87219cf4e4..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/DownloadNativeDeps.cmake +++ /dev/null @@ -1,478 +0,0 @@ -# Everything downloaded, extracted or built from the pinned native-dep archives -# lives in one per-user cache that every build of every checkout shares, so a -# new target dir or worktree does not download Boost or build OpenSSL again. -# Layout (nothing here depends on the build dir): -# downloads// verified archives -# sources/-/ extracted archives, never modified -# openssl//install static OpenSSL, one per toolchain key -# locks/ lock files serialising concurrent builds -# build.rs passes the folder as -DRN_GPUI_NATIVE_DEPS_CACHE (the user cache -# folder, or RN_GPUI_NATIVE_DEPS_CACHE). A CMake run by hand uses the environment -# variable, then falls back to a folder in the build dir, as builds did before. -if(NOT RN_GPUI_NATIVE_DEPS_CACHE) - if(NOT "$ENV{RN_GPUI_NATIVE_DEPS_CACHE}" STREQUAL "") - set(RN_GPUI_NATIVE_DEPS_CACHE "$ENV{RN_GPUI_NATIVE_DEPS_CACHE}") - else() - set(RN_GPUI_NATIVE_DEPS_CACHE "${CMAKE_BINARY_DIR}/native-deps/cache") - endif() -endif() -file(TO_CMAKE_PATH "${RN_GPUI_NATIVE_DEPS_CACHE}" RN_GPUI_NATIVE_DEPS_CACHE) -set(RN_GPUI_NATIVE_DEPS_DOWNLOADS "${RN_GPUI_NATIVE_DEPS_CACHE}/downloads") -set(RN_GPUI_NATIVE_DEPS_SOURCES "${RN_GPUI_NATIVE_DEPS_CACHE}/sources") -set(RN_GPUI_NATIVE_DEPS_LOCKS "${RN_GPUI_NATIVE_DEPS_CACHE}/locks") -# What depends on this build's flags and React Native version stays in the build -# dir: the prepared copies of the sources, and the third-party CMake builds. -set(RN_GPUI_NATIVE_DEPS_PREPARED "${CMAKE_BINARY_DIR}/native-deps/third-party-ndk") -message(STATUS "Native dependency cache: ${RN_GPUI_NATIVE_DEPS_CACHE}") -file(MAKE_DIRECTORY "${RN_GPUI_NATIVE_DEPS_DOWNLOADS}" "${RN_GPUI_NATIVE_DEPS_SOURCES}" - "${RN_GPUI_NATIVE_DEPS_LOCKS}") - -# Holds a lock on the cache until the calling function returns. Locks are -# released by the operating system when a build dies, and the wait is bounded -# because another build may be downloading Boost or compiling OpenSSL. -macro(rn_gpui_native_deps_lock lock_name) - file(LOCK "${RN_GPUI_NATIVE_DEPS_LOCKS}/${lock_name}.lock" GUARD FUNCTION - TIMEOUT 3600 RESULT_VARIABLE _rn_gpui_lock_result) - if(NOT _rn_gpui_lock_result EQUAL 0) - message(FATAL_ERROR - "Timed out waiting for another build to finish with ${lock_name} in " - "${RN_GPUI_NATIVE_DEPS_CACHE} (${_rn_gpui_lock_result}). If no build is " - "running, delete ${RN_GPUI_NATIVE_DEPS_LOCKS}/${lock_name}.lock.") - endif() -endmacro() - -# Downloads one archive into the cache and checks it against its pinned sha256. -# A bad copy in the cache (a truncated or tampered file) is downloaded again. -function(rn_gpui_fetch_archive archive_name url sha256 out_archive) - string(SUBSTRING "${sha256}" 0 12 _id) - set(_dir "${RN_GPUI_NATIVE_DEPS_DOWNLOADS}/${_id}") - set(_archive "${_dir}/${archive_name}") - file(MAKE_DIRECTORY "${_dir}") - rn_gpui_native_deps_lock("download-${_id}") - if(EXISTS "${_archive}") - file(SHA256 "${_archive}" _actual) - if(NOT _actual STREQUAL sha256) - message(WARNING "${_archive} has sha256 ${_actual}, expected ${sha256}; downloading it again") - file(REMOVE "${_archive}") - endif() - endif() - if(NOT EXISTS "${_archive}") - message(STATUS "Downloading ${archive_name} into ${_dir}") - set(_download_succeeded FALSE) - set(_download_message "") - foreach(_attempt RANGE 1 5) - # The partial file is private to the lock holder and only renamed once - # complete and verified, so no build ever sees a half-written archive. - set(_partial_archive "${_archive}.part") - file(REMOVE "${_partial_archive}") - # No overall TIMEOUT: Boost is 145 MB, and a cap on the whole transfer - # fails every attempt on a slow link however steadily it downloads. - file(DOWNLOAD "${url}" "${_partial_archive}" SHOW_PROGRESS TLS_VERIFY ON - INACTIVITY_TIMEOUT 45 STATUS _download_status) - list(GET _download_status 0 _download_code) - list(GET _download_status 1 _download_message) - if(_download_code EQUAL 0) - file(SHA256 "${_partial_archive}" _actual) - if(_actual STREQUAL sha256) - file(RENAME "${_partial_archive}" "${_archive}") - set(_download_succeeded TRUE) - break() - endif() - set(_download_message "sha256 is ${_actual}, expected ${sha256}") - endif() - file(REMOVE "${_partial_archive}") - if(_attempt LESS 5) - math(EXPR _retry_delay "${_attempt} * 2") - message(STATUS "Download attempt ${_attempt}/5 failed (${_download_message}); retrying in ${_retry_delay}s") - execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep "${_retry_delay}") - endif() - endforeach() - if(NOT _download_succeeded) - message(FATAL_ERROR "Failed to download ${url} after 5 attempts: ${_download_message}") - endif() - endif() - set(${out_archive} "${_archive}" PARENT_SCOPE) -endfunction() - -# Makes the archive's contents available at ${out_source}, which is the -# directory that holds the archive's top-level folder. -function(rn_gpui_download_extract name archive_name url sha256 out_source) - string(SUBSTRING "${sha256}" 0 12 _id) - set(_source "${RN_GPUI_NATIVE_DEPS_SOURCES}/${name}-${_id}") - set_property(GLOBAL APPEND PROPERTY RN_GPUI_NATIVE_DEPS_ARCHIVES "${archive_name} ${sha256}") - # A folder only appears under its final name once it is completely extracted - # from a verified archive, so its existence is the whole check. - if(NOT EXISTS "${_source}") - rn_gpui_native_deps_lock("source-${name}-${_id}") - if(NOT EXISTS "${_source}") - rn_gpui_fetch_archive("${archive_name}" "${url}" "${sha256}" _archive) - set(_extract_dir "${_source}.tmp") - file(REMOVE_RECURSE "${_extract_dir}") - file(MAKE_DIRECTORY "${_extract_dir}") - message(STATUS "Extracting ${archive_name} into ${_source}") - file(ARCHIVE_EXTRACT INPUT "${_archive}" DESTINATION "${_extract_dir}") - file(RENAME "${_extract_dir}" "${_source}") - endif() - endif() - set(${out_source} "${_source}" PARENT_SCOPE) -endfunction() - -# Keep these versions and source URLs aligned with node_modules/react-native/ -# gradle/libs.versions.toml and ReactAndroid/build.gradle.kts. -# -# Each archive is pinned by sha256: change the checksum with the version. -rn_gpui_download_extract(boost "boost_1_83_0.tar.gz" - "https://archives.boost.io/release/1.83.0/source/boost_1_83_0.tar.gz" - "c0685b68dd44cc46574cce86c4e17c0f611b15e195be9848dfd0769a0a207628" RN_GPUI_BOOST_ARCHIVE_DIR) -rn_gpui_download_extract(double-conversion "double-conversion-1.1.6.tar.gz" - "https://github.com/google/double-conversion/archive/v1.1.6.tar.gz" - "6b850acd8e88515764472c52973277744a945f9a769a93968efc42efef64d67a" RN_GPUI_DOUBLE_CONVERSION_ARCHIVE_DIR) -rn_gpui_download_extract(fast_float "fast_float-8.0.0.tar.gz" - "https://github.com/fastfloat/fast_float/archive/v8.0.0.tar.gz" - "f312f2dc34c61e665f4b132c0307d6f70ad9420185fa831911bc24408acf625d" RN_GPUI_FAST_FLOAT_ARCHIVE_DIR) -rn_gpui_download_extract(fmt "fmt-12.1.0.tar.gz" - "https://github.com/fmtlib/fmt/archive/12.1.0.tar.gz" - "ea7de4299689e12b6dddd392f9896f08fb0777ac7168897a244a6d6085043fea" RN_GPUI_FMT_ARCHIVE_DIR) -rn_gpui_download_extract(folly "folly-2024.11.18.00.tar.gz" - "https://github.com/facebook/folly/archive/v2024.11.18.00.tar.gz" - "b2c6879ba8ba625218d1ab9eefcc1611a9003d05bc2cb1a38f3bae21892e5167" RN_GPUI_FOLLY_ARCHIVE_DIR) -rn_gpui_download_extract(glog "glog-0.3.5.tar.gz" - "https://github.com/google/glog/archive/v0.3.5.tar.gz" - "7580e408a2c0b5a89ca214739978ce6ff480b5e7d8d7698a2aa92fadc484d1e0" RN_GPUI_GLOG_ARCHIVE_DIR) -rn_gpui_download_extract(nlohmann_json "json-3.11.2.tar.gz" - "https://github.com/nlohmann/json/archive/v3.11.2.tar.gz" - "d69f9deb6a75e2580465c6c4c5111b89c4dc2fa94e3a85fcd2ffcd9a143d9273" RN_GPUI_NLOHMANN_JSON_ARCHIVE_DIR) -rn_gpui_download_extract(curl "curl-8.11.1.tar.gz" - "https://curl.se/download/curl-8.11.1.tar.gz" - "a889ac9dbba3644271bd9d1302b5c22a088893719b72be3487bc3d401e5c4e80" RN_GPUI_CURL_ARCHIVE_DIR) -# OpenSSL is only needed to build it, so its archive is fetched by -# rn_gpui_build_openssl below and only when no built copy is cached. -set(RN_GPUI_OPENSSL_ARCHIVE_NAME "openssl-3.3.2.tar.gz") -set(RN_GPUI_OPENSSL_ARCHIVE_URL "https://www.openssl.org/source/openssl-3.3.2.tar.gz") -set(RN_GPUI_OPENSSL_ARCHIVE_SHA256 "2e8a40b01979afe8be0bbfb3de5dc1c6709fedb46d6c89c10da114ab5fc3d281") - -# OpenSSL's upstream project uses Configure + Make rather than CMake. Build a -# static copy into the shared cache before CMake discovers it; this keeps CURL -# and ReactCxxPlatform off host OpenSSL installations. -if(WIN32) - # The VS developer environment must be active so OpenSSL uses the same - # MSVC toolchain/runtime as React Native and the GPUI host. - if(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64") - set(_openssl_target VC-WIN64A) - elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "ARM64|arm64|aarch64") - set(_openssl_target VC-WIN64-ARM) - else() - message(FATAL_ERROR "No OpenSSL source-build target for Windows/${CMAKE_SYSTEM_PROCESSOR}") - endif() -elseif(APPLE AND CMAKE_SYSTEM_PROCESSOR MATCHES "arm64|aarch64") - set(_openssl_target darwin64-arm64-cc) -elseif(APPLE) - set(_openssl_target darwin64-x86_64-cc) -elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64") - set(_openssl_target linux-x86_64) -elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64|arm64") - set(_openssl_target linux-aarch64) -else() - message(FATAL_ERROR "No OpenSSL source-build target for ${CMAKE_SYSTEM_NAME}/${CMAKE_SYSTEM_PROCESSOR}") -endif() -# no-apps: GPUI links only libssl and libcrypto; the openssl CLI in apps/ -# is not needed. The Xcode toolchain cc has no default sysroot, so -# is missing from every OpenSSL compile unless SDKROOT names -# the SDK; OpenSSL's Makefile does not pass -isysroot itself. -set(_openssl_configure_options no-shared no-tests no-apps) -set(_openssl_env ${CMAKE_COMMAND} -E env) -set(_openssl_sdk "") -if(APPLE) - execute_process(COMMAND xcrun --sdk macosx --show-sdk-path - OUTPUT_VARIABLE _openssl_sdk OUTPUT_STRIP_TRAILING_WHITESPACE - RESULT_VARIABLE _openssl_sdk_status) - if(NOT _openssl_sdk_status EQUAL 0 OR _openssl_sdk STREQUAL "") - message(FATAL_ERROR "xcrun could not locate the macOS SDK for OpenSSL") - endif() - set(_openssl_env ${CMAKE_COMMAND} -E env "SDKROOT=${_openssl_sdk}") -endif() - -# The installed copy is keyed by everything that changes what OpenSSL compiles -# to: the target, the build type, the compiler and the flags Configure reads -# from the environment. Builds that differ in any of them each get their own -# copy, so they never overwrite or reuse each other's. -set(_openssl_key_inputs - "openssl=3.3.2" "sha256=${RN_GPUI_OPENSSL_ARCHIVE_SHA256}" - "target=${_openssl_target}" "options=${_openssl_configure_options}" - "system=${CMAKE_SYSTEM_NAME}" "processor=${CMAKE_SYSTEM_PROCESSOR}" - "build_type=${CMAKE_BUILD_TYPE}" - "compiler=${CMAKE_C_COMPILER_ID} ${CMAKE_C_COMPILER_VERSION}" - "osx_deployment_target=${CMAKE_OSX_DEPLOYMENT_TARGET}" - "osx_architectures=${CMAKE_OSX_ARCHITECTURES}" "sdk=${_openssl_sdk}") -# Configure reads these; the cc crate never sets them, but a user may. -foreach(_openssl_env_var IN ITEMS CC CFLAGS CPPFLAGS LDFLAGS MACOSX_DEPLOYMENT_TARGET SDKROOT) - list(APPEND _openssl_key_inputs "env_${_openssl_env_var}=$ENV{${_openssl_env_var}}") -endforeach() -string(JOIN "\n" _openssl_key_text ${_openssl_key_inputs}) -string(SHA256 _openssl_key_hash "${_openssl_key_text}") -string(SUBSTRING "${_openssl_key_hash}" 0 16 _openssl_key_hash) -string(TOLOWER "${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}-${CMAKE_BUILD_TYPE}" _openssl_key_name) -set(RN_GPUI_OPENSSL_DIR - "${RN_GPUI_NATIVE_DEPS_CACHE}/openssl/3.3.2-${_openssl_key_name}-${_openssl_key_hash}") -set(RN_GPUI_OPENSSL_INSTALL "${RN_GPUI_OPENSSL_DIR}/install") -# Written last, once the install is whole; a folder without it is a build that -# was interrupted and is started again. -set(_openssl_complete_marker "${RN_GPUI_OPENSSL_DIR}/.complete") - -function(rn_gpui_build_openssl) - rn_gpui_native_deps_lock("openssl-${_openssl_key_hash}") - # Another build may have finished the install while this one waited. - if(EXISTS "${_openssl_complete_marker}") - return() - endif() - # The install prefix is compiled into the libraries, so the install cannot be - # built elsewhere and renamed into place; the marker plays that part. - file(REMOVE_RECURSE "${RN_GPUI_OPENSSL_DIR}") - set(_openssl_work "${RN_GPUI_OPENSSL_DIR}/work") - file(MAKE_DIRECTORY "${_openssl_work}") - rn_gpui_fetch_archive("${RN_GPUI_OPENSSL_ARCHIVE_NAME}" "${RN_GPUI_OPENSSL_ARCHIVE_URL}" - "${RN_GPUI_OPENSSL_ARCHIVE_SHA256}" _openssl_archive) - # Configure and make build inside the source tree, so every key builds in a - # copy of its own and the cached sources stay untouched. - file(ARCHIVE_EXTRACT INPUT "${_openssl_archive}" DESTINATION "${_openssl_work}") - file(GLOB _openssl_roots LIST_DIRECTORIES TRUE "${_openssl_work}/openssl-3.3.2*") - list(GET _openssl_roots 0 RN_GPUI_OPENSSL_SOURCE_DIR) - message(STATUS "Building OpenSSL ${_openssl_target} into ${RN_GPUI_OPENSSL_INSTALL}") - # OpenSSL's Configure needs a native Windows Perl. Git for Windows ships an - # MSYS Perl without Locale::Maketext::Simple and puts it ahead on PATH in Git - # Bash, so look in Strawberry Perl's default location first and check the - # module before Configure fails with a far less readable error. - find_program(RN_GPUI_PERL_EXECUTABLE perl - HINTS "C:/Strawberry/perl/bin" REQUIRED) - if(WIN32) - execute_process( - COMMAND "${RN_GPUI_PERL_EXECUTABLE}" -MLocale::Maketext::Simple -e 1 - RESULT_VARIABLE _rn_gpui_perl_check - OUTPUT_QUIET ERROR_QUIET) - if(NOT _rn_gpui_perl_check EQUAL 0) - message(FATAL_ERROR - "${RN_GPUI_PERL_EXECUTABLE} cannot build OpenSSL (it lacks " - "Locale::Maketext::Simple; Git for Windows' Perl does). Install Strawberry " - "Perl, put it ahead of Git on PATH, or pass -DRN_GPUI_PERL_EXECUTABLE=.") - endif() - find_program(RN_GPUI_MAKE_EXECUTABLE nmake REQUIRED) - else() - find_program(RN_GPUI_MAKE_EXECUTABLE make REQUIRED) - endif() - execute_process( - COMMAND ${_openssl_env} "${RN_GPUI_PERL_EXECUTABLE}" ./Configure "${_openssl_target}" ${_openssl_configure_options} - "--prefix=${RN_GPUI_OPENSSL_INSTALL}" --libdir=lib - WORKING_DIRECTORY "${RN_GPUI_OPENSSL_SOURCE_DIR}" - RESULT_VARIABLE _openssl_configure_status) - if(NOT _openssl_configure_status EQUAL 0) - message(FATAL_ERROR "OpenSSL Configure failed for ${_openssl_target}") - endif() - if(WIN32) - execute_process( - COMMAND "${RN_GPUI_MAKE_EXECUTABLE}" build_libs - WORKING_DIRECTORY "${RN_GPUI_OPENSSL_SOURCE_DIR}" - RESULT_VARIABLE _openssl_build_status) - else() - execute_process( - COMMAND ${_openssl_env} "${RN_GPUI_MAKE_EXECUTABLE}" -j2 build_libs - WORKING_DIRECTORY "${RN_GPUI_OPENSSL_SOURCE_DIR}" - RESULT_VARIABLE _openssl_build_status) - endif() - if(NOT _openssl_build_status EQUAL 0) - message(FATAL_ERROR "Building cached OpenSSL source failed") - endif() - execute_process( - COMMAND ${_openssl_env} "${RN_GPUI_MAKE_EXECUTABLE}" install_dev - WORKING_DIRECTORY "${RN_GPUI_OPENSSL_SOURCE_DIR}" - RESULT_VARIABLE _openssl_install_status) - if(NOT _openssl_install_status EQUAL 0) - message(FATAL_ERROR "Installing cached OpenSSL into the shared cache failed") - endif() - file(REMOVE_RECURSE "${_openssl_work}") - file(WRITE "${_openssl_complete_marker}" "${_openssl_key_text}\n") -endfunction() - -# Prebuilt mode: the archive carries OpenSSL's libraries and generated headers, -# so nothing is built here. -if(NOT RN_GPUI_PREBUILT_DIR) - set_property(GLOBAL APPEND PROPERTY RN_GPUI_NATIVE_DEPS_ARCHIVES - "${RN_GPUI_OPENSSL_ARCHIVE_NAME} ${RN_GPUI_OPENSSL_ARCHIVE_SHA256}") - if(NOT EXISTS "${_openssl_complete_marker}") - rn_gpui_build_openssl() - else() - message(STATUS "Using cached OpenSSL ${RN_GPUI_OPENSSL_INSTALL}") - endif() -endif() -list(PREPEND CMAKE_PREFIX_PATH "${RN_GPUI_OPENSSL_INSTALL}") -set(OPENSSL_ROOT_DIR "${RN_GPUI_OPENSSL_INSTALL}" CACHE PATH "GPUI build-cache OpenSSL" FORCE) -set(OPENSSL_USE_STATIC_LIBS TRUE) - -file(GLOB _curl_roots LIST_DIRECTORIES TRUE "${RN_GPUI_CURL_ARCHIVE_DIR}/curl-8.11.1*") -list(GET _curl_roots 0 RN_GPUI_CURL_SOURCE_DIR) - -file(MAKE_DIRECTORY "${RN_GPUI_NATIVE_DEPS_PREPARED}") -set(RN_GPUI_NATIVE_DEPS_BUILD "${CMAKE_BINARY_DIR}/native-deps/build") -file(MAKE_DIRECTORY "${RN_GPUI_NATIVE_DEPS_BUILD}") - -# ReactAndroid's Gradle prepare tasks strip unused files and retain only what -# its CMake dependency targets compile. Use the same CMake recipes from RN. -set(_rn_third_party "${REACT_ANDROID_SOURCE_DIR}/src/main/jni/third-party") - -set(_dst "${RN_GPUI_NATIVE_DEPS_PREPARED}/boost") -file(REMOVE_RECURSE "${_dst}") -file(MAKE_DIRECTORY "${_dst}") -file(GLOB _boost_root LIST_DIRECTORIES TRUE "${RN_GPUI_BOOST_ARCHIVE_DIR}/boost_1_83_0*") -list(GET _boost_root 0 _boost_root) -file(COPY "${_boost_root}/boost" DESTINATION "${_dst}/boost_1_83_0") - -set(_dst "${RN_GPUI_NATIVE_DEPS_PREPARED}/double-conversion") -file(REMOVE_RECURSE "${_dst}") -file(MAKE_DIRECTORY "${_dst}") -file(GLOB _double_root LIST_DIRECTORIES TRUE "${RN_GPUI_DOUBLE_CONVERSION_ARCHIVE_DIR}/double-conversion-1.1.6*") -list(GET _double_root 0 _double_root) -file(COPY "${_double_root}/src/" DESTINATION "${_dst}/double-conversion") -configure_file("${_rn_third_party}/double-conversion/CMakeLists.txt" "${_dst}/CMakeLists.txt" COPYONLY) -# double-conversion 1.1.6 predates MSVC ARM64 and stops on `#error` there; ARM64 -# has correct double operations, as the `__aarch64__` branch already says. -set(_double_utils "${_dst}/double-conversion/utils.h") -file(READ "${_double_utils}" _double_utils_text) -string(REPLACE "#if defined(_M_X64) || defined(__x86_64__)" - "#if defined(_M_X64) || defined(_M_ARM64) || defined(__x86_64__)" - _double_utils_patched "${_double_utils_text}") -if(_double_utils_patched STREQUAL _double_utils_text) - message(FATAL_ERROR "double-conversion changed ${_double_utils}; update the ARM64 check") -endif() -file(WRITE "${_double_utils}" "${_double_utils_patched}") - -set(_dst "${RN_GPUI_NATIVE_DEPS_PREPARED}/fast_float") -file(REMOVE_RECURSE "${_dst}") -file(MAKE_DIRECTORY "${_dst}") -file(GLOB _fast_float_root LIST_DIRECTORIES TRUE "${RN_GPUI_FAST_FLOAT_ARCHIVE_DIR}/fast_float-8.0.0*") -list(GET _fast_float_root 0 _fast_float_root) -file(COPY "${_fast_float_root}/include" DESTINATION "${_dst}") -configure_file("${_rn_third_party}/fast_float/CMakeLists.txt" "${_dst}/CMakeLists.txt" COPYONLY) - -set(_dst "${RN_GPUI_NATIVE_DEPS_PREPARED}/fmt") -file(REMOVE_RECURSE "${_dst}") -file(MAKE_DIRECTORY "${_dst}") -file(GLOB _fmt_root LIST_DIRECTORIES TRUE "${RN_GPUI_FMT_ARCHIVE_DIR}/fmt-12.1.0*") -list(GET _fmt_root 0 _fmt_root) -file(COPY "${_fmt_root}/src" "${_fmt_root}/include" DESTINATION "${_dst}") -configure_file("${_rn_third_party}/fmt/CMakeLists.txt" "${_dst}/CMakeLists.txt" COPYONLY) - -set(_dst "${RN_GPUI_NATIVE_DEPS_PREPARED}/folly") -file(REMOVE_RECURSE "${_dst}") -file(MAKE_DIRECTORY "${_dst}") -file(GLOB _folly_root LIST_DIRECTORIES TRUE "${RN_GPUI_FOLLY_ARCHIVE_DIR}/folly-2024.11.18.00*") -list(GET _folly_root 0 _folly_root) -file(COPY "${_folly_root}/folly" DESTINATION "${_dst}") -file(READ "${_rn_third_party}/folly/CMakeLists.txt" _folly_cmake) -# ReactAndroid targets libc++; GPUI uses the host C++ standard library. -string(REPLACE " -DFOLLY_USE_LIBCPP=1\n" "" _folly_cmake "${_folly_cmake}") -if(WIN32) - # The rest of ReactAndroid's folly flags describe a POSIX/Android host: - # MSVC has no pthreads, recvmmsg, XSI strerror_r or clock_gettime, and folly - # selects its Windows implementations when those are not defined. - foreach(_folly_flag IN ITEMS - "-DFOLLY_HAVE_PTHREAD=1" - "-DFOLLY_HAVE_RECVMMSG=1" - "-DFOLLY_HAVE_XSI_STRERROR_R=1" - "-DFOLLY_HAVE_CLOCK_GETTIME=1" - "-DFOLLY_MOBILE=1") - string(REPLACE "${_folly_flag}\n" "\n" _folly_cmake "${_folly_cmake}") - endforeach() -endif() -file(WRITE "${_dst}/CMakeLists.txt" "${_folly_cmake}") - -set(_dst "${RN_GPUI_NATIVE_DEPS_PREPARED}/glog") -file(REMOVE_RECURSE "${_dst}") -file(MAKE_DIRECTORY "${_dst}/glog-0.3.5" "${_dst}/exported/glog") -file(GLOB _glog_root LIST_DIRECTORIES TRUE "${RN_GPUI_GLOG_ARCHIVE_DIR}/glog-0.3.5*") -list(GET _glog_root 0 _glog_root) -file(COPY "${_glog_root}/src" DESTINATION "${_dst}/glog-0.3.5") -configure_file("${_rn_third_party}/glog/CMakeLists.txt" "${_dst}/CMakeLists.txt" COPYONLY) -configure_file("${_rn_third_party}/glog/config.h" "${_dst}/config.h" COPYONLY) -file(GLOB_RECURSE _glog_templates "${_dst}/glog-0.3.5/src/*.h.in") -set(_glog_token_names - ac_cv_have_unistd_h ac_cv_have_stdint_h ac_cv_have_systypes_h ac_cv_have_inttypes_h - ac_cv_have_libgflags ac_google_start_namespace ac_cv_have_uint16_t ac_cv_have_u_int16_t - ac_cv_have___uint16 ac_google_end_namespace ac_cv_have___builtin_expect ac_google_namespace - ac_cv___attribute___noinline ac_cv___attribute___noreturn ac_cv___attribute___printf_4_5 - ac_cv_cxx_using_operator) -if(WIN32) - # MSVC has no , no __builtin_expect and no GNU __attribute__. The - # attribute tokens are commented out rather than emptied: CMake lists cannot - # carry empty elements reliably, and a comment keeps the declarations valid. - set(_glog_have_unistd_h 0) - set(_glog_have_builtin_expect 0) - set(_glog_attribute_noinline "/* noinline */") - set(_glog_attribute_noreturn "/* noreturn */") - set(_glog_attribute_printf "/* printf format attribute */") -else() - set(_glog_have_unistd_h 1) - set(_glog_have_builtin_expect 1) - set(_glog_attribute_noinline "__attribute__ ((noinline))") - set(_glog_attribute_noreturn "__attribute__ ((noreturn))") - set(_glog_attribute_printf "__attribute__((__format__ (__printf__, 4, 5)))") -endif() -set(_glog_token_values - ${_glog_have_unistd_h} 1 1 1 0 "namespace google {" 1 1 0 "}" ${_glog_have_builtin_expect} google - "${_glog_attribute_noinline}" "${_glog_attribute_noreturn}" - "${_glog_attribute_printf}" 1) -foreach(_template IN LISTS _glog_templates) - file(READ "${_template}" _glog_content) - list(LENGTH _glog_token_names _glog_token_count) - math(EXPR _glog_token_last "${_glog_token_count} - 1") - foreach(_index RANGE 0 ${_glog_token_last}) - list(GET _glog_token_names ${_index} _token_name) - list(GET _glog_token_values ${_index} _token_value) - string(REPLACE "@${_token_name}@" "${_token_value}" _glog_content "${_glog_content}") - endforeach() - string(REGEX REPLACE "\\.h\\.in$" ".h" _generated_header "${_template}") - file(WRITE "${_generated_header}" "${_glog_content}") -endforeach() -# config.h.in is an Autoconf template with #undef directives, not @name@ -# substitutions. ReactAndroid ships the configured platform header separately; -# place it at both include locations because glog's sources search src/ first. -if(WIN32) - # ReactAndroid's config.h is generated for Android/Linux and describes - # headers and builtins MSVC does not have, so Windows gets its own. - configure_file("${CMAKE_CURRENT_LIST_DIR}/glog-windows-config.h" - "${_dst}/glog-0.3.5/src/config.h" COPYONLY) - configure_file("${CMAKE_CURRENT_LIST_DIR}/glog-windows-config.h" - "${_dst}/config.h" COPYONLY) - # defines an ERROR macro, and glog refuses to compile when it is - # set. glog's escape hatch (GLOG_NO_ABBREVIATED_SEVERITIES) would force every - # ReactCommon call site onto the GLOG_ERROR spelling, so drop the macro - # instead of the severities. - file(GLOB_RECURSE _glog_severity_headers "${_dst}/glog-0.3.5/src/*log_severity.h") - foreach(_glog_severity IN LISTS _glog_severity_headers) - file(READ "${_glog_severity}" _glog_severity_content) - string(REPLACE "# error ERROR macro is defined." "# undef ERROR /* patched for Windows */ //" - _glog_severity_content "${_glog_severity_content}") - file(WRITE "${_glog_severity}" "${_glog_severity_content}") - endforeach() -else() - configure_file("${_rn_third_party}/glog/config.h" "${_dst}/glog-0.3.5/src/config.h" COPYONLY) -endif() -foreach(_header IN ITEMS stl_logging.h logging.h raw_logging.h vlog_is_on.h log_severity.h) - if(EXISTS "${_dst}/glog-0.3.5/src/${_header}") - configure_file("${_dst}/glog-0.3.5/src/${_header}" "${_dst}/exported/glog/${_header}" COPYONLY) - elseif(EXISTS "${_dst}/glog-0.3.5/src/glog/${_header}") - configure_file("${_dst}/glog-0.3.5/src/glog/${_header}" "${_dst}/exported/glog/${_header}" COPYONLY) - endif() -endforeach() - -set(_dst "${RN_GPUI_NATIVE_DEPS_PREPARED}/nlohmann_json") -file(REMOVE_RECURSE "${_dst}") -file(MAKE_DIRECTORY "${_dst}") -file(GLOB _json_root LIST_DIRECTORIES TRUE "${RN_GPUI_NLOHMANN_JSON_ARCHIVE_DIR}/json-3.11.2*") -list(GET _json_root 0 _json_root) -file(COPY "${_json_root}/include" DESTINATION "${_dst}") - -# The archives (name and sha256) this build used, for scripts/build-prebuilt.mjs -# to list in the manifest; the shared cache holds archives of other builds too. -get_property(_rn_gpui_native_deps_archives GLOBAL PROPERTY RN_GPUI_NATIVE_DEPS_ARCHIVES) -list(SORT _rn_gpui_native_deps_archives) -string(JOIN "\n" _rn_gpui_native_deps_archives_text ${_rn_gpui_native_deps_archives}) -file(WRITE "${CMAKE_BINARY_DIR}/native-deps/archives.txt" "${_rn_gpui_native_deps_archives_text}\n") diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/NodeModules.cmake b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/NodeModules.cmake deleted file mode 100644 index 60a001ddbc..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/NodeModules.cmake +++ /dev/null @@ -1,28 +0,0 @@ -# Finds an installed package without assuming a repository layout. -# -# Every package lives at `node_modules/` in an app, but this repository -# keeps its own packages at different depths (`packages/core`, `packages/hermes`), -# so counting parent directories can only be right in one of the two. The walk -# starts at the project root and goes up, which covers a package hoisted to an -# ancestor `node_modules` (npm workspaces) as well as one sitting beside the app -# (pnpm, a nested install). -function(rn_gpui_find_node_module package out_var) - if(NOT RN_GPUI_PROJECT_ROOT) - message(FATAL_ERROR - "rn_gpui_find_node_module(${package}) needs RN_GPUI_PROJECT_ROOT, which the platform's build.rs sets") - endif() - set(_rn_gpui_search "${RN_GPUI_PROJECT_ROOT}") - while(_rn_gpui_search) - if(EXISTS "${_rn_gpui_search}/node_modules/${package}/package.json") - set(${out_var} "${_rn_gpui_search}/node_modules/${package}" PARENT_SCOPE) - return() - endif() - get_filename_component(_rn_gpui_parent "${_rn_gpui_search}" DIRECTORY) - if(_rn_gpui_parent STREQUAL _rn_gpui_search) - break() - endif() - set(_rn_gpui_search "${_rn_gpui_parent}") - endwhile() - message(FATAL_ERROR - "${package} was not found in any node_modules at or above ${RN_GPUI_PROJECT_ROOT}") -endfunction() diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/glog-windows-config.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/glog-windows-config.h deleted file mode 100644 index d8f575d130..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/glog-windows-config.h +++ /dev/null @@ -1,33 +0,0 @@ -/* glog configuration for MSVC on Windows. - * - * ReactAndroid ships an Autoconf config.h generated on Android/Linux, and - * glog 0.3.5 predates MSVC support in its own build system, so the Windows - * answers are provided here instead of reusing those POSIX results. Anything - * not defined here is deliberately absent: no , , - * or , no __sync builtins, no GNU __attribute__, - * no __builtin_expect, no execinfo/glob/pwd/sigaction/sigaltstack/syslog and - * no pread or pthreads. - */ -/* No HAVE_FCNTL: MSVC's lacks F_SETFD/FD_CLOEXEC, and glog's - * fopen fallback is the Windows path. */ -#define HAVE_INTTYPES_H 1 -#define HAVE_SNPRINTF 1 -#define HAVE_STDINT_H 1 -#define HAVE_STRING_H 1 -#define HAVE_SYS_STAT_H 1 -#define HAVE_SYS_TYPES_H 1 -#define HAVE_TIME_H 1 -#define HAVE_USING_OPERATOR 1 - -/* glog's headers wrap their declarations in these namespace macros. */ -#define _START_GOOGLE_NAMESPACE_ namespace google { -#define _END_GOOGLE_NAMESPACE_ } - -#define STL_NAMESPACE std - -/* ReactAndroid's android-* builds are 32-bit; this one is 64-bit. */ -#define SIZEOF_VOID_P 8 - -#define PACKAGE "glog" -#define PACKAGE_VERSION "0.3.5" -#define VERSION "0.3.5" diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/modules/PrebuiltInstall.cmake b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/modules/PrebuiltInstall.cmake deleted file mode 100644 index b9fd7b279b..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/modules/PrebuiltInstall.cmake +++ /dev/null @@ -1,400 +0,0 @@ -include(GNUInstallDirs) - -set(RN_GPUI_PREBUILT_CONFIG_NAME "react-native-gpui-prebuilt") -set(_rn_gpui_prebuilt_gen "${CMAKE_BINARY_DIR}/prebuilt") - -# --- classify the link closure ------------------------------------------------- -# Skipped: app-side and per-app targets (rn_gpui_app_turbo_modules, -# rn_gpui_modules, rn_gpui_autolink_*). -set(_rn_gpui_built "") # real archives/dylibs we built (names resolved) -set(_rn_gpui_imported "") # imported archives/dylibs, names as in the closure -set(_rn_gpui_shadow "") # OBJECT/INTERFACE names -set(_rn_gpui_order "") # ordered entries that real/imported targets need -foreach(_rn_gpui_entry IN LISTS RN_GPUI_LINK_TARGETS) - if(_rn_gpui_entry STREQUAL "rn_gpui_app_turbo_modules" - OR _rn_gpui_entry STREQUAL "rn_gpui_modules" - OR _rn_gpui_entry MATCHES "^rn_gpui_autolink_") - continue() - endif() - get_target_property(_rn_gpui_type "${_rn_gpui_entry}" TYPE) - get_target_property(_rn_gpui_aliased "${_rn_gpui_entry}" ALIASED_TARGET) - if(_rn_gpui_aliased) - set(_rn_gpui_real "${_rn_gpui_aliased}") - else() - set(_rn_gpui_real "${_rn_gpui_entry}") - endif() - if(_rn_gpui_type MATCHES "^(OBJECT|INTERFACE)_LIBRARY$") - list(APPEND _rn_gpui_shadow "${_rn_gpui_entry}") - elseif(_rn_gpui_type MATCHES "^(STATIC|SHARED)_LIBRARY$" OR _rn_gpui_type STREQUAL "UNKNOWN_LIBRARY") - get_target_property(_rn_gpui_imported_flag "${_rn_gpui_real}" IMPORTED) - if(_rn_gpui_imported_flag) - list(APPEND _rn_gpui_imported "${_rn_gpui_real}") - else() - list(APPEND _rn_gpui_built "${_rn_gpui_real}") - endif() - list(APPEND _rn_gpui_order "${_rn_gpui_entry}") - endif() -endforeach() -list(REMOVE_DUPLICATES _rn_gpui_built) -list(REMOVE_DUPLICATES _rn_gpui_imported) - -install(TARGETS ${_rn_gpui_built} - ARCHIVE DESTINATION lib - LIBRARY DESTINATION lib - RUNTIME DESTINATION bin) - -# Imported archives (OpenSSL and the third-party libraries) are copied from the -# path configure found. An engine's own shared library is not part of the -# archive: the installed engine package ships it. -set(_rn_gpui_imported_paths "") -foreach(_rn_gpui_imp IN LISTS _rn_gpui_imported) - get_target_property(_rn_gpui_loc "${_rn_gpui_imp}" IMPORTED_LOCATION) - if(_rn_gpui_loc AND EXISTS "${_rn_gpui_loc}") - list(APPEND _rn_gpui_imported_paths "${_rn_gpui_loc}") - else() - message(WARNING "prebuilt: imported ${_rn_gpui_imp} has no IMPORTED_LOCATION; not installed") - endif() -endforeach() -if(_rn_gpui_imported_paths) - install(FILES ${_rn_gpui_imported_paths} DESTINATION lib) -endif() - -# --- headers -------------------------------------------------------------------- -# The archive ships no headers except OpenSSL's generated tree (Configure output, -# which consumers cannot produce without Perl). Every other header tree is named -# by a root variable RN_GPUI_PREBUILT_ROOT_ that the consumer sets to the -# source directory it already has (node_modules/react-native, the react-native-gpui -# package, its own cxxbridge and codegen output, an installed engine package, and -# the native-deps downloads). The targets file refers to those roots, so the -# config file checks they are set before anything is included. -install(DIRECTORY "${RN_GPUI_OPENSSL_INSTALL}/include/" - DESTINATION include/openssl-generated - FILES_MATCHING PATTERN "*.h") - -# Static include roots in search order. ReactCommonOverrides precedes ReactCommon -# so the override headers shadow the upstream ones, as the source build does. -set(_rn_gpui_include_roots - "\${RN_GPUI_PREBUILT_ROOT_react_native_gpui}" - "\${RN_GPUI_PREBUILT_ROOT_react_common_overrides}" - "\${RN_GPUI_PREBUILT_ROOT_react_common}" - "\${RN_GPUI_PREBUILT_ROOT_react_common}/jsi" - "\${RN_GPUI_PREBUILT_ROOT_react_common}/callinvoker" - "\${RN_GPUI_PREBUILT_ROOT_react_cxx_platform}" - "\${RN_GPUI_PREBUILT_ROOT_generated_rncore}" - "\${RN_GPUI_PREBUILT_ROOT_cxxbridge}" - "\${RN_GPUI_PREBUILT_ROOT_folly}" - "\${RN_GPUI_PREBUILT_ROOT_glog}" - "\${RN_GPUI_PREBUILT_ROOT_fmt}" - "\${RN_GPUI_PREBUILT_ROOT_double_conversion}" - "\${RN_GPUI_PREBUILT_ROOT_fast_float}" - "\${RN_GPUI_PREBUILT_ROOT_nlohmann_json}" - "\${RN_GPUI_PREBUILT_ROOT_boost}" - "\${RN_GPUI_PREBUILT_ROOT_curl}" - "\${RN_GPUI_PREBUILT_ROOT_openssl_generated}") - -# --- folly compile flags ---------------------------------------------------------- -# The source build has no folly-config.h. folly's flags (FOLLY_NO_CONFIG, -# FOLLY_HAVE_*, ...) are PUBLIC compile *options* on folly_runtime -# (-D= in folly/CMakeLists.txt), so they live in -# INTERFACE_COMPILE_OPTIONS. Split them: -D entries become compile definitions, -# everything else stays a compile option. Every exported target carries them, -# so consumers compile folly headers the same way the source build does. -set(_rn_gpui_folly_defs "") -set(_rn_gpui_folly_opts "") -if(TARGET folly_runtime) - get_target_property(_rn_gpui_folly_all folly_runtime INTERFACE_COMPILE_OPTIONS) - if(NOT _rn_gpui_folly_all) - set(_rn_gpui_folly_all "") - endif() - foreach(_rn_gpui_flag IN LISTS _rn_gpui_folly_all) - if(_rn_gpui_flag MATCHES "^-D(.+)$") - list(APPEND _rn_gpui_folly_defs "${CMAKE_MATCH_1}") - else() - list(APPEND _rn_gpui_folly_opts "${_rn_gpui_flag}") - endif() - endforeach() -endif() - -# --- include roots from the link closure ---------------------------------------- -# Source targets add their own include dirs (ReactCommon subdirectories such as -# react/renderer/graphics/platform/cxx and react/nativemodule/core). Map every dir -# that lies inside a source tree to "/", so -# the consumer resolves it against the tree it has. Longest source prefix wins. -# Pairs are "" "". -set(_rn_gpui_include_map - "${RN_GPUI_OVERRIDES_DIR}" "\${RN_GPUI_PREBUILT_ROOT_react_common_overrides}" - "${REACT_COMMON_DIR}" "\${RN_GPUI_PREBUILT_ROOT_react_common}" - "${REACT_CXX_PLATFORM_DIR}" "\${RN_GPUI_PREBUILT_ROOT_react_cxx_platform}" - "${CMAKE_CURRENT_SOURCE_DIR}" "\${RN_GPUI_PREBUILT_ROOT_react_native_gpui}" - "${RN_GPUI_CXXBRIDGE_INCLUDE_DIR}" "\${RN_GPUI_PREBUILT_ROOT_cxxbridge}" - "${RN_GPUI_GENERATED_RNCORE_DIR}/jni" "\${RN_GPUI_PREBUILT_ROOT_generated_rncore}" - "${RN_GPUI_NATIVE_DEPS_PREPARED}/folly" "\${RN_GPUI_PREBUILT_ROOT_folly}" - "${RN_GPUI_NATIVE_DEPS_PREPARED}/glog/exported" "\${RN_GPUI_PREBUILT_ROOT_glog}" - "${RN_GPUI_NATIVE_DEPS_PREPARED}/fmt/include" "\${RN_GPUI_PREBUILT_ROOT_fmt}" - "${RN_GPUI_NATIVE_DEPS_PREPARED}/double-conversion" "\${RN_GPUI_PREBUILT_ROOT_double_conversion}" - "${RN_GPUI_NATIVE_DEPS_PREPARED}/fast_float/include" "\${RN_GPUI_PREBUILT_ROOT_fast_float}" - "${RN_GPUI_NATIVE_DEPS_PREPARED}/nlohmann_json/include" "\${RN_GPUI_PREBUILT_ROOT_nlohmann_json}" - "${RN_GPUI_NATIVE_DEPS_PREPARED}/boost/boost_1_83_0" "\${RN_GPUI_PREBUILT_ROOT_boost}" - "${RN_GPUI_CURL_SOURCE_DIR}/include" "\${RN_GPUI_PREBUILT_ROOT_curl}" - "${RN_GPUI_OPENSSL_INSTALL}/include" "\${RN_GPUI_PREBUILT_ROOT_openssl_generated}") - -# rn_gpui_prebuilt_include_ref( ): sets to the -# root-variable reference for (e.g. "${RN_GPUI_PREBUILT_ROOT_boost}/x"), -# or "" when the dir is not inside any mapped source tree. -function(rn_gpui_prebuilt_include_ref dir out_var) - # Source trees are often named with "..", e.g. REACT_COMMON_DIR is - # ${CMAKE_CURRENT_SOURCE_DIR}/../../..; targets report normalized paths. - # Normalize both sides so the prefix comparison can match. - get_filename_component(dir "${dir}" ABSOLUTE) - set(_best_len -1) - set(_best "") - list(LENGTH _rn_gpui_include_map _map_count) - math(EXPR _map_last "${_map_count} - 1") - foreach(_map_i RANGE 0 ${_map_last} 2) - list(GET _rn_gpui_include_map ${_map_i} _prefix) - if(NOT _prefix STREQUAL "") - get_filename_component(_prefix "${_prefix}" ABSOLUTE) - endif() - math(EXPR _installed_i "${_map_i} + 1") - list(GET _rn_gpui_include_map ${_installed_i} _installed) - string(LENGTH "${_prefix}" _plen) - # An unset source variable leaves an empty prefix; it must not match anything. - if(_plen EQUAL 0 OR NOT _plen GREATER _best_len) - continue() - endif() - string(LENGTH "${dir}" _dlen) - if(dir STREQUAL _prefix) - set(_rel "") - else() - if(NOT _dlen GREATER _plen) - continue() - endif() - string(SUBSTRING "${dir}" 0 ${_plen} _head) - string(SUBSTRING "${dir}" ${_plen} 1 _sep) - if(NOT _head STREQUAL _prefix OR NOT _sep STREQUAL "/") - continue() - endif() - math(EXPR _rest_at "${_plen} + 1") - string(SUBSTRING "${dir}" ${_rest_at} -1 _rel) - endif() - set(_best_len ${_plen}) - if(_rel STREQUAL "") - set(_best "${_installed}") - else() - set(_best "${_installed}/${_rel}") - endif() - endforeach() - set(${out_var} "${_best}" PARENT_SCOPE) -endfunction() - -# Walk the link closure and the shadow targets, collect every include dir they -# declare (BUILD_INTERFACE only; INSTALL_INTERFACE and unexpanded generator -# expressions are skipped), and map each one to its installed location. -set(_rn_gpui_mapped_includes "") -set(_rn_gpui_include_walk ${RN_GPUI_LINK_TARGETS} ${_rn_gpui_shadow}) -list(REMOVE_DUPLICATES _rn_gpui_include_walk) -foreach(_rn_gpui_walk_name IN LISTS _rn_gpui_include_walk) - if(NOT TARGET "${_rn_gpui_walk_name}") - continue() - endif() - foreach(_rn_gpui_prop IN ITEMS INTERFACE_INCLUDE_DIRECTORIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES) - get_target_property(_rn_gpui_dirs "${_rn_gpui_walk_name}" ${_rn_gpui_prop}) - if(NOT _rn_gpui_dirs) - continue() - endif() - foreach(_rn_gpui_dir IN LISTS _rn_gpui_dirs) - if(_rn_gpui_dir MATCHES "^\\$$") - set(_rn_gpui_dir "${CMAKE_MATCH_1}") - elseif(_rn_gpui_dir MATCHES "\\$<") - continue() - endif() - rn_gpui_prebuilt_include_ref("${_rn_gpui_dir}" _rn_gpui_inst) - if(_rn_gpui_inst) - list(APPEND _rn_gpui_mapped_includes "${_rn_gpui_inst}") - endif() - endforeach() - endforeach() -endforeach() -# Directory-level include_directories() calls (overrides, cpp/) reach targets -# only through the directory's INCLUDE_DIRECTORIES property, not their own -# INTERFACE properties. Map those too, so they stay on the consumer's path. -get_property(_rn_gpui_dir_incs DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" PROPERTY INCLUDE_DIRECTORIES) -foreach(_rn_gpui_dir IN LISTS _rn_gpui_dir_incs) - rn_gpui_prebuilt_include_ref("${_rn_gpui_dir}" _rn_gpui_inst) - if(_rn_gpui_inst) - list(APPEND _rn_gpui_mapped_includes "${_rn_gpui_inst}") - endif() -endforeach() -list(REMOVE_DUPLICATES _rn_gpui_mapped_includes) -foreach(_rn_gpui_inc IN LISTS _rn_gpui_mapped_includes) - list(APPEND _rn_gpui_include_roots "${_rn_gpui_inc}") -endforeach() -# Static roots first, so overrides (installed into include/react-common, which -# the mapped dirs also point at) keep their place ahead of upstream headers. -list(REMOVE_DUPLICATES _rn_gpui_include_roots) - -# --- targets file --------------------------------------------------------------- -# Generated with file(GENERATE) so $ resolves to the real -# archive name for this configuration. Paths use _rn_gpui_prebuilt_root, which -# the file computes from its own location, so the archive works unpacked anywhere. -set(_rn_gpui_targets_text -"# Generated by cpp/cmake/modules/PrebuiltInstall.cmake. Do not edit. -get_filename_component(_rn_gpui_prebuilt_root \"\${CMAKE_CURRENT_LIST_DIR}/..\" ABSOLUTE) -# OpenSSL's generated headers are the only headers in the archive. -set(RN_GPUI_PREBUILT_ROOT_openssl_generated \"\${_rn_gpui_prebuilt_root}/include/openssl-generated\") -set(_rn_gpui_prebuilt_include_roots \"${_rn_gpui_include_roots}\") -") - -# Every archive/dylib entry in the closure gets one IMPORTED target under the -# entry's own name (CURL::libcurl stays CURL::libcurl, even though its real -# target is libcurl_static), so INTERFACE_LINK_LIBRARIES below resolves in the -# consumer. Built entries point at $ for this configuration; -# imported entries use the file name configure resolved. -foreach(_rn_gpui_entry IN LISTS _rn_gpui_order) - if(_rn_gpui_entry STREQUAL "rn_gpui_core") - continue() - endif() - get_target_property(_rn_gpui_aliased "${_rn_gpui_entry}" ALIASED_TARGET) - if(_rn_gpui_aliased) - set(_rn_gpui_real "${_rn_gpui_aliased}") - else() - set(_rn_gpui_real "${_rn_gpui_entry}") - endif() - get_target_property(_rn_gpui_imported_flag "${_rn_gpui_real}" IMPORTED) - get_target_property(_rn_gpui_real_type "${_rn_gpui_real}" TYPE) - if(_rn_gpui_real_type STREQUAL "SHARED_LIBRARY") - set(_rn_gpui_kind "SHARED") - elseif(_rn_gpui_real_type STREQUAL "UNKNOWN_LIBRARY") - set(_rn_gpui_kind "UNKNOWN") - else() - set(_rn_gpui_kind "STATIC") - endif() - if(_rn_gpui_imported_flag) - get_target_property(_rn_gpui_loc "${_rn_gpui_real}" IMPORTED_LOCATION) - if(NOT _rn_gpui_loc OR NOT EXISTS "${_rn_gpui_loc}") - message(WARNING "prebuilt: imported ${_rn_gpui_real} has no IMPORTED_LOCATION; skipped") - continue() - endif() - get_filename_component(_rn_gpui_base "${_rn_gpui_loc}" NAME) - set(_rn_gpui_file "${_rn_gpui_base}") - else() - set(_rn_gpui_file "$") - endif() - # A built shared library links through its import library, which the install - # rules above put in `lib/` while the DLL itself goes to `bin/`. Emitting only - # IMPORTED_LOCATION left the consumer with nothing to link against: CMake - # resolved the target to `jsi-NOTFOUND` and the link emitted an empty `-L`, - # failing with "empty search path given via `-L`". Name the DLL in `bin/` and - # the import library in `lib/`. - # - # Only built targets: an imported shared library is installed with - # `install(FILES ... DESTINATION lib)` and has no import library in the - # archive, so its single file keeps naming `lib/`. - if(_rn_gpui_kind STREQUAL "SHARED" AND NOT _rn_gpui_imported_flag) - string(APPEND _rn_gpui_targets_text -"add_library(${_rn_gpui_entry} ${_rn_gpui_kind} IMPORTED) -set_target_properties(${_rn_gpui_entry} PROPERTIES - IMPORTED_LOCATION \"\${_rn_gpui_prebuilt_root}/bin/${_rn_gpui_file}\" - IMPORTED_IMPLIB \"\${_rn_gpui_prebuilt_root}/lib/$\") -") - continue() - endif() - string(APPEND _rn_gpui_targets_text -"add_library(${_rn_gpui_entry} ${_rn_gpui_kind} IMPORTED) -set_target_properties(${_rn_gpui_entry} PROPERTIES - IMPORTED_LOCATION \"\${_rn_gpui_prebuilt_root}/lib/${_rn_gpui_file}\") -") -endforeach() - -# Shadow targets: INTERFACE, include roots, folly defs, and their own defs. -# They link rn_gpui_core, which already carries every archive. -foreach(_rn_gpui_shadow_name IN LISTS _rn_gpui_shadow) - get_target_property(_rn_gpui_own_defs "${_rn_gpui_shadow_name}" INTERFACE_COMPILE_DEFINITIONS) - if(NOT _rn_gpui_own_defs) - set(_rn_gpui_own_defs "") - endif() - set(_rn_gpui_defs ${_rn_gpui_folly_defs} ${_rn_gpui_own_defs}) - list(REMOVE_DUPLICATES _rn_gpui_defs) - string(APPEND _rn_gpui_targets_text -"add_library(${_rn_gpui_shadow_name} INTERFACE IMPORTED) -set_target_properties(${_rn_gpui_shadow_name} PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES \"\${_rn_gpui_prebuilt_include_roots}\" - INTERFACE_COMPILE_DEFINITIONS \"${_rn_gpui_defs}\" - INTERFACE_COMPILE_OPTIONS \"${_rn_gpui_folly_opts}\" - INTERFACE_LINK_LIBRARIES rn_gpui_core) -") -endforeach() - -# rn_gpui_core links the real archives in the closure's order, which is the -# order static archives must be resolved in. -set(_rn_gpui_core_links "") -foreach(_rn_gpui_entry IN LISTS _rn_gpui_order) - if(NOT _rn_gpui_entry STREQUAL "rn_gpui_core") - list(APPEND _rn_gpui_core_links "${_rn_gpui_entry}") - endif() -endforeach() -list(REMOVE_DUPLICATES _rn_gpui_core_links) -get_target_property(_rn_gpui_core_defs rn_gpui_core INTERFACE_COMPILE_DEFINITIONS) -if(NOT _rn_gpui_core_defs) - set(_rn_gpui_core_defs "") -endif() -set(_rn_gpui_core_all_defs ${_rn_gpui_folly_defs} ${_rn_gpui_core_defs}) -list(REMOVE_DUPLICATES _rn_gpui_core_all_defs) -string(APPEND _rn_gpui_targets_text -"add_library(rn_gpui_core STATIC IMPORTED) -set_target_properties(rn_gpui_core PROPERTIES - IMPORTED_LOCATION \"\${_rn_gpui_prebuilt_root}/lib/$\" - INTERFACE_INCLUDE_DIRECTORIES \"\${_rn_gpui_prebuilt_include_roots}\" - INTERFACE_COMPILE_DEFINITIONS \"${_rn_gpui_core_all_defs}\" - INTERFACE_COMPILE_OPTIONS \"${_rn_gpui_folly_opts}\" - INTERFACE_LINK_LIBRARIES \"${_rn_gpui_core_links}\") -") - -# The targets file is evaluated per configuration: `$` -# differs between Debug and Release on MSVC (`libcurl-d.lib` vs `libcurl.lib`). -# A multi-config generator (Visual Studio) therefore rejects a fixed output name -# ("Evaluation file to be written multiple times with different content"), so the -# configuration goes into the generated name there. The install step below picks -# the one that belongs to the configuration being installed and renames it back, -# so the installed layout is identical on every platform. -if(CMAKE_CONFIGURATION_TYPES) - set(_rn_gpui_targets_suffix "-$") -else() - set(_rn_gpui_targets_suffix "") -endif() -set(_rn_gpui_targets_file - "${_rn_gpui_prebuilt_gen}/${RN_GPUI_PREBUILT_CONFIG_NAME}-targets${_rn_gpui_targets_suffix}.cmake") -file(GENERATE OUTPUT "${_rn_gpui_targets_file}" - CONTENT "${_rn_gpui_targets_text}") - -# --- config file -------------------------------------------------------------------- -# Every root the targets file can reference. The consumer must set each one to -# an existing directory before find_package; openssl_generated is set by the -# targets file itself. -set(_rn_gpui_required_roots - react_native_gpui react_common_overrides react_common react_cxx_platform - generated_rncore cxxbridge folly glog fmt double_conversion fast_float - nlohmann_json boost curl) -set(_rn_gpui_root_checks "") -foreach(_rn_gpui_root IN LISTS _rn_gpui_required_roots) - string(APPEND _rn_gpui_root_checks -"if(NOT DEFINED RN_GPUI_PREBUILT_ROOT_${_rn_gpui_root} OR NOT EXISTS \"\${RN_GPUI_PREBUILT_ROOT_${_rn_gpui_root}}\") - message(FATAL_ERROR \"${RN_GPUI_PREBUILT_CONFIG_NAME}: RN_GPUI_PREBUILT_ROOT_${_rn_gpui_root} must be set to an existing directory\") -endif() -") -endforeach() -file(WRITE "${_rn_gpui_prebuilt_gen}/${RN_GPUI_PREBUILT_CONFIG_NAME}-config.cmake" -"# Consumer entry point: find_package(${RN_GPUI_PREBUILT_CONFIG_NAME} CONFIG REQUIRED) -# Set RN_GPUI_PREBUILT_ROOT_ for each name below before calling it. -${_rn_gpui_root_checks}include(\"\${CMAKE_CURRENT_LIST_DIR}/${RN_GPUI_PREBUILT_CONFIG_NAME}-targets.cmake\") -set(${RN_GPUI_PREBUILT_CONFIG_NAME}_FOUND TRUE) -") - -install(FILES - "${_rn_gpui_prebuilt_gen}/${RN_GPUI_PREBUILT_CONFIG_NAME}-config.cmake" - DESTINATION cmake) -# `$` in the source name resolves to the configuration being installed, -# and RENAME gives every platform the same installed file name. -install(FILES "${_rn_gpui_targets_file}" - DESTINATION cmake - RENAME "${RN_GPUI_PREBUILT_CONFIG_NAME}-targets.cmake") diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/modules/ThirdParty.cmake b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/modules/ThirdParty.cmake deleted file mode 100644 index a70529693c..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/modules/ThirdParty.cmake +++ /dev/null @@ -1,84 +0,0 @@ -add_subdirectory("${RN_GPUI_NATIVE_DEPS_PREPARED}/glog" "${RN_GPUI_NATIVE_DEPS_BUILD}/glog") -if(WIN32) - # glog's utilities.h includes "port.h" when OS_WINDOWS is defined, and that - # header lives in glog-/src/windows. RN's Android-first CMakeLists - # only exposes the project root and exported/ to the compiler. - file(GLOB _rn_gpui_glog_windows_include - "${RN_GPUI_NATIVE_DEPS_PREPARED}/glog/glog-*/src/windows") - if(_rn_gpui_glog_windows_include) - target_include_directories(glog PRIVATE ${_rn_gpui_glog_windows_include}) - endif() - # glog 0.3.5 predates VS2015's C99 snprintf and would declare its own - # (C2375: redefinition; different linkage); HAVE_SNPRINTF skips that - # declaration. Its symbolize.cc uses the DbgHelp API. - target_compile_definitions(glog PRIVATE HAVE_SNPRINTF=1) - target_link_libraries(glog PUBLIC dbghelp) - # ReactAndroid's glog source list omits src/windows/port.cc, which provides - # safe_vsnprintf (used by raw_logging) and the other Windows shims. - file(GLOB _rn_gpui_glog_windows_sources - "${RN_GPUI_NATIVE_DEPS_PREPARED}/glog/glog-*/src/windows/*.cc") - if(_rn_gpui_glog_windows_sources) - target_sources(glog PRIVATE ${_rn_gpui_glog_windows_sources}) - endif() -endif() -add_subdirectory("${RN_GPUI_NATIVE_DEPS_PREPARED}/double-conversion" "${RN_GPUI_NATIVE_DEPS_BUILD}/double-conversion") -add_subdirectory("${RN_GPUI_NATIVE_DEPS_PREPARED}/fast_float" "${RN_GPUI_NATIVE_DEPS_BUILD}/fast_float") -add_subdirectory("${RN_GPUI_NATIVE_DEPS_PREPARED}/fmt" "${RN_GPUI_NATIVE_DEPS_BUILD}/fmt") -add_subdirectory("${RN_GPUI_NATIVE_DEPS_PREPARED}/folly" "${RN_GPUI_NATIVE_DEPS_BUILD}/folly") -# RN's reduced Folly target omits platform-neutral sources used by -# ReactCxxPlatform's HTTP and threading implementations on desktop targets. -target_sources(folly_runtime PRIVATE - "${RN_GPUI_NATIVE_DEPS_PREPARED}/folly/folly/system/ThreadName.cpp" - "${RN_GPUI_NATIVE_DEPS_PREPARED}/folly/folly/io/IOBuf.cpp" - "${RN_GPUI_NATIVE_DEPS_PREPARED}/folly/folly/Uri.cpp" - "${RN_GPUI_NATIVE_DEPS_PREPARED}/folly/folly/memory/SanitizeAddress.cpp") -if(WIN32) - # On Windows folly routes POSIX calls (close, dup, sysconf, open, mmap, - # getrusage) through folly/portability/*.cpp, which Android never needs. - # Unistd.cpp closes sockets through SocketFileDescriptorMap, and MSVC - # references the leak annotations that clang folds away. - file(GLOB _rn_gpui_folly_portability - "${RN_GPUI_NATIVE_DEPS_PREPARED}/folly/folly/portability/*.cpp") - list(FILTER _rn_gpui_folly_portability EXCLUDE REGEX "/SysUio\\.cpp$") - target_sources(folly_runtime PRIVATE - ${_rn_gpui_folly_portability} - "${RN_GPUI_NATIVE_DEPS_PREPARED}/folly/folly/net/detail/SocketFileDescriptorMap.cpp" - "${RN_GPUI_NATIVE_DEPS_PREPARED}/folly/folly/memory/SanitizeLeak.cpp") - target_link_libraries(folly_runtime ws2_32) - # portability/PThread.cpp implements pthread keys with - # boost::thread_specific_ptr, which lives in compiled Boost.Thread. Only - # its Win32 TSS sources are needed; tss_pe.cpp runs the per-thread cleanup. - set(_rn_gpui_boost_thread - "${RN_GPUI_BOOST_ARCHIVE_DIR}/boost_1_83_0/libs/thread/src/win32") - target_sources(folly_runtime PRIVATE - "${_rn_gpui_boost_thread}/thread.cpp" - "${_rn_gpui_boost_thread}/thread_primitives.cpp" - "${_rn_gpui_boost_thread}/tss_pe.cpp") - set_source_files_properties( - "${_rn_gpui_boost_thread}/thread.cpp" - "${_rn_gpui_boost_thread}/thread_primitives.cpp" - "${_rn_gpui_boost_thread}/tss_pe.cpp" - TARGET_DIRECTORY folly_runtime - PROPERTIES COMPILE_DEFINITIONS "BOOST_THREAD_BUILD_LIB;BOOST_CHRONO_HEADER_ONLY") -endif() - -add_library(boost INTERFACE) -target_include_directories(boost INTERFACE - "${RN_GPUI_NATIVE_DEPS_PREPARED}/boost/boost_1_83_0" - "${RN_GPUI_OPENSSL_INSTALL}/include") - -add_library(nlohmann_json INTERFACE) -target_include_directories(nlohmann_json INTERFACE - "${RN_GPUI_NATIVE_DEPS_PREPARED}/nlohmann_json/include") -add_library(double_conversion ALIAS double-conversion) - -# folly -> folly_runtime (RN's name for this dependency). -# fbgloginit and fbjni are Android/JNI-only. -add_library(glog_init INTERFACE) -add_library(fbjni INTERFACE) - -find_package(OpenSSL REQUIRED) - -# The Hermes VM and the React Native Hermes glue live in the engine package -# @react-native-gpui/hermes/desktop/CMakeLists.txt, which autolink adds when the -# package is installed. Core has no engine of its own. diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/msvc-preinclude.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/msvc-preinclude.h deleted file mode 100644 index ed989d2f96..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/cmake/msvc-preinclude.h +++ /dev/null @@ -1,65 +0,0 @@ -// Standard headers that MSVC's standard library does not pull in -// transitively the way libc++ does. -// -// ReactCommon (and folly) rely on the libc++ behaviour in places, for example -// jsinspector-modern/HostTarget.h uses std::mutex without including . -// This header is force-included into every C++ translation unit on MSVC -// (`/FI`), mirroring the `-include cstdint` the Linux build already needs. -#pragma once - -/* The header is force-included into C sources too (lexbor); the C++ standard - headers below make the MSVC C compiler fail with STL1003. */ -#ifdef __cplusplus - -/* M_PI and friends are only exposed when this is defined before . */ -#ifndef _USE_MATH_DEFINES -#define _USE_MATH_DEFINES -#endif -#include - -/* ReactCommon calls __builtin_trap() in a few places. */ -#if !defined(__builtin_trap) -#define __builtin_trap() __debugbreak() -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Additional headers MSVC does not reach transitively from ReactCommon's own -// includes (react-native-windows force-includes the same set through its PCH). -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#endif /* __cplusplus */ diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/jni/CMakeLists.txt b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/jni/CMakeLists.txt deleted file mode 100644 index c19b292769..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/jni/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -# The build script runs the pinned React Native @react-native/codegen into -# Cargo's OUT_DIR. Consume its Android component/C++ TurboModule output here; -# Android Java and JNI implementation sources are intentionally not built. - -cmake_minimum_required(VERSION 3.13) -set(CMAKE_VERBOSE_MAKEFILE on) - -set(RN_GPUI_CODEGEN_JNI_DIR "${RN_GPUI_GENERATED_RNCORE_DIR}/jni") -file(GLOB react_codegen_SRCS CONFIGURE_DEPENDS - "${RN_GPUI_CODEGEN_JNI_DIR}/react/renderer/components/FBReactNativeSpec/*.cpp") - -add_library( - react_codegen_rncore - OBJECT - ${react_codegen_SRCS} -) - -target_include_directories(react_codegen_rncore PUBLIC - "${RN_GPUI_CODEGEN_JNI_DIR}" - "${RN_GPUI_CODEGEN_JNI_DIR}/react/renderer/components/FBReactNativeSpec" - "${RN_GPUI_CODEGEN_JNI_DIR}/react/renderer/components" -) - -target_link_libraries( - react_codegen_rncore - jsi - # We need to link different libraries based on whether we are building rncore or not, that's necessary - # because we want to break a circular dependency between react_codegen_rncore and reactnative - folly_runtime glog react_debug react_nativemodule_core react_renderer_componentregistry react_renderer_core react_renderer_debug react_renderer_graphics react_renderer_imagemanager react_renderer_mapbuffer react_utils rrc_image rrc_view yoga -) - -target_compile_reactnative_options(react_codegen_rncore PRIVATE) diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/rn_gpui_linux_prefix.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/rn_gpui_linux_prefix.h deleted file mode 100644 index 757685ece1..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/rn_gpui_linux_prefix.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -// Force-included on Linux (see CMakeLists.txt), before every C++ translation -// unit in this tree. React Native's headers and the packages it bundles rely on -// the libc++ headers shipping transitively; GCC/libstdc++ does not. -// -// - RN 0.87.1 uses `uint*_t` without including in several headers. -// `CSS/common/transforms/vectors.h` uses bare `size_t` and only gets it -// from , which it includes *only when NDEBUG is undefined*. A -// Release build defines NDEBUG, so that header lost `size_t` and the build -// failed with "'size_t' has not been declared" in a third-party file. -// -// Both are declared here instead of patching the packages. It is one header so -// the compiler is given a single `-include` argument: CMake de-duplicates -// repeated options, and a second `-include
` pair collapses. -#include -#include diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/test/gpui_js_engine_test.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/test/gpui_js_engine_test.cpp deleted file mode 100644 index ecf9e76269..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/test/gpui_js_engine_test.cpp +++ /dev/null @@ -1,143 +0,0 @@ -// Unit test for the JS engine registry and its selection rules -//. -// -// The registry is process-global and registration is startup-only, so the cases -// run in the order the rules apply: no engine, one engine, several engines with -// and without an explicit selection, and an unknown name. -#include "GpuiJsEngine.h" - -#include -#include -#include - -namespace { - -int failures = 0; - -void check(bool condition, const std::string& what) { - if (!condition) { - ++failures; - std::fprintf(stderr, "FAIL: %s\n", what.c_str()); - } -} - -// Runs `body` and reports whether it threw a std::exception whose message -// contains `expected`. -template -void checkThrows( - Body body, - const std::string& expected, - const std::string& what) { - try { - body(); - } catch (const std::exception& error) { - if (std::string(error.what()).find(expected) == std::string::npos) { - ++failures; - std::fprintf( - stderr, - "FAIL: %s (message %s does not contain %s)\n", - what.c_str(), - error.what(), - expected.c_str()); - } - return; - } catch (...) { - ++failures; - std::fprintf(stderr, "FAIL: %s (threw the wrong type)\n", what.c_str()); - return; - } - ++failures; - std::fprintf(stderr, "FAIL: %s (did not throw)\n", what.c_str()); -} - -rngpui::GpuiJsEngine makeEngine(const std::string& name) { - return rngpui::GpuiJsEngine{ - .info = {.name = name, .version = "1.2.3"}, - .makeRuntimeFactory = [] { return nullptr; }, - }; -} - -} // namespace - -int main() { - using rngpui::activeJsEngine; - using rngpui::registeredJsEngines; - using rngpui::registerJsEngine; - using rngpui::selectJsEngine; - - // No engine installed. - check(registeredJsEngines().empty(), "no engines are registered yet"); - checkThrows( - [] { activeJsEngine(); }, - "no JS engine installed", - "activeJsEngine with no engine"); - - // One engine: it is the default. - registerJsEngine(makeEngine("alpha")); - check(registeredJsEngines().size() == 1, "one engine registered"); - check( - activeJsEngine().info.name == "alpha", "the only engine is the default"); - check(activeJsEngine().info.version == "1.2.3", "the version is reported"); - - // Several engines: ambiguous until one is selected. - registerJsEngine(makeEngine("beta")); - check(registeredJsEngines().size() == 2, "two engines registered"); - checkThrows( - [] { activeJsEngine(); }, - "several JS engines are installed", - "activeJsEngine with two engines and no selection"); - checkThrows( - [] { activeJsEngine(); }, - "alpha, beta", - "the ambiguity message lists the registered engines"); - - // Several engines with a selection. - selectJsEngine("beta"); - check(activeJsEngine().info.name == "beta", "the selection wins"); - selectJsEngine("alpha"); - check(activeJsEngine().info.name == "alpha", "the selection can change"); - selectJsEngine(""); - checkThrows( - [] { activeJsEngine(); }, - "several JS engines", - "an empty selection returns to the ambiguous default"); - - // Unknown name. - checkThrows( - [] { selectJsEngine("gamma"); }, - "unknown JS engine 'gamma'", - "selectJsEngine with an unknown name"); - checkThrows( - [] { selectJsEngine("gamma"); }, - "alpha, beta", - "the unknown-name message lists the registered engines"); - - // Registration is validated. - checkThrows( - [] { registerJsEngine(makeEngine("")); }, - "must report a name", - "registerJsEngine with an empty name"); - checkThrows( - [] { registerJsEngine(makeEngine("alpha")); }, - "duplicate JS engine 'alpha'", - "registerJsEngine with a duplicate name"); - checkThrows( - [] { - registerJsEngine(rngpui::GpuiJsEngine{ - .info = {.name = "gamma", .version = "1"}, - }); - }, - "no runtime factory", - "registerJsEngine without a runtime factory"); - - // A failed registration must not have been recorded. - selectJsEngine("alpha"); - check(activeJsEngine().info.name == "alpha", "the registry is unchanged"); - - if (failures == 0) { - std::printf("gpui_js_engine_test: all checks passed\n"); - return 0; - } - std::fprintf(stderr, "gpui_js_engine_test: %d check(s) failed\n", failures); - return 1; -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/test/gpui_turbo_module_test.cpp b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/test/gpui_turbo_module_test.cpp deleted file mode 100644 index c542a8507c..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/test/gpui_turbo_module_test.cpp +++ /dev/null @@ -1,117 +0,0 @@ -// Unit test for the module task queue: ordering, that work leaves the caller's -// thread, and that destruction never hangs. -#include "GpuiTurboModule.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/// Stands in for the Rust side of `rngpui::dispatchMain`, which this test does -/// not link. -namespace rngpui { -void rn_gpui_run_on_main(uint64_t) noexcept {} -} // namespace rngpui - -namespace { - -int failures = 0; - -void check(bool condition, const std::string& what) { - if (!condition) { - ++failures; - std::fprintf(stderr, "FAIL: %s\n", what.c_str()); - } -} - -void checkRunsInOrderOnOneThread() { - rngpui::ModuleQueue queue("rn.module.Test"); - const auto caller = std::this_thread::get_id(); - std::mutex mutex; - std::condition_variable done; - std::vector order; - std::vector threads; - for (int index = 0; index < 8; ++index) { - queue.post([&, index] { - std::lock_guard lock(mutex); - order.push_back(index); - threads.push_back(std::this_thread::get_id()); - if (order.size() == 8) { - done.notify_one(); - } - }); - } - { - std::unique_lock lock(mutex); - done.wait_for( - lock, std::chrono::seconds(10), [&] { return order.size() == 8; }); - } - check(order.size() == 8, "every posted task ran"); - for (size_t index = 0; index < order.size(); ++index) { - check( - order[index] == static_cast(index), - "tasks run in the order they were posted"); - } - check( - !threads.empty() && threads.front() != caller, - "the worker is not the posting thread"); - for (const auto thread : threads) { - check(thread == threads.front(), "all tasks run on one worker thread"); - } -} - -void checkDestructionDiscardsPendingTasks() { - std::atomic finished{0}; - { - rngpui::ModuleQueue queue("rn.module.Test"); - queue.post([&] { - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - finished.fetch_add(1); - }); - for (int index = 0; index < 32; ++index) { - queue.post([&] { finished.fetch_add(1); }); - } - } - check( - finished.load() <= 1, - "tasks still pending when the queue is destroyed are discarded"); -} - -void checkDestructionFromWorkerDoesNotDeadlock() { - // The task deletes the queue, so the destructor runs on the worker thread. - auto* queue = new rngpui::ModuleQueue("rn.module.Test"); - std::mutex mutex; - std::condition_variable destroyed; - bool destroyedFlag = false; - queue->post([queue, &mutex, &destroyed, &destroyedFlag] { - delete queue; - { - std::lock_guard lock(mutex); - destroyedFlag = true; - } - destroyed.notify_one(); - }); - std::unique_lock lock(mutex); - const auto destroyedInTime = destroyed.wait_for( - lock, std::chrono::seconds(10), [&] { return destroyedFlag; }); - check(destroyedInTime, "destroying the queue from its worker does not hang"); -} - -} // namespace - -int main() { - checkRunsInOrderOnOneThread(); - checkDestructionDiscardsPendingTasks(); - checkDestructionFromWorkerDoesNotDeadlock(); - if (failures != 0) { - std::fprintf(stderr, "%d check(s) failed\n", failures); - return 1; - } - std::printf("gpui_turbo_module_test: all checks passed\n"); - return 0; -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/ascii_number.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/ascii_number.h deleted file mode 100644 index e814f12f13..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/ascii_number.h +++ /dev/null @@ -1,903 +0,0 @@ -#ifndef FASTFLOAT_ASCII_NUMBER_H -#define FASTFLOAT_ASCII_NUMBER_H - -#include -#include -#include -#include -#include -#include - -#include "float_common.h" - -#ifdef FASTFLOAT_SSE2 -#include -#endif - -#ifdef FASTFLOAT_NEON -#include -#endif - -namespace fast_float { - -template fastfloat_really_inline constexpr bool has_simd_opt() { -#ifdef FASTFLOAT_HAS_SIMD - return std::is_same::value; -#else - return false; -#endif -} - -// Next function can be micro-optimized, but compilers are entirely -// able to optimize it well. -template -fastfloat_really_inline constexpr bool is_integer(UC c) noexcept { - return static_cast(c - UC('0')) <= 9u; -} - -fastfloat_really_inline constexpr uint64_t byteswap(uint64_t val) { - return (val & 0xFF00000000000000) >> 56 | (val & 0x00FF000000000000) >> 40 | - (val & 0x0000FF0000000000) >> 24 | (val & 0x000000FF00000000) >> 8 | - (val & 0x00000000FF000000) << 8 | (val & 0x0000000000FF0000) << 24 | - (val & 0x000000000000FF00) << 40 | (val & 0x00000000000000FF) << 56; -} - -fastfloat_really_inline constexpr uint32_t byteswap_32(uint32_t val) { - return (val >> 24) | ((val >> 8) & 0x0000FF00u) | ((val << 8) & 0x00FF0000u) | - (val << 24); -} - -// Read 8 UC into a u64. Truncates UC if not char. -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t -read8_to_u64(UC const *chars) { - if (cpp20_and_in_constexpr() || !std::is_same::value) { - uint64_t val = 0; - for (int i = 0; i < 8; ++i) { - val |= uint64_t(uint8_t(*chars)) << (i * 8); - ++chars; - } - return val; - } - uint64_t val; - ::memcpy(&val, chars, sizeof(uint64_t)); -#if FASTFLOAT_IS_BIG_ENDIAN == 1 - // Need to read as-if the number was in little-endian order. - val = byteswap(val); -#endif - return val; -} - -// Read 4 UC into a u32. Truncates UC if not char. -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint32_t -read4_to_u32(UC const *chars) { - if (cpp20_and_in_constexpr() || !std::is_same::value) { - uint32_t val = 0; - for (int i = 0; i < 4; ++i) { - val |= uint32_t(uint8_t(*chars)) << (i * 8); - ++chars; - } - return val; - } - uint32_t val; - ::memcpy(&val, chars, sizeof(uint32_t)); -#if FASTFLOAT_IS_BIG_ENDIAN == 1 - val = byteswap_32(val); -#endif - return val; -} -#ifdef FASTFLOAT_SSE2 - -fastfloat_really_inline uint64_t simd_read8_to_u64(__m128i const data) { - FASTFLOAT_SIMD_DISABLE_WARNINGS - __m128i const packed = _mm_packus_epi16(data, data); -#ifdef FASTFLOAT_64BIT - return uint64_t(_mm_cvtsi128_si64(packed)); -#else - uint64_t value; - // Visual Studio + older versions of GCC don't support _mm_storeu_si64 - _mm_storel_epi64(reinterpret_cast<__m128i *>(&value), packed); - return value; -#endif - FASTFLOAT_SIMD_RESTORE_WARNINGS -} - -fastfloat_really_inline uint64_t simd_read8_to_u64(char16_t const *chars) { - FASTFLOAT_SIMD_DISABLE_WARNINGS - return simd_read8_to_u64( - _mm_loadu_si128(reinterpret_cast<__m128i const *>(chars))); - FASTFLOAT_SIMD_RESTORE_WARNINGS -} - -#elif defined(FASTFLOAT_NEON) - -fastfloat_really_inline uint64_t simd_read8_to_u64(uint16x8_t const data) { - FASTFLOAT_SIMD_DISABLE_WARNINGS - uint8x8_t utf8_packed = vmovn_u16(data); - return vget_lane_u64(vreinterpret_u64_u8(utf8_packed), 0); - FASTFLOAT_SIMD_RESTORE_WARNINGS -} - -fastfloat_really_inline uint64_t simd_read8_to_u64(char16_t const *chars) { - FASTFLOAT_SIMD_DISABLE_WARNINGS - return simd_read8_to_u64( - vld1q_u16(reinterpret_cast(chars))); - FASTFLOAT_SIMD_RESTORE_WARNINGS -} - -#endif // FASTFLOAT_SSE2 - -// MSVC SFINAE is broken pre-VS2017 -#if defined(_MSC_VER) && _MSC_VER <= 1900 -template -#else -template ()) = 0> -#endif -// dummy for compile -uint64_t simd_read8_to_u64(UC const *) { - return 0; -} - -// credit @aqrit -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 uint32_t -parse_eight_digits_unrolled(uint64_t val) { - uint64_t const mask = 0x000000FF000000FF; - uint64_t const mul1 = 0x000F424000000064; // 100 + (1000000ULL << 32) - uint64_t const mul2 = 0x0000271000000001; // 1 + (10000ULL << 32) - val -= 0x3030303030303030; - val = (val * 10) + (val >> 8); // val = (val * 2561) >> 8; - val = (((val & mask) * mul1) + (((val >> 16) & mask) * mul2)) >> 32; - return uint32_t(val); -} - -// Call this if chars are definitely 8 digits. -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint32_t -parse_eight_digits_unrolled(UC const *chars) noexcept { - if (cpp20_and_in_constexpr() || !has_simd_opt()) { - return parse_eight_digits_unrolled(read8_to_u64(chars)); // truncation okay - } - return parse_eight_digits_unrolled(simd_read8_to_u64(chars)); -} - -// credit @aqrit -fastfloat_really_inline constexpr bool -is_made_of_eight_digits_fast(uint64_t val) noexcept { - return !((((val + 0x4646464646464646) | (val - 0x3030303030303030)) & - 0x8080808080808080)); -} - -fastfloat_really_inline constexpr bool -is_made_of_four_digits_fast(uint32_t val) noexcept { - return !((((val + 0x46464646) | (val - 0x30303030)) & 0x80808080)); -} - -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 uint32_t -parse_four_digits_unrolled(uint32_t val) noexcept { - val -= 0x30303030; - val = (val * 10) + (val >> 8); - return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; -} - -#ifdef FASTFLOAT_HAS_SIMD - -// Call this if chars might not be 8 digits. -// Using this style (instead of is_made_of_eight_digits_fast() then -// parse_eight_digits_unrolled()) ensures we don't load SIMD registers twice. -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool -simd_parse_if_eight_digits_unrolled(char16_t const *chars, - uint64_t &i) noexcept { - if (cpp20_and_in_constexpr()) { - return false; - } -#ifdef FASTFLOAT_SSE2 - FASTFLOAT_SIMD_DISABLE_WARNINGS - __m128i const data = - _mm_loadu_si128(reinterpret_cast<__m128i const *>(chars)); - - // (x - '0') <= 9 - // http://0x80.pl/articles/simd-parsing-int-sequences.html - __m128i const t0 = _mm_add_epi16(data, _mm_set1_epi16(32720)); - __m128i const t1 = _mm_cmpgt_epi16(t0, _mm_set1_epi16(-32759)); - - if (_mm_movemask_epi8(t1) == 0) { - i = i * 100000000 + parse_eight_digits_unrolled(simd_read8_to_u64(data)); - return true; - } else - return false; - FASTFLOAT_SIMD_RESTORE_WARNINGS -#elif defined(FASTFLOAT_NEON) - FASTFLOAT_SIMD_DISABLE_WARNINGS - uint16x8_t const data = vld1q_u16(reinterpret_cast(chars)); - - // (x - '0') <= 9 - // http://0x80.pl/articles/simd-parsing-int-sequences.html - uint16x8_t const t0 = vsubq_u16(data, vmovq_n_u16('0')); - uint16x8_t const mask = vcltq_u16(t0, vmovq_n_u16('9' - '0' + 1)); - - if (vminvq_u16(mask) == 0xFFFF) { - i = i * 100000000 + parse_eight_digits_unrolled(simd_read8_to_u64(data)); - return true; - } else - return false; - FASTFLOAT_SIMD_RESTORE_WARNINGS -#else - static_cast(chars); - static_cast(i); - return false; -#endif // FASTFLOAT_SSE2 -} - -#endif // FASTFLOAT_HAS_SIMD - -// MSVC SFINAE is broken pre-VS2017 -#if defined(_MSC_VER) && _MSC_VER <= 1900 -template -#else -template ()) = 0> -#endif -// dummy for compile -bool simd_parse_if_eight_digits_unrolled(UC const *, uint64_t &) { - return 0; -} - -template ::value) = 0> -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void -loop_parse_if_eight_digits(UC const *&p, UC const *const pend, uint64_t &i) { - if (!has_simd_opt()) { - return; - } - while ((std::distance(p, pend) >= 8) && - simd_parse_if_eight_digits_unrolled( - p, i)) { // in rare cases, this will overflow, but that's ok - p += 8; - } -} - -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void -loop_parse_if_eight_digits(char const *&p, char const *const pend, - uint64_t &i) { - // optimizes better than parse_if_eight_digits_unrolled() for UC = char. - while ((std::distance(p, pend) >= 8) && - is_made_of_eight_digits_fast(read8_to_u64(p))) { - i = i * 100000000 + - parse_eight_digits_unrolled(read8_to_u64( - p)); // in rare cases, this will overflow, but that's ok - p += 8; - } - // Consume a remaining 4-7 digit run in a single SWAR step instead of - // byte-by-byte (reuses the existing 4-digit helpers). The parsed result is - // identical either way. Historically gated to clang because gcc regressed on - // short remainders, but that verdict predates the span-elision restructure; - // with the leaner hot path the 4-digit step now wins on gcc as well. - if ((pend - p) >= 4) { - uint32_t const val4 = read4_to_u32(p); - if (is_made_of_four_digits_fast(val4)) { - i = i * 10000 + - parse_four_digits_unrolled(val4); // may overflow, that's ok - p += 4; - } - } -} - -enum class parse_error { - no_error, - // [JSON-only] The minus sign must be followed by an integer. - missing_integer_after_sign, - // A sign must be followed by an integer or dot. - missing_integer_or_dot_after_sign, - // [JSON/JavaScript-only] The integer part must not have leading zeros. - leading_zeros_in_integer_part, - // [JSON-only] The integer part must have at least one digit. - no_digits_in_integer_part, - // [JSON-only] If there is a decimal point, there must be digits in the - // fractional part. - no_digits_in_fractional_part, - // The mantissa must have at least one digit. - no_digits_in_mantissa, - // Scientific notation requires an exponential part. - missing_exponential_part, - // [JavaScript-only, sloppy mode] The integer part is a legacy octal literal - // (a leading zero followed by octal digits only), which is not a decimal - // number. Parse it in base 8 instead. - legacy_octal_integer_part, -}; - -template struct parsed_number_string_t { - int64_t exponent{0}; - uint64_t mantissa{0}; - UC const *lastmatch{nullptr}; - bool negative{false}; - bool valid{false}; - bool too_many_digits{false}; - // contains the range of the significant digits - span integer{}; // non-nullable - span fraction{}; // nullable - parse_error error{parse_error::no_error}; -}; - -using byte_span = span; -using parsed_number_string = parsed_number_string_t; - -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 parsed_number_string_t -report_parse_error(UC const *p, parse_error error) { - parsed_number_string_t answer; - answer.valid = false; - answer.lastmatch = p; - answer.error = error; - return answer; -} - -// Assuming that you use no more than 19 digits, this will -// parse an ASCII string. -// -// store_spans is a *runtime* flag (not a template parameter, deliberately: a -// template would create a second instantiation of this whole function and the -// extra icache pressure wipes out the gain). When false, the integer/fraction -// spans (read only by the rare digit_comp slow path) are not materialized, -// which keeps the fat parsed_number_string_t off the hot path. The caller -// re-parses with store_spans=true if the slow path is actually reached. -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 parsed_number_string_t -parse_number_string_impl(UC const *p, UC const *pend, - parse_options_t options, - bool store_spans) noexcept { - chars_format const fmt = detail::adjust_for_feature_macros(options.format); - UC const decimal_point = options.decimal_point; - - parsed_number_string_t answer; - answer.valid = false; - answer.too_many_digits = false; - // assume p < pend, so dereference without checks; - answer.negative = (*p == UC('-')); - // C++17 20.19.3.(7.1) explicitly forbids '+' sign here - if ((*p == UC('-')) || (uint64_t(fmt & chars_format::allow_leading_plus) && - !basic_json_fmt && *p == UC('+'))) { - ++p; - if (p == pend) { - return report_parse_error( - p, parse_error::missing_integer_or_dot_after_sign); - } - FASTFLOAT_IF_CONSTEXPR17(basic_json_fmt) { - if (!is_integer(*p)) { // a sign must be followed by an integer - return report_parse_error(p, - parse_error::missing_integer_after_sign); - } - } - else { - if (!is_integer(*p) && - (*p != - decimal_point)) { // a sign must be followed by an integer or the dot - return report_parse_error( - p, parse_error::missing_integer_or_dot_after_sign); - } - } - } - UC const *const start_digits = p; - - uint64_t i = 0; // an unsigned int avoids signed overflows (which are bad) - - // Straight-line unroll of the integer-part scan: most integer parts are - // 1-5 digits, so peeling the first iterations eliminates the loop back-edge - // for the common case. Semantics are identical to the original `while` loop: - // i = 10*i + digit, advancing p. - if ((p != pend) && is_integer(*p)) { - i = uint64_t(*p - UC('0')); - ++p; - if ((p != pend) && is_integer(*p)) { - i = 10 * i + uint64_t(*p - UC('0')); - ++p; - if ((p != pend) && is_integer(*p)) { - i = 10 * i + uint64_t(*p - UC('0')); - ++p; - if ((p != pend) && is_integer(*p)) { - i = 10 * i + uint64_t(*p - UC('0')); - ++p; - if ((p != pend) && is_integer(*p)) { - i = 10 * i + uint64_t(*p - UC('0')); - ++p; - while ((p != pend) && is_integer(*p)) { - // a multiplication by 10 is cheaper than an arbitrary integer - // multiplication - i = 10 * i + - uint64_t(*p - UC('0')); // might overflow, handled later - ++p; - } - } - } - } - } - } - UC const *const end_of_integer_part = p; - int64_t digit_count = int64_t(end_of_integer_part - start_digits); - if (store_spans) { - answer.integer = span(start_digits, size_t(digit_count)); - } - FASTFLOAT_IF_CONSTEXPR17(basic_json_fmt) { - // at least 1 digit in integer part, without leading zeros - if (digit_count == 0) { - return report_parse_error(p, parse_error::no_digits_in_integer_part); - } - if ((start_digits[0] == UC('0') && digit_count > 1)) { - return report_parse_error(start_digits, - parse_error::leading_zeros_in_integer_part); - } - } - else FASTFLOAT_IF_CONSTEXPR17(basic_javascript_fmt) { - // ECMAScript DecimalIntegerLiteral is "0" or a non-zero digit followed by - // digits: no leading zeros. Unlike JSON, the integer part may be empty - // (".5"); the no_digits_in_mantissa check below still rejects ".". - if ((digit_count > 1) && (start_digits[0] == UC('0'))) { - if (!uint64_t(fmt & detail::basic_javascript_sloppy_fmt)) { - return report_parse_error( - start_digits, parse_error::leading_zeros_in_integer_part); - } - // Sloppy mode (Annex B): a NonOctalDecimalIntegerLiteral has a leading - // zero and at least one digit that is 8 or 9 ("08.5" is 8.5). With - // octal digits only, it is a LegacyOctalIntegerLiteral ("0775"), which - // is not a decimal number: report it so the caller can parse it in - // base 8. - bool has_non_octal_digit = false; - for (UC const *q = start_digits; q != end_of_integer_part; ++q) { - has_non_octal_digit |= (*q >= UC('8')); - } - if (!has_non_octal_digit) { - return report_parse_error(start_digits, - parse_error::legacy_octal_integer_part); - } - } - } - - int64_t exponent = 0; - bool const has_decimal_point = (p != pend) && (*p == decimal_point); - if (has_decimal_point) { - ++p; - UC const *before = p; - // can occur at most twice without overflowing, but let it occur more, since - // for integers with many digits, digit parsing is the primary bottleneck. - loop_parse_if_eight_digits(p, pend, i); - - while ((p != pend) && is_integer(*p)) { - uint8_t digit = uint8_t(*p - UC('0')); - ++p; - i = i * 10 + digit; // in rare cases, this will overflow, but that's ok - } - exponent = before - p; - if (store_spans) { - answer.fraction = span(before, size_t(p - before)); - } - digit_count -= exponent; - } - FASTFLOAT_IF_CONSTEXPR17(basic_json_fmt) { - // at least 1 digit in fractional part - if (has_decimal_point && exponent == 0) { - return report_parse_error(p, - parse_error::no_digits_in_fractional_part); - } - } - else if (digit_count == 0) { // we must have encountered at least one integer! - return report_parse_error(p, parse_error::no_digits_in_mantissa); - } - int64_t exp_number = 0; // explicit exponential part - if ((uint64_t(fmt & chars_format::scientific) && (p != pend) && - ((UC('e') == *p) || (UC('E') == *p))) || - (uint64_t(fmt & detail::basic_fortran_fmt) && (p != pend) && - ((UC('+') == *p) || (UC('-') == *p) || (UC('d') == *p) || - (UC('D') == *p)))) { - UC const *location_of_e = p; - if ((UC('e') == *p) || (UC('E') == *p) || (UC('d') == *p) || - (UC('D') == *p)) { - ++p; - } - bool neg_exp = false; - if ((p != pend) && (UC('-') == *p)) { - neg_exp = true; - ++p; - } else if ((p != pend) && - (UC('+') == - *p)) { // '+' on exponent is allowed by C++17 20.19.3.(7.1) - ++p; - } - if ((p == pend) || !is_integer(*p)) { - if (!uint64_t(fmt & chars_format::fixed)) { - // The exponential part is invalid for scientific notation, so it must - // be a trailing token for fixed notation. However, fixed notation is - // disabled, so report a scientific notation error. - return report_parse_error(p, parse_error::missing_exponential_part); - } - // Otherwise, we will be ignoring the 'e'. - p = location_of_e; - } else { - while ((p != pend) && is_integer(*p)) { - uint8_t digit = uint8_t(*p - UC('0')); - if (exp_number < 0x10000000) { - exp_number = 10 * exp_number + digit; - } - ++p; - } - if (neg_exp) { - exp_number = -exp_number; - } - exponent += exp_number; - } - } else { - // If it scientific and not fixed, we have to bail out. - if (uint64_t(fmt & chars_format::scientific) && - !uint64_t(fmt & chars_format::fixed)) { - return report_parse_error(p, parse_error::missing_exponential_part); - } - } - answer.lastmatch = p; - answer.valid = true; - - // If we frequently had to deal with long strings of digits, - // we could extend our code by using a 128-bit integer instead - // of a 64-bit integer. However, this is uncommon. - // - // We can deal with up to 19 digits. - if (digit_count > 19) { // this is uncommon - // It is possible that the integer had an overflow. - // We have to handle the case where we have 0.0000somenumber. - // We need to be mindful of the case where we only have zeroes... - // E.g., 0.000000000...000. - UC const *start = start_digits; - while ((start != pend) && (*start == UC('0') || *start == decimal_point)) { - if (*start == UC('0')) { - digit_count--; - } - start++; - } - - if (digit_count > 19) { - answer.too_many_digits = true; - // The truncation recompute below reads the integer/fraction spans. When - // store_spans is false we didn't materialize them, so just flag - // too_many_digits; the caller re-parses with store_spans=true to obtain - // the corrected mantissa/exponent before taking the slow path. - if (store_spans) { - // Let us start again, this time, avoiding overflows. - // We don't need to call if is_integer, since we use the - // pre-tokenized spans from above. - i = 0; - p = answer.integer.ptr; - UC const *int_end = p + answer.integer.len(); - uint64_t const minimal_nineteen_digit_integer{1000000000000000000}; - while ((i < minimal_nineteen_digit_integer) && (p != int_end)) { - i = i * 10 + uint64_t(*p - UC('0')); - ++p; - } - if (i >= minimal_nineteen_digit_integer) { // We have a big integer - exponent = end_of_integer_part - p + exp_number; - } else { // We have a value with a fractional component. - p = answer.fraction.ptr; - UC const *frac_end = p + answer.fraction.len(); - while ((i < minimal_nineteen_digit_integer) && (p != frac_end)) { - i = i * 10 + uint64_t(*p - UC('0')); - ++p; - } - exponent = answer.fraction.ptr - p + exp_number; - } - // We have now corrected both exponent and i, to a truncated value - } - } - } - answer.exponent = exponent; - answer.mantissa = i; - return answer; -} - -// Cold instantiation of the parser: the ECMAScript integer-part rule costs two -// error returns plus the Annex B octal scan, and parse_number_string_impl is -// force-inlined, so an inlined javascript body would enlarge the frame of every -// caller that never asks for it. Out of line, it costs those callers nothing. -template -fastfloat_never_inline FASTFLOAT_CONSTEXPR20 parsed_number_string_t -parse_number_string_javascript(UC const *p, UC const *pend, - parse_options_t options, - bool store_spans) noexcept { - return parse_number_string_impl(p, pend, options, - store_spans); -} - -// Public entry point, behaviour unchanged: chars_format::javascript is still -// honoured, it is just selected here once instead of being re-tested inside the -// parser loop. Callers that have already ruled the format out (see -// from_chars_float_advanced) should call parse_number_string_impl directly so -// that not even this test reaches their hot path. -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 parsed_number_string_t -parse_number_string(UC const *p, UC const *pend, parse_options_t options, - bool store_spans = true) noexcept { - // JSON and JavaScript are mutually exclusive, so only the non-JSON - // instantiation has to look at the flag. - FASTFLOAT_IF_CONSTEXPR17(!basic_json_fmt) { - if fastfloat_unlikely (uint64_t(options.format & - detail::basic_javascript_fmt)) { - return parse_number_string_javascript(p, pend, options, store_spans); - } - } - return parse_number_string_impl(p, pend, options, - store_spans); -} - -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t -parse_int_string(UC const *p, UC const *pend, T &value, - parse_options_t options) { - chars_format const fmt = detail::adjust_for_feature_macros(options.format); - int const base = options.base; - - from_chars_result_t answer; - - UC const *const first = p; - - bool const negative = (*p == UC('-')); -#ifdef FASTFLOAT_VISUAL_STUDIO -#pragma warning(push) -#pragma warning(disable : 4127) -#endif - if (!std::is_signed::value && negative) { -#ifdef FASTFLOAT_VISUAL_STUDIO -#pragma warning(pop) -#endif - answer.ec = std::errc::invalid_argument; - answer.ptr = first; - return answer; - } - if ((*p == UC('-')) || - (uint64_t(fmt & chars_format::allow_leading_plus) && (*p == UC('+')))) { - ++p; - } - - UC const *const start_num = p; - - while (p != pend && *p == UC('0')) { - ++p; - } - - bool const has_leading_zeros = p > start_num; - - UC const *const start_digits = p; - - FASTFLOAT_IF_CONSTEXPR17( - (std::is_same::value && sizeof(UC) == 1)) { - if (base == 10) { - const size_t len = static_cast(pend - p); - if (len == 0) { - if (has_leading_zeros) { - value = 0; - answer.ec = std::errc(); - answer.ptr = p; - } else { - answer.ec = std::errc::invalid_argument; - answer.ptr = first; - } - return answer; - } - - uint32_t digits; - -#if FASTFLOAT_HAS_IS_CONSTANT_EVALUATED && FASTFLOAT_HAS_BIT_CAST - if (std::is_constant_evaluated()) { - uint8_t str[4]{}; - for (size_t j = 0; j < 4 && j < len; ++j) { - str[j] = static_cast(p[j]); - } - digits = std::bit_cast(str); -#if FASTFLOAT_IS_BIG_ENDIAN - digits = byteswap_32(digits); -#endif - } -#else - if (false) { - } -#endif - else if (len >= 4) { - ::memcpy(&digits, p, 4); -#if FASTFLOAT_IS_BIG_ENDIAN - digits = byteswap_32(digits); -#endif - } else { - uint32_t b0 = static_cast(p[0]); - uint32_t b1 = (len > 1) ? static_cast(p[1]) : 0xFFu; - uint32_t b2 = (len > 2) ? static_cast(p[2]) : 0xFFu; - uint32_t b3 = 0xFFu; - digits = b0 | (b1 << 8) | (b2 << 16) | (b3 << 24); - } - - uint32_t magic = - ((digits + 0x46464646u) | (digits - 0x30303030u)) & 0x80808080u; - uint32_t tz = - static_cast(countr_zero_32(magic)); // 7, 15, 23, 31, or 32 - uint32_t nd = (tz == 32) ? 4 : (tz >> 3); - nd = static_cast(nd < len ? nd : len); - if (nd == 0) { - if (has_leading_zeros) { - value = 0; - answer.ec = std::errc(); - answer.ptr = p; - return answer; - } - answer.ec = std::errc::invalid_argument; - answer.ptr = first; - return answer; - } - if (nd > 3) { - const UC *q = p + nd; - size_t rem = len - nd; - while (rem) { - if (*q < UC('0') || *q > UC('9')) - break; - ++q; - --rem; - } - answer.ec = std::errc::result_out_of_range; - answer.ptr = q; - return answer; - } - - digits ^= 0x30303030u; - digits <<= ((4 - nd) * 8); - - uint32_t check = ((digits >> 24) & 0xff) | ((digits >> 8) & 0xff00) | - ((digits << 8) & 0xff0000); - if (check > 0x00020505) { - answer.ec = std::errc::result_out_of_range; - answer.ptr = p + nd; - return answer; - } - value = static_cast((0x640a01 * digits) >> 24); - answer.ec = std::errc(); - answer.ptr = p + nd; - return answer; - } - } - - FASTFLOAT_IF_CONSTEXPR17( - (std::is_same::value && sizeof(UC) == 1)) { - if (base == 10) { - const size_t len = size_t(pend - p); - if (len == 0) { - if (has_leading_zeros) { - value = 0; - answer.ec = std::errc(); - answer.ptr = p; - } else { - answer.ec = std::errc::invalid_argument; - answer.ptr = first; - } - return answer; - } - - if (len >= 4) { - uint32_t digits = read4_to_u32(p); - if (is_made_of_four_digits_fast(digits)) { - uint32_t v = parse_four_digits_unrolled(digits); - if (len >= 5 && is_integer(p[4])) { - v = v * 10 + uint32_t(p[4] - '0'); - if (len >= 6 && is_integer(p[5])) { - answer.ec = std::errc::result_out_of_range; - const UC *q = p + 5; - while (q != pend && is_integer(*q)) { - q++; - } - answer.ptr = q; - return answer; - } - if (v > 65535) { - answer.ec = std::errc::result_out_of_range; - answer.ptr = p + 5; - return answer; - } - value = uint16_t(v); - answer.ec = std::errc(); - answer.ptr = p + 5; - return answer; - } - // 4 digits - value = uint16_t(v); - answer.ec = std::errc(); - answer.ptr = p + 4; - return answer; - } - } - } - } - - uint64_t i = 0; - if (base == 10) { - loop_parse_if_eight_digits(p, pend, i); // use SIMD if possible - } - while (p != pend) { - uint8_t digit = ch_to_digit(*p); - if (digit >= base) { - break; - } - i = uint64_t(base) * i + digit; // might overflow, check this later - p++; - } - - size_t digit_count = size_t(p - start_digits); - - if (digit_count == 0) { - if (has_leading_zeros) { - value = 0; - answer.ec = std::errc(); - answer.ptr = p; - } else { - answer.ec = std::errc::invalid_argument; - answer.ptr = first; - } - return answer; - } - - answer.ptr = p; - - // check u64 overflow - size_t max_digits = max_digits_u64(base); - if (digit_count > max_digits) { - answer.ec = std::errc::result_out_of_range; - return answer; - } - // this check can be eliminated for all other types, but they will all require - // a max_digits(base) equivalent - if (digit_count == max_digits) { - // At the max_digits boundary the accumulator `i` may have wrapped around - // 2^64. A plain `i < min_safe_u64(base)` test is not sufficient: for any - // base whose max_digits-length range exceeds 2^64 (base 10 reaches - // ~5.4 * 2^64 at 20 digits) the value can wrap a whole multiple of 2^64 and - // land back above min_safe, slipping through. Decide exactly in O(1) using - // the leading digit, following the approach used in simdjson: - // ms == min_safe_u64(base) == base^(max_digits-1), the smallest - // max_digits-length value. - // dmax == the largest leading digit whose number can still fit in u64. - // The leading-digit band [d*ms, (d+1)*ms) has width ms < 2^64, so within - // the single band where d == dmax the value straddles 2^64 at most once, - // and a single threshold separates wrapped from non-wrapped values. A - // leading digit above dmax always overflows; below dmax always fits. - uint64_t const ms = min_safe_u64(base); - uint64_t const dmax = (std::numeric_limits::max)() / ms; - uint64_t const lead = ch_to_digit(*start_digits); - if (lead > dmax || (lead == dmax && i < dmax * ms)) { - answer.ec = std::errc::result_out_of_range; - return answer; - } - } - - // check other types overflow - if (!std::is_same::value) { - if (i > uint64_t((std::numeric_limits::max)()) + uint64_t(negative)) { - answer.ec = std::errc::result_out_of_range; - return answer; - } - } - - if (negative) { -#ifdef FASTFLOAT_VISUAL_STUDIO -#pragma warning(push) -#pragma warning(disable : 4146) -#endif - // this weird workaround is required because: - // - converting unsigned to signed when its value is greater than signed max - // is UB pre-C++23. - // - reinterpret_casting (~i + 1) would work, but it is not constexpr - // this is always optimized into a neg instruction (note: T is an integer - // type) - value = T(-(std::numeric_limits::max)() - - T(i - uint64_t((std::numeric_limits::max)()))); -#ifdef FASTFLOAT_VISUAL_STUDIO -#pragma warning(pop) -#endif - } else { - value = T(i); - } - - answer.ec = std::errc(); - return answer; -} - -} // namespace fast_float - -#endif diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/bigint.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/bigint.h deleted file mode 100644 index 665debb721..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/bigint.h +++ /dev/null @@ -1,638 +0,0 @@ -#ifndef FASTFLOAT_BIGINT_H -#define FASTFLOAT_BIGINT_H - -#include -#include -#include -#include - -#include "float_common.h" - -namespace fast_float { - -// the limb width: we want efficient multiplication of double the bits in -// limb, or for 64-bit limbs, at least 64-bit multiplication where we can -// extract the high and low parts efficiently. this is every 64-bit -// architecture except for sparc, which emulates 128-bit multiplication. -// we might have platforms where `CHAR_BIT` is not 8, so let's avoid -// doing `8 * sizeof(limb)`. -#if defined(FASTFLOAT_64BIT) && !defined(__sparc) -#define FASTFLOAT_64BIT_LIMB 1 -typedef uint64_t limb; -constexpr size_t limb_bits = 64; -#else -#define FASTFLOAT_32BIT_LIMB -typedef uint32_t limb; -constexpr size_t limb_bits = 32; -#endif - -typedef span limb_span; - -// number of bits in a bigint. this needs to be at least the number -// of bits required to store the largest bigint, which is -// `log2(10**(digits + max_exp))`, or `log2(10**(767 + 342))`, or -// ~3600 bits, so we round to 4000. -constexpr size_t bigint_bits = 4000; -constexpr size_t bigint_limbs = bigint_bits / limb_bits; - -// vector-like type that is allocated on the stack. the entire -// buffer is pre-allocated, and only the length changes. -template struct stackvec { - limb data[size]; - // we never need more than 150 limbs - uint16_t length{0}; - - stackvec() = default; - stackvec(stackvec const &) = delete; - stackvec &operator=(stackvec const &) = delete; - stackvec(stackvec &&) = delete; - stackvec &operator=(stackvec &&other) = delete; - - // create stack vector from existing limb span. - FASTFLOAT_CONSTEXPR20 stackvec(limb_span s) { - FASTFLOAT_ASSERT(try_extend(s)); - } - - FASTFLOAT_CONSTEXPR14 limb &operator[](size_t index) noexcept { - FASTFLOAT_DEBUG_ASSERT(index < length); - return data[index]; - } - - FASTFLOAT_CONSTEXPR14 const limb &operator[](size_t index) const noexcept { - FASTFLOAT_DEBUG_ASSERT(index < length); - return data[index]; - } - - // index from the end of the container - FASTFLOAT_CONSTEXPR14 const limb &rindex(size_t index) const noexcept { - FASTFLOAT_DEBUG_ASSERT(index < length); - size_t rindex = length - index - 1; - return data[rindex]; - } - - // set the length, without bounds checking. - FASTFLOAT_CONSTEXPR14 void set_len(size_t len) noexcept { - length = uint16_t(len); - } - - constexpr size_t len() const noexcept { return length; } - - constexpr bool is_empty() const noexcept { return length == 0; } - - constexpr size_t capacity() const noexcept { return size; } - - // append item to vector, without bounds checking - FASTFLOAT_CONSTEXPR14 void push_unchecked(limb value) noexcept { - data[length] = value; - length++; - } - - // append item to vector, returning if item was added - FASTFLOAT_CONSTEXPR14 bool try_push(limb value) noexcept { - if (len() < capacity()) { - push_unchecked(value); - return true; - } else { - return false; - } - } - - // add items to the vector, from a span, without bounds checking - FASTFLOAT_CONSTEXPR20 void extend_unchecked(limb_span s) noexcept { - limb *ptr = data + length; - std::copy_n(s.ptr, s.len(), ptr); - set_len(len() + s.len()); - } - - // try to add items to the vector, returning if items were added - FASTFLOAT_CONSTEXPR20 bool try_extend(limb_span s) noexcept { - if (len() + s.len() <= capacity()) { - extend_unchecked(s); - return true; - } else { - return false; - } - } - - // resize the vector, without bounds checking - // if the new size is longer than the vector, assign value to each - // appended item. - FASTFLOAT_CONSTEXPR20 - void resize_unchecked(size_t new_len, limb value) noexcept { - if (new_len > len()) { - size_t count = new_len - len(); - limb *first = data + len(); - limb *last = first + count; - ::std::fill(first, last, value); - set_len(new_len); - } else { - set_len(new_len); - } - } - - // try to resize the vector, returning if the vector was resized. - FASTFLOAT_CONSTEXPR20 bool try_resize(size_t new_len, limb value) noexcept { - if (new_len > capacity()) { - return false; - } else { - resize_unchecked(new_len, value); - return true; - } - } - - // check if any limbs are non-zero after the given index. - // this needs to be done in reverse order, since the index - // is relative to the most significant limbs. - FASTFLOAT_CONSTEXPR14 bool nonzero(size_t index) const noexcept { - while (index < len()) { - if (rindex(index) != 0) { - return true; - } - index++; - } - return false; - } - - // normalize the big integer, so most-significant zero limbs are removed. - FASTFLOAT_CONSTEXPR14 void normalize() noexcept { - while (len() > 0 && rindex(0) == 0) { - length--; - } - } -}; - -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 uint64_t -empty_hi64(bool &truncated) noexcept { - truncated = false; - return 0; -} - -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t -uint64_hi64(uint64_t r0, bool &truncated) noexcept { - truncated = false; - int shl = leading_zeroes(r0); - return r0 << shl; -} - -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t -uint64_hi64(uint64_t r0, uint64_t r1, bool &truncated) noexcept { - int shl = leading_zeroes(r0); - if (shl == 0) { - truncated = r1 != 0; - return r0; - } else { - int shr = 64 - shl; - truncated = (r1 << shl) != 0; - return (r0 << shl) | (r1 >> shr); - } -} - -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t -uint32_hi64(uint32_t r0, bool &truncated) noexcept { - return uint64_hi64(r0, truncated); -} - -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t -uint32_hi64(uint32_t r0, uint32_t r1, bool &truncated) noexcept { - uint64_t x0 = r0; - uint64_t x1 = r1; - return uint64_hi64((x0 << 32) | x1, truncated); -} - -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t -uint32_hi64(uint32_t r0, uint32_t r1, uint32_t r2, bool &truncated) noexcept { - uint64_t x0 = r0; - uint64_t x1 = r1; - uint64_t x2 = r2; - return uint64_hi64(x0, (x1 << 32) | x2, truncated); -} - -// add two small integers, checking for overflow. -// we want an efficient operation. for msvc, where -// we don't have built-in intrinsics, this is still -// pretty fast. -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 limb -scalar_add(limb x, limb y, bool &overflow) noexcept { - limb z; -// gcc and clang -#if defined(__has_builtin) -#if __has_builtin(__builtin_add_overflow) - if (!cpp20_and_in_constexpr()) { - overflow = __builtin_add_overflow(x, y, &z); - return z; - } -#endif -#endif - - // generic, this still optimizes correctly on MSVC. - z = x + y; - overflow = z < x; - return z; -} - -// multiply two small integers, getting both the high and low bits. -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 limb -scalar_mul(limb x, limb y, limb &carry) noexcept { -#ifdef FASTFLOAT_64BIT_LIMB -#if defined(__SIZEOF_INT128__) - // GCC and clang both define it as an extension. - __uint128_t z = __uint128_t(x) * __uint128_t(y) + __uint128_t(carry); - carry = limb(z >> limb_bits); - return limb(z); -#else - // fallback, no native 128-bit integer multiplication with carry. - // on msvc, this optimizes identically, somehow. - value128 z = full_multiplication(x, y); - bool overflow; - z.low = scalar_add(z.low, carry, overflow); - z.high += uint64_t(overflow); // cannot overflow - carry = z.high; - return z.low; -#endif -#else - uint64_t z = uint64_t(x) * uint64_t(y) + uint64_t(carry); - carry = limb(z >> limb_bits); - return limb(z); -#endif -} - -// add scalar value to bigint starting from offset. -// used in grade school multiplication -template -inline FASTFLOAT_CONSTEXPR20 bool small_add_from(stackvec &vec, limb y, - size_t start) noexcept { - size_t index = start; - limb carry = y; - bool overflow; - while (carry != 0 && index < vec.len()) { - vec[index] = scalar_add(vec[index], carry, overflow); - carry = limb(overflow); - index += 1; - } - if (carry != 0) { - FASTFLOAT_TRY(vec.try_push(carry)); - } - return true; -} - -// add scalar value to bigint. -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool -small_add(stackvec &vec, limb y) noexcept { - return small_add_from(vec, y, 0); -} - -// multiply bigint by scalar value. -template -inline FASTFLOAT_CONSTEXPR20 bool small_mul(stackvec &vec, - limb y) noexcept { - limb carry = 0; - for (size_t index = 0; index < vec.len(); index++) { - vec[index] = scalar_mul(vec[index], y, carry); - } - if (carry != 0) { - FASTFLOAT_TRY(vec.try_push(carry)); - } - return true; -} - -// add bigint to bigint starting from index. -// used in grade school multiplication -template -FASTFLOAT_CONSTEXPR20 bool large_add_from(stackvec &x, limb_span y, - size_t start) noexcept { - // the effective x buffer is from `xstart..x.len()`, so exit early - // if we can't get that current range. - if (x.len() < start || y.len() > x.len() - start) { - FASTFLOAT_TRY(x.try_resize(y.len() + start, 0)); - } - - bool carry = false; - for (size_t index = 0; index < y.len(); index++) { - limb xi = x[index + start]; - limb yi = y[index]; - bool c1 = false; - bool c2 = false; - xi = scalar_add(xi, yi, c1); - if (carry) { - xi = scalar_add(xi, 1, c2); - } - x[index + start] = xi; - carry = c1 | c2; - } - - // handle overflow - if (carry) { - FASTFLOAT_TRY(small_add_from(x, 1, y.len() + start)); - } - return true; -} - -// add bigint to bigint. -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool -large_add_from(stackvec &x, limb_span y) noexcept { - return large_add_from(x, y, 0); -} - -// grade-school multiplication algorithm -template -FASTFLOAT_CONSTEXPR20 bool long_mul(stackvec &x, limb_span y) noexcept { - limb_span xs = limb_span(x.data, x.len()); - stackvec z(xs); - limb_span zs = limb_span(z.data, z.len()); - - if (y.len() != 0) { - limb y0 = y[0]; - FASTFLOAT_TRY(small_mul(x, y0)); - for (size_t index = 1; index < y.len(); index++) { - limb yi = y[index]; - stackvec zi; - if (yi != 0) { - // re-use the same buffer throughout - zi.set_len(0); - FASTFLOAT_TRY(zi.try_extend(zs)); - FASTFLOAT_TRY(small_mul(zi, yi)); - limb_span zis = limb_span(zi.data, zi.len()); - FASTFLOAT_TRY(large_add_from(x, zis, index)); - } - } - } - - x.normalize(); - return true; -} - -// grade-school multiplication algorithm -template -FASTFLOAT_CONSTEXPR20 bool large_mul(stackvec &x, limb_span y) noexcept { - if (y.len() == 1) { - FASTFLOAT_TRY(small_mul(x, y[0])); - } else { - FASTFLOAT_TRY(long_mul(x, y)); - } - return true; -} - -template struct pow5_tables { - static constexpr uint32_t large_step = 135; - static constexpr uint64_t small_power_of_5[] = { - 1UL, - 5UL, - 25UL, - 125UL, - 625UL, - 3125UL, - 15625UL, - 78125UL, - 390625UL, - 1953125UL, - 9765625UL, - 48828125UL, - 244140625UL, - 1220703125UL, - 6103515625UL, - 30517578125UL, - 152587890625UL, - 762939453125UL, - 3814697265625UL, - 19073486328125UL, - 95367431640625UL, - 476837158203125UL, - 2384185791015625UL, - 11920928955078125UL, - 59604644775390625UL, - 298023223876953125UL, - 1490116119384765625UL, - 7450580596923828125UL, - }; -#ifdef FASTFLOAT_64BIT_LIMB - constexpr static limb large_power_of_5[] = { - 1414648277510068013UL, 9180637584431281687UL, 4539964771860779200UL, - 10482974169319127550UL, 198276706040285095UL}; -#else - constexpr static limb large_power_of_5[] = { - 4279965485U, 329373468U, 4020270615U, 2137533757U, 4287402176U, - 1057042919U, 1071430142U, 2440757623U, 381945767U, 46164893U}; -#endif -}; - -#if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE - -template constexpr uint32_t pow5_tables::large_step; - -template constexpr uint64_t pow5_tables::small_power_of_5[]; - -template constexpr limb pow5_tables::large_power_of_5[]; - -#endif - -// big integer type. implements a small subset of big integer -// arithmetic, using simple algorithms since asymptotically -// faster algorithms are slower for a small number of limbs. -// all operations assume the big-integer is normalized. -struct bigint : pow5_tables<> { - // storage of the limbs, in little-endian order. - stackvec vec; - - FASTFLOAT_CONSTEXPR20 bigint() : vec() {} - - bigint(bigint const &) = delete; - bigint &operator=(bigint const &) = delete; - bigint(bigint &&) = delete; - bigint &operator=(bigint &&other) = delete; - - FASTFLOAT_CONSTEXPR20 bigint(uint64_t value) : vec() { -#ifdef FASTFLOAT_64BIT_LIMB - vec.push_unchecked(value); -#else - vec.push_unchecked(uint32_t(value)); - vec.push_unchecked(uint32_t(value >> 32)); -#endif - vec.normalize(); - } - - // get the high 64 bits from the vector, and if bits were truncated. - // this is to get the significant digits for the float. - FASTFLOAT_CONSTEXPR20 uint64_t hi64(bool &truncated) const noexcept { -#ifdef FASTFLOAT_64BIT_LIMB - if (vec.len() == 0) { - return empty_hi64(truncated); - } else if (vec.len() == 1) { - return uint64_hi64(vec.rindex(0), truncated); - } else { - uint64_t result = uint64_hi64(vec.rindex(0), vec.rindex(1), truncated); - truncated |= vec.nonzero(2); - return result; - } -#else - if (vec.len() == 0) { - return empty_hi64(truncated); - } else if (vec.len() == 1) { - return uint32_hi64(vec.rindex(0), truncated); - } else if (vec.len() == 2) { - return uint32_hi64(vec.rindex(0), vec.rindex(1), truncated); - } else { - uint64_t result = - uint32_hi64(vec.rindex(0), vec.rindex(1), vec.rindex(2), truncated); - truncated |= vec.nonzero(3); - return result; - } -#endif - } - - // compare two big integers, returning the large value. - // assumes both are normalized. if the return value is - // negative, other is larger, if the return value is - // positive, this is larger, otherwise they are equal. - // the limbs are stored in little-endian order, so we - // must compare the limbs in ever order. - FASTFLOAT_CONSTEXPR20 int compare(bigint const &other) const noexcept { - if (vec.len() > other.vec.len()) { - return 1; - } else if (vec.len() < other.vec.len()) { - return -1; - } else { - for (size_t index = vec.len(); index > 0; index--) { - limb xi = vec[index - 1]; - limb yi = other.vec[index - 1]; - if (xi > yi) { - return 1; - } else if (xi < yi) { - return -1; - } - } - return 0; - } - } - - // shift left each limb n bits, carrying over to the new limb - // returns true if we were able to shift all the digits. - FASTFLOAT_CONSTEXPR20 bool shl_bits(size_t n) noexcept { - // Internally, for each item, we shift left by n, and add the previous - // right shifted limb-bits. - // For example, we transform (for u8) shifted left 2, to: - // b10100100 b01000010 - // b10 b10010001 b00001000 - FASTFLOAT_DEBUG_ASSERT(n != 0); - FASTFLOAT_DEBUG_ASSERT(n < sizeof(limb) * 8); - - size_t shl = n; - size_t shr = limb_bits - shl; - limb prev = 0; - for (size_t index = 0; index < vec.len(); index++) { - limb xi = vec[index]; - vec[index] = (xi << shl) | (prev >> shr); - prev = xi; - } - - limb carry = prev >> shr; - if (carry != 0) { - return vec.try_push(carry); - } - return true; - } - - // move the limbs left by `n` limbs. - FASTFLOAT_CONSTEXPR20 bool shl_limbs(size_t n) noexcept { - FASTFLOAT_DEBUG_ASSERT(n != 0); - if (n + vec.len() > vec.capacity()) { - return false; - } else if (!vec.is_empty()) { - // move limbs - limb *dst = vec.data + n; - limb const *src = vec.data; - std::copy_backward(src, src + vec.len(), dst + vec.len()); - // fill in empty limbs - limb *first = vec.data; - limb *last = first + n; - ::std::fill(first, last, 0); - vec.set_len(n + vec.len()); - return true; - } else { - return true; - } - } - - // move the limbs left by `n` bits. - FASTFLOAT_CONSTEXPR20 bool shl(size_t n) noexcept { - size_t rem = n % limb_bits; - size_t div = n / limb_bits; - if (rem != 0) { - FASTFLOAT_TRY(shl_bits(rem)); - } - if (div != 0) { - FASTFLOAT_TRY(shl_limbs(div)); - } - return true; - } - - // get the number of leading zeros in the bigint. - FASTFLOAT_CONSTEXPR20 int ctlz() const noexcept { - if (vec.is_empty()) { - return 0; - } else { -#ifdef FASTFLOAT_64BIT_LIMB - return leading_zeroes(vec.rindex(0)); -#else - // no use defining a specialized leading_zeroes for a 32-bit type. - uint64_t r0 = vec.rindex(0); - return leading_zeroes(r0 << 32); -#endif - } - } - - // get the number of bits in the bigint. - FASTFLOAT_CONSTEXPR20 int bit_length() const noexcept { - int lz = ctlz(); - return int(limb_bits * vec.len()) - lz; - } - - FASTFLOAT_CONSTEXPR20 bool mul(limb y) noexcept { return small_mul(vec, y); } - - FASTFLOAT_CONSTEXPR20 bool add(limb y) noexcept { return small_add(vec, y); } - - // multiply as if by 2 raised to a power. - FASTFLOAT_CONSTEXPR20 bool pow2(uint32_t exp) noexcept { return shl(exp); } - - // multiply as if by 5 raised to a power. - FASTFLOAT_CONSTEXPR20 bool pow5(uint32_t exp) noexcept { - // multiply by a power of 5 - size_t large_length = sizeof(large_power_of_5) / sizeof(limb); - limb_span large = limb_span(large_power_of_5, large_length); - while (exp >= large_step) { - FASTFLOAT_TRY(large_mul(vec, large)); - exp -= large_step; - } -#ifdef FASTFLOAT_64BIT_LIMB - uint32_t small_step = 27; - limb max_native = 7450580596923828125UL; -#else - uint32_t small_step = 13; - limb max_native = 1220703125U; -#endif - while (exp >= small_step) { - FASTFLOAT_TRY(small_mul(vec, max_native)); - exp -= small_step; - } - if (exp != 0) { - // Work around clang bug https://godbolt.org/z/zedh7rrhc - // This is similar to https://github.com/llvm/llvm-project/issues/47746, - // except the workaround described there don't work here - FASTFLOAT_TRY(small_mul(vec, limb((static_cast(small_power_of_5[0]), - small_power_of_5[exp])))); - } - - return true; - } - - // multiply as if by 10 raised to a power. - FASTFLOAT_CONSTEXPR20 bool pow10(uint32_t exp) noexcept { - FASTFLOAT_TRY(pow5(exp)); - return pow2(exp); - } -}; - -} // namespace fast_float - -#endif diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/constexpr_feature_detect.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/constexpr_feature_detect.h deleted file mode 100644 index 6751afecd6..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/constexpr_feature_detect.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef FASTFLOAT_CONSTEXPR_FEATURE_DETECT_H -#define FASTFLOAT_CONSTEXPR_FEATURE_DETECT_H - -#ifdef __has_include -#if __has_include() -#include -#endif -#endif - -// Testing for https://wg21.link/N3652, adopted in C++14 -#if defined(__cpp_constexpr) && __cpp_constexpr >= 201304 -#define FASTFLOAT_CONSTEXPR14 constexpr -#else -#define FASTFLOAT_CONSTEXPR14 -#endif - -#if defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L -#define FASTFLOAT_HAS_BIT_CAST 1 -#else -#define FASTFLOAT_HAS_BIT_CAST 0 -#endif - -#if defined(__cpp_lib_is_constant_evaluated) && \ - __cpp_lib_is_constant_evaluated >= 201811L -#define FASTFLOAT_HAS_IS_CONSTANT_EVALUATED 1 -#else -#define FASTFLOAT_HAS_IS_CONSTANT_EVALUATED 0 -#endif - -#if defined(__cpp_if_constexpr) && __cpp_if_constexpr >= 201606L -#define FASTFLOAT_IF_CONSTEXPR17(x) if constexpr (x) -#else -#define FASTFLOAT_IF_CONSTEXPR17(x) if (x) -#endif - -// Testing for relevant C++20 constexpr library features -#if FASTFLOAT_HAS_IS_CONSTANT_EVALUATED && FASTFLOAT_HAS_BIT_CAST && \ - defined(__cpp_lib_constexpr_algorithms) && \ - __cpp_lib_constexpr_algorithms >= 201806L /*For std::copy and std::fill*/ -#define FASTFLOAT_CONSTEXPR20 constexpr -#define FASTFLOAT_IS_CONSTEXPR 1 -#else -#define FASTFLOAT_CONSTEXPR20 -#define FASTFLOAT_IS_CONSTEXPR 0 -#endif - -#if __cplusplus >= 201703L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) -#define FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE 0 -#else -#define FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE 1 -#endif - -#endif // FASTFLOAT_CONSTEXPR_FEATURE_DETECT_H diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/decimal_to_binary.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/decimal_to_binary.h deleted file mode 100644 index 5389701b78..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/decimal_to_binary.h +++ /dev/null @@ -1,238 +0,0 @@ -#ifndef FASTFLOAT_DECIMAL_TO_BINARY_H -#define FASTFLOAT_DECIMAL_TO_BINARY_H - -#include "float_common.h" -#include "fast_table.h" -#include -#include -#include -#include -#include -#include - -namespace fast_float { - -// This will compute or rather approximate w * 5**q and return a pair of 64-bit -// words approximating the result, with the "high" part corresponding to the -// most significant bits and the low part corresponding to the least significant -// bits. -// -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 value128 -compute_product_approximation(int64_t q, uint64_t w) { - int const index = 2 * int(q - powers::smallest_power_of_five); - // For small values of q, e.g., q in [0,27], the answer is always exact - // because The line value128 firstproduct = full_multiplication(w, - // power_of_five_128[index]); gives the exact answer. - value128 firstproduct = - full_multiplication(w, powers::power_of_five_128[index]); - static_assert((bit_precision >= 0) && (bit_precision <= 64), - " precision should be in (0,64]"); - constexpr uint64_t precision_mask = - (bit_precision < 64) ? (uint64_t(0xFFFFFFFFFFFFFFFF) >> bit_precision) - : uint64_t(0xFFFFFFFFFFFFFFFF); - if ((firstproduct.high & precision_mask) == - precision_mask) { // could further guard with (lower + w < lower) - // regarding the second product, we only need secondproduct.high, but our - // expectation is that the compiler will optimize this extra work away if - // needed. - value128 secondproduct = - full_multiplication(w, powers::power_of_five_128[index + 1]); - firstproduct.low += secondproduct.high; - if (secondproduct.high > firstproduct.low) { - firstproduct.high++; - } - } - return firstproduct; -} - -namespace detail { -/** - * For q in (0,350), we have that - * f = (((152170 + 65536) * q ) >> 16); - * is equal to - * floor(p) + q - * where - * p = log(5**q)/log(2) = q * log(5)/log(2) - * - * For negative values of q in (-400,0), we have that - * f = (((152170 + 65536) * q ) >> 16); - * is equal to - * -ceil(p) + q - * where - * p = log(5**-q)/log(2) = -q * log(5)/log(2) - */ -constexpr fastfloat_really_inline int32_t power(int32_t q) noexcept { - return (((152170 + 65536) * q) >> 16) + 63; -} -} // namespace detail - -// create an adjusted mantissa, biased by the invalid power2 -// for significant digits already multiplied by 10 ** q. -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 adjusted_mantissa -compute_error_scaled(int64_t q, uint64_t w, int lz) noexcept { - int hilz = int(w >> 63) ^ 1; - adjusted_mantissa answer; - answer.mantissa = w << hilz; - int bias = binary::mantissa_explicit_bits() - binary::minimum_exponent(); - answer.power2 = int32_t(detail::power(int32_t(q)) + bias - hilz - lz - 62 + - invalid_am_bias); - return answer; -} - -// w * 10 ** q, without rounding the representation up. -// the power2 in the exponent will be adjusted by invalid_am_bias. -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa -compute_error(int64_t q, uint64_t w) noexcept { - int lz = leading_zeroes(w); - w <<= lz; - value128 product = - compute_product_approximation(q, w); - return compute_error_scaled(q, product.high, lz); -} - -// Computers w * 10 ** q. -// The returned value should be a valid number that simply needs to be -// packed. However, in some very rare cases, the computation will fail. In such -// cases, we return an adjusted_mantissa with a negative power of 2: the caller -// should recompute in such cases. -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa -compute_float(int64_t q, uint64_t w) noexcept { - adjusted_mantissa answer; - if ((w == 0) || (q < binary::smallest_power_of_ten())) { - answer.power2 = 0; - answer.mantissa = 0; - // result should be zero - return answer; - } - if (q > binary::largest_power_of_ten()) { - // we want to get infinity: - answer.power2 = binary::infinite_power(); - answer.mantissa = 0; - return answer; - } - // At this point in time q is in [powers::smallest_power_of_five, - // powers::largest_power_of_five]. - - // We want the most significant bit of i to be 1. Shift if needed. - int lz = leading_zeroes(w); - w <<= lz; - - // The required precision is binary::mantissa_explicit_bits() + 3 because - // 1. We need the implicit bit - // 2. We need an extra bit for rounding purposes - // 3. We might lose a bit due to the "upperbit" routine (result too small, - // requiring a shift) - - value128 product = - compute_product_approximation(q, w); - // The computed 'product' is always sufficient. - // Mathematical proof: - // Noble Mushtak and Daniel Lemire, Fast Number Parsing Without Fallback (to - // appear) See script/mushtak_lemire.py - - // The "compute_product_approximation" function can be slightly slower than a - // branchless approach: value128 product = compute_product(q, w); but in - // practice, we can win big with the compute_product_approximation if its - // additional branch is easily predicted. Which is best is data specific. - int upperbit = int(product.high >> 63); - int shift = upperbit + 64 - binary::mantissa_explicit_bits() - 3; - - answer.mantissa = product.high >> shift; - - answer.power2 = int32_t(detail::power(int32_t(q)) + upperbit - lz - - binary::minimum_exponent()); - if (answer.power2 <= 0) { // we have a subnormal? - // Here have that answer.power2 <= 0 so -answer.power2 >= 0 - if (-answer.power2 + 1 >= - 64) { // if we have more than 64 bits below the minimum exponent, you - // have a zero for sure. - answer.power2 = 0; - answer.mantissa = 0; - // result should be zero - return answer; - } - // next line is safe because -answer.power2 + 1 < 64 - int const subnormal_shift = -answer.power2 + 1; - answer.mantissa >>= subnormal_shift; - // A subnormal result can also fall exactly between two floats. With at - // most 19 digits this never happens for float and double, but it does for - // std::float16_t (e.g., 2^-25 = 298023223876953125e-25), so we apply the - // same round-to-even test as in the normal case below. - // See script/format_parameters.py. - if (binary::subnormal_ties_possible() && (product.low <= 1) && - (q >= binary::min_exponent_round_to_even()) && - (q <= binary::max_exponent_round_to_even()) && - ((answer.mantissa & 3) == 1)) { - if (((answer.mantissa << subnormal_shift) << shift) == product.high) { - answer.mantissa &= ~uint64_t(1); // flip it so that we do not round up - } - } - answer.mantissa += (answer.mantissa & 1); // round up - answer.mantissa >>= 1; - // There is a weird scenario where we don't have a subnormal but just. - // Suppose we start with 2.2250738585072013e-308, we end up - // with 0x3fffffffffffff x 2^-1023-53 which is technically subnormal - // whereas 0x40000000000000 x 2^-1023-53 is normal. Now, we need to round - // up 0x3fffffffffffff x 2^-1023-53 and once we do, we are no longer - // subnormal, but we can only know this after rounding. - // So we only declare a subnormal if we are smaller than the threshold. - answer.power2 = - (answer.mantissa < (uint64_t(1) << binary::mantissa_explicit_bits())) - ? 0 - : 1; - return answer; - } - - // usually, we round *up*, but if we fall right in between and and we have an - // even basis, we need to round down - // We are only concerned with the cases where 5**q fits in single 64-bit word. - if ((product.low <= 1) && (q >= binary::min_exponent_round_to_even()) && - (q <= binary::max_exponent_round_to_even()) && - ((answer.mantissa & 3) == 1)) { // we may fall between two floats! - // To be in-between two floats we need that in doing - // answer.mantissa = product.high >> (upperbit + 64 - - // binary::mantissa_explicit_bits() - 3); - // ... we dropped out only zeroes. But if this happened, then we can go - // back!!! - if ((answer.mantissa << shift) == product.high) { - answer.mantissa &= ~uint64_t(1); // flip it so that we do not round up - } - } - - answer.mantissa += (answer.mantissa & 1); // round up - answer.mantissa >>= 1; - // Both fix-ups below are rare. They are marked unlikely so that clang keeps - // them as branches instead of folding them into conditional moves that - // every conversion pays for. -#ifdef __clang__ -#pragma clang diagnostic push -#if (!defined(__APPLE_CC__) && __clang_major__ >= 10) || (__clang_major__ >= 13) -#pragma clang diagnostic ignored "-Wc++20-extensions" -#endif -#endif - if fastfloat_clang_unlikely (answer.mantissa >= - (uint64_t(2) - << binary::mantissa_explicit_bits())) { - answer.mantissa = (uint64_t(1) << binary::mantissa_explicit_bits()); - answer.power2++; // undo previous addition - } - - answer.mantissa &= ~(uint64_t(1) << binary::mantissa_explicit_bits()); - if fastfloat_clang_unlikely (answer.power2 >= binary::infinite_power()) { - // infinity - answer.power2 = binary::infinite_power(); - answer.mantissa = 0; - } -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - return answer; -} - -} // namespace fast_float - -#endif diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/digit_comparison.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/digit_comparison.h deleted file mode 100644 index 6aac9522ee..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/digit_comparison.h +++ /dev/null @@ -1,450 +0,0 @@ -#ifndef FASTFLOAT_DIGIT_COMPARISON_H -#define FASTFLOAT_DIGIT_COMPARISON_H - -#include -#include -#include - -#include "float_common.h" -#include "bigint.h" -#include "ascii_number.h" - -namespace fast_float { - -// 1e0 to 1e19 -constexpr static uint64_t powers_of_ten_uint64[] = {1UL, - 10UL, - 100UL, - 1000UL, - 10000UL, - 100000UL, - 1000000UL, - 10000000UL, - 100000000UL, - 1000000000UL, - 10000000000UL, - 100000000000UL, - 1000000000000UL, - 10000000000000UL, - 100000000000000UL, - 1000000000000000UL, - 10000000000000000UL, - 100000000000000000UL, - 1000000000000000000UL, - 10000000000000000000UL}; - -// calculate the exponent, in scientific notation, of the number. -// this algorithm is not even close to optimized, but it has no practical -// effect on performance: in order to have a faster algorithm, we'd need -// to slow down performance for faster algorithms, and this is still fast. -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 int32_t -scientific_exponent(uint64_t mantissa, int32_t exponent) noexcept { - while (mantissa >= 10000) { - mantissa /= 10000; - exponent += 4; - } - while (mantissa >= 100) { - mantissa /= 100; - exponent += 2; - } - while (mantissa >= 10) { - mantissa /= 10; - exponent += 1; - } - return exponent; -} - -// this converts a native floating-point number to an extended-precision float. -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa -to_extended(T value) noexcept { - using equiv_uint = equiv_uint_t; - constexpr equiv_uint exponent_mask = binary_format::exponent_mask(); - constexpr equiv_uint mantissa_mask = binary_format::mantissa_mask(); - constexpr equiv_uint hidden_bit_mask = binary_format::hidden_bit_mask(); - - adjusted_mantissa am; - int32_t bias = binary_format::mantissa_explicit_bits() - - binary_format::minimum_exponent(); - equiv_uint bits; -#if FASTFLOAT_HAS_BIT_CAST - bits = std::bit_cast(value); -#else - ::memcpy(&bits, &value, sizeof(T)); -#endif - if ((bits & exponent_mask) == 0) { - // denormal - am.power2 = 1 - bias; - am.mantissa = bits & mantissa_mask; - } else { - // normal - am.power2 = int32_t((bits & exponent_mask) >> - binary_format::mantissa_explicit_bits()); - am.power2 -= bias; - am.mantissa = (bits & mantissa_mask) | hidden_bit_mask; - } - - return am; -} - -// get the extended precision value of the halfway point between b and b+u. -// we are given a native float that represents b, so we need to adjust it -// halfway between b and b+u. -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa -to_extended_halfway(T value) noexcept { - adjusted_mantissa am = to_extended(value); - am.mantissa <<= 1; - am.mantissa += 1; - am.power2 -= 1; - return am; -} - -// round an extended-precision float to the nearest machine float. -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 void round(adjusted_mantissa &am, - callback cb) noexcept { - int32_t mantissa_shift = 64 - binary_format::mantissa_explicit_bits() - 1; - if (-am.power2 >= mantissa_shift) { - // have a denormal float - int32_t shift = -am.power2 + 1; - cb(am, (shift < 64 ? shift : 64)); - // check for round-up: if rounding-nearest carried us to the hidden bit. - am.power2 = (am.mantissa < - (uint64_t(1) << binary_format::mantissa_explicit_bits())) - ? 0 - : 1; - return; - } - - // have a normal float, use the default shift. - cb(am, mantissa_shift); - - // check for carry - if (am.mantissa >= - (uint64_t(2) << binary_format::mantissa_explicit_bits())) { - am.mantissa = (uint64_t(1) << binary_format::mantissa_explicit_bits()); - am.power2++; - } - - // check for infinite: we could have carried to an infinite power - am.mantissa &= ~(uint64_t(1) << binary_format::mantissa_explicit_bits()); - if (am.power2 >= binary_format::infinite_power()) { - am.power2 = binary_format::infinite_power(); - am.mantissa = 0; - } -} - -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 void -round_nearest_tie_even(adjusted_mantissa &am, int32_t shift, - callback cb) noexcept { - uint64_t const mask = (shift == 64) ? UINT64_MAX : (uint64_t(1) << shift) - 1; - uint64_t const halfway = (shift == 0) ? 0 : uint64_t(1) << (shift - 1); - uint64_t truncated_bits = am.mantissa & mask; - bool is_above = truncated_bits > halfway; - bool is_halfway = truncated_bits == halfway; - - // shift digits into position - if (shift == 64) { - am.mantissa = 0; - } else { - am.mantissa >>= shift; - } - am.power2 += shift; - - bool is_odd = (am.mantissa & 1) == 1; - am.mantissa += uint64_t(cb(is_odd, is_halfway, is_above)); -} - -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 void -round_down(adjusted_mantissa &am, int32_t shift) noexcept { - if (shift == 64) { - am.mantissa = 0; - } else { - am.mantissa >>= shift; - } - am.power2 += shift; -} - -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void -skip_zeros(UC const *&first, UC const *last) noexcept { - uint64_t val; - while (!cpp20_and_in_constexpr() && - std::distance(first, last) >= int_cmp_len()) { - ::memcpy(&val, first, sizeof(uint64_t)); - if (val != int_cmp_zeros()) { - break; - } - first += int_cmp_len(); - } - while (first != last) { - if (*first != UC('0')) { - break; - } - first++; - } -} - -// determine if any non-zero digits were truncated. -// all characters must be valid digits. -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool -is_truncated(UC const *first, UC const *last) noexcept { - // do 8-bit optimizations, can just compare to 8 literal 0s. - uint64_t val; - while (!cpp20_and_in_constexpr() && - std::distance(first, last) >= int_cmp_len()) { - ::memcpy(&val, first, sizeof(uint64_t)); - if (val != int_cmp_zeros()) { - return true; - } - first += int_cmp_len(); - } - while (first != last) { - if (*first != UC('0')) { - return true; - } - ++first; - } - return false; -} - -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool -is_truncated(span s) noexcept { - return is_truncated(s.ptr, s.ptr + s.len()); -} - -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void -parse_eight_digits(UC const *&p, limb &value, size_t &counter, - size_t &count) noexcept { - value = value * 100000000 + parse_eight_digits_unrolled(p); - p += 8; - counter += 8; - count += 8; -} - -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 void -parse_one_digit(UC const *&p, limb &value, size_t &counter, - size_t &count) noexcept { - value = value * 10 + limb(*p - UC('0')); - p++; - counter++; - count++; -} - -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void -add_native(bigint &big, limb power, limb value) noexcept { - big.mul(power); - big.add(value); -} - -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void -round_up_bigint(bigint &big, size_t &count) noexcept { - // need to round-up the digits, but need to avoid rounding - // ....9999 to ...10000, which could cause a false halfway point. - add_native(big, 10, 1); - count++; -} - -// parse the significant digits into a big integer -template -inline FASTFLOAT_CONSTEXPR20 void -parse_mantissa(bigint &result, parsed_number_string_t &num, - size_t max_digits, size_t &digits) noexcept { - // try to minimize the number of big integer and scalar multiplication. - // therefore, try to parse 8 digits at a time, and multiply by the largest - // scalar value (9 or 19 digits) for each step. - size_t counter = 0; - digits = 0; - limb value = 0; -#ifdef FASTFLOAT_64BIT_LIMB - size_t step = 19; -#else - size_t step = 9; -#endif - - // process all integer digits. - UC const *p = num.integer.ptr; - UC const *pend = p + num.integer.len(); - skip_zeros(p, pend); - // process all digits, in increments of step per loop - while (p != pend) { - while ((std::distance(p, pend) >= 8) && (step - counter >= 8) && - (max_digits - digits >= 8)) { - parse_eight_digits(p, value, counter, digits); - } - while (counter < step && p != pend && digits < max_digits) { - parse_one_digit(p, value, counter, digits); - } - if (digits == max_digits) { - // add the temporary value, then check if we've truncated any digits - add_native(result, limb(powers_of_ten_uint64[counter]), value); - bool truncated = is_truncated(p, pend); - if (num.fraction.ptr != nullptr) { - truncated |= is_truncated(num.fraction); - } - if (truncated) { - round_up_bigint(result, digits); - } - return; - } else { - add_native(result, limb(powers_of_ten_uint64[counter]), value); - counter = 0; - value = 0; - } - } - - // add our fraction digits, if they're available. - if (num.fraction.ptr != nullptr) { - p = num.fraction.ptr; - pend = p + num.fraction.len(); - if (digits == 0) { - skip_zeros(p, pend); - } - // process all digits, in increments of step per loop - while (p != pend) { - while ((std::distance(p, pend) >= 8) && (step - counter >= 8) && - (max_digits - digits >= 8)) { - parse_eight_digits(p, value, counter, digits); - } - while (counter < step && p != pend && digits < max_digits) { - parse_one_digit(p, value, counter, digits); - } - if (digits == max_digits) { - // add the temporary value, then check if we've truncated any digits - add_native(result, limb(powers_of_ten_uint64[counter]), value); - bool truncated = is_truncated(p, pend); - if (truncated) { - round_up_bigint(result, digits); - } - return; - } else { - add_native(result, limb(powers_of_ten_uint64[counter]), value); - counter = 0; - value = 0; - } - } - } -} - -template -inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa -positive_digit_comp(bigint &bigmant, int32_t exponent) noexcept { - FASTFLOAT_ASSERT(bigmant.pow10(uint32_t(exponent))); - adjusted_mantissa answer; - bool truncated; - answer.mantissa = bigmant.hi64(truncated); - int bias = binary_format::mantissa_explicit_bits() - - binary_format::minimum_exponent(); - answer.power2 = bigmant.bit_length() - 64 + bias; - - round(answer, [truncated](adjusted_mantissa &a, int32_t shift) { - round_nearest_tie_even( - a, shift, - [truncated](bool is_odd, bool is_halfway, bool is_above) -> bool { - return is_above || (is_halfway && truncated) || - (is_odd && is_halfway); - }); - }); - - return answer; -} - -// the scaling here is quite simple: we have, for the real digits `m * 10^e`, -// and for the theoretical digits `n * 2^f`. Since `e` is always negative, -// to scale them identically, we do `n * 2^f * 5^-f`, so we now have `m * 2^e`. -// we then need to scale by `2^(f- e)`, and then the two significant digits -// are of the same magnitude. -template -inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa negative_digit_comp( - bigint &bigmant, adjusted_mantissa am, int32_t exponent) noexcept { - bigint &real_digits = bigmant; - int32_t real_exp = exponent; - - // get the value of `b`, rounded down, and get a bigint representation of b+h - adjusted_mantissa am_b = am; - // gcc7 buf: use a lambda to remove the noexcept qualifier bug with - // -Wnoexcept-type. - round(am_b, - [](adjusted_mantissa &a, int32_t shift) { round_down(a, shift); }); - T b; - to_float(false, am_b, b); - adjusted_mantissa theor = to_extended_halfway(b); - bigint theor_digits(theor.mantissa); - int32_t theor_exp = theor.power2; - - // scale real digits and theor digits to be same power. - int32_t pow2_exp = theor_exp - real_exp; - uint32_t pow5_exp = uint32_t(-real_exp); - if (pow5_exp != 0) { - FASTFLOAT_ASSERT(theor_digits.pow5(pow5_exp)); - } - if (pow2_exp > 0) { - FASTFLOAT_ASSERT(theor_digits.pow2(uint32_t(pow2_exp))); - } else if (pow2_exp < 0) { - FASTFLOAT_ASSERT(real_digits.pow2(uint32_t(-pow2_exp))); - } - - // compare digits, and use it to direct rounding - int ord = real_digits.compare(theor_digits); - adjusted_mantissa answer = am; - round(answer, [ord](adjusted_mantissa &a, int32_t shift) { - round_nearest_tie_even( - a, shift, [ord](bool is_odd, bool _, bool __) -> bool { - static_cast(_); // not needed, since we've done our comparison - static_cast(__); // not needed, since we've done our comparison - if (ord > 0) { - return true; - } else if (ord < 0) { - return false; - } else { - return is_odd; - } - }); - }); - - return answer; -} - -// parse the significant digits as a big integer to unambiguously round -// the significant digits. here, we are trying to determine how to round -// an extended float representation close to `b+h`, halfway between `b` -// (the float rounded-down) and `b+u`, the next positive float. this -// algorithm is always correct, and uses one of two approaches. when -// the exponent is positive relative to the significant digits (such as -// 1234), we create a big-integer representation, get the high 64-bits, -// determine if any lower bits are truncated, and use that to direct -// rounding. in case of a negative exponent relative to the significant -// digits (such as 1.2345), we create a theoretical representation of -// `b` as a big-integer type, scaled to the same binary exponent as -// the actual digits. we then compare the big integer representations -// of both, and use that to direct rounding. -template -inline FASTFLOAT_CONSTEXPR20 adjusted_mantissa -digit_comp(parsed_number_string_t &num, adjusted_mantissa am) noexcept { - // remove the invalid exponent bias - am.power2 -= invalid_am_bias; - - int32_t sci_exp = - scientific_exponent(num.mantissa, static_cast(num.exponent)); - size_t max_digits = binary_format::max_digits(); - size_t digits = 0; - bigint bigmant; - parse_mantissa(bigmant, num, max_digits, digits); - // can't underflow, since digits is at most max_digits. - int32_t exponent = sci_exp + 1 - int32_t(digits); - if (exponent >= 0) { - return positive_digit_comp(bigmant, exponent); - } else { - return negative_digit_comp(bigmant, am, exponent); - } -} - -} // namespace fast_float - -#endif diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/fast_float.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/fast_float.h deleted file mode 100644 index 1e79ac612e..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/fast_float.h +++ /dev/null @@ -1,91 +0,0 @@ - -#ifndef FASTFLOAT_FAST_FLOAT_H -#define FASTFLOAT_FAST_FLOAT_H - -#include "float_common.h" - -namespace fast_float { -/** - * This function parses the character sequence [first,last) for a number. It - * parses floating-point numbers expecting a locale-independent format - * equivalent to what is used by std::strtod in the default ("C") locale. The - * resulting floating-point value is the closest floating-point values (using - * either float or double), using the "round to even" convention for values that - * would otherwise fall right in-between two values. That is, we provide exact - * parsing according to the IEEE standard. - * - * Given a successful parse, the pointer (`ptr`) in the returned value is set to - * point right after the parsed number, and the `value` referenced is set to the - * parsed value. In case of error, the returned `ec` contains a representative - * error, otherwise the default (`std::errc()`) value is stored. - * - * The implementation does not throw and does not allocate memory (e.g., with - * `new` or `malloc`). - * - * Like the C++17 standard, the `fast_float::from_chars` functions take an - * optional last argument of the type `fast_float::chars_format`. It is a bitset - * value: we check whether `fmt & fast_float::chars_format::fixed` and `fmt & - * fast_float::chars_format::scientific` are set to determine whether we allow - * the fixed point and scientific notation respectively. The default is - * `fast_float::chars_format::general` which allows both `fixed` and - * `scientific`. - */ -template ::value)> -FASTFLOAT_CONSTEXPR20 from_chars_result_t -from_chars(UC const *first, UC const *last, T &value, - chars_format fmt = chars_format::general) noexcept; - -/** - * Like from_chars, but accepts an `options` argument to govern number parsing. - * Both for floating-point types and integer types. - */ -template -FASTFLOAT_CONSTEXPR20 from_chars_result_t -from_chars_advanced(UC const *first, UC const *last, T &value, - parse_options_t options) noexcept; - -/** - * This function multiplies an integer number by a power of 10 and returns - * the result as a double precision floating-point value that is correctly - * rounded. The resulting floating-point value is the closest floating-point - * value, using the "round to nearest, tie to even" convention for values that - * would otherwise fall right in-between two values. That is, we provide exact - * conversion according to the IEEE standard. - * - * On overflow infinity is returned, on underflow 0 is returned. - * - * The implementation does not throw and does not allocate memory (e.g., with - * `new` or `malloc`). - */ -FASTFLOAT_CONSTEXPR20 inline double -integer_times_pow10(uint64_t mantissa, int decimal_exponent) noexcept; -FASTFLOAT_CONSTEXPR20 inline double -integer_times_pow10(int64_t mantissa, int decimal_exponent) noexcept; - -/** - * This function is a template overload of `integer_times_pow10()` - * that returns a floating-point value of type `T` that is one of - * supported floating-point types (e.g. `double`, `float`). - */ -template -FASTFLOAT_CONSTEXPR20 - typename std::enable_if::value, T>::type - integer_times_pow10(uint64_t mantissa, int decimal_exponent) noexcept; -template -FASTFLOAT_CONSTEXPR20 - typename std::enable_if::value, T>::type - integer_times_pow10(int64_t mantissa, int decimal_exponent) noexcept; - -/** - * from_chars for integer types. - */ -template ::value)> -FASTFLOAT_CONSTEXPR20 from_chars_result_t -from_chars(UC const *first, UC const *last, T &value, int base = 10) noexcept; - -} // namespace fast_float - -#include "parse_number.h" -#endif // FASTFLOAT_FAST_FLOAT_H diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/fast_table.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/fast_table.h deleted file mode 100644 index 69f9b2c924..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/fast_table.h +++ /dev/null @@ -1,708 +0,0 @@ -#ifndef FASTFLOAT_FAST_TABLE_H -#define FASTFLOAT_FAST_TABLE_H - -#include - -namespace fast_float { - -/** - * When mapping numbers from decimal to binary, - * we go from w * 10^q to m * 2^p but we have - * 10^q = 5^q * 2^q, so effectively - * we are trying to match - * w * 2^q * 5^q to m * 2^p. Thus the powers of two - * are not a concern since they can be represented - * exactly using the binary notation, only the powers of five - * affect the binary significand. - */ - -/** - * The smallest non-zero float (binary64) is 2^-1074. - * We take as input numbers of the form w x 10^q where w < 2^64. - * We have that w * 10^-343 < 2^(64-344) 5^-343 < 2^-1076. - * However, we have that - * (2^64-1) * 10^-342 = (2^64-1) * 2^-342 * 5^-342 > 2^-1074. - * Thus it is possible for a number of the form w * 10^-342 where - * w is a 64-bit value to be a non-zero floating-point number. - ********* - * Any number of form w * 10^309 where w>= 1 is going to be - * infinite in binary64 so we never need to worry about powers - * of 5 greater than 308. - */ -template struct powers_template { - - constexpr static int smallest_power_of_five = - binary_format::smallest_power_of_ten(); - constexpr static int largest_power_of_five = - binary_format::largest_power_of_ten(); - constexpr static int number_of_entries = - 2 * (largest_power_of_five - smallest_power_of_five + 1); - // Powers of five from 5^-342 all the way to 5^308 rounded toward one. - constexpr static uint64_t power_of_five_128[number_of_entries] = { - 0xeef453d6923bd65a, 0x113faa2906a13b3f, - 0x9558b4661b6565f8, 0x4ac7ca59a424c507, - 0xbaaee17fa23ebf76, 0x5d79bcf00d2df649, - 0xe95a99df8ace6f53, 0xf4d82c2c107973dc, - 0x91d8a02bb6c10594, 0x79071b9b8a4be869, - 0xb64ec836a47146f9, 0x9748e2826cdee284, - 0xe3e27a444d8d98b7, 0xfd1b1b2308169b25, - 0x8e6d8c6ab0787f72, 0xfe30f0f5e50e20f7, - 0xb208ef855c969f4f, 0xbdbd2d335e51a935, - 0xde8b2b66b3bc4723, 0xad2c788035e61382, - 0x8b16fb203055ac76, 0x4c3bcb5021afcc31, - 0xaddcb9e83c6b1793, 0xdf4abe242a1bbf3d, - 0xd953e8624b85dd78, 0xd71d6dad34a2af0d, - 0x87d4713d6f33aa6b, 0x8672648c40e5ad68, - 0xa9c98d8ccb009506, 0x680efdaf511f18c2, - 0xd43bf0effdc0ba48, 0x212bd1b2566def2, - 0x84a57695fe98746d, 0x14bb630f7604b57, - 0xa5ced43b7e3e9188, 0x419ea3bd35385e2d, - 0xcf42894a5dce35ea, 0x52064cac828675b9, - 0x818995ce7aa0e1b2, 0x7343efebd1940993, - 0xa1ebfb4219491a1f, 0x1014ebe6c5f90bf8, - 0xca66fa129f9b60a6, 0xd41a26e077774ef6, - 0xfd00b897478238d0, 0x8920b098955522b4, - 0x9e20735e8cb16382, 0x55b46e5f5d5535b0, - 0xc5a890362fddbc62, 0xeb2189f734aa831d, - 0xf712b443bbd52b7b, 0xa5e9ec7501d523e4, - 0x9a6bb0aa55653b2d, 0x47b233c92125366e, - 0xc1069cd4eabe89f8, 0x999ec0bb696e840a, - 0xf148440a256e2c76, 0xc00670ea43ca250d, - 0x96cd2a865764dbca, 0x380406926a5e5728, - 0xbc807527ed3e12bc, 0xc605083704f5ecf2, - 0xeba09271e88d976b, 0xf7864a44c633682e, - 0x93445b8731587ea3, 0x7ab3ee6afbe0211d, - 0xb8157268fdae9e4c, 0x5960ea05bad82964, - 0xe61acf033d1a45df, 0x6fb92487298e33bd, - 0x8fd0c16206306bab, 0xa5d3b6d479f8e056, - 0xb3c4f1ba87bc8696, 0x8f48a4899877186c, - 0xe0b62e2929aba83c, 0x331acdabfe94de87, - 0x8c71dcd9ba0b4925, 0x9ff0c08b7f1d0b14, - 0xaf8e5410288e1b6f, 0x7ecf0ae5ee44dd9, - 0xdb71e91432b1a24a, 0xc9e82cd9f69d6150, - 0x892731ac9faf056e, 0xbe311c083a225cd2, - 0xab70fe17c79ac6ca, 0x6dbd630a48aaf406, - 0xd64d3d9db981787d, 0x92cbbccdad5b108, - 0x85f0468293f0eb4e, 0x25bbf56008c58ea5, - 0xa76c582338ed2621, 0xaf2af2b80af6f24e, - 0xd1476e2c07286faa, 0x1af5af660db4aee1, - 0x82cca4db847945ca, 0x50d98d9fc890ed4d, - 0xa37fce126597973c, 0xe50ff107bab528a0, - 0xcc5fc196fefd7d0c, 0x1e53ed49a96272c8, - 0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7a, - 0x9faacf3df73609b1, 0x77b191618c54e9ac, - 0xc795830d75038c1d, 0xd59df5b9ef6a2417, - 0xf97ae3d0d2446f25, 0x4b0573286b44ad1d, - 0x9becce62836ac577, 0x4ee367f9430aec32, - 0xc2e801fb244576d5, 0x229c41f793cda73f, - 0xf3a20279ed56d48a, 0x6b43527578c1110f, - 0x9845418c345644d6, 0x830a13896b78aaa9, - 0xbe5691ef416bd60c, 0x23cc986bc656d553, - 0xedec366b11c6cb8f, 0x2cbfbe86b7ec8aa8, - 0x94b3a202eb1c3f39, 0x7bf7d71432f3d6a9, - 0xb9e08a83a5e34f07, 0xdaf5ccd93fb0cc53, - 0xe858ad248f5c22c9, 0xd1b3400f8f9cff68, - 0x91376c36d99995be, 0x23100809b9c21fa1, - 0xb58547448ffffb2d, 0xabd40a0c2832a78a, - 0xe2e69915b3fff9f9, 0x16c90c8f323f516c, - 0x8dd01fad907ffc3b, 0xae3da7d97f6792e3, - 0xb1442798f49ffb4a, 0x99cd11cfdf41779c, - 0xdd95317f31c7fa1d, 0x40405643d711d583, - 0x8a7d3eef7f1cfc52, 0x482835ea666b2572, - 0xad1c8eab5ee43b66, 0xda3243650005eecf, - 0xd863b256369d4a40, 0x90bed43e40076a82, - 0x873e4f75e2224e68, 0x5a7744a6e804a291, - 0xa90de3535aaae202, 0x711515d0a205cb36, - 0xd3515c2831559a83, 0xd5a5b44ca873e03, - 0x8412d9991ed58091, 0xe858790afe9486c2, - 0xa5178fff668ae0b6, 0x626e974dbe39a872, - 0xce5d73ff402d98e3, 0xfb0a3d212dc8128f, - 0x80fa687f881c7f8e, 0x7ce66634bc9d0b99, - 0xa139029f6a239f72, 0x1c1fffc1ebc44e80, - 0xc987434744ac874e, 0xa327ffb266b56220, - 0xfbe9141915d7a922, 0x4bf1ff9f0062baa8, - 0x9d71ac8fada6c9b5, 0x6f773fc3603db4a9, - 0xc4ce17b399107c22, 0xcb550fb4384d21d3, - 0xf6019da07f549b2b, 0x7e2a53a146606a48, - 0x99c102844f94e0fb, 0x2eda7444cbfc426d, - 0xc0314325637a1939, 0xfa911155fefb5308, - 0xf03d93eebc589f88, 0x793555ab7eba27ca, - 0x96267c7535b763b5, 0x4bc1558b2f3458de, - 0xbbb01b9283253ca2, 0x9eb1aaedfb016f16, - 0xea9c227723ee8bcb, 0x465e15a979c1cadc, - 0x92a1958a7675175f, 0xbfacd89ec191ec9, - 0xb749faed14125d36, 0xcef980ec671f667b, - 0xe51c79a85916f484, 0x82b7e12780e7401a, - 0x8f31cc0937ae58d2, 0xd1b2ecb8b0908810, - 0xb2fe3f0b8599ef07, 0x861fa7e6dcb4aa15, - 0xdfbdcece67006ac9, 0x67a791e093e1d49a, - 0x8bd6a141006042bd, 0xe0c8bb2c5c6d24e0, - 0xaecc49914078536d, 0x58fae9f773886e18, - 0xda7f5bf590966848, 0xaf39a475506a899e, - 0x888f99797a5e012d, 0x6d8406c952429603, - 0xaab37fd7d8f58178, 0xc8e5087ba6d33b83, - 0xd5605fcdcf32e1d6, 0xfb1e4a9a90880a64, - 0x855c3be0a17fcd26, 0x5cf2eea09a55067f, - 0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481e, - 0xd0601d8efc57b08b, 0xf13b94daf124da26, - 0x823c12795db6ce57, 0x76c53d08d6b70858, - 0xa2cb1717b52481ed, 0x54768c4b0c64ca6e, - 0xcb7ddcdda26da268, 0xa9942f5dcf7dfd09, - 0xfe5d54150b090b02, 0xd3f93b35435d7c4c, - 0x9efa548d26e5a6e1, 0xc47bc5014a1a6daf, - 0xc6b8e9b0709f109a, 0x359ab6419ca1091b, - 0xf867241c8cc6d4c0, 0xc30163d203c94b62, - 0x9b407691d7fc44f8, 0x79e0de63425dcf1d, - 0xc21094364dfb5636, 0x985915fc12f542e4, - 0xf294b943e17a2bc4, 0x3e6f5b7b17b2939d, - 0x979cf3ca6cec5b5a, 0xa705992ceecf9c42, - 0xbd8430bd08277231, 0x50c6ff782a838353, - 0xece53cec4a314ebd, 0xa4f8bf5635246428, - 0x940f4613ae5ed136, 0x871b7795e136be99, - 0xb913179899f68584, 0x28e2557b59846e3f, - 0xe757dd7ec07426e5, 0x331aeada2fe589cf, - 0x9096ea6f3848984f, 0x3ff0d2c85def7621, - 0xb4bca50b065abe63, 0xfed077a756b53a9, - 0xe1ebce4dc7f16dfb, 0xd3e8495912c62894, - 0x8d3360f09cf6e4bd, 0x64712dd7abbbd95c, - 0xb080392cc4349dec, 0xbd8d794d96aacfb3, - 0xdca04777f541c567, 0xecf0d7a0fc5583a0, - 0x89e42caaf9491b60, 0xf41686c49db57244, - 0xac5d37d5b79b6239, 0x311c2875c522ced5, - 0xd77485cb25823ac7, 0x7d633293366b828b, - 0x86a8d39ef77164bc, 0xae5dff9c02033197, - 0xa8530886b54dbdeb, 0xd9f57f830283fdfc, - 0xd267caa862a12d66, 0xd072df63c324fd7b, - 0x8380dea93da4bc60, 0x4247cb9e59f71e6d, - 0xa46116538d0deb78, 0x52d9be85f074e608, - 0xcd795be870516656, 0x67902e276c921f8b, - 0x806bd9714632dff6, 0xba1cd8a3db53b6, - 0xa086cfcd97bf97f3, 0x80e8a40eccd228a4, - 0xc8a883c0fdaf7df0, 0x6122cd128006b2cd, - 0xfad2a4b13d1b5d6c, 0x796b805720085f81, - 0x9cc3a6eec6311a63, 0xcbe3303674053bb0, - 0xc3f490aa77bd60fc, 0xbedbfc4411068a9c, - 0xf4f1b4d515acb93b, 0xee92fb5515482d44, - 0x991711052d8bf3c5, 0x751bdd152d4d1c4a, - 0xbf5cd54678eef0b6, 0xd262d45a78a0635d, - 0xef340a98172aace4, 0x86fb897116c87c34, - 0x9580869f0e7aac0e, 0xd45d35e6ae3d4da0, - 0xbae0a846d2195712, 0x8974836059cca109, - 0xe998d258869facd7, 0x2bd1a438703fc94b, - 0x91ff83775423cc06, 0x7b6306a34627ddcf, - 0xb67f6455292cbf08, 0x1a3bc84c17b1d542, - 0xe41f3d6a7377eeca, 0x20caba5f1d9e4a93, - 0x8e938662882af53e, 0x547eb47b7282ee9c, - 0xb23867fb2a35b28d, 0xe99e619a4f23aa43, - 0xdec681f9f4c31f31, 0x6405fa00e2ec94d4, - 0x8b3c113c38f9f37e, 0xde83bc408dd3dd04, - 0xae0b158b4738705e, 0x9624ab50b148d445, - 0xd98ddaee19068c76, 0x3badd624dd9b0957, - 0x87f8a8d4cfa417c9, 0xe54ca5d70a80e5d6, - 0xa9f6d30a038d1dbc, 0x5e9fcf4ccd211f4c, - 0xd47487cc8470652b, 0x7647c3200069671f, - 0x84c8d4dfd2c63f3b, 0x29ecd9f40041e073, - 0xa5fb0a17c777cf09, 0xf468107100525890, - 0xcf79cc9db955c2cc, 0x7182148d4066eeb4, - 0x81ac1fe293d599bf, 0xc6f14cd848405530, - 0xa21727db38cb002f, 0xb8ada00e5a506a7c, - 0xca9cf1d206fdc03b, 0xa6d90811f0e4851c, - 0xfd442e4688bd304a, 0x908f4a166d1da663, - 0x9e4a9cec15763e2e, 0x9a598e4e043287fe, - 0xc5dd44271ad3cdba, 0x40eff1e1853f29fd, - 0xf7549530e188c128, 0xd12bee59e68ef47c, - 0x9a94dd3e8cf578b9, 0x82bb74f8301958ce, - 0xc13a148e3032d6e7, 0xe36a52363c1faf01, - 0xf18899b1bc3f8ca1, 0xdc44e6c3cb279ac1, - 0x96f5600f15a7b7e5, 0x29ab103a5ef8c0b9, - 0xbcb2b812db11a5de, 0x7415d448f6b6f0e7, - 0xebdf661791d60f56, 0x111b495b3464ad21, - 0x936b9fcebb25c995, 0xcab10dd900beec34, - 0xb84687c269ef3bfb, 0x3d5d514f40eea742, - 0xe65829b3046b0afa, 0xcb4a5a3112a5112, - 0x8ff71a0fe2c2e6dc, 0x47f0e785eaba72ab, - 0xb3f4e093db73a093, 0x59ed216765690f56, - 0xe0f218b8d25088b8, 0x306869c13ec3532c, - 0x8c974f7383725573, 0x1e414218c73a13fb, - 0xafbd2350644eeacf, 0xe5d1929ef90898fa, - 0xdbac6c247d62a583, 0xdf45f746b74abf39, - 0x894bc396ce5da772, 0x6b8bba8c328eb783, - 0xab9eb47c81f5114f, 0x66ea92f3f326564, - 0xd686619ba27255a2, 0xc80a537b0efefebd, - 0x8613fd0145877585, 0xbd06742ce95f5f36, - 0xa798fc4196e952e7, 0x2c48113823b73704, - 0xd17f3b51fca3a7a0, 0xf75a15862ca504c5, - 0x82ef85133de648c4, 0x9a984d73dbe722fb, - 0xa3ab66580d5fdaf5, 0xc13e60d0d2e0ebba, - 0xcc963fee10b7d1b3, 0x318df905079926a8, - 0xffbbcfe994e5c61f, 0xfdf17746497f7052, - 0x9fd561f1fd0f9bd3, 0xfeb6ea8bedefa633, - 0xc7caba6e7c5382c8, 0xfe64a52ee96b8fc0, - 0xf9bd690a1b68637b, 0x3dfdce7aa3c673b0, - 0x9c1661a651213e2d, 0x6bea10ca65c084e, - 0xc31bfa0fe5698db8, 0x486e494fcff30a62, - 0xf3e2f893dec3f126, 0x5a89dba3c3efccfa, - 0x986ddb5c6b3a76b7, 0xf89629465a75e01c, - 0xbe89523386091465, 0xf6bbb397f1135823, - 0xee2ba6c0678b597f, 0x746aa07ded582e2c, - 0x94db483840b717ef, 0xa8c2a44eb4571cdc, - 0xba121a4650e4ddeb, 0x92f34d62616ce413, - 0xe896a0d7e51e1566, 0x77b020baf9c81d17, - 0x915e2486ef32cd60, 0xace1474dc1d122e, - 0xb5b5ada8aaff80b8, 0xd819992132456ba, - 0xe3231912d5bf60e6, 0x10e1fff697ed6c69, - 0x8df5efabc5979c8f, 0xca8d3ffa1ef463c1, - 0xb1736b96b6fd83b3, 0xbd308ff8a6b17cb2, - 0xddd0467c64bce4a0, 0xac7cb3f6d05ddbde, - 0x8aa22c0dbef60ee4, 0x6bcdf07a423aa96b, - 0xad4ab7112eb3929d, 0x86c16c98d2c953c6, - 0xd89d64d57a607744, 0xe871c7bf077ba8b7, - 0x87625f056c7c4a8b, 0x11471cd764ad4972, - 0xa93af6c6c79b5d2d, 0xd598e40d3dd89bcf, - 0xd389b47879823479, 0x4aff1d108d4ec2c3, - 0x843610cb4bf160cb, 0xcedf722a585139ba, - 0xa54394fe1eedb8fe, 0xc2974eb4ee658828, - 0xce947a3da6a9273e, 0x733d226229feea32, - 0x811ccc668829b887, 0x806357d5a3f525f, - 0xa163ff802a3426a8, 0xca07c2dcb0cf26f7, - 0xc9bcff6034c13052, 0xfc89b393dd02f0b5, - 0xfc2c3f3841f17c67, 0xbbac2078d443ace2, - 0x9d9ba7832936edc0, 0xd54b944b84aa4c0d, - 0xc5029163f384a931, 0xa9e795e65d4df11, - 0xf64335bcf065d37d, 0x4d4617b5ff4a16d5, - 0x99ea0196163fa42e, 0x504bced1bf8e4e45, - 0xc06481fb9bcf8d39, 0xe45ec2862f71e1d6, - 0xf07da27a82c37088, 0x5d767327bb4e5a4c, - 0x964e858c91ba2655, 0x3a6a07f8d510f86f, - 0xbbe226efb628afea, 0x890489f70a55368b, - 0xeadab0aba3b2dbe5, 0x2b45ac74ccea842e, - 0x92c8ae6b464fc96f, 0x3b0b8bc90012929d, - 0xb77ada0617e3bbcb, 0x9ce6ebb40173744, - 0xe55990879ddcaabd, 0xcc420a6a101d0515, - 0x8f57fa54c2a9eab6, 0x9fa946824a12232d, - 0xb32df8e9f3546564, 0x47939822dc96abf9, - 0xdff9772470297ebd, 0x59787e2b93bc56f7, - 0x8bfbea76c619ef36, 0x57eb4edb3c55b65a, - 0xaefae51477a06b03, 0xede622920b6b23f1, - 0xdab99e59958885c4, 0xe95fab368e45eced, - 0x88b402f7fd75539b, 0x11dbcb0218ebb414, - 0xaae103b5fcd2a881, 0xd652bdc29f26a119, - 0xd59944a37c0752a2, 0x4be76d3346f0495f, - 0x857fcae62d8493a5, 0x6f70a4400c562ddb, - 0xa6dfbd9fb8e5b88e, 0xcb4ccd500f6bb952, - 0xd097ad07a71f26b2, 0x7e2000a41346a7a7, - 0x825ecc24c873782f, 0x8ed400668c0c28c8, - 0xa2f67f2dfa90563b, 0x728900802f0f32fa, - 0xcbb41ef979346bca, 0x4f2b40a03ad2ffb9, - 0xfea126b7d78186bc, 0xe2f610c84987bfa8, - 0x9f24b832e6b0f436, 0xdd9ca7d2df4d7c9, - 0xc6ede63fa05d3143, 0x91503d1c79720dbb, - 0xf8a95fcf88747d94, 0x75a44c6397ce912a, - 0x9b69dbe1b548ce7c, 0xc986afbe3ee11aba, - 0xc24452da229b021b, 0xfbe85badce996168, - 0xf2d56790ab41c2a2, 0xfae27299423fb9c3, - 0x97c560ba6b0919a5, 0xdccd879fc967d41a, - 0xbdb6b8e905cb600f, 0x5400e987bbc1c920, - 0xed246723473e3813, 0x290123e9aab23b68, - 0x9436c0760c86e30b, 0xf9a0b6720aaf6521, - 0xb94470938fa89bce, 0xf808e40e8d5b3e69, - 0xe7958cb87392c2c2, 0xb60b1d1230b20e04, - 0x90bd77f3483bb9b9, 0xb1c6f22b5e6f48c2, - 0xb4ecd5f01a4aa828, 0x1e38aeb6360b1af3, - 0xe2280b6c20dd5232, 0x25c6da63c38de1b0, - 0x8d590723948a535f, 0x579c487e5a38ad0e, - 0xb0af48ec79ace837, 0x2d835a9df0c6d851, - 0xdcdb1b2798182244, 0xf8e431456cf88e65, - 0x8a08f0f8bf0f156b, 0x1b8e9ecb641b58ff, - 0xac8b2d36eed2dac5, 0xe272467e3d222f3f, - 0xd7adf884aa879177, 0x5b0ed81dcc6abb0f, - 0x86ccbb52ea94baea, 0x98e947129fc2b4e9, - 0xa87fea27a539e9a5, 0x3f2398d747b36224, - 0xd29fe4b18e88640e, 0x8eec7f0d19a03aad, - 0x83a3eeeef9153e89, 0x1953cf68300424ac, - 0xa48ceaaab75a8e2b, 0x5fa8c3423c052dd7, - 0xcdb02555653131b6, 0x3792f412cb06794d, - 0x808e17555f3ebf11, 0xe2bbd88bbee40bd0, - 0xa0b19d2ab70e6ed6, 0x5b6aceaeae9d0ec4, - 0xc8de047564d20a8b, 0xf245825a5a445275, - 0xfb158592be068d2e, 0xeed6e2f0f0d56712, - 0x9ced737bb6c4183d, 0x55464dd69685606b, - 0xc428d05aa4751e4c, 0xaa97e14c3c26b886, - 0xf53304714d9265df, 0xd53dd99f4b3066a8, - 0x993fe2c6d07b7fab, 0xe546a8038efe4029, - 0xbf8fdb78849a5f96, 0xde98520472bdd033, - 0xef73d256a5c0f77c, 0x963e66858f6d4440, - 0x95a8637627989aad, 0xdde7001379a44aa8, - 0xbb127c53b17ec159, 0x5560c018580d5d52, - 0xe9d71b689dde71af, 0xaab8f01e6e10b4a6, - 0x9226712162ab070d, 0xcab3961304ca70e8, - 0xb6b00d69bb55c8d1, 0x3d607b97c5fd0d22, - 0xe45c10c42a2b3b05, 0x8cb89a7db77c506a, - 0x8eb98a7a9a5b04e3, 0x77f3608e92adb242, - 0xb267ed1940f1c61c, 0x55f038b237591ed3, - 0xdf01e85f912e37a3, 0x6b6c46dec52f6688, - 0x8b61313bbabce2c6, 0x2323ac4b3b3da015, - 0xae397d8aa96c1b77, 0xabec975e0a0d081a, - 0xd9c7dced53c72255, 0x96e7bd358c904a21, - 0x881cea14545c7575, 0x7e50d64177da2e54, - 0xaa242499697392d2, 0xdde50bd1d5d0b9e9, - 0xd4ad2dbfc3d07787, 0x955e4ec64b44e864, - 0x84ec3c97da624ab4, 0xbd5af13bef0b113e, - 0xa6274bbdd0fadd61, 0xecb1ad8aeacdd58e, - 0xcfb11ead453994ba, 0x67de18eda5814af2, - 0x81ceb32c4b43fcf4, 0x80eacf948770ced7, - 0xa2425ff75e14fc31, 0xa1258379a94d028d, - 0xcad2f7f5359a3b3e, 0x96ee45813a04330, - 0xfd87b5f28300ca0d, 0x8bca9d6e188853fc, - 0x9e74d1b791e07e48, 0x775ea264cf55347e, - 0xc612062576589dda, 0x95364afe032a819e, - 0xf79687aed3eec551, 0x3a83ddbd83f52205, - 0x9abe14cd44753b52, 0xc4926a9672793543, - 0xc16d9a0095928a27, 0x75b7053c0f178294, - 0xf1c90080baf72cb1, 0x5324c68b12dd6339, - 0x971da05074da7bee, 0xd3f6fc16ebca5e04, - 0xbce5086492111aea, 0x88f4bb1ca6bcf585, - 0xec1e4a7db69561a5, 0x2b31e9e3d06c32e6, - 0x9392ee8e921d5d07, 0x3aff322e62439fd0, - 0xb877aa3236a4b449, 0x9befeb9fad487c3, - 0xe69594bec44de15b, 0x4c2ebe687989a9b4, - 0x901d7cf73ab0acd9, 0xf9d37014bf60a11, - 0xb424dc35095cd80f, 0x538484c19ef38c95, - 0xe12e13424bb40e13, 0x2865a5f206b06fba, - 0x8cbccc096f5088cb, 0xf93f87b7442e45d4, - 0xafebff0bcb24aafe, 0xf78f69a51539d749, - 0xdbe6fecebdedd5be, 0xb573440e5a884d1c, - 0x89705f4136b4a597, 0x31680a88f8953031, - 0xabcc77118461cefc, 0xfdc20d2b36ba7c3e, - 0xd6bf94d5e57a42bc, 0x3d32907604691b4d, - 0x8637bd05af6c69b5, 0xa63f9a49c2c1b110, - 0xa7c5ac471b478423, 0xfcf80dc33721d54, - 0xd1b71758e219652b, 0xd3c36113404ea4a9, - 0x83126e978d4fdf3b, 0x645a1cac083126ea, - 0xa3d70a3d70a3d70a, 0x3d70a3d70a3d70a4, - 0xcccccccccccccccc, 0xcccccccccccccccd, - 0x8000000000000000, 0x0, - 0xa000000000000000, 0x0, - 0xc800000000000000, 0x0, - 0xfa00000000000000, 0x0, - 0x9c40000000000000, 0x0, - 0xc350000000000000, 0x0, - 0xf424000000000000, 0x0, - 0x9896800000000000, 0x0, - 0xbebc200000000000, 0x0, - 0xee6b280000000000, 0x0, - 0x9502f90000000000, 0x0, - 0xba43b74000000000, 0x0, - 0xe8d4a51000000000, 0x0, - 0x9184e72a00000000, 0x0, - 0xb5e620f480000000, 0x0, - 0xe35fa931a0000000, 0x0, - 0x8e1bc9bf04000000, 0x0, - 0xb1a2bc2ec5000000, 0x0, - 0xde0b6b3a76400000, 0x0, - 0x8ac7230489e80000, 0x0, - 0xad78ebc5ac620000, 0x0, - 0xd8d726b7177a8000, 0x0, - 0x878678326eac9000, 0x0, - 0xa968163f0a57b400, 0x0, - 0xd3c21bcecceda100, 0x0, - 0x84595161401484a0, 0x0, - 0xa56fa5b99019a5c8, 0x0, - 0xcecb8f27f4200f3a, 0x0, - 0x813f3978f8940984, 0x4000000000000000, - 0xa18f07d736b90be5, 0x5000000000000000, - 0xc9f2c9cd04674ede, 0xa400000000000000, - 0xfc6f7c4045812296, 0x4d00000000000000, - 0x9dc5ada82b70b59d, 0xf020000000000000, - 0xc5371912364ce305, 0x6c28000000000000, - 0xf684df56c3e01bc6, 0xc732000000000000, - 0x9a130b963a6c115c, 0x3c7f400000000000, - 0xc097ce7bc90715b3, 0x4b9f100000000000, - 0xf0bdc21abb48db20, 0x1e86d40000000000, - 0x96769950b50d88f4, 0x1314448000000000, - 0xbc143fa4e250eb31, 0x17d955a000000000, - 0xeb194f8e1ae525fd, 0x5dcfab0800000000, - 0x92efd1b8d0cf37be, 0x5aa1cae500000000, - 0xb7abc627050305ad, 0xf14a3d9e40000000, - 0xe596b7b0c643c719, 0x6d9ccd05d0000000, - 0x8f7e32ce7bea5c6f, 0xe4820023a2000000, - 0xb35dbf821ae4f38b, 0xdda2802c8a800000, - 0xe0352f62a19e306e, 0xd50b2037ad200000, - 0x8c213d9da502de45, 0x4526f422cc340000, - 0xaf298d050e4395d6, 0x9670b12b7f410000, - 0xdaf3f04651d47b4c, 0x3c0cdd765f114000, - 0x88d8762bf324cd0f, 0xa5880a69fb6ac800, - 0xab0e93b6efee0053, 0x8eea0d047a457a00, - 0xd5d238a4abe98068, 0x72a4904598d6d880, - 0x85a36366eb71f041, 0x47a6da2b7f864750, - 0xa70c3c40a64e6c51, 0x999090b65f67d924, - 0xd0cf4b50cfe20765, 0xfff4b4e3f741cf6d, - 0x82818f1281ed449f, 0xbff8f10e7a8921a4, - 0xa321f2d7226895c7, 0xaff72d52192b6a0d, - 0xcbea6f8ceb02bb39, 0x9bf4f8a69f764490, - 0xfee50b7025c36a08, 0x2f236d04753d5b4, - 0x9f4f2726179a2245, 0x1d762422c946590, - 0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef5, - 0xf8ebad2b84e0d58b, 0xd2e0898765a7deb2, - 0x9b934c3b330c8577, 0x63cc55f49f88eb2f, - 0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fb, - 0xf316271c7fc3908a, 0x8bef464e3945ef7a, - 0x97edd871cfda3a56, 0x97758bf0e3cbb5ac, - 0xbde94e8e43d0c8ec, 0x3d52eeed1cbea317, - 0xed63a231d4c4fb27, 0x4ca7aaa863ee4bdd, - 0x945e455f24fb1cf8, 0x8fe8caa93e74ef6a, - 0xb975d6b6ee39e436, 0xb3e2fd538e122b44, - 0xe7d34c64a9c85d44, 0x60dbbca87196b616, - 0x90e40fbeea1d3a4a, 0xbc8955e946fe31cd, - 0xb51d13aea4a488dd, 0x6babab6398bdbe41, - 0xe264589a4dcdab14, 0xc696963c7eed2dd1, - 0x8d7eb76070a08aec, 0xfc1e1de5cf543ca2, - 0xb0de65388cc8ada8, 0x3b25a55f43294bcb, - 0xdd15fe86affad912, 0x49ef0eb713f39ebe, - 0x8a2dbf142dfcc7ab, 0x6e3569326c784337, - 0xacb92ed9397bf996, 0x49c2c37f07965404, - 0xd7e77a8f87daf7fb, 0xdc33745ec97be906, - 0x86f0ac99b4e8dafd, 0x69a028bb3ded71a3, - 0xa8acd7c0222311bc, 0xc40832ea0d68ce0c, - 0xd2d80db02aabd62b, 0xf50a3fa490c30190, - 0x83c7088e1aab65db, 0x792667c6da79e0fa, - 0xa4b8cab1a1563f52, 0x577001b891185938, - 0xcde6fd5e09abcf26, 0xed4c0226b55e6f86, - 0x80b05e5ac60b6178, 0x544f8158315b05b4, - 0xa0dc75f1778e39d6, 0x696361ae3db1c721, - 0xc913936dd571c84c, 0x3bc3a19cd1e38e9, - 0xfb5878494ace3a5f, 0x4ab48a04065c723, - 0x9d174b2dcec0e47b, 0x62eb0d64283f9c76, - 0xc45d1df942711d9a, 0x3ba5d0bd324f8394, - 0xf5746577930d6500, 0xca8f44ec7ee36479, - 0x9968bf6abbe85f20, 0x7e998b13cf4e1ecb, - 0xbfc2ef456ae276e8, 0x9e3fedd8c321a67e, - 0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101e, - 0x95d04aee3b80ece5, 0xbba1f1d158724a12, - 0xbb445da9ca61281f, 0x2a8a6e45ae8edc97, - 0xea1575143cf97226, 0xf52d09d71a3293bd, - 0x924d692ca61be758, 0x593c2626705f9c56, - 0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836c, - 0xe498f455c38b997a, 0xb6dfb9c0f956447, - 0x8edf98b59a373fec, 0x4724bd4189bd5eac, - 0xb2977ee300c50fe7, 0x58edec91ec2cb657, - 0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ed, - 0x8b865b215899f46c, 0xbd79e0d20082ee74, - 0xae67f1e9aec07187, 0xecd8590680a3aa11, - 0xda01ee641a708de9, 0xe80e6f4820cc9495, - 0x884134fe908658b2, 0x3109058d147fdcdd, - 0xaa51823e34a7eede, 0xbd4b46f0599fd415, - 0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91a, - 0x850fadc09923329e, 0x3e2cf6bc604ddb0, - 0xa6539930bf6bff45, 0x84db8346b786151c, - 0xcfe87f7cef46ff16, 0xe612641865679a63, - 0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07e, - 0xa26da3999aef7749, 0xe3be5e330f38f09d, - 0xcb090c8001ab551c, 0x5cadf5bfd3072cc5, - 0xfdcb4fa002162a63, 0x73d9732fc7c8f7f6, - 0x9e9f11c4014dda7e, 0x2867e7fddcdd9afa, - 0xc646d63501a1511d, 0xb281e1fd541501b8, - 0xf7d88bc24209a565, 0x1f225a7ca91a4226, - 0x9ae757596946075f, 0x3375788de9b06958, - 0xc1a12d2fc3978937, 0x52d6b1641c83ae, - 0xf209787bb47d6b84, 0xc0678c5dbd23a49a, - 0x9745eb4d50ce6332, 0xf840b7ba963646e0, - 0xbd176620a501fbff, 0xb650e5a93bc3d898, - 0xec5d3fa8ce427aff, 0xa3e51f138ab4cebe, - 0x93ba47c980e98cdf, 0xc66f336c36b10137, - 0xb8a8d9bbe123f017, 0xb80b0047445d4184, - 0xe6d3102ad96cec1d, 0xa60dc059157491e5, - 0x9043ea1ac7e41392, 0x87c89837ad68db2f, - 0xb454e4a179dd1877, 0x29babe4598c311fb, - 0xe16a1dc9d8545e94, 0xf4296dd6fef3d67a, - 0x8ce2529e2734bb1d, 0x1899e4a65f58660c, - 0xb01ae745b101e9e4, 0x5ec05dcff72e7f8f, - 0xdc21a1171d42645d, 0x76707543f4fa1f73, - 0x899504ae72497eba, 0x6a06494a791c53a8, - 0xabfa45da0edbde69, 0x487db9d17636892, - 0xd6f8d7509292d603, 0x45a9d2845d3c42b6, - 0x865b86925b9bc5c2, 0xb8a2392ba45a9b2, - 0xa7f26836f282b732, 0x8e6cac7768d7141e, - 0xd1ef0244af2364ff, 0x3207d795430cd926, - 0x8335616aed761f1f, 0x7f44e6bd49e807b8, - 0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a6, - 0xcd036837130890a1, 0x36dba887c37a8c0f, - 0x802221226be55a64, 0xc2494954da2c9789, - 0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6c, - 0xc83553c5c8965d3d, 0x6f92829494e5acc7, - 0xfa42a8b73abbf48c, 0xcb772339ba1f17f9, - 0x9c69a97284b578d7, 0xff2a760414536efb, - 0xc38413cf25e2d70d, 0xfef5138519684aba, - 0xf46518c2ef5b8cd1, 0x7eb258665fc25d69, - 0x98bf2f79d5993802, 0xef2f773ffbd97a61, - 0xbeeefb584aff8603, 0xaafb550ffacfd8fa, - 0xeeaaba2e5dbf6784, 0x95ba2a53f983cf38, - 0x952ab45cfa97a0b2, 0xdd945a747bf26183, - 0xba756174393d88df, 0x94f971119aeef9e4, - 0xe912b9d1478ceb17, 0x7a37cd5601aab85d, - 0x91abb422ccb812ee, 0xac62e055c10ab33a, - 0xb616a12b7fe617aa, 0x577b986b314d6009, - 0xe39c49765fdf9d94, 0xed5a7e85fda0b80b, - 0x8e41ade9fbebc27d, 0x14588f13be847307, - 0xb1d219647ae6b31c, 0x596eb2d8ae258fc8, - 0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bb, - 0x8aec23d680043bee, 0x25de7bb9480d5854, - 0xada72ccc20054ae9, 0xaf561aa79a10ae6a, - 0xd910f7ff28069da4, 0x1b2ba1518094da04, - 0x87aa9aff79042286, 0x90fb44d2f05d0842, - 0xa99541bf57452b28, 0x353a1607ac744a53, - 0xd3fa922f2d1675f2, 0x42889b8997915ce8, - 0x847c9b5d7c2e09b7, 0x69956135febada11, - 0xa59bc234db398c25, 0x43fab9837e699095, - 0xcf02b2c21207ef2e, 0x94f967e45e03f4bb, - 0x8161afb94b44f57d, 0x1d1be0eebac278f5, - 0xa1ba1ba79e1632dc, 0x6462d92a69731732, - 0xca28a291859bbf93, 0x7d7b8f7503cfdcfe, - 0xfcb2cb35e702af78, 0x5cda735244c3d43e, - 0x9defbf01b061adab, 0x3a0888136afa64a7, - 0xc56baec21c7a1916, 0x88aaa1845b8fdd0, - 0xf6c69a72a3989f5b, 0x8aad549e57273d45, - 0x9a3c2087a63f6399, 0x36ac54e2f678864b, - 0xc0cb28a98fcf3c7f, 0x84576a1bb416a7dd, - 0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d5, - 0x969eb7c47859e743, 0x9f644ae5a4b1b325, - 0xbc4665b596706114, 0x873d5d9f0dde1fee, - 0xeb57ff22fc0c7959, 0xa90cb506d155a7ea, - 0x9316ff75dd87cbd8, 0x9a7f12442d588f2, - 0xb7dcbf5354e9bece, 0xc11ed6d538aeb2f, - 0xe5d3ef282a242e81, 0x8f1668c8a86da5fa, - 0x8fa475791a569d10, 0xf96e017d694487bc, - 0xb38d92d760ec4455, 0x37c981dcc395a9ac, - 0xe070f78d3927556a, 0x85bbe253f47b1417, - 0x8c469ab843b89562, 0x93956d7478ccec8e, - 0xaf58416654a6babb, 0x387ac8d1970027b2, - 0xdb2e51bfe9d0696a, 0x6997b05fcc0319e, - 0x88fcf317f22241e2, 0x441fece3bdf81f03, - 0xab3c2fddeeaad25a, 0xd527e81cad7626c3, - 0xd60b3bd56a5586f1, 0x8a71e223d8d3b074, - 0x85c7056562757456, 0xf6872d5667844e49, - 0xa738c6bebb12d16c, 0xb428f8ac016561db, - 0xd106f86e69d785c7, 0xe13336d701beba52, - 0x82a45b450226b39c, 0xecc0024661173473, - 0xa34d721642b06084, 0x27f002d7f95d0190, - 0xcc20ce9bd35c78a5, 0x31ec038df7b441f4, - 0xff290242c83396ce, 0x7e67047175a15271, - 0x9f79a169bd203e41, 0xf0062c6e984d386, - 0xc75809c42c684dd1, 0x52c07b78a3e60868, - 0xf92e0c3537826145, 0xa7709a56ccdf8a82, - 0x9bbcc7a142b17ccb, 0x88a66076400bb691, - 0xc2abf989935ddbfe, 0x6acff893d00ea435, - 0xf356f7ebf83552fe, 0x583f6b8c4124d43, - 0x98165af37b2153de, 0xc3727a337a8b704a, - 0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5c, - 0xeda2ee1c7064130c, 0x1162def06f79df73, - 0x9485d4d1c63e8be7, 0x8addcb5645ac2ba8, - 0xb9a74a0637ce2ee1, 0x6d953e2bd7173692, - 0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0437, - 0x910ab1d4db9914a0, 0x1d9c9892400a22a2, - 0xb54d5e4a127f59c8, 0x2503beb6d00cab4b, - 0xe2a0b5dc971f303a, 0x2e44ae64840fd61d, - 0x8da471a9de737e24, 0x5ceaecfed289e5d2, - 0xb10d8e1456105dad, 0x7425a83e872c5f47, - 0xdd50f1996b947518, 0xd12f124e28f77719, - 0x8a5296ffe33cc92f, 0x82bd6b70d99aaa6f, - 0xace73cbfdc0bfb7b, 0x636cc64d1001550b, - 0xd8210befd30efa5a, 0x3c47f7e05401aa4e, - 0x8714a775e3e95c78, 0x65acfaec34810a71, - 0xa8d9d1535ce3b396, 0x7f1839a741a14d0d, - 0xd31045a8341ca07c, 0x1ede48111209a050, - 0x83ea2b892091e44d, 0x934aed0aab460432, - 0xa4e4b66b68b65d60, 0xf81da84d5617853f, - 0xce1de40642e3f4b9, 0x36251260ab9d668e, - 0x80d2ae83e9ce78f3, 0xc1d72b7c6b426019, - 0xa1075a24e4421730, 0xb24cf65b8612f81f, - 0xc94930ae1d529cfc, 0xdee033f26797b627, - 0xfb9b7cd9a4a7443c, 0x169840ef017da3b1, - 0x9d412e0806e88aa5, 0x8e1f289560ee864e, - 0xc491798a08a2ad4e, 0xf1a6f2bab92a27e2, - 0xf5b5d7ec8acb58a2, 0xae10af696774b1db, - 0x9991a6f3d6bf1765, 0xacca6da1e0a8ef29, - 0xbff610b0cc6edd3f, 0x17fd090a58d32af3, - 0xeff394dcff8a948e, 0xddfc4b4cef07f5b0, - 0x95f83d0a1fb69cd9, 0x4abdaf101564f98e, - 0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f1, - 0xea53df5fd18d5513, 0x84c86189216dc5ed, - 0x92746b9be2f8552c, 0x32fd3cf5b4e49bb4, - 0xb7118682dbb66a77, 0x3fbc8c33221dc2a1, - 0xe4d5e82392a40515, 0xfabaf3feaa5334a, - 0x8f05b1163ba6832d, 0x29cb4d87f2a7400e, - 0xb2c71d5bca9023f8, 0x743e20e9ef511012, - 0xdf78e4b2bd342cf6, 0x914da9246b255416, - 0x8bab8eefb6409c1a, 0x1ad089b6c2f7548e, - 0xae9672aba3d0c320, 0xa184ac2473b529b1, - 0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741e, - 0x8865899617fb1871, 0x7e2fa67c7a658892, - 0xaa7eebfb9df9de8d, 0xddbb901b98feeab7, - 0xd51ea6fa85785631, 0x552a74227f3ea565, - 0x8533285c936b35de, 0xd53a88958f87275f, - 0xa67ff273b8460356, 0x8a892abaf368f137, - 0xd01fef10a657842c, 0x2d2b7569b0432d85, - 0x8213f56a67f6b29b, 0x9c3b29620e29fc73, - 0xa298f2c501f45f42, 0x8349f3ba91b47b8f, - 0xcb3f2f7642717713, 0x241c70a936219a73, - 0xfe0efb53d30dd4d7, 0xed238cd383aa0110, - 0x9ec95d1463e8a506, 0xf4363804324a40aa, - 0xc67bb4597ce2ce48, 0xb143c6053edcd0d5, - 0xf81aa16fdc1b81da, 0xdd94b7868e94050a, - 0x9b10a4e5e9913128, 0xca7cf2b4191c8326, - 0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f0, - 0xf24a01a73cf2dccf, 0xbc633b39673c8cec, - 0x976e41088617ca01, 0xd5be0503e085d813, - 0xbd49d14aa79dbc82, 0x4b2d8644d8a74e18, - 0xec9c459d51852ba2, 0xddf8e7d60ed1219e, - 0x93e1ab8252f33b45, 0xcabb90e5c942b503, - 0xb8da1662e7b00a17, 0x3d6a751f3b936243, - 0xe7109bfba19c0c9d, 0xcc512670a783ad4, - 0x906a617d450187e2, 0x27fb2b80668b24c5, - 0xb484f9dc9641e9da, 0xb1f9f660802dedf6, - 0xe1a63853bbd26451, 0x5e7873f8a0396973, - 0x8d07e33455637eb2, 0xdb0b487b6423e1e8, - 0xb049dc016abc5e5f, 0x91ce1a9a3d2cda62, - 0xdc5c5301c56b75f7, 0x7641a140cc7810fb, - 0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9d, - 0xac2820d9623bf429, 0x546345fa9fbdcd44, - 0xd732290fbacaf133, 0xa97c177947ad4095, - 0x867f59a9d4bed6c0, 0x49ed8eabcccc485d, - 0xa81f301449ee8c70, 0x5c68f256bfff5a74, - 0xd226fc195c6a2f8c, 0x73832eec6fff3111, - 0x83585d8fd9c25db7, 0xc831fd53c5ff7eab, - 0xa42e74f3d032f525, 0xba3e7ca8b77f5e55, - 0xcd3a1230c43fb26f, 0x28ce1bd2e55f35eb, - 0x80444b5e7aa7cf85, 0x7980d163cf5b81b3, - 0xa0555e361951c366, 0xd7e105bcc332621f, - 0xc86ab5c39fa63440, 0x8dd9472bf3fefaa7, - 0xfa856334878fc150, 0xb14f98f6f0feb951, - 0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d3, - 0xc3b8358109e84f07, 0xa862f80ec4700c8, - 0xf4a642e14c6262c8, 0xcd27bb612758c0fa, - 0x98e7e9cccfbd7dbd, 0x8038d51cb897789c, - 0xbf21e44003acdd2c, 0xe0470a63e6bd56c3, - 0xeeea5d5004981478, 0x1858ccfce06cac74, - 0x95527a5202df0ccb, 0xf37801e0c43ebc8, - 0xbaa718e68396cffd, 0xd30560258f54e6ba, - 0xe950df20247c83fd, 0x47c6b82ef32a2069, - 0x91d28b7416cdd27e, 0x4cdc331d57fa5441, - 0xb6472e511c81471d, 0xe0133fe4adf8e952, - 0xe3d8f9e563a198e5, 0x58180fddd97723a6, - 0x8e679c2f5e44ff8f, 0x570f09eaa7ea7648, - }; -}; - -#if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE - -template -constexpr uint64_t - powers_template::power_of_five_128[number_of_entries]; - -#endif - -using powers = powers_template<>; - -} // namespace fast_float - -#endif diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/float_common.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/float_common.h deleted file mode 100644 index 1070603a81..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/float_common.h +++ /dev/null @@ -1,1419 +0,0 @@ -#ifndef FASTFLOAT_FLOAT_COMMON_H -#define FASTFLOAT_FLOAT_COMMON_H - -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef __has_include -#if __has_include() && (__cplusplus > 202002L || (defined(_MSVC_LANG) && (_MSVC_LANG > 202002L))) -#include -#endif -#endif -#include "constexpr_feature_detect.h" - -#define FASTFLOAT_VERSION_MAJOR 8 -#define FASTFLOAT_VERSION_MINOR 3 -#define FASTFLOAT_VERSION_PATCH 0 - -#define FASTFLOAT_STRINGIZE_IMPL(x) #x -#define FASTFLOAT_STRINGIZE(x) FASTFLOAT_STRINGIZE_IMPL(x) - -#define FASTFLOAT_VERSION_STR \ - FASTFLOAT_STRINGIZE(FASTFLOAT_VERSION_MAJOR) \ - "." FASTFLOAT_STRINGIZE(FASTFLOAT_VERSION_MINOR) "." FASTFLOAT_STRINGIZE( \ - FASTFLOAT_VERSION_PATCH) - -#define FASTFLOAT_VERSION \ - (FASTFLOAT_VERSION_MAJOR * 10000 + FASTFLOAT_VERSION_MINOR * 100 + \ - FASTFLOAT_VERSION_PATCH) - -namespace fast_float { - -enum class chars_format : uint64_t; - -namespace detail { -constexpr chars_format basic_json_fmt = chars_format(1 << 5); -constexpr chars_format basic_fortran_fmt = chars_format(1 << 6); -constexpr chars_format basic_javascript_fmt = chars_format(1 << 9); -constexpr chars_format basic_javascript_sloppy_fmt = chars_format(1 << 10); -} // namespace detail - -enum class chars_format : uint64_t { - scientific = 1 << 0, - fixed = 1 << 2, - hex = 1 << 3, - no_infnan = 1 << 4, - // RFC 8259: https://datatracker.ietf.org/doc/html/rfc8259#section-6 - json = uint64_t(detail::basic_json_fmt) | fixed | scientific | no_infnan, - // Extension of RFC 8259 where, e.g., "inf" and "nan" are allowed. - json_or_infnan = uint64_t(detail::basic_json_fmt) | fixed | scientific, - fortran = uint64_t(detail::basic_fortran_fmt) | fixed | scientific, - general = fixed | scientific, - allow_leading_plus = 1 << 7, - skip_white_space = 1 << 8, - // ECMAScript DecimalLiteral (strict mode): - // https://tc39.es/ecma262/#prod-DecimalLiteral - // Like JSON, the integer part must not have leading zeros ("01" is - // rejected), but unlike JSON the integer part may be empty (".5") and the - // fractional part may be empty ("5.", "5.e3"). A leading minus sign is - // accepted, and a leading plus sign with allow_leading_plus. - javascript = - uint64_t(detail::basic_javascript_fmt) | fixed | scientific | no_infnan, - // ECMAScript DecimalLiteral in sloppy mode, which adds Annex B's - // NonOctalDecimalIntegerLiteral: a leading zero is accepted when one of - // the digits is 8 or 9 ("08.5" is 8.5). A leading zero followed only by - // octal digits is a LegacyOctalIntegerLiteral ("0775"): it is not a - // decimal number, so it is rejected with legacy_octal_integer_part and the - // caller may parse it in base 8. - // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals - javascript_sloppy = uint64_t(detail::basic_javascript_fmt) | - uint64_t(detail::basic_javascript_sloppy_fmt) | fixed | - scientific | no_infnan, -}; - -template struct from_chars_result_t { - UC const *ptr; - std::errc ec; - - // https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2497r0.html - constexpr explicit operator bool() const noexcept { - return ec == std::errc(); - } -}; - -using from_chars_result = from_chars_result_t; - -template struct parse_options_t { - constexpr explicit parse_options_t(chars_format fmt = chars_format::general, - UC dot = UC('.'), int b = 10) - : format(fmt), decimal_point(dot), base(b) {} - - /** Which number formats are accepted */ - chars_format format; - /** The character used as decimal point */ - UC decimal_point; - /** The base used for integers */ - int base; -}; - -using parse_options = parse_options_t; - -} // namespace fast_float - -#if FASTFLOAT_HAS_BIT_CAST -#include -#endif - -#if (defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ - defined(__amd64) || defined(__aarch64__) || defined(_M_ARM64) || \ - defined(__MINGW64__) || defined(__s390x__) || \ - (defined(__ppc64__) || defined(__PPC64__) || defined(__ppc64le__) || \ - defined(__PPC64LE__)) || \ - defined(__loongarch64) || (defined(__riscv) && __riscv_xlen == 64)) -#define FASTFLOAT_64BIT 1 -#elif (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \ - defined(__arm__) || defined(_M_ARM) || defined(__ppc__) || \ - defined(__MINGW32__) || defined(__EMSCRIPTEN__) || \ - (defined(__riscv) && __riscv_xlen == 32)) -#define FASTFLOAT_32BIT 1 -#else - // Need to check incrementally, since SIZE_MAX is a size_t, avoid overflow. -// We can never tell the register width, but the SIZE_MAX is a good -// approximation. UINTPTR_MAX and INTPTR_MAX are optional, so avoid them for max -// portability. -#if SIZE_MAX == 0xffff -#error Unknown platform (16-bit, unsupported) -#elif SIZE_MAX == 0xffffffff -#define FASTFLOAT_32BIT 1 -#elif SIZE_MAX == 0xffffffffffffffff -#define FASTFLOAT_64BIT 1 -#else -#error Unknown platform (not 32-bit, not 64-bit?) -#endif -#endif - -#if ((defined(_WIN32) || defined(_WIN64)) && !defined(__clang__)) || \ - (defined(_M_ARM64) && !defined(__MINGW32__)) -#include -#endif - -#if defined(_MSC_VER) && !defined(__clang__) -#define FASTFLOAT_VISUAL_STUDIO 1 -#endif - -#if defined __BYTE_ORDER__ && defined __ORDER_BIG_ENDIAN__ -#define FASTFLOAT_IS_BIG_ENDIAN (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) -#elif defined _WIN32 -#define FASTFLOAT_IS_BIG_ENDIAN 0 -#else -#if defined(__APPLE__) || defined(__FreeBSD__) -#include -#elif defined(sun) || defined(__sun) -#include -#elif defined(__MVS__) -#include -#else -#ifdef __has_include -#if __has_include() -#include -#endif //__has_include() -#endif //__has_include -#endif -# -#ifndef __BYTE_ORDER__ -// safe choice -#define FASTFLOAT_IS_BIG_ENDIAN 0 -#endif -# -#ifndef __ORDER_LITTLE_ENDIAN__ -// safe choice -#define FASTFLOAT_IS_BIG_ENDIAN 0 -#endif -# -#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ -#define FASTFLOAT_IS_BIG_ENDIAN 0 -#else -#define FASTFLOAT_IS_BIG_ENDIAN 1 -#endif -#endif - -#if defined(__SSE2__) || (defined(FASTFLOAT_VISUAL_STUDIO) && \ - (defined(_M_AMD64) || defined(_M_X64) || \ - (defined(_M_IX86_FP) && _M_IX86_FP == 2))) -#define FASTFLOAT_SSE2 1 -#endif - -#if defined(__aarch64__) || defined(_M_ARM64) -#define FASTFLOAT_NEON 1 -#endif - -#if defined(FASTFLOAT_SSE2) || defined(FASTFLOAT_NEON) -#define FASTFLOAT_HAS_SIMD 1 -#endif - -#if defined(__GNUC__) -// disable -Wcast-align=strict (GCC only) -#define FASTFLOAT_SIMD_DISABLE_WARNINGS \ - _Pragma("GCC diagnostic push") \ - _Pragma("GCC diagnostic ignored \"-Wcast-align\"") -#else -#define FASTFLOAT_SIMD_DISABLE_WARNINGS -#endif - -#if defined(__GNUC__) -#define FASTFLOAT_SIMD_RESTORE_WARNINGS _Pragma("GCC diagnostic pop") -#else -#define FASTFLOAT_SIMD_RESTORE_WARNINGS -#endif - -#ifdef FASTFLOAT_VISUAL_STUDIO -#define fastfloat_really_inline __forceinline -#else -#define fastfloat_really_inline inline __attribute__((always_inline)) -#endif - -// Opposite of fastfloat_really_inline. Used for a rare, format-specific variant -// of a force-inlined function, so that its body does not land in the frame of -// every caller that will never execute it. -#ifdef FASTFLOAT_VISUAL_STUDIO -#define fastfloat_never_inline __declspec(noinline) -#elif defined(__GNUC__) || defined(__clang__) -#define fastfloat_never_inline __attribute__((noinline)) -#else -#define fastfloat_never_inline -#endif - -// fastfloat_really_inline under clang only, a no-op elsewhere. Clang declines -// to inline the parser into its callers, so the parser instantiation with a -// compile-time format (from_chars_fixed_format) must force the one thin -// forwarder between it and the parser body. GCC inlines the chain on its own, -// and forcing it there changes its inlining order for the worse. -#ifdef __clang__ -#define fastfloat_clang_really_inline fastfloat_really_inline -#else -#define fastfloat_clang_really_inline -#endif - -// fastfloat_unlikely under clang only, a plain condition elsewhere. Clang -// if-converts rare checks into chains of conditional moves that every -// conversion executes; the hint keeps them as branches. GCC already emits -// branches there, and the hint only reorders its blocks, for the worse. -#ifdef __clang__ -#define fastfloat_clang_unlikely(x) fastfloat_unlikely(x) -#else -#define fastfloat_clang_unlikely(x) (x) -#endif - -// Branch-probability hint marking the rare slow-path branches as cold, so the -// optimizer keeps the out-of-line slow-path re-parse off the hot path (and does -// not duplicate the force-inlined hot scanner into the caller, which bloated -// the hot frame and hurt ILP on some targets). Used at the call site as -// if fastfloat_unlikely(cond) { ... } -// (the macro supplies the parentheses). It expands to the standard [[unlikely]] -// attribute when supported, otherwise to __builtin_expect on GCC/Clang, or -// to a no-op elsewhere (e.g. pre-C++20 MSVC, which has no equivalent hint). -#ifdef __has_cpp_attribute -#if __has_cpp_attribute(unlikely) >= 201803L -// g++-9 hits hits this branch, but then fails to compile -// [[unlikely]]. This happens only with g++-9. -#if !defined(__GNUC__) || (__GNUC__ != 9) -#define FASTFLOAT_USE_UNLIKELY_ATTR -#endif -#endif -#endif - -#ifdef FASTFLOAT_USE_UNLIKELY_ATTR -#define fastfloat_unlikely(x) (x) [[unlikely]] -#elif defined(__GNUC__) || defined(__clang__) -#define fastfloat_unlikely(x) (__builtin_expect(!!(x), 0)) -#else -#define fastfloat_unlikely(x) (x) -#endif - -#ifndef FASTFLOAT_ASSERT -#define FASTFLOAT_ASSERT(x) \ - { static_cast(x); } -#endif - -#ifndef FASTFLOAT_DEBUG_ASSERT -#define FASTFLOAT_DEBUG_ASSERT(x) \ - { static_cast(x); } -#endif - -// rust style `try!()` macro, or `?` operator -#define FASTFLOAT_TRY(x) \ - { \ - if (!(x)) \ - return false; \ - } - -#define FASTFLOAT_ENABLE_IF(...) \ - typename std::enable_if<(__VA_ARGS__), int>::type - -namespace fast_float { - -fastfloat_really_inline constexpr bool cpp20_and_in_constexpr() { -#if FASTFLOAT_HAS_IS_CONSTANT_EVALUATED - return std::is_constant_evaluated(); -#else - return false; -#endif -} - -template -struct is_supported_float_type - : std::integral_constant< - bool, std::is_same::value || std::is_same::value -#ifdef __STDCPP_FLOAT64_T__ - || std::is_same::value -#endif -#ifdef __STDCPP_FLOAT32_T__ - || std::is_same::value -#endif -#ifdef __STDCPP_FLOAT16_T__ - || std::is_same::value -#endif -#ifdef __STDCPP_BFLOAT16_T__ - || std::is_same::value -#endif - > { -}; - -template -using equiv_uint_t = typename std::conditional< - sizeof(T) == 1, uint8_t, - typename std::conditional< - sizeof(T) == 2, uint16_t, - typename std::conditional::type>::type>::type; - -template struct is_supported_integer_type : std::is_integral {}; - -template -struct is_supported_char_type - : std::integral_constant::value || - std::is_same::value || - std::is_same::value || - std::is_same::value -#ifdef __cpp_char8_t - || std::is_same::value -#endif - > { -}; - -// Compares two ASCII strings in a case insensitive manner. The expected -// string is lowercase ASCII, so OR-ing 0x20 into each actual character maps -// 'A'..'Z' onto 'a'..'z' and leaves everything else mismatched. The lengths -// used are tiny constants (3 and 5), so the compiler unrolls this loop; keep -// it small so that the (rarely executed) inf/nan path does not bloat the hot -// parser it is inlined into. -template -inline FASTFLOAT_CONSTEXPR14 bool -fastfloat_strncasecmp(UC const *actual_mixedcase, UC const *expected_lowercase, - size_t length) { - for (size_t i = 0; i < length; ++i) { - if ((actual_mixedcase[i] | 32) != expected_lowercase[i]) { - return false; - } - } - return true; -} - -#ifndef FLT_EVAL_METHOD -#error "FLT_EVAL_METHOD should be defined, please include cfloat." -#endif - -// a pointer and a length to a contiguous block of memory -template struct span { - T const *ptr; - size_t length; - - constexpr span(T const *_ptr, size_t _length) : ptr(_ptr), length(_length) {} - - constexpr span() : ptr(nullptr), length(0) {} - - constexpr size_t len() const noexcept { return length; } - - FASTFLOAT_CONSTEXPR14 const T &operator[](size_t index) const noexcept { - FASTFLOAT_DEBUG_ASSERT(index < length); - return ptr[index]; - } -}; - -struct value128 { - uint64_t low; - uint64_t high; - - constexpr value128(uint64_t _low, uint64_t _high) : low(_low), high(_high) {} - - constexpr value128() : low(0), high(0) {} -}; - -/* Helper C++14 constexpr generic implementation of leading_zeroes */ -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 int -leading_zeroes_generic(uint64_t input_num, int last_bit = 0) { - if (input_num & uint64_t(0xffffffff00000000)) { - input_num >>= 32; - last_bit |= 32; - } - if (input_num & uint64_t(0xffff0000)) { - input_num >>= 16; - last_bit |= 16; - } - if (input_num & uint64_t(0xff00)) { - input_num >>= 8; - last_bit |= 8; - } - if (input_num & uint64_t(0xf0)) { - input_num >>= 4; - last_bit |= 4; - } - if (input_num & uint64_t(0xc)) { - input_num >>= 2; - last_bit |= 2; - } - if (input_num & uint64_t(0x2)) { /* input_num >>= 1; */ - last_bit |= 1; - } - return 63 - last_bit; -} - -/* result might be undefined when input_num is zero */ -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 int -leading_zeroes(uint64_t input_num) { - assert(input_num > 0); - if (cpp20_and_in_constexpr()) { - return leading_zeroes_generic(input_num); - } -#ifdef FASTFLOAT_VISUAL_STUDIO -#if defined(_M_X64) || defined(_M_ARM64) - unsigned long leading_zero = 0; - // Search the mask data from most significant bit (MSB) - // to least significant bit (LSB) for a set bit (1). - _BitScanReverse64(&leading_zero, input_num); - return static_cast(63 - leading_zero); -#else - return leading_zeroes_generic(input_num); -#endif -#else - return __builtin_clzll(input_num); -#endif -} - -/* Helper C++14 constexpr generic implementation of countr_zero for 32-bit */ -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 int -countr_zero_generic_32(uint32_t input_num) { - if (input_num == 0) { - return 32; - } - int last_bit = 0; - if (!(input_num & 0x0000FFFF)) { - input_num >>= 16; - last_bit |= 16; - } - if (!(input_num & 0x00FF)) { - input_num >>= 8; - last_bit |= 8; - } - if (!(input_num & 0x0F)) { - input_num >>= 4; - last_bit |= 4; - } - if (!(input_num & 0x3)) { - input_num >>= 2; - last_bit |= 2; - } - if (!(input_num & 0x1)) { - last_bit |= 1; - } - return last_bit; -} - -/* count trailing zeroes for 32-bit integers */ -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 int -countr_zero_32(uint32_t input_num) { - if (cpp20_and_in_constexpr()) { - return countr_zero_generic_32(input_num); - } -#ifdef FASTFLOAT_VISUAL_STUDIO - unsigned long trailing_zero = 0; - if (_BitScanForward(&trailing_zero, input_num)) { - return static_cast(trailing_zero); - } - return 32; -#else - return input_num == 0 ? 32 : __builtin_ctz(input_num); -#endif -} - -// slow emulation routine for 32-bit -fastfloat_really_inline constexpr uint64_t emulu(uint32_t x, uint32_t y) { - return x * static_cast(y); -} - -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 uint64_t -umul128_generic(uint64_t ab, uint64_t cd, uint64_t *hi) { - uint64_t ad = - emulu(static_cast(ab >> 32), static_cast(cd)); - uint64_t bd = emulu(static_cast(ab), static_cast(cd)); - uint64_t adbc = - ad + emulu(static_cast(ab), static_cast(cd >> 32)); - uint64_t adbc_carry = static_cast(adbc < ad); - uint64_t lo = bd + (adbc << 32); - *hi = - emulu(static_cast(ab >> 32), static_cast(cd >> 32)) + - (adbc >> 32) + (adbc_carry << 32) + static_cast(lo < bd); - return lo; -} - -#ifdef FASTFLOAT_32BIT - -// slow emulation routine for 32-bit -#if !defined(__MINGW64__) -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 uint64_t _umul128(uint64_t ab, - uint64_t cd, - uint64_t *hi) { - return umul128_generic(ab, cd, hi); -} -#endif // !__MINGW64__ - -#endif // FASTFLOAT_32BIT - -// compute 64-bit a*b -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 value128 -full_multiplication(uint64_t a, uint64_t b) { - if (cpp20_and_in_constexpr()) { - value128 answer; - answer.low = umul128_generic(a, b, &answer.high); - return answer; - } - value128 answer; -#if defined(_M_ARM64) && !defined(__MINGW32__) - // ARM64 has native support for 64-bit multiplications, no need to emulate - // But MinGW on ARM64 doesn't have native support for 64-bit multiplications - answer.high = __umulh(a, b); - answer.low = a * b; -#elif defined(FASTFLOAT_32BIT) || (defined(_WIN64) && !defined(__clang__) && \ - !defined(_M_ARM64) && !defined(__GNUC__)) - answer.low = _umul128(a, b, &answer.high); // _umul128 not available on ARM64 -#elif defined(FASTFLOAT_64BIT) && defined(__SIZEOF_INT128__) - __uint128_t r = static_cast<__uint128_t>(a) * b; - answer.low = uint64_t(r); - answer.high = uint64_t(r >> 64); -#else - answer.low = umul128_generic(a, b, &answer.high); -#endif - return answer; -} - -struct adjusted_mantissa { - uint64_t mantissa{0}; - int32_t power2{0}; // a negative value indicates an invalid result - adjusted_mantissa() = default; - - constexpr bool operator==(adjusted_mantissa const &o) const { - return mantissa == o.mantissa && power2 == o.power2; - } - - constexpr bool operator!=(adjusted_mantissa const &o) const { - return mantissa != o.mantissa || power2 != o.power2; - } -}; - -// Bias so we can get the real exponent with an invalid adjusted_mantissa. -constexpr static int32_t invalid_am_bias = -0x8000; - -// used for binary_format_lookup_tables::max_mantissa -constexpr uint64_t constant_55555 = 5 * 5 * 5 * 5 * 5; - -template struct binary_format_lookup_tables; - -template struct binary_format : binary_format_lookup_tables { - using equiv_uint = equiv_uint_t; - - static constexpr int mantissa_explicit_bits(); - static constexpr int minimum_exponent(); - static constexpr int infinite_power(); - static constexpr int sign_index(); - static constexpr int - min_exponent_fast_path(); // used when fegetround() == FE_TONEAREST - static constexpr int max_exponent_fast_path(); - static constexpr int max_exponent_round_to_even(); - static constexpr int min_exponent_round_to_even(); - static constexpr uint64_t max_mantissa_fast_path(int64_t power); - static constexpr uint64_t - max_mantissa_fast_path(); // used when fegetround() == FE_TONEAREST - static constexpr bool fast_path_can_overflow(); - static constexpr bool subnormal_ties_possible(); - static constexpr int largest_power_of_ten(); - static constexpr int smallest_power_of_ten(); - static constexpr T exact_power_of_ten(int64_t power); - static constexpr size_t max_digits(); - static constexpr equiv_uint exponent_mask(); - static constexpr equiv_uint mantissa_mask(); - static constexpr equiv_uint hidden_bit_mask(); -}; - -template struct binary_format_lookup_tables { - static constexpr double powers_of_ten[] = { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, - 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22}; - - // Largest integer value v so that (5**index * v) <= 1<<53. - // 0x20000000000000 == 1 << 53 - static constexpr uint64_t max_mantissa[] = { - 0x20000000000000, - 0x20000000000000 / 5, - 0x20000000000000 / (5 * 5), - 0x20000000000000 / (5 * 5 * 5), - 0x20000000000000 / (5 * 5 * 5 * 5), - 0x20000000000000 / (constant_55555), - 0x20000000000000 / (constant_55555 * 5), - 0x20000000000000 / (constant_55555 * 5 * 5), - 0x20000000000000 / (constant_55555 * 5 * 5 * 5), - 0x20000000000000 / (constant_55555 * 5 * 5 * 5 * 5), - 0x20000000000000 / (constant_55555 * constant_55555), - 0x20000000000000 / (constant_55555 * constant_55555 * 5), - 0x20000000000000 / (constant_55555 * constant_55555 * 5 * 5), - 0x20000000000000 / (constant_55555 * constant_55555 * 5 * 5 * 5), - 0x20000000000000 / (constant_55555 * constant_55555 * 5 * 5 * 5 * 5), - 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555), - 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * 5), - 0x20000000000000 / - (constant_55555 * constant_55555 * constant_55555 * 5 * 5), - 0x20000000000000 / - (constant_55555 * constant_55555 * constant_55555 * 5 * 5 * 5), - 0x20000000000000 / - (constant_55555 * constant_55555 * constant_55555 * 5 * 5 * 5 * 5), - 0x20000000000000 / - (constant_55555 * constant_55555 * constant_55555 * constant_55555), - 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * - constant_55555 * 5), - 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * - constant_55555 * 5 * 5), - 0x20000000000000 / (constant_55555 * constant_55555 * constant_55555 * - constant_55555 * 5 * 5 * 5)}; -}; - -#if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE - -template -constexpr double binary_format_lookup_tables::powers_of_ten[]; - -template -constexpr uint64_t binary_format_lookup_tables::max_mantissa[]; - -#endif - -template struct binary_format_lookup_tables { - static constexpr float powers_of_ten[] = {1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, - 1e6f, 1e7f, 1e8f, 1e9f, 1e10f}; - - // Largest integer value v so that (5**index * v) <= 1<<24. - // 0x1000000 == 1<<24 - static constexpr uint64_t max_mantissa[] = { - 0x1000000, - 0x1000000 / 5, - 0x1000000 / (5 * 5), - 0x1000000 / (5 * 5 * 5), - 0x1000000 / (5 * 5 * 5 * 5), - 0x1000000 / (constant_55555), - 0x1000000 / (constant_55555 * 5), - 0x1000000 / (constant_55555 * 5 * 5), - 0x1000000 / (constant_55555 * 5 * 5 * 5), - 0x1000000 / (constant_55555 * 5 * 5 * 5 * 5), - 0x1000000 / (constant_55555 * constant_55555), - 0x1000000 / (constant_55555 * constant_55555 * 5)}; -}; - -#if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE - -template -constexpr float binary_format_lookup_tables::powers_of_ten[]; - -template -constexpr uint64_t binary_format_lookup_tables::max_mantissa[]; - -#endif - -template <> -inline constexpr int binary_format::min_exponent_fast_path() { -#if (FLT_EVAL_METHOD != 1) && (FLT_EVAL_METHOD != 0) - return 0; -#else - return -22; -#endif -} - -template <> -inline constexpr int binary_format::min_exponent_fast_path() { -#if (FLT_EVAL_METHOD != 1) && (FLT_EVAL_METHOD != 0) - return 0; -#else - return -10; -#endif -} - -template <> -inline constexpr int binary_format::mantissa_explicit_bits() { - return 52; -} - -template <> -inline constexpr int binary_format::mantissa_explicit_bits() { - return 23; -} - -template <> -inline constexpr int binary_format::max_exponent_round_to_even() { - return 23; -} - -template <> -inline constexpr int binary_format::max_exponent_round_to_even() { - return 10; -} - -template <> -inline constexpr int binary_format::min_exponent_round_to_even() { - return -4; -} - -template <> -inline constexpr int binary_format::min_exponent_round_to_even() { - return -17; -} - -template <> inline constexpr int binary_format::minimum_exponent() { - return -1023; -} - -template <> inline constexpr int binary_format::minimum_exponent() { - return -127; -} - -template <> inline constexpr int binary_format::infinite_power() { - return 0x7FF; -} - -template <> inline constexpr int binary_format::infinite_power() { - return 0xFF; -} - -template <> inline constexpr int binary_format::sign_index() { - return 63; -} - -template <> inline constexpr int binary_format::sign_index() { - return 31; -} - -template <> -inline constexpr int binary_format::max_exponent_fast_path() { - return 22; -} - -template <> -inline constexpr int binary_format::max_exponent_fast_path() { - return 10; -} - -template <> -inline constexpr uint64_t binary_format::max_mantissa_fast_path() { - return uint64_t(2) << mantissa_explicit_bits(); -} - -template <> -inline constexpr uint64_t binary_format::max_mantissa_fast_path() { - return uint64_t(2) << mantissa_explicit_bits(); -} - -// credit: Jakub Jelínek -#ifdef __STDCPP_FLOAT16_T__ -template struct binary_format_lookup_tables { - static constexpr std::float16_t powers_of_ten[] = {1e0f16, 1e1f16, 1e2f16, - 1e3f16, 1e4f16}; - - // Largest integer value v so that (5**index * v) <= 1<<11. - // 0x800 == 1<<11 - static constexpr uint64_t max_mantissa[] = {0x800, - 0x800 / 5, - 0x800 / (5 * 5), - 0x800 / (5 * 5 * 5), - 0x800 / (5 * 5 * 5 * 5), - 0x800 / (constant_55555)}; -}; - -#if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE - -template -constexpr std::float16_t - binary_format_lookup_tables::powers_of_ten[]; - -template -constexpr uint64_t - binary_format_lookup_tables::max_mantissa[]; - -#endif - -template <> -inline constexpr std::float16_t -binary_format::exact_power_of_ten(int64_t power) { - // Work around clang bug https://godbolt.org/z/zedh7rrhc - return static_cast(powers_of_ten[0]), powers_of_ten[power]; -} - -template <> -inline constexpr binary_format::equiv_uint -binary_format::exponent_mask() { - return 0x7C00; -} - -template <> -inline constexpr binary_format::equiv_uint -binary_format::mantissa_mask() { - return 0x03FF; -} - -template <> -inline constexpr binary_format::equiv_uint -binary_format::hidden_bit_mask() { - return 0x0400; -} - -template <> -inline constexpr int binary_format::max_exponent_fast_path() { - return 4; -} - -template <> -inline constexpr int binary_format::mantissa_explicit_bits() { - return 10; -} - -template <> -inline constexpr uint64_t -binary_format::max_mantissa_fast_path() { - return uint64_t(2) << mantissa_explicit_bits(); -} - -template <> -inline constexpr uint64_t -binary_format::max_mantissa_fast_path(int64_t power) { - // caller is responsible to ensure that - // power >= 0 && power <= 4 - // - // Work around clang bug https://godbolt.org/z/zedh7rrhc - return static_cast(max_mantissa[0]), max_mantissa[power]; -} - -template <> -inline constexpr int binary_format::min_exponent_fast_path() { - // w / 10^k with w <= 2^11 and k <= 4 rounds correctly even when evaluated - // in float or double first (checked in script/format_parameters.py). - return -4; -} - -template <> -inline constexpr int -binary_format::max_exponent_round_to_even() { - return 5; -} - -template <> -inline constexpr int -binary_format::min_exponent_round_to_even() { - // -22 covers the normal ties; subnormal ties such as - // 2^-25 = 298023223876953125e-25 need q = -25 and q = -26. - return -26; -} - -template <> -inline constexpr int binary_format::minimum_exponent() { - return -15; -} - -template <> -inline constexpr int binary_format::infinite_power() { - return 0x1F; -} - -template <> inline constexpr int binary_format::sign_index() { - return 15; -} - -template <> -inline constexpr int binary_format::largest_power_of_ten() { - return 4; -} - -template <> -inline constexpr int binary_format::smallest_power_of_ten() { - // (10^19 - 1) * 10^-27 < 2^-25, so any q < -26 rounds to zero. - return -26; -} - -template <> -inline constexpr size_t binary_format::max_digits() { - return 22; -} -#endif // __STDCPP_FLOAT16_T__ - -// credit: Jakub Jelínek -#ifdef __STDCPP_BFLOAT16_T__ -template struct binary_format_lookup_tables { - static constexpr std::bfloat16_t powers_of_ten[] = {1e0bf16, 1e1bf16, 1e2bf16, - 1e3bf16}; - - // Largest integer value v so that (5**index * v) <= 1<<8. - // 0x100 == 1<<8 - static constexpr uint64_t max_mantissa[] = {0x100, 0x100 / 5, 0x100 / (5 * 5), - 0x100 / (5 * 5 * 5), - 0x100 / (5 * 5 * 5 * 5)}; -}; - -#if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE - -template -constexpr std::bfloat16_t - binary_format_lookup_tables::powers_of_ten[]; - -template -constexpr uint64_t - binary_format_lookup_tables::max_mantissa[]; - -#endif - -template <> -inline constexpr std::bfloat16_t -binary_format::exact_power_of_ten(int64_t power) { - // Work around clang bug https://godbolt.org/z/zedh7rrhc - return static_cast(powers_of_ten[0]), powers_of_ten[power]; -} - -template <> -inline constexpr int binary_format::max_exponent_fast_path() { - return 3; -} - -template <> -inline constexpr binary_format::equiv_uint -binary_format::exponent_mask() { - return 0x7F80; -} - -template <> -inline constexpr binary_format::equiv_uint -binary_format::mantissa_mask() { - return 0x007F; -} - -template <> -inline constexpr binary_format::equiv_uint -binary_format::hidden_bit_mask() { - return 0x0080; -} - -template <> -inline constexpr int binary_format::mantissa_explicit_bits() { - return 7; -} - -template <> -inline constexpr uint64_t -binary_format::max_mantissa_fast_path() { - return uint64_t(2) << mantissa_explicit_bits(); -} - -template <> -inline constexpr uint64_t -binary_format::max_mantissa_fast_path(int64_t power) { - // caller is responsible to ensure that - // power >= 0 && power <= 3 - // - // Work around clang bug https://godbolt.org/z/zedh7rrhc - return static_cast(max_mantissa[0]), max_mantissa[power]; -} - -template <> -inline constexpr int binary_format::min_exponent_fast_path() { - // Same argument as for std::float16_t (w <= 2^8, k <= 3). - return -3; -} - -template <> -inline constexpr int -binary_format::max_exponent_round_to_even() { - return 3; -} - -template <> -inline constexpr int -binary_format::min_exponent_round_to_even() { - return -24; -} - -template <> -inline constexpr int binary_format::minimum_exponent() { - return -127; -} - -template <> -inline constexpr int binary_format::infinite_power() { - return 0xFF; -} - -template <> inline constexpr int binary_format::sign_index() { - return 15; -} - -template <> -inline constexpr int binary_format::largest_power_of_ten() { - return 38; -} - -template <> -inline constexpr int binary_format::smallest_power_of_ten() { - // (10^19 - 1) * 10^-60 < 2^-134, so any q < -59 rounds to zero. - return -59; -} - -template <> -inline constexpr size_t binary_format::max_digits() { - return 98; -} -#endif // __STDCPP_BFLOAT16_T__ - -// Whether Clinger's fast path can overflow: only for std::float16_t, where -// 2^11 * 10^4 > 65504. -template -inline constexpr bool binary_format::fast_path_can_overflow() { - return double(max_mantissa_fast_path()) * - double(exact_power_of_ten(max_exponent_fast_path())) > - double((std::numeric_limits::max)()); -} - -// A subnormal needs w * 10^q < 2^(minimum_exponent() + 1), so q is at most -// (minimum_exponent() + 1) * log10(2), with 1233/4096 < log10(2). Only -// std::float16_t has such q in its round-to-even range. We compare -// 4096 * q with (minimum_exponent() + 1) * 1233 to avoid right-shifting a -// negative value (implementation-defined before C++20). -template -inline constexpr bool binary_format::subnormal_ties_possible() { - return min_exponent_round_to_even() * 4096 <= (minimum_exponent() + 1) * 1233; -} - -template <> -inline constexpr uint64_t -binary_format::max_mantissa_fast_path(int64_t power) { - // caller is responsible to ensure that - // power >= 0 && power <= 22 - // - // Work around clang bug https://godbolt.org/z/zedh7rrhc - return static_cast(max_mantissa[0]), max_mantissa[power]; -} - -template <> -inline constexpr uint64_t -binary_format::max_mantissa_fast_path(int64_t power) { - // caller is responsible to ensure that - // power >= 0 && power <= 10 - // - // Work around clang bug https://godbolt.org/z/zedh7rrhc - return static_cast(max_mantissa[0]), max_mantissa[power]; -} - -template <> -inline constexpr double -binary_format::exact_power_of_ten(int64_t power) { - // Work around clang bug https://godbolt.org/z/zedh7rrhc - return static_cast(powers_of_ten[0]), powers_of_ten[power]; -} - -template <> -inline constexpr float binary_format::exact_power_of_ten(int64_t power) { - // Work around clang bug https://godbolt.org/z/zedh7rrhc - return static_cast(powers_of_ten[0]), powers_of_ten[power]; -} - -template <> inline constexpr int binary_format::largest_power_of_ten() { - return 308; -} - -template <> inline constexpr int binary_format::largest_power_of_ten() { - return 38; -} - -template <> -inline constexpr int binary_format::smallest_power_of_ten() { - return -342; -} - -template <> inline constexpr int binary_format::smallest_power_of_ten() { - return -64; -} - -template <> inline constexpr size_t binary_format::max_digits() { - return 769; -} - -template <> inline constexpr size_t binary_format::max_digits() { - return 114; -} - -template <> -inline constexpr binary_format::equiv_uint -binary_format::exponent_mask() { - return 0x7F800000; -} - -template <> -inline constexpr binary_format::equiv_uint -binary_format::exponent_mask() { - return 0x7FF0000000000000; -} - -template <> -inline constexpr binary_format::equiv_uint -binary_format::mantissa_mask() { - return 0x007FFFFF; -} - -template <> -inline constexpr binary_format::equiv_uint -binary_format::mantissa_mask() { - return 0x000FFFFFFFFFFFFF; -} - -template <> -inline constexpr binary_format::equiv_uint -binary_format::hidden_bit_mask() { - return 0x00800000; -} - -template <> -inline constexpr binary_format::equiv_uint -binary_format::hidden_bit_mask() { - return 0x0010000000000000; -} - -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void -to_float(bool negative, adjusted_mantissa am, T &value) { - using equiv_uint = equiv_uint_t; - equiv_uint word = equiv_uint(am.mantissa); - word = equiv_uint(word | equiv_uint(am.power2) - << binary_format::mantissa_explicit_bits()); - word = - equiv_uint(word | equiv_uint(negative) << binary_format::sign_index()); -#if FASTFLOAT_HAS_BIT_CAST - value = std::bit_cast(word); -#else - ::memcpy(&value, &word, sizeof(T)); -#endif -} - -template struct space_lut { - static constexpr bool value[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; -}; - -#if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE - -template constexpr bool space_lut::value[]; - -#endif - -template constexpr bool is_space(UC c) { - // wchar_t and char can be signed, so a negative code unit slips past a plain - // `c < 256` and then indexes the table by its truncated low byte. Compare as - // unsigned, matching the care taken in ch_to_digit. - using UnsignedUC = typename std::make_unsigned::type; - return static_cast(c) < 256 && space_lut<>::value[uint8_t(c)]; -} - -template static constexpr uint64_t int_cmp_zeros() { - static_assert((sizeof(UC) == 1) || (sizeof(UC) == 2) || (sizeof(UC) == 4), - "Unsupported character size"); - return (sizeof(UC) == 1) ? 0x3030303030303030 - : (sizeof(UC) == 2) - ? (uint64_t(UC('0')) << 48 | uint64_t(UC('0')) << 32 | - uint64_t(UC('0')) << 16 | UC('0')) - : (uint64_t(UC('0')) << 32 | UC('0')); -} - -template static constexpr int int_cmp_len() { - return sizeof(uint64_t) / sizeof(UC); -} - -template constexpr UC const *str_const_nan(); - -template <> constexpr char const *str_const_nan() { return "nan"; } - -template <> constexpr wchar_t const *str_const_nan() { return L"nan"; } - -template <> constexpr char16_t const *str_const_nan() { - return u"nan"; -} - -template <> constexpr char32_t const *str_const_nan() { - return U"nan"; -} - -#ifdef __cpp_char8_t -template <> constexpr char8_t const *str_const_nan() { - return u8"nan"; -} -#endif - -template constexpr UC const *str_const_inf(); - -template <> constexpr char const *str_const_inf() { return "infinity"; } - -template <> constexpr wchar_t const *str_const_inf() { - return L"infinity"; -} - -template <> constexpr char16_t const *str_const_inf() { - return u"infinity"; -} - -template <> constexpr char32_t const *str_const_inf() { - return U"infinity"; -} - -#ifdef __cpp_char8_t -template <> constexpr char8_t const *str_const_inf() { - return u8"infinity"; -} -#endif - -template struct int_luts { - static constexpr uint8_t chdigit[] = { - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, - 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, - 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, - 35, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 16, 17, - 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, - 33, 34, 35, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255}; - - static constexpr size_t maxdigits_u64[] = { - 64, 41, 32, 28, 25, 23, 22, 21, 20, 19, 18, 18, 17, 17, 16, 16, 16, 16, - 15, 15, 15, 15, 14, 14, 14, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13}; - - static constexpr uint64_t min_safe_u64[] = { - 9223372036854775808ull, 12157665459056928801ull, 4611686018427387904, - 7450580596923828125, 4738381338321616896, 3909821048582988049, - 9223372036854775808ull, 12157665459056928801ull, 10000000000000000000ull, - 5559917313492231481, 2218611106740436992, 8650415919381337933, - 2177953337809371136, 6568408355712890625, 1152921504606846976, - 2862423051509815793, 6746640616477458432, 15181127029874798299ull, - 1638400000000000000, 3243919932521508681, 6221821273427820544, - 11592836324538749809ull, 876488338465357824, 1490116119384765625, - 2481152873203736576, 4052555153018976267, 6502111422497947648, - 10260628712958602189ull, 15943230000000000000ull, 787662783788549761, - 1152921504606846976, 1667889514952984961, 2386420683693101056, - 3379220508056640625, 4738381338321616896}; -}; - -#if FASTFLOAT_DETAIL_MUST_DEFINE_CONSTEXPR_VARIABLE - -template constexpr uint8_t int_luts::chdigit[]; - -template constexpr size_t int_luts::maxdigits_u64[]; - -template constexpr uint64_t int_luts::min_safe_u64[]; - -#endif - -template -fastfloat_really_inline constexpr uint8_t ch_to_digit(UC c) { - // wchar_t and char can be signed, so we need to be careful. - using UnsignedUC = typename std::make_unsigned::type; - return int_luts<>::chdigit[static_cast( - static_cast(c) & - static_cast( - -((static_cast(c) & ~0xFFull) == 0)))]; -} - -fastfloat_really_inline constexpr size_t max_digits_u64(int base) { - return int_luts<>::maxdigits_u64[base - 2]; -} - -// If a u64 is exactly max_digits_u64() in length, this is -// the value below which it has definitely overflowed. -fastfloat_really_inline constexpr uint64_t min_safe_u64(int base) { - return int_luts<>::min_safe_u64[base - 2]; -} - -static_assert(std::is_same, uint64_t>::value, - "equiv_uint should be uint64_t for double"); -static_assert(std::numeric_limits::is_iec559, - "double must fulfill the requirements of IEC 559 (IEEE 754)"); - -static_assert(std::is_same, uint32_t>::value, - "equiv_uint should be uint32_t for float"); -static_assert(std::numeric_limits::is_iec559, - "float must fulfill the requirements of IEC 559 (IEEE 754)"); - -#ifdef __STDCPP_FLOAT64_T__ -static_assert(std::is_same, uint64_t>::value, - "equiv_uint should be uint64_t for std::float64_t"); -static_assert( - std::numeric_limits::is_iec559, - "std::float64_t must fulfill the requirements of IEC 559 (IEEE 754)"); - -template <> -struct binary_format : public binary_format {}; -#endif // __STDCPP_FLOAT64_T__ - -#ifdef __STDCPP_FLOAT32_T__ -static_assert(std::is_same, uint32_t>::value, - "equiv_uint should be uint32_t for std::float32_t"); -static_assert( - std::numeric_limits::is_iec559, - "std::float32_t must fulfill the requirements of IEC 559 (IEEE 754)"); - -template <> -struct binary_format : public binary_format {}; -#endif // __STDCPP_FLOAT32_T__ - -#ifdef __STDCPP_FLOAT16_T__ -static_assert( - std::is_same::equiv_uint, uint16_t>::value, - "equiv_uint should be uint16_t for std::float16_t"); -static_assert( - std::numeric_limits::is_iec559, - "std::float16_t must fulfill the requirements of IEC 559 (IEEE 754)"); -#endif // __STDCPP_FLOAT16_T__ - -#ifdef __STDCPP_BFLOAT16_T__ -static_assert( - std::is_same::equiv_uint, uint16_t>::value, - "equiv_uint should be uint16_t for std::bfloat16_t"); -static_assert( - std::numeric_limits::is_iec559, - "std::bfloat16_t must fulfill the requirements of IEC 559 (IEEE 754)"); -#endif // __STDCPP_BFLOAT16_T__ - -constexpr chars_format operator~(chars_format rhs) noexcept { - using int_type = std::underlying_type::type; - return static_cast(~static_cast(rhs)); -} - -constexpr chars_format operator&(chars_format lhs, chars_format rhs) noexcept { - using int_type = std::underlying_type::type; - return static_cast(static_cast(lhs) & - static_cast(rhs)); -} - -constexpr chars_format operator|(chars_format lhs, chars_format rhs) noexcept { - using int_type = std::underlying_type::type; - return static_cast(static_cast(lhs) | - static_cast(rhs)); -} - -constexpr chars_format operator^(chars_format lhs, chars_format rhs) noexcept { - using int_type = std::underlying_type::type; - return static_cast(static_cast(lhs) ^ - static_cast(rhs)); -} - -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 chars_format & -operator&=(chars_format &lhs, chars_format rhs) noexcept { - return lhs = (lhs & rhs); -} - -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 chars_format & -operator|=(chars_format &lhs, chars_format rhs) noexcept { - return lhs = (lhs | rhs); -} - -fastfloat_really_inline FASTFLOAT_CONSTEXPR14 chars_format & -operator^=(chars_format &lhs, chars_format rhs) noexcept { - return lhs = (lhs ^ rhs); -} - -namespace detail { -// adjust for deprecated feature macros -constexpr chars_format adjust_for_feature_macros(chars_format fmt) { - return fmt -#ifdef FASTFLOAT_ALLOWS_LEADING_PLUS - | chars_format::allow_leading_plus -#endif -#ifdef FASTFLOAT_SKIP_WHITE_SPACE - | chars_format::skip_white_space -#endif - ; -} -} // namespace detail -} // namespace fast_float - -#endif diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/parse_number.h b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/parse_number.h deleted file mode 100644 index 038be5b1ca..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/cpp/third_party/fast_float/include/fast_float/parse_number.h +++ /dev/null @@ -1,627 +0,0 @@ -#ifndef FASTFLOAT_PARSE_NUMBER_H -#define FASTFLOAT_PARSE_NUMBER_H - -#include "ascii_number.h" -#include "decimal_to_binary.h" -#include "digit_comparison.h" -#include "float_common.h" - -#include -#include -#include -#include - -namespace fast_float { - -namespace detail { -/** - * Special case +inf, -inf, nan, infinity, -infinity. - * The case comparisons could be made much faster given that we know that the - * strings a null-free and fixed. - **/ -template -from_chars_result_t - FASTFLOAT_CONSTEXPR14 parse_infnan(UC const *first, UC const *last, - T &value, chars_format fmt) noexcept { - from_chars_result_t answer{}; - answer.ptr = first; - answer.ec = std::errc(); // be optimistic - // assume first < last, so dereference without checks; - bool const minusSign = (*first == UC('-')); - // C++17 20.19.3.(7.1) explicitly forbids '+' sign here - if ((*first == UC('-')) || - (uint64_t(fmt & chars_format::allow_leading_plus) && - (*first == UC('+')))) { - ++first; - } - if (last - first >= 3) { - if (fastfloat_strncasecmp(first, str_const_nan(), 3)) { - answer.ptr = (first += 3); - value = minusSign ? -std::numeric_limits::quiet_NaN() - : std::numeric_limits::quiet_NaN(); - // Check for possible nan(n-char-seq-opt), C++17 20.19.3.7, - // C11 7.20.1.3.3. At least MSVC produces nan(ind) and nan(snan). - if (first != last && *first == UC('(')) { - for (UC const *ptr = first + 1; ptr != last; ++ptr) { - if (*ptr == UC(')')) { - answer.ptr = ptr + 1; // valid nan(n-char-seq-opt) - break; - } else if (!((UC('a') <= *ptr && *ptr <= UC('z')) || - (UC('A') <= *ptr && *ptr <= UC('Z')) || - (UC('0') <= *ptr && *ptr <= UC('9')) || *ptr == UC('_'))) - break; // forbidden char, not nan(n-char-seq-opt) - } - } - return answer; - } - if (fastfloat_strncasecmp(first, str_const_inf(), 3)) { - if ((last - first >= 8) && - fastfloat_strncasecmp(first + 3, str_const_inf() + 3, 5)) { - answer.ptr = first + 8; - } else { - answer.ptr = first + 3; - } - value = minusSign ? -std::numeric_limits::infinity() - : std::numeric_limits::infinity(); - return answer; - } - } - answer.ec = std::errc::invalid_argument; - return answer; -} - -/** - * Returns true if the floating-pointing rounding mode is to 'nearest'. - * It is the default on most system. This function is meant to be inexpensive. - * Credit : @mwalcott3 - */ -fastfloat_really_inline bool rounds_to_nearest() noexcept { - // https://lemire.me/blog/2020/06/26/gcc-not-nearest/ -#if (FLT_EVAL_METHOD != 1) && (FLT_EVAL_METHOD != 0) - return false; -#endif - // See - // A fast function to check your floating-point rounding mode - // https://lemire.me/blog/2022/11/16/a-fast-function-to-check-your-floating-point-rounding-mode/ - // - // This function is meant to be equivalent to : - // prior: #include - // return fegetround() == FE_TONEAREST; - // However, it is expected to be much faster than the fegetround() - // function call. - // - // The volatile keyword prevents the compiler from computing the function - // at compile-time. - // There might be other ways to prevent compile-time optimizations (e.g., - // asm). The value does not need to be std::numeric_limits::min(), any - // small value so that 1 + x should round to 1 would do (after accounting for - // excess precision, as in 387 instructions). - static float volatile fmin = (std::numeric_limits::min)(); - float fmini = fmin; // we copy it so that it gets loaded at most once. -// -// Explanation: -// Only when fegetround() == FE_TONEAREST do we have that -// fmin + 1.0f == 1.0f - fmin. -// -// FE_UPWARD: -// fmin + 1.0f > 1 -// 1.0f - fmin == 1 -// -// FE_DOWNWARD or FE_TOWARDZERO: -// fmin + 1.0f == 1 -// 1.0f - fmin < 1 -// -// Note: This may fail to be accurate if fast-math has been -// enabled, as rounding conventions may not apply. -#ifdef FASTFLOAT_VISUAL_STUDIO -#pragma warning(push) -// todo: is there a VS warning? -// see -// https://stackoverflow.com/questions/46079446/is-there-a-warning-for-floating-point-equality-checking-in-visual-studio-2013 -#elif defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wfloat-equal" -#elif defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wfloat-equal" -#endif - return (fmini + 1.0f == 1.0f - fmini); -#ifdef FASTFLOAT_VISUAL_STUDIO -#pragma warning(pop) -#elif defined(__clang__) -#pragma clang diagnostic pop -#elif defined(__GNUC__) -#pragma GCC diagnostic pop -#endif -} - -} // namespace detail - -template struct from_chars_caller { - template - fastfloat_clang_really_inline - FASTFLOAT_CONSTEXPR20 static from_chars_result_t - call(UC const *first, UC const *last, T &value, - parse_options_t options) noexcept { - return from_chars_advanced(first, last, value, options); - } -}; - -#ifdef __STDCPP_FLOAT32_T__ -template <> struct from_chars_caller { - template - FASTFLOAT_CONSTEXPR20 static from_chars_result_t - call(UC const *first, UC const *last, std::float32_t &value, - parse_options_t options) noexcept { - // if std::float32_t is defined, and we are in C++23 mode; macro set for - // float32; set value to float due to equivalence between float and - // float32_t - float val = 0.0f; - auto ret = from_chars_advanced(first, last, val, options); - value = val; - return ret; - } -}; -#endif - -#ifdef __STDCPP_FLOAT64_T__ -template <> struct from_chars_caller { - template - FASTFLOAT_CONSTEXPR20 static from_chars_result_t - call(UC const *first, UC const *last, std::float64_t &value, - parse_options_t options) noexcept { - // if std::float64_t is defined, and we are in C++23 mode; macro set for - // float64; set value as double due to equivalence between double and - // float64_t - double val = 0.0; - auto ret = from_chars_advanced(first, last, val, options); - value = val; - return ret; - } -}; -#endif - -#ifdef __clang__ -// Parser instantiated for a format fixed at compile time, so that every test -// on the format folds away inside it. GCC gets the same effect by inlining the -// whole parser into each caller, where the format is a constant; clang keeps -// it out of line and would otherwise re-test each format flag per conversion. -template -FASTFLOAT_CONSTEXPR20 from_chars_result_t -from_chars_fixed_format(UC const *first, UC const *last, T &value) noexcept { - return from_chars_caller::call(first, last, value, - parse_options_t(Fmt)); -} -#endif - -template -FASTFLOAT_CONSTEXPR20 from_chars_result_t -from_chars(UC const *first, UC const *last, T &value, - chars_format fmt /*= chars_format::general*/) noexcept { -#ifdef __clang__ - if (fmt == chars_format::general) { - return from_chars_fixed_format(first, last, - value); - } -#endif - return from_chars_caller::call(first, last, value, - parse_options_t(fmt)); -} - -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool -clinger_fast_path_impl(uint64_t mantissa, int64_t exponent, bool is_negative, - T &value) noexcept { - // The implementation of the Clinger's fast path is convoluted because - // we want round-to-nearest in all cases, irrespective of the rounding mode - // selected on the thread. - // We proceed optimistically, assuming that detail::rounds_to_nearest() - // returns true. - if (binary_format::min_exponent_fast_path() <= exponent && - exponent <= binary_format::max_exponent_fast_path() && - mantissa <= binary_format::max_mantissa_fast_path()) { - // The mantissa bound above is a necessary condition for BOTH branches - // below: the rounding-mode-dependent branch checks the tighter - // max_mantissa_fast_path(exponent) <= max_mantissa_fast_path(). Testing - // it before detail::rounds_to_nearest() spares long-mantissa inputs - // (which can never take the fast path) the volatile-float probe. - // - // Unfortunately, the conventional Clinger's fast path is only possible - // when the system rounds to the nearest float. - // - // We expect the next branch to almost always be selected. - // We could check it first (before the previous branch), but - // there might be performance advantages at having the check - // be last. - if (!cpp20_and_in_constexpr() && detail::rounds_to_nearest()) { - // We have that fegetround() == FE_TONEAREST. - // Next is Clinger's fast path. - value = T(mantissa); - if (exponent < 0) { - value = value / binary_format::exact_power_of_ten(-exponent); - } else { - value = value * binary_format::exact_power_of_ten(exponent); - // Only std::float16_t can overflow here (e.g., "656e2"); let the - // slow path report result_out_of_range. - if (binary_format::fast_path_can_overflow() && - value > (std::numeric_limits::max)()) { - return false; - } - } - if (is_negative) { - value = -value; - } - return true; - } else { - // We do not have that fegetround() == FE_TONEAREST. - // Next is a modified Clinger's fast path, inspired by Jakub Jelínek's - // proposal - if (exponent >= 0 && - mantissa <= binary_format::max_mantissa_fast_path(exponent)) { -#if defined(__clang__) || defined(FASTFLOAT_32BIT) - // Clang may map 0 to -0.0 when fegetround() == FE_DOWNWARD - if (mantissa == 0) { - value = is_negative ? T(-0.) : T(0.); - return true; - } -#endif - value = T(mantissa) * binary_format::exact_power_of_ten(exponent); - if (is_negative) { - value = -value; - } - return true; - } - } - } - return false; -} - -/** - * This function overload takes parsed_number_string_t structure that is created - * and populated either by from_chars_advanced function taking chars range and - * parsing options or other parsing custom function implemented by user. - */ -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t -from_chars_advanced(parsed_number_string_t &pns, T &value) noexcept { - static_assert(is_supported_float_type::value, - "only some floating-point types are supported"); - static_assert(is_supported_char_type::value, - "only char, wchar_t, char16_t and char32_t are supported"); - - from_chars_result_t answer; - - answer.ec = std::errc(); // be optimistic - answer.ptr = pns.lastmatch; - - if (!pns.too_many_digits && - clinger_fast_path_impl(pns.mantissa, pns.exponent, pns.negative, value)) - return answer; - - adjusted_mantissa am = - compute_float>(pns.exponent, pns.mantissa); - if (pns.too_many_digits && am.power2 >= 0) { - if (am != compute_float>(pns.exponent, pns.mantissa + 1)) { - am = compute_error>(pns.exponent, pns.mantissa); - } - } - // If we called compute_float>(pns.exponent, pns.mantissa) - // and we have an invalid power (am.power2 < 0), then we need to go the long - // way around again. This is very uncommon. - if (am.power2 < 0) { - am = digit_comp(pns, am); - } - to_float(pns.negative, am, value); - // Test for over/underflow. - if ((pns.mantissa != 0 && am.mantissa == 0 && am.power2 == 0) || - am.power2 == binary_format::infinite_power()) { - answer.ec = std::errc::result_out_of_range; - } - return answer; -} - -// Slow path: re-parse materializing the integer/fraction spans the hot no-span -// parse skipped, then run the full algorithm. The two callers reach it only -// through a fastfloat_unlikely branch, so the optimizer keeps this re-parse off -// the hot path on its own (no function-level noinline needed). -// from_chars_advanced already handles both the too_many_digits disambiguation -// and the am.power2<0 digit_comp recompute, so both slow branches collapse to -// one helper call. -template -FASTFLOAT_CONSTEXPR20 from_chars_result_t -parse_number_slow_path(UC const *first, UC const *last, T &value, - parse_options_t options, bool bjf) noexcept { - parsed_number_string_t pns = - bjf ? parse_number_string_impl(first, last, options, - true) - : parse_number_string_impl(first, last, options, - true); - return from_chars_advanced(pns, value); -} - -// Cold: the whole chars_format::javascript conversion. Kept out of line and out -// of from_chars_float_advanced so the common frame holds neither the javascript -// parser body nor a call that would force the parsed number string onto the -// stack. Mirrors the main path, only with the javascript parser. -template -fastfloat_never_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t -from_chars_float_javascript(UC const *first, UC const *last, T &value, - parse_options_t options) noexcept { - chars_format const fmt = detail::adjust_for_feature_macros(options.format); - if (uint64_t(fmt & chars_format::skip_white_space)) { - while ((first != last) && fast_float::is_space(*first)) { - first++; - } - } - from_chars_result_t answer; - answer.ec = std::errc::invalid_argument; - answer.ptr = first; - if (first == last) { - return answer; - } - parsed_number_string_t pns = - parse_number_string_javascript(first, last, options, true); - if (!pns.valid) { - if (uint64_t(fmt & chars_format::no_infnan)) { - return answer; - } - return detail::parse_infnan(first, last, value, fmt); - } - return from_chars_advanced(pns, value); -} - -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t -from_chars_float_advanced(UC const *first, UC const *last, T &value, - parse_options_t options) noexcept { - - static_assert(is_supported_float_type::value, - "only some floating-point types are supported"); - static_assert(is_supported_char_type::value, - "only char, wchar_t, char16_t and char32_t are supported"); - - chars_format const fmt = detail::adjust_for_feature_macros(options.format); - - // Leave for the javascript conversion before anything else is live, so this - // compiles to a tail call and the common path keeps its registers. The cold - // function repeats the leading-whitespace and empty-input handling below. - if fastfloat_unlikely (uint64_t(fmt & detail::basic_javascript_fmt)) { - return from_chars_float_javascript(first, last, value, options); - } - - from_chars_result_t answer; - if (uint64_t(fmt & chars_format::skip_white_space)) { - while ((first != last) && fast_float::is_space(*first)) { - first++; - } - } - if (first == last) { - answer.ec = std::errc::invalid_argument; - answer.ptr = first; - return answer; - } - bool const bjf = uint64_t(fmt & detail::basic_json_fmt) != 0; - - // Fast path: parse WITHOUT materializing the integer/fraction spans (read - // only by the rare slow paths). Skipping their stores keeps the fat - // parsed_number_string_t off the hot path. store_spans is a runtime argument, - // so this reuses the single parse_number_string_impl instantiation. - parsed_number_string_t pns = - bjf ? parse_number_string_impl(first, last, options, - false) - : parse_number_string_impl(first, last, options, - false); - if (!pns.valid) { - if (uint64_t(fmt & chars_format::no_infnan)) { - answer.ec = std::errc::invalid_argument; - answer.ptr = first; - return answer; - } else { - return detail::parse_infnan(first, last, value, fmt); - } - } - - // Slow path A (rare): > 19 significant digits. The no-span parse left the - // mantissa un-truncated and skipped the span-based recompute; the cold helper - // re-parses with spans and runs the full algorithm. - // -// We have to disable -Wc++20-extensions for the [[unlikely]] attribute -// See comment for @jwakely at -// https://github.com/fastfloat/fast_float/pull/387#discussion_r3366943539 -// This is unfortunate. -#ifdef __clang__ -#pragma clang diagnostic push -#if (!defined(__APPLE_CC__) && __clang_major__ >= 10) || (__clang_major__ >= 13) -#pragma clang diagnostic ignored "-Wc++20-extensions" -#endif -#endif - if fastfloat_unlikely (pns.too_many_digits) { - return parse_number_slow_path(first, last, value, options, bjf); - } - answer.ec = std::errc(); // be optimistic - answer.ptr = pns.lastmatch; - - if (clinger_fast_path_impl(pns.mantissa, pns.exponent, pns.negative, value)) { - return answer; - } - - adjusted_mantissa am = - compute_float>(pns.exponent, pns.mantissa); - // Slow path B (rare): Eisel-Lemire could not resolve; digit_comp needs the - // integer/fraction spans. Route to the cold helper (clinger there is a - // dead-effect since it already failed here; the cold re-parse + digit_comp - // via from_chars_advanced reproduces this branch). - if fastfloat_unlikely (am.power2 < 0) { - return parse_number_slow_path(first, last, value, options, bjf); - } - to_float(pns.negative, am, value); - // Test for over/underflow. Marked unlikely so that clang keeps it as a - // branch instead of folding it into a chain of conditional moves that - // every conversion pays for. - if fastfloat_clang_unlikely ((pns.mantissa != 0 && am.mantissa == 0 && - am.power2 == 0) || - am.power2 == - binary_format::infinite_power()) { - answer.ec = std::errc::result_out_of_range; - } -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - return answer; -} - -template -FASTFLOAT_CONSTEXPR20 from_chars_result_t -from_chars(UC const *first, UC const *last, T &value, int base) noexcept { - - static_assert(is_supported_integer_type::value, - "only integer types are supported"); - static_assert(is_supported_char_type::value, - "only char, wchar_t, char16_t and char32_t are supported"); - - parse_options_t options; - options.base = base; - return from_chars_advanced(first, last, value, options); -} - -template -FASTFLOAT_CONSTEXPR20 - typename std::enable_if::value, T>::type - integer_times_pow10(uint64_t mantissa, int decimal_exponent) noexcept { - T value; - if (clinger_fast_path_impl(mantissa, decimal_exponent, false, value)) - return value; - - adjusted_mantissa am = - compute_float>(decimal_exponent, mantissa); - to_float(false, am, value); - return value; -} - -template -FASTFLOAT_CONSTEXPR20 - typename std::enable_if::value, T>::type - integer_times_pow10(int64_t mantissa, int decimal_exponent) noexcept { - const bool is_negative = mantissa < 0; - const uint64_t m = static_cast(is_negative ? -mantissa : mantissa); - - T value; - if (clinger_fast_path_impl(m, decimal_exponent, is_negative, value)) - return value; - - adjusted_mantissa am = compute_float>(decimal_exponent, m); - to_float(is_negative, am, value); - return value; -} - -FASTFLOAT_CONSTEXPR20 inline double -integer_times_pow10(uint64_t mantissa, int decimal_exponent) noexcept { - return integer_times_pow10(mantissa, decimal_exponent); -} - -FASTFLOAT_CONSTEXPR20 inline double -integer_times_pow10(int64_t mantissa, int decimal_exponent) noexcept { - return integer_times_pow10(mantissa, decimal_exponent); -} - -// the following overloads are here to avoid surprising ambiguity for int, -// unsigned, etc. -template -FASTFLOAT_CONSTEXPR20 - typename std::enable_if::value && - std::is_integral::value && - !std::is_signed::value, - T>::type - integer_times_pow10(Int mantissa, int decimal_exponent) noexcept { - return integer_times_pow10(static_cast(mantissa), - decimal_exponent); -} - -template -FASTFLOAT_CONSTEXPR20 - typename std::enable_if::value && - std::is_integral::value && - std::is_signed::value, - T>::type - integer_times_pow10(Int mantissa, int decimal_exponent) noexcept { - return integer_times_pow10(static_cast(mantissa), - decimal_exponent); -} - -template -FASTFLOAT_CONSTEXPR20 typename std::enable_if< - std::is_integral::value && !std::is_signed::value, double>::type -integer_times_pow10(Int mantissa, int decimal_exponent) noexcept { - return integer_times_pow10(static_cast(mantissa), decimal_exponent); -} - -template -FASTFLOAT_CONSTEXPR20 typename std::enable_if< - std::is_integral::value && std::is_signed::value, double>::type -integer_times_pow10(Int mantissa, int decimal_exponent) noexcept { - return integer_times_pow10(static_cast(mantissa), decimal_exponent); -} - -template -FASTFLOAT_CONSTEXPR20 from_chars_result_t -from_chars_int_advanced(UC const *first, UC const *last, T &value, - parse_options_t options) noexcept { - - static_assert(is_supported_integer_type::value, - "only integer types are supported"); - static_assert(is_supported_char_type::value, - "only char, wchar_t, char16_t and char32_t are supported"); - - chars_format const fmt = detail::adjust_for_feature_macros(options.format); - int const base = options.base; - - from_chars_result_t answer; - if (uint64_t(fmt & chars_format::skip_white_space)) { - while ((first != last) && fast_float::is_space(*first)) { - first++; - } - } - if (first == last || base < 2 || base > 36) { - answer.ec = std::errc::invalid_argument; - answer.ptr = first; - return answer; - } - - return parse_int_string(first, last, value, options); -} - -template struct from_chars_advanced_caller { - static_assert(TypeIx > 0, "unsupported type"); -}; - -template <> struct from_chars_advanced_caller<1> { - template - fastfloat_really_inline FASTFLOAT_CONSTEXPR20 static from_chars_result_t - call(UC const *first, UC const *last, T &value, - parse_options_t options) noexcept { - return from_chars_float_advanced(first, last, value, options); - } -}; - -template <> struct from_chars_advanced_caller<2> { - template - fastfloat_really_inline FASTFLOAT_CONSTEXPR20 static from_chars_result_t - call(UC const *first, UC const *last, T &value, - parse_options_t options) noexcept { - return from_chars_int_advanced(first, last, value, options); - } -}; - -template -fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t -from_chars_advanced(UC const *first, UC const *last, T &value, - parse_options_t options) noexcept { - return from_chars_advanced_caller< - size_t(is_supported_float_type::value) + - 2 * size_t(is_supported_integer_type::value)>::call(first, last, value, - options); -} - -} // namespace fast_float - -#endif diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/scripts/generate-fbreactnativespec.cjs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/scripts/generate-fbreactnativespec.cjs deleted file mode 100644 index a7827f9d60..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/scripts/generate-fbreactnativespec.cjs +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env node - -const fs = require('fs'); -const path = require('path'); - -const [reactNativeRoot, outputDir] = process.argv.slice(2); -if (!reactNativeRoot || !outputDir) { - throw new Error( - 'usage: generate-fbreactnativespec.cjs ', - ); -} -const reactNativeDir = path.resolve(reactNativeRoot); - -const packageRoot = path.resolve(__dirname, '../../..'); -const platformPackage = require(path.join(packageRoot, 'package.json')); -const expectedVersion = platformPackage.peerDependencies['react-native']; -const reactNativePackage = require(path.join(reactNativeDir, 'package.json')); -// The peer range is a minor (`0.87.x`): the generated spec is stable across its -// patch releases. -const expectedMinor = /^(\d+\.\d+)\.x$/u.exec(expectedVersion)?.[1]; -const installedMinor = /^(\d+\.\d+)\./u.exec(reactNativePackage.version)?.[1]; -if ( - expectedMinor === undefined - ? reactNativePackage.version !== expectedVersion - : installedMinor !== expectedMinor -) { - throw new Error( - `React Native ${reactNativePackage.version} is installed; this generated GPUI spec is pinned to ${expectedVersion}. Update the pin and verify the generated C++ before continuing.`, - ); -} - -const codegenUtils = require( - path.join(reactNativeDir, 'scripts/codegen/codegen-utils.js'), -); -const executor = require( - path.join(reactNativeDir, 'scripts/codegen/generate-specs-cli-executor.js'), -); -const schema = codegenUtils - .getCombineJSToSchema() - .combineSchemasInFileList([path.join(reactNativeDir, 'src')], 'android'); - -const generatedDir = path.resolve(outputDir); -fs.rmSync(generatedDir, { recursive: true, force: true }); -fs.mkdirSync(generatedDir, { recursive: true }); -executor.generateSpecFromInMemorySchema( - 'android', - schema, - generatedDir, - 'FBReactNativeSpec', - 'com.facebook.fbreact.specs', - 'all', - false, -); diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/src/lib.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/src/lib.rs deleted file mode 100644 index 65add6edea..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/src/lib.rs +++ /dev/null @@ -1,1075 +0,0 @@ -#[cxx::bridge(namespace = "rngpui")] -pub mod ffi { - // SAFETY: the signature matches the declaration in `GpuiImageLoader.h`. - unsafe extern "C++" { - include!("GpuiImageLoader.h"); - fn rn_gpui_on_image_load_result(request_id: u64, width: f64, height: f64, error: String); - fn rn_gpui_on_image_progress(request_id: u64, loaded: i64, total: i64); - } - - #[derive(Clone, Copy, Debug, Default, PartialEq)] - pub struct RectF { - pub x: f32, - pub y: f32, - pub w: f32, - pub h: f32, - } - - #[derive(Clone, Copy, Debug, Default)] - pub struct EdgesF { - pub left: f32, - pub top: f32, - pub right: f32, - pub bottom: f32, - } - - #[derive(Clone, Copy, Debug, Default)] - pub struct CornersF { - pub tl: f32, - pub tr: f32, - pub br: f32, - pub bl: f32, - } - - #[derive(Clone, Debug, Default)] - pub struct ShadowF { - pub dx: f32, - pub dy: f32, - pub blur: f32, - pub spread: f32, - pub color: u32, - pub inset: bool, - } - - #[derive(Clone, Debug, Default)] - pub struct AccessibilityActionFlat { - pub name: String, - pub label: String, - } - - /// Colors are 0xAARRGGBB, 0 = none. - #[derive(Clone, Debug, Default)] - pub struct ViewPropsFlat { - pub opacity: f32, - pub background_color: u32, - pub border_widths: EdgesF, - pub content_insets: EdgesF, // RN layout border + padding insets - pub border_colors: [u32; 4], // left, top, right, bottom - pub border_styles: [u8; 4], // 0 solid, 1 dotted, 2 dashed - pub border_radii: CornersF, - pub outline_color: u32, - pub outline_width: f32, - pub outline_offset: f32, - pub outline_style: u8, - pub overflow_hidden: bool, - pub display_none: bool, // Fabric layout visibility, including retained descendants - pub pointer_events: u8, // 0 auto, 1 none, 2 box-none, 3 box-only - pub cursor: u8, // RN's `Cursor` ordinal; 0 = auto - pub shadows: Vec, - pub background_json: String, // gradients with their size, position and repeat; empty = none - pub filter_json: String, // `[[name, amount], ...]` from `filter`; empty = none - pub mix_blend_mode: u8, // RN's `BlendMode` ordinal; 0 = normal - pub isolate: bool, // `isolation: 'isolate'` - pub hit_slop: [f32; 4], // `hitSlop`: left, top, right, bottom - pub transform: [f32; 16], // column-major 4x4, resolved with layout - pub has_transform: bool, - pub backface_hidden: bool, // `backfaceVisibility: 'hidden'` - /// Whether `transformOrigin` is in the matrix; when it is not, the view turns about its centre. - pub transform_origin_set: bool, - pub test_id: String, - pub accessibility_label: String, - pub accessibility_hint: String, - pub accessibility_language: String, - pub accessibility_role: String, - pub accessibility_traits: u32, - pub accessibility_value_text: String, - pub accessibility_value_min: i32, - pub accessibility_value_max: i32, - pub accessibility_value_now: i32, - pub accessibility_has_value_min: bool, - pub accessibility_has_value_max: bool, - pub accessibility_has_value_now: bool, - pub accessibility_actions: Vec, - pub accessibility_labelled_by: Vec, - pub accessibility_order: Vec, - pub accessible: bool, - pub accessibility_disabled: bool, - pub accessibility_selected: bool, - pub accessibility_busy: bool, - pub accessibility_checked: u8, // 0 absent, 1 unchecked, 2 checked, 3 mixed - pub accessibility_expanded: i8, // -1 absent, 0 false, 1 true - pub accessibility_important: u8, // Auto, Yes, No, NoHideDescendants - pub accessibility_live_region: u8, // None, Polite, Assertive - pub accessibility_hidden: bool, - pub accessibility_modal: bool, - pub accessibility_responds_to_interaction: bool, - pub accessibility_has_action_listener: bool, - pub accessibility_has_tap_listener: bool, - pub accessibility_has_escape_listener: bool, - pub accessibility_has_magic_tap_listener: bool, - pub accessibility_native_id: String, - pub accessibility_ignores_invert_colors: bool, - pub accessibility_large_content_enabled: bool, - pub accessibility_large_content_title: String, - pub focusable: bool, - pub desktop_drag_region: bool, - /// "minimize" | "maximize" | "close" for a custom caption button. - pub on_context_menu: bool, - pub on_wheel: bool, - pub on_layout: bool, - /// A node's group name, and the JSON of each state style prop; empty = not set. - pub group: String, - pub hover_style: String, - pub active_style: String, - pub focus_style: String, - pub focus_visible_style: String, - pub group_hover_style: String, - pub group_active_style: String, - pub drag_over_style: String, - /// Whether the view takes files dropped from the operating system. - pub accepts_files: bool, - pub tooltip: String, - pub draggable: bool, - pub droppable: bool, - } - - #[derive(Clone, Debug, Default)] - pub struct TextFragmentFlat { - pub text: String, - pub font_family: String, - pub font_size: f32, - pub font_weight: u16, // 100..900 - pub italic: bool, - pub color: u32, - pub line_height: f32, // 0 = default - pub letter_spacing: f32, - pub underline: bool, - pub strikethrough: bool, - pub text_transform: u8, // 0 none, 1 uppercase, 2 lowercase, 3 capitalize - pub font_variant: u32, // RN's FontVariant bitmask - pub background_color: u32, // ARGB, 0 = none - } - - #[derive(Clone, Debug, Default)] - pub struct ParagraphFlat { - pub fragments: Vec, - pub max_lines: i32, // 0 = unlimited - pub text_align: u8, // 0 natural, 1 left, 2 center, 3 right, 4 justify, 5 start, 6 end - pub ellipsize: u8, // 0 tail, 1 head, 2 middle, 3 clip - pub adjusts_to_fit: bool, - pub selectable: bool, - pub min_font_scale: f32, // 0 = no lower bound - pub shadow_color: u32, // ARGB, 0 = none - pub shadow_dx: f32, - pub shadow_dy: f32, - pub shadow_radius: f32, - /// An empty single-line input measured for the height of one line of - /// its font. - pub measure_empty_line: bool, - /// A shaped layout of this paragraph (`rn_gpui_prepare_text`) that the - /// op owns, and the content width it was shaped for. 0 for none. - pub prepared: u64, - pub prepared_width: f32, - } - - #[derive(Clone, Copy, Debug, PartialEq, Eq)] - #[repr(u8)] - pub enum MountKind { - Create = 1, - Delete = 2, - Insert = 4, - Remove = 8, - Update = 16, - } - - /// One validated command argument. `kind` says which field holds it: 0 a - /// number (`number`), 1 a bool (`number` as 0 or 1), 2 a string (`text`), - /// 3 an array of numbers, 4 of bools (`numbers`, each 0 or 1), 5 of strings. - #[derive(Clone, Debug, Default)] - pub struct HostCommandArg { - pub kind: u8, - pub number: f64, - pub text: String, - pub numbers: Vec, - pub texts: Vec, - } - - #[derive(Clone, Debug)] - pub struct MountOp { - pub kind: MountKind, - pub tag: i32, - pub parent_tag: i32, // Insert/Remove/Update, else -1 - pub index: i32, // Insert/Remove, else -1 - /// "View", "Paragraph", "Image", "ScrollView", ...: interned by the host - /// for the life of the process, so an op does not allocate its name. - pub component: &'static str, - pub frame: RectF, // layoutMetrics.frame, relative to parent, DIPs - pub props_changed: bool, - pub view: ViewPropsFlat, - pub extension_props_json: String, - /// The registry index of the host component this op is for, or `-1`. - pub host_index: i32, - /// An owned handle to the node's Fabric props (a `shared_ptr`), or zero. Set on `Create`, and on an `Update` only when the - /// props changed in a way the component can see: Rust takes ownership and - /// the generated accessors read the C++ fields in place. - pub host_props_handle: usize, - /// An owned handle to the node's event emitter, on `Create` only. - pub host_emitter_handle: usize, - /// The props that changed since the props Rust last received, one bit per - /// prop: the first 64 here, any more in `host_changed_more`. Computed in - /// C++ against `oldChildShadowView`, so it is relative to what the - /// component has seen even when several clones happened in between. - pub host_changed: u64, - pub host_changed_more: Vec, - pub has_paragraph: bool, - pub paragraph: ParagraphFlat, // filled for "Paragraph" from its state's AttributedString - pub layout_changed: bool, - /// What changed in a node whose view props did not (the op then carries - /// no whole view). 1 content insets and display, 2 border widths, 4 - /// border radii, 8 transform (these four are groups of `view`), 16 the - /// paragraph's `selectable`, 32 the extension props. - pub layout_patch: u8, - } - - #[derive(Clone, Debug, Default)] - pub struct MountBatch { - pub surface_id: i32, - pub ops: Vec, - /// The size Fabric laid this surface's root out at, in DIPs. - pub content_width: f32, - pub content_height: f32, - /// Whether the surface's root was laid out at all in this commit. A - /// batch from a surface whose root has not been measured yet reports - /// zeros, which must not be mistaken for an empty tree. - pub has_content_size: bool, - } - - #[derive(Clone, Copy, Debug, Default)] - pub struct AnimatedPropsFlat { - pub tag: i32, - pub opacity: f32, - pub has_opacity: bool, - pub transform: [f32; 16], - pub has_transform: bool, - pub reset_transform: bool, - pub background_color: u32, - pub has_background_color: bool, - pub text_color: u32, - pub has_text_color: bool, - } - - #[derive(Clone, Debug)] - pub struct RustModuleMethod { - pub name: String, - pub arg_count: u32, - /// Arguments JS has to pass; the rest may be omitted. - pub required_args: u32, - /// 0 value, 1 void, 2 promise. - pub kind: u8, - /// Whether the spec returns `void`, which makes a promise resolve with - /// `undefined`. - pub returns_void: bool, - pub callback_args: Vec, - } - - #[derive(Clone, Debug)] - pub struct RustModuleEvent { - pub name: String, - pub has_value: bool, - } - - /// What a host component measured under a constraint, if it measures. - #[derive(Clone, Copy, Debug, Default)] - pub struct HostMeasure { - pub width: f32, - pub height: f32, - pub measured: bool, - } - - /// A paragraph shaped by `rn_gpui_prepare_text`: the handle owns a - /// reference to the layout until `rn_gpui_release_prepared`. - #[derive(Clone, Copy, Debug, Default)] - pub struct PreparedText { - pub handle: u64, - pub width: f32, - pub height: f32, - } - - #[derive(Clone, Copy, Debug, Default)] - pub struct MeasureResult { - pub width: f32, - pub height: f32, - } - - /// One laid-out row of a paragraph, for `onTextLayout`. - #[derive(Default)] - pub struct LineFlat { - pub text: String, - pub x: f32, - pub y: f32, - pub width: f32, - pub height: f32, - pub ascender: f32, - pub descender: f32, - pub cap_height: f32, - pub x_height: f32, - } - - extern "Rust" { - fn rn_gpui_load_image(uri: String, request_id: u64); - fn rn_gpui_image_is_cached(uri: &str) -> bool; - fn rn_gpui_load_font(family: &str, uri: &str) -> bool; - fn rn_gpui_render_text_image( - family: &str, - text: &str, - font_size: f64, - color: u32, - ) -> String; - /// Called on the JS/Fabric thread. Must not block, must not touch GPUI. - fn rn_gpui_on_mount(batch: MountBatch); - fn rn_gpui_on_animated_props(props: AnimatedPropsFlat); - fn rn_gpui_on_text_input_command(tag: i32, focus: bool); - fn rn_gpui_request_accessibility_focus(tag: i32); - fn rn_gpui_on_text_input_clear(tag: i32); - /// A wheel event's JS handlers have run: `prevented` is whether one called - /// `preventDefault` or `stopPropagation`. Called on the JS thread. - fn rn_gpui_on_wheel_done(id: u64, prevented: bool); - /// Whether scrollers are drawn the legacy way, always shown. - fn rn_gpui_scroller_legacy() -> bool; - /// A batch of operations for a native tree, as JSON, from JavaScript. - fn rn_gpui_native_root_ops(root: u32, ops: &str); - /// Measures a host component under a constraint on the layout thread. - /// `props` is the address of the node's props handle. - fn rn_gpui_host_measure( - index: u32, - props: usize, - min_width: f32, - min_height: f32, - max_width: f32, - max_height: f32, - ) -> HostMeasure; - /// Whether surfaces start right to left, and whether left and right - /// swap in that direction. - fn rn_gpui_layout_direction_rtl() -> bool; - fn rn_gpui_swap_left_and_right_in_rtl() -> bool; - /// A command Fabric dispatched to a built-in component other than - /// `TextInput`; `args_json` is the JSON array of its arguments. - fn rn_gpui_on_builtin_command(tag: i32, component: &str, name: &str, args_json: &str); - /// A command Fabric dispatched to a host component. The generated C++ - /// dispatcher already validated the arguments against the spec and - /// resolved the command to its index in the spec's `COMMANDS`. - fn rn_gpui_on_host_command(tag: i32, command: u32, args: Vec); - fn rn_gpui_set_animated_active(active: bool); - fn rn_gpui_dev_menu_show(); - fn rn_gpui_dev_setting(name: &str, enabled: bool); - /// Called from a module thread to run a task on the GPUI main thread. - /// The task stays in C++ under `id`; the main loop calls - /// `rn_gpui_run_main_task` for it. - fn rn_gpui_run_on_main(id: u64); - /// Whether the calling thread is the GPUI main thread. - fn rn_gpui_is_main_thread() -> bool; - /// Called on the JS/Fabric thread during layout. Thread-safe. - fn rn_gpui_measure_text( - p: &ParagraphFlat, - max_width: f32, - max_height: f32, - ) -> MeasureResult; - /// Shapes a paragraph for `max_width` like `rn_gpui_measure_text` and - /// returns the layout with it, so the main thread paints it without - /// shaping. Thread-safe. - fn rn_gpui_prepare_text(p: &ParagraphFlat, max_width: f32) -> PreparedText; - /// Another reference to a prepared layout, for an op to carry. - fn rn_gpui_retain_prepared(handle: u64) -> u64; - fn rn_gpui_release_prepared(handle: u64); - /// Called on the JS/Fabric thread when a paragraph asks for `onTextLayout`. - fn rn_gpui_measure_lines(p: &ParagraphFlat, max_width: f32) -> Vec; - fn rn_gpui_log(level: i32, message: &str); - /// Whether `rn_gpui_log` at `level` is written anywhere, so a caller - /// can skip formatting a message nobody reads. - fn rn_gpui_log_enabled(level: i32) -> bool; - fn rn_gpui_on_surface_stopped(surface_id: i32); - } - - extern "Rust" { - /// Returns the handle of a registered module, or 0 when no module has - /// that name. - fn rn_gpui_rust_module_create(name: &str) -> u64; - fn rn_gpui_rust_module_methods(handle: u64) -> Vec; - fn rn_gpui_rust_module_events(handle: u64) -> Vec; - /// Runs a value method on the calling (JS) thread. The result is written - /// into `scope` and returned, or `kDynamicNoNode` when `ok` is false. - fn rn_gpui_rust_module_call_value( - handle: u64, - method: u32, - scope: u32, - args: u32, - ok: &mut bool, - code: &mut String, - message: &mut String, - ) -> u32; - /// Converts the arguments on the calling thread, then queues the call on - /// the module's thread; `ok` reports a conversion failure. - fn rn_gpui_rust_module_call_void( - handle: u64, - method: u32, - scope: u32, - args: u32, - ok: &mut bool, - code: &mut String, - message: &mut String, - ); - /// The same, settling the promise `request` identifies. - fn rn_gpui_rust_module_call_promise( - handle: u64, - method: u32, - scope: u32, - args: u32, - request: i32, - ); - /// Drops the module instance, which stops its thread. - fn rn_gpui_rust_module_drop(handle: u64); - } - - // SAFETY: the signatures match the declarations in `GpuiHostComponent.h`. - unsafe extern "C++" { - include!("GpuiHostComponent.h"); - - /// Releases a props handle a mount op gave Rust. - fn releaseHostPropsHandle(handle: usize); - /// Releases an event emitter handle a `Create` op gave Rust. - fn releaseHostEmitterHandle(handle: usize); - /// How many times the C++ registry was asked for a component since the - /// last reset. Only the test driver reads it. - fn hostEntryLookups() -> u64; - fn resetHostEntryLookups(); - /// Pushes a size a host component measured into its shadow node's state, - /// which is what Yoga reads, and asks for the commit that re-measures. - fn reportHostComponentSize(tag: i32, width: f32, height: f32); - /// Pushes the size a native root laid its tree out at into its shadow - /// node's state, where it becomes Yoga's size for the box. - fn reportNativeRootSize( - tag: i32, - height: f32, - has_width: bool, - width: f32, - min_width: f32, - ) -> bool; - /// Pushes the size the native layout gave a slot's placeholder into the - /// slot's shadow node's state, where it becomes the content's size. - fn reportNativeSlotSize( - tag: i32, - has_width: bool, - width: f32, - has_height: bool, - height: f32, - ) -> bool; - /// Pushes the insets a container reported for its chrome into its shadow - /// node's state, where they become Yoga padding around the children. - fn reportHostComponentInsets(tag: i32, top: f32, right: f32, bottom: f32, left: f32); - } - - // SAFETY: the signatures match the declarations in `GpuiCppHostBridge.h`. - unsafe extern "C++" { - include!("GpuiCppHostBridge.h"); - - /// Creates the C++ view of a `cpp` host component node and gives it its - /// first props. Zero when no C++ implementation is registered. - fn rn_gpui_cpp_host_create(index: u32, tag: i32, props: usize) -> u64; - fn rn_gpui_cpp_host_update(id: u64, props: usize); - /// Creates the node's native view. `kind` is 0 for a composited view, - /// 1 for an NSView and 2 for an X11 window; the result is the view. - #[allow(clippy::too_many_arguments)] - fn rn_gpui_cpp_host_create_view( - id: u64, - windows_visual: usize, - wayland: bool, - x11_window: u32, - xcb_connection: usize, - wayland_display: usize, - wayland_surface: usize, - kind: &mut u8, - ) -> u64; - fn rn_gpui_cpp_host_destroy(id: u64); - } - - // SAFETY: the signatures match the declarations in `GpuiDynamic.h`. - unsafe extern "C++" { - include!("GpuiDynamic.h"); - - /// Values cross as nodes in a C++-owned arena, one scope per call, so - /// nothing is serialised to text. - fn dynamic_scope_open() -> u32; - fn dynamic_scope_close(scope: u32); - fn dynamic_node_new(scope: u32, kind: u8) -> u32; - fn dynamic_node_set_bool(scope: u32, node: u32, value: bool); - fn dynamic_node_set_number(scope: u32, node: u32, value: f64); - fn dynamic_node_set_text(scope: u32, node: u32, text: &str); - fn dynamic_node_set_buffer(scope: u32, node: u32, bytes: &[u8]); - fn dynamic_node_append(scope: u32, parent: u32, child: u32, key: &str); - fn dynamic_node_kind(scope: u32, node: u32) -> u8; - fn dynamic_node_bool(scope: u32, node: u32) -> bool; - fn dynamic_node_number(scope: u32, node: u32) -> f64; - fn dynamic_node_text(scope: u32, node: u32) -> String; - fn dynamic_node_buffer_len(scope: u32, node: u32) -> usize; - fn dynamic_node_buffer(scope: u32, node: u32) -> Vec; - fn dynamic_node_len(scope: u32, node: u32) -> usize; - fn dynamic_node_child(scope: u32, node: u32, index: usize) -> u32; - fn dynamic_node_key(scope: u32, node: u32, index: usize) -> String; - } - - // SAFETY: the signatures match the declarations in `GpuiRustTurboModules.h`. - unsafe extern "C++" { - include!("GpuiRustTurboModules.h"); - - fn rn_gpui_rust_module_result( - request: i32, - ok: bool, - scope: u32, - root: u32, - code: String, - message: String, - ); - fn rn_gpui_rust_callback_invoke(id: u64, scope: u32, root: u32); - fn rn_gpui_rust_callback_drop(id: u64); - fn rn_gpui_rust_module_emit( - handle: u64, - event: &str, - has_value: bool, - scope: u32, - root: u32, - ); - fn rn_gpui_rust_module_send_event(handle: u64, name: &str, scope: u32, root: u32); - /// Drops the promises and JS functions of the runtime that is going - /// away. - fn rn_gpui_rust_module_clear_pending(); - } - - // SAFETY: the signatures match the declarations in `GpuiHttpBridge.h`. - unsafe extern "C++" { - include!("GpuiHttpBridge.h"); - - /// Issue a request; the response arrives through `rn_gpui_http_complete`. - fn rn_gpui_http_request( - request_id: u64, - method: &str, - url: &str, - headers: &str, - body: &str, - ); - fn rn_gpui_http_request_cancel(request_id: u64); - } - - // SAFETY: the signatures match the declarations in `GpuiNetworkConfig.h`. - unsafe extern "C++" { - include!("GpuiNetworkConfig.h"); - - /// Replaces the proxy and DNS settings; returns an error message or an - /// empty string. - fn rn_gpui_network_configure(mode: &str, rules: &str, bypass: &str, doh: &str) -> String; - /// The proxy a request to `url` uses: `DIRECT` or the proxy's URL. - fn rn_gpui_network_proxy_for(url: &str) -> String; - } - - extern "Rust" { - /// Called by the C++ bridge when a request finishes. Implemented in - /// `rn-gpui`, which owns the future waiting for it. - fn rn_gpui_http_complete( - request_id: u64, - status: i32, - headers: &str, - // Bytes, not text: GPUI loads images and fonts through this client, - // and cxx rejects non-UTF-8 for `&str` by throwing. An image response - // crashed the app with "data for rust::Str is not utf-8". - body: &[u8], - error: &str, - ); - } - - // SAFETY: the signature matches the declaration in `GpuiStartupSignpost.h`. - unsafe extern "C++" { - include!("GpuiStartupSignpost.h"); - - /// A startup stage, as an `os_signpost` point event. A no-op off Apple. - fn rn_gpui_startup_signpost(stage: &str, elapsed_ms: u64); - } - - // SAFETY: the signatures match the declarations in `GpuiHost.h`. - unsafe extern "C++" { - include!("GpuiHost.h"); - type GpuiHost; - - fn new_gpui_host( - app_id: &str, - dev_server_host: &str, - dev_server_port: u32, - js_engine: &str, - js_thread: &str, - dev_mode: bool, - ) -> UniquePtr; - fn load_script(self: Pin<&mut GpuiHost>, bundle_path: &str, source_url: &str) -> bool; - fn start_surface( - self: Pin<&mut GpuiHost>, - surface_id: i32, - module_name: &str, - width: f32, - height: f32, - scale: f32, - ); - fn start_surface_with_props( - self: Pin<&mut GpuiHost>, - surface_id: i32, - module_name: &str, - props_json: &str, - width: f32, - height: f32, - scale: f32, - ); - fn set_surface_size( - self: Pin<&mut GpuiHost>, - surface_id: i32, - width: f32, - height: f32, - scale: f32, - ); - /// Starts a surface whose size is a range rather than a point. Fabric - /// lays the root out against the constraints and reports the size it - /// used in every mount batch. - fn start_surface_with_constraints( - self: Pin<&mut GpuiHost>, - surface_id: i32, - module_name: &str, - props_json: &str, - min_width: f32, - min_height: f32, - max_width: f32, - max_height: f32, - scale: f32, - ); - /// Changes a running surface's constraints. - fn set_surface_constraints( - self: Pin<&mut GpuiHost>, - surface_id: i32, - min_width: f32, - min_height: f32, - max_width: f32, - max_height: f32, - scale: f32, - ); - fn set_window_top_inset(self: Pin<&mut GpuiHost>, top: f32); - fn set_app_state(self: Pin<&mut GpuiHost>, state: &str); - fn emit_memory_warning(self: &GpuiHost); - fn set_window_metrics(self: Pin<&mut GpuiHost>, width: f32, height: f32, scale: f32); - fn set_display_metrics( - self: Pin<&mut GpuiHost>, - screen_width: f32, - screen_height: f32, - font_scale: f32, - ); - fn set_system_appearance(self: Pin<&mut GpuiHost>, appearance: &str); - fn rn_gpui_run_main_task(id: u64); - fn stop_surface(self: Pin<&mut GpuiHost>, surface_id: i32); - fn request_reload(self: Pin<&mut GpuiHost>); - fn set_dev_server(self: Pin<&mut GpuiHost>, host: &str, port: u32) -> bool; - fn dev_server_address(self: &GpuiHost) -> String; - fn open_debugger(self: &GpuiHost); - fn js_frame_probe(self: &GpuiHost) -> u64; - fn js_heap_bytes(self: &GpuiHost) -> u64; - fn on_render(self: &GpuiHost) -> Result<()>; - fn on_frame(self: &GpuiHost, timestamp: f64) -> Result<()>; - fn on_pointer_frame(self: &GpuiHost, timestamp: f64) -> Result<()>; - /// payload_json is a JSON object string, e.g. {"pageX":10,"pageY":20} - fn dispatch_event(self: &GpuiHost, tag: i32, event_type: &str, payload_json: &str); - /// Delivers a `topWheel` event whose `nativeEvent` can be prevented, then - /// reports through `rn_gpui_on_wheel_done` once its handlers have run. - fn dispatch_wheel(self: &GpuiHost, tag: i32, id: u64, payload_json: &str); - fn emit_device_event(self: &GpuiHost, event_name: &str); - fn emit_device_event_bool(self: &GpuiHost, event_name: &str, value: bool); - fn emit_device_event_json(self: &GpuiHost, event_name: &str, payload_json: &str); - fn dispatch_pointer_event( - self: &GpuiHost, - target_chain_json: &str, - x: f32, - y: f32, - phase: i32, - timestamp: f64, - ); - fn set_scroll_offset(self: &GpuiHost, tag: i32, x: f32, y: f32); - } -} - -mod rust_module; - -// The `extern "Rust"` declarations in the bridge resolve in this module, so the -// implementations are re-exported here. -pub use rust_module::{ - args_from_dynamic, rn_gpui_rust_module_call_promise, rn_gpui_rust_module_call_value, - rn_gpui_rust_module_call_void, rn_gpui_rust_module_create, rn_gpui_rust_module_drop, - rn_gpui_rust_module_events, rn_gpui_rust_module_methods, value_from_node, value_to_node, -}; - -use std::sync::OnceLock; - -pub use ffi::{ - CornersF, EdgesF, LineFlat, MeasureResult, MountBatch, MountKind, MountOp, ParagraphFlat, - PreparedText, RectF, ShadowF, TextFragmentFlat, ViewPropsFlat, -}; - -/// Where JavaScript runs with the Loom renderer: the `jsThread` autolink -/// recorded, fixed when the app is built. -pub const JS_THREAD: &str = env!("RN_GPUI_JS_THREAD_BUILT"); -/// Whether the Loom renderer was active when this crate was built. -pub const LOOM_RENDERER: bool = match option_env!("RN_GPUI_LOOM_RENDERER_BUILT") { - Some(value) => matches!(value.as_bytes(), b"1"), - None => false, -}; - -pub type MountHandler = Box; -pub type MeasureHandler = - Box ffi::MeasureResult + Send + Sync>; -pub type SurfaceStoppedHandler = Box; -pub type AnimatedPropsHandler = Box; -pub type AnimatedActiveHandler = Box; -pub type TextInputCommandHandler = Box; -pub type TextInputClearHandler = Box; -pub type WheelDoneHandler = Box; -pub type ScrollerLegacyHandler = Box bool + Send + Sync>; -pub type LayoutDirectionHandler = Box (bool, bool) + Send + Sync>; -pub static LAYOUT_DIRECTION_HANDLER: OnceLock = OnceLock::new(); -pub type BuiltinCommandHandler = Box; -/// One command for one tag: the command's index and its validated arguments. -/// Called on the JS/Fabric thread. -pub type HostCommandHandler = Box) + Send + Sync>; -pub type AccessibilityFocusHandler = Box; -pub static MOUNT_HANDLER: OnceLock = OnceLock::new(); -pub type LinesHandler = Box Vec + Send + Sync>; - -pub type PreparedLayout = std::sync::Arc; -pub type PrepareHandler = - Box (PreparedLayout, ffi::MeasureResult) + Send + Sync>; -pub static PREPARE_HANDLER: OnceLock = OnceLock::new(); -pub static LINES_HANDLER: OnceLock = OnceLock::new(); -pub static MEASURE_HANDLER: OnceLock = OnceLock::new(); -pub static SURFACE_STOPPED_HANDLER: OnceLock = OnceLock::new(); -pub static ANIMATED_PROPS_HANDLER: OnceLock = OnceLock::new(); -pub static ANIMATED_ACTIVE_HANDLER: OnceLock = OnceLock::new(); -pub static TEXT_INPUT_COMMAND_HANDLER: OnceLock = OnceLock::new(); -pub static TEXT_INPUT_CLEAR_HANDLER: OnceLock = OnceLock::new(); -pub static WHEEL_DONE_HANDLER: OnceLock = OnceLock::new(); -pub static SCROLLER_LEGACY_HANDLER: OnceLock = OnceLock::new(); -pub type NativeRootOpsHandler = Box; -pub static NATIVE_ROOT_OPS_HANDLER: OnceLock = OnceLock::new(); -pub type HostMeasureHandler = Box Option<(f32, f32)> + Send + Sync>; -pub static HOST_MEASURE_HANDLER: OnceLock = OnceLock::new(); -pub static BUILTIN_COMMAND_HANDLER: OnceLock = OnceLock::new(); -pub static HOST_COMMAND_HANDLER: OnceLock = OnceLock::new(); -pub static ACCESSIBILITY_FOCUS_HANDLER: OnceLock = OnceLock::new(); -pub type MainTaskHandler = Box; -pub static MAIN_TASK_HANDLER: OnceLock = OnceLock::new(); -pub static MAIN_THREAD_ID: OnceLock = OnceLock::new(); - -/// Records the calling thread as the GPUI main thread. The main loop calls this -/// before it can receive main-thread tasks. -pub fn note_main_thread() { - let _ = MAIN_THREAD_ID.set(std::thread::current().id()); -} -pub type DevMenuShowHandler = Box; -pub static DEV_MENU_SHOW_HANDLER: OnceLock = OnceLock::new(); -pub type DevSettingHandler = Box; -pub static DEV_SETTING_HANDLER: OnceLock = OnceLock::new(); -pub type DevMenuPerformHandler = Box; -pub static DEV_MENU_PERFORM_HANDLER: OnceLock = OnceLock::new(); -pub type TrayClickHandler = Box; -pub static TRAY_CLICK_HANDLER: OnceLock = OnceLock::new(); -pub type TrayMenuPerformHandler = Box; -pub static TRAY_MENU_PERFORM_HANDLER: OnceLock = OnceLock::new(); -pub type MenuBarPerformHandler = Box; -pub static MENU_BAR_PERFORM_HANDLER: OnceLock = OnceLock::new(); -/// A finished HTTP request, reported by the bridge. -pub type HttpCompleteHandler = Box, String) + Send + Sync>; -pub static HTTP_COMPLETE_HANDLER: OnceLock = OnceLock::new(); - -pub type ImageHandler = Box; -pub static IMAGE_HANDLER: OnceLock = OnceLock::new(); -pub type ImageCacheQueryHandler = Box bool + Send + Sync>; -pub static IMAGE_CACHE_QUERY_HANDLER: OnceLock = OnceLock::new(); -pub type FontLoadHandler = Box bool + Send + Sync>; -pub type TextImageHandler = Box String + Send + Sync>; -pub static FONT_LOAD_HANDLER: OnceLock = OnceLock::new(); -pub static TEXT_IMAGE_HANDLER: OnceLock = OnceLock::new(); - -fn rn_gpui_load_font(family: &str, uri: &str) -> bool { - FONT_LOAD_HANDLER - .get() - .is_some_and(|handler| handler(family, uri)) -} - -fn rn_gpui_render_text_image(family: &str, text: &str, font_size: f64, color: u32) -> String { - TEXT_IMAGE_HANDLER - .get() - .map_or_else(String::new, |handler| { - handler(family, text, font_size, color) - }) -} - -/// The C++ bridge reports a finished request here. -fn rn_gpui_http_complete(request_id: u64, status: i32, headers: &str, body: &[u8], error: &str) { - if let Some(handler) = HTTP_COMPLETE_HANDLER.get() { - handler( - request_id, - status, - headers.to_string(), - body.to_vec(), - error.to_string(), - ); - } -} - -fn rn_gpui_load_image(uri: String, request_id: u64) { - if let Some(handler) = IMAGE_HANDLER.get() { - handler(uri, request_id); - } else { - ffi::rn_gpui_on_image_load_result( - request_id, - 0.0, - 0.0, - "image loader is not initialized".into(), - ); - } -} - -fn rn_gpui_image_is_cached(uri: &str) -> bool { - IMAGE_CACHE_QUERY_HANDLER - .get() - .map(|handler| handler(uri)) - .unwrap_or(false) -} - -pub const ALL_SURFACES: i32 = -1; - -/// Fabric emits no Delete mutations for a dying surface, so this is the only -/// cleanup signal. -fn rn_gpui_on_surface_stopped(surface_id: i32) { - match SURFACE_STOPPED_HANDLER.get() { - Some(handler) => handler(surface_id), - None => log::debug!( - "rn_gpui_on_surface_stopped({surface_id}): no handler registered yet — dropped" - ), - } -} - -/// Called on the Fabric thread. Queues the batch for the GPUI main thread and -/// returns at once, so mounting never blocks on rendering. -fn rn_gpui_on_mount(batch: ffi::MountBatch) { - match MOUNT_HANDLER.get() { - Some(handler) => handler(batch), - None => { - log::debug!( - "rn_gpui_on_mount: dropping batch for surface {} ({} ops) — no handler registered", - batch.surface_id, - batch.ops.len() - ); - } - } -} - -fn rn_gpui_on_animated_props(props: ffi::AnimatedPropsFlat) { - if let Some(handler) = ANIMATED_PROPS_HANDLER.get() { - handler(props); - } -} - -fn rn_gpui_set_animated_active(active: bool) { - if let Some(handler) = ANIMATED_ACTIVE_HANDLER.get() { - handler(active); - } -} - -fn rn_gpui_on_text_input_command(tag: i32, focus: bool) { - if let Some(handler) = TEXT_INPUT_COMMAND_HANDLER.get() { - handler(tag, focus); - } -} - -fn rn_gpui_on_text_input_clear(tag: i32) { - if let Some(handler) = TEXT_INPUT_CLEAR_HANDLER.get() { - handler(tag); - } -} - -fn rn_gpui_host_measure( - index: u32, - props: usize, - min_width: f32, - min_height: f32, - max_width: f32, - max_height: f32, -) -> ffi::HostMeasure { - let measured = HOST_MEASURE_HANDLER - .get() - .and_then(|handler| handler(index, props, [min_width, min_height, max_width, max_height])); - match measured { - Some((width, height)) => ffi::HostMeasure { - width, - height, - measured: true, - }, - None => ffi::HostMeasure::default(), - } -} - -fn rn_gpui_native_root_ops(root: u32, ops: &str) { - if let Some(handler) = NATIVE_ROOT_OPS_HANDLER.get() { - handler(root, ops); - } -} - -fn rn_gpui_scroller_legacy() -> bool { - SCROLLER_LEGACY_HANDLER - .get() - .is_some_and(|handler| handler()) -} - -fn rn_gpui_on_wheel_done(id: u64, prevented: bool) { - if let Some(handler) = WHEEL_DONE_HANDLER.get() { - handler(id, prevented); - } -} - -fn rn_gpui_layout_direction_rtl() -> bool { - LAYOUT_DIRECTION_HANDLER - .get() - .is_some_and(|handler| handler().0) -} - -fn rn_gpui_swap_left_and_right_in_rtl() -> bool { - LAYOUT_DIRECTION_HANDLER - .get() - .map_or(true, |handler| handler().1) -} - -fn rn_gpui_on_builtin_command(tag: i32, component: &str, name: &str, args_json: &str) { - if let Some(handler) = BUILTIN_COMMAND_HANDLER.get() { - handler(tag, component, name, args_json); - } -} - -fn rn_gpui_on_host_command(tag: i32, command: u32, args: Vec) { - if let Some(handler) = HOST_COMMAND_HANDLER.get() { - handler(tag, command, args); - } -} - -fn rn_gpui_request_accessibility_focus(tag: i32) { - if let Some(handler) = ACCESSIBILITY_FOCUS_HANDLER.get() { - handler(tag); - } -} - -fn rn_gpui_dev_menu_show() { - if let Some(handler) = DEV_MENU_SHOW_HANDLER.get() { - handler(); - } -} - -fn rn_gpui_run_on_main(id: u64) { - match MAIN_TASK_HANDLER.get() { - Some(handler) => handler(id), - None => { - // No main loop is listening (startup, or a build without the - // desktop module), so the task would never run. Say so once. - static WARNED: std::sync::Once = std::sync::Once::new(); - WARNED.call_once(|| { - log::warn!("rn_gpui_run_on_main: no main-thread handler installed; task dropped"); - }); - } - } -} - -fn rn_gpui_is_main_thread() -> bool { - MAIN_THREAD_ID - .get() - .is_some_and(|id| *id == std::thread::current().id()) -} - -fn rn_gpui_dev_setting(name: &str, enabled: bool) { - if let Some(handler) = DEV_SETTING_HANDLER.get() { - handler(name.to_string(), enabled); - } -} - -fn rn_gpui_measure_text( - p: &ffi::ParagraphFlat, - max_width: f32, - max_height: f32, -) -> ffi::MeasureResult { - match MEASURE_HANDLER.get() { - Some(handler) => handler(p, max_width, max_height), - None => ffi::MeasureResult::default(), - } -} - -fn rn_gpui_prepare_text(p: &ffi::ParagraphFlat, max_width: f32) -> ffi::PreparedText { - let Some(handler) = PREPARE_HANDLER.get() else { - return ffi::PreparedText::default(); - }; - let (layout, measured) = handler(p, max_width); - ffi::PreparedText { - handle: Box::into_raw(Box::new(layout)) as u64, - width: measured.width, - height: measured.height, - } -} - -fn rn_gpui_retain_prepared(handle: u64) -> u64 { - if handle == 0 { - return 0; - } - // SAFETY: a nonzero handle is a live `Box` this module made. - let layout = unsafe { &*(handle as *const PreparedLayout) }; - Box::into_raw(Box::new(layout.clone())) as u64 -} - -fn rn_gpui_release_prepared(handle: u64) { - if handle != 0 { - // SAFETY: as above, and released once. - drop(unsafe { Box::from_raw(handle as *mut PreparedLayout) }); - } -} - -/// Takes ownership of the layout an op carries, once. -pub fn take_prepared(handle: u64) -> Option { - // SAFETY: as above; the caller does not use `handle` again. - (handle != 0).then(|| *unsafe { Box::from_raw(handle as *mut PreparedLayout) }) -} - -fn rn_gpui_measure_lines(p: &ffi::ParagraphFlat, max_width: f32) -> Vec { - match LINES_HANDLER.get() { - Some(handler) => handler(p, max_width), - None => Vec::new(), - } -} - -fn rn_gpui_log_enabled(level: i32) -> bool { - log::log_enabled!(match level { - 0 => log::Level::Debug, - 1 => log::Level::Info, - 2 => log::Level::Warn, - _ => log::Level::Error, - }) -} - -fn rn_gpui_log(level: i32, message: &str) { - match level { - 0 => log::debug!("{message}"), - 1 => log::info!("{message}"), - 2 => log::warn!("{message}"), - _ => log::error!("{message}"), - } -} - -// SAFETY: the C++ GpuiHost is created, driven and dropped from the GPUI main -// thread; the wrapper is moved to Rust, so cxx needs this declared explicitly. -unsafe impl Send for ffi::GpuiHost {} -// SAFETY: as for `Send`, every call goes through the GPUI main thread. -unsafe impl Sync for ffi::GpuiHost {} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/src/rust_module.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/src/rust_module.rs deleted file mode 100644 index 265a1552ed..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui-sys/src/rust_module.rs +++ /dev/null @@ -1,481 +0,0 @@ -//! The Rust side of the TurboModule bridge: the handle registry, the value -//! conversions, and the hooks the module crate calls back through. - -use std::collections::HashMap; -use std::sync::{Arc, Mutex, OnceLock}; - -use rn_gpui_module::{ - descriptor, EventEmitter, HostHooks, ModuleDescriptor, ModuleInstance, ModuleQueue, - ModuleThread, RawCallback, Value, -}; - -use crate::ffi; - -const DYNAMIC_NULL: u8 = 0; -const DYNAMIC_BOOL: u8 = 1; -const DYNAMIC_NUMBER: u8 = 2; -const DYNAMIC_STRING: u8 = 3; -const DYNAMIC_ARRAY: u8 = 4; -const DYNAMIC_OBJECT: u8 = 5; -const DYNAMIC_BUFFER: u8 = 6; -const NO_NODE: u32 = 0xffff_ffff; - -/// A module instance JS asked for, with the queue its `void` and `Promise` -/// methods run on. -struct Handle { - instance: Arc, - descriptor: &'static ModuleDescriptor, - queue: OnceLock, -} - -static HANDLES: OnceLock>>> = OnceLock::new(); -static NEXT_HANDLE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); - -fn handles() -> &'static Mutex>> { - HANDLES.get_or_init(|| Mutex::new(HashMap::new())) -} - -fn handle_for(id: u64) -> Option> { - handles() - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .get(&id) - .cloned() -} - -impl Handle { - fn queue(&self) -> &ModuleQueue { - self.queue - .get_or_init(|| ModuleQueue::new(self.descriptor.name)) - } -} - -/// Converts the JS arguments of a call; the positions in `callback_args` hold a -/// `RawCallback` id the C++ side put there. -pub fn args_from_dynamic(scope: u32, args: u32, callback_args: &[usize]) -> Vec { - let converted = value_from_node(scope, args); - let Value::Array(items) = converted else { - return vec![converted]; - }; - items - .into_iter() - .enumerate() - .map(|(index, item)| { - if callback_args.contains(&index) { - match item { - Value::Number(id) => Value::Callback(RawCallback::new(id as u64)), - other => other, - } - } else { - item - } - }) - .collect() -} - -pub fn value_from_node(scope: u32, node: u32) -> Value { - match ffi::dynamic_node_kind(scope, node) { - DYNAMIC_BOOL => Value::Bool(ffi::dynamic_node_bool(scope, node)), - DYNAMIC_NUMBER => Value::Number(ffi::dynamic_node_number(scope, node)), - DYNAMIC_STRING => Value::String(ffi::dynamic_node_text(scope, node)), - DYNAMIC_BUFFER => Value::Buffer(ffi::dynamic_node_buffer(scope, node)), - DYNAMIC_ARRAY => Value::Array( - (0..ffi::dynamic_node_len(scope, node)) - .map(|index| value_from_node(scope, ffi::dynamic_node_child(scope, node, index))) - .collect(), - ), - DYNAMIC_OBJECT => Value::Object( - (0..ffi::dynamic_node_len(scope, node)) - .map(|index| { - let key = ffi::dynamic_node_key(scope, node, index); - let child = ffi::dynamic_node_child(scope, node, index); - (key, value_from_node(scope, child)) - }) - .collect(), - ), - _ => Value::Null, - } -} - -/// Writes the value tree into a scope and returns its root node. A callback -/// never appears in a result, so it becomes null instead of failing the call. -pub fn value_to_node(scope: u32, value: Value) -> u32 { - let (kind, number, text) = match &value { - Value::Null | Value::Callback(_) => (DYNAMIC_NULL, 0.0, String::new()), - Value::Bool(flag) => (DYNAMIC_BOOL, if *flag { 1.0 } else { 0.0 }, String::new()), - Value::Number(number) => (DYNAMIC_NUMBER, *number, String::new()), - Value::String(text) => (DYNAMIC_STRING, 0.0, text.clone()), - Value::Buffer(_) => (DYNAMIC_BUFFER, 0.0, String::new()), - Value::Array(_) => (DYNAMIC_ARRAY, 0.0, String::new()), - Value::Object(_) => (DYNAMIC_OBJECT, 0.0, String::new()), - }; - let node = ffi::dynamic_node_new(scope, kind); - match kind { - DYNAMIC_BOOL => ffi::dynamic_node_set_bool(scope, node, number != 0.0), - DYNAMIC_NUMBER => ffi::dynamic_node_set_number(scope, node, number), - DYNAMIC_STRING => ffi::dynamic_node_set_text(scope, node, &text), - DYNAMIC_BUFFER => { - if let Value::Buffer(bytes) = value { - ffi::dynamic_node_set_buffer(scope, node, &bytes); - } - } - DYNAMIC_ARRAY | DYNAMIC_OBJECT => { - let children = match value { - Value::Array(items) => items - .into_iter() - .map(|item| (String::new(), item)) - .collect::>(), - Value::Object(fields) => fields, - _ => Vec::new(), - }; - for (key, item) in children { - let child = value_to_node(scope, item); - ffi::dynamic_node_append(scope, node, child, &key); - } - } - _ => {} - } - node -} - -/// Builds a value in a fresh scope for a result that crosses later. The caller -/// closes the scope. -fn scope_for_value(value: Value) -> (u32, u32) { - let scope = ffi::dynamic_scope_open(); - let root = value_to_node(scope, value); - (scope, root) -} - -fn result_parts(error: rn_gpui_module::ModuleError) -> (bool, String, String) { - (false, error.code.unwrap_or_default(), error.message) -} - -fn report_result(request: i32, result: Result) { - let (ok, value, code, message) = match result { - Ok(value) => (true, Some(value), String::new(), String::new()), - Err(error) => { - let (_, code, message) = result_parts(error); - (false, None, code, message) - } - }; - let (scope, root) = match value { - Some(value) => scope_for_value(value), - None => (ffi::dynamic_scope_open(), NO_NODE), - }; - ffi::rn_gpui_rust_module_result(request, ok, scope, root, code, message); - ffi::dynamic_scope_close(scope); -} - -fn install_hooks() { - static INSTALLED: OnceLock<()> = OnceLock::new(); - INSTALLED.get_or_init(|| { - rn_gpui_module::set_host_hooks(HostHooks { - invoke_callback: |id, args| { - let (scope, root) = scope_for_value(Value::Array(args)); - ffi::rn_gpui_rust_callback_invoke(id, scope, root); - ffi::dynamic_scope_close(scope); - }, - drop_callback: |id| ffi::rn_gpui_rust_callback_drop(id), - emit_event: |module, event, value| { - let has_value = value.is_some(); - let (scope, root) = match value { - Some(value) => scope_for_value(value), - None => (ffi::dynamic_scope_open(), NO_NODE), - }; - ffi::rn_gpui_rust_module_emit(module, event, has_value, scope, root); - ffi::dynamic_scope_close(scope); - }, - send_event: |module, name, body| { - let (scope, root) = scope_for_value(body); - ffi::rn_gpui_rust_module_send_event(module, name, scope, root); - ffi::dynamic_scope_close(scope); - }, - log: |message| log::error!("{message}"), - }); - }); -} - -pub fn rn_gpui_rust_module_create(name: &str) -> u64 { - let Some(descriptor) = descriptor(name) else { - return 0; - }; - install_hooks(); - let id = NEXT_HANDLE.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let instance = (descriptor.create)(EventEmitter::new(id)); - handles() - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert( - id, - Arc::new(Handle { - instance, - descriptor, - queue: OnceLock::new(), - }), - ); - id -} - -pub fn rn_gpui_rust_module_methods(handle: u64) -> Vec { - let Some(handle) = handle_for(handle) else { - return Vec::new(); - }; - handle - .descriptor - .methods - .iter() - .map(|method| ffi::RustModuleMethod { - name: method.name.to_string(), - arg_count: method.arg_count as u32, - required_args: method.required_args as u32, - kind: match method.kind { - rn_gpui_module::MethodKind::Value => 0, - rn_gpui_module::MethodKind::Void => 1, - rn_gpui_module::MethodKind::Promise => 2, - }, - returns_void: method.returns_void, - callback_args: method - .callback_args - .iter() - .map(|index| *index as u32) - .collect(), - }) - .collect() -} - -pub fn rn_gpui_rust_module_events(handle: u64) -> Vec { - let Some(handle) = handle_for(handle) else { - return Vec::new(); - }; - handle - .descriptor - .events - .iter() - .map(|event| ffi::RustModuleEvent { - name: event.name.to_string(), - has_value: event.has_value, - }) - .collect() -} - -pub fn rn_gpui_rust_module_call_value( - handle: u64, - method: u32, - scope: u32, - args: u32, - ok: &mut bool, - code: &mut String, - message: &mut String, -) -> u32 { - let Some(handle) = handle_for(handle) else { - *ok = false; - *message = "the Rust module is gone".to_string(); - return NO_NODE; - }; - let Some(info) = handle.descriptor.methods.get(method as usize) else { - *ok = false; - *message = "unknown method".to_string(); - return NO_NODE; - }; - let converted = args_from_dynamic(scope, args, info.callback_args); - match handle.instance.call_value(method as usize, converted) { - Ok(value) => { - *ok = true; - value_to_node(scope, value) - } - Err(error) => { - let (_, error_code, error_message) = result_parts(error); - *ok = false; - *code = error_code; - *message = error_message; - NO_NODE - } - } -} - -pub fn rn_gpui_rust_module_call_void( - handle: u64, - method: u32, - scope: u32, - args: u32, - ok: &mut bool, - code: &mut String, - message: &mut String, -) { - let Some(handle) = handle_for(handle) else { - *ok = false; - *message = "the Rust module is gone".to_string(); - return; - }; - let Some(info) = handle.descriptor.methods.get(method as usize) else { - *ok = false; - *message = "unknown method".to_string(); - return; - }; - // Arguments are converted here, on the calling thread, so a bad argument is - // a thrown JS error rather than a silent failure on the module thread. - let converted = args_from_dynamic(scope, args, info.callback_args); - match handle - .instance - .clone() - .prepare_void(method as usize, converted) - { - Ok(work) => { - *ok = true; - post( - &handle, - Box::new(move || { - work(); - Box::pin(async {}) - }), - ); - } - Err(error) => { - let (_, error_code, error_message) = result_parts(error); - *ok = false; - *code = error_code; - *message = error_message; - } - } -} - -pub fn rn_gpui_rust_module_call_promise( - handle: u64, - method: u32, - scope: u32, - args: u32, - request: i32, -) { - let Some(module) = handle_for(handle) else { - report_result( - request, - Err(rn_gpui_module::ModuleError::new("the Rust module is gone")), - ); - return; - }; - let Some(info) = module.descriptor.methods.get(method as usize) else { - report_result( - request, - Err(rn_gpui_module::ModuleError::new("unknown method")), - ); - return; - }; - let converted = args_from_dynamic(scope, args, info.callback_args); - // The future is created on the module's thread: it does not have to be - // `Send`, only the job that builds it does. - let instance = module.instance.clone(); - let job: rn_gpui_module::Job = Box::new(move || { - let future = instance.call_promise(method as usize, converted); - Box::pin(async move { - // A panic here would kill the module thread, and the host is the - // only side that can settle the promise. - let reported = rn_gpui_module::__private::catch_async(async move { - match future { - Ok(future) => report_result(request, future.await), - Err(error) => report_result(request, Err(error)), - } - }) - .await; - if let Err(error) = reported { - rn_gpui_module::log_error("a Rust promise result", &error); - } - }) - }); - post(&module, job); -} - -pub fn rn_gpui_rust_module_drop(handle_id: u64) { - // Removing the last reference stops the queue, which ends its thread and - // drops unfinished futures; results still in flight are discarded by C++ - // because their request ids are gone. - handles() - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .remove(&handle_id); -} - -fn post(handle: &Handle, job: rn_gpui_module::Job) { - match handle.descriptor.thread { - ModuleThread::Own => handle.queue().post(job), - ModuleThread::Main => rn_gpui_module::spawn_main(job), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_nested_value_round_trips_through_a_scope() { - let value = Value::Object(vec![ - ("text".into(), Value::String("hello".into())), - ("count".into(), Value::Number(2.5)), - ("whole".into(), Value::Number(3.0)), - ("flag".into(), Value::Bool(true)), - ("nothing".into(), Value::Null), - ( - "items".into(), - Value::Array(vec![ - Value::Number(1.0), - Value::Object(vec![("deep".into(), Value::String("yes".into()))]), - ]), - ), - ]); - let scope = ffi::dynamic_scope_open(); - let root = value_to_node(scope, value); - let round_tripped = value_from_node(scope, root); - ffi::dynamic_scope_close(scope); - - let Value::Object(fields) = &round_tripped else { - panic!("expected an object, got {round_tripped:?}"); - }; - let field = |name: &str| { - fields - .iter() - .find(|(key, _)| key == name) - .map(|(_, value)| value) - .unwrap_or_else(|| panic!("missing field {name}")) - }; - assert!(matches!(field("text"), Value::String(text) if text == "hello")); - assert!(matches!(field("count"), Value::Number(number) if *number == 2.5)); - assert!(matches!(field("whole"), Value::Number(number) if *number == 3.0)); - assert!(matches!(field("flag"), Value::Bool(true))); - assert!(matches!(field("nothing"), Value::Null)); - let Value::Array(items) = field("items") else { - panic!("expected an array"); - }; - assert_eq!(items.len(), 2); - assert!(matches!(&items[0], Value::Number(number) if *number == 1.0)); - let Value::Object(nested) = &items[1] else { - panic!("expected a nested object"); - }; - assert!(matches!(&nested[0].1, Value::String(text) if text == "yes")); - } - - #[test] - fn callback_positions_become_raw_callbacks() { - let scope = ffi::dynamic_scope_open(); - let args = value_to_node( - scope, - Value::Array(vec![Value::String("key".into()), Value::Number(41.0)]), - ); - let converted = args_from_dynamic(scope, args, &[1]); - ffi::dynamic_scope_close(scope); - assert!(matches!(&converted[0], Value::String(text) if text == "key")); - match &converted[1] { - Value::Callback(callback) => assert_eq!(callback.id(), 41), - other => panic!("expected a callback, got {other:?}"), - } - } -} - -/// `GpuiHost.cpp` calls this hook, which the `rn-gpui` crate defines. This -/// crate's own unit-test binary links the C++ core without `rn-gpui`, so on -/// Linux the reference is unresolved. Windows uses an `/alternatename` fallback -/// in the C++ instead. Lives here rather than in `lib.rs` because `lib.rs` is a -/// prebuilt input and this is test-only. -#[cfg(test)] -#[no_mangle] -pub extern "C" fn rn_gpui_accessibility_active() -> bool { - false -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/Cargo.toml b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/Cargo.toml deleted file mode 100644 index eccb6b5d6b..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/Cargo.toml +++ /dev/null @@ -1,135 +0,0 @@ -[package] -name = "react-native-gpui" -version = "0.1.0" -edition = "2021" -links = "rn_gpui_runtime" - -[features] -# Test/probe controls: synthetic input, resize/scale/headless overrides, custom -# window-state paths, startup tracing, native-view probes, and frame capture. -# `RN_GPUI_SCREENSHOT` renders the window's own scene to a PNG off-screen. -# gpui's `Window::render_to_image` is gated on `test-support` in gpui, -# gpui_macos, gpui_apple and (with the Linux patches) gpui_linux, so the -# feature has to be enabled at the platform crate too. -visual-capture = ["gpui_platform/test-support"] -# A local-only WebSocket test driver. It is absent from normal builds. -test-driver = ["visual-capture", "dep:tungstenite"] -# Enables Window's draw/present histograms for the 10k-node benchmark. -perf-timing = ["gpui/profiler"] -# Compiles the Metal shaders when the app starts instead of at build time, so a -# macOS build needs no Metal compiler (which only ships with full Xcode). -runtime-shaders = ["gpui_platform/runtime_shaders"] - -[build-dependencies] -rn-gpui-module-build = { path = "../rn-gpui-module-build" } - -[dependencies] -rn-gpui-sys = { path = "../rn-gpui-sys" } -rn-gpui-module = { path = "../rn-gpui-module" } -gpui = { workspace = true } -cxx = { workspace = true } -async-channel = { workspace = true } -anyhow = { workspace = true } -log = { workspace = true } -env_logger = { workspace = true } -serde_json = { workspace = true } -futures = { workspace = true } -http_client = { workspace = true } -fontdue = { workspace = true } -image = { version = "0.25.1" } -base64 = "0.22" -sys-locale = "0.3" -# Menu-bar (tray) apps: NSStatusItem on macOS, the notification area -# on Windows, StatusNotifierItem on Linux. `default-features = false` because -# the crate default is its GTK Linux backend; the Linux block below selects the -# GTK-free one instead (Cargo unifies features per crate, so a default here -# would keep the GTK backend enabled no matter what the target block asked for). -# macOS and Windows backends are not feature-gated, so they are unaffected. -tray-icon = { version = "0.26", default-features = false } -# Shortcuts that fire while no window of the app has focus. -global-hotkey = "0.9" -tungstenite = { version = "0.26", default-features = false, features = ["handshake"], optional = true } - -[lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ['cfg(feature, values("cargo-clippy"))'] } - -[target.'cfg(any(target_os = "macos", target_os = "windows"))'.dependencies] -# Native context menus. On macOS this is an NSMenu shown for the -# window's NSView; on Windows a Win32 popup menu on the HWND. -muda = "0.15" - -[target.'cfg(target_os = "macos")'.dependencies] -# `font-kit` makes gpui_macos build a real (CoreText) text system; without it -# every glyph paints as nothing. -gpui_platform = { workspace = true, features = ["font-kit"] } -cocoa = "0.25" -block = "0.1" -objc = "0.2" -raw-window-handle = "0.6" - -[target.'cfg(target_os = "linux")'.dependencies] -# gpui_platform intentionally has no default features. Enable both backends so -# Linux users can run under either X11 or Wayland. -gpui_platform = { workspace = true, features = ["x11", "wayland"] } -# `tray-icon`'s default Linux backend is `libappindicator`, which is a GTK -# widget: `app_indicator_new` needs a GTK screen and its menu needs the GTK main -# loop. GPUI runs its own X11 loop and never enters a GTK one, so the icon was -# created but never appeared (the process logged -# `gtk_icon_theme_get_for_screen: assertion 'GDK_IS_SCREEN (screen)' failed`). -# `ksni` is the same StatusNotifierItem protocol over plain D-Bus, served from a -# worker thread, and needs no GTK. -tray-icon = { version = "0.26", default-features = false, features = ["ksni"] } -# Already in the tree through `ksni`; named directly so the tray can ask the -# session bus whether a StatusNotifier host is running (see -# `tray_host_available`). "blocking-api" supplies the synchronous `Connection`. -zbus = { version = "5", default-features = false, features = ["blocking-api"] } -# `poll` on `/proc/pressure/memory` for the memory warning. -libc = "0.2" - -# X11 window calls GPUI does not expose. Wayland has no -# equivalent, so those sessions stay `unsupported`. The X11 path reads the -# window's raw handle, which gpui exposes through raw-window-handle. -x11-dl = "2.21" -raw-window-handle = "0.6" - -[target.'cfg(target_os = "windows")'.dependencies] -gpui_platform = { workspace = true } -# Win32 window calls GPUI does not expose. -windows-sys = { version = "0.59", features = [ - "Win32_Foundation", - # `MonitorFromPoint` and `GetMonitorInfoW`: the work area a popover is placed in. - "Win32_Graphics_Gdi", - # `RegGetValueW`: the text scale the user chose in Accessibility settings. - "Win32_System_Registry", - # `AssocQueryStringW`: whether a URL scheme has a registered handler. - "Win32_UI_Shell", - # `CreateMemoryResourceNotification`: the low-memory signal. - "Win32_System_Memory", - "Win32_System_Threading", - # `GetDpiForSystem`: the scale a tray icon's physical rectangle is divided by. - "Win32_UI_HiDpi", - "Win32_UI_WindowsAndMessaging", - # `keybd_event`: the test driver takes the foreground for its window. - "Win32_UI_Input_KeyboardAndMouse", - # `CreateNamedPipeW`: the single-instance pipe, with an owner-only access list. - "Win32_System_Pipes", - "Win32_System_IO", - "Win32_Storage_FileSystem", - "Win32_Security", - "Win32_Security_Authorization", - # `DwmFlush`: wait for the compositor before a screen copy in the test driver. - "Win32_Graphics_Dwm", -] } -# `InputPane`: the on-screen keyboard's occluded rectangle. `DataTransferManager`: the -# system share UI. -windows = { version = "0.62", features = [ - "UI_ViewManagement", - "ApplicationModel_DataTransfer", - "Foundation", - "Win32_System_WinRT", - "Win32_UI_Shell", - "Win32_Foundation", -] } -# The HWND for the native menu bar and context menus, read from the window's -# raw handle the same way macOS reads its NSView. -raw-window-handle = "0.6" diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/build.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/build.rs deleted file mode 100644 index 016e52db1b..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/build.rs +++ /dev/null @@ -1,75 +0,0 @@ -//! rpath metadata for the host executable and consuming desktop app. -//! -//! Linked libraries built with `@rpath/...` install names — `libjsi.dylib` from -//! our CMake build, and any shared library an installed JS engine package adds — -//! so an executable that links them needs those directories on its rpath at run -//! time. -//! The sys crate exports paths as `DEP_RN_GPUI_CORE_RPATHS`. Re-export them as -//! `DEP_RN_GPUI_RUNTIME_RPATHS` for the app-local desktop crate's build.rs; a -//! downstream executable must carry its own rpath because the host runtime is -//! an rlib dependency. -//! -//! The same file re-exports the engine's Node-API export list, which the app's -//! build script turns into a module definition (see `DEP_RN_GPUI_CORE_NODE_API_EXPORTS`). - -fn main() { - rn_gpui_module_build::generate(&[ - "../../src-gpui/src/private/specs/NativeGpuiDesktop.ts", - "../../src-gpui/src/private/specs/NativeGpuiAlertManager.ts", - "../../src-gpui/src/private/specs/NativeGpuiApp.ts", - "../../src-gpui/src/private/specs/NativeGpuiClipboard.ts", - "../../src-gpui/src/private/specs/NativeGpuiNetwork.ts", - "../../src-gpui/src/private/specs/NativeGpuiLinkingManager.ts", - "../../src-gpui/src/private/specs/NativeGpuiI18nManager.ts", - "../../src-gpui/src/private/specs/NativeGpuiShare.ts", - "../../src-gpui/src/private/specs/NativeGpuiPerfMonitor.ts", - "../../src-gpui/src/private/specs/NativeGpuiTray.ts", - "../../src-gpui/src/private/specs/NativeGpuiWindows.ts", - "../../src-gpui/src/private/specs/NativeGpuiAppMenu.ts", - "../../src-gpui/src/private/specs/NativeGpuiContextMenu.ts", - "../../src-gpui/src/private/specs/NativeGpuiDevMenu.ts", - "../../src-gpui/src/private/specs/NativeGpuiShortcuts.ts", - "../../src-gpui/src/private/specs/NativeVibration.ts", - "../../src-gpui/src/private/specs/NativeSettingsManager.ts", - ]); - println!("cargo:rerun-if-changed=build.rs"); - println!("cargo:rerun-if-env-changed=DEP_RN_GPUI_CORE_RPATHS"); - println!("cargo:rerun-if-env-changed=DEP_RN_GPUI_CORE_NODE_API_EXPORTS"); - println!("cargo:rerun-if-env-changed=DEP_RN_GPUI_CORE_NODE_API_LIBRARY"); - - // Windows needs the Node-API forwarding even though it has no rpath, so - // re-export those two before the early return below. - for (from, to) in [ - ( - "DEP_RN_GPUI_CORE_NODE_API_EXPORTS", - "cargo:node_api_exports", - ), - ( - "DEP_RN_GPUI_CORE_NODE_API_LIBRARY", - "cargo:node_api_library", - ), - ] { - if let Ok(value) = std::env::var(from) { - if !value.is_empty() { - println!("{to}={value}"); - } - } - } - - let Ok(dirs) = std::env::var("DEP_RN_GPUI_CORE_RPATHS") else { - return; - }; - let dirs = dirs - .split('|') - .filter(|dir| !dir.is_empty()) - .collect::>(); - println!("cargo:rpaths={}", dirs.join("|")); - if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { - // Windows locates DLLs beside the executable or through PATH; ELF and - // Mach-O rpath linker flags are invalid for MSVC and MinGW targets. - return; - } - for dir in dirs { - println!("cargo:rustc-link-arg=-Wl,-rpath,{dir}"); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/accessibility.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/accessibility.rs deleted file mode 100644 index 0dd537d1d1..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/accessibility.rs +++ /dev/null @@ -1,288 +0,0 @@ -use crate::{node_view::RNNodeView, store::StoreGlobal}; -use gpui::{App, Entity, FocusHandle, Global, Window}; -use std::collections::HashSet; - -#[derive(Default)] -struct ModalFocusState { - active: Option, - visible: HashSet, - restore: Option<(i32, FocusHandle)>, - pending_focus: bool, -} -impl Global for ModalFocusState {} - -pub(crate) fn hidden_by_active_modal(tag: i32, cx: &App) -> bool { - cx.try_global::() - .is_some_and(|state| state.active.is_some() && !state.visible.contains(&tag)) -} - -fn collect_modal( - node: &Entity, - cx: &App, - tags: &mut HashSet, - focus: &mut Vec, -) { - let node = node.read(cx); - if node.view.display_none - || node.view.accessibility_hidden - || node.view.accessibility_important == 3 - { - return; - } - tags.insert(node.tag); - if node.focusable - && !node.view.accessibility_disabled - && node.view.accessibility_responds_to_interaction - { - if let Some(handle) = node.accessibility_focus_handle() { - focus.push(handle); - } - } - for (_, child) in &node.children { - collect_modal(child, cx, tags, focus); - } -} - -/// Called after the mount/render transaction, while no RN entity is leased. -pub(crate) fn sync_modal_focus(window: &mut Window, cx: &mut App) { - let Some(store) = cx.try_global::().map(|store| store.0.clone()) else { - return; - }; - let (active, descendants, visible, targets, fallback, nodes, focused) = { - let store = store.read(cx); - #[cfg(feature = "visual-capture")] - if std::env::var_os("RN_GPUI_DEBUG_A11Y_TREE").is_some() { - log::info!( - "[accessibility] sync modal tags={:?}", - store.accessibility_modal_tags - ); - } - if store.accessibility_modal_tags.is_empty() - && cx - .try_global::() - .is_none_or(|state| state.active.is_none()) - { - return; - } - let active = store.accessibility_modal_tags.iter().rev().find_map(|tag| { - store - .nodes - .get(tag) - .filter(|node| { - let node = node.read(cx); - !node.view.display_none && !node.view.accessibility_hidden - }) - .map(|node| (*tag, node.clone())) - }); - let mut descendants = HashSet::new(); - let mut targets = Vec::new(); - let mut visible = HashSet::new(); - let mut fallback = None; - if let Some((_, modal)) = &active { - collect_modal(modal, cx, &mut descendants, &mut targets); - visible.clone_from(&descendants); - let modal = modal.read(cx); - fallback = modal.accessibility_focus_handle(); - let mut parent = modal.parent.clone(); - while let Some(entity) = parent.and_then(|node| node.upgrade()) { - let node = entity.read(cx); - visible.insert(node.tag); - parent = node.parent.clone(); - } - } - let focused = store.nodes.iter().find_map(|(tag, node)| { - node.read(cx) - .accessibility_focus_handle() - .filter(|handle| handle.is_focused(window)) - .map(|handle| (*tag, handle)) - }); - ( - active.map(|(tag, _)| tag), - descendants, - visible, - targets, - fallback, - store.nodes.values().cloned().collect::>(), - focused, - ) - }; - if cx.try_global::().is_none() { - cx.set_global(ModalFocusState::default()); - } - let state = cx.global_mut::(); - let changed = state.active != active; - let tree_changed = state.visible != visible; - if changed && state.active.is_none() && active.is_some() { - state.restore = focused; - } - if changed { - state.pending_focus = active.is_some(); - } - let pending_focus = state.pending_focus; - state.active = active; - state.visible = visible; - let restore = if changed && active.is_none() { - state.restore.take() - } else { - None - }; - if changed || tree_changed { - for node in nodes { - node.update(cx, |node, cx| { - node.set_accessibility_tab_stop_allowed( - active.is_none() || descendants.contains(&node.tag), - ); - cx.notify(); - }); - } - window.refresh(); - } - if changed || pending_focus { - if active.is_some() { - if let Some(target) = targets.first().cloned().or(fallback) { - target.focus(window, cx); - cx.global_mut::().pending_focus = false; - } else { - window.on_next_frame(sync_modal_focus); - window.refresh(); - } - } else if let Some((tag, handle)) = restore { - if store.read(cx).nodes.contains_key(&tag) { - handle.focus(window, cx); - } - } - log::info!( - "[accessibility] modal focus active={active:?} restored={}", - active.is_none() - ); - } -} - -/// What `AccessibilityInfo.announceForAccessibility` asked the screen reader to -/// say, shown as a live region of the window: a change of its label is what -/// Narrator and Orca read out. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct Announcement { - pub label: String, - pub assertive: bool, -} - -static ANNOUNCEMENT: std::sync::Mutex> = std::sync::Mutex::new(None); - -/// The label a live region carries for announcement number `sequence`. A -/// zero-width space on every other announcement makes a repeated message a -/// change. -fn announcement_label(text: &str, sequence: u64) -> String { - if sequence % 2 == 1 { - format!("{text}\u{200b}") - } else { - text.to_string() - } -} - -/// Priority 0 is `low`; the rest interrupt. -fn is_assertive(priority: i32) -> bool { - priority > 0 -} - -pub(crate) fn current_announcement() -> Option { - let state = ANNOUNCEMENT.lock().expect("announcement poisoned"); - state - .as_ref() - .map(|(sequence, text, priority)| Announcement { - label: announcement_label(text, *sequence), - assertive: is_assertive(*priority), - }) -} - -fn record_announcement(text: &str, priority: i32) { - let mut state = ANNOUNCEMENT.lock().expect("announcement poisoned"); - let sequence = state.as_ref().map_or(0, |(sequence, _, _)| sequence + 1); - *state = Some((sequence, text.to_string(), priority)); -} - -/// The live region element for the current announcement. -pub(crate) fn announcement_element(announcement: Announcement) -> impl gpui::IntoElement { - use gpui::{div, prelude::*, px, Role}; - let live = if announcement.assertive { - gpui::accesskit::Live::Assertive - } else { - gpui::accesskit::Live::Polite - }; - div() - .id("accessibility-announcement") - .absolute() - .top_0() - .left_0() - .size(px(1.0)) - .role(Role::Status) - .aria_label(announcement.label) - .a11y_synthetic_children(move |builder| { - let node = builder.parent_node(); - node.set_live(live); - node.set_live_atomic(); - }) -} - -#[cfg(not(target_os = "macos"))] -extern "C" { - fn rn_gpui_set_announce_handler(handler: extern "C" fn(*const std::ffi::c_char, i32)); -} - -#[cfg(not(target_os = "macos"))] -extern "C" fn on_announce(text: *const std::ffi::c_char, priority: i32) { - if text.is_null() { - return; - } - // SAFETY: the caller passes a NUL-terminated string that outlives the call. - let text = unsafe { std::ffi::CStr::from_ptr(text) }.to_string_lossy(); - record_announcement(&text, priority); - crate::desktop::post_to_main(Box::new(|cx: &mut App| { - let Some(store) = crate::store::store_from(cx) else { - return; - }; - let window = store.read(cx).window; - if let Some(window) = window.downcast::() { - let _ = window.update(cx, |_root, _window, cx| cx.notify()); - } - })); -} - -/// Routes the host's announcements to the window. macOS has the system's own. -#[cfg(not(target_os = "macos"))] -pub(crate) fn install_announcer() { - // SAFETY: the handler is a plain function that lives for the whole process. - unsafe { rn_gpui_set_announce_handler(on_announce) }; -} - -#[cfg(test)] -mod announcement_tests { - use super::*; - - #[test] - fn a_repeated_message_changes_the_label() { - assert_eq!(announcement_label("Saved", 0), "Saved"); - assert_eq!(announcement_label("Saved", 1), "Saved\u{200b}"); - assert_eq!(announcement_label("Saved", 2), "Saved"); - } - - #[test] - fn low_priority_waits_and_the_rest_interrupt() { - assert!(!is_assertive(0)); - assert!(is_assertive(1)); - assert!(is_assertive(2)); - } - - #[test] - fn each_announcement_replaces_the_last() { - record_announcement("one", 1); - let first = current_announcement().unwrap(); - record_announcement("one", 1); - let second = current_announcement().unwrap(); - assert_ne!(first.label, second.label); - record_announcement("two", 0); - let third = current_announcement().unwrap(); - assert!(third.label.starts_with("two")); - assert!(!third.assertive); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/animation_policy.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/animation_policy.rs deleted file mode 100644 index c3b44730f4..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/animation_policy.rs +++ /dev/null @@ -1,44 +0,0 @@ -//! Test-only override for platform-owned transitions. -//! -//! This does not change the operating system's reduce-motion preference and -//! does not suppress React Native's frame callbacks (which animated values -//! need in order to reach their final state). - -#[cfg(feature = "test-driver")] -use std::sync::atomic::{AtomicBool, Ordering}; - -#[cfg(feature = "test-driver")] -static DISABLED: AtomicBool = AtomicBool::new(false); - -/// Whether the test driver turned platform transitions off. A component library -/// with transitions of its own follows it, as it follows the system's reduce-motion -/// setting, so a test sees the end state at once. -pub fn animations_disabled() -> bool { - #[cfg(feature = "test-driver")] - { - return DISABLED.load(Ordering::Relaxed); - } - - #[cfg(not(feature = "test-driver"))] - false -} - -#[cfg(feature = "test-driver")] -pub(crate) fn set_animations_disabled(disabled: bool) { - DISABLED.store(disabled, Ordering::Relaxed); -} - -#[cfg(all(test, feature = "test-driver"))] -mod tests { - use super::{animations_disabled, set_animations_disabled}; - - #[test] - fn test_driver_can_toggle_animations_without_changing_reduce_motion() { - set_animations_disabled(false); - assert!(!animations_disabled()); - set_animations_disabled(true); - assert!(animations_disabled()); - set_animations_disabled(false); - assert!(!animations_disabled()); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/app_hooks.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/app_hooks.rs deleted file mode 100644 index 092019aca0..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/app_hooks.rs +++ /dev/null @@ -1,289 +0,0 @@ -//! Opt-in hooks a module registers from `rn_gpui_register()`. -//! -//! An app that links no module registering one sees no change: with nothing -//! registered each hook does nothing and windows open as they always did. - -use crate::store::SurfaceRootView; -use gpui::{ - AnyView, AnyWindowHandle, App, AppContext, Context, Entity, Render, Subscription, Window, - WindowOptions, -}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex}; - -type AppInit = Arc; - -pub(crate) type RootBuilder = Box Entity>; - -type RootOpener = Arc< - dyn Fn(&mut App, WindowOptions, RootBuilder) -> anyhow::Result + Send + Sync, ->; - -static APP_INITS: Mutex> = Mutex::new(Vec::new()); -static APP_INIT_DONE: AtomicBool = AtomicBool::new(false); -static ASSET_SOURCES: Mutex>> = Mutex::new(Vec::new()); -static ROOT_OPENER: Mutex> = Mutex::new(None); - -/// Registers `init` to run once, with the `App`, before the first window opens. -/// -/// Called from a module's `rn_gpui_register()`. Several may be registered; they -/// run in registration order. Registering after the first window opened does -/// nothing. -pub fn register_app_init(init: Arc) { - APP_INITS - .lock() - .expect("app init registry poisoned") - .push(init); -} - -/// Registers a source of assets (icons, images by path) that the app loads -/// from, beside the ones registered before it: a path is loaded from the first -/// source that has it. -/// -/// Called from a module's `rn_gpui_register()`. Assets are read when the -/// application starts, so a source registered later is not used. -pub fn register_asset_source(source: impl gpui::AssetSource + 'static) { - ASSET_SOURCES - .lock() - .expect("asset source registry poisoned") - .push(Arc::new(source)); -} - -struct CombinedAssets(Vec>); - -impl gpui::AssetSource for CombinedAssets { - fn load(&self, path: &str) -> anyhow::Result>> { - for source in &self.0 { - if let Some(asset) = source.load(path)? { - return Ok(Some(asset)); - } - } - Ok(None) - } - - fn list(&self, path: &str) -> anyhow::Result> { - let mut all = Vec::new(); - for source in &self.0 { - all.extend(source.list(path)?); - } - Ok(all) - } -} - -/// The application with the registered asset sources, when there are any. -pub(crate) fn with_registered_assets(application: gpui::Application) -> gpui::Application { - match registered_assets() { - Some(assets) => application.with_assets(assets), - None => application, - } -} - -/// The registered asset sources as one, when there are any. -pub(crate) fn registered_assets() -> Option { - let sources = ASSET_SOURCES - .lock() - .expect("asset source registry poisoned") - .clone(); - (!sources.is_empty()).then(|| CombinedAssets(sources)) -} - -/// Runs the registered app init hooks the first time it is called. -pub(crate) fn run_app_init(cx: &mut App) { - if APP_INIT_DONE.swap(true, Ordering::SeqCst) { - return; - } - let inits: Vec = APP_INITS - .lock() - .expect("app init registry poisoned") - .clone(); - for init in inits { - init(cx); - } -} - -/// Registers a wrapper for the root view of every window that hosts a React -/// tree (the main window, windows opened with `DesktopWindow.open` and tray -/// popovers). -/// -/// `wrap` receives the root view that takes the React tree and returns the -/// view that becomes the window's root, typically one that holds the given -/// view as a child. Its type `V` is the window's root type, so a library that -/// looks the root up with `window.root::()` finds it. A second call replaces -/// the first. -/// -/// Called from a module's `rn_gpui_register()`. -pub fn register_root_wrapper( - wrap: impl Fn(AnyView, &mut Window, &mut App) -> Entity + Send + Sync + 'static, -) { - let wrap = Arc::new(wrap); - let opener: RootOpener = Arc::new(move |cx, options, build| { - let wrap = wrap.clone(); - cx.open_window(options, move |window, cx| { - let root = build(window, cx); - wrap(root.into(), window, cx) - }) - .map(Into::into) - }); - *ROOT_OPENER.lock().expect("root wrapper registry poisoned") = Some(opener); -} - -/// What window-level observers and hooks run against. Its window's root view -/// can be of any type once a root wrapper is registered, so they cannot use it. -pub(crate) struct WindowObservers; - -/// Runs `f` with a context for observers that belong to a window, and returns -/// with it a subscription that keeps the context alive until it is dropped. -pub(crate) fn observer_context( - cx: &mut App, - f: impl FnOnce(&mut Context) -> R, -) -> (R, Subscription) { - let entity = cx.new(|_| WindowObservers); - let result = entity.update(cx, |_, cx| f(cx)); - (result, Subscription::new(move || drop(entity))) -} - -/// For one observer: its subscription, which also keeps the context alive. -pub(crate) fn observer_context_joined( - cx: &mut App, - f: impl FnOnce(&mut Context) -> Subscription, -) -> Subscription { - let (subscription, keep_alive) = observer_context(cx, f); - Subscription::new(move || { - drop(subscription); - drop(keep_alive); - }) -} - -/// The same for observers that last as long as the app: the context is never -/// released. -pub(crate) fn observer_context_for_good( - cx: &mut App, - f: impl FnOnce(&mut Context) -> R, -) -> R { - let entity = cx.new(|_| WindowObservers); - let result = entity.update(cx, |_, cx| f(cx)); - std::mem::forget(entity); - result -} - -/// Opens a window whose React root `build` makes, wrapped by the registered -/// root wrapper if there is one. -pub(crate) fn open_root_window( - cx: &mut App, - options: WindowOptions, - build: impl FnOnce(&mut Window, &mut App) -> Entity + 'static, -) -> anyhow::Result { - let opener = ROOT_OPENER - .lock() - .expect("root wrapper registry poisoned") - .clone(); - match opener { - Some(opener) => opener(cx, options, Box::new(build)), - None => cx.open_window(options, build).map(Into::into), - } -} - -#[cfg(test)] -pub(crate) static TEST_LOCK: Mutex<()> = Mutex::new(()); - -#[cfg(test)] -pub(crate) fn reset_for_test() { - APP_INITS.lock().unwrap().clear(); - APP_INIT_DONE.store(false, Ordering::SeqCst); - *ROOT_OPENER.lock().unwrap() = None; -} - -#[cfg(test)] -mod tests { - use super::*; - use gpui::{div, IntoElement, ParentElement, TestAppContext}; - use std::sync::atomic::AtomicUsize; - - struct Wrapper { - inner: AnyView, - } - - impl Render for Wrapper { - fn render(&mut self, _: &mut Window, _: &mut gpui::Context) -> impl IntoElement { - div().child(self.inner.clone()) - } - } - - fn build(window: &mut Window, cx: &mut App) -> Entity { - let _ = window; - cx.new(|_| SurfaceRootView::new(1)) - } - - #[gpui::test] - fn without_a_wrapper_the_window_root_is_the_surface_root(cx: &mut TestAppContext) { - let _guard = TEST_LOCK - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - reset_for_test(); - let handle = cx - .update(|cx| open_root_window(cx, WindowOptions::default(), build)) - .unwrap(); - let is_surface_root = cx - .update(|cx| { - handle.update(cx, |_, window, _| { - window.root::().flatten().is_some() - }) - }) - .unwrap(); - assert!(is_surface_root); - } - - #[gpui::test] - fn a_registered_wrapper_becomes_the_window_root_and_holds_the_surface_root( - cx: &mut TestAppContext, - ) { - let _guard = TEST_LOCK - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - reset_for_test(); - let wrapped = Arc::new(AtomicUsize::new(0)); - let counter = wrapped.clone(); - register_root_wrapper(move |inner, _window, cx| { - counter.fetch_add(1, Ordering::SeqCst); - cx.new(|_| Wrapper { inner }) - }); - let handle = cx - .update(|cx| open_root_window(cx, WindowOptions::default(), build)) - .unwrap(); - assert_eq!(wrapped.load(Ordering::SeqCst), 1); - let (wrapper_is_root, surface_is_root) = cx - .update(|cx| { - handle.update(cx, |_, window, _| { - ( - window.root::().flatten().is_some(), - window.root::().flatten().is_some(), - ) - }) - }) - .unwrap(); - assert!(wrapper_is_root); - assert!(!surface_is_root); - reset_for_test(); - } - - #[gpui::test] - fn app_init_hooks_run_once_in_order_and_nothing_registered_does_nothing( - cx: &mut TestAppContext, - ) { - let _guard = TEST_LOCK - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - reset_for_test(); - cx.update(run_app_init); - let log = Arc::new(Mutex::new(Vec::new())); - reset_for_test(); - for name in ["first", "second"] { - let log = log.clone(); - register_app_init(Arc::new(move |_| log.lock().unwrap().push(name))); - } - cx.update(run_app_init); - cx.update(run_app_init); - assert_eq!(*log.lock().unwrap(), vec!["first", "second"]); - reset_for_test(); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/bootstrap.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/bootstrap.rs deleted file mode 100644 index 26351e439e..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/bootstrap.rs +++ /dev/null @@ -1,3019 +0,0 @@ -use crate::host::Host; -use crate::store::{ - LayoutEventOwner, OverlayHost, StoreGlobal, SurfaceRootView, ViewStore, APP_SURFACE_ID, -}; -use gpui::{point, px, size, App, AppContext, Application, Bounds, WindowBounds, WindowOptions}; -use rn_gpui_sys::ffi::MountBatch; -use std::cell::Cell; -use std::rc::Rc; -use std::time::Duration; - -// SAFETY: `rn_gpui_mount_batch_applied` is defined in `GpuiMountingManager.cpp` with this signature. -unsafe extern "C" { - fn rn_gpui_mount_batch_applied(); -} - -fn env_string(key: &str, default: &str) -> String { - std::env::var(key).unwrap_or_else(|_| default.to_string()) -} - -/// Smoke mode answers "does the app start and render?" for CI and packaging -/// checks: `run_with` exits with a single result line instead of opening a -/// window for a human. Exit codes: 0 first frame, 1 timeout, 2 JS error. -fn smoke_enabled() -> bool { - matches!( - std::env::var("RN_GPUI_SMOKE").as_deref(), - Ok("1") | Ok("true") - ) -} - -fn smoke_exit(code: i32, message: String) -> ! { - use std::io::Write; - println!("{message}"); - let _ = std::io::stdout().flush(); - let _ = std::io::stderr().flush(); - // `_exit`, not `std::process::exit`: `exit` runs C++ static destructors - // while the JS, network and inspector threads are still running, and one - // of them then calls into a destroyed object ("Pure virtual function - // called", SIGABRT). The result line is already flushed, so nothing is lost. - extern "C" { - fn _exit(code: i32) -> !; - } - // SAFETY: `_exit` ends the process without unwinding, and nothing is borrowed across it. - unsafe { _exit(code) } -} - -fn smoke_first_frame() -> ! { - smoke_exit(0, "RN_GPUI_SMOKE: first frame rendered".to_string()); -} - -/// The last stage: the frame the user is waiting for is on screen. -/// -/// Separate from `smoke_first_frame` because that only runs in smoke mode, and -/// this trace should describe a real launch too. -fn trace_first_frame() { - startup_trace("first frame presented"); -} - -fn smoke_timeout() -> ! { - smoke_exit(1, "RN_GPUI_SMOKE: timeout".to_string()); -} - -fn smoke_js_error(message: &str) -> ! { - smoke_exit(2, format!("RN_GPUI_SMOKE: js error: {message}")); -} - -/// The C++ `onJsError` handler reports a JS error by logging it at error level -/// from `rn-gpui-sys`; that crate logs nothing else at error level except the -/// failure of a `void` TurboModule method. Smoke mode therefore watches for -/// that record and reports the first one before the first frame. -struct SmokeLogger { - inner: env_logger::Logger, -} - -impl log::Log for SmokeLogger { - fn enabled(&self, metadata: &log::Metadata<'_>) -> bool { - self.inner.enabled(metadata) - } - - fn log(&self, record: &log::Record<'_>) { - if record.level() == log::Level::Error && record.target() == "rn_gpui_sys" { - smoke_js_error(&record.args().to_string()); - } - self.inner.log(record); - } - - fn flush(&self) { - self.inner.flush(); - } -} - -/// Installs the process logger. Smoke mode wraps `env_logger` so a JS error can -/// fail the run; otherwise this is the usual one-line init. -fn install_logger(smoke: bool) { - let inner = env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")) - .format_timestamp_millis() - .build(); - let max_level = inner.filter(); - if smoke { - log::set_boxed_logger(Box::new(SmokeLogger { inner })).expect("install the smoke logger"); - } else { - log::set_boxed_logger(Box::new(inner)).expect("install the logger"); - } - log::set_max_level(max_level); -} - -/// Starts the smoke deadline. A run that never draws a frame has to fail on its -/// own, because nothing else in the process is watching the clock. -fn smoke_start_timeout() { - let timeout_ms = env_u32("RN_GPUI_SMOKE_TIMEOUT_MS", 60_000); - std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(u64::from(timeout_ms))); - smoke_timeout(); - }); -} - -/// Reports the first frame that draws React content. A mount batch dirties the -/// window, so the frame GPUI draws after it carries the content, but -/// `on_next_frame` callbacks run *before* that draw. The callback therefore -/// re-arms once and exits at the start of the following frame. -fn smoke_arm_first_frame(cx: &mut gpui::AsyncApp, window: gpui::AnyWindowHandle) { - let armed = cx.update_window( - window, - |_root: gpui::AnyView, window: &mut gpui::Window, _cx: &mut gpui::App| { - window.on_next_frame(|window, _cx| { - window.on_next_frame(|_window, _cx| { - trace_first_frame(); - smoke_first_frame() - }); - }); - }, - ); - if let Err(error) = armed { - log::warn!("could not arm the smoke first-frame callback: {error}"); - } -} - -/// Traces the frame GPUI draws after a mount batch, the first one that shows -/// it: `on_next_frame` callbacks run before that draw, so the callback re-arms -/// once. -fn trace_next_content_frame(cx: &mut gpui::AsyncApp, window: gpui::AnyWindowHandle) { - if std::env::var_os("RN_GPUI_STARTUP_TRACE").is_none() { - return; - } - let _ = cx.update_window( - window, - |_root: gpui::AnyView, window: &mut gpui::Window, _cx: &mut gpui::App| { - window.on_next_frame(|window, _cx| { - window.on_next_frame(|_window, _cx| startup_trace("content frame presented")); - }); - }, - ); -} - -/// Whether `RN_GPUI_MOUNT_TRACE` is set: every app-surface mount batch then logs -/// when it was applied and when the frame that shows it was presented, and the -/// test driver logs when it dispatches a click or keystroke, as wall-clock epoch -/// milliseconds that line up with JS `Date.now()`. -pub(crate) fn mount_trace_enabled() -> bool { - static ENABLED: std::sync::OnceLock = std::sync::OnceLock::new(); - *ENABLED.get_or_init(|| std::env::var_os("RN_GPUI_MOUNT_TRACE").is_some()) -} - -pub(crate) fn epoch_ms() -> f64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0.0, |elapsed| elapsed.as_secs_f64() * 1000.0) -} - -/// Logs the frame drawn after a mount batch. `on_next_frame` callbacks run just -/// before that frame's draw and present, on the main thread, so a task spawned -/// from the callback runs once both are done. -fn trace_mount_presented(cx: &mut gpui::AsyncApp, window: gpui::AnyWindowHandle, batch: u64) { - let _ = cx.update_window( - window, - move |_root: gpui::AnyView, window: &mut gpui::Window, _cx: &mut gpui::App| { - window.on_next_frame(move |_window, cx| { - cx.spawn(async move |_| { - eprintln!( - "[mount-trace] presented batch={batch} epoch_ms={:.3}", - epoch_ms() - ); - }) - .detach(); - }); - }, - ); -} - -/// Milliseconds since the process started, measured once. -/// -/// A wall-clock delta from `main` would miss dyld and the C++ static -/// initialisers, which are part of what startup costs. Each platform has a way to -/// ask when the process began; the fallback is simply when this was first called. -fn process_elapsed() -> std::time::Duration { - static START: std::sync::OnceLock = std::sync::OnceLock::new(); - static PROCESS_START: std::sync::OnceLock> = - std::sync::OnceLock::new(); - let now = START.get_or_init(std::time::Instant::now); - let started = PROCESS_START.get_or_init(process_start_time); - match started { - Some(start) => start.elapsed().unwrap_or_else(|_| now.elapsed()), - None => now.elapsed(), - } -} - -/// When the current process started, where the OS will say. -#[cfg(target_os = "macos")] -fn process_start_time() -> Option { - use std::os::raw::c_int; - - // `proc_pidinfo(PROC_PIDTBSDINFO)` fills a struct whose first two fields are - // `pbi_flags` and `pbi_status`; the start time is the pair after them. - #[repr(C)] - #[derive(Default)] - struct ProcBsdInfo { - pbi_flags: u32, - pbi_status: u32, - pbi_xstatus: u32, - pbi_pid: u32, - pbi_ppid: u32, - pbi_uid: u32, - pbi_gid: u32, - pbi_ruid: u32, - pbi_rgid: u32, - pbi_svuid: u32, - // The saved-group id. Named for its position in `proc_bsdinfo`, not read - // here; the layout is what matters for `proc_pidinfo` to fill it. - #[allow(dead_code)] - pbi_saved_gid: u32, - rfu_1: u32, - pbi_comm: [u8; 16], - pbi_name: [u8; 32], - pbi_nfiles: u32, - pbi_pgid: u32, - pbi_pjobc: u32, - e_tdev: u32, - e_tpgid: u32, - pbi_nice: i32, - pbi_start_tvsec: u64, - pbi_start_tvusec: u64, - } - - extern "C" { - fn proc_pidinfo( - pid: c_int, - flavor: c_int, - arg: u64, - buffer: *mut std::os::raw::c_void, - buffersize: c_int, - ) -> c_int; - } - const PROC_PIDTBSDINFO: c_int = 3; - - let mut info = ProcBsdInfo::default(); - let size = std::mem::size_of::() as c_int; - // SAFETY: `info` is a correctly sized, writable struct of the layout the - // call expects, and the return value is checked before it is read. - let written = unsafe { - proc_pidinfo( - std::process::id() as c_int, - PROC_PIDTBSDINFO, - 0, - &mut info as *mut _ as *mut std::os::raw::c_void, - size, - ) - }; - if written != size { - return None; - } - std::time::UNIX_EPOCH.checked_add(std::time::Duration::new( - info.pbi_start_tvsec, - info.pbi_start_tvusec as u32 * 1_000, - )) -} - -#[cfg(target_os = "linux")] -fn process_start_time() -> Option { - // `/proc/self/stat` field 22 is the start time in clock ticks since boot, and - // `/proc/uptime` gives the boot instant's age. Together they date the process. - let stat = std::fs::read_to_string("/proc/self/stat").ok()?; - let start_ticks: u64 = stat - .rsplit_once(") ")? - .1 - .split_whitespace() - .nth(19)? - .parse() - .ok()?; - let uptime: f64 = std::fs::read_to_string("/proc/uptime") - .ok()? - .split_whitespace() - .next()? - .parse() - .ok()?; - // `_SC_CLK_TCK` is 100 on every Linux that matters here. - let started_ago = uptime - (start_ticks as f64 / 100.0); - std::time::SystemTime::now() - .checked_sub(std::time::Duration::from_secs_f64(started_ago.max(0.0))) -} - -#[cfg(target_os = "windows")] -fn process_start_time() -> Option { - #[repr(C)] - #[derive(Default)] - struct FileTime { - low: u32, - high: u32, - } - extern "system" { - fn GetCurrentProcess() -> *mut std::os::raw::c_void; - fn GetProcessTimes( - process: *mut std::os::raw::c_void, - creation: *mut FileTime, - exit: *mut FileTime, - kernel: *mut FileTime, - user: *mut FileTime, - ) -> i32; - } - let mut creation = FileTime::default(); - let mut exit = FileTime::default(); - let mut kernel = FileTime::default(); - let mut user = FileTime::default(); - // SAFETY: all four pointers are to initialised, writable local structs. - let ok = unsafe { - GetProcessTimes( - GetCurrentProcess(), - &mut creation, - &mut exit, - &mut kernel, - &mut user, - ) - }; - if ok == 0 { - return None; - } - // FILETIME counts 100 ns intervals since 1601-01-01. - let ticks = ((creation.high as u64) << 32) | creation.low as u64; - let since_unix = ticks.checked_sub(116_444_736_000_000_000)?; - std::time::UNIX_EPOCH.checked_add(std::time::Duration::from_nanos(since_unix * 100)) -} - -#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] -fn process_start_time() -> Option { - None -} - -/// Emit a startup stage, when `RN_GPUI_STARTUP_TRACE` is set. -/// -/// One cached env check when off, which is the only cost a shipped app pays. On -/// macOS each stage is also an `os_signpost` interval, so Instruments shows the -/// phases by name instead of a flat profile. -fn startup_trace(stage: &str) { - static ENABLED: std::sync::OnceLock = std::sync::OnceLock::new(); - if !*ENABLED.get_or_init(|| std::env::var_os("RN_GPUI_STARTUP_TRACE").is_some()) { - return; - } - let elapsed = process_elapsed(); - eprintln!("[startup] +{} {stage}", elapsed.as_millis()); - signpost_stage(stage, elapsed); -} - -/// Emit the signpost for a stage. -/// -/// The macros in `os/signpost.h` are variadic and expand to a call whose ABI is -/// easy to get wrong from Rust; one wrong argument crashed the app on the very -/// first stage. The C++ side expands them as Apple intends. -fn signpost_stage(stage: &str, elapsed: std::time::Duration) { - rn_gpui_sys::ffi::rn_gpui_startup_signpost(stage, elapsed.as_millis() as u64); -} - -fn window_state_path(app_id: &str) -> std::path::PathBuf { - #[cfg(feature = "visual-capture")] - if let Some(path) = std::env::var_os("RN_GPUI_WINDOW_STATE") { - return path.into(); - } - let safe_id = crate::desktop::app_dir::safe_id(app_id); - crate::desktop::app_dir::app_dir().join(format!("{safe_id}-window.json")) -} - -fn load_window_bounds(path: &std::path::Path) -> Option<(f32, f32, f32, f32)> { - let value: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?; - let number = |key| value.get(key)?.as_f64().map(|value| value as f32); - let (x, y, width, height) = ( - number("x")?, - number("y")?, - number("width")?, - number("height")?, - ); - (x.is_finite() - && y.is_finite() - && width.is_finite() - && height.is_finite() - && width >= 320.0 - && height >= 240.0) - .then_some((x, y, width, height)) -} - -fn save_window_bounds( - path: &std::path::Path, - bounds: Bounds, - viewport: gpui::Size, -) { - let value = serde_json::json!({ - "x": f32::from(bounds.origin.x), - "y": f32::from(bounds.origin.y), - // Persist the content size used in `WindowBounds`; GPUI adds the - // platform title-bar inset to `window.bounds()` on restore. - "width": f32::from(viewport.width), - "height": f32::from(viewport.height), - }); - let result = (|| -> std::io::Result<()> { - let parent = path.parent().ok_or_else(|| { - std::io::Error::new( - std::io::ErrorKind::InvalidInput, - "window state path has no parent", - ) - })?; - std::fs::create_dir_all(parent)?; - let temporary = path.with_extension("json.tmp"); - std::fs::write(&temporary, serde_json::to_vec(&value)?)?; - std::fs::rename(temporary, path) - })(); - if let Err(error) = result { - log::warn!( - "could not save window bounds to {}: {error}", - path.display() - ); - } -} - -static DESKTOP_DEFAULTS: std::sync::OnceLock = std::sync::OnceLock::new(); - -/// Records the app's `desktop.json`, as the generated autolink crate passes it -/// on, so the window options in it reach the app without `main.rs` repeating -/// them. Anything `main.rs` sets on the config afterwards wins. -pub fn set_desktop_defaults(json: &str) { - if let Ok(value) = serde_json::from_str(json) { - let _ = DESKTOP_DEFAULTS.set(value); - } -} - -fn env_f32(key: &str, default: f32) -> f32 { - std::env::var(key) - .ok() - .and_then(|value| value.parse().ok()) - .unwrap_or(default) -} - -fn env_u32(key: &str, default: u32) -> u32 { - std::env::var(key) - .ok() - .and_then(|value| value.parse().ok()) - .unwrap_or(default) -} - -/// Whether the runtime should talk to Metro instead of loading `bundle_path`. -/// -/// This is a runtime decision, not a compile-time one. The ReactCommon headers -/// default `enableDevMode` from `REACT_NATIVE_DEBUG`, but the prebuilt runtime -/// is always built in Release, so a debug app that links it would otherwise -/// never reach the dev server. The `rn-gpui` crate is compiled in the app's own -/// Cargo profile, so `debug_assertions` is the right default here and -/// `RN_GPUI_DEV_MODE` overrides it either way. -fn dev_mode() -> bool { - std::env::var("RN_GPUI_DEV_MODE") - .ok() - .map(|value| matches!(value.as_str(), "1" | "true" | "yes")) - .unwrap_or(cfg!(debug_assertions)) -} - -#[cfg(feature = "visual-capture")] -fn env_bool(key: &str, default: bool) -> bool { - std::env::var(key) - .ok() - .map(|value| matches!(value.as_str(), "1" | "true" | "yes")) - .unwrap_or(default) -} - -#[cfg(feature = "visual-capture")] -fn env_opt_f32(key: &str) -> Option { - std::env::var(key).ok().and_then(|value| value.parse().ok()) -} - -#[cfg(feature = "visual-capture")] -fn env_points(key: &str) -> Vec<(f32, f32)> { - std::env::var(key) - .ok() - .map(|value| { - value - .split(';') - .filter_map(|pair| { - let (x, y) = pair.split_once(',')?; - Some((x.trim().parse().ok()?, y.trim().parse().ok()?)) - }) - .collect() - }) - .unwrap_or_default() -} - -#[cfg(feature = "visual-capture")] -fn env_drags(key: &str) -> Vec<(f32, f32, f32, f32, bool)> { - std::env::var(key) - .unwrap_or_default() - .split(';') - .filter_map(|entry| { - let mut parts = entry.split(':'); - let start = parts.next()?; - let end = parts.next()?; - let cancel = parts.next().is_some_and(|phase| phase.trim() == "cancel"); - let (start_x, start_y) = start.split_once(',')?; - let (end_x, end_y) = end.split_once(',')?; - Some(( - start_x.trim().parse().ok()?, - start_y.trim().parse().ok()?, - end_x.trim().parse().ok()?, - end_y.trim().parse().ok()?, - cancel, - )) - }) - .collect() -} - -#[cfg(feature = "visual-capture")] -fn env_scrolls(key: &str) -> Vec<(f32, f32, f32, f32)> { - std::env::var(key) - .unwrap_or_default() - .split(';') - .filter_map(|entry| { - let mut values = entry - .split(',') - .filter_map(|v| v.trim().parse::().ok()); - Some(( - values.next()?, - values.next()?, - values.next()?, - values.next()?, - )) - }) - .collect() -} - -/// macOS stops delivering frames while the display is asleep, so JS work a -/// synthetic click queued would never run; the input loops call this instead. -#[cfg(feature = "visual-capture")] -async fn flush_js(host: &Host, cx: &mut gpui::AsyncApp) { - for _ in 0..6 { - host.on_render(); - cx.background_executor() - .timer(Duration::from_millis(16)) - .await; - } -} - -pub(crate) enum MainEvent { - Mount(MountBatch), - SurfaceStopped(i32), - AnimatedProps(rn_gpui_sys::ffi::AnimatedPropsFlat), - AnimatedActivity(bool), - TextInputCommand { - tag: i32, - focus: bool, - }, - AccessibilityFocus(i32), - TextInputClear(i32), - WheelDone { - id: u64, - prevented: bool, - }, - ScrollerStyleChanged, - BuiltinCommand { - tag: i32, - component: String, - name: String, - args: serde_json::Value, - }, - /// A command Fabric sent to a host component: its index in the spec's - /// `COMMANDS` and its arguments, already validated by the generated C++ - /// dispatcher. - HostCommand { - tag: i32, - command: u32, - args: Vec, - }, - NativeRootOps { - root: u32, - payload: String, - }, - DevMenuShow, - DevSetting { - name: String, - enabled: bool, - }, - DevMenuPerform(String), - TrayClick { - x: f32, - y: f32, - width: f32, - height: f32, - button: u8, - }, - TrayMenuPerform(String), - GlobalShortcut(u32), - GlobalShortcutNamed(String), - GlobalShortcutRefused(String, String), - MenuBarPerform(String), - /// One desktop-shell command, run with the app context the main loop holds. - /// It answers through the channel it was built with, which may be later: - /// a context menu answers when it closes. - DesktopCommand(Box), - MainTask(u64), - /// Work a Rust module asked to run on the main thread. - RustJob(rn_gpui_module::Job), -} - -pub type WindowOptionsHook = Box; -pub type AppReadyHook = Box; - -pub type WindowOpenedHook = Box; - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum WindowTitleBar { - #[default] - Default, - Transparent, - /// No system title bar at all. GPUI only has "transparent" on macOS, so - /// this is the same as [`WindowTitleBar::Transparent`] there. - Hidden, - /// No system chrome at all. On macOS the window is borderless: no title bar, - /// border line or system corners, so the app draws every edge. Elsewhere this - /// is the same as [`WindowTitleBar::Hidden`]. - Borderless, -} - -impl WindowTitleBar { - /// What a `desktop.json` value or a `titleBar` prop names. - /// - /// An unknown name falls back to the default bar rather than failing: the - /// schema is what rejects a typo in `desktop.json`, and a secondary window - /// opened by an app built against an older schema must still open. - pub fn from_name(name: &str) -> Self { - match name { - "transparent" => Self::Transparent, - "hidden" => Self::Hidden, - "none" => Self::Borderless, - _ => Self::Default, - } - } - - /// Whether the app draws the bar itself, which is what lets the platform - /// drop its own chrome. - pub fn is_custom(self) -> bool { - !matches!(self, Self::Default) - } -} - -/// What shows through a window where the app draws nothing opaque. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum WindowBackground { - #[default] - Opaque, - /// Plain alpha transparency: the app's own colors decide how much shows. - Transparent, - /// Transparency with what is behind the window blurred. - Blurred, - /// The Windows 11 Mica material; elsewhere the window stays opaque. - Mica, -} - -impl WindowBackground { - /// What a `desktop.json` value or a `background` prop names. An unknown name - /// keeps the window opaque, for the same reason as [`WindowTitleBar::from_name`]. - pub fn from_name(name: &str) -> Self { - match name { - "transparent" => Self::Transparent, - "blurred" => Self::Blurred, - "mica" => Self::Mica, - _ => Self::Opaque, - } - } - - pub fn appearance(self) -> gpui::WindowBackgroundAppearance { - match self { - Self::Opaque => gpui::WindowBackgroundAppearance::Opaque, - Self::Transparent => gpui::WindowBackgroundAppearance::Transparent, - Self::Blurred => gpui::WindowBackgroundAppearance::Blurred, - Self::Mica => gpui::WindowBackgroundAppearance::MicaBackdrop, - } - } -} - -/// Keeps the traffic lights inside the window they belong to. -/// -/// A position from `desktop.json` is app-authored, so it can name somewhere the -/// window does not reach; AppKit would then move the buttons off screen with no -/// way to drag them back. A non-finite coordinate is treated as the origin rather -/// than propagated, because `f32::clamp` panics on `NaN`. -pub fn clamp_traffic_light_position(x: f32, y: f32, width: f32, height: f32) -> (f32, f32) { - fn clamp(value: f32, limit: f32) -> f32 { - if !value.is_finite() || !(limit > 0.0) { - 0.0 - } else { - value.clamp(0.0, limit) - } - } - (clamp(x, width), clamp(y, height)) -} - -/// Builds the GPUI view that is a GPUI-first app's main window content. -type GpuiRootHook = Box gpui::AnyView>; - -/// Launching with this argument opens the main window without showing it; a tray -/// click, the Dock icon or a second launch brings it up. -pub const START_HIDDEN_ARGUMENT: &str = "--hidden"; - -pub struct DesktopAppConfig { - pub app_id: String, - pub module: String, - /// Name of the installed JS engine package to run, e.g. `"hermes"`. Empty - /// uses the only installed engine. `RN_GPUI_JS_ENGINE` overrides this. - pub js_engine: String, - pub width: f32, - pub height: f32, - pub title: Option, - pub position: Option<(f32, f32)>, - pub restore_window_state: bool, - /// Whether the main window is shown when the app starts. Without it the - /// window is created, and its React tree mounts and commits, but nothing is - /// shown and no focus or activation is taken until the app shows it. - pub visible: bool, - pub quit_on_last_window_closed: bool, - pub title_bar: WindowTitleBar, - pub background: WindowBackground, - /// Whether macOS draws the traffic lights. - pub window_buttons: bool, - /// Whether the window has the system shadow. - pub shadow: bool, - /// Whether the Dev Menu is available. `None` follows the build: on in a - /// debug build, off in a release build. - pub dev_menu: Option, - /// Whether the app runs with no Dock icon (macOS), which is also what lets a - /// window show over another app's full-screen Space. - pub accessory: bool, - pub tray: Option, - pub traffic_light_position: Option<(f32, f32)>, - /// URL schemes that open this app. - pub url_schemes: Vec, - /// Whether a second launch hands its arguments to the running copy. - pub single_instance: bool, - /// Whether the main window shows a menu bar. Windows and Linux only. - pub menu_bar: bool, - /// Whether the caption buttons go on the left where the desktop does not say. - pub window_controls_left: bool, - /// Corner radius on Linux where the desktop's own cannot be measured. - pub corner_radius: Option, - pub configure_window: Option, - resizable: bool, - pub on_app_ready: Option, - - pub on_window_opened: Option, - /// A GPUI-first app's main window content. When set, - /// the main window shows this view instead of starting `module` on surface 1; - /// React content lives in the `ReactSurface`s the view places. - pub gpui_root: Option, -} - -impl DesktopAppConfig { - pub fn from_env() -> Self { - Self::from_env_with_defaults("App", "com.example.rngpui") - } - - pub fn from_env_with_defaults(module: &str, app_id: &str) -> Self { - let mut config = Self { - app_id: env_string("RN_GPUI_APP_ID", app_id), - module: env_string("RN_GPUI_MODULE", module), - js_engine: String::new(), - width: env_f32("RN_GPUI_WIDTH", 800.0), - height: env_f32("RN_GPUI_HEIGHT", 600.0), - title: None, - position: None, - restore_window_state: true, - visible: true, - quit_on_last_window_closed: true, - title_bar: WindowTitleBar::Default, - background: WindowBackground::Opaque, - window_buttons: true, - shadow: true, - dev_menu: None, - accessory: false, - tray: None, - traffic_light_position: None, - url_schemes: Vec::new(), - single_instance: false, - menu_bar: true, - window_controls_left: false, - corner_radius: None, - configure_window: None, - resizable: true, - on_app_ready: None, - on_window_opened: None, - gpui_root: None, - }; - if let Some(defaults) = DESKTOP_DEFAULTS.get() { - config.apply_desktop_values(defaults); - } - config - } - - /// The window options `desktop.json` gave the build, which the generated - /// autolink crate records. A builder call made after this one replaces them. - fn apply_desktop_values(&mut self, defaults: &serde_json::Value) { - let window = &defaults["window"]; - let text = |key: &str| window.get(key).and_then(serde_json::Value::as_str); - let flag = |key: &str| window.get(key).and_then(serde_json::Value::as_bool); - let number = |value: &serde_json::Value| value.as_f64().map(|n| n as f32); - if let Some(title) = text("title") { - self.title = Some(title.to_string()); - } - if std::env::var_os("RN_GPUI_WIDTH").is_none() { - if let Some(width) = number(&window["width"]) { - self.width = width.max(320.0); - } - } - if std::env::var_os("RN_GPUI_HEIGHT").is_none() { - if let Some(height) = number(&window["height"]) { - self.height = height.max(240.0); - } - } - if let (Some(x), Some(y)) = ( - number(&window["position"]["x"]), - number(&window["position"]["y"]), - ) { - self.position = Some((x, y)); - } - if let Some(restore) = flag("restoreState") { - self.restore_window_state = restore; - } - if let Some(visible) = flag("visible") { - self.visible = visible; - } - if let Some(resizable) = flag("resizable") { - self.resizable = resizable; - } - if let Some(name) = text("titleBar") { - self.title_bar = WindowTitleBar::from_name(name); - } - if let Some(name) = text("background") { - self.background = WindowBackground::from_name(name); - } - if let Some(show) = flag("windowButtons") { - self.window_buttons = show; - } - if let Some(shadow) = flag("shadow") { - self.shadow = shadow; - } - if let (Some(x), Some(y)) = ( - number(&window["trafficLightPosition"]["x"]), - number(&window["trafficLightPosition"]["y"]), - ) { - self.traffic_light_position = Some((x, y)); - } - if let Some(radius) = number(&window["cornerRadius"]) { - self.corner_radius = Some(radius); - } - if let Some(side) = text("windowControlsPosition") { - self.window_controls_left = side == "left"; - } - if let Some(visible) = flag("menuBar") { - self.menu_bar = visible; - } - if let Some(accessory) = defaults["accessory"].as_bool() { - self.accessory = accessory; - } - } - - #[must_use] - pub fn js_engine(mut self, name: impl Into) -> Self { - self.js_engine = name.into(); - self - } - - #[must_use] - pub fn tray(mut self, config: crate::desktop::tray::TrayConfig) -> Self { - self.tray = Some(config); - self - } - - #[must_use] - pub fn url_schemes(mut self, schemes: &[&str]) -> Self { - self.url_schemes = schemes.iter().map(|scheme| (*scheme).to_string()).collect(); - self - } - - #[must_use] - pub fn single_instance(mut self, enabled: bool) -> Self { - self.single_instance = enabled; - self - } - - /// Runs the app with no Dock icon. macOS only. - #[must_use] - pub fn accessory(mut self, accessory: bool) -> Self { - self.accessory = accessory; - self - } - - #[must_use] - pub fn dev_menu(mut self, enabled: bool) -> Self { - self.dev_menu = Some(enabled); - self - } - - #[must_use] - pub fn window_title(mut self, title: impl Into) -> Self { - self.title = Some(title.into()); - self - } - - #[must_use] - pub fn window_size(mut self, width: f32, height: f32) -> Self { - self.width = width.max(320.0); - self.height = height.max(240.0); - self - } - - #[must_use] - pub fn window_position(mut self, x: f32, y: f32) -> Self { - self.position = Some((x, y)); - self - } - - #[must_use] - pub fn visible(mut self, visible: bool) -> Self { - self.visible = visible; - self - } - - #[must_use] - pub fn restore_window_state(mut self, restore: bool) -> Self { - self.restore_window_state = restore; - self - } - - #[must_use] - pub fn quit_on_last_window_closed(mut self, quit: bool) -> Self { - self.quit_on_last_window_closed = quit; - self - } - - #[must_use] - pub fn title_bar(mut self, title_bar: WindowTitleBar) -> Self { - self.title_bar = title_bar; - self - } - - #[must_use] - pub fn background(mut self, background: WindowBackground) -> Self { - self.background = background; - self - } - - /// Whether macOS draws the traffic lights. Other systems ignore it. - #[must_use] - pub fn window_buttons(mut self, show: bool) -> Self { - self.window_buttons = show; - self - } - - /// Whether the window has the system shadow. Only macOS draws one yet. - #[must_use] - pub fn shadow(mut self, shadow: bool) -> Self { - self.shadow = shadow; - self - } - - #[must_use] - pub fn traffic_light_position(mut self, x: f32, y: f32) -> Self { - self.traffic_light_position = Some((x, y)); - self - } - - /// Whether the main window shows a menu bar. - /// - /// Only Windows and Linux draw one inside the window; on macOS the bar is the - /// system's, so this is ignored there. - /// The side of the title bar the caption buttons use on Linux when neither - /// the desktop's settings nor its theme say. `"left"` puts them there; - /// anything else keeps them on the right. - /// The corner radius, in points, of a client-decorated window on Linux when - /// the desktop's own frame cannot be measured. - #[must_use] - pub fn corner_radius(mut self, radius: f32) -> Self { - self.corner_radius = Some(radius); - self - } - - #[must_use] - pub fn window_controls_position(mut self, side: &str) -> Self { - self.window_controls_left = side == "left"; - self - } - - #[must_use] - pub fn menu_bar(mut self, visible: bool) -> Self { - self.menu_bar = visible; - self - } - - #[must_use] - pub fn configure_window( - mut self, - configure: impl FnOnce(&mut WindowOptions) + 'static, - ) -> Self { - self.configure_window = Some(Box::new(configure)); - self - } - - #[must_use] - pub fn on_app_ready(mut self, callback: impl FnOnce(&mut App) + 'static) -> Self { - self.on_app_ready = Some(Box::new(callback)); - self - } - - #[must_use] - pub fn on_window_opened( - mut self, - callback: impl FnOnce(gpui::WindowId, &mut gpui::Window, &mut App) + 'static, - ) -> Self { - self.on_window_opened = Some(Box::new(callback)); - self - } - - /// Makes this a GPUI-first app: the main window shows the view `build` - /// returns, and React content appears where that view places a - /// [`ReactSurface`](crate::ReactSurface). - /// - /// The runtime still boots the way `run_with` always does — the JS engine, the - /// bundle, the modules, the store — but no React tree is started on the main - /// surface, so the window belongs to the app. `build` runs once, with the - /// [`ReactRuntime`](crate::ReactRuntime) it can open further windows through. - /// - /// ```ignore - /// run_with(DesktopAppConfig::from_env().gpui_first(|cx, _runtime| { - /// cx.new(|cx| { - /// let details = cx.new(|cx| ReactSurface::new("Details", cx)); - /// Root { details } - /// }) - /// .into() - /// })); - /// ``` - #[must_use] - pub fn gpui_first( - mut self, - build: impl FnOnce(&mut App, crate::runtime::ReactRuntime) -> gpui::AnyView + 'static, - ) -> Self { - self.gpui_root = Some(Box::new(build)); - self - } -} - -impl Default for DesktopAppConfig { - fn default() -> Self { - Self::from_env() - } -} - -pub fn run() { - run_with(DesktopAppConfig::from_env()); -} - -pub fn run_with(mut config: DesktopAppConfig) { - #[cfg(target_os = "linux")] - if std::env::args().nth(1).as_deref() == Some("--rn-gpui-probe-frame") { - crate::desktop::frame_probe::run_and_exit(); - } - crate::desktop::window_frame::configure(config.corner_radius, config.shadow); - crate::desktop::window_frame::load(&config.app_id); - - #[cfg(not(feature = "test-driver"))] - if std::env::var_os("RN_GPUI_TEST_DRIVER").is_some_and(|value| value != "0") { - panic!("RN_GPUI_TEST_DRIVER is enabled, but this app was not built with --features test-driver"); - } - startup_trace("main entered"); - rn_gpui_sys::note_main_thread(); - rn_gpui_module::note_main_thread(); - let smoke = smoke_enabled(); - install_logger(smoke); - if smoke { - smoke_start_timeout(); - } - - // A packaged release build has no source tree: the bundle is beside the - // executable. `RN_GPUI_BUNDLE`, which the CLI sets in development, still - // wins, and a debug build bakes in the path it was developed against. - // - // A release build with neither is a packaging mistake — no resources were - // installed — so the fallback names the file it looked for rather than a - // path into some checkout. That path must never be a repository path: it - // would resolve on the machine that built the app, and nowhere else. - let bundle = crate::resources::default_bundle("index.bundle"); - let source_url = env_string("RN_GPUI_SOURCE_URL", "index"); - let app_id = config.app_id.clone(); - let js_engine = env_string("RN_GPUI_JS_ENGINE", &config.js_engine); - let js_thread = rn_gpui_sys::JS_THREAD; - let dev_host = env_string("RN_GPUI_DEV_HOST", "localhost"); - let dev_port = env_u32("RN_GPUI_DEV_PORT", 8081); - let launch_args: Vec = std::env::args().skip(1).collect(); - if let Some(url) = crate::desktop::deep_link::url_in_args(&launch_args, &config.url_schemes) { - crate::desktop::deep_link::handle_url(url); - } - if config.single_instance { - let schemes = config.url_schemes.clone(); - let instance = crate::desktop::deep_link::acquire( - &crate::desktop::app_dir::app_dir(), - &app_id, - &launch_args, - move |args| { - let url = crate::desktop::deep_link::url_in_args(&args, &schemes); - crate::desktop::post_to_main(Box::new(move |cx| { - crate::desktop::deep_link::second_instance(&args); - if std::env::var("RN_GPUI_TEST_OFFSCREEN").as_deref() != Ok("1") { - let _ = crate::desktop::windows::show( - cx, - crate::desktop::windows::MAIN_WINDOW_KEY, - ); - } - let _ = crate::desktop::windows::focus( - cx, - crate::desktop::windows::MAIN_WINDOW_KEY, - ); - if let Some(url) = url { - crate::desktop::deep_link::handle_url(url); - } - })); - }, - ); - if matches!(instance, crate::desktop::deep_link::Instance::Forwarded) { - std::process::exit(0); - } - } - let module = config.module.clone(); - let width = config.width; - let height = config.height; - let window_state_path = window_state_path(&app_id); - #[cfg(feature = "visual-capture")] - let scale_override = env_opt_f32("RN_GPUI_SCALE"); - #[cfg(not(feature = "visual-capture"))] - let scale_override: Option = None; - #[cfg(feature = "visual-capture")] - let run_ms = env_u32("RN_GPUI_RUN_MS", 0); - #[cfg(feature = "perf-timing")] - let benchmark_ms = env_u32("RN_GPUI_BENCHMARK_MS", 0); - #[cfg(feature = "perf-timing")] - let benchmark_mode = crate::store::benchmark_mode() - .unwrap_or("unspecified") - .to_owned(); - #[cfg(feature = "visual-capture")] - let resize_ms = env_u32("RN_GPUI_RESIZE_MS", 0); - #[cfg(feature = "visual-capture")] - let resize_width = env_f32("RN_GPUI_RESIZE_WIDTH", 1200.0); - #[cfg(feature = "visual-capture")] - let resize_height = env_f32("RN_GPUI_RESIZE_HEIGHT", 400.0); - #[cfg(feature = "visual-capture")] - let clicks = env_points("RN_GPUI_CLICK"); - #[cfg(feature = "visual-capture")] - let click_ms = env_u32("RN_GPUI_CLICK_MS", 1500); - #[cfg(feature = "visual-capture")] - let click_hold_ms = env_u32("RN_GPUI_CLICK_HOLD_MS", 0); - #[cfg(feature = "visual-capture")] - let drags = env_drags("RN_GPUI_DRAG"); - #[cfg(feature = "visual-capture")] - let drag_ms = env_u32("RN_GPUI_DRAG_MS", 1800); - #[cfg(feature = "visual-capture")] - let drag_start_ms = env_u32("RN_GPUI_DRAG_START_MS", drag_ms); - #[cfg(feature = "visual-capture")] - let skip_synthetic_input_flush = env_bool("RN_GPUI_SKIP_INPUT_FLUSH", false); - #[cfg(feature = "visual-capture")] - let hovers = env_points("RN_GPUI_HOVER"); - #[cfg(feature = "visual-capture")] - let hover_ms = env_u32("RN_GPUI_HOVER_MS", 800); - #[cfg(feature = "visual-capture")] - let scrolls = env_scrolls("RN_GPUI_SCROLL"); - #[cfg(feature = "visual-capture")] - let scroll_ms = env_u32("RN_GPUI_SCROLL_MS", 1500); - #[cfg(feature = "visual-capture")] - let scroll_start_ms = env_u32("RN_GPUI_SCROLL_START_MS", scroll_ms); - #[cfg(feature = "visual-capture")] - let keys: Vec = std::env::var("RN_GPUI_KEY") - .unwrap_or_default() - .split(';') - .map(str::trim) - .filter(|key| !key.is_empty()) - .map(str::to_owned) - .collect(); - #[cfg(feature = "visual-capture")] - let key_ms = env_u32("RN_GPUI_KEY_MS", 1500); - #[cfg(feature = "visual-capture")] - let mouse_navigation: Vec = std::env::var("RN_GPUI_MOUSE_NAV") - .unwrap_or_default() - .split(';') - .map(str::trim) - .filter(|direction| matches!(*direction, "back" | "forward")) - .map(str::to_owned) - .collect(); - #[cfg(feature = "visual-capture")] - let mouse_navigation_ms = env_u32("RN_GPUI_MOUSE_NAV_MS", 1500); - #[cfg(feature = "visual-capture")] - let screenshot = std::env::var("RN_GPUI_SCREENSHOT").ok(); - #[cfg(feature = "visual-capture")] - let screenshot_delay_ms = env_u32("RN_GPUI_SCREENSHOT_DELAY_MS", 500); - #[cfg(feature = "visual-capture")] - let screenshots: Vec<(u32, String)> = std::env::var("RN_GPUI_SCREENSHOTS") - .unwrap_or_default() - .split(';') - .filter_map(|entry| { - let (delay, path) = entry.split_once(':')?; - Some((delay.parse().ok()?, path.to_owned())) - }) - .collect(); - - // Installed before any surface starts, otherwise the first mount batch would - // be dropped. - let (tx, rx) = async_channel::unbounded::(); - let mount_tx = tx.clone(); - let _ = rn_gpui_sys::MOUNT_HANDLER.set(Box::new(move |batch: MountBatch| { - let _ = mount_tx.send_blocking(MainEvent::Mount(batch)); - })); - let surface_tx = tx.clone(); - let _ = rn_gpui_sys::SURFACE_STOPPED_HANDLER.set(Box::new(move |surface_id: i32| { - let _ = surface_tx.send_blocking(MainEvent::SurfaceStopped(surface_id)); - })); - let animated_tx = tx.clone(); - let _ = rn_gpui_sys::ANIMATED_PROPS_HANDLER.set(Box::new(move |props| { - let _ = animated_tx.send_blocking(MainEvent::AnimatedProps(props)); - })); - let activity_tx = tx.clone(); - let _ = rn_gpui_sys::ANIMATED_ACTIVE_HANDLER.set(Box::new(move |active| { - let _ = activity_tx.send_blocking(MainEvent::AnimatedActivity(active)); - })); - let text_input_command_tx = tx.clone(); - let _ = rn_gpui_sys::TEXT_INPUT_COMMAND_HANDLER.set(Box::new(move |tag, focus| { - let _ = text_input_command_tx.send_blocking(MainEvent::TextInputCommand { tag, focus }); - })); - let host_command_tx = tx.clone(); - let _ = rn_gpui_sys::HOST_COMMAND_HANDLER.set(Box::new(move |tag, command, args| { - let _ = host_command_tx.send_blocking(MainEvent::HostCommand { - tag, - command, - args: args - .into_iter() - .map(crate::host_component::HostArg::from_ffi) - .collect(), - }); - })); - let native_root_tx = tx.clone(); - let _ = rn_gpui_sys::NATIVE_ROOT_OPS_HANDLER.set(Box::new(move |root, payload| { - let _ = native_root_tx.send_blocking(MainEvent::NativeRootOps { - root, - payload: payload.to_string(), - }); - })); - let accessibility_focus_tx = tx.clone(); - let _ = rn_gpui_sys::ACCESSIBILITY_FOCUS_HANDLER.set(Box::new(move |tag| { - let _ = accessibility_focus_tx.send_blocking(MainEvent::AccessibilityFocus(tag)); - })); - let text_input_clear_tx = tx.clone(); - let _ = rn_gpui_sys::TEXT_INPUT_CLEAR_HANDLER.set(Box::new(move |tag| { - let _ = text_input_clear_tx.send_blocking(MainEvent::TextInputClear(tag)); - })); - let _ = rn_gpui_sys::SCROLLER_LEGACY_HANDLER.set(Box::new(crate::scroller_style::legacy)); - let _ = rn_gpui_sys::HOST_MEASURE_HANDLER.set(Box::new( - |index, props, [min_w, min_h, max_w, max_h]| { - let constraint = crate::host_component::MeasureConstraint { - min_width: min_w, - min_height: min_h, - max_width: max_w, - max_height: max_h, - }; - crate::host_component::measure_component( - index, - props as *const core::ffi::c_void, - &constraint, - ) - .map(|size| (size.width, size.height)) - }, - )); - let scroller_style_tx = tx.clone(); - crate::scroller_style::install(move || { - let _ = scroller_style_tx.send_blocking(MainEvent::ScrollerStyleChanged); - }); - let wheel_done_tx = tx.clone(); - let _ = rn_gpui_sys::WHEEL_DONE_HANDLER.set(Box::new(move |id, prevented| { - let _ = wheel_done_tx.send_blocking(MainEvent::WheelDone { id, prevented }); - })); - let builtin_command_tx = tx.clone(); - let _ = - rn_gpui_sys::BUILTIN_COMMAND_HANDLER.set(Box::new(move |tag, component, name, args| { - if crate::extensions::component_renderer(component).is_none() { - return; - } - let _ = builtin_command_tx.send_blocking(MainEvent::BuiltinCommand { - tag, - component: component.to_owned(), - name: name.to_owned(), - args: serde_json::from_str(args).unwrap_or(serde_json::Value::Null), - }); - })); - let desktop_tx = tx.clone(); - crate::desktop::set_command_sender(desktop_tx); - let main_task_tx = tx.clone(); - let _ = rn_gpui_sys::MAIN_TASK_HANDLER.set(Box::new(move |id| { - let _ = main_task_tx.send_blocking(MainEvent::MainTask(id)); - })); - // Rust modules that ask for the main thread hand their work over here; the - // future is created and polled on the main thread, so it never has to be - // `Send`. - let rust_job_tx = tx.clone(); - rn_gpui_module::set_main_spawner(move |job| { - let _ = rust_job_tx.send_blocking(MainEvent::RustJob(job)); - }); - let dev_menu_tx = tx.clone(); - let _ = rn_gpui_sys::DEV_MENU_SHOW_HANDLER.set(Box::new(move || { - let _ = dev_menu_tx.send_blocking(MainEvent::DevMenuShow); - })); - let dev_setting_tx = tx.clone(); - let _ = rn_gpui_sys::DEV_SETTING_HANDLER.set(Box::new(move |name, enabled| { - let _ = dev_setting_tx.send_blocking(MainEvent::DevSetting { name, enabled }); - })); - let dev_perform_tx = tx.clone(); - let _ = rn_gpui_sys::DEV_MENU_PERFORM_HANDLER.set(Box::new(move |id| { - let _ = dev_perform_tx.send_blocking(MainEvent::DevMenuPerform(id)); - })); - let tray_click_tx = tx.clone(); - let _ = rn_gpui_sys::TRAY_CLICK_HANDLER.set(Box::new(move |x, y, width, height, button| { - let _ = tray_click_tx.send_blocking(MainEvent::TrayClick { - x, - y, - width, - height, - button, - }); - })); - let global_shortcut_tx = tx.clone(); - let _ = crate::desktop::global_shortcut::PRESS_HANDLER.set(Box::new(move |hotkey| { - let _ = global_shortcut_tx.send_blocking(MainEvent::GlobalShortcut(hotkey)); - })); - #[cfg(target_os = "linux")] - { - let pressed_tx = tx.clone(); - let _ = crate::desktop::portal_shortcuts::ACTIVATED_HANDLER.set(Box::new(move |id| { - let _ = pressed_tx.send_blocking(MainEvent::GlobalShortcutNamed(id)); - })); - let refused_tx = tx.clone(); - let _ = - crate::desktop::portal_shortcuts::FAILURE_HANDLER.set(Box::new(move |id, reason| { - let _ = refused_tx.send_blocking(MainEvent::GlobalShortcutRefused(id, reason)); - })); - } - let menu_bar_tx = tx.clone(); - let _ = rn_gpui_sys::MENU_BAR_PERFORM_HANDLER.set(Box::new(move |id| { - let _ = menu_bar_tx.send_blocking(MainEvent::MenuBarPerform(id)); - })); - let tray_menu_tx = tx; - let _ = rn_gpui_sys::TRAY_MENU_PERFORM_HANDLER.set(Box::new(move |id| { - let _ = tray_menu_tx.send_blocking(MainEvent::TrayMenuPerform(id)); - })); - // The snapshot is read on the JS thread during module initialization, so it - // has to be installed before the bundle loads. - crate::desktop::install_snapshot(&app_id); - // The desktop shell is a Rust TurboModule: JS asks for it by name. - crate::desktop::module::register(); - crate::builtins::register(); - - // A headless test run starts on GPUI's test platform: no real platform, - // display or window server is asked for (see `headless.rs`). - #[cfg(feature = "test-driver")] - let test_headless = crate::headless::enabled(); - #[cfg(not(feature = "test-driver"))] - let test_headless = false; - crate::desktop::test_scale::apply_to_environment(); - let application = (!test_headless).then(platform_application); - // Before any request can arrive: the C++ bridge reports completions through - // this handler, and it is registered once. - crate::http_client::install(); - // The real platform's application loop, or the headless test platform's - // (see `headless.rs`), runs the same launch. - let launch = move |cx: &mut App| { - startup_trace("application run"); - crate::image_loader::install(cx); - crate::desktop::icon::install(cx); - crate::text::install_fonts(cx); - // Installed before the host starts a surface: Fabric measures paragraphs - // from the JS thread and would otherwise fall back to a zero-size stub. - crate::text::install_measure_handler(cx); - if let Some(icon) = std::env::var_os("RN_GPUI_APP_ICON") { - crate::desktop::platform_window::set_dock_icon(std::path::Path::new(&icon)); - } - // Has to happen before the first window opens. - if !test_headless - && (config.accessory || config.tray.as_ref().is_some_and(|tray| tray.accessory)) - { - crate::desktop::platform_window::set_accessory_app(true); - } - if let Some(on_app_ready) = config.on_app_ready.take() { - on_app_ready(cx); - } - - // Both must exist before the main window opens: the registry adopts it - // below, and the close hook reads the policy while the window is live. - cx.set_global(crate::desktop::windows::DesktopWindowsGlobal( - crate::desktop::windows::DesktopWindows::new(), - )); - cx.set_global(crate::desktop::windows::QuitOnLastWindowClosed( - config.quit_on_last_window_closed, - )); - // Installed before the bundle loads so a startup failure still leaves a - // working menu bar. - let menu_app_name = config - .title - .clone() - .unwrap_or_else(|| config.module.clone()); - let dev_menu = config.dev_menu.unwrap_or(cfg!(debug_assertions)); - crate::desktop::dev_menu::install(cx, dev_menu); - crate::desktop::app_menu::install(cx, &menu_app_name, dev_menu); - crate::desktop::context_menu::install(cx); - // The tray icon needs a running NSApplication, so it is created here - // rather than while parsing the config. - if let Some(tray) = config.tray.take() { - if let Err(error) = crate::desktop::tray::install(cx, tray) { - log::error!("[desktop][tray] {error}"); - } - } - crate::desktop::perf_monitor::install(cx); - // Shortcut bindings are ordinary keymap bindings; this only installs the - // handler for the ones with no scope element, which is the last stop - // after every element on the focus path had its turn. - crate::desktop::keymap::register(cx); - - // The overlay slot (LogBox) has to be in the app root's element tree from the - // first frame: GPUI only re-renders entities the window tracked while drawing. - let overlay_host = cx.new(|_| OverlayHost::new()); - let root_view = - SurfaceRootView::new(APP_SURFACE_ID).with_overlay_host(overlay_host.clone()); - #[cfg(all(target_os = "macos", feature = "visual-capture"))] - let root_view = if env_bool("RN_GPUI_NATIVE_WEBVIEW_PROBE", false) { - root_view - .with_native_view_probe(crate::native_view_probe::create_webview_probe_entity(cx)) - } else if env_bool("RN_GPUI_NATIVE_COMPOSITION_PROBE", false) { - root_view.with_native_view_probe(crate::native_view_probe::create_probe_entity(cx)) - } else { - root_view - }; - let root = cx.new(|_| root_view); - let restored_bounds = config - .restore_window_state - .then(|| load_window_bounds(&window_state_path)) - .flatten(); - startup_trace("window state loaded"); - let bounds = restored_bounds - .map(|(x, y, width, height)| { - Bounds::new(point(px(x), px(y)), size(px(width), px(height))) - }) - .unwrap_or_else(|| { - let size = size(px(width), px(height)); - if let Some((x, y)) = config.position { - Bounds::new(point(px(x), px(y)), size) - } else { - Bounds::centered(None, size, cx) - } - }); - let test_display = crate::desktop::background::test_display(cx); - let bounds = if let Some(display) = &test_display { - Bounds::centered(Some(display.id()), bounds.size, cx) - } else { - #[cfg(feature = "test-driver")] - if env_bool("RN_GPUI_TEST_OFFSCREEN", false) { - Bounds::new(point(px(-10000.0), px(-10000.0)), bounds.size) - } else { - bounds - } - #[cfg(not(feature = "test-driver"))] - bounds - }; - let (width, height) = - restored_bounds.map_or((width, height), |(_, _, width, height)| (width, height)); - if let Some((x, y, restored_width, restored_height)) = restored_bounds { - log::info!( - "restoring window at ({x:.0},{y:.0} {restored_width:.0}x{restored_height:.0})" - ); - } - // Start React Native before the window exists. - // - // JS runs on its own thread, and a real app's startup is 50-300 ms that - // used to happen entirely after AppKit finished. The size and scale here - // are the values the window is about to be created with; anything the - // window alone can report (its top inset, its final scale) is applied - // once it exists, through the same path a resize takes. - // GPUI reports the scale from a window, and there is no window yet. - // `RN_GPUI_SCALE` overrides it for tests; otherwise the estimate is the - // Retina default on macOS and 1.0 elsewhere. The surface is corrected - // below if the window disagrees, so a wrong guess costs one resize, not a - // wrong layout. - let estimated_scale = - scale_override.unwrap_or(if cfg!(target_os = "macos") { 2.0 } else { 1.0 }); - // A surface must not start at zero: `RN_GPUI_WIDTH=0` would otherwise - // reach JS as a 0x0 viewport, and Fabric would lay out the whole tree in - // no space at all. The window's own size is authoritative once it opens. - let surface_width = width.max(320.0); - let surface_height = height.max(240.0); - let host = Host::new( - &app_id, - &dev_host, - dev_port, - &js_engine, - js_thread, - dev_mode(), - ); - startup_trace("host created"); - host.set_window_metrics(surface_width, surface_height, estimated_scale); - let screen = cx - .primary_display() - .map(|display| display.bounds().size) - .map(|size| (f32::from(size.width), f32::from(size.height))) - .unwrap_or((surface_width, surface_height)); - host.set_display_metrics( - screen.0, - screen.1, - crate::desktop::display::system_font_scale(), - ); - crate::desktop::memory_pressure::start(host.clone()); - #[cfg(not(target_os = "macos"))] - crate::accessibility::install_announcer(); - startup_trace("bundle load start"); - if !host.load_script(&bundle, &source_url) { - log::error!("load_script failed for {bundle}"); - std::process::exit(1); - } - crate::desktop::deep_link::mark_ready(host.clone()); - startup_trace("bundle load end"); - log::info!("loaded {bundle}"); - // The surface starts now as well: mount batches queue on the main-thread - // channel until the store and its window exist, which is the same path a - // background surface already uses. - let menu_bar_inset = crate::desktop::gpui_menu::menu_bar_inset(); - // Before the window exists the compositor's answer is unknown; a custom - // title bar asks for client decorations, which is what gets the margin. - #[cfg(target_os = "linux")] - if crate::desktop::window_frame::wanted( - matches!(config.background, WindowBackground::Opaque), - config.shadow, - config.title_bar == WindowTitleBar::Borderless, - ) { - crate::desktop::window_frame::enroll(APP_SURFACE_ID); - } - let estimated_frame = if cfg!(target_os = "linux") - && (config.title_bar.is_custom() || crate::desktop::capabilities::is_wayland()) - { - let extent = crate::desktop::window_frame::frame().shadow_extent; - crate::desktop::window_frame::Insets { - left: extent, - top: extent, - right: extent, - bottom: extent, - } - } else { - crate::desktop::window_frame::Insets::default() - }; - let gpui_first = config.gpui_root.is_some(); - if let Some(build) = config.gpui_root.take() { - let view = build(cx, crate::runtime::ReactRuntime::new(estimated_scale)); - root.update(cx, |root, _cx| root.set_app_content(view)); - } else { - host.start_surface( - 1, - &module, - (surface_width - estimated_frame.horizontal()).max(1.0), - (surface_height - menu_bar_inset - estimated_frame.vertical()).max(1.0), - estimated_scale, - ); - } - startup_trace("surface started"); - if !gpui_first { - cx.set_global(crate::desktop::windows::ReopenWindow( - crate::desktop::windows::OpenWindowOptions { - component: module.clone(), - title: Some(config.title.clone().unwrap_or_else(|| module.clone())), - width: Some(width), - height: Some(height), - resizable: true, - title_bar: config.title_bar, - background: config.background, - window_buttons: Some(config.window_buttons), - shadow: Some(config.shadow), - traffic_light_position: config.traffic_light_position, - ..Default::default() - }, - )); - } - - startup_trace("opening GPUI window"); - let mut window_options = WindowOptions { - window_bounds: Some(WindowBounds::Windowed(bounds)), - window_background: config.background.appearance(), - ..Default::default() - }; - if config.title_bar.is_custom() { - let titlebar = window_options.titlebar.get_or_insert_with(Default::default); - // macOS and Windows both express "no system chrome" as a transparent - // title bar. Linux has no such flag: it asks the compositor for - // client-side decorations instead, which is the same outcome — the - // window keeps no title bar and the app draws and moves its own. - titlebar.appears_transparent = true; - if let Some((x, y)) = config.traffic_light_position { - let (x, y) = clamp_traffic_light_position(x, y, width, height); - titlebar.traffic_light_position = Some(point(px(x), px(y))); - } - // The app draws and moves the bar itself, so AppKit must not also - // treat the content view as titlebar chrome. - window_options.app_owns_titlebar_drag = true; - // Ignored on macOS and Windows; on X11 and Wayland it is what - // removes the server-side frame. A compositor that cannot do - // client-side decorations falls back to the server's, and - // `window.window_decorations()` then says so. - window_options.window_decorations = Some(gpui::WindowDecorations::Client); - // The frame's shadow is drawn in a margin of the window itself, which - // has to be see-through for the shadow to show over the desktop. - #[cfg(target_os = "linux")] - if config.shadow - && config.title_bar != WindowTitleBar::Borderless - && matches!( - window_options.window_background, - gpui::WindowBackgroundAppearance::Opaque - ) - { - window_options.window_background = gpui::WindowBackgroundAppearance::Transparent; - } - } - #[cfg(feature = "test-driver")] - if env_bool("RN_GPUI_TEST_OFFSCREEN", false) { - // AppKit clamps remote coordinates into the visible desktop. - // Hidden windows still support forced draws and injected input. - window_options.show = false; - window_options.focus = false; - } - if !config.visible - || std::env::args() - .skip(1) - .any(|argument| argument == START_HIDDEN_ARGUMENT) - { - window_options.show = false; - window_options.focus = false; - crate::desktop::windows::note_main_started_hidden(); - } - window_options.is_resizable = config.resizable; - if let Some(display) = &test_display { - window_options.display_id = Some(display.id()); - } - if let Some(configure_window) = config.configure_window.take() { - configure_window(&mut window_options); - } - let show_behind = crate::desktop::background::prepare(&mut window_options); - #[cfg(feature = "visual-capture")] - if std::env::var_os("RN_GPUI_TRANSPARENT_TITLEBAR").is_some() { - window_options - .titlebar - .get_or_insert_with(Default::default) - .appears_transparent = true; - } - #[cfg(target_os = "windows")] - let opens_hidden = !window_options.show; - crate::app_hooks::run_app_init(cx); - let window = crate::app_hooks::open_root_window(cx, window_options, { - let root = root.clone(); - move |_window, _cx| root - }) - .expect("failed to open the GPUI window"); - startup_trace("window open"); - if show_behind { - let _ = window.update(cx, |_root, window, _cx| { - crate::desktop::background::show_behind(window); - }); - } - // Set per window, not once: a dev run's executable carries no icon, and - // on Windows the icon belongs to the window, not the application. Windows - // opened later get it in `windows::open_window`. - let _ = window.update(cx, |_root, window, _cx| { - crate::desktop::platform_window::apply_app_icon(window); - }); - let window_id = window.window_id(); - // What the compositor actually gave, which is the only authority on - // whether the request for client-side decorations was granted. A window - // manager that ignored it kept its own frame, and the app then has to - // know not to draw a second set of caption buttons beside it. - let applied_decorations = window - .update(cx, |_root, window, _cx| window.window_decorations()) - .ok(); - if let Some(decorations) = applied_decorations { - crate::desktop::capabilities::note_window_decorations(decorations); - } - - // A window created with `show: false` never receives the message that - // carries its initial size on Windows, and GPUI creates the HWND with - // `CW_USEDEFAULT`, so `window.bounds()` reports that sentinel - // (`-1717986944`) until something resizes the window. Laying out at that - // size fails React Native's own assertion (`minimumSize.width >= 0`) and - // kills the process. Resizing delivers the `WM_SIZE` a shown window - // would have received at creation, which is what publishes the real - // size to the bounds observers. `bounds_changed` is deliberately not - // called here: it would lay the surface out at the sentinel size before - // that message arrives. - #[cfg(target_os = "windows")] - if opens_hidden { - let requested = bounds.size; - let applied = window.update(cx, move |_root, window, _cx| { - if window.viewport_size() != requested { - window.resize(requested); - } - }); - if let Err(error) = applied { - log::warn!("could not size the hidden window: {error}"); - } - } - - if config.title.is_some() || config.on_window_opened.is_some() { - let title = config.title.take(); - let on_window_opened = config.on_window_opened.take(); - window - .update(cx, move |_root, window, cx| { - if let Some(title) = title.as_deref() { - window.set_window_title(title); - } - if let Some(on_window_opened) = on_window_opened { - on_window_opened(window_id, window, cx); - } - }) - .expect("failed to configure the opened GPUI window"); - } - - let window_bounds = window - .update(cx, |_root, window, _cx| { - let bounds = window.bounds(); - ( - f32::from(bounds.origin.x), - f32::from(bounds.origin.y), - f32::from(bounds.size.width), - f32::from(bounds.size.height), - ) - }) - .map(|bounds| { - format!( - "({:.0},{:.0} {:.0}x{:.0})", - bounds.0, bounds.1, bounds.2, bounds.3 - ) - }) - .unwrap_or_else(|error| format!("")); - log::info!("window {window_id:?} open at {window_bounds}"); - - #[cfg(any(feature = "visual-capture", feature = "perf-timing"))] - let any_window = window; - - // React Native is already running; the window supplies the three values - // only it knows, and the surface is corrected if the estimate was wrong. - let window_scale = window - .update(cx, |_root, window, _cx| window.scale_factor()) - .unwrap_or(estimated_scale); - let scale = scale_override.unwrap_or(window_scale); - let _ = window.update(cx, |_root, window, _cx| { - crate::desktop::platform_window::style_window( - window, - config.window_buttons, - config.shadow, - config.title_bar, - ) - }); - - crate::desktop::windows::set_custom_title_bar( - crate::desktop::windows::MAIN_WINDOW_KEY, - config.title_bar.is_custom(), - ); - let top_inset = window - .update(cx, |_root, window, _cx| { - crate::desktop::windows::top_inset(window, crate::desktop::windows::MAIN_WINDOW_KEY) - }) - .unwrap_or(0.0); - host.set_window_top_inset(top_inset); - log::info!("[window-inset] native window top inset={top_inset}"); - let appearance = match cx.window_appearance() { - gpui::WindowAppearance::Dark | gpui::WindowAppearance::VibrantDark => "dark", - _ => "light", - }; - host.set_system_appearance(appearance); - // The window may have opened at a different size or scale than the - // estimate — a restore onto another display, or a maximized window — so - // the surface is told, through the path a resize takes. - // A wrong estimate is corrected here, not tolerated: JS reads Dimensions at - // module initialization, so a surface told the wrong size or scale lays out - // against it until something resizes it. Size is checked as well as scale, - // because they are wrong for different reasons — the scale is a guess from - // the platform, the size comes from the config or the restored window - // state, and a window manager can override either. - #[cfg(target_os = "linux")] - let _ = window.update(cx, |_root, window, _cx| { - crate::desktop::window_frame::sync(window, APP_SURFACE_ID) - }); - let frame_insets = crate::desktop::window_frame::insets_of(APP_SURFACE_ID); - let size_moved = (width - surface_width).abs() > f32::EPSILON - || (height - surface_height).abs() > f32::EPSILON - || frame_insets != estimated_frame; - if size_moved || (window_scale - estimated_scale).abs() > f32::EPSILON { - log::info!( - "surface corrected {surface_width}x{surface_height}@{estimated_scale}x -> \ - {width}x{height}@{window_scale}x after the window opened" - ); - if gpui_first { - // No React surface: only `Dimensions` has to learn the values. - host.set_window_metrics(width, height, scale); - } else { - // The surface itself, not only `Dimensions`. It was started at the - // estimated scale, and Yoga rounds the layout to that scale's pixel - // grid: told only about `Dimensions`, a surface started at 1x kept - // its 1x layout, so a 1230.4-point window laid out 1230 points — - // 1537.5 pixels at 1.25x — and the window's last pixel column was - // never painted until something resized it. `set_surface_size` is - // what a resize calls, and it updates `Dimensions` as well. - host.set_surface_size( - APP_SURFACE_ID, - (width - frame_insets.horizontal()).max(1.0), - (height - menu_bar_inset - frame_insets.vertical()).max(1.0), - scale, - ); - } - } - if gpui_first { - log::info!("GPUI-first app: no React tree on surface 1 (window scale {window_scale})"); - } else { - log::info!( - "started surface 1 ({module}) at {width}x{}@{scale}x (window scale {window_scale}, \ - menu bar inset {menu_bar_inset})", - height - menu_bar_inset - ); - } - - let frame_hook = crate::frame::FrameHook::new(host.clone()); - window - .update(cx, |_root, window, _cx| frame_hook.arm(window)) - .expect("failed to arm the per-frame hook"); - let appearance_host = host.clone(); - let appearance_subscription = window - .update(cx, |_root, window, _cx| { - window.observe_window_appearance(move |window, _cx| { - let appearance = match window.appearance() { - gpui::WindowAppearance::Dark | gpui::WindowAppearance::VibrantDark => { - "dark" - } - _ => "light", - }; - appearance_host.set_system_appearance(appearance); - // The compositor can settle the decorations after the window - // exists (a Wayland `configure`), so a change is passed on to - // the app, which draws its caption buttons by it. - #[cfg(target_os = "linux")] - { - let before = crate::desktop::capabilities::observed_client_decorations(); - crate::desktop::capabilities::note_window_decorations( - window.window_decorations(), - ); - if crate::desktop::capabilities::observed_client_decorations() != before { - appearance_host - .emit_device_event_json("gpuiDesktop:windowDecorations", "{}"); - } - } - }) - }) - .expect("failed to observe window appearance"); - - #[cfg(feature = "visual-capture")] - let host_for_input = host.clone(); - let store = cx.new(|_| { - ViewStore::new( - host, - window, - frame_hook.clone(), - overlay_host, - LayoutEventOwner::from_loom_flag(rn_gpui_sys::LOOM_RENDERER), - ) - }); - cx.set_global(StoreGlobal(store.clone())); - #[cfg(feature = "test-driver")] - if std::env::var("RN_GPUI_TEST_DRIVER").as_deref() == Ok("1") { - let animations_disabled = std::env::var("RN_GPUI_TEST_DISABLE_ANIMATIONS") - .map(|value| matches!(value.as_str(), "1" | "true" | "yes")) - .unwrap_or(false); - crate::animation_policy::set_animations_disabled(animations_disabled); - crate::test_driver::start(cx, store.clone(), window); - } - let keyboard_host = store.read(cx).host.clone(); - let keyboard_hook = frame_hook.clone(); - let navigation_keyboard_subscription = cx.intercept_keystrokes(move |event, window, cx| { - if window.window_handle().window_id() != window_id { - return; - } - if let Some(event_name) = - crate::builtins::textinput::input::desktop_navigation_event(&event.keystroke) - { - keyboard_host.emit_device_event(event_name); - keyboard_hook.arm(window); - log::info!("[navigation] emitted {event_name} from keyboard"); - cx.stop_propagation(); - } - }); - - crate::desktop::perf_monitor::attach(cx, &root, 1); - // The menu bar is prepared inside a window update (it needs the window - // for the activation observer) and attached to the root afterwards, - // outside any update that has already leased the root. - // `window.menuBar: false` hides the bar before it is ever drawn, so the - // window opens at the right size instead of shrinking once the bar goes. - crate::desktop::button_layout::set_fallback_left(config.window_controls_left); - if !config.menu_bar { - crate::desktop::gpui_menu::set_menu_bar_visible( - crate::desktop::windows::MAIN_WINDOW_KEY, - false, - ); - } - let menu_bar = window - .update(cx, |_root, window, cx| { - crate::desktop::gpui_menu::prepare(window, cx, 1) - }) - .ok() - .flatten(); - if let Some(prepared) = menu_bar { - crate::desktop::gpui_menu::attach(cx, &root, prepared); - } - store.update(cx, |store, cx| { - store.register_root(1, root); - store.top_inset = top_inset; - store.refresh_inherited(1, cx); - store.navigation_keyboard_subscription = Some(navigation_keyboard_subscription); - store.window_appearance_subscription = Some(appearance_subscription); - cx.notify(); - }); - - cx.global_mut::() - .0 - .adopt( - crate::desktop::windows::MAIN_WINDOW_KEY, - window, - 1, - module.clone(), - serde_json::json!({}), - crate::desktop::windows::WindowRole::Main, - ); - - crate::desktop::windows::install_main_window_events( - cx, - window, - crate::desktop::windows::MAIN_WINDOW_KEY, - ); - - // Without the close hook `closeRequested` never fires for the main window. - crate::desktop::windows::install_close_hook_for( - cx, - window, - crate::desktop::windows::MAIN_WINDOW_KEY, - ); - - #[cfg(feature = "visual-capture")] - if !clicks.is_empty() { - let host = host_for_input.clone(); - cx.spawn(async move |cx| { - for (x, y) in clicks { - let timer = cx - .background_executor() - .timer(Duration::from_millis(u64::from(click_ms))); - timer.await; - let position = gpui::point(px(x), px(y)); - log::info!("clicking at {x},{y}"); - let clicked = cx.update_window( - any_window, - move |_root: gpui::AnyView, window: &mut gpui::Window, cx: &mut App| { - let arena_clear_needed = window.draw(cx); - arena_clear_needed.clear(cx); - let down = gpui::PlatformInput::MouseDown(gpui::MouseDownEvent { - button: gpui::MouseButton::Left, - position, - ..Default::default() - }); - window.dispatch_event(down, cx); - }, - ); - if let Err(error) = clicked { - log::error!("click at {x},{y} failed: {error}"); - } - if click_hold_ms > 0 { - cx.background_executor() - .timer(Duration::from_millis(u64::from(click_hold_ms))) - .await; - } - let _ = cx.update_window( - any_window, - move |_root: gpui::AnyView, window: &mut gpui::Window, cx: &mut App| { - window.dispatch_event( - gpui::PlatformInput::MouseUp(gpui::MouseUpEvent { - button: gpui::MouseButton::Left, - position, - ..Default::default() - }), - cx, - ); - }, - ); - if !skip_synthetic_input_flush { - flush_js(&host, cx).await; - } - } - }) - .detach(); - } - - #[cfg(feature = "visual-capture")] - if !drags.is_empty() { - let host = host_for_input.clone(); - let frame_hook = frame_hook.clone(); - cx.spawn(async move |cx| { - for (index, (start_x, start_y, end_x, end_y, cancel)) in - drags.into_iter().enumerate() - { - let delay = if index == 0 { drag_start_ms } else { drag_ms }; - cx.background_executor() - .timer(Duration::from_millis(u64::from(delay))) - .await; - log::info!("dragging from {start_x},{start_y} to {end_x},{end_y}"); - let start = gpui::point(px(start_x), px(start_y)); - let down = cx.update_window( - any_window, - move |_root: gpui::AnyView, window: &mut gpui::Window, cx: &mut App| { - let arena_clear_needed = window.draw(cx); - arena_clear_needed.clear(cx); - window.dispatch_event( - gpui::PlatformInput::MouseDown(gpui::MouseDownEvent { - button: gpui::MouseButton::Left, - position: start, - ..Default::default() - }), - cx, - ); - }, - ); - if let Err(error) = down { - log::error!("drag down failed: {error}"); - continue; - } - flush_js(&host, cx).await; - - for step in 1..=8 { - let amount = step as f32 / 8.0; - let position = gpui::point( - px(start_x + (end_x - start_x) * amount), - px(start_y + (end_y - start_y) * amount), - ); - let hook = frame_hook.clone(); - let moved = cx.update_window( - any_window, - move |_root: gpui::AnyView, window: &mut gpui::Window, cx: &mut App| { - let arena_clear_needed = window.draw(cx); - arena_clear_needed.clear(cx); - window.dispatch_event( - gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent { - position, - pressed_button: Some(gpui::MouseButton::Left), - ..Default::default() - }), - cx, - ); - hook.arm(window); - }, - ); - if let Err(error) = moved { - log::error!("drag move {step} failed: {error}"); - break; - } - flush_js(&host, cx).await; - } - - let end = gpui::point(px(end_x), px(end_y)); - let hook = frame_hook.clone(); - let released = cx.update_window( - any_window, - move |_root: gpui::AnyView, window: &mut gpui::Window, cx: &mut App| { - let arena_clear_needed = window.draw(cx); - arena_clear_needed.clear(cx); - if cancel { - crate::events::cancel_active_touch(window, cx, end); - } - window.dispatch_event( - gpui::PlatformInput::MouseUp(gpui::MouseUpEvent { - button: gpui::MouseButton::Left, - position: end, - ..Default::default() - }), - cx, - ); - hook.arm(window); - }, - ); - if let Err(error) = released { - log::error!("drag release failed: {error}"); - } - flush_js(&host, cx).await; - } - }) - .detach(); - } - - #[cfg(feature = "visual-capture")] - if !hovers.is_empty() { - let frame_hook = frame_hook.clone(); - let host = host_for_input.clone(); - cx.spawn(async move |cx| { - for (x, y) in hovers { - let timer = cx - .background_executor() - .timer(Duration::from_millis(u64::from(hover_ms))); - timer.await; - let position = gpui::point(px(x), px(y)); - log::info!("hovering at {x},{y}"); - let hook = frame_hook.clone(); - let hovered = cx.update_window( - any_window, - move |_root: gpui::AnyView, window: &mut gpui::Window, cx: &mut App| { - // Hit testing uses the last drawn frame, and a - // headless run cannot rely on the platform asking - // for one after a mount batch, so draw first. - let arena_clear_needed = window.draw(cx); - arena_clear_needed.clear(cx); - let input = gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent { - position, - pressed_button: None, - ..Default::default() - }); - window.dispatch_event(input, cx); - hook.arm(window); - }, - ); - if let Err(error) = hovered { - log::error!("hover at {x},{y} failed: {error}"); - } - flush_js(&host, cx).await; - } - }) - .detach(); - } - - #[cfg(feature = "visual-capture")] - if !scrolls.is_empty() { - let frame_hook = frame_hook.clone(); - let host = host_for_input.clone(); - cx.spawn(async move |cx| { - for (index, (x, y, dx, dy)) in scrolls.into_iter().enumerate() { - let delay = if index == 0 { - scroll_start_ms - } else { - scroll_ms - }; - cx.background_executor() - .timer(Duration::from_millis(u64::from(delay))) - .await; - let position = gpui::point(px(x), px(y)); - log::info!("scrolling at {x},{y} by {dx},{dy}"); - let hook = frame_hook.clone(); - let scrolled = cx.update_window( - any_window, - move |_root: gpui::AnyView, window: &mut gpui::Window, cx: &mut App| { - let arena_clear_needed = window.draw(cx); - arena_clear_needed.clear(cx); - window.dispatch_event( - gpui::PlatformInput::Scroll(gpui::ScrollEvent { - position, - delta: gpui::ScrollDelta::Pixels(gpui::point(px(dx), px(dy))), - ..Default::default() - }), - cx, - ); - hook.arm(window); - }, - ); - if let Err(error) = scrolled { - log::error!("scroll at {x},{y} failed: {error}"); - } - flush_js(&host, cx).await; - } - }) - .detach(); - } - - #[cfg(feature = "visual-capture")] - if !keys.is_empty() { - let frame_hook = frame_hook.clone(); - let host = host_for_input.clone(); - cx.spawn(async move |cx| { - for key in keys { - cx.background_executor() - .timer(Duration::from_millis(u64::from(key_ms))) - .await; - let Ok(keystroke) = - gpui::Keystroke::parse_with_os(&key, crate::desktop::keymap::host_os()) - else { - log::warn!("invalid synthetic keystroke: {key}"); - continue; - }; - log::info!("pressing key {key}"); - let hook = frame_hook.clone(); - let pressed = cx.update_window( - any_window, - move |_root: gpui::AnyView, window: &mut gpui::Window, cx: &mut App| { - let arena_clear_needed = window.draw(cx); - arena_clear_needed.clear(cx); - window.dispatch_keystroke(keystroke.clone(), cx); - window.dispatch_event( - gpui::PlatformInput::KeyUp(gpui::KeyUpEvent { keystroke }), - cx, - ); - hook.arm(window); - }, - ); - if let Err(error) = pressed { - log::error!("key {key} failed: {error}"); - } - flush_js(&host, cx).await; - } - }) - .detach(); - } - - #[cfg(feature = "visual-capture")] - if !mouse_navigation.is_empty() { - let host = host_for_input.clone(); - let frame_hook = frame_hook.clone(); - cx.spawn(async move |cx| { - for direction in mouse_navigation { - cx.background_executor() - .timer(Duration::from_millis(u64::from(mouse_navigation_ms))) - .await; - let button = match direction.as_str() { - "back" => gpui::MouseButton::Navigate(gpui::NavigationDirection::Back), - _ => gpui::MouseButton::Navigate(gpui::NavigationDirection::Forward), - }; - let hook = frame_hook.clone(); - let dispatched = cx.update_window( - any_window, - move |_root: gpui::AnyView, window: &mut gpui::Window, cx: &mut App| { - let arena_clear_needed = window.draw(cx); - arena_clear_needed.clear(cx); - let position = gpui::point(px(1.), px(1.)); - window.dispatch_event( - gpui::PlatformInput::MouseDown(gpui::MouseDownEvent { - button, - position, - ..Default::default() - }), - cx, - ); - window.dispatch_event( - gpui::PlatformInput::MouseUp(gpui::MouseUpEvent { - button, - position, - ..Default::default() - }), - cx, - ); - hook.arm(window); - }, - ); - if let Err(error) = dispatched { - log::error!("synthetic mouse navigation {direction} failed: {error}"); - } else { - log::info!("pressed mouse navigation {direction}"); - } - flush_js(&host, cx).await; - } - }) - .detach(); - } - - #[cfg(all(target_os = "macos", feature = "visual-capture"))] - if env_u32("RN_GPUI_TITLEBAR_TOGGLE_MS", 0) > 0 { - let delay = env_u32("RN_GPUI_TITLEBAR_TOGGLE_MS", 0); - cx.spawn(async move |cx| { - for transparent in [false, true] { - cx.background_executor() - .timer(Duration::from_millis(u64::from(delay))) - .await; - let _ = cx.update_window(any_window, move |_, window, cx| { - crate::native_view::set_probe_titlebar_transparent(window, transparent); - window.bounds_changed(cx); - window.refresh(); - log::info!("[window-inset] probe titlebar transparent={transparent}"); - }); - } - }) - .detach(); - } - #[cfg(feature = "visual-capture")] - if env_u32("RN_GPUI_FULLSCREEN_MS", 0) > 0 { - let delay = env_u32("RN_GPUI_FULLSCREEN_MS", 0); - cx.spawn(async move |cx| { - for interval in [delay, 3000] { - cx.background_executor() - .timer(Duration::from_millis(u64::from(interval))) - .await; - let _ = cx.update_window(any_window, |_, window, _| window.toggle_fullscreen()); - } - }) - .detach(); - } - - // The subscription unsubscribes the moment it drops, so it is handed to the - // store. - let last_surface_size = Rc::new(Cell::new((width, height, scale, 0.0, 0.0))); - let bounds_subscription = window - .update(cx, |_root, window, cx| { - let store = cx.global::().0.clone(); - let frame_hook = frame_hook.clone(); - let window_state_path = window_state_path.clone(); - let last_surface_size = last_surface_size.clone(); - crate::app_hooks::observer_context_joined(cx, |observers| { - observers.observe_window_bounds(window, move |_root, window, cx| { - // GPUI calls bounds observers on every resize notification and layout, so - // nothing here may write to disk or log unless a value changed. - let size = window.viewport_size(); - let scale = scale_override.unwrap_or_else(|| window.scale_factor()); - let (width, height) = (f32::from(size.width), f32::from(size.height)); - let bounds = window.bounds(); - let origin = (f32::from(bounds.origin.x), f32::from(bounds.origin.y)); - #[cfg(target_os = "linux")] - let frame_changed = - crate::desktop::window_frame::sync(window, APP_SURFACE_ID); - #[cfg(not(target_os = "linux"))] - let frame_changed = false; - let previous = last_surface_size.get(); - let resized = frame_changed - || (previous.0 - width).abs() > 0.01 - || (previous.1 - height).abs() > 0.01 - || (previous.2 - scale).abs() > 0.001; - let moved = (previous.3 - origin.0).abs() > 0.01 - || (previous.4 - origin.1).abs() > 0.01; - let top = crate::desktop::windows::top_inset( - window, - crate::desktop::windows::MAIN_WINDOW_KEY, - ); - let inset_changed = cx - .try_global::() - .is_some_and(|global| (global.0.read(cx).top_inset - top).abs() > 0.01); - if !resized && !moved && !inset_changed { - return; - } - last_surface_size.set((width, height, scale, origin.0, origin.1)); - save_window_bounds(&window_state_path, bounds, size); - if inset_changed { - crate::desktop::window_mirror::patch( - crate::desktop::windows::MAIN_WINDOW_KEY, - &[("topInset", serde_json::json!(top))], - ); - store.update(cx, |store, _cx| { - store.top_inset = top; - store.host.set_window_top_inset(top); - store.frame_hook.arm(window); - }); - // Deferred: this observer runs with the window's root view - // borrowed, and refreshing the surface reads it. A compositor - // that settles the decorations after the window opens (sway) - // changes the inset right here. - let deferred_store = store.clone(); - cx.defer(move |cx| { - deferred_store.update(cx, |store, cx| { - for node in store.nodes.values() { - let component = node.read(cx).component.clone(); - let depends = - crate::extensions::component_renderer(&component) - .is_some_and(|renderer| { - renderer.depends_on_window_insets() - }); - if depends { - node.update(cx, |_, cx| cx.notify()); - } - } - store.refresh_inherited(1, cx); - }); - }); - log::info!( - "[window-inset] native window top inset={top} fullscreen={}", - window.is_fullscreen() - ); - } - if resized { - log::info!("window resized to {width}x{height}@{scale}x"); - let handle: gpui::AnyWindowHandle = window.window_handle().into(); - store.update(cx, |store, cx| { - store.resize_window(handle, width, height, scale, cx) - }); - frame_hook.arm(window); - } - }) - }) - }) - .expect("failed to observe the window's bounds"); - // Windows only: its caption buttons and the title bar's double click maximize - // the window without the app being told, which this is how it learns. - let state_subscription = if cfg!(windows) { - Some( - window - .update(cx, |_root, window, cx| { - crate::app_hooks::observer_context_joined(cx, |observers| { - crate::desktop::windows::install_state_observer(window, observers) - }) - }) - .expect("failed to observe the window's state"), - ) - } else { - None - }; - store.update(cx, |store, _cx| { - store.window_bounds_subscription = Some(bounds_subscription); - store.window_state_subscription = state_subscription; - }); - - #[cfg(feature = "visual-capture")] - if resize_ms > 0 { - let target = size(px(resize_width), px(resize_height)); - let timer = cx - .background_executor() - .timer(Duration::from_millis(u64::from(resize_ms))); - cx.spawn(async move |cx| { - timer.await; - log::info!("resizing the window to {resize_width}x{resize_height}"); - let resized = cx.update_window( - any_window, - move |_root: gpui::AnyView, window: &mut gpui::Window, _cx: &mut App| { - window.resize(target) - }, - ); - if let Err(error) = resized { - log::error!("window resize failed: {error}"); - } - }) - .detach(); - } - - #[cfg(feature = "visual-capture")] - if run_ms > 0 { - let timer = cx - .background_executor() - .timer(Duration::from_millis(u64::from(run_ms))); - cx.spawn(async move |cx| { - timer.await; - log::info!("staying alive for {run_ms} ms — closing"); - cx.update(|cx| cx.quit()); - }) - .detach(); - } - - #[cfg(feature = "perf-timing")] - if benchmark_ms > 0 { - let timer = cx - .background_executor() - .timer(Duration::from_millis(u64::from(benchmark_ms))); - cx.spawn(async move |cx| { - timer.await; - let result = cx.update_window( - any_window, - move |_root: gpui::AnyView, window: &mut gpui::Window, _cx: &mut App| { - let snapshot = window.frame_duration_snapshot(); - let draw = &snapshot.draw_duration_histogram; - let interval = &snapshot.present_interval_histogram; - log::info!( - "[bench] mode={benchmark_mode} draw_frames={} draw_mean_ms={:.3} draw_p50_ms={:.3} draw_p95_ms={:.3} draw_p99_ms={:.3} draw_max_ms={:.3} present_intervals={} present_mean_ms={:.3} present_p95_ms={:.3}", - draw.len(), - draw.mean() / 1_000_000.0, - draw.value_at_quantile(0.50) as f64 / 1_000_000.0, - draw.value_at_quantile(0.95) as f64 / 1_000_000.0, - draw.value_at_quantile(0.99) as f64 / 1_000_000.0, - draw.max() as f64 / 1_000_000.0, - interval.len(), - interval.mean() / 1_000_000.0, - interval.value_at_quantile(0.95) as f64 / 1_000_000.0, - ); - }, - ); - if let Err(error) = result { - log::error!("benchmark snapshot failed: {error}"); - } - }) - .detach(); - } - - cx.spawn(async move |cx| { - let mut smoke_frame_armed = false; - let mut startup_mounts_traced = 0u32; - let mut mount_batches_traced = 0u64; - #[cfg(feature = "visual-capture")] - for (delay_ms, path) in screenshots { - let store = store.clone(); - let mut path = Some(path); - cx.spawn(async move |cx| { - capture_and_quit(cx, &store, &mut path, delay_ms).await; - }) - .detach(); - } - #[cfg(feature = "visual-capture")] - if let Some(path) = screenshot { - let store = store.clone(); - let mut path = Some(path); - cx.spawn(async move |cx| { - capture_and_quit(cx, &store, &mut path, screenshot_delay_ms).await; - }) - .detach(); - } - while let Ok(event) = rx.recv().await { - match event { - MainEvent::Mount(batch) => { - let surface_id = batch.surface_id; - let ops = batch.ops.len(); - let started = std::time::Instant::now(); - store.update(cx, |store, cx| store.apply_batch(batch, cx)); - let elapsed = started.elapsed().as_secs_f32() * 1000.0; - cx.update(|cx| crate::desktop::perf_monitor::record_mount(cx, elapsed)); - // SAFETY: the C++ function decrements an atomic counter and takes no arguments. - unsafe { rn_gpui_mount_batch_applied() }; - if surface_id == APP_SURFACE_ID && mount_trace_enabled() { - mount_batches_traced += 1; - eprintln!( - "[mount-trace] applied batch={mount_batches_traced} ops={ops} store_apply_ms={elapsed:.2} epoch_ms={:.3}", - epoch_ms() - ); - let window = store.read_with(cx, |store, _| store.window); - trace_mount_presented(cx, window, mount_batches_traced); - } - if surface_id == APP_SURFACE_ID && startup_mounts_traced < 16 { - startup_mounts_traced += 1; - startup_trace(&format!("mount applied ops={ops} store_apply_ms={elapsed:.1}")); - let window = store.read_with(cx, |store, _| store.window); - trace_next_content_frame(cx, window); - } - // Smoke mode: an app-surface batch is React content, so - // the frame GPUI draws after it is the one a human sees. - if smoke && !smoke_frame_armed && surface_id == APP_SURFACE_ID { - smoke_frame_armed = true; - let window = store.read_with(cx, |store, _| store.window); - smoke_arm_first_frame(cx, window); - } - } - MainEvent::SurfaceStopped(surface_id) => { - if surface_id == rn_gpui_sys::ALL_SURFACES { - rn_gpui_sys::ffi::rn_gpui_rust_module_clear_pending(); - } - store.update(cx, |store, cx| store.surface_stopped(surface_id, cx)); - } - MainEvent::DevMenuShow => { - cx.update(|cx| crate::desktop::dev_menu::show(cx)); - } - MainEvent::TrayClick { - x, - y, - width, - height, - button, - } => { - cx.update(|cx| { - crate::desktop::tray::handle_click( - cx, - crate::desktop::tray::TrayRect { - x, - y, - width, - height, - }, - match button { - 1 => crate::desktop::tray::TrayButton::Right, - 2 => crate::desktop::tray::TrayButton::Middle, - _ => crate::desktop::tray::TrayButton::Left, - }, - ) - }); - } - MainEvent::GlobalShortcut(hotkey) => { - cx.update(|cx| crate::desktop::global_shortcut::fire(cx, hotkey)); - } - MainEvent::GlobalShortcutNamed(id) => { - cx.update(|cx| crate::desktop::global_shortcut::fire_named(cx, &id)); - } - MainEvent::GlobalShortcutRefused(id, reason) => { - cx.update(|cx| { - crate::desktop::global_shortcut::report_failure(cx, &id, &reason) - }); - } - MainEvent::MenuBarPerform(id) => { - cx.update(|cx| crate::desktop::app_menu::trigger_item(cx, &id)); - } - MainEvent::TrayMenuPerform(id) => { - cx.update(|cx| crate::desktop::tray::perform_menu(cx, &id)); - } - MainEvent::DevMenuPerform(id) => { - cx.update(|cx| crate::desktop::dev_menu::perform(cx, &id)); - } - MainEvent::DevSetting { name, enabled } => { - cx.update(|cx| { - crate::desktop::dev_menu::apply_setting(cx, &name, enabled) - }); - } - MainEvent::DesktopCommand(command) => { - cx.update(|cx| command(cx)); - } - MainEvent::MainTask(id) => { - rn_gpui_sys::ffi::rn_gpui_run_main_task(id); - } - MainEvent::RustJob(job) => { - cx.spawn(async move |_| { - job().await; - }) - .detach(); - } - MainEvent::AnimatedProps(props) => { - if props.has_opacity - || props.has_transform - || props.reset_transform - || props.has_background_color - || props.has_text_color - { - let mut target = None; - store.update(cx, |store, cx| { - target = store - .nodes - .get(&props.tag) - .cloned() - .map(|node| (node.read(cx).surface_id, node)); - }); - if let Some((surface_id, node)) = target { - node.update(cx, |node, cx| { - if props.has_opacity { - node.set_animated_opacity(props.opacity); - } - if props.has_background_color { - node.set_animated_background_color(props.background_color); - } - if props.has_text_color { - node.set_animated_text_color(props.text_color); - } - if props.has_transform { - node.set_animated_transform(Some(props.transform)); - } else if props.reset_transform { - node.set_animated_transform(None); - } - cx.notify(); - }); - if props.has_transform || props.reset_transform { - store.update(cx, |store, cx| { - store.refresh_inherited(surface_id, cx) - }); - } - } - } - } - MainEvent::AnimatedActivity(active) => { - let mut target = None; - store.update(cx, |store, _cx| { - target = Some((store.window, store.frame_hook.clone())); - }); - if let Some((window, frame_hook)) = target { - if let Err(error) = - cx.update_window(window, move |_root, window, cx| { - frame_hook.set_animation_active(active, window, cx); - }) - { - log::debug!( - "[native-animated] failed to update GPUI window activity: {error}" - ); - } - } else if std::env::var_os("RN_GPUI_DEBUG_ANIMATION").is_some() { - log::warn!("[native-animated] animation activity has no window"); - } - } - MainEvent::TextInputCommand { tag, focus } => { - let target = { - let mut target = None; - store.update(cx, |store, _cx| { - target = store.nodes.get(&tag).cloned().map(|node| (store.window, node)); - }); - target - }; - if let Some((window_handle, node)) = target { - let _ = cx.update_window(window_handle, move |_root, window, cx| { - node.update(cx, |node, cx| { - node.apply_text_input_focus_command(focus, window, cx); - }); - }); - } - } - MainEvent::AccessibilityFocus(tag) => { - let target = { - let mut target = None; - store.update(cx, |store, _cx| { - target = store - .nodes - .get(&tag) - .cloned() - .map(|node| (store.window, node)); - }); - target - }; - if let Some((window_handle, node)) = target { - let _ = cx.update_window(window_handle, move |_root, window, cx| { - node.update(cx, |node, cx| { - node.focus_for_accessibility(window, cx); - }); - }); - } - } - MainEvent::NativeRootOps { root, payload } => { - let _ = cx.update(|cx| crate::builtins::native_root::apply_ops(cx, root, &payload)); - } - MainEvent::HostCommand { tag, command, args } => { - let target = { - let mut target = None; - store.update(cx, |store, _cx| { - target = store.nodes.get(&tag).cloned().map(|node| { - let window = store - .window_for(node.read(_cx).surface_id) - .unwrap_or(store.window); - (window, node) - }); - }); - target - }; - if let Some((window_handle, node)) = target { - let _ = cx.update_window(window_handle, move |_root, window, cx| { - node.update(cx, |node, cx| { - node.dispatch_host_command(command, &args, Some(window), cx); - }); - }); - } - } - MainEvent::BuiltinCommand { tag, component, name, args } => { - let target = { - let mut target = None; - store.update(cx, |store, _cx| { - target = store.nodes.get(&tag).cloned().map(|node| (store.window, node)); - }); - target - }; - let handle = crate::extensions::StoreHandle::new(store.downgrade()); - if let Some((window_handle, node)) = target { - let _ = cx.update_window(window_handle, move |_root, _window, cx| { - crate::extensions::run_builtin_command( - &node, &component, &name, &args, &handle, cx, - ); - }); - } - } - MainEvent::ScrollerStyleChanged => { - let _ = cx.update(crate::scroller_style::announce); - } - MainEvent::WheelDone { id, prevented } => { - crate::wheel::done(id, prevented, cx); - } - MainEvent::TextInputClear(tag) => { - let target = { - let mut target = None; - store.update(cx, |store, _cx| { - target = store.nodes.get(&tag).cloned().map(|node| (store.window, node)); - }); - target - }; - if let Some((window_handle, node)) = target { - let _ = cx.update_window(window_handle, move |_root, window, cx| { - node.update(cx, |node, cx| { - crate::builtins::textinput::input::clear_text_input(node, window, cx); - }); - }); - } - } - } - } - log::info!("mount channel closed"); - }) - .detach(); - - // A background run (the test driver, or `RN_GPUI_BACKGROUND=1`) never - // activates the app: it must not take focus or the menu bar, or pull - // the person to the desktop it launched on. - if test_headless { - // No application to activate or keep out of the Dock. - } else if crate::desktop::background::enabled() { - #[cfg(target_os = "macos")] - run_as_accessory_app(); - } else { - cx.activate(true); - } - log::info!("waiting for mount batches"); - }; - let http_client = std::sync::Arc::new(crate::http_client::RnHttpClient::new()); - match application { - Some(application) => application.with_http_client(http_client).run(launch), - #[cfg(feature = "test-driver")] - None => crate::headless::run(http_client, launch), - #[cfg(not(feature = "test-driver"))] - None => unreachable!("headless runs need the test-driver feature"), - } -} - -/// The real platform's application: AppKit, X11/Wayland or Win32. -fn platform_application() -> Application { - #[cfg(feature = "visual-capture")] - let headless = env_bool("RN_GPUI_HEADLESS", false); - #[cfg(not(feature = "visual-capture"))] - let headless = false; - startup_trace(if headless { - "using GPUI headless platform" - } else { - "using GPUI AppKit platform" - }); - let platform = gpui_platform::current_platform(headless); - startup_trace("platform created"); - // A locked or absent session on macOS cannot launch AppKit, and the platform - // reports no display until it can. Nothing else does: on Linux GPUI starts on - // a placeholder connection and attaches X11 or Wayland once the app runs, so - // its display list is legitimately empty here — waiting for it never ends. - #[cfg(target_os = "macos")] - { - let mut waited_for_display = 0u64; - while platform.displays().is_empty() { - if waited_for_display == 0 { - log::warn!("no active display; waiting before entering AppKit launch"); - startup_trace("waiting for an active display"); - } - std::thread::sleep(Duration::from_secs(2)); - waited_for_display += 2; - if waited_for_display % 30 == 0 { - log::warn!("still waiting for an active display ({waited_for_display}s)"); - } - } - } - startup_trace("active display detected"); - let application = - crate::app_hooks::with_registered_assets(Application::with_platform(platform)); - // An accessory app takes no Dock icon or menu bar, and the policy has to - // be set before the run loop starts or the Dock bounces at launch. - #[cfg(target_os = "macos")] - let application = if crate::desktop::background::enabled() { - application.with_windowing(gpui::WindowingRequest::Headless) - } else { - application - }; - application.on_reopen(crate::desktop::windows::reopen); - application.on_open_urls(|urls| { - for url in urls { - crate::desktop::deep_link::handle_url(url); - } - }); - application -} - -#[cfg(feature = "visual-capture")] -async fn capture_and_quit( - cx: &mut gpui::AsyncApp, - store: &gpui::Entity, - path: &mut Option, - delay_ms: u32, -) { - let timer = cx - .background_executor() - .timer(Duration::from_millis(u64::from(delay_ms))); - timer.await; - - let Some(path) = path.take() else { return }; - let window = store.read_with(cx, |store, _| store.window); - let captured = cx.update_window( - window, - |_root: gpui::AnyView, window: &mut gpui::Window, cx: &mut App| { - // `render_to_image` only replays the last drawn scene, and a headless - // run can go idle after the first frame. Draw synchronously so the capture - // reflects the current element tree. - let arena_clear_needed = window.draw(cx); - arena_clear_needed.clear(cx); - window.render_to_image() - }, - ); - match captured { - Ok(Ok(image)) => match image.save(&path) { - Ok(()) => log::info!("screenshot saved to {path}"), - Err(error) => log::error!("could not save {path}: {error}"), - }, - Ok(Err(error)) => log::error!("render_to_image failed: {error}"), - Err(error) => log::error!("update_window failed: {error}"), - } - if env_bool("RN_GPUI_KEEP_ALIVE", false) { - log::info!("screenshot saved; keeping the GPUI window open"); - } else { - cx.update(|cx| cx.quit()); - } -} - -#[cfg(target_os = "macos")] -fn run_as_accessory_app() { - use objc::{class, msg_send, sel, sel_impl}; - const ACCESSORY: isize = 1; - // SAFETY: `NSApplication` is messaged from the main thread. - unsafe { - let app: cocoa::base::id = msg_send![class!(NSApplication), sharedApplication]; - let _: bool = msg_send![app, setActivationPolicy: ACCESSORY]; - } -} - -#[cfg(test)] -mod tests { - #[test] - fn desktop_json_window_options_apply_and_a_builder_call_still_wins() { - let defaults = serde_json::json!({ - "window": { - "title": "From JSON", - "titleBar": "hidden", - "windowButtons": false, - "shadow": false, - "trafficLightPosition": {"x": 10, "y": 14}, - "resizable": false, - "menuBar": false, - "visible": false, - }, - "accessory": true, - }); - let mut config = DesktopAppConfig::from_env_with_defaults("App", "com.example.app"); - config.apply_desktop_values(&defaults); - assert_eq!(config.title.as_deref(), Some("From JSON")); - assert_eq!(config.title_bar, WindowTitleBar::Hidden); - assert!(!config.window_buttons && !config.shadow && !config.menu_bar); - assert_eq!(config.traffic_light_position, Some((10.0, 14.0))); - assert!(!config.resizable && config.accessory && !config.visible); - let config = config.title_bar(WindowTitleBar::Transparent); - assert_eq!(config.title_bar, WindowTitleBar::Transparent); - } - - use super::*; - - #[test] - fn a_title_bar_name_maps_to_the_enum_the_schema_documents() { - assert_eq!( - WindowTitleBar::from_name("default"), - WindowTitleBar::Default - ); - assert_eq!( - WindowTitleBar::from_name("transparent"), - WindowTitleBar::Transparent - ); - assert_eq!(WindowTitleBar::from_name("hidden"), WindowTitleBar::Hidden); - assert_eq!( - WindowTitleBar::from_name("none"), - WindowTitleBar::Borderless - ); - } - - #[test] - fn an_unknown_title_bar_name_keeps_the_platform_bar() { - // The schema rejects a typo in `desktop.json`, but a secondary window's - // `titleBar` prop comes from JS and an older app can send anything. A - // window with the platform's own bar is the harmless outcome; a failed - // `open` would leave the app with no window at all. - assert_eq!(WindowTitleBar::from_name(""), WindowTitleBar::Default); - assert_eq!(WindowTitleBar::from_name("Hidden"), WindowTitleBar::Default); - assert_eq!( - WindowTitleBar::from_name("nonsense"), - WindowTitleBar::Default - ); - } - - #[test] - fn only_the_two_custom_kinds_are_custom() { - assert!(!WindowTitleBar::Default.is_custom()); - assert!(WindowTitleBar::Transparent.is_custom()); - assert!(WindowTitleBar::Hidden.is_custom()); - assert!(WindowTitleBar::Borderless.is_custom()); - } - - #[test] - fn a_traffic_light_position_inside_the_window_is_unchanged() { - assert_eq!( - clamp_traffic_light_position(14.0, 10.0, 520.0, 360.0), - (14.0, 10.0) - ); - assert_eq!( - clamp_traffic_light_position(0.0, 0.0, 520.0, 360.0), - (0.0, 0.0) - ); - } - - #[test] - fn a_traffic_light_position_outside_the_window_is_pulled_back() { - // AppKit would move the buttons past the edge and leave no way to drag - // them back, so the host clamps instead. - assert_eq!( - clamp_traffic_light_position(900.0, 700.0, 520.0, 360.0), - (520.0, 360.0) - ); - assert_eq!( - clamp_traffic_light_position(-4.0, -8.0, 520.0, 360.0), - (0.0, 0.0) - ); - } - - #[test] - fn a_non_finite_or_degenerate_traffic_light_position_is_the_origin() { - // `f32::clamp` panics on NaN, and a window with no size has nowhere to - // put the buttons, so both answers are the origin rather than a panic. - assert_eq!( - clamp_traffic_light_position(f32::NAN, f32::INFINITY, 520.0, 360.0), - (0.0, 0.0) - ); - assert_eq!( - clamp_traffic_light_position(10.0, 10.0, 0.0, 0.0), - (0.0, 0.0) - ); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/activity_indicator/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/activity_indicator/mod.rs deleted file mode 100644 index f8e9d9e4c4..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/activity_indicator/mod.rs +++ /dev/null @@ -1,183 +0,0 @@ -//! `ActivityIndicator`: spokes on macOS, a sweeping arc on Windows and Linux. -//! -//! Frames are requested only while it animates, so a stopped indicator costs -//! nothing. - -use std::f32::consts::TAU; -use std::sync::Arc; -use std::time::UNIX_EPOCH; - -use gpui::{canvas, point, prelude::*, px, AnyElement, App, Bounds, Hsla, PathBuilder, Window}; -use serde_json::Value; - -use crate::extensions::{register_component_renderer, ComponentNode, ComponentRenderer}; -use crate::style::color; - -const SPOKES: usize = 12; -const SPOKE_PERIOD_SECONDS: f32 = 1.0; -const ARC_PERIOD_SECONDS: f32 = 1.2; - -fn animating(props: &Value) -> bool { - props - .get("animating") - .and_then(Value::as_bool) - .unwrap_or(true) -} - -fn hides_when_stopped(props: &Value) -> bool { - props - .get("hidesWhenStopped") - .and_then(Value::as_bool) - .unwrap_or(true) -} - -fn tint(props: &Value) -> Hsla { - let argb = props - .get("color") - .and_then(Value::as_u64) - .map(|value| value as u32) - .filter(|value| *value != 0) - .unwrap_or(if cfg!(target_os = "macos") { - 0x99_3C3C43 - } else { - 0xFF_6E6E6E - }); - color(argb) -} - -/// Seconds since an arbitrary fixed moment, so every indicator is in step. -fn clock() -> f32 { - std::time::SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0.0, |duration| (duration.as_secs_f64() % 3600.0) as f32) -} - -/// How bright spoke `index` is when the leading one is `lead`: the leader is -/// full and the ones behind it fade. -pub(crate) fn spoke_alpha(index: usize, lead: usize) -> f32 { - let behind = (lead + SPOKES - index) % SPOKES; - (1.0 - behind as f32 / SPOKES as f32).max(0.12) -} - -pub(crate) fn spoke_lead(seconds: f32) -> usize { - ((seconds / SPOKE_PERIOD_SECONDS).fract() * SPOKES as f32) as usize % SPOKES -} - -struct ActivityIndicatorRenderer; - -impl ComponentRenderer for ActivityIndicatorRenderer { - fn render(&self, _: &ComponentNode, _: &mut Window, _: &mut App) -> Option { - None - } - - fn content( - &self, - node: &ComponentNode, - window: &mut Window, - cx: &mut App, - ) -> Option { - let running = animating(&node.props); - if !running && hides_when_stopped(&node.props) { - return None; - } - let animated = running && !cx.reduce_motion(); - if animated { - window.request_animation_frame(); - } - let tint = tint(&node.props); - let seconds = if animated { clock() } else { 0.0 }; - Some( - canvas( - |_, _, _| (), - move |bounds, (), window, _cx| paint(bounds, tint, seconds, window), - ) - .size_full() - .into_any_element(), - ) - } -} - -fn paint(bounds: Bounds, tint: Hsla, seconds: f32, window: &mut Window) { - let size = f32::from(bounds.size.width.min(bounds.size.height)); - let center = point( - bounds.origin.x + bounds.size.width / 2.0, - bounds.origin.y + bounds.size.height / 2.0, - ); - if cfg!(target_os = "macos") { - let lead = spoke_lead(seconds); - let (inner, outer, thickness) = (size * 0.28, size * 0.5, size * 0.1); - for index in 0..SPOKES { - let angle = index as f32 / SPOKES as f32 * TAU; - let (sin, cos) = angle.sin_cos(); - let mut builder = PathBuilder::stroke(px(thickness)); - builder.move_to(point( - center.x + px(sin * inner), - center.y - px(cos * inner), - )); - builder.line_to(point( - center.x + px(sin * outer), - center.y - px(cos * outer), - )); - if let Ok(path) = builder.build() { - let mut spoke = tint; - spoke.a *= spoke_alpha(index, lead); - window.paint_path(path, spoke); - } - } - } else { - let radius = size * 0.5 - size * 0.08; - let turn = (seconds / ARC_PERIOD_SECONDS).fract(); - let start = turn * TAU * 2.0; - // The sweep grows and shrinks as it turns. - let sweep = TAU * (0.15 + 0.55 * (0.5 - 0.5 * (turn * TAU).cos())); - let mut builder = PathBuilder::stroke(px(size * 0.1)); - let steps = 32; - for step in 0..=steps { - let angle = start + sweep * step as f32 / steps as f32; - let (sin, cos) = angle.sin_cos(); - let at = point(center.x + px(sin * radius), center.y - px(cos * radius)); - if step == 0 { - builder.move_to(at); - } else { - builder.line_to(at); - } - } - if let Ok(path) = builder.build() { - window.paint_path(path, tint); - } - } -} - -pub fn register() { - register_component_renderer("ActivityIndicatorView", Arc::new(ActivityIndicatorRenderer)); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_leading_spoke_is_brightest_and_the_trail_fades() { - assert_eq!(spoke_alpha(3, 3), 1.0); - assert!(spoke_alpha(2, 3) < spoke_alpha(3, 3)); - assert!(spoke_alpha(4, 3) < spoke_alpha(2, 3)); - assert!(spoke_alpha(4, 3) >= 0.12); - } - - #[test] - fn the_leader_advances_once_per_period() { - assert_eq!(spoke_lead(0.0), 0); - assert_eq!(spoke_lead(0.5), SPOKES / 2); - assert_eq!(spoke_lead(1.0), 0); - } - - #[test] - fn a_stopped_indicator_follows_hides_when_stopped() { - let stopped = serde_json::json!({"animating": false}); - assert!(!animating(&stopped)); - assert!(hides_when_stopped(&stopped)); - assert!(!hides_when_stopped( - &serde_json::json!({"animating": false, "hidesWhenStopped": false}) - )); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/alert/dialog.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/alert/dialog.rs deleted file mode 100644 index 3d7061514a..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/alert/dialog.rs +++ /dev/null @@ -1,358 +0,0 @@ -//! The alert as a small GPUI window, for platforms with no native sheet: it -//! has the text fields and button styles GPUI's own prompt has no room for. - -use gpui::prelude::FluentBuilder as _; -use gpui::AppContext as _; -use gpui::{ - div, px, rgb, size, App, Bounds, Context, FocusHandle, Focusable, InteractiveElement, - IntoElement, KeyDownEvent, MouseButton, ParentElement, Render, SharedString, Styled, - TitlebarOptions, Window, WindowBounds, WindowKind, WindowOptions, -}; -use std::cell::RefCell; -use std::rc::Rc; - -use super::{Input, Outcome, Request}; - -const WIDTH: f32 = 400.0; - -struct Field { - placeholder: &'static str, - value: String, - secure: bool, -} - -thread_local! { - static CURRENT: RefCell>> = const { RefCell::new(None) }; -} - -pub(crate) struct Dialog { - request: Request, - fields: Vec, - focused_field: usize, - focus: FocusHandle, - answer: Rc>>>, -} - -/// Opens the dialog. `done` is called once, with the button chosen or -/// `Dismissed` when the window closes without one. -pub(crate) fn present(cx: &mut App, request: Request, done: Box) { - let fields = match request.input { - Input::None => Vec::new(), - Input::Plain => vec![Field { - placeholder: "", - value: request.default_value.clone(), - secure: false, - }], - Input::Secure => vec![Field { - placeholder: "", - value: request.default_value.clone(), - secure: true, - }], - Input::Login => vec![ - Field { - placeholder: "Login", - value: request.default_value.clone(), - secure: false, - }, - Field { - placeholder: "Password", - value: String::new(), - secure: true, - }, - ], - }; - let height = - 120.0 + fields.len() as f32 * 38.0 + if request.message.is_some() { 24.0 } else { 0.0 }; - let bounds = Bounds::centered(None, size(px(WIDTH), px(height)), cx); - let title = request.title.clone(); - let answer: Rc>>> = Rc::new(RefCell::new(Some(done))); - let opened = cx.open_window( - WindowOptions { - window_bounds: Some(WindowBounds::Windowed(bounds)), - titlebar: Some(TitlebarOptions { - title: Some(SharedString::from(title)), - ..Default::default() - }), - is_resizable: false, - kind: WindowKind::Dialog, - ..Default::default() - }, - { - let answer = answer.clone(); - move |window, cx| { - let focus = cx.focus_handle(); - window.focus(&focus, cx); - window.on_window_should_close(cx, { - let answer = answer.clone(); - move |_window, _cx| { - if let Some(done) = answer.borrow_mut().take() { - done(Outcome::Dismissed); - } - true - } - }); - cx.new(|_| Dialog { - request, - fields, - focused_field: 0, - focus, - answer, - }) - } - }, - ); - match opened { - Ok(handle) => CURRENT.with(|current| *current.borrow_mut() = Some(handle)), - Err(_) => { - if let Some(done) = answer.borrow_mut().take() { - done(Outcome::Dismissed); - } - } - } -} - -/// The dialog on screen: its title, button labels and text field values. -#[cfg(feature = "test-driver")] -pub fn describe(cx: &mut App) -> Option { - let handle = CURRENT.with(|current| *current.borrow())?; - handle - .read_with(cx, |dialog, _| { - serde_json::json!({ - "title": dialog.request.title, - "buttons": dialog.request.buttons.iter().map(|(_, label)| label.clone()).collect::>(), - "fields": dialog.fields.iter().map(|field| field.value.clone()).collect::>(), - }) - }) - .ok() -} - -/// Presses Escape in the dialog. -#[cfg(feature = "test-driver")] -pub fn press_escape(cx: &mut App) -> bool { - let Some(handle) = CURRENT.with(|current| *current.borrow()) else { - return false; - }; - handle - .update(cx, |dialog, window, _cx| dialog.escape(window)) - .is_ok() -} - -/// Types into the dialog's fields and presses a button. -#[cfg(feature = "test-driver")] -pub fn respond(cx: &mut App, button: usize, texts: &[String]) -> bool { - let Some(handle) = CURRENT.with(|current| *current.borrow()) else { - return false; - }; - handle - .update(cx, |dialog, window, _cx| { - if button >= dialog.request.buttons.len() { - return false; - } - for (field, text) in dialog.fields.iter_mut().zip(texts) { - field.value = text.clone(); - } - dialog.press(button, window); - true - }) - .unwrap_or(false) -} - -impl Dialog { - fn finish(&mut self, outcome: Outcome, window: &mut Window) { - CURRENT.with(|current| *current.borrow_mut() = None); - if let Some(done) = self.answer.borrow_mut().take() { - done(outcome); - } - window.remove_window(); - } - - fn escape(&mut self, window: &mut Window) { - if let Some(cancel) = self.request.cancel { - self.press(cancel, window); - } else if self.request.cancelable { - self.finish(Outcome::Dismissed, window); - } - } - - fn press(&mut self, position: usize, window: &mut Window) { - let text = match self.request.input { - Input::None => String::new(), - Input::Plain | Input::Secure => self.fields[0].value.clone(), - // The same shape the native sheet answers with. - Input::Login => serde_json::json!({ - "login": self.fields[0].value, - "password": self.fields[1].value, - }) - .to_string(), - }; - self.finish(Outcome::Button { position, text }, window); - } - - fn key(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context) { - let keystroke = &event.keystroke; - match keystroke.key.as_str() { - "escape" => { - self.escape(window); - return; - } - "enter" => { - let position = self - .request - .preferred - .unwrap_or(self.request.buttons.len().saturating_sub(1)); - self.press(position, window); - return; - } - "tab" if !self.fields.is_empty() => { - self.focused_field = (self.focused_field + 1) % self.fields.len(); - } - "backspace" => { - if let Some(field) = self.fields.get_mut(self.focused_field) { - field.value.pop(); - } - } - "v" if keystroke.modifiers.secondary(cx) => { - if let (Some(field), Some(text)) = ( - self.fields.get_mut(self.focused_field), - cx.read_from_clipboard().and_then(|item| item.text()), - ) { - field.value.push_str(&text.replace('\n', " ")); - } - } - _ => { - if keystroke.modifiers.control || keystroke.modifiers.platform { - return; - } - if let (Some(field), Some(text)) = - (self.fields.get_mut(self.focused_field), &keystroke.key_char) - { - field.value.push_str(text); - } - } - } - cx.notify(); - } -} - -impl Focusable for Dialog { - fn focus_handle(&self, _cx: &App) -> FocusHandle { - self.focus.clone() - } -} - -impl Render for Dialog { - fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let dark = self.request.dark.unwrap_or(false); - let (background, foreground, muted, field_background) = if dark { - (0x2b2b2b, 0xf2f2f2, 0xa0a0a0, 0x1e1e1e) - } else { - (0xf6f6f6, 0x1c1c1e, 0x6e6e73, 0xffffff) - }; - let fields: Vec<_> = self - .fields - .iter() - .enumerate() - .map(|(index, field)| { - let shown = if field.secure { - "•".repeat(field.value.chars().count()) - } else { - field.value.clone() - }; - let focused = index == self.focused_field; - div() - .id(SharedString::from(format!("alert-field-{index}"))) - .h(px(28.0)) - .px_2() - .flex() - .items_center() - .rounded(px(5.0)) - .bg(rgb(field_background)) - .border_1() - .border_color(rgb(if focused { 0x0a84ff } else { 0xc7c7cc })) - .on_mouse_down( - MouseButton::Left, - cx.listener(move |this, _event, _window, cx| { - this.focused_field = index; - cx.notify(); - }), - ) - .child(if shown.is_empty() { - div() - .text_color(rgb(muted)) - .child(field.placeholder.to_string()) - } else { - div().child(shown) - }) - }) - .collect(); - let buttons: Vec<_> = self - .request - .buttons - .iter() - .enumerate() - .map(|(position, (_, label))| { - let preferred = self.request.preferred == Some(position) - || (self.request.preferred.is_none() - && position + 1 == self.request.buttons.len()); - let destructive = self.request.destructive == Some(position); - div() - .id(SharedString::from(format!("alert-button-{position}"))) - .h(px(28.0)) - .px_3() - .flex() - .items_center() - .rounded(px(5.0)) - .cursor_pointer() - .when(preferred, |button| { - button.bg(rgb(0x0a84ff)).text_color(rgb(0xffffff)) - }) - .when(!preferred, |button| { - button - .bg(rgb(field_background)) - .border_1() - .border_color(rgb(0xc7c7cc)) - .text_color(rgb(if destructive { 0xff3b30 } else { foreground })) - }) - .on_mouse_down( - MouseButton::Left, - cx.listener(move |this, _event, window, _cx| { - this.press(position, window); - }), - ) - .child(label.clone()) - }) - .collect(); - div() - .id("alert-dialog") - .track_focus(&self.focus) - .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| { - this.key(event, window, cx); - })) - .size_full() - .p_4() - .flex() - .flex_col() - .gap_3() - .bg(rgb(background)) - .text_color(rgb(foreground)) - .text_size(px(13.0)) - .child( - div() - .font_weight(gpui::FontWeight::BOLD) - .text_size(px(15.0)) - .child(self.request.title.clone()), - ) - .when_some(self.request.message.clone(), |dialog, message| { - dialog.child(div().text_color(rgb(muted)).child(message)) - }) - .children(fields) - .child( - div() - .flex() - .flex_row() - .justify_end() - .gap_2() - .children(buttons), - ) - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/alert/mac.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/alert/mac.rs deleted file mode 100644 index b96fb9e0f1..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/alert/mac.rs +++ /dev/null @@ -1,285 +0,0 @@ -//! `NSAlert` shown as a sheet, with the options and text fields GPUI's prompt -//! has no room for. - -use block::ConcreteBlock; -use cocoa::base::{id, nil, YES}; -use cocoa::foundation::{NSPoint, NSRect, NSSize, NSString}; -use objc::{class, msg_send, sel, sel_impl}; -use std::cell::RefCell; - -use super::{Input, Outcome, Request}; - -const FIRST_BUTTON_RETURN: isize = 1000; -const ESCAPE_KEY_CODE: u16 = 53; -const KEY_DOWN_MASK: u64 = 1 << 10; -const FIELD_WIDTH: f64 = 260.0; -const FIELD_HEIGHT: f64 = 24.0; - -unsafe fn ns(text: &str) -> id { - NSString::alloc(nil).init_str(text) -} - -unsafe fn text_field(secure: bool, placeholder: &str, value: &str, y: f64) -> id { - let class = if secure { - class!(NSSecureTextField) - } else { - class!(NSTextField) - }; - let frame = NSRect::new(NSPoint::new(0.0, y), NSSize::new(FIELD_WIDTH, FIELD_HEIGHT)); - let field: id = msg_send![class, alloc]; - let field: id = msg_send![field, initWithFrame: frame]; - let _: () = msg_send![field, setPlaceholderString: ns(placeholder)]; - let _: () = msg_send![field, setStringValue: ns(value)]; - field -} - -unsafe fn string_of(field: id) -> String { - let value: id = msg_send![field, stringValue]; - let bytes: *const std::os::raw::c_char = msg_send![value, UTF8String]; - if bytes.is_null() { - return String::new(); - } - std::ffi::CStr::from_ptr(bytes) - .to_string_lossy() - .into_owned() -} - -struct Pending { - alert: id, - window: id, - buttons: Vec, - fields: Vec, -} - -thread_local! { - static CURRENT: RefCell> = const { RefCell::new(None) }; -} - -/// The sheet on screen: its title, button labels and text field values. -#[cfg(feature = "test-driver")] -pub fn describe() -> Option { - CURRENT.with(|current| { - let current = current.borrow(); - let pending = current.as_ref()?; - // SAFETY: main thread, and the sheet is alive while it is in `CURRENT`. - unsafe { - let title: id = msg_send![pending.alert, messageText]; - let bytes: *const std::os::raw::c_char = msg_send![title, UTF8String]; - let title = std::ffi::CStr::from_ptr(bytes) - .to_string_lossy() - .into_owned(); - let fields: Vec = pending.fields.iter().map(|f| string_of(*f)).collect(); - Some(serde_json::json!({ - "title": title, - "buttons": pending.buttons, - "fields": fields, - })) - } - }) -} - -/// Types into the sheet's fields and presses a button. -#[cfg(feature = "test-driver")] -pub fn respond(button: usize, texts: &[String]) -> bool { - // The press completes the sheet, which clears `CURRENT`: take what is - // needed out first so nothing is borrowed while it runs. - let Some((alert, fields)) = CURRENT.with(|current| { - current - .borrow() - .as_ref() - .map(|pending| (pending.alert, pending.fields.clone())) - }) else { - return false; - }; - // SAFETY: main thread, and the sheet is alive until its completion runs. - unsafe { - for (field, text) in fields.iter().zip(texts) { - let _: () = msg_send![*field, setStringValue: ns(text)]; - } - let buttons: id = msg_send![alert, buttons]; - let count: usize = msg_send![buttons, count]; - if button >= count { - return false; - } - let target: id = msg_send![buttons, objectAtIndex: button]; - let _: () = msg_send![target, performClick: nil]; - } - true -} - -/// Sends an Escape key press to the sheet. -#[cfg(feature = "test-driver")] -pub fn press_escape() -> bool { - let Some(window) = CURRENT.with(|current| current.borrow().as_ref().map(|p| p.window)) else { - return false; - }; - { - // SAFETY: main thread, and the sheet is alive until its completion runs. - unsafe { - let number: isize = msg_send![window, windowNumber]; - let escape = ns("\u{1b}"); - let event: id = msg_send![ - class!(NSEvent), - keyEventWithType: 10usize - location: NSPoint::new(0.0, 0.0) - modifierFlags: 0usize - timestamp: 0.0f64 - windowNumber: number - context: nil - characters: escape - charactersIgnoringModifiers: escape - isARepeat: false - keyCode: ESCAPE_KEY_CODE - ]; - let app: id = msg_send![class!(NSApplication), sharedApplication]; - let _: () = msg_send![app, sendEvent: event]; - } - true - } -} - -/// Shows `request` as a sheet on `window`; `done` runs once, on the main thread. -pub fn present(window: &gpui::Window, request: Request, done: Box) { - let Ok(parent) = crate::desktop::platform_window::ns_window(window) else { - done(Outcome::Dismissed); - return; - }; - // SAFETY: AppKit is only messaged from the main thread, where GPUI runs this. - unsafe { - let alert: id = msg_send![class!(NSAlert), new]; - let _: () = msg_send![alert, setMessageText: ns(&request.title)]; - if let Some(message) = &request.message { - let _: () = msg_send![alert, setInformativeText: ns(message)]; - } - for (position, (_, label)) in request.buttons.iter().enumerate() { - let button: id = msg_send![alert, addButtonWithTitle: ns(label)]; - let key = if request.cancel == Some(position) { - "\u{1b}" - } else if request.preferred == Some(position) { - "\r" - } else if request.preferred.is_some() { - "" - } else { - continue; - }; - let _: () = msg_send![button, setKeyEquivalent: ns(key)]; - if request.destructive == Some(position) { - let responds: bool = - msg_send![button, respondsToSelector: sel!(setHasDestructiveAction:)]; - if responds { - let _: () = msg_send![button, setHasDestructiveAction: YES]; - } - } - } - if let (Some(position), true) = (request.destructive, request.cancel != request.destructive) - { - let buttons: id = msg_send![alert, buttons]; - let button: id = msg_send![buttons, objectAtIndex: position]; - let responds: bool = - msg_send![button, respondsToSelector: sel!(setHasDestructiveAction:)]; - if responds { - let _: () = msg_send![button, setHasDestructiveAction: YES]; - } - } - let alert_window: id = msg_send![alert, window]; - if let Some(dark) = request.dark { - let name = if dark { - "NSAppearanceNameDarkAqua" - } else { - "NSAppearanceNameAqua" - }; - let appearance: id = msg_send![class!(NSAppearance), appearanceNamed: ns(name)]; - let _: () = msg_send![alert_window, setAppearance: appearance]; - } - - let fields: Vec = match request.input { - Input::None => Vec::new(), - Input::Plain => vec![text_field(false, "", &request.default_value, 0.0)], - Input::Secure => vec![text_field(true, "", &request.default_value, 0.0)], - Input::Login => vec![ - text_field(false, "Login", &request.default_value, FIELD_HEIGHT + 8.0), - text_field(true, "Password", "", 0.0), - ], - }; - if !fields.is_empty() { - let height = FIELD_HEIGHT * fields.len() as f64 + 8.0 * (fields.len() - 1) as f64; - let frame = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(FIELD_WIDTH, height)); - let container: id = msg_send![class!(NSView), alloc]; - let container: id = msg_send![container, initWithFrame: frame]; - for field in &fields { - let _: () = msg_send![container, addSubview: *field]; - } - let _: () = msg_send![alert, setAccessoryView: container]; - let _: () = msg_send![alert, layout]; - let _: () = msg_send![alert_window, setInitialFirstResponder: fields[0]]; - } - - // A cancelable alert with no cancel button still has to close on Escape. - let monitor: RefCell = RefCell::new(nil); - if request.cancelable && request.cancel.is_none() { - let handler = ConcreteBlock::new(move |event: id| -> id { - let code: u16 = msg_send![event, keyCode]; - if code == ESCAPE_KEY_CODE { - let _: () = msg_send![parent, endSheet: alert_window returnCode: 0isize]; - return nil; - } - event - }) - .copy(); - *monitor.borrow_mut() = msg_send![ - class!(NSEvent), - addLocalMonitorForEventsMatchingMask: KEY_DOWN_MASK - handler: &*handler - ]; - } - - let monitor = std::rc::Rc::new(monitor); - let done = RefCell::new(Some(done)); - let keys = request.buttons.len(); - let fields_for_result = fields.clone(); - let input = request.input; - let completion = ConcreteBlock::new(move |code: isize| { - CURRENT.with(|current| current.borrow_mut().take()); - let existing = *monitor.borrow(); - if existing != nil { - let _: () = msg_send![class!(NSEvent), removeMonitor: existing]; - } - let outcome = match code - FIRST_BUTTON_RETURN { - position if (0..keys as isize).contains(&position) => Outcome::Button { - position: position as usize, - text: match input { - Input::None => String::new(), - Input::Plain | Input::Secure => string_of(fields_for_result[0]), - Input::Login => serde_json::json!({ - "login": string_of(fields_for_result[0]), - "password": string_of(fields_for_result[1]), - }) - .to_string(), - }, - }, - _ => Outcome::Dismissed, - }; - if let Some(done) = done.borrow_mut().take() { - done(outcome); - } - }) - .copy(); - CURRENT.with(|current| { - *current.borrow_mut() = Some(Pending { - alert, - window: alert_window, - buttons: request - .buttons - .iter() - .map(|(_, label)| label.clone()) - .collect(), - fields: fields.clone(), - }); - }); - let _: () = msg_send![ - alert, - beginSheetModalForWindow: parent - completionHandler: &*completion - ]; - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/alert/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/alert/mod.rs deleted file mode 100644 index 5296a4d462..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/alert/mod.rs +++ /dev/null @@ -1,165 +0,0 @@ -use gpui::{App, AppContext}; -use rn_gpui_module::{ModuleThread, Value}; - -use crate::builtins::rn_gpui_specs::{ - AlertArgs, NativeGpuiAlertManagerEvents, NativeGpuiAlertManagerSpec, -}; - -pub(crate) mod dialog; -#[cfg(target_os = "macos")] -pub(crate) mod mac; - -struct AlertManagerModule; - -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum Input { - None, - Plain, - Secure, - Login, -} - -/// What a dialog was asked to show. -pub(crate) struct Request { - pub title: String, - pub message: Option, - /// `(key, label)` for each button, in display order. - pub buttons: Vec<(String, String)>, - pub cancel: Option, - pub destructive: Option, - pub preferred: Option, - pub cancelable: bool, - pub input: Input, - pub default_value: String, - pub dark: Option, -} - -pub(crate) enum Outcome { - Button { position: usize, text: String }, - Dismissed, -} - -fn buttons_of(buttons: Option>) -> Vec<(String, String)> { - let Some(buttons) = buttons else { - return Vec::new(); - }; - let mut labelled: Vec<(usize, String, String)> = buttons - .into_iter() - .enumerate() - .filter_map(|(position, button)| match button { - Value::String(text) => Some((position, position.to_string(), text)), - Value::Object(fields) => fields.iter().find_map(|(key, value)| match value { - Value::String(text) => { - Some((key.parse().unwrap_or(position), key.clone(), text.clone())) - } - _ => None, - }), - _ => None, - }) - .collect(); - labelled.sort_by_key(|(order, _, _)| *order); - labelled - .into_iter() - .map(|(_, key, text)| (key, text)) - .collect() -} - -fn position_of(buttons: &[(String, String)], key: Option<&String>) -> Option { - let key = key?; - buttons.iter().position(|(candidate, _)| candidate == key) -} - -fn input_of(kind: Option<&str>) -> Input { - match kind { - Some("plain-text") => Input::Plain, - Some("secure-text") => Input::Secure, - Some("login-password") => Input::Login, - _ => Input::None, - } -} - -impl NativeGpuiAlertManagerSpec for AlertManagerModule { - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(_events: NativeGpuiAlertManagerEvents) -> Self { - Self - } - - fn alert_with_args(&self, args: AlertArgs, callback: Box) { - let mut buttons = buttons_of(args.buttons); - if buttons.is_empty() { - buttons.push(("0".to_string(), "OK".to_string())); - } - let request = Request { - title: args.title.unwrap_or_default(), - message: args.message.filter(|message| !message.is_empty()), - cancel: position_of(&buttons, args.cancel_button_key.as_ref()), - destructive: position_of(&buttons, args.destructive_button_key.as_ref()), - preferred: position_of(&buttons, args.preferred_button_key.as_ref()), - cancelable: args.cancelable.unwrap_or(false), - input: input_of(args.r#type.as_deref()), - default_value: args.default_value.unwrap_or_default(), - dark: match args.user_interface_style.as_deref() { - Some("dark") => Some(true), - Some("light") => Some(false), - _ => None, - }, - buttons, - }; - crate::desktop::post_to_main(Box::new(move |cx: &mut App| { - let store = match cx.try_global::() { - Some(store) => store.0.clone(), - None => { - callback(-1.0, String::new()); - return; - } - }; - let mut window = None; - store.update(cx, |store, _cx| window = Some(store.window)); - let Some(window) = window else { - callback(-1.0, String::new()); - return; - }; - let keys: Vec = request.buttons.iter().map(|(key, _)| key.clone()).collect(); - let answer = move |outcome: Outcome| match outcome { - Outcome::Button { position, text } => { - let id = keys - .get(position) - .and_then(|key| key.parse::().ok()) - .unwrap_or(position as f64); - callback(id, text) - } - Outcome::Dismissed => callback(-1.0, String::new()), - }; - #[cfg(target_os = "macos")] - if std::env::var_os("RN_GPUI_ALERT_DIALOG").is_some() { - dialog::present(cx, request, Box::new(answer)); - } else { - let mut answer = Some(answer); - let shown = cx.update_window(window, |_root, window, _cx| { - mac::present( - window, - request, - Box::new(answer.take().expect("answer taken once")), - ); - }); - if shown.is_err() { - if let Some(answer) = answer { - answer(Outcome::Dismissed); - } - } - } - #[cfg(not(target_os = "macos"))] - { - let _ = window; - dialog::present(cx, request, Box::new(answer)); - } - })); - } -} - -pub fn register() { - rn_gpui_module::register( - crate::builtins::rn_gpui_specs::native_gpui_alert_manager_module::(), - ); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/app/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/app/mod.rs deleted file mode 100644 index e818f70d74..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/app/mod.rs +++ /dev/null @@ -1,83 +0,0 @@ -//! `App`: the running application as a whole: its launch arguments, quitting -//! and relaunching. - -use rn_gpui_module::{ModuleError, ModuleThread}; - -use crate::builtins::main_thread::on_main; -use crate::builtins::rn_gpui_specs::{NativeGpuiAppEvents, NativeGpuiAppSpec}; - -struct AppModule; - -#[cfg(target_os = "macos")] -fn beep() { - #[link(name = "AppKit", kind = "framework")] - // SAFETY: `NSBeep` takes no arguments and may be called from any thread. - unsafe extern "C" { - fn NSBeep(); - } - // SAFETY: see the declaration. - unsafe { NSBeep() } -} - -#[cfg(target_os = "windows")] -fn beep() { - #[link(name = "user32")] - // SAFETY: `MessageBeep` takes a sound type and may be called from any thread. - unsafe extern "system" { - fn MessageBeep(kind: u32) -> i32; - } - // SAFETY: see the declaration; `u32::MAX` is the default beep. - unsafe { - MessageBeep(u32::MAX); - } -} - -#[cfg(not(any(target_os = "macos", target_os = "windows")))] -fn beep() { - use std::io::Write; - let _ = std::io::stderr().write_all(b"\x07"); -} - -impl NativeGpuiAppSpec for AppModule { - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(_events: NativeGpuiAppEvents) -> Self { - Self - } - - fn launch_args(&self) -> Result, ModuleError> { - Ok(std::env::args().skip(1).collect()) - } - - async fn quit(&self) -> Result<(), ModuleError> { - on_main(|cx| cx.quit()).await - } - - async fn exit(&self, code: f64) -> Result<(), ModuleError> { - std::process::exit(code as i32) - } - - async fn relaunch(&self) -> Result<(), ModuleError> { - let executable = std::env::current_exe() - .map_err(|error| ModuleError::new(format!("the executable is unknown: {error}")))?; - std::process::Command::new(executable) - .args(std::env::args().skip(1)) - .spawn() - .map_err(|error| ModuleError::new(format!("the app could not be started: {error}")))?; - on_main(|cx| cx.quit()).await - } - - async fn beep(&self) -> Result<(), ModuleError> { - on_main(|_| beep()).await - } - - fn add_listener(&self, _event_name: String) {} - - fn remove_listeners(&self, _count: f64) {} -} - -pub fn register() { - rn_gpui_module::register(crate::builtins::rn_gpui_specs::native_gpui_app_module::< - AppModule, - >()); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/app_menu/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/app_menu/mod.rs deleted file mode 100644 index 5edba6e178..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/app_menu/mod.rs +++ /dev/null @@ -1,200 +0,0 @@ -use rn_gpui_module::{FromValue, IntoValue, ModuleError, ModuleThread, Path, Value}; - -use crate::builtins::main_thread::on_main; -use crate::builtins::rn_gpui_specs::{ - MenuDescription, MenuItemPatch, NativeGpuiAppMenuEvents, NativeGpuiAppMenuSpec, -}; -use crate::desktop::app_menu; -use crate::desktop::errors::{DesktopError, DesktopResult}; -use crate::desktop::windows::MAIN_WINDOW_KEY; - -const MODULE: &str = "GpuiAppMenu"; - -struct AppMenuModule; - -fn value_json(value: Value) -> serde_json::Value { - match value { - Value::Null | Value::Callback(_) => serde_json::Value::Null, - Value::Bool(flag) => serde_json::Value::Bool(flag), - Value::Number(number) => serde_json::Number::from_f64(number) - .map(serde_json::Value::Number) - .unwrap_or(serde_json::Value::Null), - Value::String(text) => serde_json::Value::String(text), - Value::Array(items) => { - serde_json::Value::Array(items.into_iter().map(value_json).collect()) - } - Value::Object(fields) => serde_json::Value::Object( - fields - .into_iter() - .map(|(key, item)| (key, value_json(item))) - .collect(), - ), - Value::Buffer(bytes) => serde_json::Value::Array( - bytes - .into_iter() - .map(|byte| serde_json::Value::Number(byte.into())) - .collect(), - ), - } -} - -fn json_value(value: &serde_json::Value) -> Value { - match value { - serde_json::Value::Null => Value::Null, - serde_json::Value::Bool(flag) => Value::Bool(*flag), - serde_json::Value::Number(number) => { - number.as_f64().map(Value::Number).unwrap_or(Value::Null) - } - serde_json::Value::String(text) => Value::String(text.clone()), - serde_json::Value::Array(items) => Value::Array(items.iter().map(json_value).collect()), - serde_json::Value::Object(fields) => Value::Object( - fields - .iter() - .map(|(key, item)| (key.clone(), json_value(item))) - .collect(), - ), - } -} - -fn json_items(items: Option>) -> Option { - items.map(|items| serde_json::Value::Array(items.into_iter().map(value_json).collect())) -} - -fn module_error(error: DesktopError) -> ModuleError { - ModuleError::new(error.message) -} - -fn typed(method: &'static str, result: DesktopResult) -> Result { - let mut path = Path::result(MODULE, method); - let value = json_value(&result.map_err(module_error)?); - T::from_value(value, &mut path).map_err(|error| ModuleError::new(error.message)) -} - -impl NativeGpuiAppMenuSpec for AppMenuModule { - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(_events: NativeGpuiAppMenuEvents) -> Self { - Self - } - - async fn menu_set_application_menu( - &self, - items: Option>, - ) -> Result<(), ModuleError> { - let items = json_items(items); - if let Some(items) = &items { - crate::desktop::icon::preload_menu(items).await; - } - on_main(move |cx| { - app_menu::set_application_menu(cx, items.as_ref())?; - Ok(serde_json::Value::Null) - }) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn menu_set_dock_menu(&self, items: Option>) -> Result<(), ModuleError> { - let items = json_items(items); - if let Some(items) = &items { - crate::desktop::icon::preload_menu(items).await; - } - on_main(move |cx| { - app_menu::set_dock_menu(cx, items.as_ref())?; - Ok(serde_json::Value::Null) - }) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn menu_update(&self, id: String, patch: MenuItemPatch) -> Result<(), ModuleError> { - on_main(move |cx| { - app_menu::update_item(cx, &id, &value_json(patch.into_value()))?; - Ok(serde_json::Value::Null) - }) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn menu_set_menu_bar_visible( - &self, - visible: bool, - window_id: Option, - ) -> Result<(), ModuleError> { - let window_id = window_id.map(|id| id as u32).unwrap_or(MAIN_WINDOW_KEY); - on_main(move |cx| { - app_menu::set_menu_bar_visible(cx, window_id, visible)?; - Ok(serde_json::Value::Null) - }) - .await? - .map(|_| ()) - .map_err(module_error) - } - - #[allow(clippy::too_many_arguments)] - async fn menu_set_menu_bar_slot( - &self, - x: f64, - y: f64, - width: f64, - height: f64, - foreground: f64, - hover: f64, - window_id: Option, - ) -> Result<(), ModuleError> { - let window_id = window_id.map(|id| id as u32).unwrap_or(MAIN_WINDOW_KEY); - let slot = crate::desktop::gpui_menu::MenuBarSlot { - x: x as f32, - y: y as f32, - width: width as f32, - height: height as f32, - foreground: foreground as u32, - hover: hover as u32, - }; - on_main(move |cx| { - app_menu::set_menu_bar_slot(cx, window_id, Some(slot))?; - Ok(serde_json::Value::Null) - }) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn menu_clear_menu_bar_slot(&self, window_id: Option) -> Result<(), ModuleError> { - let window_id = window_id.map(|id| id as u32).unwrap_or(MAIN_WINDOW_KEY); - on_main(move |cx| { - app_menu::set_menu_bar_slot(cx, window_id, None)?; - Ok(serde_json::Value::Null) - }) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn menu_perform_role(&self, role: String) -> Result<(), ModuleError> { - on_main(move |cx| { - app_menu::perform_role(cx, &role)?; - Ok(serde_json::Value::Null) - }) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn menu_get(&self) -> Result { - let result = on_main(|cx| -> DesktopResult { Ok(app_menu::menu_json(cx)) }).await?; - typed("menuGet", result) - } - - fn add_listener(&self, _event_name: String) {} - - fn remove_listeners(&self, _count: f64) {} -} - -pub fn register() { - rn_gpui_module::register( - crate::builtins::rn_gpui_specs::native_gpui_app_menu_module::(), - ); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/clipboard/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/clipboard/mod.rs deleted file mode 100644 index 114dd7873c..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/clipboard/mod.rs +++ /dev/null @@ -1,41 +0,0 @@ -use rn_gpui_module::{ModuleError, ModuleThread}; - -use crate::builtins::main_thread::on_main; -use crate::builtins::rn_gpui_specs::{ - GetConstantsResult, NativeGpuiClipboardEvents, NativeGpuiClipboardSpec, -}; - -struct ClipboardModule; - -impl NativeGpuiClipboardSpec for ClipboardModule { - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(_events: NativeGpuiClipboardEvents) -> Self { - Self - } - - fn get_constants(&self) -> Result { - Ok(GetConstantsResult {}) - } - - async fn get_string(&self) -> Result { - on_main(|cx| { - cx.read_from_clipboard() - .and_then(|item| item.text()) - .unwrap_or_default() - }) - .await - } - - fn set_string(&self, content: String) { - crate::desktop::post_to_main(Box::new(move |cx| { - cx.write_to_clipboard(gpui::ClipboardItem::new_string(content)); - })); - } -} - -pub fn register() { - rn_gpui_module::register( - crate::builtins::rn_gpui_specs::native_gpui_clipboard_module::(), - ); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/context_menu/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/context_menu/mod.rs deleted file mode 100644 index c6e2af9b07..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/context_menu/mod.rs +++ /dev/null @@ -1,113 +0,0 @@ -use futures::channel::oneshot; -use gpui::App; -use rn_gpui_module::{FromValue, ModuleError, ModuleThread, Path, Value}; - -use crate::builtins::rn_gpui_specs::{ - ContextMenuOptions, ContextMenuSelection, NativeGpuiContextMenuEvents, - NativeGpuiContextMenuSpec, -}; -use crate::desktop::context_menu; -use crate::desktop::errors::DesktopError; - -const MODULE: &str = "GpuiContextMenu"; - -struct ContextMenuModule; - -fn window_key(window_id: i32) -> u32 { - window_id as u32 -} - -fn to_json(value: Value) -> serde_json::Value { - match value { - Value::Null | Value::Callback(_) => serde_json::Value::Null, - Value::Bool(flag) => serde_json::Value::Bool(flag), - Value::Number(number) => serde_json::Number::from_f64(number) - .map(serde_json::Value::Number) - .unwrap_or(serde_json::Value::Null), - Value::String(text) => serde_json::Value::String(text), - Value::Array(items) => serde_json::Value::Array(items.into_iter().map(to_json).collect()), - Value::Object(fields) => serde_json::Value::Object( - fields - .into_iter() - .map(|(key, item)| (key, to_json(item))) - .collect(), - ), - Value::Buffer(bytes) => serde_json::Value::Array( - bytes - .into_iter() - .map(|byte| serde_json::Value::Number(byte.into())) - .collect(), - ), - } -} - -fn from_json(value: &serde_json::Value) -> Value { - match value { - serde_json::Value::Null => Value::Null, - serde_json::Value::Bool(flag) => Value::Bool(*flag), - serde_json::Value::Number(number) => { - number.as_f64().map(Value::Number).unwrap_or(Value::Null) - } - serde_json::Value::String(text) => Value::String(text.clone()), - serde_json::Value::Array(items) => Value::Array(items.iter().map(from_json).collect()), - serde_json::Value::Object(fields) => Value::Object( - fields - .iter() - .map(|(key, item)| (key.clone(), from_json(item))) - .collect(), - ), - } -} - -fn module_error(error: DesktopError) -> ModuleError { - ModuleError::new(error.message) -} - -impl NativeGpuiContextMenuSpec for ContextMenuModule { - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(_events: NativeGpuiContextMenuEvents) -> Self { - Self - } - - async fn context_menu_show( - &self, - items: Vec, - options: ContextMenuOptions, - ) -> Result { - let items = serde_json::Value::Array(items.into_iter().map(to_json).collect()); - crate::desktop::icon::preload_menu(&items).await; - let (sender, receiver) = oneshot::channel(); - crate::desktop::post_to_main(Box::new(move |cx: &mut App| { - let responder = context_menu::Responder::desktop(sender); - let rejected = responder.clone(); - if let Err(error) = context_menu::show( - cx, - items, - options.x, - options.y, - options.window_id.map(window_key), - responder, - ) { - rejected.reject(error); - } - })); - let result = receiver - .await - .map_err(|_| ModuleError::new("the command was dismissed"))? - .map_err(module_error)?; - let mut path = Path::result(MODULE, "contextMenuShow"); - ContextMenuSelection::from_value(from_json(&result), &mut path) - .map_err(|error| ModuleError::new(error.message)) - } - - fn add_listener(&self, _event_name: String) {} - - fn remove_listeners(&self, _count: f64) {} -} - -pub fn register() { - rn_gpui_module::register( - crate::builtins::rn_gpui_specs::native_gpui_context_menu_module::(), - ); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/context_menu_view/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/context_menu_view/mod.rs deleted file mode 100644 index aaab52be43..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/context_menu_view/mod.rs +++ /dev/null @@ -1,285 +0,0 @@ -//! A view whose context menu opens natively. -//! -//! A right click (or Ctrl + click on macOS, or the Menu key on Windows and -//! Linux) opens the view's `items` straight from native, so the menu appears even -//! while JS is busy. JS only hears about the item that was chosen, through -//! `onMenuSelect`; the menu itself was never described to JS at the moment it -//! opened. -//! -//! The component lays out like a `View` — core paints the element, the style and -//! the children — so this renderer only claims the press and presents the menu. - -use std::sync::Arc; - -use gpui::{AnyElement, App, Window}; -use serde_json::Value; - -use crate::desktop::menu_model::{self, MenuModel}; -use crate::events::ContextMenuTriggerSource; -use crate::extensions::input::{ContextMenuTrigger, InputContext, InputSpec, Propagation}; -use crate::extensions::{register_component_renderer, ComponentNode, ComponentRenderer}; - -const OPEN_EVENT: &str = "topMenuOpen"; - -/// What a press on the view should do, decided from the parsed props alone. -/// -/// Split out so the three outcomes — show a menu, stay out of the way, or report -/// a model that cannot be read — are testable without a window or a presenter. -enum MenuRequest { - /// No `items`, or the press is not this view's to take. - None, - Menu(MenuModel), - /// `items` was supposed to be a menu and is not one. - Invalid(crate::desktop::errors::DesktopError), -} - -/// Whether the press on this view belongs to its menu. -/// -/// A disabled view has nothing to open, and a `custom` presentation is drawn by -/// JS, so neither takes the press. -fn claims_press(props: &Value) -> bool { - if props - .get("disabled") - .and_then(Value::as_bool) - .unwrap_or(false) - { - return false; - } - // `custom` is drawn by JS, so the descending `View` opens it through - // `onContextMenu`, exactly as it did before this component existed. Claiming - // the press here would open a native menu over the React one. - match props.get("presentation").and_then(Value::as_str) { - Some("custom") => false, - _ => true, - } -} - -/// Whether the props carry something that could be a menu. -/// -/// An empty array is not one: `items` defaults to `[]` on the C++ side, and a -/// caller that filtered a dynamic menu down to nothing has no menu to show. Either -/// way the press belongs to whatever is behind the view, so this is not a menu -/// owner at all rather than an owner that shows nothing. -fn has_items(props: &Value) -> bool { - match props.get("items") { - None | Some(Value::Null) => false, - Some(Value::Array(items)) => !items.is_empty(), - // Not an array is a mistake worth reporting, so it still counts as "the - // caller meant to pass a menu"; `request` turns it into `Invalid`. - Some(_) => true, - } -} - -fn request(props: &Value) -> MenuRequest { - if !claims_press(props) || !has_items(props) { - return MenuRequest::None; - } - match menu_model::parse_menu(&props["items"]) { - Ok(model) => MenuRequest::Menu(model), - Err(error) => MenuRequest::Invalid(error), - } -} - -fn trigger_name(source: ContextMenuTriggerSource) -> &'static str { - match source { - ContextMenuTriggerSource::Mouse => "mouse", - ContextMenuTriggerSource::Keyboard => "keyboard", - } -} - -/// The `topMenuOpen` payload, in the shape `topContextMenu` uses. -/// -/// The two are the same press reported through different components, so a -/// handler written for `onContextMenu` keeps working when the wrapper switches -/// to the native path. -fn open_payload(trigger: &ContextMenuTrigger, window_id: u32) -> serde_json::Value { - let x = f32::from(trigger.position.x); - let y = f32::from(trigger.position.y); - serde_json::json!({ - "x": x, - "y": y, - // The menu is placed in window coordinates, which is also the page's - // here: the surface fills the window, and the top inset is part of the - // layer's own origin rather than something a handler would add back. - "pageX": x, - "pageY": y, - "windowId": window_id, - "button": trigger.button.number(), - "ctrlKey": trigger.modifiers.ctrl, - "shiftKey": trigger.modifiers.shift, - "altKey": trigger.modifiers.alt, - "metaKey": trigger.modifiers.meta, - "trigger": trigger_name(trigger.source), - }) -} - -struct ContextMenuViewRenderer; - -impl ComponentRenderer for ContextMenuViewRenderer { - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } - - fn input(&self, node: &ComponentNode) -> InputSpec { - if !claims_press(&node.props) || !has_items(&node.props) { - return InputSpec::default(); - } - crate::desktop::icon::prefetch_menu(&node.props["items"]); - InputSpec { - // No buttons: the right press is already reported by the node's own - // listener. This flag is what makes the press find this component as - // the menu's owner, and what keeps a parent `View`'s `onContextMenu` - // from also firing. - context_menu: true, - ..InputSpec::default() - } - } - - fn on_context_menu( - &self, - node: &ComponentNode, - trigger: &ContextMenuTrigger, - cx: &mut InputContext<'_>, - ) -> Propagation { - match request(&node.props) { - MenuRequest::None => Propagation::Continue, - MenuRequest::Invalid(error) => { - // A model JS built wrong is not a reason to swallow the press: an - // ancestor's menu can still be a real one. - log::warn!("[context-menu-view] ignoring unreadable items: {error}"); - Propagation::Continue - } - MenuRequest::Menu(model) => { - cx.show_context_menu(model, trigger.position); - // After the menu is up, so a handler that reads its own state - // sees it already open. The payload carries what `onContextMenu` - // reports, because the component keeps that prop working on this - // path and the native side is the only place these fields exist. - cx.dispatch_event(OPEN_EVENT, &open_payload(trigger, cx.window_id())); - // Only the innermost view opens, as native menus do. - Propagation::Stop - } - } - } -} - -pub fn register() { - register_component_renderer("DesktopContextMenuView", Arc::new(ContextMenuViewRenderer)); -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::desktop::menu_model::MenuNode; - use serde_json::json; - - fn props(value: Value) -> Arc { - Arc::new(value) - } - - fn node(value: Value) -> ComponentNode { - ComponentNode { - component: "DesktopContextMenuView".to_string(), - tag: 9, - frame: rn_gpui_sys::ffi::RectF { - x: 0.0, - y: 0.0, - w: 200.0, - h: 40.0, - }, - scale: (1.0, 1.0), - props: props(value), - parent: None, - children: Vec::new(), - } - } - - const ITEMS: &str = r#"[ - {"id": "open", "label": "Open"}, - {"type": "submenu", "label": "More", "items": [ - {"id": "nested", "label": "Nested"} - ]}, - {"type": "separator"}, - {"id": "pin", "label": "Pin", "checked": true} - ]"#; - - fn items() -> Value { - serde_json::from_str(ITEMS).expect("valid json") - } - - #[test] - fn items_become_the_same_model_a_js_menu_uses() { - let value = json!({"items": items()}); - let MenuRequest::Menu(model) = request(&value) else { - panic!("a readable menu"); - }; - assert_eq!(model.ids(), vec!["open", "nested", "pin"]); - assert!(matches!(model.items[1], MenuNode::Submenu(_))); - assert!(matches!(model.items[2], MenuNode::Separator)); - let MenuNode::Item(pin) = &model.items[3] else { - panic!("a leaf item"); - }; - assert!(pin.checked); - } - - #[test] - fn a_disabled_view_asks_for_nothing() { - let value = json!({"items": items(), "disabled": true}); - assert!(!claims_press(&value)); - assert!(matches!(request(&value), MenuRequest::None)); - // The spec is the other half: a disabled view must not become a menu - // owner, or the press would be claimed with nothing to show. - let spec = ContextMenuViewRenderer.input(&node(value)); - assert!(!spec.context_menu); - assert_eq!(spec, InputSpec::default()); - } - - #[test] - fn a_custom_presentation_is_left_to_js() { - let value = json!({"items": items(), "presentation": "custom"}); - assert!(!claims_press(&value)); - assert!(!ContextMenuViewRenderer.input(&node(value)).context_menu); - } - - #[test] - fn native_and_default_presentations_open_here() { - for presentation in [json!("default"), json!("native"), json!(null)] { - let value = json!({"items": items(), "presentation": presentation}); - assert!(claims_press(&value), "{presentation}"); - assert!(ContextMenuViewRenderer.input(&node(value)).context_menu); - } - } - - #[test] - fn items_that_are_not_a_menu_are_reported_rather_than_swallowed() { - // The shape a caller gets wrong most easily: an item with no label. - let value = json!({"items": [{"id": "a"}]}); - let MenuRequest::Invalid(error) = request(&value) else { - panic!("an unreadable model"); - }; - assert_eq!(error.code, crate::desktop::errors::codes::INVALID_ARGUMENT); - // Still an owner, so the hook runs and can log; the press is then passed - // on rather than stopped. - assert!(ContextMenuViewRenderer.input(&node(value)).context_menu); - } - - #[test] - fn no_items_is_simply_no_menu() { - assert!(matches!(request(&json!({})), MenuRequest::None)); - } - - #[test] - fn an_empty_menu_is_not_a_menu() { - // What the C++ side sends for `items` left out, and what a caller that - // filtered every entry out of a dynamic menu sends. Neither should claim - // the press and then show nothing. - assert!(matches!(request(&json!({"items": []})), MenuRequest::None)); - let spec = ContextMenuViewRenderer.input(&node(json!({"items": []}))); - assert!(!spec.context_menu); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/desktop_scroll_bar/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/desktop_scroll_bar/mod.rs deleted file mode 100644 index 2c3445aa46..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/desktop_scroll_bar/mod.rs +++ /dev/null @@ -1,30 +0,0 @@ -//! The scrollbar component. -//! -//! It paints nothing: the scroll view that contains it finds it while the store -//! refreshes the tree (`store::refresh_inherited_tree`) and draws its own bar -//! from these props. - -use std::sync::Arc; - -use gpui::{AnyElement, App, Window}; - -use crate::extensions::{register_component_renderer, ComponentNode, ComponentRenderer}; - -pub const COMPONENT: &str = "DesktopScrollBar"; - -struct ScrollBarRenderer; - -impl ComponentRenderer for ScrollBarRenderer { - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } -} - -pub fn register() { - register_component_renderer(COMPONENT, Arc::new(ScrollBarRenderer)); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/dev_menu/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/dev_menu/mod.rs deleted file mode 100644 index 18eae96190..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/dev_menu/mod.rs +++ /dev/null @@ -1,53 +0,0 @@ -use rn_gpui_module::ModuleThread; - -use crate::builtins::rn_gpui_specs::{NativeGpuiDevMenuEvents, NativeGpuiDevMenuSpec}; - -struct DevMenuModule; - -impl NativeGpuiDevMenuSpec for DevMenuModule { - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(_events: NativeGpuiDevMenuEvents) -> Self { - Self - } - - fn show(&self) { - if let Some(handler) = rn_gpui_sys::DEV_MENU_SHOW_HANDLER.get() { - handler(); - } - } - - fn reload(&self) { - if let Some(handler) = rn_gpui_sys::DEV_MENU_PERFORM_HANDLER.get() { - handler(crate::desktop::dev_menu::RELOAD.to_string()); - } - } - - fn set_profiling_enabled(&self, enabled: bool) { - dev_setting("profiling", enabled); - } - - fn set_hot_loading_enabled(&self, enabled: bool) { - dev_setting("hotLoading", enabled); - } - - fn toggle_element_inspector(&self) { - dev_setting("inspectorToggle", true); - } - - fn add_listener(&self, _event_name: String) {} - - fn remove_listeners(&self, _count: f64) {} -} - -fn dev_setting(name: &str, enabled: bool) { - if let Some(handler) = rn_gpui_sys::DEV_SETTING_HANDLER.get() { - handler(name.to_string(), enabled); - } -} - -pub fn register() { - rn_gpui_module::register( - crate::builtins::rn_gpui_specs::native_gpui_dev_menu_module::(), - ); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/i18n/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/i18n/mod.rs deleted file mode 100644 index b09c668590..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/i18n/mod.rs +++ /dev/null @@ -1,221 +0,0 @@ -//! `I18nManager`: the layout direction a surface starts with. -//! -//! The three flags live in a JSON file next to the window state and are read on -//! every use, so a change takes effect on the next load, as on iOS. - -use std::path::PathBuf; - -use rn_gpui_module::{ModuleError, ModuleThread}; - -use crate::builtins::rn_gpui_specs::{ - I18nManagerConstants, NativeGpuiI18nManagerEvents, NativeGpuiI18nManagerSpec, -}; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Settings { - pub allow_rtl: bool, - pub force_rtl: bool, - pub swap_left_and_right: bool, -} - -impl Default for Settings { - fn default() -> Self { - Self { - allow_rtl: true, - force_rtl: false, - swap_left_and_right: true, - } - } -} - -impl Settings { - fn from_json(text: &str) -> Self { - let mut settings = Self::default(); - let Ok(value) = serde_json::from_str::(text) else { - return settings; - }; - let flag = |key: &str, slot: &mut bool| { - if let Some(read) = value.get(key).and_then(serde_json::Value::as_bool) { - *slot = read; - } - }; - flag("allowRTL", &mut settings.allow_rtl); - flag("forceRTL", &mut settings.force_rtl); - flag("swapLeftAndRightInRTL", &mut settings.swap_left_and_right); - settings - } - - fn to_json(self) -> String { - serde_json::json!({ - "allowRTL": self.allow_rtl, - "forceRTL": self.force_rtl, - "swapLeftAndRightInRTL": self.swap_left_and_right, - }) - .to_string() - } - - /// Whether surfaces lay out right to left for a locale. - pub fn is_rtl(self, locale: &str) -> bool { - self.force_rtl || (self.allow_rtl && locale_is_rtl(locale)) - } -} - -/// Languages written right to left, by their primary subtag. -const RTL_LANGUAGES: &[&str] = &[ - "ar", "he", "iw", "fa", "ur", "ps", "sd", "ug", "yi", "dv", "ckb", -]; - -/// Scripts written right to left, by ISO 15924 code. -const RTL_SCRIPTS: &[&str] = &["Arab", "Hebr", "Thaa", "Syrc", "Nkoo"]; - -pub(crate) fn locale_is_rtl(locale: &str) -> bool { - let mut subtags = locale.split(['-', '_', '.', '@']); - let language = subtags.next().unwrap_or_default().to_ascii_lowercase(); - if let Some(script) = subtags.find(|subtag| subtag.len() == 4) { - return RTL_SCRIPTS - .iter() - .any(|rtl| rtl.eq_ignore_ascii_case(script)); - } - match language.as_str() { - // Kurdish is written in Arabic script only in its Sorani form. - "ku" => locale.to_ascii_lowercase().contains("arab"), - language => RTL_LANGUAGES.contains(&language), - } -} - -fn settings_path() -> PathBuf { - let app_id = crate::desktop::snapshot_app_id(); - let safe_id = crate::desktop::app_dir::safe_id(&app_id); - let path = crate::desktop::app_dir::app_dir().join(format!("{safe_id}-i18n.json")); - #[cfg(feature = "visual-capture")] - if let Some(window_state) = std::env::var_os("RN_GPUI_WINDOW_STATE") { - return PathBuf::from(window_state).with_extension("i18n.json"); - } - path -} - -fn load() -> Settings { - std::fs::read_to_string(settings_path()) - .map(|text| Settings::from_json(&text)) - .unwrap_or_default() -} - -fn update(change: impl FnOnce(&mut Settings)) { - if let Err(error) = try_update(change) { - log::warn!("I18nManager: could not save settings: {error}"); - } -} - -fn try_update(change: impl FnOnce(&mut Settings)) -> std::io::Result<()> { - let mut settings = load(); - change(&mut settings); - let path = settings_path(); - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent)?; - } - std::fs::write(&path, settings.to_json()) -} - -fn locale() -> String { - sys_locale::get_locale().unwrap_or_else(|| "en-US".to_string()) -} - -/// What a new surface's layout needs: right to left, and whether left and right -/// swap in that direction. -pub(crate) fn layout_direction() -> (bool, bool) { - let settings = load(); - let rtl = settings.is_rtl(&locale()); - RTL_ACTIVE.store(rtl, std::sync::atomic::Ordering::Relaxed); - (rtl, settings.swap_left_and_right) -} - -/// The direction the newest surface started with, for text alignment. -static RTL_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - -pub(crate) fn rtl_active() -> bool { - RTL_ACTIVE.load(std::sync::atomic::Ordering::Relaxed) -} - -struct I18nManagerModule; - -impl NativeGpuiI18nManagerSpec for I18nManagerModule { - const THREAD: ModuleThread = ModuleThread::Own; - - fn new(_events: NativeGpuiI18nManagerEvents) -> Self { - Self - } - - fn get_constants(&self) -> Result { - let (is_rtl, _) = layout_direction(); - let settings = load(); - let locale = locale(); - Ok(I18nManagerConstants { - is_rtl, - do_left_and_right_swap_in_rtl: settings.swap_left_and_right, - locale_identifier: locale, - }) - } - - fn allow_rtl(&self, allow_rtl: bool) { - update(|settings| settings.allow_rtl = allow_rtl) - } - - fn force_rtl(&self, force_rtl: bool) { - update(|settings| settings.force_rtl = force_rtl) - } - - fn swap_left_and_right_in_rtl(&self, swap_left_and_right: bool) { - update(|settings| settings.swap_left_and_right = swap_left_and_right) - } -} - -pub fn register() { - rn_gpui_module::register( - crate::builtins::rn_gpui_specs::native_gpui_i18n_manager_module::(), - ); - let _ = rn_gpui_sys::LAYOUT_DIRECTION_HANDLER.set(Box::new(layout_direction)); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn right_to_left_languages_and_scripts_are_recognised() { - for locale in [ - "ar", "ar-EG", "he_IL", "fa-IR", "ur-PK", "ps", "yi", "dv", "ckb-IQ", - ] { - assert!(locale_is_rtl(locale), "{locale}"); - } - for locale in ["en-US", "de", "ja-JP", "zh-Hans", "ku-Latn", "sr-Latn"] { - assert!(!locale_is_rtl(locale), "{locale}"); - } - assert!(locale_is_rtl("ku-Arab")); - assert!(locale_is_rtl("az-Arab")); - assert!(locale_is_rtl("en-Arab")); - } - - #[test] - fn force_overrides_the_locale_and_allow_gates_it() { - let mut settings = Settings::default(); - assert!(settings.is_rtl("ar")); - assert!(!settings.is_rtl("en")); - settings.force_rtl = true; - assert!(settings.is_rtl("en")); - settings.force_rtl = false; - settings.allow_rtl = false; - assert!(!settings.is_rtl("ar")); - } - - #[test] - fn settings_round_trip_and_ignore_garbage() { - let settings = Settings { - allow_rtl: false, - force_rtl: true, - swap_left_and_right: false, - }; - assert_eq!(Settings::from_json(&settings.to_json()), settings); - assert_eq!(Settings::from_json("not json"), Settings::default()); - assert_eq!(Settings::from_json("{\"forceRTL\":true}").force_rtl, true); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/image/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/image/mod.rs deleted file mode 100644 index 3617b39c5a..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/image/mod.rs +++ /dev/null @@ -1,141 +0,0 @@ -use gpui::{prelude::*, AnyElement, App, ObjectFit, StyledImage, Window}; -use serde_json::Value; - -use crate::extensions::{register_component_renderer, ComponentNode, ComponentRenderer}; - -mod processed; - -struct ImageRenderer; - -impl ComponentRenderer for ImageRenderer { - fn content( - &self, - node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - paint(&node.props, (node.frame.w, node.frame.h)) - } - - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } -} - -fn fit_for(resize_mode: Option<&str>) -> ObjectFit { - match resize_mode { - Some("contain") => ObjectFit::Contain, - Some("cover") => ObjectFit::Cover, - Some("center") | Some("none") => ObjectFit::ScaleDown, - _ => ObjectFit::Fill, - } -} - -fn plain(uri: &str) -> Option { - if let Some(data) = uri.strip_prefix("data:") { - crate::node_view::decode_data_image(data).map(|image| gpui::img(std::sync::Arc::new(image))) - } else if let Some(path) = crate::image_loader::file_uri_path(uri) { - Some(gpui::img(path)) - } else { - Some(gpui::img( - crate::image_loader::dev_server_asset_url(uri).into_owned(), - )) - } -} - -/// The image at its natural size, repeated across the box. -fn tiled(uri: String, tint: u32, blur: f32) -> AnyElement { - gpui::canvas( - |_, _, _| (), - move |bounds, (), window, cx| { - let Some(Ok(image)) = processed::image(&uri, tint, blur, window, cx) else { - return; - }; - let size = image.size(0); - let scale = window.scale_factor(); - let (tile_w, tile_h) = ( - f32::from(size.width.0 as f32 / scale), - f32::from(size.height.0 as f32 / scale), - ); - if tile_w < 1.0 || tile_h < 1.0 { - return; - } - window.with_content_mask(Some(gpui::ContentMask { bounds: bounds }), |window| { - let mut y = 0.0; - while y < f32::from(bounds.size.height) { - let mut x = 0.0; - while x < f32::from(bounds.size.width) { - let tile = gpui::Bounds { - origin: bounds.origin + gpui::point(gpui::px(x), gpui::px(y)), - size: gpui::size(gpui::px(tile_w), gpui::px(tile_h)), - }; - let _ = window.paint_image( - tile, - tile, - gpui::Corners::default(), - image.clone(), - 0, - false, - ); - x += tile_w; - } - y += tile_h; - } - }); - }, - ) - .size_full() - .into_any_element() -} - -fn paint(props: &Value, size: (f32, f32)) -> Option { - let uri = props.get("uri")?.as_str()?; - let resize_mode = props.get("resizeMode").and_then(Value::as_str); - let tint = props.get("tintColor").and_then(Value::as_u64).unwrap_or(0) as u32; - let blur = props - .get("blurRadius") - .and_then(Value::as_f64) - .unwrap_or(0.0) as f32; - if resize_mode == Some("repeat") { - return Some(tiled(uri.to_owned(), tint, blur)); - } - let fit = fit_for(resize_mode); - let mut image = if tint >> 24 != 0 || blur > 0.0 { - let uri = uri.to_owned(); - gpui::img(move |window: &mut Window, cx: &mut App| { - processed::image(&uri, tint, blur, window, cx) - }) - } else { - plain(uri)? - }; - if let Some(default) = props - .get("defaultSource") - .and_then(Value::as_str) - .map(str::to_owned) - { - let mode = resize_mode.map(str::to_owned); - image = image.with_loading(move || { - let fit = fit_for(mode.as_deref()); - plain(&default) - .map(|placeholder| placeholder.size_full().object_fit(fit).into_any_element()) - .unwrap_or_else(|| gpui::Empty.into_any_element()) - }); - } - // The node's size in points, not 100%: the decoder reads it before the - // image has loaded to know how big a picture to make. - let image = if size.0 > 0.0 && size.1 > 0.0 { - image.w(gpui::px(size.0)).h(gpui::px(size.1)) - } else { - image.size_full() - }; - Some(image.object_fit(fit).into_any_element()) -} - -pub fn register() { - register_component_renderer("Image", std::sync::Arc::new(ImageRenderer)); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/image/processed.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/image/processed.rs deleted file mode 100644 index f09a2e0d31..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/image/processed.rs +++ /dev/null @@ -1,97 +0,0 @@ -//! Images drawn through the app's own loader rather than GPUI's: a tint or a -//! blur has to be applied to the pixels, and a repeating image needs them to -//! tile. - -use std::collections::HashMap; -use std::sync::{Arc, Mutex, OnceLock}; - -use gpui::{App, ImageCacheError, RenderImage, Window}; -use image::{imageops, Frame, RgbaImage}; - -enum Entry { - Loading, - Ready(Arc), - Failed(Arc), -} - -static CACHE: OnceLock>> = OnceLock::new(); - -fn cache() -> &'static Mutex> { - CACHE.get_or_init(|| Mutex::new(HashMap::new())) -} - -/// Replaces the colour of every pixel with `tint`, keeping its alpha. -fn tinted(image: &mut RgbaImage, tint: u32) { - let [red, green, blue] = [(tint >> 16) as u8, (tint >> 8) as u8, tint as u8]; - let opacity = f32::from((tint >> 24) as u8) / 255.0; - for pixel in image.pixels_mut() { - pixel.0 = [ - red, - green, - blue, - (f32::from(pixel.0[3]) * opacity).round() as u8, - ]; - } -} - -fn process(bytes: &[u8], tint: u32, blur: f32) -> anyhow::Result> { - let mut rgba = image::load_from_memory(bytes)?.into_rgba8(); - if blur > 0.0 { - rgba = imageops::blur(&rgba, blur / 2.0); - } - if tint >> 24 != 0 { - tinted(&mut rgba, tint); - } - for pixel in rgba.chunks_exact_mut(4) { - pixel.swap(0, 2); - } - Ok(Arc::new(RenderImage::new(vec![Frame::new(rgba)]))) -} - -/// The decoded image for `uri`, loading it on first ask: `None` while it loads. -pub(crate) fn image( - uri: &str, - tint: u32, - blur: f32, - _window: &mut Window, - cx: &mut App, -) -> Option, ImageCacheError>> { - let key = format!("{uri}|{tint}|{}", blur.to_bits()); - { - let mut entries = cache() - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - match entries.get(&key) { - Some(Entry::Ready(image)) => return Some(Ok(image.clone())), - Some(Entry::Failed(error)) => return Some(Err(ImageCacheError::Other(error.clone()))), - Some(Entry::Loading) => return None, - None => { - entries.insert(key.clone(), Entry::Loading); - } - } - } - let client = cx.http_client(); - let executor = cx.background_executor().clone(); - let uri = uri.to_owned(); - cx.spawn(async move |cx| { - let loaded = match crate::image_loader::load_bytes(&uri, client).await { - Ok(bytes) => { - executor - .spawn(async move { process(&bytes, tint, blur) }) - .await - } - Err(error) => Err(anyhow::anyhow!(error)), - }; - let entry = match loaded { - Ok(image) => Entry::Ready(image), - Err(error) => Entry::Failed(Arc::new(error)), - }; - cache() - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert(key, entry); - cx.update(|cx| cx.refresh_windows()); - }) - .detach(); - None -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/linking/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/linking/mod.rs deleted file mode 100644 index 95a6169727..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/linking/mod.rs +++ /dev/null @@ -1,47 +0,0 @@ -mod scheme; - -use rn_gpui_module::{ModuleError, ModuleThread}; - -use crate::builtins::main_thread::on_main; -use crate::builtins::rn_gpui_specs::{ - NativeGpuiLinkingManagerEvents, NativeGpuiLinkingManagerSpec, -}; - -struct LinkingManagerModule; - -impl NativeGpuiLinkingManagerSpec for LinkingManagerModule { - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(_events: NativeGpuiLinkingManagerEvents) -> Self { - Self - } - - async fn get_initial_url(&self) -> Result, ModuleError> { - Ok(crate::desktop::deep_link::initial_url()) - } - - async fn can_open_url(&self, url: String) -> Result { - Ok(scheme::can_open(&url)) - } - - async fn open_url(&self, url: String) -> Result<(), ModuleError> { - on_main(move |cx| cx.open_url(&url)).await - } - - async fn open_settings(&self) -> Result<(), ModuleError> { - on_main(|cx| scheme::open_settings(cx)) - .await? - .map_err(ModuleError::new) - } - - fn add_listener(&self, _event_name: String) {} - - fn remove_listeners(&self, _count: f64) {} -} - -pub fn register() { - rn_gpui_module::register( - crate::builtins::rn_gpui_specs::native_gpui_linking_manager_module::( - ), - ); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/linking/scheme.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/linking/scheme.rs deleted file mode 100644 index 26036611d3..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/linking/scheme.rs +++ /dev/null @@ -1,154 +0,0 @@ -//! Whether any installed app handles a URL's scheme, and the OS settings URL. - -/// The scheme of `url`, lowercased, or `None` when there is none. -pub fn scheme_of(url: &str) -> Option { - let (scheme, _) = url.split_once(':')?; - let valid = !scheme.is_empty() - && scheme.starts_with(|c: char| c.is_ascii_alphabetic()) - && scheme - .chars() - .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')); - valid.then(|| scheme.to_ascii_lowercase()) -} - -#[cfg(target_os = "macos")] -pub fn can_open(url: &str) -> bool { - use cocoa::base::{id, nil}; - use cocoa::foundation::NSString; - use objc::{class, msg_send, sel, sel_impl}; - if scheme_of(url).is_none() { - return false; - } - // SAFETY: Foundation and AppKit calls with live receivers; `NSWorkspace` - // may be asked from any thread for this query. - unsafe { - let text = NSString::alloc(nil).init_str(url); - let ns_url: id = msg_send![class!(NSURL), URLWithString: text]; - if ns_url == nil { - return false; - } - let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace]; - let handler: id = msg_send![workspace, URLForApplicationToOpenURL: ns_url]; - handler != nil - } -} - -#[cfg(target_os = "windows")] -pub fn can_open(url: &str) -> bool { - use windows_sys::Win32::UI::Shell::{AssocQueryStringW, ASSOCF_IS_PROTOCOL, ASSOCSTR_COMMAND}; - let Some(scheme) = scheme_of(url) else { - return false; - }; - let wide: Vec = scheme.encode_utf16().chain(std::iter::once(0)).collect(); - let mut size: u32 = 0; - // SAFETY: `wide` is NUL-terminated; a null output buffer asks only for the size. - let status = unsafe { - AssocQueryStringW( - ASSOCF_IS_PROTOCOL, - ASSOCSTR_COMMAND, - wide.as_ptr(), - std::ptr::null(), - std::ptr::null_mut(), - &mut size, - ) - }; - status == 0 || status == 1 /* S_FALSE: the size was returned */ -} - -#[cfg(target_os = "linux")] -pub fn can_open(url: &str) -> bool { - use std::process::Command; - let Some(scheme) = scheme_of(url) else { - return false; - }; - let web = matches!(scheme.as_str(), "http" | "https"); - let output = if web { - Command::new("xdg-settings") - .args(["get", "default-web-browser"]) - .output() - } else { - Command::new("xdg-mime") - .args(["query", "default", &format!("x-scheme-handler/{scheme}")]) - .output() - }; - let registered = output - .map(|output| output.status.success() && !output.stdout.iter().all(u8::is_ascii_whitespace)) - .unwrap_or(false); - registered || web && web_browser_fallback() -} - -/// `xdg-open` opens a web address with `$BROWSER` or the distribution's -/// `x-www-browser` when no desktop entry is the default browser. -#[cfg(target_os = "linux")] -fn web_browser_fallback() -> bool { - std::env::var_os("BROWSER").is_some_and(|browser| !browser.is_empty()) - || std::env::var_os("PATH").is_some_and(|path| { - std::env::split_paths(&path).any(|dir| dir.join("x-www-browser").is_file()) - }) -} - -#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))] -pub fn can_open(_url: &str) -> bool { - false -} - -/// Opens the OS settings app, or says why it cannot. -pub fn open_settings(cx: &gpui::App) -> Result<(), String> { - #[cfg(target_os = "macos")] - { - cx.open_url("x-apple.systempreferences:"); - Ok(()) - } - #[cfg(target_os = "windows")] - { - cx.open_url("ms-settings:"); - Ok(()) - } - #[cfg(target_os = "linux")] - { - let _ = cx; - for program in [ - "gnome-control-center", - "systemsettings", - "xfce4-settings-manager", - ] { - if std::process::Command::new(program).spawn().is_ok() { - return Ok(()); - } - } - Err("no settings application was found on PATH".to_string()) - } - #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))] - { - let _ = cx; - Err("opening settings is not supported on this system".to_string()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_scheme_is_the_part_before_the_first_colon() { - assert_eq!(scheme_of("HTTPS://example.com").as_deref(), Some("https")); - assert_eq!(scheme_of("mailto:a@b.c").as_deref(), Some("mailto")); - assert_eq!( - scheme_of("x-apple.systempreferences:").as_deref(), - Some("x-apple.systempreferences") - ); - assert_eq!(scheme_of("no scheme here"), None); - assert_eq!(scheme_of("1http://x"), None); - assert_eq!(scheme_of(":empty"), None); - } - - #[test] - fn a_known_scheme_has_a_handler_and_an_unregistered_one_does_not() { - #[cfg(any(target_os = "macos", target_os = "windows"))] - { - assert!(can_open("https://example.com")); - assert!(!can_open("rngpui-no-such-scheme-zzz://x")); - } - assert!(!can_open("not a url")); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/main_thread.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/main_thread.rs deleted file mode 100644 index d1fec882d0..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/main_thread.rs +++ /dev/null @@ -1,15 +0,0 @@ -use futures::channel::oneshot; -use gpui::App; -use rn_gpui_module::ModuleError; - -pub(crate) async fn on_main( - command: impl FnOnce(&mut App) -> T + Send + 'static, -) -> Result { - let (sender, receiver) = oneshot::channel(); - crate::desktop::post_to_main(Box::new(move |cx| { - let _ = sender.send(command(cx)); - })); - receiver - .await - .map_err(|_| ModuleError::new("the desktop shell is not running")) -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/mod.rs deleted file mode 100644 index baaf41349e..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/mod.rs +++ /dev/null @@ -1,64 +0,0 @@ -rn_gpui_module::include_specs!(); - -pub mod activity_indicator; -pub mod alert; -pub mod app; -pub mod app_menu; -pub mod clipboard; -pub mod context_menu; -pub mod context_menu_view; -pub mod desktop_scroll_bar; -pub mod dev_menu; -pub mod i18n; -pub mod image; -pub mod linking; -pub mod main_thread; -pub mod modal; -pub mod native_list; -pub mod native_root; -pub mod native_slot; -pub mod network; -pub mod perf_monitor; -pub mod scrollview; -pub mod settings; -pub mod share; -pub mod shortcut_scope; -pub mod shortcuts; -pub mod switch; -pub(crate) mod text_select; -pub mod textinput; -pub mod tray; -pub mod vibration; -pub mod window_control; -pub mod windows; - -pub fn register() { - activity_indicator::register(); - alert::register(); - app::register(); - app_menu::register(); - clipboard::register(); - context_menu::register(); - context_menu_view::register(); - dev_menu::register(); - i18n::register(); - image::register(); - linking::register(); - modal::register(); - native_list::register(); - native_root::register(); - native_slot::register(); - network::register(); - perf_monitor::register(); - scrollview::register(); - settings::register(); - share::register(); - desktop_scroll_bar::register(); - shortcut_scope::register(); - shortcuts::register(); - switch::register(); - tray::register(); - vibration::register(); - window_control::register(); - windows::register(); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/modal/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/modal/mod.rs deleted file mode 100644 index ef9d78f34a..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/modal/mod.rs +++ /dev/null @@ -1,33 +0,0 @@ -use serde_json::Value; - -use crate::extensions::{register_component_renderer, ComponentNode, ComponentRenderer, Portal}; -use gpui::{AnyElement, App, Window}; - -const CLOSE_REQUEST_EVENT: &str = "topRequestClose"; - -struct ModalRenderer; - -impl ComponentRenderer for ModalRenderer { - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } - - fn portal(&self, props: &Value) -> Option { - Some(Portal { - visible: props - .get("visible") - .and_then(Value::as_bool) - .unwrap_or(true), - close_request_event: Some(CLOSE_REQUEST_EVENT.to_string()), - }) - } -} - -pub fn register() { - register_component_renderer("ModalHostView", std::sync::Arc::new(ModalRenderer)); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/native_list/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/native_list/mod.rs deleted file mode 100644 index 0d147ed5dc..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/native_list/mod.rs +++ /dev/null @@ -1,425 +0,0 @@ -//! A virtual list for native trees. -//! -//! The list owns the scrolling and tells JavaScript which items are in view -//! (`onRangeChange`, `{ first, last }`); JavaScript renders those items, and a -//! few more on each side, as `NativeVirtualItem` children. Items have the height -//! of their content: a native item is measured by GPUI, an item that holds a -//! `NativeSlot` by the layout of its React Native content. Items not measured -//! yet count as the estimate. When an item above the viewport changes size the -//! scroll position moves by the difference, so what is on screen stays put. -//! -//! `scrollRequest` scrolls to an index or an offset, and `onEndReached` fires -//! when the end comes within a threshold of the viewport. - -use std::cell::{Cell, RefCell}; -use std::collections::HashMap; -use std::rc::Rc; - -use gpui::{canvas, div, point, prelude::*, px, AnyElement, App, ScrollHandle, Window}; -use serde_json::{json, Map, Value}; - -use crate::native_tree::{ - register_native_component, NativeComponent, NativeContext, NativeEmitter, -}; - -pub const LIST: &str = "NativeVirtualList"; -pub const ITEM: &str = "NativeVirtualItem"; - -fn number(props: &Map, name: &str) -> f32 { - props.get(name).and_then(Value::as_f64).unwrap_or(0.0) as f32 -} - -/// The heights of a list's items: measured ones, and the estimate for the rest. -/// Positions are prefix sums, kept in a Fenwick tree of each measured item's -/// difference from the estimate, so a position and an item at a position are -/// both a logarithm. -struct Heights { - estimate: f32, - count: usize, - measured: HashMap, - tree: Vec, -} - -impl Heights { - fn new(estimate: f32, count: usize) -> Self { - Self { - estimate, - count, - measured: HashMap::new(), - tree: vec![0.0; count + 1], - } - } - - fn rebuild(&mut self, estimate: f32, count: usize) { - if estimate == self.estimate && count == self.count { - return; - } - self.estimate = estimate; - self.count = count; - self.measured.retain(|index, _| *index < count); - self.tree = vec![0.0; count + 1]; - let entries: Vec<_> = self.measured.iter().map(|(i, h)| (*i, *h)).collect(); - for (index, height) in entries { - self.add(index, f64::from(height - estimate)); - } - } - - fn add(&mut self, index: usize, delta: f64) { - let mut at = index + 1; - while at < self.tree.len() { - self.tree[at] += delta; - at += at & at.wrapping_neg(); - } - } - - fn delta_before(&self, index: usize) -> f64 { - let mut at = index.min(self.count); - let mut sum = 0.0; - while at > 0 { - sum += self.tree[at]; - at -= at & at.wrapping_neg(); - } - sum - } - - fn height(&self, index: usize) -> f32 { - self.measured.get(&index).copied().unwrap_or(self.estimate) - } - - fn offset_of(&self, index: usize) -> f32 { - (index as f64 * f64::from(self.estimate) + self.delta_before(index)) as f32 - } - - fn total(&self) -> f32 { - self.offset_of(self.count) - } - - /// The item that covers `y`, the last one if `y` is past the end. - fn index_at(&self, y: f32) -> usize { - if self.count == 0 { - return 0; - } - let (mut low, mut high) = (0, self.count - 1); - while low < high { - let middle = (low + high).div_ceil(2); - if self.offset_of(middle) <= y { - low = middle; - } else { - high = middle - 1; - } - } - low - } - - /// Records a measurement, returning how far it moved what follows the item. - fn set(&mut self, index: usize, height: f32) -> Option { - if index >= self.count || (self.height(index) - height).abs() < 0.5 { - return None; - } - let before = self.height(index); - self.measured.insert(index, height); - self.add(index, f64::from(height - before)); - Some(height - before) - } -} - -struct ListState { - heights: Heights, - scroll: ScrollHandle, -} - -thread_local! { - static LISTS: RefCell>>> = RefCell::new(HashMap::new()); -} - -fn list_state(id: u32) -> Option>> { - LISTS.with(|lists| lists.borrow().get(&id).cloned()) -} - -#[derive(Clone, Copy)] -struct ScrollRequest { - id: i64, - index: Option, - offset: f32, - align: f32, - attempts: u8, -} - -fn read_request(value: &Value) -> Option { - let id = value.get("id")?.as_i64()?; - let align = match value.get("align").and_then(Value::as_str) { - Some("center") => 0.5, - Some("end") => 1.0, - _ => 0.0, - }; - Some(ScrollRequest { - id, - index: value - .get("index") - .and_then(Value::as_u64) - .map(|i| i as usize), - offset: value.get("offset").and_then(Value::as_f64).unwrap_or(0.0) as f32, - align, - attempts: 0, - }) -} - -struct VirtualList { - emitter: NativeEmitter, - id: u32, - state: Rc>, - reported: Rc>, - pending: Rc>>, - end_reached_for: Rc>, -} - -fn list_id(props: &Map) -> u32 { - props.get("listId").and_then(Value::as_u64).unwrap_or(0) as u32 -} - -impl NativeComponent for VirtualList { - fn create(props: &Map, cx: &mut NativeContext) -> Self { - let id = list_id(props); - let state = Rc::new(RefCell::new(ListState { - heights: Heights::new( - number(props, "estimatedItemHeight").max(1.0), - number(props, "count") as usize, - ), - scroll: ScrollHandle::new(), - })); - LISTS.with(|lists| lists.borrow_mut().insert(id, state.clone())); - Self { - emitter: cx.emitter(), - id, - state, - reported: Rc::new(Cell::new((-2, -2))), - pending: Rc::new(Cell::new(None)), - end_reached_for: Rc::new(Cell::new(-1)), - } - } - - fn update(&mut self, props: &Map, changed: &[String], _cx: &mut NativeContext) { - self.state.borrow_mut().heights.rebuild( - number(props, "estimatedItemHeight").max(1.0), - number(props, "count") as usize, - ); - if changed.iter().any(|name| name == "count") { - self.end_reached_for.set(-1); - } - if changed.iter().any(|name| name == "scrollRequest") { - self.pending - .set(props.get("scrollRequest").and_then(read_request)); - } - } - - fn render( - &mut self, - props: &Map, - children: Vec, - _window: &mut Window, - _cx: &mut App, - ) -> AnyElement { - let state = self.state.clone(); - let (total, handle) = { - let state = state.borrow(); - (state.heights.total(), state.scroll.clone()) - }; - let count = number(props, "count") as i64; - let threshold = props - .get("endReachedThreshold") - .and_then(Value::as_f64) - .unwrap_or(200.0) as f32; - let wants_end = props.get("onEndReached").is_some(); - let emitter = self.emitter.clone(); - let reported = self.reported.clone(); - let pending = self.pending.clone(); - let end_reached_for = self.end_reached_for.clone(); - div() - .relative() - .size_full() - .child( - div() - .id("native-virtual-list") - .size_full() - .overflow_y_scroll() - .track_scroll(&handle) - .child(div().relative().w_full().h(px(total)).children(children)), - ) - .child( - canvas( - move |bounds, _window, _cx| { - if count <= 0 { - return; - } - let view = f32::from(bounds.size.height); - let state = state.borrow(); - let scroll = &state.scroll; - let max_top = (state.heights.total() - view).max(0.0); - if let Some(mut request) = pending.get() { - let target = match request.index { - Some(index) => { - let index = index.min(count as usize - 1); - let top = state.heights.offset_of(index); - let height = state.heights.height(index); - top - (view - height) * request.align - } - None => request.offset, - } - .clamp(0.0, max_top); - let current = -f32::from(scroll.offset().y); - if (current - target).abs() > 0.5 { - scroll.set_offset(point(px(0.0), px(-target))); - } - request.attempts += 1; - let settled = (current - target).abs() <= 0.5 - && request.index.is_none_or(|index| { - state.heights.measured.contains_key(&index) - }); - pending.set((!settled && request.attempts < 12).then_some(request)); - } - let top = -f32::from(scroll.offset().y); - let first = state.heights.index_at(top) as i64; - let last = (state.heights.index_at(top + view) as i64).max(first); - if reported.get() != (first, last) { - reported.set((first, last)); - emitter.emit("onRangeChange", json!({ "first": first, "last": last })); - } - if wants_end - && end_reached_for.get() != count - && top + view >= state.heights.total() - threshold - { - end_reached_for.set(count); - emitter.emit("onEndReached", json!({})); - } - }, - |_, _, _, _| {}, - ) - .absolute() - .size_full(), - ) - .into_any_element() - } -} - -impl Drop for VirtualList { - fn drop(&mut self) { - let id = self.id; - let _ = LISTS.try_with(|lists| lists.borrow_mut().remove(&id)); - } -} - -struct VirtualItem; - -impl NativeComponent for VirtualItem { - fn create(_props: &Map, _cx: &mut NativeContext) -> Self { - VirtualItem - } - - fn update( - &mut self, - _props: &Map, - _changed: &[String], - _cx: &mut NativeContext, - ) { - } - - fn recyclable(&self) -> bool { - true - } - - fn recycle(&mut self, _props: &Map, _cx: &mut NativeContext) -> bool { - true - } - - fn render( - &mut self, - props: &Map, - children: Vec, - _window: &mut Window, - _cx: &mut App, - ) -> AnyElement { - let index = number(props, "index") as usize; - let state = list_state(list_id(props)); - let top = state - .as_ref() - .map_or(0.0, |state| state.borrow().heights.offset_of(index)); - let root = crate::builtins::native_root::current_root(); - div() - .absolute() - .left_0() - .top(px(top)) - .w_full() - .flex() - .flex_col() - .children(children) - .child( - canvas( - move |bounds, window, cx| { - let Some(state) = state else { - return; - }; - let height = f32::from(bounds.size.height); - let mut state = state.borrow_mut(); - let above = - state.heights.offset_of(index) < -f32::from(state.scroll.offset().y); - if let Some(delta) = state.heights.set(index, height) { - if above { - let offset = state.scroll.offset(); - state - .scroll - .set_offset(point(offset.x, offset.y - px(delta))); - } - drop(state); - crate::builtins::native_root::notify_root_later(root, window, cx); - } - }, - |_, _, _, _| {}, - ) - .absolute() - .size_full(), - ) - .into_any_element() - } -} - -pub fn register() { - register_native_component::(LIST); - register_native_component::(ITEM); -} - -#[cfg(test)] -mod tests { - use super::Heights; - - #[test] - fn unmeasured_items_count_as_the_estimate() { - let heights = Heights::new(10.0, 100); - assert_eq!(heights.offset_of(5), 50.0); - assert_eq!(heights.total(), 1000.0); - assert_eq!(heights.index_at(55.0), 5); - assert_eq!(heights.index_at(5000.0), 99); - } - - #[test] - fn a_measurement_moves_what_follows_it() { - let mut heights = Heights::new(10.0, 100); - assert_eq!(heights.set(3, 25.0), Some(15.0)); - assert_eq!(heights.offset_of(3), 30.0); - assert_eq!(heights.offset_of(4), 55.0); - assert_eq!(heights.total(), 1015.0); - assert_eq!(heights.index_at(54.0), 3); - assert_eq!(heights.index_at(55.0), 4); - assert_eq!(heights.set(3, 25.2), None); - } - - #[test] - fn a_new_count_or_estimate_keeps_the_measurements_that_still_apply() { - let mut heights = Heights::new(10.0, 100); - heights.set(3, 20.0); - heights.set(90, 40.0); - heights.rebuild(10.0, 50); - assert_eq!(heights.total(), 510.0); - heights.rebuild(20.0, 50); - assert_eq!(heights.offset_of(4), 3.0 * 20.0 + 20.0); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/native_root/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/native_root/mod.rs deleted file mode 100644 index 0725f8ab6f..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/native_root/mod.rs +++ /dev/null @@ -1,827 +0,0 @@ -//! The native root: a box whose content is a native tree. -//! -//! A second React reconciler describes nested components of one family as -//! batches of operations, and [`crate::native_tree`] keeps them as instances. This -//! component is where such a tree meets React Native's layout: Yoga sizes the box -//! like any view, and the tree is built inside it as one GPUI element tree. -//! -//! The batches arrive from JavaScript through `__gpuiNativeRootApply(rootId, -//! json)` and are applied on the main thread. Events go back as `topNativeEvent` -//! on the box, naming the instance and the prop that holds its handler. - -use std::cell::{Cell, RefCell}; -use std::collections::HashMap; -use std::rc::Rc; -use std::sync::Arc; - -use gpui::{ - canvas, div, prelude::*, px, size, AnyElement, App, AvailableSpace, Element, GlobalElementId, - InspectorElementId, LayoutId, Window, -}; -use serde_json::{json, Map, Value}; - -use crate::extensions::{register_component_renderer, ComponentNode, ComponentRenderer}; -use crate::host::Host; -use crate::native_tree::{ - register_native_component, NativeComponent, NativeContext, NativeOp, NativeTree, -}; - -/// The name of the event that tells JavaScript the size a tree was laid out at, -/// for it to remember. The box itself takes the size from the shadow node's -/// state. -pub const CONTENT_SIZE: &str = "__contentSize"; - -pub const COMPONENT: &str = "DesktopNativeRoot"; - -/// The type of the instance that holds a tree's top-level components. -pub const CONTAINER: &str = "NativeRootContainer"; - -struct RootState { - tree: NativeTree, - /// The tag of the node that shows this tree, once it has rendered. - tag: Rc>>, - /// The box has no height of its own: the tree is laid out at its natural - /// height and that height is reported to the box's shadow node. - auto_height: Rc>, - /// The box has no width of its own: the tree's max-content and min-content - /// widths are reported with the height, and the box fits between them. - auto_width: Rc>, - reported_height: Rc>, - reported_width: Rc>, -} - -thread_local! { - static CURRENT_ROOT: Cell = const { Cell::new(0) }; - /// The nodes that hold the React Native children of the slots of the tree - /// being rendered, by slot id. - static SLOT_HOSTS: RefCell>> = - RefCell::new(HashMap::new()); - static TREES: RefCell> = RefCell::new(HashMap::new()); - /// The trees that appeared less than `SETTLE_LIMIT` ago, which the window - /// holds its last frame for while their box does not have the tree's size - /// or a slot waits for its content. - static UNSETTLED: RefCell> = RefCell::new(HashMap::new()); - static SEQUENCE: Cell = const { Cell::new(0) }; - /// Every tree seen, gone ones too: a box rendered once more as its tree is - /// destroyed is not a new tree. Ids are never reused. - static STARTED: RefCell> = RefCell::new(Default::default()); - /// The nodes that rendered before their tree arrived, so the tree's first - /// batch repaints them. - static EARLY_TAGS: RefCell> = RefCell::new(HashMap::new()); - /// The hinted trees whose first content has been checked against their box. - static CHECKED: RefCell> = RefCell::new(Default::default()); - static HOLD: Rc bool> = Rc::new(holding); - /// When the window began holding its last frame, while it does. - static HELD_SINCE: Cell> = const { Cell::new(None) }; - /// When the windows' recent holds ended and how long each took. - static RECENT_HOLDS: RefCell> = - RefCell::new(std::collections::VecDeque::new()); -} - -/// How much holding a window may do within `HOLD_BUDGET_WINDOW` before new -/// roots stop holding it: a stream of roots that mount one after another -/// would otherwise keep the window on its last frame. -const HOLD_BUDGET: std::time::Duration = std::time::Duration::from_millis(200); -const HOLD_BUDGET_WINDOW: std::time::Duration = std::time::Duration::from_secs(1); - -/// How recent a scroll event is that keeps a new root from holding the window: -/// a row that mounts while the list is scrolled shifts nothing in view, and a -/// frozen frame would stop the scroll. -const SCROLL_QUIET: std::time::Duration = std::time::Duration::from_millis(150); - -/// Records when the window starts and stops holding. -fn note_hold(held: bool) { - let now = std::time::Instant::now(); - HELD_SINCE.with(|since| match (since.get(), held) { - (None, true) => since.set(Some(now)), - (Some(started), false) => { - since.set(None); - let took = now.duration_since(started); - RECENT_HOLDS.with(|recent| recent.borrow_mut().push_back((now, took))); - crate::counters::add(crate::counters::Counter::NativeRootHolds, 1); - crate::counters::add( - crate::counters::Counter::NativeRootHeldMicros, - took.as_micros() as u64, - ); - } - _ => {} - }); -} - -/// Whether a new root may hold the window: not while it is scrolling, and not -/// once it has held for `HOLD_BUDGET` within the last `HOLD_BUDGET_WINDOW`. -fn hold_allowed() -> bool { - let spent = RECENT_HOLDS.with(|recent| { - let mut recent = recent.borrow_mut(); - while recent - .front() - .is_some_and(|(ended, _)| ended.elapsed() > HOLD_BUDGET_WINDOW) - { - recent.pop_front(); - } - recent - .iter() - .map(|(_, took)| *took) - .sum::() - }) + HELD_SINCE.with(|since| { - since - .get() - .map_or(std::time::Duration::ZERO, |at| at.elapsed()) - }); - let allowed = !crate::wheel::scrolled_within(SCROLL_QUIET) && spent <= HOLD_BUDGET; - if !allowed { - crate::counters::add(crate::counters::Counter::NativeRootHoldsSkipped, 1); - } - allowed -} - -/// How long a window holds its last frame for new trees to settle. -const SETTLE_LIMIT: std::time::Duration = std::time::Duration::from_millis(250); - -struct Settling { - since: std::time::Instant, - /// When the tree was last rendered and last painted, in one sequence. - rendered: Option, - painted: Option, -} - -fn next_sequence() -> u64 { - SEQUENCE.with(|sequence| { - sequence.set(sequence.get() + 1); - sequence.get() - }) -} - -/// Whether a window should keep showing its last frame: a new tree is still -/// settling, so the frame would show it, and what is laid out around it, at -/// sizes about to change. A tree rendered but not painted is out of view. -fn holding() -> bool { - let held = UNSETTLED.with(|unsettled| { - let mut unsettled = unsettled.borrow_mut(); - unsettled.retain(|_, settling| settling.since.elapsed() < SETTLE_LIMIT); - unsettled.values().any(|settling| match settling.rendered { - None => true, - Some(rendered) => settling.painted.is_some_and(|painted| painted > rendered), - }) - }); - note_hold(held); - held -} - -fn root_id(node: &ComponentNode) -> u32 { - node.props - .get("rootId") - .and_then(Value::as_u64) - .unwrap_or(0) as u32 -} - -/// Applies a batch of operations to the tree `root`, making the tree if this is -/// its first, and repaints the node that shows it. `"destroy"` drops the tree. -pub(crate) fn apply_ops(cx: &mut App, root: u32, payload: &str) { - if payload == "destroy" { - TREES.with(|trees| { - trees.borrow_mut().remove(&root); - }); - UNSETTLED.with(|unsettled| unsettled.borrow_mut().remove(&root)); - EARLY_TAGS.with(|tags| tags.borrow_mut().remove(&root)); - CHECKED.with(|checked| checked.borrow_mut().remove(&root)); - return; - } - if payload == "auto-height" || payload == "auto-width" { - TREES.with(|trees| { - let mut trees = trees.borrow_mut(); - let state = trees.entry(root).or_insert_with(|| new_state(root, cx)); - if payload == "auto-height" { - state.auto_height.set(true); - } else { - state.auto_width.set(true); - } - }); - return; - } - let ops = match serde_json::from_str::(payload) - .map_err(|error| error.to_string()) - .and_then(|batch| NativeOp::parse_batch(&batch)) - { - Ok(ops) => ops, - Err(error) => { - log::error!("[native-root] bad batch for tree {root}: {error}"); - return; - } - }; - let Some(store) = crate::store::store_from(cx) else { - return; - }; - drop_stale_trees(cx, root); - let tag = TREES.with(|trees| { - let mut trees = trees.borrow_mut(); - let state = trees.entry(root).or_insert_with(|| new_state(root, cx)); - let window = state - .tag - .get() - .and_then(|tag| store.read(cx).nodes.get(&tag).cloned()) - .and_then(|node| crate::store::window_of_surface(node.read(cx).surface_id)); - if window.is_some() { - state.tree.set_window(window); - } - let started = std::time::Instant::now(); - let count = ops.len() as u64; - state.tree.apply(ops, cx); - crate::counters::add(crate::counters::Counter::NativeOpsApplied, count); - crate::counters::add( - crate::counters::Counter::NativeApplyMicros, - started.elapsed().as_micros() as u64, - ); - state.tag.get() - }); - if let Some(node) = tag.and_then(|tag| store.read(cx).nodes.get(&tag).cloned()) { - node.update(cx, |_, cx| cx.notify()); - if let Some(window) = crate::store::window_of_surface(node.read(cx).surface_id) { - draw_settling_now(window, cx); - } - } -} - -thread_local! { - static DRAW_QUEUED: Cell = const { Cell::new(false) }; -} - -/// While a tree is settling, draws `window` as soon as new content arrives -/// instead of on its next frame: the frame is not shown during a hold, so a -/// size that takes several rounds between the tree and React Native's layout -/// settles in one frame interval rather than one per round. -pub(crate) fn draw_settling_now(window: gpui::AnyWindowHandle, cx: &mut App) { - if UNSETTLED.with(|unsettled| unsettled.borrow().is_empty()) - || DRAW_QUEUED.with(|queued| queued.replace(true)) - { - return; - } - cx.defer(move |cx| { - DRAW_QUEUED.with(|queued| queued.set(false)); - let _ = window.update(cx, |_, window, cx| window.draw_while_held(cx)); - }); -} - -/// Whether this is the first time the tree `root` is seen, by its box rendering -/// or its first batch arriving, whichever comes first. -fn first_seen(root: u32) -> bool { - STARTED.with(|started| started.borrow_mut().insert(root)) -} - -/// Starts holding the window's last frame for the tree `root` to settle, unless -/// the window is scrolling or has held enough lately. Whether it did. -fn begin_settling(root: u32) -> bool { - if !hold_allowed() { - return false; - } - UNSETTLED.with(|unsettled| { - unsettled.borrow_mut().insert( - root, - Settling { - since: std::time::Instant::now(), - rendered: None, - painted: None, - }, - ); - }); - true -} - -fn new_state(root: u32, cx: &App) -> RootState { - if first_seen(root) { - begin_settling(root); - } - let host: Host = crate::store::store_from(cx) - .map(|store| store.read(cx).host.clone()) - .expect("the store exists while a tree is applied to"); - let tag = Rc::new(Cell::new( - EARLY_TAGS.with(|tags| tags.borrow_mut().remove(&root)), - )); - let sink_tag = tag.clone(); - let mut tree = NativeTree::new(move |event| { - if let Some(tag) = sink_tag.get() { - host.dispatch_event( - tag, - "topNativeEvent", - &json!({ - "id": event.id, - "name": event.name, - "payload": event.payload, - }), - ); - } - }); - tree.set_instance_renderer(Rc::new(move |id, window, cx| { - CURRENT_ROOT.with(|current| current.set(root)); - collect_slot_hosts(root, cx); - TREES.with(|trees| match trees.borrow_mut().get_mut(&root) { - Some(state) => state.tree.render(id, window, cx), - None => div().into_any_element(), - }) - })); - RootState { - tree, - tag, - auto_height: Rc::new(Cell::new(false)), - auto_width: Rc::new(Cell::new(false)), - reported_height: Rc::new(Cell::new(-1.0)), - reported_width: Rc::new(Cell::new((-1.0, -1.0))), - } -} - -/// Drops the trees whose node is gone, which is what a reload or an unmount that -/// never sent `destroy` leaves behind. `keep` is the tree being applied to. -fn drop_stale_trees(cx: &App, keep: u32) { - let Some(store) = crate::store::store_from(cx) else { - return; - }; - let store = store.read(cx); - TREES.with(|trees| { - trees.borrow_mut().retain(|root, state| { - *root == keep - || state - .tag - .get() - .is_none_or(|tag| store.nodes.contains_key(&tag)) - }); - }); -} - -fn collect_slot_hosts(root: u32, cx: &App) { - let Some(store) = crate::store::store_from(cx) else { - return; - }; - let store = store.read(cx); - let hosts = crate::builtins::native_slot::hosts_of(root) - .into_iter() - .filter_map(|(slot, tag)| Some((slot, store.nodes.get(&tag)?.clone()))) - .collect::>(); - SLOT_HOSTS.with(|slots| *slots.borrow_mut() = hosts); -} - -/// The tree whose components are being rendered. -pub(crate) fn current_root() -> u32 { - CURRENT_ROOT.with(Cell::get) -} - -/// Renders the node that shows tree `root` again, once the current frame is -/// done. For a component that learns something while painting that changes what -/// it renders, such as the size of an item. -pub(crate) fn notify_root_later(root: u32, window: &mut Window, cx: &mut App) { - window.defer(cx, move |_, cx| { - let Some(store) = crate::store::store_from(cx) else { - return; - }; - let tag = TREES.with(|trees| trees.borrow().get(&root).and_then(|state| state.tag.get())); - if let Some(node) = tag.and_then(|tag| store.read(cx).nodes.get(&tag).cloned()) { - node.update(cx, |_, cx| cx.notify()); - } - }); -} - -/// The node holding the React Native children of slot `slot` in the tree being -/// rendered. -pub(crate) fn slot_host(slot: i64) -> Option> { - SLOT_HOSTS.with(|slots| slots.borrow().get(&slot).cloned()) -} - -struct NativeRootRenderer; - -impl ComponentRenderer for NativeRootRenderer { - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } - - fn content( - &self, - node: &ComponentNode, - window: &mut Window, - cx: &mut App, - ) -> Option { - let root = root_id(node); - // A box that started at a remembered size is probably right already: - // it holds the window only if its first content shows it was not. - let hinted = node.props.get("hinted").and_then(Value::as_bool) == Some(true); - // A box whose tree has not arrived yet holds the window too: the frame - // would show the page around it at sizes about to change. - if root != 0 && TREES.with(|trees| !trees.borrow().contains_key(&root)) { - if first_seen(root) { - EARLY_TAGS.with(|tags| tags.borrow_mut().insert(root, node.tag)); - if !hinted && begin_settling(root) { - window.set_presentation_hold(Some(HOLD.with(Rc::clone))); - } - } - return None; - } - TREES.with(|trees| { - let mut trees = trees.borrow_mut(); - let state = trees.get_mut(&root)?; - state.tag.set(Some(node.tag)); - let settling = UNSETTLED.with(|unsettled| { - unsettled - .borrow_mut() - .get_mut(&root) - .map(|settling| settling.rendered = Some(next_sequence())) - .is_some() - }); - if settling { - window.set_presentation_hold(Some(HOLD.with(Rc::clone))); - } - let started = std::time::Instant::now(); - CURRENT_ROOT.with(|current| current.set(root)); - collect_slot_hosts(root, cx); - let auto = state.auto_height.get(); - let auto_width = state.auto_width.get(); - let roots: Vec<_> = state.tree.roots().to_vec(); - // A tree of one component without a width of its own is laid out - // as the item of a row, as a GPUI flex item of a row would be: it - // shrinks with the box down to its automatic minimum width. - let single = match roots.as_slice() { - [root] if auto_width => match state.tree.children(*root) { - [child] => Some(*child), - _ => None, - }, - _ => None, - }; - let shown = single.map_or_else(|| roots.clone(), |child| vec![child]); - let elements: Vec = shown - .iter() - .map(|&id| state.tree.render(id, window, cx)) - .collect(); - // Copies that are only laid out, as items of a row: one in a row - // of no width, where they shrink as far as GPUI lets them, and one - // at max-content. Their extents are the tree's min-content and - // max-content widths. - let probes = auto_width.then(|| { - [single.is_some(), false].map(|shrunk| { - let measured: Vec = shown - .iter() - .map(|&id| Measured::new(state.tree.render(id, window, cx))) - .collect(); - let ids = measured - .iter() - .map(|item| item.id.clone()) - .collect::>(); - let probe = div().flex().flex_row().children(measured); - let probe = if shrunk { probe.w(px(0.)) } else { probe }; - (probe.into_any_element(), ids) - }) - }); - crate::counters::add( - crate::counters::Counter::NativeRenderMicros, - started.elapsed().as_micros() as u64, - ); - let reported = state.reported_height.clone(); - let reported_width = state.reported_width.clone(); - let tag = node.tag; - let measure = canvas( - move |bounds, window, cx| { - let height = f32::from(bounds.size.height); - let widths = probes.map(|[min, max]| { - let extent = |(mut probe, ids): ( - AnyElement, - Vec>>>, - ), - width: AvailableSpace, - window: &mut Window, - cx: &mut App| { - probe.layout_as_root( - size(width, AvailableSpace::MaxContent), - window, - cx, - ); - let bounds: Vec<_> = ids - .iter() - .filter_map(|id| id.get()) - .map(|id| window.layout_bounds(id)) - .collect(); - let left = bounds - .iter() - .map(|b| f32::from(b.left())) - .fold(f32::INFINITY, f32::min); - let right = bounds - .iter() - .map(|b| f32::from(b.right())) - .fold(f32::NEG_INFINITY, f32::max); - if bounds.is_empty() { - 0.0 - } else { - right - left - } - }; - let min = extent(min, AvailableSpace::Definite(px(0.)), window, cx); - let max = extent(max, AvailableSpace::MaxContent, window, cx); - (max, min.min(max)) - }); - let changed = (reported.get() - height).abs() > 0.01 - || widths.is_some_and(|(max, min)| { - let (old_max, old_min) = reported_width.get(); - (old_max - max).abs() > 0.01 || (old_min - min).abs() > 0.01 - }); - if changed { - let (max, min) = widths.unwrap_or_default(); - if rn_gpui_sys::ffi::reportNativeRootSize( - tag, - height, - widths.is_some(), - max, - min, - ) { - reported.set(height); - let payload = match widths { - Some((max, min)) => { - reported_width.set((max, min)); - json!({ "width": max, "minWidth": min, "height": height }) - } - None => json!({ "height": height }), - }; - if let Some(store) = crate::store::store_from(cx) { - store.read(cx).host.dispatch_event( - tag, - "topNativeEvent", - &json!({ "id": 0, "name": CONTENT_SIZE, "payload": payload }), - ); - } - } - } - }, - |_, _, _, _| {}, - ) - .absolute() - .size_full(); - let frame_size = (node.frame.w, node.frame.h); - // A tree without its first batch is empty, and as high as its - // empty box: that is not its size. - let has_content = state - .tree - .roots() - .first() - .is_some_and(|&container| !state.tree.children(container).is_empty()); - let settled_width = state.reported_width.clone(); - let late = hinted - && !settling - && has_content - && CHECKED.with(|checked| checked.borrow_mut().insert(root)); - let settle = (settling || late).then(|| { - canvas( - move |bounds, window, _| { - let (width, height) = frame_size; - let (max, min) = settled_width.get(); - // Yoga rounds the box to the pixel grid: within half a - // device pixel of the tree, it will not move again. - let slack = 0.5 / window.scale_factor(); - let sized = (!auto - || (height - f32::from(bounds.size.height)).abs() <= slack) - && (!auto_width - || (max >= 0.0 && width >= min - slack && width <= max + slack)); - let settled = has_content && sized; - // A settled tree stays watched until its time is up: a - // component that renders its real content in a later - // batch grows the tree after it first matched its box. - if !settled { - if late && begin_settling(root) { - window.set_presentation_hold(Some(HOLD.with(Rc::clone))); - } - UNSETTLED.with(|unsettled| { - if let Some(settling) = unsettled.borrow_mut().get_mut(&root) { - settling.rendered = Some(next_sequence()); - settling.painted = Some(next_sequence()); - } - }); - } - }, - |_, _, _, _| {}, - ) - .absolute() - .size_full() - }); - let frame = div().absolute().w_full(); - let frame = if auto { frame } else { frame.h_full() }; - let auto = auto || auto_width; - Some( - frame - .flex() - .when(single.is_some(), |this| this.flex_row()) - .when(single.is_none(), |this| this.flex_col()) - .tab_group() - .tab_index(node.tag as isize) - .on_key_down(|event, window, cx| { - if event.keystroke.key == "tab" { - if event.keystroke.modifiers.shift { - window.focus_prev(cx); - } else { - window.focus_next(cx); - } - cx.stop_propagation(); - } - }) - .children(elements) - .when(auto, |this| this.child(measure)) - .children(settle) - .into_any_element(), - ) - }) - } -} - -/// The instance every tree hangs from: a box that lays its children out in a -/// column, or in a row when its `direction` prop says so. -struct Container; - -impl NativeComponent for Container { - fn create(_props: &Map, _cx: &mut NativeContext) -> Self { - Container - } - - fn update( - &mut self, - _props: &Map, - _changed: &[String], - _cx: &mut NativeContext, - ) { - } - - fn render( - &mut self, - props: &Map, - children: Vec, - _window: &mut Window, - _cx: &mut App, - ) -> AnyElement { - let row = props.get("direction").and_then(Value::as_str) == Some("row"); - let element = div().size_full().flex(); - if row { - element.flex_row() - } else { - element.flex_col() - } - .children(children) - .into_any_element() - } -} - -pub fn register() { - register_native_component::(CONTAINER); - register_component_renderer(COMPONENT, Arc::new(NativeRootRenderer)); -} - -/// What the test driver and the accessibility checks see of one instance. -pub(crate) struct InstanceInfo { - pub tag: i32, - pub type_name: String, - pub props: Map, - /// In window coordinates, once the instance has painted. - pub bounds: Option>, - pub children: Vec, - pub root: u32, -} - -thread_local! { - static SYNTHETIC: RefCell = RefCell::new(Synthetic::default()); -} - -/// The tags the test driver gives instances. Fabric's are positive; these are -/// negative, so one number says which kind it is and which instance. -#[derive(Default)] -struct Synthetic { - by_instance: HashMap<(u32, u64), i32>, - by_tag: HashMap, - last: i32, -} - -fn synthetic_tag(root: u32, id: u64) -> i32 { - SYNTHETIC.with(|synthetic| { - let mut synthetic = synthetic.borrow_mut(); - if let Some(tag) = synthetic.by_instance.get(&(root, id)) { - return *tag; - } - synthetic.last -= 1; - let tag = synthetic.last; - synthetic.by_instance.insert((root, id), tag); - synthetic.by_tag.insert(tag, (root, id)); - tag - }) -} - -/// Every instance of the tree `root`, parents first. -pub(crate) fn instances(root: u32) -> Vec { - TREES.with(|trees| { - let trees = trees.borrow(); - let Some(state) = trees.get(&root) else { - return Vec::new(); - }; - state - .tree - .ids() - .into_iter() - .map(|id| InstanceInfo { - tag: synthetic_tag(root, id), - type_name: state.tree.type_of(id).unwrap_or_default().to_string(), - props: state.tree.props_of(id).cloned().unwrap_or_default(), - bounds: state.tree.bounds_of(id), - children: state - .tree - .children(id) - .iter() - .map(|child| synthetic_tag(root, *child)) - .collect(), - root, - }) - .collect() - }) -} - -/// Every tree that has a node showing it. -pub(crate) fn root_ids() -> Vec { - TREES.with(|trees| trees.borrow().keys().copied().collect()) -} - -/// Where a click on the instance with this tag goes: its centre in window -/// coordinates, and the tag of the node that shows its tree, which is what the -/// pointer is over as far as React Native's hit testing goes. -pub(crate) fn pointer_target(tag: i32) -> Option<(gpui::Point, i32)> { - let (root, id) = SYNTHETIC.with(|synthetic| synthetic.borrow().by_tag.get(&tag).copied())?; - TREES.with(|trees| { - let trees = trees.borrow(); - let state = trees.get(&root)?; - let bounds = state.tree.bounds_of(id)?; - Some((bounds.center(), state.tag.get()?)) - }) -} - -/// Lays out its child as itself and keeps the child's layout id, so the size -/// the child was given can be read after a probe layout. -struct Measured { - child: AnyElement, - id: Rc>>, -} - -impl Measured { - fn new(child: AnyElement) -> Self { - Self { - child, - id: Rc::new(Cell::new(None)), - } - } -} - -impl IntoElement for Measured { - type Element = Self; - - fn into_element(self) -> Self { - self - } -} - -impl Element for Measured { - type RequestLayoutState = (); - type PrepaintState = (); - - fn id(&self) -> Option { - None - } - - fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { - None - } - - fn request_layout( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&InspectorElementId>, - window: &mut Window, - cx: &mut App, - ) -> (LayoutId, ()) { - let id = self.child.request_layout(window, cx); - self.id.set(Some(id)); - (id, ()) - } - - fn prepaint( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&InspectorElementId>, - _bounds: gpui::Bounds, - _request_layout: &mut (), - _window: &mut Window, - _cx: &mut App, - ) { - } - - fn paint( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&InspectorElementId>, - _bounds: gpui::Bounds, - _request_layout: &mut (), - _prepaint: &mut (), - _window: &mut Window, - _cx: &mut App, - ) { - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/native_slot/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/native_slot/mod.rs deleted file mode 100644 index 6f24b47cdb..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/native_slot/mod.rs +++ /dev/null @@ -1,263 +0,0 @@ -//! A place in a native tree that shows React Native children. -//! -//! `` inside a native tree is two things. In the tree it is an -//! instance, the placeholder: a box as wide as the tree's layout makes it. Next -//! to the tree, in React Native's, it is a `DesktopNativeSlot` node that holds -//! the children. The placeholder embeds that node, so the node is painted, -//! clipped and hit where the placeholder is, as part of the tree's element -//! tree. Layout goes the other way: the placeholder puts its width into the -//! node's Fabric state, which Yoga lays the node out at without a React render, -//! and the node's height becomes the placeholder's. -//! -//! Where React Native thinks the node is (`measure`, the test driver, the -//! accessibility tree) is corrected by `slot_shift`, a scroll link the placeholder -//! keeps current with where it was painted. - -use std::cell::{Cell, RefCell}; -use std::collections::HashMap; -use std::rc::Rc; -use std::sync::Arc; - -use gpui::{canvas, div, point, prelude::*, px, AnyElement, App, Window}; -use serde_json::{Map, Value}; - -use crate::extensions::{register_component_renderer, ComponentNode, ComponentRenderer}; -use crate::native_tree::{register_native_component, NativeComponent, NativeContext}; - -pub const COMPONENT: &str = "DesktopNativeSlot"; - -/// The type of the placeholder instance in a native tree. -pub const PLACEHOLDER: &str = "NativeSlot"; - -thread_local! { - static HOSTS: std::cell::RefCell> = - std::cell::RefCell::new(std::collections::HashMap::new()); -} - -/// Notes the node that holds slot `slot` of tree `root`, when the node is made. -pub(crate) fn register_host(props: &Value, tag: i32) { - let root = props.get("rootId").and_then(Value::as_u64); - let slot = props.get("slotId").and_then(Value::as_i64); - if let (Some(root), Some(slot)) = (root, slot) { - HOSTS.with(|hosts| hosts.borrow_mut().insert((root as u32, slot), tag)); - } -} - -/// The tags of the nodes that hold the slots of tree `root`, by slot id. A tag -/// whose node is gone is dropped by whoever looks it up. -pub(crate) fn hosts_of(root: u32) -> Vec<(i64, i32)> { - HOSTS.with(|hosts| { - hosts - .borrow() - .iter() - .filter(|((tree, _), _)| *tree == root) - .map(|((_, slot), tag)| (*slot, *tag)) - .collect() - }) -} - -fn slot_tag(root: u32, slot: i64) -> Option { - HOSTS.with(|hosts| hosts.borrow().get(&(root, slot)).copied()) -} - -struct NativeSlotRenderer; - -impl ComponentRenderer for NativeSlotRenderer { - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } -} - -thread_local! { - /// The placeholders whose content has not got the width the tree gave it, - /// with their tree and since when. - static WAITING: RefCell> = RefCell::new(HashMap::new()); -} - -/// How long a placeholder waits for its content before it is shown as it is. -const WAIT_LIMIT: std::time::Duration = std::time::Duration::from_millis(750); - -static NEXT_KEY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); - -/// Whether a slot has shown its first frame less than a moment ago and is still -/// waiting for its content to get the width the tree gave it. A slot that stops -/// being rendered while it waits is forgotten after that moment. -pub(crate) fn layouts_pending() -> bool { - WAITING.with(|waiting| { - waiting - .borrow() - .values() - .any(|(_, since)| since.elapsed() < WAIT_LIMIT) - }) -} - -struct Placeholder { - reported: Rc>, - shown: Rc>, - /// The tree's layout gave the slot no width (its parent is as wide as its - /// content), so the slot takes the width of its content instead. - fit: Rc>, - key: u64, -} - -impl Drop for Placeholder { - fn drop(&mut self) { - let key = self.key; - let _ = WAITING.try_with(|waiting| waiting.borrow_mut().remove(&key)); - } -} - -fn slot_id(props: &Map) -> i64 { - props.get("slotId").and_then(Value::as_i64).unwrap_or(0) -} - -impl NativeComponent for Placeholder { - fn create(_props: &Map, _cx: &mut NativeContext) -> Self { - Self { - reported: Rc::new(Cell::new((-1.0, -1.0))), - shown: Rc::new(Cell::new(false)), - fit: Rc::new(Cell::new(false)), - key: NEXT_KEY.fetch_add(1, std::sync::atomic::Ordering::Relaxed), - } - } - - fn update( - &mut self, - _props: &Map, - _changed: &[String], - _cx: &mut NativeContext, - ) { - } - - fn render( - &mut self, - props: &Map, - _children: Vec, - _window: &mut Window, - cx: &mut App, - ) -> AnyElement { - let host = super::native_root::slot_host(slot_id(props)); - let height = host - .as_ref() - .map(|host| host.read(cx).frame.h) - .unwrap_or(0.0); - let slot_tag = slot_tag(super::native_root::current_root(), slot_id(props)); - let reported = self.reported.clone(); - let fill = props.get("fill").and_then(Value::as_bool).unwrap_or(false); - let measured = host.clone(); - if props.get("fit").and_then(Value::as_bool) == Some(true) { - self.fit.set(true); - } - // A slot as wide as its content does not clip it unless asked: - // content that overflows its own box shows, as it would in React Native. - let clip = props - .get("clip") - .and_then(Value::as_bool) - .unwrap_or(!self.fit.get()); - let mut element = div().relative().w_full().min_h(px(0.0)); - if clip { - element = element.overflow_hidden(); - } - element = if fill { - element.flex_grow(1.0).flex_shrink(1.0).flex_basis(px(0.0)) - } else { - element.flex_shrink(1.0).h(px(height)) - }; - let fit = self.fit.clone(); - if fit.get() { - if let Some(host) = &host { - element = element.w(px(host.read(cx).frame.w)).flex_none(); - } - } - let has_frame = host.as_ref().is_some_and(|host| { - let (width, _) = reported.get(); - width >= 0.0 && (host.read(cx).frame.w - width).abs() < 0.5 - }); - if has_frame { - self.shown.set(true); - } - let key = self.key; - let root = super::native_root::current_root(); - if has_frame { - WAITING.with(|waiting| waiting.borrow_mut().remove(&key)); - } - if let Some(host) = host.filter(|_| self.shown.get()) { - element = element.child(host); - } - element - .child( - canvas( - move |bounds, window, cx| { - // Only a slot that is painted waits for its content, and - // one whose node has not arrived yet waits for it too: - // its content comes a commit after the tree. - if !has_frame { - WAITING.with(|waiting| { - waiting - .borrow_mut() - .entry(key) - .or_insert_with(|| (root, std::time::Instant::now())); - }); - } - let width = f32::from(bounds.size.width); - let height = f32::from(bounds.size.height); - if !fit.get() - && width < 0.5 - && measured - .as_ref() - .is_some_and(|host| host.read(cx).frame.w > 0.5) - { - fit.set(true); - window.refresh(); - return; - } - if let Some(host) = &measured { - let shift = host.read(cx).slot_shift.clone(); - if let Some(shift) = shift { - let origin = host.read(cx).absolute_origin(cx); - let (offset_x, offset_y) = host.read(cx).window_offset(); - let current = shift.get(); - let next = point( - f32::from(origin.x) + current.x - - (f32::from(bounds.origin.x) - offset_x), - f32::from(origin.y) + current.y - - (f32::from(bounds.origin.y) - offset_y), - ); - if next != current { - shift.set(next); - } - } - } - let (last_width, last_height) = reported.get(); - let height_matters = fill && (last_height - height).abs() > 0.01; - let changed = (last_width - width).abs() > 0.01 || height_matters; - if let Some(tag) = slot_tag.filter(|_| changed) { - if rn_gpui_sys::ffi::reportNativeSlotSize( - tag, - !fit.get(), - width, - fill, - height, - ) { - reported.set((width, height)); - } - } - }, - |_, _, _, _| {}, - ) - .absolute() - .size_full(), - ) - .into_any_element() - } -} - -pub fn register() { - register_native_component::(PLACEHOLDER); - register_component_renderer(COMPONENT, Arc::new(NativeSlotRenderer)); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/network/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/network/mod.rs deleted file mode 100644 index 01657e39ae..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/network/mod.rs +++ /dev/null @@ -1,127 +0,0 @@ -//! `Network`: the proxy and DNS settings of the HTTP client that `fetch`, -//! `XMLHttpRequest` and GPUI's image and font loads share. - -use std::sync::Mutex; - -use rn_gpui_module::{ModuleError, ModuleThread}; - -use crate::builtins::rn_gpui_specs::{ - NativeGpuiNetworkEvents, NativeGpuiNetworkSpec, NetworkSettings, -}; - -#[derive(Clone, Default)] -struct Settings { - mode: String, - rules: String, - bypass: String, - dns_over_https: String, -} - -static SETTINGS: Mutex> = Mutex::new(None); - -fn current() -> Settings { - SETTINGS - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .clone() - .unwrap_or_else(|| Settings { - mode: "system".to_string(), - ..Settings::default() - }) -} - -/// Hands the settings to the client, which checks the proxy rules. -fn apply(next: Settings) -> Result<(), ModuleError> { - let error = rn_gpui_sys::ffi::rn_gpui_network_configure( - &next.mode, - &next.rules, - &next.bypass, - &next.dns_over_https, - ); - if !error.is_empty() { - return Err(ModuleError::new(error)); - } - *SETTINGS - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(next); - Ok(()) -} - -/// The servers are one URL per line, and each has to be `https`, which is all -/// libcurl takes. -fn check_doh(urls: &str) -> Result<(), ModuleError> { - for url in urls.lines().filter(|line| !line.is_empty()) { - if !url.starts_with("https://") { - return Err(ModuleError::new(format!( - "a DNS-over-HTTPS URL must start with https://, got \"{url}\"" - ))); - } - } - Ok(()) -} - -struct NetworkModule; - -impl NativeGpuiNetworkSpec for NetworkModule { - const THREAD: ModuleThread = ModuleThread::Own; - - fn new(_events: NativeGpuiNetworkEvents) -> Self { - Self - } - - async fn set_proxy( - &self, - mode: String, - rules: String, - bypass: String, - ) -> Result<(), ModuleError> { - apply(Settings { - mode, - rules, - bypass, - ..current() - }) - } - - async fn set_dns_over_https(&self, url: String) -> Result<(), ModuleError> { - check_doh(&url)?; - apply(Settings { - dns_over_https: url, - ..current() - }) - } - - async fn get_settings(&self) -> Result { - let settings = current(); - Ok(NetworkSettings { - mode: settings.mode, - rules: settings.rules, - bypass: settings.bypass, - dns_over_https: settings.dns_over_https, - }) - } - - async fn proxy_for_url(&self, url: String) -> Result { - Ok(rn_gpui_sys::ffi::rn_gpui_network_proxy_for(&url)) - } -} - -pub fn register() { - rn_gpui_module::register( - crate::builtins::rn_gpui_specs::native_gpui_network_module::(), - ); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_dns_over_https_url_has_to_be_https() { - assert!(check_doh("").is_ok()); - assert!(check_doh("https://dns.example/dns-query").is_ok()); - assert!(check_doh("http://dns.example/dns-query").is_err()); - assert!(check_doh("https://a.example/q\nhttps://b.example/q").is_ok()); - assert!(check_doh("https://a.example/q\nhttp://b.example/q").is_err()); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/perf_monitor/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/perf_monitor/mod.rs deleted file mode 100644 index 44b15b157a..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/perf_monitor/mod.rs +++ /dev/null @@ -1,63 +0,0 @@ -use rn_gpui_module::{FromValue, ModuleError, ModuleThread, Path, Value}; - -use crate::builtins::main_thread::on_main; -use crate::builtins::rn_gpui_specs::{ - NativeGpuiPerfMonitorEvents, NativeGpuiPerfMonitorSpec, PerfMetrics, PerfToggle, -}; - -const MODULE: &str = "GpuiPerfMonitor"; - -struct PerfMonitorModule; - -fn typed(method: &'static str, value: &serde_json::Value) -> Result { - let mut path = Path::result(MODULE, method); - let value = json_value(value); - T::from_value(value, &mut path).map_err(|error| ModuleError::new(error.message)) -} - -fn json_value(value: &serde_json::Value) -> Value { - match value { - serde_json::Value::Null => Value::Null, - serde_json::Value::Bool(flag) => Value::Bool(*flag), - serde_json::Value::Number(number) => { - number.as_f64().map(Value::Number).unwrap_or(Value::Null) - } - serde_json::Value::String(text) => Value::String(text.clone()), - serde_json::Value::Array(items) => Value::Array(items.iter().map(json_value).collect()), - serde_json::Value::Object(fields) => Value::Object( - fields - .iter() - .map(|(key, item)| (key.clone(), json_value(item))) - .collect(), - ), - } -} - -impl NativeGpuiPerfMonitorSpec for PerfMonitorModule { - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(_events: NativeGpuiPerfMonitorEvents) -> Self { - Self - } - - async fn perf_monitor_set_enabled(&self, enabled: bool) -> Result { - let value = - on_main(move |cx| crate::desktop::perf_monitor::set_enabled(cx, enabled)).await?; - typed("perfMonitorSetEnabled", &value) - } - - async fn perf_monitor_get_metrics(&self) -> Result { - let value = on_main(|cx| crate::desktop::perf_monitor::metrics(cx)).await?; - typed("perfMonitorGetMetrics", &value) - } - - fn add_listener(&self, _event_name: String) {} - - fn remove_listeners(&self, _count: f64) {} -} - -pub fn register() { - rn_gpui_module::register( - crate::builtins::rn_gpui_specs::native_gpui_perf_monitor_module::(), - ); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/scrollview/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/scrollview/mod.rs deleted file mode 100644 index d6f66467c8..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/scrollview/mod.rs +++ /dev/null @@ -1,49 +0,0 @@ -use serde_json::Value; - -use crate::extensions::{ - register_component_renderer, ComponentNode, ComponentRenderer, ScrollSpec, -}; -use gpui::{AnyElement, App, Window}; - -const SCROLL_EVENT: &str = "topScroll"; - -struct ScrollViewRenderer; - -impl ComponentRenderer for ScrollViewRenderer { - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } - - fn scroll(&self, props: &Value) -> Option { - let number = |key: &str| props.get(key).and_then(Value::as_f64).unwrap_or(0.0) as f32; - Some(ScrollSpec { - content_size: (number("contentWidth"), number("contentHeight")), - horizontal: props - .get("horizontal") - .and_then(Value::as_bool) - .unwrap_or(false), - enabled: props - .get("enabled") - .and_then(Value::as_bool) - .unwrap_or(true), - indicator: props - .get("indicator") - .and_then(Value::as_bool) - .unwrap_or(true), - offset: (number("offsetX"), number("offsetY")), - event: Some(SCROLL_EVENT.to_string()), - snap: crate::scroll_snap::SnapSpec::from_props(props), - deceleration: crate::scroll_momentum::deceleration_from(props), - event_throttle_ms: number("scrollEventThrottle"), - }) - } -} - -pub fn register() { - register_component_renderer("ScrollView", std::sync::Arc::new(ScrollViewRenderer)); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/settings/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/settings/mod.rs deleted file mode 100644 index 6b45b8c118..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/settings/mod.rs +++ /dev/null @@ -1,125 +0,0 @@ -//! `Settings`: a persistent key-value store in a JSON file in the app's data -//! directory. - -use std::path::PathBuf; - -use rn_gpui_module::{ModuleError, ModuleThread, Value}; -use serde_json::Map; - -use crate::builtins::rn_gpui_specs::{ - NativeSettingsManagerEvents, NativeSettingsManagerSpec, SettingsConstants, -}; - -struct SettingsModule; - -fn value_json(value: Value) -> serde_json::Value { - match value { - Value::Null | Value::Callback(_) => serde_json::Value::Null, - Value::Bool(flag) => serde_json::Value::Bool(flag), - Value::Number(number) => serde_json::Number::from_f64(number) - .map(serde_json::Value::Number) - .unwrap_or(serde_json::Value::Null), - Value::String(text) => serde_json::Value::String(text), - Value::Array(items) => { - serde_json::Value::Array(items.into_iter().map(value_json).collect()) - } - Value::Object(fields) => serde_json::Value::Object( - fields - .into_iter() - .map(|(key, item)| (key, value_json(item))) - .collect(), - ), - Value::Buffer(bytes) => serde_json::Value::Array( - bytes - .into_iter() - .map(|byte| serde_json::Value::Number(byte.into())) - .collect(), - ), - } -} - -fn json_value(value: &serde_json::Value) -> Value { - match value { - serde_json::Value::Null => Value::Null, - serde_json::Value::Bool(flag) => Value::Bool(*flag), - serde_json::Value::Number(number) => { - number.as_f64().map(Value::Number).unwrap_or(Value::Null) - } - serde_json::Value::String(text) => Value::String(text.clone()), - serde_json::Value::Array(items) => Value::Array(items.iter().map(json_value).collect()), - serde_json::Value::Object(fields) => Value::Object( - fields - .iter() - .map(|(key, item)| (key.clone(), json_value(item))) - .collect(), - ), - } -} - -fn settings_path() -> PathBuf { - let app_id = crate::desktop::snapshot_app_id(); - let safe_id = crate::desktop::app_dir::safe_id(&app_id); - #[cfg(feature = "visual-capture")] - if let Some(window_state) = std::env::var_os("RN_GPUI_WINDOW_STATE") { - return PathBuf::from(window_state).with_extension("settings.json"); - } - crate::desktop::app_dir::app_dir().join(format!("{safe_id}-settings.json")) -} - -fn load() -> Map { - std::fs::read_to_string(settings_path()) - .ok() - .and_then(|text| serde_json::from_str(&text).ok()) - .unwrap_or_default() -} - -fn update(change: impl FnOnce(&mut Map)) { - let mut settings = load(); - change(&mut settings); - let path = settings_path(); - let saved = path - .parent() - .map_or(Ok(()), std::fs::create_dir_all) - .and_then(|()| { - let temporary = path.with_extension("json.tmp"); - std::fs::write(&temporary, serde_json::Value::Object(settings).to_string())?; - std::fs::rename(&temporary, &path) - }); - if let Err(error) = saved { - log::warn!("Settings: could not save: {error}"); - } -} - -impl NativeSettingsManagerSpec for SettingsModule { - const THREAD: ModuleThread = ModuleThread::Own; - - fn new(_events: NativeSettingsManagerEvents) -> Self { - Self - } - - fn get_constants(&self) -> Result { - Ok(SettingsConstants { - settings: json_value(&serde_json::Value::Object(load())), - }) - } - - fn set_values(&self, values: Value) { - if let serde_json::Value::Object(values) = value_json(values) { - update(|settings| settings.extend(values)); - } - } - - fn delete_values(&self, keys: Vec) { - update(|settings| { - for key in keys { - settings.remove(&key); - } - }); - } -} - -pub fn register() { - rn_gpui_module::register( - crate::builtins::rn_gpui_specs::native_settings_manager_module::(), - ); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/share/mac.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/share/mac.rs deleted file mode 100644 index 651c000b96..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/share/mac.rs +++ /dev/null @@ -1,186 +0,0 @@ -//! `NSSharingServicePicker` below the middle of the window. - -use cocoa::base::{id, nil}; -use cocoa::foundation::{NSArray, NSPoint, NSRect, NSSize, NSString}; -use objc::declare::ClassDecl; -use objc::runtime::{Class, Object, Sel}; -use objc::{class, msg_send, sel, sel_impl}; -use std::cell::RefCell; -use std::ffi::c_void; -use std::sync::Once; - -type Done = Box)>; - -thread_local! { - static OPEN: RefCell = const { RefCell::new(false) }; - static DELEGATE: RefCell> = const { RefCell::new(None) }; -} - -fn delegate_class() -> &'static Class { - static REGISTER: Once = Once::new(); - REGISTER.call_once(|| { - let mut declaration = ClassDecl::new("RNGpuiShareDelegate", class!(NSObject)) - .expect("the share delegate class is registered once"); - declaration.add_ivar::<*mut c_void>("done"); - // SAFETY: the method's signature matches `NSSharingServicePickerDelegate`. - unsafe { - declaration.add_method( - sel!(sharingServicePicker:didChooseSharingService:), - did_choose as extern "C" fn(&Object, Sel, id, id), - ); - } - declaration.register(); - }); - Class::get("RNGpuiShareDelegate").expect("the share delegate class exists") -} - -extern "C" fn did_choose(this: &Object, _selector: Sel, _picker: id, service: id) { - OPEN.with(|open| *open.borrow_mut() = false); - // SAFETY: `done` holds the `Box` leaked in `present`; it is taken - // once, here, and the pointer cleared. - let done = unsafe { - let pointer: *mut c_void = *this.get_ivar("done"); - let this = this as *const Object as *mut Object; - (*this).set_ivar("done", std::ptr::null_mut::()); - if pointer.is_null() { - return; - } - Box::from_raw(pointer.cast::()) - }; - let title = if service.is_null() { - None - } else { - // SAFETY: `service` is a live `NSSharingService`. - unsafe { - let title: id = msg_send![service, title]; - let bytes: *const std::os::raw::c_char = msg_send![title, UTF8String]; - (!bytes.is_null()).then(|| { - std::ffi::CStr::from_ptr(bytes) - .to_string_lossy() - .into_owned() - }) - } - }; - (*done)(title); -} - -/// Opens the picker; `done` gets the chosen service's name, or `None` when it -/// was dismissed. -pub fn present( - window: &gpui::Window, - message: Option, - url: Option, - anchor: Option<(f32, f32, f32, f32)>, - done: Done, -) { - let Ok(native) = crate::desktop::platform_window::ns_window(window) else { - done(None); - return; - }; - // SAFETY: AppKit is only messaged from the main thread, where GPUI runs this. - unsafe { - let mut items: Vec = Vec::new(); - if let Some(message) = &message { - items.push(NSString::alloc(nil).init_str(message)); - } - if let Some(url) = &url { - let text = NSString::alloc(nil).init_str(url); - let ns_url: id = msg_send![class!(NSURL), URLWithString: text]; - items.push(if ns_url == nil { text } else { ns_url }); - } - if items.is_empty() { - done(None); - return; - } - let array = NSArray::arrayWithObjects(nil, &items); - let picker: id = msg_send![class!(NSSharingServicePicker), alloc]; - let picker: id = msg_send![picker, initWithItems: array]; - let delegate: id = msg_send![delegate_class(), new]; - let boxed: *mut Done = Box::into_raw(Box::new(done)); - (*delegate).set_ivar("done", boxed.cast::()); - let _: () = msg_send![picker, setDelegate: delegate]; - DELEGATE.with(|slot| *slot.borrow_mut() = Some(delegate)); - let view: id = msg_send![native, contentView]; - let bounds: NSRect = msg_send![view, bounds]; - let flipped: bool = msg_send![view, isFlipped]; - let anchor = match anchor { - Some((x, y, width, height)) => { - // The window's coordinates run down from the top; a view that - // is not flipped runs up from the bottom. - let y = if flipped { - f64::from(y) - } else { - bounds.size.height - f64::from(y) - f64::from(height) - }; - NSRect::new( - NSPoint::new(f64::from(x), y), - NSSize::new(f64::from(width).max(1.0), f64::from(height).max(1.0)), - ) - } - None => NSRect::new( - NSPoint::new(bounds.size.width / 2.0, bounds.size.height / 2.0), - NSSize::new(1.0, 1.0), - ), - }; - #[cfg(feature = "test-driver")] - LAST_ANCHOR.with(|last| { - *last.borrow_mut() = Some(( - anchor.origin.x as f32, - anchor.origin.y as f32, - anchor.size.width as f32, - anchor.size.height as f32, - flipped, - )); - }); - OPEN.with(|open| *open.borrow_mut() = true); - // NSMinYEdge: the menu opens below the anchor. - let _: () = - msg_send![picker, showRelativeToRect: anchor ofView: view preferredEdge: 1usize]; - } -} - -#[cfg(feature = "test-driver")] -thread_local! { - static LAST_ANCHOR: std::cell::RefCell> = - const { std::cell::RefCell::new(None) }; -} - -/// The view rectangle the picker was last shown relative to, and whether the -/// view is flipped. -#[cfg(feature = "test-driver")] -pub fn last_anchor() -> Option<(f32, f32, f32, f32, bool)> { - LAST_ANCHOR.with(|last| *last.borrow()) -} - -/// Whether the picker is on screen. -#[cfg(feature = "test-driver")] -pub fn is_open() -> bool { - OPEN.with(|open| *open.borrow()) -} - -/// Reports the picker's delegate callback as the OS makes it: a chosen service -/// by its `NSSharingServiceName`, or `None` for a dismissal. The sheet itself is -/// not driven, because its menu tracking cannot be reached by synthetic events. -#[cfg(feature = "test-driver")] -pub fn simulate_choice(service_name: Option<&str>) -> bool { - let Some(delegate) = DELEGATE.with(|delegate| *delegate.borrow()) else { - return false; - }; - // SAFETY: main thread; the delegate was leaked in `present` and is alive. - unsafe { - let service: id = match service_name { - Some(name) => { - let name = NSString::alloc(nil).init_str(name); - msg_send![class!(NSSharingService), sharingServiceNamed: name] - } - None => nil, - }; - did_choose( - &*delegate, - sel!(sharingServicePicker:didChooseSharingService:), - nil, - service, - ); - } - true -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/share/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/share/mod.rs deleted file mode 100644 index 2ee471df23..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/share/mod.rs +++ /dev/null @@ -1,254 +0,0 @@ -//! `Share`: the system share sheet on macOS and Windows, and a small dialog on -//! Linux, which has none: copy to the clipboard or send by email. - -use rn_gpui_module::{ModuleError, ModuleThread}; - -use crate::builtins::main_thread::on_main; -use crate::builtins::rn_gpui_specs::{ - NativeGpuiShareEvents, NativeGpuiShareSpec, ShareItems, ShareResult, -}; - -#[cfg(target_os = "macos")] -pub(crate) mod mac; -#[cfg(target_os = "windows")] -pub(crate) mod win; - -struct ShareModule; - -/// What goes on the clipboard when there is no share sheet. -#[cfg_attr(not(target_os = "linux"), allow(dead_code))] -fn clipboard_text(message: Option<&str>, url: Option<&str>) -> String { - match (message, url) { - (Some(message), Some(url)) if !message.contains(url) => format!("{message}\n{url}"), - (Some(message), _) => message.to_string(), - (None, Some(url)) => url.to_string(), - (None, None) => String::new(), - } -} - -/// `mailto:` for the content, with the subject and body percent-encoded. -#[cfg_attr(not(target_os = "linux"), allow(dead_code))] -fn mailto(subject: Option<&str>, body: &str) -> String { - fn encode(text: &str) -> String { - let mut out = String::new(); - for byte in text.bytes() { - match byte { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { - out.push(byte as char) - } - _ => out.push_str(&format!("%{byte:02X}")), - } - } - out - } - match subject { - Some(subject) => format!("mailto:?subject={}&body={}", encode(subject), encode(body)), - None => format!("mailto:?body={}", encode(body)), - } -} - -/// The window rectangle `(x, y, width, height)` of the node with this tag. -#[cfg(target_os = "macos")] -fn anchor_rect(cx: &gpui::App, tag: i32) -> Option<(f32, f32, f32, f32)> { - let store = crate::store::store_from(cx)?; - let entity = store.read(cx).nodes.get(&tag)?.clone(); - let node = entity.read(cx); - let origin = node.absolute_origin(cx); - let (scale_x, scale_y) = node.cumulative_scale(cx); - Some(( - f32::from(origin.x), - f32::from(origin.y), - node.frame.w * scale_x, - node.frame.h * scale_y, - )) -} - -impl NativeGpuiShareSpec for ShareModule { - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(_events: NativeGpuiShareEvents) -> Self { - Self - } - - async fn share(&self, items: ShareItems) -> Result { - let (sender, receiver) = futures::channel::oneshot::channel::>>(); - let sender = std::sync::Mutex::new(Some(sender)); - let message = items.message.clone(); - let url = items.url.clone(); - #[cfg(not(target_os = "macos"))] - let subject = items.subject.clone(); - let anchor_tag = items.anchor.map(|tag| tag as i32); - let _ = on_main(move |cx| { - // `None` is a dismissal; `Some` is a share, with the activity if the - // system names one. - let finish = move |outcome: Option>| { - if let Some(sender) = sender.lock().expect("share sender poisoned").take() { - let _ = sender.send(outcome); - } - }; - #[cfg(target_os = "macos")] - { - use gpui::AppContext as _; - let mut finish = Some(finish); - let window = cx - .try_global::() - .map(|store| store.0.clone()) - .map(|store| store.read(cx).window); - let anchor = anchor_tag.and_then(|tag| anchor_rect(cx, tag)); - let shown = window.and_then(|window| { - cx.update_window(window, |_root, window, _cx| { - mac::present( - window, - message.clone(), - url.clone(), - anchor, - Box::new({ - let finish = finish.take().expect("finish taken once"); - move |activity: Option| finish(activity.map(Some)) - }), - ); - }) - .ok() - }); - if shown.is_none() { - if let Some(finish) = finish { - finish(None); - } - } - } - #[cfg(target_os = "windows")] - { - use gpui::AppContext as _; - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - let _ = anchor_tag; - let finish = std::sync::Arc::new(finish); - let window = cx - .try_global::() - .map(|store| store.0.clone()) - .map(|store| store.read(cx).window); - let hwnd = window - .and_then(|window| { - cx.update_window(window, |_root, window, _cx| { - match HasWindowHandle::window_handle(window) - .map(|handle| handle.as_raw()) - { - Ok(RawWindowHandle::Win32(handle)) => Some(handle.hwnd.get()), - _ => None, - } - }) - .ok() - }) - .flatten(); - // Like Android's chooser, the share is reported as soon as Windows - // asks for the content; the UI gives no sign that it was dismissed. - let shown = hwnd.is_some_and(|hwnd| { - let requested = finish.clone(); - win::present( - hwnd, - subject.as_deref().unwrap_or("Share"), - message.as_deref(), - url.as_deref(), - move || requested(Some(None)), - ) - .map_err(|error| log::warn!("share UI unavailable: {error}")) - .is_ok() - }); - if !shown { - finish(None); - } - } - #[cfg(target_os = "linux")] - { - let _ = anchor_tag; - let text = clipboard_text(message.as_deref(), url.as_deref()); - let request = crate::builtins::alert::Request { - title: subject.clone().unwrap_or_else(|| "Share".to_string()), - message: Some(text.clone()).filter(|text| !text.is_empty()), - buttons: vec![ - ("copy".to_string(), "Copy".to_string()), - ("email".to_string(), "Email".to_string()), - ("cancel".to_string(), "Cancel".to_string()), - ], - cancel: Some(2), - destructive: None, - preferred: Some(0), - cancelable: true, - input: crate::builtins::alert::Input::None, - default_value: String::new(), - dark: None, - }; - crate::builtins::alert::dialog::present( - cx, - request, - Box::new(move |outcome| { - use crate::builtins::alert::Outcome; - let Outcome::Button { position, .. } = outcome else { - return finish(None); - }; - crate::desktop::post_to_main(Box::new(move |cx: &mut gpui::App| { - match position { - 0 => { - cx.write_to_clipboard(gpui::ClipboardItem::new_string(text)); - finish(Some(Some("copy".to_string()))); - } - 1 => { - cx.open_url(&mailto(subject.as_deref(), &text)); - finish(Some(Some("email".to_string()))); - } - _ => finish(None), - } - })); - }), - ); - } - }) - .await?; - let activity = receiver - .await - .map_err(|_| ModuleError::new("the share sheet was closed"))?; - Ok(match activity { - Some(activity_type) => ShareResult { - action: "sharedAction".to_string(), - activity_type, - }, - None => ShareResult { - action: "dismissedAction".to_string(), - activity_type: None, - }, - }) - } -} - -pub fn register() { - rn_gpui_module::register(crate::builtins::rn_gpui_specs::native_gpui_share_module::< - ShareModule, - >()); -} - -#[cfg(test)] -mod tests { - use super::{clipboard_text, mailto}; - - #[test] - fn the_mail_link_encodes_the_subject_and_body() { - assert_eq!( - mailto(Some("A & B"), "hi\nhttps://x/?a=1"), - "mailto:?subject=A%20%26%20B&body=hi%0Ahttps%3A%2F%2Fx%2F%3Fa%3D1" - ); - assert_eq!(mailto(None, "é"), "mailto:?body=%C3%A9"); - } - - #[test] - fn the_clipboard_gets_the_message_and_the_link_once() { - assert_eq!( - clipboard_text(Some("hi"), Some("https://x")), - "hi\nhttps://x" - ); - assert_eq!( - clipboard_text(Some("see https://x"), Some("https://x")), - "see https://x" - ); - assert_eq!(clipboard_text(None, Some("https://x")), "https://x"); - assert_eq!(clipboard_text(Some("hi"), None), "hi"); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/share/win.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/share/win.rs deleted file mode 100644 index f2de62881c..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/share/win.rs +++ /dev/null @@ -1,63 +0,0 @@ -//! The Windows share UI, opened with `IDataTransferManagerInterop`. - -use std::cell::RefCell; -use windows::{ - core::{factory, Ref, HSTRING}, - ApplicationModel::DataTransfer::{DataRequestedEventArgs, DataTransferManager}, - Foundation::{TypedEventHandler, Uri}, - Win32::{Foundation::HWND, UI::Shell::IDataTransferManagerInterop}, -}; - -thread_local! { - /// The handler of the previous share, which is removed before the next one is - /// added: a manager keeps every handler it is given. - static PREVIOUS: RefCell> = const { RefCell::new(None) }; -} - -/// Opens the share UI for `hwnd`. `requested` is called when Windows asks for the -/// content, which is when the user has chosen a target. Fails when the UI cannot -/// be shown or there is nothing to share. -pub fn present( - hwnd: isize, - title: &str, - message: Option<&str>, - url: Option<&str>, - requested: impl Fn() + Send + 'static, -) -> windows::core::Result<()> { - if message.is_none() && url.is_none() { - return Err(windows::core::Error::from_hresult(windows::core::HRESULT( - 0x8007_0057_u32 as i32, - ))); - } - let interop = factory::()?; - // SAFETY: `hwnd` is the live handle of a window owned by this thread. - let manager: DataTransferManager = unsafe { interop.GetForWindow(HWND(hwnd as _))? }; - PREVIOUS.with(|previous| { - if let Some((old, token)) = previous.borrow_mut().take() { - let _ = old.RemoveDataRequested(token); - } - }); - let title = HSTRING::from(title); - let message = message.map(HSTRING::from); - let url = url.map(HSTRING::from); - let token = manager.DataRequested(&TypedEventHandler::new( - move |_: Ref<'_, DataTransferManager>, args: Ref<'_, DataRequestedEventArgs>| { - let Some(args) = args.as_ref() else { - return Ok(()); - }; - let data = args.Request()?.Data()?; - data.Properties()?.SetTitle(&title)?; - if let Some(message) = &message { - data.SetText(message)?; - } - if let Some(url) = &url { - data.SetWebLink(&Uri::CreateUri(url)?)?; - } - requested(); - Ok(()) - }, - ))?; - PREVIOUS.with(|previous| *previous.borrow_mut() = Some((manager, token))); - // SAFETY: the same window handle, on the thread that owns it. - unsafe { interop.ShowShareUIForWindow(HWND(hwnd as _)) } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/shortcut_scope/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/shortcut_scope/mod.rs deleted file mode 100644 index 9bbba2cea4..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/shortcut_scope/mod.rs +++ /dev/null @@ -1,115 +0,0 @@ -//! A named scope for keyboard shortcuts. -//! -//! The component paints nothing of its own: core builds the box, the style and -//! the children exactly as it does for a `View`, and this only adds the node's -//! key context. Scopes nest, and GPUI resolves a keystroke against the contexts -//! on the focused element's dispatch path — so a binding in an inner scope -//! outranks one in an outer scope without any of that logic living here. -//! -//! The action listener lives in `node_view.rs` beside the element, because a -//! `ComponentRenderer` never sees the element it would have to attach to. - -use std::sync::Arc; - -use gpui::{AnyElement, App, Window}; -use serde_json::Value; - -use crate::desktop::keymap; -use crate::extensions::{register_component_renderer, ComponentNode, ComponentRenderer}; - -pub const COMPONENT: &str = "DesktopShortcutScope"; - -/// The scope a `ShortcutScope` node declares, or an empty string when its props -/// carry no usable name. -/// -/// A scope with no name claims nothing: it still groups its children, but no -/// shortcut can be registered into it, which is better than every unnamed scope -/// sharing one context and overriding the others. -pub fn scope_name(node: &ComponentNode) -> String { - node.props - .get("name") - .and_then(Value::as_str) - .unwrap_or_default() - .to_string() -} - -struct ShortcutScopeRenderer; - -impl ComponentRenderer for ShortcutScopeRenderer { - /// Core paints the element, so the renderer claims no appearance at all. - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - None - } - - fn key_context(&self, node: &ComponentNode) -> Option { - let name = scope_name(node); - if name.is_empty() { - return None; - } - Some(keymap::scope_context(&name)) - } -} - -pub fn register() { - register_component_renderer("DesktopShortcutScope", Arc::new(ShortcutScopeRenderer)); -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::Arc; - - fn node(props: Value) -> ComponentNode { - ComponentNode { - component: COMPONENT.to_string(), - tag: 1, - frame: rn_gpui_sys::ffi::RectF { - x: 0.0, - y: 0.0, - w: 100.0, - h: 100.0, - }, - scale: (1.0, 1.0), - props: Arc::new(props), - parent: None, - children: Vec::new(), - } - } - - #[test] - fn a_named_scope_gets_its_context() { - let renderer = ShortcutScopeRenderer; - assert_eq!( - renderer.key_context(&node(serde_json::json!({"name": "editor"}))), - Some("rn-scope-editor".to_string()) - ); - } - - #[test] - fn an_unnamed_scope_claims_no_context() { - let renderer = ShortcutScopeRenderer; - assert_eq!(renderer.key_context(&node(serde_json::json!({}))), None); - assert_eq!( - renderer.key_context(&node(serde_json::json!({"name": ""}))), - None - ); - assert_eq!( - renderer.key_context(&node(serde_json::json!({"name": 7}))), - None - ); - } - - #[test] - fn scope_names_are_read_from_the_parsed_props() { - assert_eq!( - scope_name(&node(serde_json::json!({"name": "files"}))), - "files" - ); - assert_eq!(scope_name(&node(serde_json::json!({}))), ""); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/shortcuts/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/shortcuts/mod.rs deleted file mode 100644 index 8220b1ed4e..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/shortcuts/mod.rs +++ /dev/null @@ -1,130 +0,0 @@ -//! The `GpuiShortcuts` TurboModule: how the JS registry installs its list. -//! -//! Every method is a thin wrapper over `desktop::keymap`, which owns the -//! shortcuts and the keymap rebuild. The list is the *only* thing JS sends: -//! parsing, precedence and dispatch are native, so a shortcut behaves the same -//! whether JS registered it through `useShortcut` or `Shortcut.addHandler`. - -use rn_gpui_module::{FromValue, ModuleError, ModuleThread, Path, Value}; - -use crate::builtins::main_thread::on_main; -use crate::builtins::rn_gpui_specs::{ - NativeGpuiShortcutsEvents, NativeGpuiShortcutsSpec, ShortcutFailure, ShortcutInstallResult, - ShortcutSpec, -}; -use crate::desktop::keymap; - -const MODULE: &str = "GpuiShortcuts"; - -struct ShortcutsModule; - -fn value_json(value: Value) -> serde_json::Value { - match value { - Value::Null | Value::Callback(_) => serde_json::Value::Null, - Value::Bool(flag) => serde_json::Value::Bool(flag), - Value::Number(number) => serde_json::Number::from_f64(number) - .map(serde_json::Value::Number) - .unwrap_or(serde_json::Value::Null), - Value::String(text) => serde_json::Value::String(text), - Value::Array(items) => { - serde_json::Value::Array(items.into_iter().map(value_json).collect()) - } - Value::Object(fields) => serde_json::Value::Object( - fields - .into_iter() - .map(|(key, item)| (key, value_json(item))) - .collect(), - ), - Value::Buffer(bytes) => serde_json::Value::Array( - bytes - .into_iter() - .map(|byte| serde_json::Value::Number(byte.into())) - .collect(), - ), - } -} - -fn json_value(value: &serde_json::Value) -> Value { - match value { - serde_json::Value::Null => Value::Null, - serde_json::Value::Bool(flag) => Value::Bool(*flag), - serde_json::Value::Number(number) => { - number.as_f64().map(Value::Number).unwrap_or(Value::Null) - } - serde_json::Value::String(text) => Value::String(text.clone()), - serde_json::Value::Array(items) => Value::Array(items.iter().map(json_value).collect()), - serde_json::Value::Object(fields) => Value::Object( - fields - .iter() - .map(|(key, item)| (key.clone(), json_value(item))) - .collect(), - ), - } -} - -fn typed(method: &'static str, value: &serde_json::Value) -> Result { - let mut path = Path::result(MODULE, method); - T::from_value(json_value(value), &mut path).map_err(|error| ModuleError::new(error.message)) -} - -impl NativeGpuiShortcutsSpec for ShortcutsModule { - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(_events: NativeGpuiShortcutsEvents) -> Self { - Self - } - - async fn shortcut_install( - &self, - shortcuts: Vec, - ) -> Result { - // The generated spec struct is turned back into the JSON the parser - // reads, so there is one implementation of "what a shortcut is" and the - // module cannot drift from `keymap::Shortcut`. - let json = serde_json::Value::Array( - shortcuts - .into_iter() - .map(|spec| { - serde_json::json!({ - "id": spec.id, - "keys": spec.keys, - "scope": spec.scope, - "enabled": spec.enabled, - "allowInTextInput": spec.allow_in_text_input, - "global": spec.global, - }) - }) - .collect(), - ); - // Bad input is reported, not swallowed: an app that spelled a key wrong - // has a shortcut that does not fire, and the error says which. - let parsed = keymap::parse_shortcuts(&json).map_err(ModuleError::new)?; - let installed = parsed.len(); - let failed = on_main(move |cx| keymap::install(cx, parsed)).await?; - Ok(ShortcutInstallResult { - installed: installed as f64, - failed: failed - .into_iter() - .map(|failure| ShortcutFailure { - id: failure.id, - reason: failure.reason, - }) - .collect(), - }) - } - - async fn shortcut_get(&self) -> Result, ModuleError> { - let value = on_main(|cx| keymap::shortcuts_json(cx)).await?; - typed(MODULE, &value) - } - - fn add_listener(&self, _event_name: String) {} - - fn remove_listeners(&self, _count: f64) {} -} - -pub fn register() { - rn_gpui_module::register( - crate::builtins::rn_gpui_specs::native_gpui_shortcuts_module::(), - ); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/switch/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/switch/mod.rs deleted file mode 100644 index 0f73f90787..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/switch/mod.rs +++ /dev/null @@ -1,366 +0,0 @@ -//! `Switch`: a track and a thumb in the style of the host OS. -//! -//! The value shown is native: a click or Space flips it, redraws and reports -//! `onChange`; React Native's JS answers a refusal with `setValue`. A new `value` -//! prop from JS replaces it. - -use std::collections::HashMap; -use std::sync::{Arc, Mutex, OnceLock}; -use std::time::{Duration, Instant}; - -use gpui::{div, prelude::*, px, AnyElement, App, Window}; -use serde_json::Value; - -use crate::extensions::input::{ - ButtonSet, CursorStyle, InputContext, InputSpec, MouseEvent, Propagation, -}; -use crate::extensions::{ - register_component_renderer, ComponentNode, ComponentRenderer, StoreHandle, -}; -use crate::style::color; - -const SLIDE: Duration = Duration::from_millis(150); - -struct State { - value: bool, - last_prop: bool, - from: f32, - started: Instant, -} - -fn states() -> &'static Mutex> { - static STATES: OnceLock>> = OnceLock::new(); - STATES.get_or_init(|| Mutex::new(HashMap::new())) -} - -fn eased(elapsed: Duration) -> f32 { - let t = (elapsed.as_secs_f32() / SLIDE.as_secs_f32()).clamp(0.0, 1.0); - 1.0 - (1.0 - t) * (1.0 - t) -} - -impl State { - fn position(&self, now: Instant) -> f32 { - let target = if self.value { 1.0 } else { 0.0 }; - self.from + (target - self.from) * eased(now.saturating_duration_since(self.started)) - } - - fn animating(&self, now: Instant) -> bool { - now.saturating_duration_since(self.started) < SLIDE - } - - fn set(&mut self, value: bool, animate: bool, now: Instant) { - if self.value == value { - return; - } - let from = self.position(now); - self.value = value; - self.from = from; - self.started = if animate { now } else { now - SLIDE }; - } -} - -fn prop_value(props: &Value) -> bool { - props.get("value").and_then(Value::as_bool).unwrap_or(false) -} - -fn disabled(props: &Value) -> bool { - props - .get("disabled") - .and_then(Value::as_bool) - .unwrap_or(false) -} - -fn argb(props: &Value, keys: &[&str]) -> Option { - keys.iter().find_map(|key| { - props - .get(*key) - .and_then(Value::as_u64) - .map(|value| value as u32) - .filter(|value| *value != 0) - }) -} - -/// The value now shown and where the thumb is, after folding in a new `value` -/// prop from JS. -fn sync(tag: i32, props: &Value, animate: bool, now: Instant) -> (bool, f32, bool) { - let prop = prop_value(props); - let mut states = states().lock().expect("switch states poisoned"); - let state = states.entry(tag).or_insert_with(|| State { - value: prop, - last_prop: prop, - from: if prop { 1.0 } else { 0.0 }, - started: now - SLIDE, - }); - if state.last_prop != prop { - state.last_prop = prop; - state.set(prop, animate, now); - } - (state.value, state.position(now), state.animating(now)) -} - -fn accent() -> u32 { - if cfg!(target_os = "macos") { - 0xFF0A84FF - } else if cfg!(target_os = "windows") { - 0xFF0067C0 - } else { - 0xFF3584E4 - } -} - -fn off_track() -> u32 { - if cfg!(target_os = "macos") { - 0xFFD1D1D6 - } else if cfg!(target_os = "windows") { - 0xFF8A8A8A - } else { - 0xFFC0BFBC - } -} - -struct SwitchRenderer; - -impl ComponentRenderer for SwitchRenderer { - fn render(&self, _: &ComponentNode, _: &mut Window, _: &mut App) -> Option { - None - } - - fn content( - &self, - node: &ComponentNode, - window: &mut Window, - cx: &mut App, - ) -> Option { - let now = Instant::now(); - let animate = !cx.reduce_motion() && !crate::animation_policy::animations_disabled(); - let (value, position, animating) = sync(node.tag, &node.props, animate, now); - if animating { - window.request_animation_frame(); - } - let (width, height) = (node.frame.w, node.frame.h); - let inset = 2.0_f32; - let diameter = (height - 2.0 * inset).max(0.0); - let travel = (width - height).max(0.0); - let on = argb(&node.props, &["onTintColor", "trackColorForTrue"]).unwrap_or_else(accent); - let off = argb(&node.props, &["tintColor", "trackColorForFalse"]).unwrap_or_else(off_track); - let thumb = argb(&node.props, &["thumbTintColor", "thumbColor"]).unwrap_or(0xFFFFFFFF); - let track = if value || position > 0.5 { on } else { off }; - let mut track_color = color(track); - if disabled(&node.props) { - track_color.a *= 0.5; - } - let mut thumb_color = color(thumb); - if disabled(&node.props) { - thumb_color.a *= 0.7; - } - Some( - div() - .absolute() - .size_full() - .child( - div() - .absolute() - .size_full() - .rounded(px(height / 2.0)) - .bg(track_color), - ) - .child( - div() - .absolute() - .top(px(inset)) - .left(px(inset + travel * position)) - .size(px(diameter)) - .rounded(px(diameter / 2.0)) - .bg(thumb_color), - ) - .into_any_element(), - ) - } - - fn input(&self, node: &ComponentNode) -> InputSpec { - if disabled(&node.props) { - return InputSpec::default(); - } - InputSpec { - mouse_buttons: ButtonSet::one(crate::events::Button::Left), - cursor: Some(CursorStyle::Pointer), - ..InputSpec::default() - } - } - - fn focusable_by_default(&self) -> bool { - true - } - - fn claims_press(&self, node: &ComponentNode) -> bool { - !disabled(&node.props) - } - - fn on_mouse_down( - &self, - _node: &ComponentNode, - _event: &MouseEvent, - cx: &mut InputContext<'_>, - ) -> Propagation { - // Capture so the release arrives even if the pointer drifted off. - cx.capture_pointer(); - Propagation::Stop - } - - fn on_mouse_up( - &self, - node: &ComponentNode, - _event: &MouseEvent, - cx: &mut InputContext<'_>, - ) -> Propagation { - cx.release_pointer(); - // A press that began here and ended anywhere acts: `event.local` is - // measured from the frame, which is relative to the parent, so the - // release point cannot be tested against the box reliably. - let value = flip(node, true); - cx.dispatch_event( - "topChange", - &serde_json::json!({"value": value, "target": node.tag}), - ); - cx.request_frame(); - Propagation::Stop - } - - fn activate( - &self, - node: &ComponentNode, - handle: &StoreHandle, - window: &mut Window, - cx: &mut App, - ) -> bool { - if disabled(&node.props) { - return true; - } - let value = flip(node, !cx.reduce_motion()); - handle.dispatch_event( - node.tag, - "topChange", - &serde_json::json!({"value": value, "target": node.tag}), - cx, - ); - window.refresh(); - true - } - - fn command( - &self, - node: &ComponentNode, - name: &str, - args: &Value, - _handle: &StoreHandle, - cx: &mut App, - ) -> bool { - if name != "setValue" { - return false; - } - let Some(value) = args.get(0).and_then(Value::as_bool) else { - return false; - }; - let animate = !cx.reduce_motion() && !crate::animation_policy::animations_disabled(); - let mut states = states().lock().expect("switch states poisoned"); - if let Some(state) = states.get_mut(&node.tag) { - state.set(value, animate, Instant::now()); - } - true - } -} - -/// Flips the shown value and returns the new one. -fn flip(node: &ComponentNode, animate: bool) -> bool { - let now = Instant::now(); - let animate = animate && !crate::animation_policy::animations_disabled(); - let mut states = states().lock().expect("switch states poisoned"); - let prop = prop_value(&node.props); - let state = states.entry(node.tag).or_insert_with(|| State { - value: prop, - last_prop: prop, - from: if prop { 1.0 } else { 0.0 }, - started: now - SLIDE, - }); - let next = !state.value; - state.set(next, animate, now); - next -} - -pub fn register() { - register_component_renderer("Switch", Arc::new(SwitchRenderer)); -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn a_flip_slides_from_where_the_thumb_is() { - let start = Instant::now(); - let mut state = State { - value: false, - last_prop: false, - from: 0.0, - started: start - SLIDE, - }; - assert_eq!(state.position(start), 0.0); - state.set(true, true, start); - assert!(state.animating(start)); - assert_eq!(state.position(start), 0.0); - assert_eq!(state.position(start + SLIDE), 1.0); - // Reversed halfway: it starts from the middle, not from an end. - let halfway = start + SLIDE / 2; - let middle = state.position(halfway); - state.set(false, true, halfway); - assert!((state.position(halfway) - middle).abs() < 1e-6); - assert_eq!(state.position(halfway + SLIDE), 0.0); - } - - #[test] - fn without_animation_the_thumb_jumps() { - let now = Instant::now(); - let mut state = State { - value: false, - last_prop: false, - from: 0.0, - started: now - SLIDE, - }; - state.set(true, false, now); - assert_eq!(state.position(now), 1.0); - assert!(!state.animating(now)); - } - - #[test] - fn a_new_value_prop_replaces_the_native_value() { - let tag = 910_001; - let now = Instant::now(); - let (value, _, _) = sync(tag, &json!({"value": false}), false, now); - assert!(!value); - flip( - &ComponentNode { - component: "Switch".into(), - tag, - frame: Default::default(), - scale: (1.0, 1.0), - props: Arc::new(json!({"value": false})), - parent: None, - children: vec![], - }, - false, - ); - // `flip` stamps the change with its own clock reading, so read after it. - let now = Instant::now(); - let (value, position, _) = sync(tag, &json!({"value": false}), false, now); - assert!( - value && position > 0.99, - "the click is kept until JS changes the prop" - ); - let (value, position, _) = sync(tag, &json!({"value": true}), false, now); - assert!(value && position > 0.99); - let (value, position, _) = sync(tag, &json!({"value": false}), false, now); - assert!(!value && position < 0.01); - states().lock().unwrap().remove(&tag); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/text_select.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/text_select.rs deleted file mode 100644 index e1741c95e8..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/text_select.rs +++ /dev/null @@ -1,296 +0,0 @@ -//! Selecting the text of a `Text` with `selectable`: a drag, a double click for -//! a word, a triple click for a line, Copy from the menu or the context menu. -//! -//! One node holds the selection at a time. Starting a selection elsewhere, or -//! pressing anything that is not selectable text, clears the previous one. - -use std::ops::Range; - -use gpui::{Context, Pixels, Point, Window}; - -use crate::node_view::RNNodeView; -use crate::store::store_from; - -/// The tag of the node that holds the selection, if any. -#[derive(Default)] -pub(crate) struct ActiveSelection(pub Option); - -impl gpui::Global for ActiveSelection {} - -pub(crate) fn is_selectable(node: &RNNodeView) -> bool { - node.component != "TextInput" && node.paragraph.as_ref().is_some_and(|p| p.selectable) -} - -fn content_width(node: &RNNodeView) -> f32 { - (node.frame.w - node.view.content_insets.left - node.view.content_insets.right).max(0.0) -} - -fn index_at(node: &RNNodeView, point: Point, cx: &gpui::App) -> Option { - let paragraph = node.paragraph.as_ref()?; - let origin = node.absolute_origin(cx); - let (scale_x, scale_y) = node.cumulative_scale(cx); - let x = f32::from(point.x - origin.x) / scale_x.max(0.0001) - node.view.content_insets.left; - let y = f32::from(point.y - origin.y) / scale_y.max(0.0001) - node.view.content_insets.top; - crate::text::text_index_at(paragraph, content_width(node), x.max(0.0), y.max(0.0)) -} - -fn class(ch: char) -> u8 { - if ch.is_alphanumeric() || ch == '_' { - 0 - } else if ch.is_whitespace() { - 1 - } else { - 2 - } -} - -/// The run of same-class characters around `index`. -fn word_range(text: &str, index: usize) -> Range { - let index = index.min(text.len()); - let before = text[..index].chars().next_back(); - let after = text[index..].chars().next(); - let Some(anchor) = after.or(before) else { - return index..index; - }; - let kind = class(anchor); - let start = text[..index] - .char_indices() - .rev() - .take_while(|(_, ch)| class(*ch) == kind) - .last() - .map_or(index, |(at, _)| at); - let end = text[index..] - .char_indices() - .find(|(_, ch)| class(*ch) != kind) - .map_or(text.len(), |(at, _)| index + at); - start..end -} - -/// The hard line around `index`, without its newline. -fn line_range(text: &str, index: usize) -> Range { - let index = index.min(text.len()); - let start = text[..index].rfind('\n').map_or(0, |at| at + 1); - let end = text[index..].find('\n').map_or(text.len(), |at| index + at); - start..end -} - -fn claim(node: &mut RNNodeView, cx: &mut Context) { - let tag = node.tag; - let previous = cx - .try_global::() - .and_then(|active| active.0) - .filter(|previous| *previous != tag); - cx.set_global(ActiveSelection(Some(tag))); - if let (Some(previous), Some(store)) = (previous, store_from(cx)) { - if let Some(entity) = store.read(cx).nodes.get(&previous).cloned() { - cx.defer(move |cx| { - entity.update(cx, |node, cx| { - node.text_selection = 0..0; - node.text_selection_anchor = None; - cx.notify(); - }); - }); - } - } -} - -/// A press on selectable text: a caret for one click, a word for two, a line -/// for three. -pub(crate) fn begin( - node: &mut RNNodeView, - point: Point, - click_count: usize, - cx: &mut Context, -) { - let Some(paragraph) = node.paragraph.as_ref() else { - return; - }; - let text = crate::text::paragraph_text(paragraph); - let index = index_at(node, point, cx) - .unwrap_or(text.len()) - .min(text.len()); - claim(node, cx); - match click_count { - 0 | 1 => { - node.text_selection = index..index; - node.text_selection_anchor = Some(index); - } - 2 => { - node.text_selection = word_range(&text, index); - node.text_selection_anchor = None; - } - _ => { - node.text_selection = line_range(&text, index); - node.text_selection_anchor = None; - } - } - cx.notify(); -} - -/// The pointer moved with the button down. -pub(crate) fn extend(node: &mut RNNodeView, point: Point, cx: &mut Context) { - let Some(anchor) = node.text_selection_anchor else { - return; - }; - let Some(index) = index_at(node, point, cx) else { - return; - }; - node.text_selection = anchor.min(index)..anchor.max(index); - cx.notify(); -} - -pub(crate) fn select_all(node: &mut RNNodeView, cx: &mut Context) { - let Some(paragraph) = node.paragraph.as_ref() else { - return; - }; - let length = crate::text::paragraph_text(paragraph).len(); - claim(node, cx); - node.text_selection = 0..length; - node.text_selection_anchor = None; - cx.notify(); -} - -pub(crate) fn selected_text(node: &RNNodeView) -> Option { - let paragraph = node.paragraph.as_ref()?; - let text = crate::text::paragraph_text(paragraph); - let range = node.text_selection.start.min(text.len())..node.text_selection.end.min(text.len()); - (!range.is_empty() && text.is_char_boundary(range.start) && text.is_char_boundary(range.end)) - .then(|| text[range].to_string()) -} - -pub(crate) fn copy(node: &RNNodeView, cx: &mut gpui::App) -> bool { - match selected_text(node) { - Some(text) => { - cx.write_to_clipboard(gpui::ClipboardItem::new_string(text)); - true - } - None => false, - } -} - -/// Copies what the node holding the selection has selected. -pub(crate) fn copy_active(cx: &mut gpui::App) -> bool { - let text = active_node(cx).and_then(|node| selected_text(node.read(cx))); - match text { - Some(text) => { - cx.write_to_clipboard(gpui::ClipboardItem::new_string(text)); - true - } - None => false, - } -} - -/// Drops the selection of whichever node holds it. -pub(crate) fn clear_active(cx: &mut gpui::App) { - let Some(tag) = cx - .try_global::() - .and_then(|active| active.0) - else { - return; - }; - cx.set_global(ActiveSelection(None)); - let Some(store) = store_from(cx) else { - return; - }; - if let Some(entity) = store.read(cx).nodes.get(&tag).cloned() { - entity.update(cx, |node, cx| { - node.text_selection = 0..0; - node.text_selection_anchor = None; - cx.notify(); - }); - } -} - -/// The node holding the selection, for the menu's Copy and Select All. -pub(crate) fn active_node(cx: &gpui::App) -> Option> { - let tag = cx.try_global::()?.0?; - store_from(cx)?.read(cx).nodes.get(&tag).cloned() -} - -const MENU_COPY: &str = "copy"; -const MENU_SELECT_ALL: &str = "selectAll"; - -/// Opens a Copy and Select All menu over selectable text. -pub(crate) fn show_menu( - entity: &gpui::Entity, - position: Point, - window: &mut Window, - cx: &mut gpui::App, -) -> bool { - use crate::desktop::menu_model::{MenuItemDef, MenuModel, MenuNode}; - let (selectable, has_selection, tag) = { - let node = entity.read(cx); - (is_selectable(node), selected_text(node).is_some(), node.tag) - }; - if !selectable { - return false; - } - let item = |id: &str, label: &str, enabled: bool| { - MenuNode::Item(MenuItemDef { - id: id.to_string(), - label: label.to_string(), - accelerator: None, - enabled, - checked: false, - role: None, - icon: None, - }) - }; - let model = MenuModel { - items: vec![ - item(MENU_COPY, "Copy", has_selection), - MenuNode::Separator, - item(MENU_SELECT_ALL, "Select All", true), - ], - }; - let handle = window.window_handle(); - let responder = crate::desktop::context_menu::Responder::callback(Box::new(move |choice| { - let Some(choice) = choice else { - return; - }; - crate::desktop::post_to_main(Box::new(move |cx: &mut gpui::App| { - let Some(entity) = - store_from(cx).and_then(|store| store.read(cx).nodes.get(&tag).cloned()) - else { - return; - }; - let _ = handle.update(cx, |_root, _window, cx| { - entity.update(cx, |node, cx| match choice.as_str() { - MENU_COPY => { - copy(node, cx); - } - MENU_SELECT_ALL => select_all(node, cx), - _ => {} - }); - }); - })); - })); - crate::desktop::context_menu::present( - cx, - model, - handle, - (f32::from(position.x), f32::from(position.y)), - responder, - ); - true -} - -#[cfg(test)] -mod tests { - use super::{line_range, word_range}; - - #[test] - fn a_word_is_the_run_of_its_own_kind_around_the_index() { - assert_eq!(word_range("hello big world", 7), 6..9); - assert_eq!(word_range("hello, world", 5), 5..6); - assert_eq!(word_range("hello world", 6), 5..7); - assert_eq!(word_range("", 0), 0..0); - } - - #[test] - fn a_line_stops_at_the_newlines() { - assert_eq!(line_range("one\ntwo\nthree", 5), 4..7); - assert_eq!(line_range("one\ntwo", 0), 0..3); - assert_eq!(line_range("one\ntwo", 7), 4..7); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/textinput/input.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/textinput/input.rs deleted file mode 100644 index f2e3a8d241..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/textinput/input.rs +++ /dev/null @@ -1,1307 +0,0 @@ -use crate::node_view::RNNodeView; -use crate::store::store_from; -use gpui::{ - Bounds, Context, EntityInputHandler, Pixels, Point, TextInputConfiguration, UTF16Selection, - Window, -}; -use std::ops::Range; - -pub(crate) fn handle_key( - this: &mut RNNodeView, - key: &str, - extend_selection: bool, - window: &mut Window, - cx: &mut Context, -) -> bool { - if !this.input().editable && !matches!(key, "left" | "right" | "home" | "end") { - return false; - } - match key { - "backspace" | "delete" => { - let mut range = selected_range(this); - if range.is_empty() { - if key == "backspace" { - range.start = this.input().text[..range.start] - .char_indices() - .next_back() - .map(|(index, _)| index) - .unwrap_or(0); - } else if range.end < this.input().text.len() { - range.end += this.input().text[range.end..] - .chars() - .next() - .map(char::len_utf8) - .unwrap_or(0); - } - } - if !range.is_empty() { - this.input_mut().text.replace_range(range.clone(), ""); - this.input_mut().selection = range.start..range.start; - this.input_mut().selection_anchor = None; - this.input_mut().marked = None; - this.sync_input_paragraph(); - emit_change(this, window, cx); - } - true - } - "enter" => { - if this - .input() - .submit_behavior - .inserts_newline(this.input().multiline) - { - let max_length = this.input().max_length; - let input = this.input_mut(); - replace_plain_text( - &mut input.text, - &mut input.selection, - &mut input.marked, - None, - "\n", - max_length, - ); - this.sync_input_paragraph(); - emit_change(this, window, cx); - } else if let Some(store) = store_from(cx) { - store.read(cx).host.dispatch_event( - this.tag, - "topSubmitEditing", - &serde_json::json!({ - "text": this.input().text, "eventCount": this.input().event_count, - }), - ); - if this.input().submit_behavior.blurs(this.input().multiline) { - window.blur(cx); - } - } - true - } - "left" | "right" | "home" | "end" => { - let text = this.input().text.clone(); - let selection = selected_range(this); - let (anchor, focus) = if extend_selection { - let anchor = *this - .input_mut() - .selection_anchor - .get_or_insert(selection.start); - let active = if selection.is_empty() { - selection.end - } else if anchor == selection.start { - selection.end - } else { - selection.start - }; - let next = match key { - "left" => text[..active] - .char_indices() - .next_back() - .map(|(index, _)| index) - .unwrap_or(0), - "right" => { - active - + text[active..] - .chars() - .next() - .map(char::len_utf8) - .unwrap_or(0) - } - "home" => text[..active] - .rfind('\n') - .map(|index| index + 1) - .unwrap_or(0), - "end" => active + text[active..].find('\n').unwrap_or(text.len() - active), - _ => active, - }; - (anchor, next) - } else if !selection.is_empty() { - this.input_mut().selection_anchor = None; - let cursor = if key == "left" || key == "home" { - selection.start - } else { - selection.end - }; - (cursor, cursor) - } else { - this.input_mut().selection_anchor = None; - let cursor = selection.end; - let next = match key { - "left" => text[..cursor] - .char_indices() - .next_back() - .map(|(index, _)| index) - .unwrap_or(0), - "right" => { - cursor - + text[cursor..] - .chars() - .next() - .map(char::len_utf8) - .unwrap_or(0) - } - "home" => text[..cursor] - .rfind('\n') - .map(|index| index + 1) - .unwrap_or(0), - "end" => cursor + text[cursor..].find('\n').unwrap_or(text.len() - cursor), - _ => cursor, - }; - (next, next) - }; - this.input_mut().selection = anchor.min(focus)..anchor.max(focus); - this.input_mut().marked = None; - emit_selection(this, window, cx); - true - } - _ => false, - } -} - -const MENU_CUT: &str = "cut"; -const MENU_COPY: &str = "copy"; -const MENU_PASTE: &str = "paste"; -const MENU_SELECT_ALL: &str = "selectAll"; - -fn text_menu_model(this: &RNNodeView, can_paste: bool) -> crate::desktop::menu_model::MenuModel { - use crate::desktop::menu_model::{MenuItemDef, MenuModel, MenuNode}; - let has_selection = !selected_range(this).is_empty(); - let editable = this.input().editable; - let item = |id: &str, label: &str, enabled: bool| { - MenuNode::Item(MenuItemDef { - id: id.to_string(), - label: label.to_string(), - accelerator: None, - enabled, - checked: false, - role: None, - icon: None, - }) - }; - let mut items = Vec::new(); - if editable { - items.push(item(MENU_CUT, "Cut", has_selection)); - } - items.push(item(MENU_COPY, "Copy", has_selection)); - if editable { - items.push(item(MENU_PASTE, "Paste", can_paste)); - } - items.push(MenuNode::Separator); - items.push(item( - MENU_SELECT_ALL, - "Select All", - !this.input().text.is_empty(), - )); - MenuModel { items } -} - -/// Opens the Cut, Copy, Paste and Select All menu over a text input, unless the -/// input hides it. Returns whether a menu was shown. -pub(crate) fn show_text_menu( - entity: &gpui::Entity, - position: Point, - window: &mut Window, - cx: &mut gpui::App, -) -> bool { - let can_paste = cx - .read_from_clipboard() - .is_some_and(|item| item.text().is_some_and(|text| !text.is_empty())); - let this = entity.read(cx); - if this.component != "TextInput" || this.input().context_menu_hidden { - return false; - } - let model = text_menu_model(this, can_paste); - let tag = this.tag; - let handle = window.window_handle(); - let responder = crate::desktop::context_menu::Responder::callback(Box::new(move |choice| { - let Some(choice) = choice else { - return; - }; - crate::desktop::post_to_main(Box::new(move |cx: &mut gpui::App| { - let Some(store) = store_from(cx) else { - return; - }; - let Some(entity) = store.read(cx).nodes.get(&tag).cloned() else { - return; - }; - let _ = handle.update(cx, |_root, window, cx| { - entity.update(cx, |this, cx| { - match choice.as_str() { - MENU_CUT => { - cut_selection(this, window, cx); - } - MENU_COPY => { - copy_selection(this, cx); - } - MENU_PASTE => { - paste_clipboard(this, window, cx); - } - MENU_SELECT_ALL => select_all(this, window, cx), - _ => {} - } - cx.notify(); - }); - }); - })); - })); - crate::desktop::context_menu::present( - cx, - model, - handle, - (f32::from(position.x), f32::from(position.y)), - responder, - ); - true -} - -pub(crate) fn select_at_point( - this: &mut RNNodeView, - point: Point, - extend: bool, - window: &mut Window, - cx: &mut Context, -) { - if this.component != "TextInput" { - return; - } - let index = this - .character_index_for_point(point, window, cx) - .map(|index| byte_at_utf16(&this.input().text, index)) - .unwrap_or(this.input().text.len()); - let anchor = if extend { - this.input() - .selection_anchor - .unwrap_or(this.input().selection.start) - } else { - index - }; - this.input_mut().selection_anchor = Some(anchor); - this.input_mut().selection = anchor.min(index)..anchor.max(index); - // The press that focused the input selects everything, not a caret. - if !extend - && this - .input() - .select_all_until - .is_some_and(|until| std::time::Instant::now() < until) - { - this.input_mut().selection = 0..this.input().text.len(); - this.input_mut().selection_anchor = None; - } - emit_selection(this, window, cx); -} - -pub(crate) fn select_all(this: &mut RNNodeView, window: &mut Window, cx: &mut Context) { - if this.component != "TextInput" { - return; - } - this.input_mut().selection = 0..this.input().text.len(); - this.input_mut().selection_anchor = None; - emit_selection(this, window, cx); -} - -pub(crate) fn copy_selection(this: &RNNodeView, cx: &mut gpui::App) -> bool { - if this.component != "TextInput" { - return false; - } - let range = selected_range(this); - if range.is_empty() { - return false; - } - let text = this.input().text[range].to_string(); - cx.write_to_clipboard(gpui::ClipboardItem::new_string(text)); - true -} - -pub(crate) fn cut_selection( - this: &mut RNNodeView, - window: &mut Window, - cx: &mut Context, -) -> bool { - if !this.input().editable || !copy_selection(this, cx) { - return false; - } - let range = selected_range(this); - this.input_mut().text.replace_range(range.clone(), ""); - this.input_mut().selection = range.start..range.start; - this.input_mut().selection_anchor = None; - this.input_mut().marked = None; - this.sync_input_paragraph(); - emit_change(this, window, cx); - true -} - -pub(crate) fn paste_clipboard( - this: &mut RNNodeView, - window: &mut Window, - cx: &mut Context, -) -> bool { - if !this.input().editable { - return false; - } - let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else { - return false; - }; - if text.is_empty() { - return false; - } - let max_length = this.input().max_length; - let input = this.input_mut(); - replace_plain_text( - &mut input.text, - &mut input.selection, - &mut input.marked, - None, - &text, - max_length, - ); - this.sync_input_paragraph(); - emit_change(this, window, cx); - true -} - -pub(crate) fn byte_at_utf16(text: &str, offset: usize) -> usize { - let mut units = 0; - for (byte, ch) in text.char_indices() { - if units >= offset { - return byte; - } - let next = units + ch.len_utf16(); - if next > offset { - return byte; - } - units = next; - } - text.len() -} - -fn utf16_at_byte(text: &str, offset: usize) -> usize { - let offset = offset.min(text.len()); - text.char_indices() - .take_while(|(byte, _)| *byte < offset) - .map(|(_, ch)| ch.len_utf16()) - .sum() -} - -fn byte_range(text: &str, range: Range) -> Range { - let start = byte_at_utf16(text, range.start); - let end = byte_at_utf16(text, range.end.max(range.start)); - start..end.max(start) -} - -pub(crate) fn reconcile_selection( - text: &str, - current: Range, - explicit_utf16: Option>, - initialize: bool, -) -> Range { - if let Some(selection) = explicit_utf16 { - byte_range(text, selection) - } else if initialize { - text.len()..text.len() - } else { - current.start.min(text.len())..current.end.min(text.len()) - } -} - -pub(crate) fn should_apply_text_update(native_event_count: i32, props_event_count: i32) -> bool { - props_event_count >= native_event_count -} - -fn utf16_range(text: &str, range: Range) -> Range { - utf16_at_byte(text, range.start)..utf16_at_byte(text, range.end) -} - -fn selected_range(this: &RNNodeView) -> Range { - this.input().selection.start.min(this.input().text.len()) - ..this.input().selection.end.min(this.input().text.len()) -} - -fn replacement_range( - text: &str, - selection: &Range, - marked: &mut Option>, - range_utf16: Option>, -) -> Range { - range_utf16 - .map(|range| byte_range(text, range)) - .or_else(|| marked.take()) - .unwrap_or_else(|| selection.clone()) -} - -/// The longest prefix of `inserted` that keeps `text` within `max_length` -/// UTF-16 units once `range` is replaced, never splitting a character. -fn fit_insert<'a>( - text: &str, - range: &Range, - inserted: &'a str, - max_length: usize, -) -> &'a str { - if max_length == usize::MAX { - return inserted; - } - let kept = - utf16_at_byte(text, range.start) + text[range.end.min(text.len())..].encode_utf16().count(); - let mut room = max_length.saturating_sub(kept); - for (byte, ch) in inserted.char_indices() { - if ch.len_utf16() > room { - return &inserted[..byte]; - } - room -= ch.len_utf16(); - } - inserted -} - -fn replace_plain_text( - text: &mut String, - selection: &mut Range, - marked: &mut Option>, - range_utf16: Option>, - inserted: &str, - max_length: usize, -) { - let range = replacement_range(text, selection, marked, range_utf16); - let inserted = fit_insert(text, &range, inserted, max_length); - text.replace_range(range.clone(), inserted); - let cursor = range.start + inserted.len(); - *selection = cursor..cursor; - *marked = None; -} - -fn replace_marked_text( - text: &mut String, - selection: &mut Range, - marked: &mut Option>, - range_utf16: Option>, - inserted: &str, - selected_range_utf16: Option>, - max_length: usize, -) { - let range = replacement_range(text, selection, marked, range_utf16); - let inserted = fit_insert(text, &range, inserted, max_length); - text.replace_range(range.clone(), inserted); - let composing = range.start..range.start + inserted.len(); - *marked = (!inserted.is_empty()).then_some(composing.clone()); - *selection = selected_range_utf16 - .map(|selected| { - let selected = byte_range(inserted, selected); - range.start + selected.start..range.start + selected.end - }) - .unwrap_or(composing.end..composing.end); -} - -fn clear_text_state( - text: &mut String, - selection: &mut Range, - marked: &mut Option>, -) -> bool { - if text.is_empty() { - return false; - } - text.clear(); - *selection = 0..0; - *marked = None; - true -} - -fn emit_change(this: &mut RNNodeView, window: &mut Window, cx: &mut Context) { - this.input_mut().event_count += 1; - this.input_mut().selection_anchor = None; - let scrolled_from = this.input().scroll_y; - keep_caret_visible(this, window); - let text = this.input().text.clone(); - let selection = utf16_range(&text, selected_range(this)); - if let Some(store) = store_from(cx) { - let host = store.read(cx).host.clone(); - host.dispatch_event( - this.tag, - "topChange", - &serde_json::json!({ - "text": text, - "eventCount": this.input().event_count, - }), - ); - host.dispatch_event( - this.tag, - "topSelectionChange", - &serde_json::json!({"selection": {"start": selection.start, "end": selection.end}}), - ); - if this.input().scroll_y != scrolled_from { - host.dispatch_event(this.tag, "topScroll", &scroll_payload(this)); - } - store.read(cx).frame_hook.arm(window); - } - emit_content_size(this, window, cx); - this.reset_text_input_caret(cx); - cx.notify(); -} - -fn emit_selection(this: &mut RNNodeView, window: &mut Window, cx: &mut Context) { - let scrolled_from = this.input().scroll_y; - keep_caret_visible(this, window); - let selection = utf16_range(&this.input().text, selected_range(this)); - if let Some(store) = store_from(cx) { - let host = store.read(cx).host.clone(); - host.dispatch_event( - this.tag, - "topSelectionChange", - &serde_json::json!({"selection": {"start": selection.start, "end": selection.end}}), - ); - if this.input().scroll_y != scrolled_from { - host.dispatch_event(this.tag, "topScroll", &scroll_payload(this)); - } - store.read(cx).frame_hook.arm(window); - } - this.reset_text_input_caret(cx); - cx.notify(); -} - -/// The height of one line in the input's own units, as the caret and the -/// selection use it. -pub(crate) fn input_line_height(this: &RNNodeView) -> f32 { - let fragment = this - .paragraph - .as_ref() - .and_then(|paragraph| paragraph.fragments.first()); - match fragment { - Some(fragment) if fragment.line_height > 0.0 => fragment.line_height, - Some(fragment) => fragment.font_size.max(14.0) * 1.2, - None => 14.0 * 1.2, - } -} - -fn viewport_height(this: &RNNodeView) -> f32 { - (this.frame.h - this.view.content_insets.top - this.view.content_insets.bottom).max(0.0) -} - -fn multiline_content_height(this: &RNNodeView) -> f32 { - this.input().text.split('\n').count().max(1) as f32 * input_line_height(this) -} - -pub(crate) fn max_scroll_y(this: &RNNodeView) -> f32 { - (multiline_content_height(this) - viewport_height(this)).max(0.0) -} - -fn scroll_payload(this: &RNNodeView) -> serde_json::Value { - let width = - (this.frame.w - this.view.content_insets.left - this.view.content_insets.right).max(0.0); - serde_json::json!({ - "contentOffset": {"x": this.input().scroll_x, "y": this.input().scroll_y}, - "contentSize": {"width": width, "height": multiline_content_height(this)}, - "layoutMeasurement": {"width": width, "height": viewport_height(this)}, - }) -} - -/// Sets the vertical offset of a multiline input and reports it to `onScroll` -/// when it moved. -pub(crate) fn scroll_input_to(this: &mut RNNodeView, y: f32, cx: &mut Context) { - let next = y.clamp(0.0, max_scroll_y(this)); - if (next - this.input().scroll_y).abs() <= f32::EPSILON { - return; - } - this.input_mut().scroll_y = next; - if let Some(store) = store_from(cx) { - store - .read(cx) - .host - .dispatch_event(this.tag, "topScroll", &scroll_payload(this)); - } - cx.notify(); -} - -/// Reports the content size to `onContentSizeChange` when it differs from the -/// last report. -fn emit_content_size(this: &mut RNNodeView, window: &mut Window, cx: &mut Context) { - let width = if this.input().multiline { - (this.frame.w - this.view.content_insets.left - this.view.content_insets.right).max(0.0) - } else { - this.paragraph.as_ref().map_or(0.0, |paragraph| { - let line = this.input().text.split('\n').next().unwrap_or_default(); - crate::text::input_caret_x(window.text_system(), paragraph, line, line.len()) - }) - }; - let height = if this.input().multiline { - multiline_content_height(this) - } else { - input_line_height(this) - }; - if this.input().content_size == (width, height) { - return; - } - this.input_mut().content_size = (width, height); - if let Some(store) = store_from(cx) { - store.read(cx).host.dispatch_event( - this.tag, - "topContentSizeChange", - &serde_json::json!({"contentSize": {"width": width, "height": height}}), - ); - } -} - -pub(crate) fn keep_caret_visible(this: &mut RNNodeView, window: &mut Window) { - if this.input().multiline { - this.input_mut().scroll_x = 0.0; - let line_height = input_line_height(this); - let end = this.input().selection.end.min(this.input().text.len()); - let line = this.input().text[..end].matches('\n').count() as f32; - let (top, bottom) = (line * line_height, (line + 1.0) * line_height); - let height = viewport_height(this); - let mut offset = this.input().scroll_y; - if top < offset { - offset = top; - } else if bottom > offset + height { - offset = bottom - height; - } - this.input_mut().scroll_y = offset.clamp(0.0, max_scroll_y(this)); - return; - } - let Some(paragraph) = this.paragraph.as_ref() else { - this.input_mut().scroll_x = 0.0; - return; - }; - if paragraph.fragments.is_empty() { - this.input_mut().scroll_x = 0.0; - return; - } - let end = this.input().selection.end.min(this.input().text.len()); - let line_start = this.input().text[..end] - .rfind('\n') - .map_or(0, |index| index + 1); - let line = &this.input().text[line_start..end]; - let caret_x = crate::text::input_caret_x(window.text_system(), paragraph, line, line.len()); - let viewport = - (this.frame.w - this.view.content_insets.left - this.view.content_insets.right).max(0.0); - this.input_mut().scroll_x = input_scroll_offset(this.input().scroll_x, caret_x, viewport); -} - -fn input_scroll_offset(current: f32, caret_x: f32, viewport: f32) -> f32 { - let current = current.max(0.0); - let viewport = viewport.max(0.0); - if caret_x < current { - caret_x.max(0.0) - } else if caret_x > current + viewport { - (caret_x - viewport + 1.0).max(0.0) - } else { - current - } -} - -pub fn clear_text_input(this: &mut RNNodeView, window: &mut Window, cx: &mut Context) { - if this.component != "TextInput" - || !{ - let input = this.input_mut(); - clear_text_state(&mut input.text, &mut input.selection, &mut input.marked) - } - { - return; - } - this.sync_input_paragraph(); - emit_change(this, window, cx); -} - -impl EntityInputHandler for RNNodeView { - fn text_for_range( - &mut self, - range_utf16: Range, - actual_range: &mut Option>, - _window: &mut Window, - _cx: &mut Context, - ) -> Option { - let range = byte_range(&self.input().text, range_utf16); - *actual_range = Some(utf16_range(&self.input().text, range.clone())); - Some(self.input().text[range].to_owned()) - } - - fn selected_text_range( - &mut self, - _ignore_disabled_input: bool, - _window: &mut Window, - _cx: &mut Context, - ) -> Option { - Some(UTF16Selection { - range: utf16_range(&self.input().text, selected_range(self)), - reversed: false, - }) - } - - fn marked_text_range( - &self, - _window: &mut Window, - _cx: &mut Context, - ) -> Option> { - self.input() - .marked - .as_ref() - .map(|range| utf16_range(&self.input().text, range.clone())) - } - - fn unmark_text(&mut self, _window: &mut Window, cx: &mut Context) { - self.input_mut().marked = None; - cx.notify(); - } - - fn replace_text_in_range( - &mut self, - range_utf16: Option>, - text: &str, - window: &mut Window, - cx: &mut Context, - ) { - if !self.input().editable { - return; - } - if !self.input().multiline && (text.contains('\n') || text.contains('\r')) { - if let Some(store) = store_from(cx) { - let host = store.read(cx).host.clone(); - host.dispatch_event( - self.tag, - "topSubmitEditing", - &serde_json::json!({ - "text": self.input().text, - "eventCount": self.input().event_count, - }), - ); - } - return; - } - let max_length = self.input().max_length; - let input = self.input_mut(); - replace_plain_text( - &mut input.text, - &mut input.selection, - &mut input.marked, - range_utf16, - text, - max_length, - ); - self.sync_input_paragraph(); - emit_change(self, window, cx); - } - - fn replace_and_mark_text_in_range( - &mut self, - range_utf16: Option>, - new_text: &str, - new_selected_range_utf16: Option>, - window: &mut Window, - cx: &mut Context, - ) { - if !self.input().editable { - return; - } - let max_length = self.input().max_length; - let input = self.input_mut(); - replace_marked_text( - &mut input.text, - &mut input.selection, - &mut input.marked, - range_utf16, - new_text, - new_selected_range_utf16, - max_length, - ); - self.sync_input_paragraph(); - emit_change(self, window, cx); - } - - fn bounds_for_range( - &mut self, - range_utf16: Range, - element_bounds: Bounds, - _window: &mut Window, - _cx: &mut Context, - ) -> Option> { - let _ = range_utf16; - Some(element_bounds) - } - - fn character_index_for_point( - &mut self, - point: Point, - window: &mut Window, - cx: &mut Context, - ) -> Option { - let origin = self.absolute_origin(cx); - let (scale_x, scale_y) = self.cumulative_scale(cx); - let font_size = self - .paragraph - .as_ref() - .and_then(|paragraph| paragraph.fragments.first()) - .map(|fragment| fragment.font_size.max(14.0)) - .unwrap_or(14.0); - let line_height = self - .paragraph - .as_ref() - .and_then(|paragraph| paragraph.fragments.first()) - .map(|fragment| { - if fragment.line_height > 0.0 { - fragment.line_height - } else { - font_size * 1.2 - } - }) - .unwrap_or(font_size * 1.2); - let local_x = (f32::from(point.x - origin.x) / scale_x.max(0.0001) - - self.view.content_insets.left) - .max(0.0); - let local_x = if self.input().multiline { - local_x - } else { - local_x + self.input().scroll_x - }; - let local_y = (f32::from(point.y - origin.y) / scale_y.max(0.0001) - - self.view.content_insets.top) - .max(0.0); - let local_y = if self.input().multiline { - local_y + self.input().scroll_y - } else { - local_y - }; - let target_line = if self.input().multiline { - (local_y / line_height.max(1.0)).floor() as usize - } else { - 0 - }; - let mut byte_start = 0; - let mut line_text = self.input().text.as_str(); - if self.input().multiline { - for (index, line) in self.input().text.split_inclusive('\n').enumerate() { - if index == target_line { - line_text = line.trim_end_matches('\n'); - break; - } - byte_start += line.len(); - line_text = ""; - } - } - let byte_in_line = self - .paragraph - .as_ref() - .map(|paragraph| { - crate::text::input_index_for_x(window.text_system(), paragraph, line_text, local_x) - }) - .unwrap_or(line_text.len()); - Some(utf16_at_byte(&self.input().text, byte_start + byte_in_line)) - } - - fn set_selected_text_range( - &mut self, - range_utf16: Range, - _window: &mut Window, - cx: &mut Context, - ) { - self.input_mut().selection = byte_range(&self.input().text, range_utf16); - self.input_mut().selection_anchor = None; - emit_selection(self, _window, cx); - } - - fn text_length_utf16( - &mut self, - _window: &mut Window, - _cx: &mut Context, - ) -> Option { - Some(self.input().text.encode_utf16().count()) - } - - fn accepts_text_input(&self, _window: &mut Window, _cx: &mut Context) -> bool { - self.input().editable - } - - fn text_input_configuration( - &mut self, - _window: &mut Window, - _cx: &mut Context, - ) -> TextInputConfiguration { - TextInputConfiguration::default() - } -} - -#[cfg(test)] -mod tests { - use super::{ - byte_at_utf16, clear_text_state, input_scroll_offset, reconcile_selection, - replace_marked_text, replace_plain_text, should_apply_text_update, utf16_at_byte, - }; - - #[test] - fn utf16_offsets_round_trip_as_unicode_scalar_boundaries() { - let text = "a😀é"; - for offset in [0, 1, 3, 4] { - let byte = byte_at_utf16(text, offset); - assert_eq!(utf16_at_byte(text, byte), offset); - } - assert_eq!(byte_at_utf16(text, 2), 1); - } - - #[test] - fn plain_replacement_handles_a_selected_surrogate_pair() { - let mut text = "A😀Z".to_owned(); - let mut selection = 1..5; - let mut marked = None; - - replace_plain_text( - &mut text, - &mut selection, - &mut marked, - Some(1..3), - "é", - usize::MAX, - ); - - assert_eq!(text, "AéZ"); - assert_eq!(selection, 3..3); - assert_eq!(marked, None); - } - - #[test] - fn insertion_stops_at_max_length_without_splitting_a_character() { - let mut text = "ab".to_owned(); - let mut selection = 2..2; - let mut marked = None; - - replace_plain_text(&mut text, &mut selection, &mut marked, None, "😀c", 3); - assert_eq!(text, "ab"); - - replace_plain_text(&mut text, &mut selection, &mut marked, None, "cd", 3); - assert_eq!(text, "abc"); - assert_eq!(selection, 3..3); - - selection = 0..3; - replace_plain_text(&mut text, &mut selection, &mut marked, None, "wxyz", 3); - assert_eq!(text, "wxy"); - } - - #[test] - fn marked_composition_replaces_its_previous_marked_text() { - let mut text = "Hi ".to_owned(); - let mut selection = 3..3; - let mut marked = None; - - replace_marked_text( - &mut text, - &mut selection, - &mut marked, - None, - "k", - None, - usize::MAX, - ); - assert_eq!(text, "Hi k"); - assert_eq!(marked, Some(3..4)); - - replace_marked_text( - &mut text, - &mut selection, - &mut marked, - None, - "か", - Some(1..1), - usize::MAX, - ); - assert_eq!(text, "Hi か"); - assert_eq!(marked, Some(3..6)); - assert_eq!(selection, 6..6); - - replace_plain_text(&mut text, &mut selection, &mut marked, None, "", usize::MAX); - assert_eq!(text, "Hi "); - assert_eq!(marked, None); - } - - #[test] - fn prop_updates_preserve_internal_selection_unless_rn_sets_one() { - let middle = 1..1; - assert_eq!( - reconcile_selection("hello", middle.clone(), None, false), - middle - ); - assert_eq!(reconcile_selection("hello", 4..4, Some(1..3), false), 1..3); - assert_eq!(reconcile_selection("hello", 0..0, None, true), 5..5); - assert_eq!(reconcile_selection("hi", 4..4, None, false), 2..2); - } - - #[test] - fn stale_props_do_not_replace_text_after_a_newer_native_edit() { - assert!(!should_apply_text_update(3, 2)); - assert!(should_apply_text_update(3, 3)); - assert!(should_apply_text_update(3, 4)); - } - - #[test] - fn clear_command_resets_text_selection_and_composition() { - let mut text = "A😀".to_owned(); - let mut selection = 1..5; - let mut marked = Some(1..5); - assert!(clear_text_state(&mut text, &mut selection, &mut marked)); - assert_eq!(text, ""); - assert_eq!(selection, 0..0); - assert_eq!(marked, None); - assert!(!clear_text_state(&mut text, &mut selection, &mut marked)); - } - - #[test] - fn horizontal_scroll_keeps_the_caret_inside_the_viewport() { - assert_eq!(input_scroll_offset(0.0, 180.0, 100.0), 81.0); - assert_eq!(input_scroll_offset(81.0, 40.0, 100.0), 40.0); - assert_eq!(input_scroll_offset(40.0, 90.0, 100.0), 40.0); - } -} - -pub(crate) fn desktop_navigation_event(stroke: &gpui::Keystroke) -> Option<&'static str> { - let modifiers = stroke.modifiers; - let no_other = !modifiers.alt && !modifiers.platform && !modifiers.shift; - let chord_enabled = if cfg!(target_os = "macos") { - modifiers.platform && !modifiers.alt && !modifiers.control && !modifiers.shift - } else if modifiers.alt && !modifiers.control && !modifiers.platform && !modifiers.shift { - true - } else { - modifiers.control && no_other - }; - if !chord_enabled { - return None; - } - let (back, forward) = if cfg!(target_os = "macos") || modifiers.control { - ("[", "]") - } else { - ("left", "right") - }; - if stroke.key == back { - Some("hardwareBackPress") - } else if stroke.key == forward { - Some("hardwareForwardPress") - } else { - None - } -} - -/// What a `TextInput` node holds besides what every node does. -#[derive(Clone, Debug)] -pub(crate) struct TextInputState { - pub(crate) text: String, - pub(crate) placeholder: String, - pub(crate) placeholder_mode: bool, - pub(crate) text_color: u32, - pub(crate) selection_color: u32, - pub(crate) multiline: bool, - pub(crate) editable: bool, - pub(crate) placeholder_color: u32, - pub(crate) caret_hidden: bool, - pub(crate) select_on_focus: bool, - pub(crate) submit_behavior: SubmitBehavior, - pub(crate) max_length: usize, - pub(crate) context_menu_hidden: bool, - /// Until when a click selects all, because it is the one that focused the input. - pub(crate) select_all_until: Option, - pub(crate) secure_text: bool, - pub(crate) selection: std::ops::Range, - pub(crate) scroll_x: f32, - pub(crate) scroll_y: f32, - pub(crate) content_size: (f32, f32), - pub(crate) selection_anchor: Option, - pub(crate) marked: Option>, - pub(crate) event_count: i32, - pub(crate) caret_visible: bool, -} - -impl TextInputState { - /// What a node that is not a `TextInput` reads. - pub(crate) const EMPTY: Self = Self { - text: String::new(), - placeholder: String::new(), - placeholder_mode: true, - text_color: 0xff000000, - selection_color: 0, - multiline: false, - editable: true, - placeholder_color: 0xff8e8e93, - caret_hidden: false, - select_on_focus: false, - submit_behavior: SubmitBehavior::Default, - max_length: usize::MAX, - context_menu_hidden: false, - select_all_until: None, - secure_text: false, - selection: 0..0, - scroll_x: 0.0, - scroll_y: 0.0, - content_size: (0.0, 0.0), - selection_anchor: None, - marked: None, - event_count: 0, - caret_visible: false, - }; -} - -/// `core-private:` this reads and writes `RNNodeView`'s input fields directly. -/// What Enter does, from `submitBehavior`. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub(crate) enum SubmitBehavior { - /// Not set by JS: a single-line input submits, a multiline one adds a line. - #[default] - Default, - Submit, - BlurAndSubmit, - Newline, -} - -impl SubmitBehavior { - pub(crate) fn parse(name: &str) -> Self { - match name { - "submit" => Self::Submit, - "blurAndSubmit" => Self::BlurAndSubmit, - "newline" => Self::Newline, - _ => Self::Default, - } - } - - /// Whether Enter inserts a newline for an input that is `multiline`. - pub(crate) fn inserts_newline(self, multiline: bool) -> bool { - match self { - Self::Newline => multiline, - Self::Submit | Self::BlurAndSubmit => false, - Self::Default => multiline, - } - } - - /// Whether Enter blurs the input once it has submitted: a single-line - /// input does unless `submitBehavior` is `submit`. - pub(crate) fn blurs(self, multiline: bool) -> bool { - match self { - Self::BlurAndSubmit => true, - Self::Default => !multiline, - Self::Submit | Self::Newline => false, - } - } -} - -/// The placeholder's colour: the one the app asked for, or the platform grey. -pub(crate) fn placeholder_color(requested: u32) -> u32 { - if requested == 0 { - 0xff8e8e93 - } else { - requested - } -} - -pub(crate) fn apply_update(this: &mut RNNodeView, op: &rn_gpui_sys::ffi::MountOp) { - let next = TextInputProps::from_json(&op.extension_props_json); - if should_apply_text_update(this.input().event_count, next.event_count) - && next.text != this.input().text - { - this.input_mut().text.clone_from(&next.text); - this.input_mut().marked = None; - } - this.input_mut().placeholder = next.placeholder; - this.input_mut().selection_color = next.selection_color; - this.input_mut().multiline = next.multiline; - this.input_mut().editable = next.editable; - this.input_mut().placeholder_color = placeholder_color(next.placeholder_color); - this.input_mut().caret_hidden = next.caret_hidden; - this.input_mut().select_on_focus = next.select_on_focus; - this.input_mut().submit_behavior = next.submit_behavior; - this.input_mut().max_length = next.max_length; - this.input_mut().context_menu_hidden = next.context_menu_hidden; - this.input_mut().selection = reconcile_selection( - &this.input().text, - this.input().selection.clone(), - next.selection, - false, - ); -} - -/// `core-private:` the node stores these as its own fields, so the module both -pub(crate) struct TextInputProps { - pub text: String, - pub placeholder: String, - pub selection_color: u32, - pub multiline: bool, - pub editable: bool, - pub secure: bool, - pub placeholder_color: u32, - pub caret_hidden: bool, - pub select_on_focus: bool, - pub submit_behavior: SubmitBehavior, - pub max_length: usize, - pub context_menu_hidden: bool, - pub event_count: i32, - pub selection: Option>, -} - -impl TextInputProps { - pub(crate) fn from_json(json: &str) -> Self { - let value: serde_json::Value = - serde_json::from_str(json).unwrap_or(serde_json::Value::Null); - let string = |key: &str| { - value - .get(key) - .and_then(serde_json::Value::as_str) - .unwrap_or_default() - .to_string() - }; - let flag = |key: &str, default: bool| { - value - .get(key) - .and_then(serde_json::Value::as_bool) - .unwrap_or(default) - }; - let number = |key: &str| { - value - .get(key) - .and_then(serde_json::Value::as_i64) - .unwrap_or_default() - }; - let selection = flag("selectionSet", false).then(|| { - number("selectionStart").max(0) as usize..number("selectionEnd").max(0) as usize - }); - Self { - text: string("text"), - placeholder: string("placeholder"), - selection_color: number("selectionColor") as u32, - multiline: flag("multiline", false), - editable: flag("editable", true), - secure: flag("secure", false), - placeholder_color: number("placeholderTextColor") as u32, - caret_hidden: flag("caretHidden", false), - select_on_focus: flag("selectTextOnFocus", false), - submit_behavior: SubmitBehavior::parse( - value - .get("submitBehavior") - .and_then(serde_json::Value::as_str) - .unwrap_or_default(), - ), - max_length: value - .get("maxLength") - .and_then(serde_json::Value::as_u64) - .map_or(usize::MAX, |length| length as usize), - context_menu_hidden: flag("contextMenuHidden", false), - event_count: number("eventCount") as i32, - selection, - } - } -} - -#[cfg(test)] -mod submit_behavior_tests { - use super::SubmitBehavior; - - #[test] - fn enter_follows_the_submit_behavior_and_the_input_kind() { - assert!(SubmitBehavior::Default.inserts_newline(true)); - assert!(!SubmitBehavior::Default.inserts_newline(false)); - assert!(!SubmitBehavior::Submit.inserts_newline(true)); - assert!(!SubmitBehavior::BlurAndSubmit.inserts_newline(true)); - assert!(SubmitBehavior::Newline.inserts_newline(true)); - assert!(!SubmitBehavior::Newline.inserts_newline(false)); - assert!(SubmitBehavior::BlurAndSubmit.blurs(true)); - assert!(SubmitBehavior::Default.blurs(false)); - assert!(!SubmitBehavior::Default.blurs(true)); - assert!(!SubmitBehavior::Submit.blurs(false)); - } - - #[test] - fn names_from_the_props_parse() { - assert_eq!(SubmitBehavior::parse("submit"), SubmitBehavior::Submit); - assert_eq!( - SubmitBehavior::parse("blurAndSubmit"), - SubmitBehavior::BlurAndSubmit - ); - assert_eq!(SubmitBehavior::parse("newline"), SubmitBehavior::Newline); - assert_eq!(SubmitBehavior::parse("default"), SubmitBehavior::Default); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/textinput/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/textinput/mod.rs deleted file mode 100644 index a3ee7b090d..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/textinput/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -// core-private: the caret, the selection and the focus handle are `RNNodeView` -// core-private: the caret geometry comes from `crate::text`, which is core's own. - -pub(crate) mod input; -pub(crate) mod render; diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/textinput/render.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/textinput/render.rs deleted file mode 100644 index b8685047c9..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/textinput/render.rs +++ /dev/null @@ -1,376 +0,0 @@ -// core-private: these functions read `RNNodeView` state (`input_selection`, - -use gpui::{div, prelude::*, px, Div, Entity, ParentElement, Stateful, Window}; -use rn_gpui_sys::ffi::{ParagraphFlat, RectF}; - -use crate::node_view::RNNodeView; - -/// How far a single-line input's text sits below the top of its content box: -/// it is centred vertically, as on iOS and Android. A multiline input starts at -/// the top. -pub(crate) fn single_line_offset( - node: &RNNodeView, - paragraph: &ParagraphFlat, - viewport_height: f32, - fallback_height: f32, -) -> f32 { - if node.input().multiline { - return 0.0; - } - let measured = crate::text::single_line_height(paragraph); - let height = if measured > 0.0 { - measured - } else { - fallback_height - }; - ((viewport_height - height) / 2.0).max(0.0) -} - -pub(crate) fn paragraph_content( - node: &RNNodeView, - mut element: Stateful
, - paragraph: &ParagraphFlat, - scale: (f32, f32), - frame: RectF, - window: &mut Window, -) -> Stateful
{ - let (scale_x, scale_y) = scale; - let left = node.view.content_insets.left * scale_x; - let top = node.view.content_insets.top * scale_y; - let right = node.view.content_insets.right * scale_x; - let bottom = node.view.content_insets.bottom * scale_y; - let viewport_width = (frame.w * scale_x - left - right).max(0.0); - let viewport_height = (frame.h * scale_y - top - bottom).max(0.0); - if !node.input().multiline { - let mut paragraph = paragraph.clone(); - paragraph.max_lines = 0; - paragraph.ellipsize = 0; - let line = node.input().text.split('\n').next().unwrap_or_default(); - let natural_width = - crate::text::input_caret_x(window.text_system(), ¶graph, line, line.len()); - let text_width = viewport_width.max(natural_width + 2.0); - let fallback = crate::builtins::textinput::input::input_line_height(node) * scale_y; - let offset = single_line_offset(node, ¶graph, viewport_height, fallback); - element = element.child( - div() - .absolute() - .left(px(left)) - .top(px(top)) - .w(px(viewport_width)) - .h(px(viewport_height)) - .overflow_hidden() - .child( - div() - .absolute() - .left(px(-node.input().scroll_x * scale_x)) - .top(px(offset)) - .w(px(text_width)) - .h(px(viewport_height)) - .child(crate::text::paragraph_element( - ¶graph, - text_width, - viewport_height, - None, - )), - ), - ); - } else { - let content_height = viewport_height - .max(crate::builtins::textinput::input::input_line_height(node) * scale_y) - .max( - node.input().text.split('\n').count() as f32 - * crate::builtins::textinput::input::input_line_height(node) - * scale_y, - ); - element = element.child( - div() - .absolute() - .left(px(left)) - .top(px(top)) - .w(px(viewport_width)) - .h(px(viewport_height)) - .overflow_hidden() - .child( - div() - .absolute() - .left_0() - .top(px(-node.input().scroll_y * scale_y)) - .w(px(viewport_width)) - .h(px(content_height)) - .child(crate::text::paragraph_element( - paragraph, - viewport_width, - content_height, - None, - )), - ), - ); - } - element -} - -/// Fabric measured the text inside the padding and border, so it is laid out -/// and painted in that content box, not across the whole frame. -/// With `overlay`, the text is not a child of `element` but returned for the -/// caller to paint over it with [`crate::text::ParagraphOverlay`]. -pub(crate) fn plain_paragraph( - node: &RNNodeView, - element: Stateful
, - paragraph: &ParagraphFlat, - scale: (f32, f32), - frame: RectF, - overlay: bool, - prepared: Option<&crate::text::PreparedParagraph>, -) -> (Stateful
, Option) { - let (scale_x, scale_y) = scale; - let insets = node.view.content_insets; - let left = insets.left * scale_x; - let top = insets.top * scale_y; - let width = (frame.w * scale_x - left - insets.right * scale_x).max(0.0); - let height = (frame.h * scale_y - top - insets.bottom * scale_y).max(0.0); - let highlights: Vec<_> = - if crate::builtins::text_select::is_selectable(node) && !node.text_selection.is_empty() { - let unscaled_width = (frame.w - insets.left - insets.right).max(0.0); - let mut unscaled = paragraph.clone(); - for fragment in &mut unscaled.fragments { - fragment.font_size /= scale_y.max(0.0001); - fragment.line_height /= scale_y.max(0.0001); - fragment.letter_spacing /= scale_x.max(0.0001); - } - crate::text::text_range_rects(&unscaled, unscaled_width, node.text_selection.clone()) - } else { - Vec::new() - }; - let element = element.children(highlights.into_iter().map(|(x, y, w, h)| { - div() - .absolute() - .left(px(left + x * scale_x)) - .top(px(top + y * scale_y)) - .w(px(w * scale_x)) - .h(px(h * scale_y)) - .bg(gpui::rgba(0x3875d788)) - })); - if overlay { - let painter = crate::text::ParagraphPainter::new(paragraph, width, height, prepared); - let parts = ( - painter, - gpui::point(px(left), px(top)), - gpui::size(px(width), px(height)), - ); - return (element, Some(parts)); - } - ( - element.child( - crate::text::paragraph_element(paragraph, width, height, prepared) - .absolute() - .left(px(left)) - .top(px(top)), - ), - None, - ) -} - -pub(crate) fn caret_canvas( - node: &RNNodeView, - element: Stateful
, - input: Entity, - scale: (f32, f32), -) -> Stateful
{ - if node.input().caret_hidden || !node.input().editable { - return element; - } - let (scale_x, scale_y) = scale; - let focus = node.focus_handle.clone(); - let caret_text = node.input().text.clone(); - let caret_offset = node.input().selection.end.min(node.input().text.len()); - let mut caret_paragraph = node.paragraph.clone().unwrap_or_default(); - for fragment in &mut caret_paragraph.fragments { - fragment.font_size *= scale_y; - fragment.letter_spacing *= scale_x; - } - let input_selection = node.input().selection.clone(); - let content_insets = node.view.content_insets; - let input_text_color = node.input().text_color; - let input_selection_color = node.input().selection_color; - let input_multiline = node.input().multiline; - let input_scroll_x = node.input().scroll_x * scale_x; - let input_scroll_y = node.input().scroll_y * scale_y; - let caret_visible = node.input().caret_visible; - let single_line_paragraph = caret_paragraph.clone(); - let multiline_input = node.input().multiline; - let fallback_line = crate::builtins::textinput::input::input_line_height(node) * scale_y; - let caret_height = node - .paragraph - .as_ref() - .and_then(|paragraph| paragraph.fragments.first()) - .map(|fragment| { - if fragment.line_height > 0.0 { - fragment.line_height * scale_y - } else { - fragment.font_size.max(14.0) * scale_y * 1.2 - } - }) - .unwrap_or(17.0 * scale_y); - element.child( - div().absolute().top_0().left_0().size_full().child( - gpui::canvas( - |_bounds, _window, _cx| (), - move |bounds, _state, window, cx| { - let content_box = gpui::Bounds { - origin: bounds.origin - + gpui::point( - px(content_insets.left * scale_x), - px(content_insets.top * scale_y), - ), - size: gpui::size( - (bounds.size.width - - px((content_insets.left + content_insets.right) * scale_x)) - .max(px(0.0)), - (bounds.size.height - - px((content_insets.top + content_insets.bottom) * scale_y)) - .max(px(0.0)), - ), - }; - let vertical = if multiline_input { - 0.0 - } else { - let measured = crate::text::single_line_height(&single_line_paragraph); - let height = if measured > 0.0 { - measured - } else { - fallback_line - }; - ((f32::from(content_box.size.height) - height) / 2.0).max(0.0) - }; - window.with_content_mask( - Some(gpui::ContentMask { - bounds: content_box, - }), - |window| { - if focus.as_ref().is_some_and(|f| f.is_focused(window)) { - if !input_selection.is_empty() { - let start = input_selection.start.min(caret_text.len()); - let end = input_selection.end.min(caret_text.len()); - let content_width = (f32::from(bounds.size.width) - - (content_insets.left + content_insets.right) * scale_x) - .max(0.0); - let mut line_start = 0; - for (line_number, raw_line) in - caret_text.split_inclusive('\n').enumerate() - { - let line = raw_line.trim_end_matches('\n'); - let line_end = line_start + line.len(); - let selected_start = start.max(line_start).min(line_end); - let selected_end = end.min(line_end).max(selected_start); - let includes_newline = end > line_end - && start <= line_end - && raw_line.ends_with('\n'); - if selected_end > selected_start || includes_newline { - let prefix = &line[..selected_start - line_start]; - let through_selection = - &line[..selected_end - line_start]; - let mut x0 = crate::text::input_caret_x( - window.text_system(), - &caret_paragraph, - prefix, - prefix.len(), - ); - let mut x1 = crate::text::input_caret_x( - window.text_system(), - &caret_paragraph, - through_selection, - through_selection.len(), - ); - if !input_multiline { - x0 -= input_scroll_x; - x1 -= input_scroll_x; - x0 = x0.clamp(0.0, content_width); - x1 = x1.clamp(0.0, content_width); - } - let width = if includes_newline { - (content_width - x0).max(1.0) - } else { - (x1 - x0).max(1.0) - }; - let selection = gpui::Bounds { - origin: gpui::point( - bounds.origin.x - + px(content_insets.left * scale_x + x0), - bounds.origin.y - + px(content_insets.top * scale_y - + vertical - + line_number as f32 * caret_height - - input_scroll_y), - ), - size: gpui::size(px(width), px(caret_height)), - }; - window.paint_quad(gpui::fill( - selection, - gpui::rgba(0x3875d788), - )); - } - line_start += raw_line.len(); - } - } - if caret_visible { - let offset = caret_offset.min(caret_text.len()); - let safe_offset = (0..=offset) - .rev() - .find(|index| caret_text.is_char_boundary(*index)) - .unwrap_or(0); - let prefix = &caret_text[..safe_offset]; - let line = prefix.rsplit('\n').next().unwrap_or(prefix); - let line_number = - prefix.bytes().filter(|byte| *byte == b'\n').count(); - let x = crate::text::input_caret_x( - window.text_system(), - &caret_paragraph, - line, - line.len(), - ); - let mut x = x - input_scroll_x; - let content_width = (f32::from(bounds.size.width) - - (content_insets.left + content_insets.right) * scale_x) - .max(0.0); - if !input_multiline { - x = x.clamp( - 0.0, - (content_width - scale_x.max(1.0)).max(0.0), - ); - } - let x = bounds.origin.x + px(content_insets.left * scale_x + x); - let y = bounds.origin.y - + px(content_insets.top * scale_y - + vertical - + line_number as f32 * caret_height - - input_scroll_y); - let caret = gpui::Bounds { - origin: gpui::point(x, y), - size: gpui::size(px(scale_x.max(1.0)), px(caret_height)), - }; - let caret_color = if input_selection_color == 0 { - input_text_color - } else { - input_selection_color - }; - window.paint_quad(gpui::fill( - caret, - crate::style::color(caret_color), - )); - } - } - }, - ); - if let Some(focus) = focus.as_ref() { - window.handle_input( - focus, - gpui::ElementInputHandler::new(bounds, input.clone()), - cx, - ); - } - }, - ) - .size_full(), - ), - ) -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/tray/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/tray/mod.rs deleted file mode 100644 index dc96c2ff3c..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/tray/mod.rs +++ /dev/null @@ -1,233 +0,0 @@ -use rn_gpui_module::{FromValue, ModuleError, ModuleThread, Path, Value}; - -use crate::builtins::main_thread::on_main; -use crate::builtins::rn_gpui_specs::{ - NativeGpuiTrayEvents, NativeGpuiTraySpec, TrayHandle, TrayOptions, TrayState, -}; -use crate::desktop::tray; - -const MODULE: &str = "GpuiTray"; - -struct TrayModule; - -fn value_json(value: Value) -> serde_json::Value { - match value { - Value::Null | Value::Callback(_) => serde_json::Value::Null, - Value::Bool(flag) => serde_json::Value::Bool(flag), - Value::Number(number) => serde_json::Number::from_f64(number) - .map(serde_json::Value::Number) - .unwrap_or(serde_json::Value::Null), - Value::Buffer(bytes) => serde_json::Value::Array( - bytes - .into_iter() - .map(|byte| serde_json::Value::Number(byte.into())) - .collect(), - ), - Value::String(text) => serde_json::Value::String(text), - Value::Array(items) => { - serde_json::Value::Array(items.into_iter().map(value_json).collect()) - } - Value::Object(fields) => serde_json::Value::Object( - fields - .into_iter() - .map(|(key, item)| (key, value_json(item))) - .collect(), - ), - } -} - -fn json_value(value: &serde_json::Value) -> Value { - match value { - serde_json::Value::Null => Value::Null, - serde_json::Value::Bool(flag) => Value::Bool(*flag), - serde_json::Value::Number(number) => { - number.as_f64().map(Value::Number).unwrap_or(Value::Null) - } - serde_json::Value::String(text) => Value::String(text.clone()), - serde_json::Value::Array(items) => Value::Array(items.iter().map(json_value).collect()), - serde_json::Value::Object(fields) => Value::Object( - fields - .iter() - .map(|(key, item)| (key.clone(), json_value(item))) - .collect(), - ), - } -} - -fn json_items(items: Option>) -> Option { - items.map(|items| serde_json::Value::Array(items.into_iter().map(value_json).collect())) -} - -fn desktop_error(error: crate::desktop::errors::DesktopError) -> ModuleError { - ModuleError::new(error.message) -} - -fn typed(method: &'static str, value: &serde_json::Value) -> Result { - let mut path = Path::result(MODULE, method); - T::from_value(json_value(value), &mut path).map_err(|error| ModuleError::new(error.message)) -} - -fn void( - result: Result, -) -> Result<(), ModuleError> { - result - .map(|_| ()) - .map_err(|error| ModuleError::new(error.message)) -} - -impl NativeGpuiTraySpec for TrayModule { - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(_events: NativeGpuiTrayEvents) -> Self { - Self - } - - async fn tray_install(&self, options: TrayOptions) -> Result { - let icon = match options.icon.as_deref() { - Some(uri) => Some( - crate::desktop::icon::load(uri) - .await - .map_err(ModuleError::new)?, - ), - None => None, - }; - let menu = json_items(options.menu); - if let Some(menu) = &menu { - crate::desktop::icon::preload_menu(menu).await; - } - let handle = on_main( - move |cx| -> Result { - let mut config = tray::TrayConfig::default(); - if let Some(id) = options.id { - config.id = id; - } - config.tooltip = options.tooltip; - config.title = options.title; - if let Some(icon) = icon { - config.icon = Some((icon.rgba.clone(), icon.width, icon.height)); - config.icon_is_template = options.icon_template.unwrap_or(false); - } - config.component = options.component; - if let Some(size) = options.size { - config = config.size(size.width as f32, size.height as f32); - } - if let Some(menu) = menu { - config.menu = Some(crate::desktop::menu_model::parse_menu(&menu)?); - } - if let Some(on_left_click) = options.menu_on_left_click { - config.menu_on_left_click = on_left_click; - } - if let Some(quit) = options.quit_on_last_window_closed { - config.quit_on_last_window_closed = quit; - } - if let Some(hide) = options.hide_window_on_close { - config.hide_window_on_close = hide; - } - if let Some(anchor) = options - .popover_anchor - .as_deref() - .and_then(crate::desktop::popover_placement::Anchor::parse) - { - config.popover_anchor = anchor; - } - if let Some(offset) = options.popover_offset { - config = config.popover_offset(offset.x as f32, offset.y as f32); - } - tray::install(cx, config) - }, - ) - .await?; - typed("trayInstall", &handle.map_err(desktop_error)?) - } - - async fn tray_destroy(&self) -> Result<(), ModuleError> { - on_main(tray::destroy).await.and_then(void) - } - - async fn tray_get_state(&self) -> Result { - let value = on_main( - |cx| -> Result { - Ok(tray::state(cx)) - }, - ) - .await?; - typed("trayGetState", &value.map_err(desktop_error)?) - } - - async fn tray_set_tooltip(&self, tooltip: Option) -> Result<(), ModuleError> { - on_main(move |cx| tray::set_tooltip(cx, tooltip.as_deref())) - .await - .and_then(void) - } - - async fn tray_set_visible(&self, visible: bool) -> Result<(), ModuleError> { - on_main(move |cx| tray::set_visible(cx, visible)) - .await - .and_then(void) - } - - async fn tray_set_icon(&self, icon: String, template: bool) -> Result<(), ModuleError> { - let icon = crate::desktop::icon::load(&icon) - .await - .map_err(ModuleError::new)?; - on_main(move |cx| tray::set_icon(cx, &icon, template)) - .await - .and_then(void) - } - - async fn tray_set_title(&self, title: Option) -> Result<(), ModuleError> { - on_main(move |cx| tray::set_title(cx, title.as_deref())) - .await - .and_then(void) - } - - async fn tray_set_menu(&self, items: Option>) -> Result<(), ModuleError> { - let items = json_items(items); - if let Some(items) = &items { - crate::desktop::icon::preload_menu(items).await; - } - on_main(move |cx| tray::set_menu(cx, items.as_ref())) - .await - .and_then(void) - } - - async fn tray_show_popover(&self) -> Result<(), ModuleError> { - on_main(tray::open_popover).await.and_then(void) - } - - async fn tray_hide_popover(&self) -> Result<(), ModuleError> { - on_main(tray::close_popover).await.and_then(void) - } - - async fn tray_toggle_popover(&self) -> Result<(), ModuleError> { - on_main(tray::flip_popover).await.and_then(void) - } - - async fn tray_set_popover_position( - &self, - anchor: Option, - offset: Option, - ) -> Result<(), ModuleError> { - let anchor = match anchor.as_deref() { - Some(name) => Some( - crate::desktop::popover_placement::Anchor::parse(name) - .ok_or_else(|| ModuleError::new(format!("unknown popover anchor {name:?}")))?, - ), - None => None, - }; - let offset = offset.map(|offset| (offset.x as f32, offset.y as f32)); - on_main(move |cx| tray::set_popover_position(cx, anchor, offset)) - .await - .and_then(void) - } - - fn add_listener(&self, _event_name: String) {} - - fn remove_listeners(&self, _count: f64) {} -} - -pub fn register() { - rn_gpui_module::register(crate::builtins::rn_gpui_specs::native_gpui_tray_module::< - TrayModule, - >()); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/vibration/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/vibration/mod.rs deleted file mode 100644 index e7f6d86dd5..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/vibration/mod.rs +++ /dev/null @@ -1,45 +0,0 @@ -//! `Vibration`: a haptic tap on a macOS trackpad, nothing elsewhere. - -use rn_gpui_module::ModuleThread; - -use crate::builtins::rn_gpui_specs::{NativeVibrationEvents, NativeVibrationSpec}; - -struct VibrationModule; - -#[cfg(target_os = "macos")] -fn tap() { - use objc::runtime::Object; - use objc::{class, msg_send, sel, sel_impl}; - // SAFETY: `defaultPerformer` returns the shared haptic performer; the - // generic pattern (0) is played immediately (performance time 1). - unsafe { - let performer: *mut Object = msg_send![class!(NSHapticFeedbackManager), defaultPerformer]; - if !performer.is_null() { - let _: () = - msg_send![performer, performFeedbackPattern: 0isize performanceTime: 1usize]; - } - } -} - -#[cfg(not(target_os = "macos"))] -fn tap() {} - -impl NativeVibrationSpec for VibrationModule { - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(_events: NativeVibrationEvents) -> Self { - Self - } - - fn vibrate(&self, _pattern: f64) { - tap(); - } - - fn cancel(&self) {} -} - -pub fn register() { - rn_gpui_module::register(crate::builtins::rn_gpui_specs::native_vibration_module::< - VibrationModule, - >()); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/window_control/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/window_control/mod.rs deleted file mode 100644 index 3da94cd39f..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/window_control/mod.rs +++ /dev/null @@ -1,206 +0,0 @@ -//! A caption button: minimize, maximize/restore, or close. -//! -//! The action runs natively, so it works while JS is busy, and on Windows the -//! area takes part in the OS hit-test — which is what gives the snap-layout -//! flyout over a custom maximize button. Only the appearance comes from JS: the -//! component's `style` and `children` may be functions of the state this reports. - -use std::sync::Arc; - -use gpui::{AnyElement, App, Window}; -use serde_json::Value; - -use crate::extensions::input::{ - InputContext, InputSpec, MouseEvent, Propagation, WindowControl as ControlArea, -}; -use crate::extensions::{register_component_renderer, ComponentNode, ComponentRenderer}; - -struct WindowControlRenderer; - -/// What `action` names, or `None` when the button is disabled. -/// -/// Disabled means no area as well as no action: on Windows the OS would otherwise -/// still draw the snap flyout over a button that does nothing. -fn claimed_area(props: &Value) -> Option { - if props - .get("disabled") - .and_then(Value::as_bool) - .unwrap_or(false) - { - return None; - } - match props.get("action").and_then(Value::as_str) { - Some("minimize") => Some(ControlArea::Minimize), - Some("maximize") => Some(ControlArea::Maximize), - Some("close") => Some(ControlArea::Close), - // The prop has a native default of `close`, and core reads the parsed - // props, so anything else is a button with nothing to do. - _ => None, - } -} - -impl ComponentRenderer for WindowControlRenderer { - fn render( - &self, - _node: &ComponentNode, - _window: &mut Window, - _cx: &mut App, - ) -> Option { - // Core paints the element, the style and the children; this renderer only - // claims the area and tracks state. - None - } - - fn window_control(&self, node: &ComponentNode) -> Option { - claimed_area(&node.props) - } - - fn claims_press(&self, node: &ComponentNode) -> bool { - claimed_area(&node.props).is_some() - } - - fn input(&self, node: &ComponentNode) -> InputSpec { - if claimed_area(&node.props).is_none() { - return InputSpec::default(); - } - InputSpec { - mouse_buttons: crate::extensions::input::ButtonSet::one(crate::events::Button::Left), - hover: true, - cursor: Some(crate::extensions::input::CursorStyle::Pointer), - ..InputSpec::default() - } - } - - fn on_hover(&self, node: &ComponentNode, hovered: bool, cx: &mut InputContext<'_>) { - send_state(node, hovered, false, cx); - } - - fn on_mouse_down( - &self, - node: &ComponentNode, - _event: &MouseEvent, - cx: &mut InputContext<'_>, - ) -> Propagation { - send_state(node, true, true, cx); - // Capture so a release outside the button cancels rather than acting. - cx.capture_pointer(); - Propagation::Stop - } - - fn on_mouse_up( - &self, - node: &ComponentNode, - event: &MouseEvent, - cx: &mut InputContext<'_>, - ) -> Propagation { - cx.release_pointer(); - send_state(node, false, false, cx); - // Only a release inside the button acts, as a native caption button does. - let inside = event.local.x >= gpui::px(0.0) - && event.local.y >= gpui::px(0.0) - && event.local.x <= gpui::px(node.frame.w) - && event.local.y <= gpui::px(node.frame.h); - if !inside { - return Propagation::Stop; - } - // macOS and Linux act here; on Windows the OS hit-test performs the action - // and this would double it, so it is skipped. See `perform_action`. - perform_action(node, cx); - Propagation::Stop - } -} - -/// Sends `onControlStateChange`. -/// -/// Called on a hover edge, a press and a release — never for every pointer move — -/// because the edge is decided by the node's own `hovered` flag. -fn send_state(_node: &ComponentNode, hovered: bool, pressed: bool, cx: &mut InputContext<'_>) { - // No deduplication here: `on_hover` is only called on a real edge now that the - // previous state lives on the node, and a press or release is always a change. - // A second guess at it read a prop that never exists, so it never fired. - let maximized = cx.window_is_maximized(); - cx.dispatch_event( - "topControlStateChange", - &serde_json::json!({ - "hovered": hovered, - "pressed": pressed, - "maximized": maximized, - }), - ); -} - -/// Performs the button's action, on the platforms where core owns it. -fn perform_action(node: &ComponentNode, cx: &mut InputContext<'_>) { - // On Windows the OS performs the action through the non-client hit-test, which - // is what makes snap layouts work. Doing it here too would run it twice. - if std::env::consts::OS == "windows" { - return; - } - match claimed_area(&node.props) { - Some(ControlArea::Minimize) => cx.minimize_window(), - Some(ControlArea::Maximize) => cx.toggle_maximize_window(), - Some(ControlArea::Close) => cx.close_window(), - _ => {} - } -} - -pub fn register() { - register_component_renderer("DesktopWindowControl", Arc::new(WindowControlRenderer)); -} - -#[cfg(test)] -mod tests { - use super::*; - - fn node(props: Value) -> ComponentNode { - ComponentNode { - component: "DesktopWindowControl".to_string(), - tag: 1, - frame: rn_gpui_sys::ffi::RectF { - x: 0.0, - y: 0.0, - w: 34.0, - h: 26.0, - }, - scale: (1.0, 1.0), - props: Arc::new(props), - parent: None, - children: Vec::new(), - } - } - - #[test] - fn each_action_claims_its_area() { - assert_eq!( - claimed_area(&serde_json::json!({ "action": "minimize" })), - Some(ControlArea::Minimize) - ); - assert_eq!( - claimed_area(&serde_json::json!({ "action": "maximize" })), - Some(ControlArea::Maximize) - ); - assert_eq!( - claimed_area(&serde_json::json!({ "action": "close" })), - Some(ControlArea::Close) - ); - } - - #[test] - fn a_disabled_button_claims_nothing() { - // No area means no hover, no press and no snap flyout on Windows: a - // caption button that does nothing must not look like it does. - assert_eq!( - claimed_area(&serde_json::json!({ "action": "close", "disabled": true })), - None - ); - } - - #[test] - fn an_unknown_action_claims_nothing() { - assert_eq!( - claimed_area(&serde_json::json!({ "action": "explode" })), - None - ); - assert_eq!(claimed_area(&serde_json::json!({})), None); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/windows/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/windows/mod.rs deleted file mode 100644 index 6c5f680cd8..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/builtins/windows/mod.rs +++ /dev/null @@ -1,385 +0,0 @@ -use rn_gpui_module::{FromValue, ModuleError, ModuleThread, Path, Value}; - -use crate::bootstrap::{WindowBackground, WindowTitleBar}; -use crate::builtins::main_thread::on_main; -use crate::builtins::rn_gpui_specs::{ - NativeGpuiWindowsEvents, NativeGpuiWindowsSpec, WindowHandle, WindowList, WindowOpenOptions, - WindowState, -}; -use crate::desktop::errors::{DesktopError, DesktopResult}; -use crate::desktop::windows; - -const MODULE: &str = "GpuiWindows"; - -struct WindowsModule; - -fn window_key(window_id: i32) -> u32 { - window_id as u32 -} - -fn value_json(value: Value) -> serde_json::Value { - match value { - Value::Null | Value::Callback(_) => serde_json::Value::Null, - Value::Bool(flag) => serde_json::Value::Bool(flag), - Value::Number(number) => serde_json::Number::from_f64(number) - .map(serde_json::Value::Number) - .unwrap_or(serde_json::Value::Null), - Value::String(text) => serde_json::Value::String(text), - Value::Array(items) => { - serde_json::Value::Array(items.into_iter().map(value_json).collect()) - } - Value::Object(fields) => serde_json::Value::Object( - fields - .into_iter() - .map(|(key, item)| (key, value_json(item))) - .collect(), - ), - Value::Buffer(bytes) => serde_json::Value::Array( - bytes - .into_iter() - .map(|byte| serde_json::Value::Number(byte.into())) - .collect(), - ), - } -} - -fn json_value(value: &serde_json::Value) -> Value { - match value { - serde_json::Value::Null => Value::Null, - serde_json::Value::Bool(flag) => Value::Bool(*flag), - serde_json::Value::Number(number) => { - number.as_f64().map(Value::Number).unwrap_or(Value::Null) - } - serde_json::Value::String(text) => Value::String(text.clone()), - serde_json::Value::Array(items) => Value::Array(items.iter().map(json_value).collect()), - serde_json::Value::Object(fields) => Value::Object( - fields - .iter() - .map(|(key, item)| (key.clone(), json_value(item))) - .collect(), - ), - } -} - -fn module_error(error: DesktopError) -> ModuleError { - ModuleError::new(error.message) -} - -fn typed(method: &'static str, result: DesktopResult) -> Result { - let mut path = Path::result(MODULE, method); - let value = json_value(&result.map_err(module_error)?); - T::from_value(value, &mut path).map_err(|error| ModuleError::new(error.message)) -} - -fn void(result: DesktopResult) -> Result<(), ModuleError> { - result.map(|_| ()).map_err(module_error) -} - -impl NativeGpuiWindowsSpec for WindowsModule { - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(_events: NativeGpuiWindowsEvents) -> Self { - Self - } - - async fn window_open(&self, options: WindowOpenOptions) -> Result { - let result = on_main(move |cx| -> DesktopResult { - let always_on_top = options.always_on_top.unwrap_or(false); - let on_all_workspaces = options.visible_on_all_workspaces.unwrap_or(false); - let open = windows::OpenWindowOptions { - component: options.component, - props: options - .props - .map(value_json) - .filter(|value| value.is_object()), - title: options.title, - width: options.width.map(|value| value as f32), - height: options.height.map(|value| value as f32), - x: options.x.map(|value| value as f32), - y: options.y.map(|value| value as f32), - resizable: options.resizable.unwrap_or(true), - // The same enum the main window's `desktop.json` maps to, so - // `transparent` and `hidden` mean one thing in both places. - title_bar: options - .title_bar - .as_deref() - .map(WindowTitleBar::from_name) - .unwrap_or_default(), - background: options - .background - .as_deref() - .map(WindowBackground::from_name) - .unwrap_or_default(), - window_buttons: options.window_buttons, - shadow: options.shadow, - traffic_light_position: options - .traffic_light_position - .map(|position| (position.x as f32, position.y as f32)), - role: windows::WindowRoleOverride::Secondary, - popup: false, - ..Default::default() - }; - let key = windows::open_window(cx, open)?; - // Both are requests the platform may not grant (Wayland has no - // raise-above, and only macOS has Spaces). A window that was asked - // for them opens anyway; `capabilities()` says what is honoured. - if always_on_top { - if let Err(error) = windows::set_always_on_top(cx, key, true) { - log::warn!("[desktop] alwaysOnTop was not applied: {error}"); - } - } - if on_all_workspaces { - if let Err(error) = windows::set_visible_on_all_workspaces(cx, key, true) { - log::warn!("[desktop] visibleOnAllWorkspaces was not applied: {error}"); - } - } - Ok(serde_json::json!({ "windowId": key })) - }) - .await?; - typed("windowOpen", result) - } - - async fn window_list(&self) -> Result { - let result = on_main(|cx| windows::list_windows(cx)).await?; - typed("windowList", result) - } - - fn window_get_state_sync(&self, window_id: i32) -> Result { - let state = crate::desktop::window_mirror::get(window_key(window_id)) - .ok_or_else(|| ModuleError::new(format!("window {window_id} is not open")))?; - typed("windowGetStateSync", Ok(state)) - } - - async fn window_get_state(&self, window_id: i32) -> Result { - let result = on_main(move |cx| windows::window_state(cx, window_key(window_id))).await?; - typed("windowGetState", result) - } - - async fn window_close(&self, window_id: i32, force: bool) -> Result<(), ModuleError> { - let result = on_main(move |cx| windows::close(cx, window_key(window_id), force)).await?; - void(result) - } - - async fn window_focus(&self, window_id: i32) -> Result<(), ModuleError> { - on_main(move |cx| windows::focus(cx, window_key(window_id))) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_set_title(&self, window_id: i32, title: String) -> Result<(), ModuleError> { - on_main(move |cx| windows::set_title(cx, window_key(window_id), title)) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_set_size( - &self, - window_id: i32, - width: f64, - height: f64, - ) -> Result<(), ModuleError> { - on_main(move |cx| windows::set_size(cx, window_key(window_id), width as f32, height as f32)) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_set_position(&self, window_id: i32, x: f64, y: f64) -> Result<(), ModuleError> { - on_main(move |cx| windows::set_position(cx, window_key(window_id), x as f32, y as f32)) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_set_min_size( - &self, - window_id: i32, - width: f64, - height: f64, - ) -> Result<(), ModuleError> { - on_main(move |cx| { - windows::set_min_size(cx, window_key(window_id), width as f32, height as f32) - }) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_set_max_size( - &self, - window_id: i32, - width: f64, - height: f64, - ) -> Result<(), ModuleError> { - on_main(move |cx| { - windows::set_max_size(cx, window_key(window_id), width as f32, height as f32) - }) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_set_resizable( - &self, - window_id: i32, - resizable: bool, - ) -> Result<(), ModuleError> { - on_main(move |cx| windows::set_resizable(cx, window_key(window_id), resizable)) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_set_fullscreen( - &self, - window_id: i32, - fullscreen: bool, - ) -> Result<(), ModuleError> { - on_main(move |cx| windows::set_fullscreen(cx, window_key(window_id), fullscreen)) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_set_always_on_top( - &self, - window_id: i32, - on_top: bool, - ) -> Result<(), ModuleError> { - on_main(move |cx| windows::set_always_on_top(cx, window_key(window_id), on_top)) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_set_visible_on_all_workspaces( - &self, - window_id: i32, - visible: bool, - ) -> Result<(), ModuleError> { - on_main(move |cx| { - windows::set_visible_on_all_workspaces(cx, window_key(window_id), visible) - }) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_minimize(&self, window_id: i32) -> Result<(), ModuleError> { - on_main(move |cx| windows::minimize(cx, window_key(window_id))) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_move_focus(&self, window_id: i32, backwards: bool) -> Result<(), ModuleError> { - on_main(move |cx| windows::move_focus(cx, window_key(window_id), backwards)) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_maximize(&self, window_id: i32) -> Result<(), ModuleError> { - on_main(move |cx| windows::maximize(cx, window_key(window_id))) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_unmaximize(&self, window_id: i32) -> Result<(), ModuleError> { - on_main(move |cx| windows::unmaximize(cx, window_key(window_id))) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_toggle_maximize(&self, window_id: i32) -> Result<(), ModuleError> { - on_main(move |cx| windows::toggle_maximize(cx, window_key(window_id))) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_set_zoom_factor(&self, window_id: i32, factor: f64) -> Result<(), ModuleError> { - on_main(move |cx| windows::set_zoom_factor(cx, window_key(window_id), factor as f32)) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_set_background_color( - &self, - window_id: i32, - color: f64, - ) -> Result<(), ModuleError> { - on_main(move |cx| windows::set_background_color(cx, window_key(window_id), color as u32)) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_set_chrome_appearance( - &self, - window_id: i32, - appearance: String, - ) -> Result<(), ModuleError> { - let dark = match appearance.as_str() { - "dark" => Some(true), - "light" => Some(false), - _ => None, - }; - on_main(move |cx| windows::set_chrome_appearance(cx, window_key(window_id), dark)) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_show(&self, window_id: i32) -> Result<(), ModuleError> { - on_main(move |cx| windows::show(cx, window_key(window_id))) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_hide(&self, window_id: i32) -> Result<(), ModuleError> { - on_main(move |cx| windows::hide(cx, window_key(window_id))) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_start_dragging(&self, window_id: i32) -> Result<(), ModuleError> { - on_main(move |cx| windows::start_dragging(cx, window_key(window_id))) - .await? - .map(|_| ()) - .map_err(module_error) - } - - async fn window_intercept_close(&self, window_id: i32, on: bool) -> Result<(), ModuleError> { - on_main(move |cx| -> DesktopResult { - let key = window_key(window_id); - let entry = cx - .global_mut::() - .0 - .get_mut(key) - .ok_or_else(|| DesktopError::not_found(format!("window {key} is not open")))?; - entry.intercept_close = on; - Ok(serde_json::Value::Null) - }) - .await? - .map(|_| ()) - .map_err(module_error) - } - - fn add_listener(&self, _event_name: String) {} - - fn remove_listeners(&self, _count: f64) {} -} - -pub fn register() { - rn_gpui_module::register( - crate::builtins::rn_gpui_specs::native_gpui_windows_module::(), - ); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/counters.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/counters.rs deleted file mode 100644 index 7f478b969e..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/counters.rs +++ /dev/null @@ -1,89 +0,0 @@ -//! Counters for the performance rules of host components and native surfaces. - -/// What is counted. -#[derive(Clone, Copy, Debug)] -#[allow(dead_code)] -pub(crate) enum Counter { - /// Lookups in the host component registry, on either side of the bridge. - HostRegistryLookups, - /// Ancestors visited to keep the native-surface counts current. A tree with - /// no native surface visits none. - NativeSurfaceWalkNodes, - /// Bytes of a host component's props copied, serialised or parsed. - /// Only an `UnsafeMixed` prop read can add to it. - HostPropsBytesCopied, - /// Calls to a host component's `update`. - HostUpdateCalls, - /// Reports the store's delivery point applied. - HostReportsDelivered, - /// Operations applied to native trees. - NativeOpsApplied, - /// Microseconds spent applying them. - NativeApplyMicros, - /// Microseconds spent building native tree elements. - NativeRenderMicros, - /// Native components made by their `create`. - NativeInstancesCreated, - /// Native components taken from the pool of removed ones instead. - NativeInstancesRecycled, - /// Times a window held its last frame for new native roots to settle. - NativeRootHolds, - /// Microseconds the windows spent holding their last frame. - NativeRootHeldMicros, - /// New native roots that did not hold the window: it was scrolling, or had - /// held for too long lately. - NativeRootHoldsSkipped, -} - -#[cfg(feature = "test-driver")] -mod enabled { - use super::Counter; - use std::sync::atomic::{AtomicU64, Ordering}; - - const COUNT: usize = 16; - static VALUES: [AtomicU64; COUNT] = [const { AtomicU64::new(0) }; COUNT]; - - pub(crate) fn add(counter: Counter, amount: u64) { - VALUES[counter as usize].fetch_add(amount, Ordering::Relaxed); - } - - pub(crate) fn read(counter: Counter) -> u64 { - VALUES[counter as usize].load(Ordering::Relaxed) - } - - pub(crate) fn reset() { - for value in &VALUES { - value.store(0, Ordering::Relaxed); - } - } -} - -#[cfg(feature = "test-driver")] -pub(crate) use enabled::{read, reset}; - -/// Adds `amount` to `counter`. -#[cfg(feature = "test-driver")] -#[inline] -pub(crate) fn add(counter: Counter, amount: u64) { - enabled::add(counter, amount); -} - -/// Adds `amount` to `counter`. Nothing without the `test-driver` feature. -#[cfg(not(feature = "test-driver"))] -#[inline(always)] -pub(crate) fn add(_counter: Counter, _amount: u64) {} - -/// Counts one occurrence. -#[inline(always)] -pub(crate) fn bump(counter: Counter) { - add(counter, 1); -} - -/// Counts bytes of a host component's props that were copied, for the generated -/// accessor that reads an `UnsafeMixed` prop. Public because generated code in a -/// package calls it. -#[doc(hidden)] -#[inline] -pub fn note_props_bytes_copied(bytes: usize) { - add(Counter::HostPropsBytesCopied, bytes as u64); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/cpp_host.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/cpp_host.rs deleted file mode 100644 index 502d6a24f6..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/cpp_host.rs +++ /dev/null @@ -1,135 +0,0 @@ -//! The Rust half of a host component implemented in C++ (`cpp: true` in -//! `hostComponents`): it forwards the node's props and lifecycle to the C++ -//! view and hands core the native view it creates. - -use crate::host_component::{HostArg, HostContext, HostObject, PropsHandle}; -use crate::native_surface::{NativeViewHandle, NativeViewParent, Result}; -use gpui::{div, prelude::*, AnyElement, Window}; - -pub(crate) struct CppHostObject { - id: u64, - /// Keeps the props the C++ view last saw alive. - props: PropsHandle, -} - -impl CppHostObject { - /// Creates the C++ view of component `index`, or `None` when no C++ - /// implementation is registered for it. - pub(crate) fn create(index: u32, tag: i32, props: PropsHandle) -> Option { - let id = rn_gpui_sys::ffi::rn_gpui_cpp_host_create(index, tag, props.as_ptr() as usize); - (id != 0).then_some(Self { id, props }) - } -} - -impl Drop for CppHostObject { - fn drop(&mut self) { - rn_gpui_sys::ffi::rn_gpui_cpp_host_destroy(self.id); - } -} - -impl HostObject for CppHostObject { - fn update(&mut self, props: PropsHandle, _changed: &[u64], _cx: HostContext) { - rn_gpui_sys::ffi::rn_gpui_cpp_host_update(self.id, props.as_ptr() as usize); - self.props = props; - } - - fn render(&mut self, _window: &mut Window, _cx: HostContext) -> AnyElement { - div().size_full().into_any_element() - } - - fn render_overlay(&mut self, _window: &mut Window, _cx: HostContext) -> Option { - None - } - - fn command(&mut self, _index: u32, _args: &[HostArg], _cx: HostContext) {} - - fn create_view( - &mut self, - parent: &NativeViewParent<'_>, - window: &mut Window, - _cx: HostContext, - ) -> Result { - let mut raw = RawParent::default(); - fill_parent(&mut raw, parent, window)?; - let mut kind = 0u8; - let value = rn_gpui_sys::ffi::rn_gpui_cpp_host_create_view( - self.id, - raw.windows_visual, - raw.wayland, - raw.x11_window, - raw.xcb_connection, - raw.wayland_display, - raw.wayland_surface, - &mut kind, - ); - Ok(match kind { - #[cfg(target_os = "macos")] - // SAFETY: the C++ view returned an owned (+1) NSView. - 1 if value != 0 => unsafe { - NativeViewHandle::from_owned_nsview(value as usize as *mut std::ffi::c_void) - }, - #[cfg(target_os = "linux")] - 2 if value != 0 => NativeViewHandle::from_x11_window(value as u32), - _ => NativeViewHandle::composited(), - }) - } -} - -#[derive(Default)] -struct RawParent { - windows_visual: usize, - wayland: bool, - x11_window: u32, - xcb_connection: usize, - wayland_display: usize, - wayland_surface: usize, -} - -#[cfg(target_os = "macos")] -fn fill_parent( - _raw: &mut RawParent, - _parent: &NativeViewParent<'_>, - _window: &Window, -) -> Result<()> { - Ok(()) -} - -#[cfg(target_os = "windows")] -fn fill_parent(raw: &mut RawParent, parent: &NativeViewParent<'_>, _window: &Window) -> Result<()> { - use windows::core::{IUnknown, Interface as _}; - let visual = parent - .visual()? - .downcast::() - .map_err(|_| anyhow::anyhow!("the composition visual is not an IUnknown"))?; - // The raw pointer is borrowed for the call only; the surface keeps the - // visual alive. - raw.windows_visual = visual.as_raw() as usize; - Ok(()) -} - -#[cfg(target_os = "linux")] -fn fill_parent(raw: &mut RawParent, parent: &NativeViewParent<'_>, window: &Window) -> Result<()> { - use raw_window_handle::{HasDisplayHandle as _, RawDisplayHandle, RawWindowHandle}; - let display = window - .display_handle() - .map_err(|error| anyhow::anyhow!("no display handle: {error}"))? - .as_raw(); - match parent.raw_window_handle()? { - RawWindowHandle::Xcb(handle) => { - raw.x11_window = handle.window.get(); - if let RawDisplayHandle::Xcb(display) = display { - raw.xcb_connection = display.connection.map_or(0, |c| c.as_ptr() as usize); - } - } - RawWindowHandle::Xlib(handle) => raw.x11_window = handle.window as u32, - RawWindowHandle::Wayland(handle) => { - raw.wayland = true; - raw.wayland_surface = handle.surface.as_ptr() as usize; - if let RawDisplayHandle::Wayland(display) = display { - raw.wayland_display = display.display.as_ptr() as usize; - } - } - other => anyhow::bail!("a C++ host component cannot draw into a {other:?} surface"), - } - Ok(()) -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/app_dir.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/app_dir.rs deleted file mode 100644 index adf36648dc..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/app_dir.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! Where the app keeps small files of its own. - -use std::path::PathBuf; - -/// `/rn-gpui`, which holds window state, I18nManager -/// settings and the single-instance lock. `RN_GPUI_APP_DATA_DIR` replaces the -/// per-user config dir. -pub fn app_dir() -> PathBuf { - app_dir_in(data_dir_override()) -} - -/// The folder `RN_GPUI_APP_DATA_DIR` names, when it is set and not empty. -pub fn data_dir_override() -> Option { - std::env::var_os("RN_GPUI_APP_DATA_DIR") - .filter(|dir| !dir.is_empty()) - .map(PathBuf::from) -} - -fn app_dir_in(override_dir: Option) -> PathBuf { - if let Some(dir) = override_dir { - return dir.join("rn-gpui"); - } - #[cfg(target_os = "macos")] - let base = std::env::var_os("HOME") - .map(|home| PathBuf::from(home).join("Library/Application Support")); - #[cfg(target_os = "windows")] - let base = std::env::var_os("APPDATA").map(PathBuf::from); - #[cfg(not(any(target_os = "macos", target_os = "windows")))] - let base = std::env::var_os("XDG_CONFIG_HOME") - .map(PathBuf::from) - .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config"))); - base.unwrap_or_else(std::env::temp_dir).join("rn-gpui") -} - -/// An app id as a file name part. -pub fn safe_id(app_id: &str) -> String { - app_id.replace( - |c: char| !c.is_ascii_alphanumeric() && c != '-' && c != '_', - "_", - ) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn override_replaces_the_base_folder() { - assert_eq!( - app_dir_in(Some(PathBuf::from("/data/one"))), - PathBuf::from("/data/one").join("rn-gpui") - ); - assert_ne!(app_dir_in(None), PathBuf::from("/data/one").join("rn-gpui")); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/app_menu.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/app_menu.rs deleted file mode 100644 index c1bceb681a..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/app_menu.rs +++ /dev/null @@ -1,1603 +0,0 @@ -//! GPUI derives an `NSMenuItem` key equivalent from the keymap binding for the -//! exact action value, and `Keymap` has no per-binding removal, so the desktop -//! bindings are filtered out and re-added whenever the menu changes. The Edit -//! roles act on the focused RN text input: `OsAction::Copy` needs an -//! `NSTextView` first responder, which GPUI-drawn inputs are not. - -use crate::desktop::errors::{DesktopError, DesktopResult}; -use crate::desktop::menu_model::{self, MenuItemDef, MenuModel, MenuNode, MenuRole, SubmenuDef}; -use crate::desktop::windows::DesktopWindowsGlobal; -use crate::node_view::RNNodeView; -use crate::store::store_from; -use gpui::{Action, App, Entity, KeyBinding, Menu, MenuItem, SharedString, SystemMenuType}; -use serde_json::{json, Value}; - -#[derive(Clone, Debug, PartialEq, gpui::Action)] -#[action(namespace = rn_gpui_desktop, no_json, no_register)] -pub struct MenuAccelerator { - pub id: String, -} - -#[derive(Clone, Debug, PartialEq, gpui::Action)] -#[action(namespace = rn_gpui_desktop, no_json, no_register)] -pub struct MenuEditAction { - pub kind: String, -} - -#[derive(Clone, Debug, PartialEq, gpui::Action)] -#[action(namespace = rn_gpui_desktop, no_json, no_register)] -pub struct MenuHostAction { - pub kind: String, -} - -#[derive(Clone, Debug, PartialEq)] -pub enum AcceleratorAction { - Press(String), - Edit(String), - Host(String), - /// A Developer menu command, performed by the host like the dev menu's own - /// buttons. - Dev(String), -} - -pub struct AppMenuState { - pub model: MenuModel, - pub user_set: bool, - pub app_name: String, - pub bindings: Vec<(String, String)>, - pub accelerators: Vec<(gpui::Keystroke, AcceleratorAction)>, - pub _interceptor: Option, - pub rebuild_scheduled: bool, - /// Windows only: the attached `muda` menu bar and the HWND it is on. - /// - /// `muda::Menu::init_for_hwnd` installs a window subclass whose `dwRefData` - /// points into the `Menu`, so the `Menu` has to outlive the subclass. The - /// value is held here, in a global that lives as long as the app, and the - /// subclass is detached before it is replaced, otherwise the next message - /// this window receives (a resize, a paint) calls through a dangling - /// pointer and the process dies with `STATUS_STACK_BUFFER_OVERRUN`. - #[cfg(target_os = "windows")] - pub platform_menu: Option<(muda::Menu, isize)>, -} - -pub struct AppMenuGlobal(pub AppMenuState); -impl gpui::Global for AppMenuGlobal {} - -impl AppMenuGlobal { - pub fn new(app_name: String) -> Self { - Self(AppMenuState { - model: default_menu(&app_name), - user_set: false, - app_name, - bindings: Vec::new(), - accelerators: Vec::new(), - _interceptor: None, - rebuild_scheduled: false, - #[cfg(target_os = "windows")] - platform_menu: None, - }) - } -} - -/// Detaches the attached menu bar when the global is dropped, so a window that -/// outlives the menu state never keeps a subclass pointing into freed memory. -#[cfg(target_os = "windows")] -impl Drop for AppMenuGlobal { - fn drop(&mut self) { - if let Some((menu, hwnd)) = self.0.platform_menu.take() { - remove_platform_menu(menu, hwnd); - } - } -} - -pub fn install(cx: &mut App, app_name: &str, dev_menu: bool) { - cx.set_global(DevMenuEnabled(dev_menu)); - cx.set_global(AppMenuGlobal::new(app_name.to_string())); - let model = default_menu(app_name); - let _ = apply(cx, model, false); - cx.on_action(|action: &MenuAccelerator, cx: &mut App| { - trigger_item(cx, &action.id); - }); - cx.on_action(|action: &MenuEditAction, cx: &mut App| { - perform_edit(cx, &action.kind, None); - }); - cx.on_action(|action: &MenuHostAction, cx: &mut App| { - perform_host_action(cx, &action.kind, None); - }); - // The keymap binding is what makes macOS draw the shortcut in the NSMenu and - // what the menu item dispatches. Keystrokes are matched here as well, - // because a window with no focused element has no dispatch path for the - // keymap to resolve, and a global shortcut must work in that state too. - let interceptor = cx.intercept_keystrokes(|event, window, cx| { - // Yield to a shortcut. The keymap resolves a keystroke from the focused - // element's context, and a shortcut in a scope outranks the app-wide - // menu accelerator — but an interceptor runs *before* the keymap is - // consulted, so handling the key here would take it away from a shortcut - // that is entitled to it. Asking the keymap first is what keeps the - // precedence the rest of this design promises. - if let Some(id) = - crate::desktop::keymap::unfocused_app_shortcut(cx, window, &event.keystroke) - { - crate::desktop::keymap::emit_app_shortcut(cx, &id, None); - if let Some(store) = store_from(cx) { - store.read(cx).frame_hook.arm(window); - } - cx.stop_propagation(); - return; - } - if crate::desktop::keymap::claims_keystroke(cx, window, &event.keystroke) { - return; - } - if handle_accelerator(cx, window, &event.keystroke) { - cx.stop_propagation(); - } - }); - cx.global_mut::().0._interceptor = Some(interceptor); -} - -pub fn trigger_item(cx: &mut App, id: &str) { - match accelerator_action(id) { - AcceleratorAction::Press(id) => emit_menu_press(cx, &id), - AcceleratorAction::Edit(kind) => perform_edit(cx, &kind, None), - AcceleratorAction::Host(kind) => perform_host_action(cx, &kind, None), - AcceleratorAction::Dev(id) => perform_dev_action(cx, id), - } -} - -pub fn handle_accelerator( - cx: &mut App, - window: &mut gpui::Window, - keystroke: &gpui::Keystroke, -) -> bool { - let action = { - let state = &cx.global::().0; - state - .accelerators - .iter() - .find(|(bound, _)| bound == keystroke) - .map(|(_, action)| action.clone()) - }; - if std::env::var_os("RN_GPUI_DEBUG_DESKTOP").is_some() { - // `RN_GPUI_DEBUG_DESKTOP=1` logs every keystroke the interceptor sees. - let installed = cx - .global::() - .0 - .accelerators - .iter() - .map(|(bound, _)| bound.unparse(crate::desktop::keymap::host_os())) - .collect::>(); - log::info!( - "[desktop] keystroke {} matched={} installed=[{}]", - keystroke.unparse(crate::desktop::keymap::host_os()), - action.is_some(), - installed.join(", ") - ); - } - let Some(action) = action else { - return false; - }; - // The window comes from the keystroke, not `active_window()`: a hidden or - // off-screen window (the test driver's) is not the platform's active one. - let handle: gpui::AnyWindowHandle = window.window_handle().into(); - match action { - AcceleratorAction::Press(id) => emit_menu_press(cx, &id), - AcceleratorAction::Edit(kind) => perform_edit(cx, &kind, Some(handle)), - AcceleratorAction::Host(kind) => perform_host_action(cx, &kind, Some(handle)), - AcceleratorAction::Dev(id) => perform_dev_action(cx, id), - } - // The JS listener needs a frame to run in. - if let Some(store) = store_from(cx) { - store.read(cx).frame_hook.arm(window); - } - true -} - -pub fn set_application_menu(cx: &mut App, items: Option<&Value>) -> DesktopResult { - let model = match items { - Some(value) => menu_model::parse_menu(value)?, - None => default_menu(&app_name(cx)), - }; - let user_set = items.is_some(); - apply(cx, model, user_set)?; - Ok(json!({"items": current_model(cx).ids().len()})) -} - -/// Sets the menu of the Dock icon. Its items report as `menuPress` like the -/// application menu's. Other platforms have no Dock, so nothing happens there. -pub fn set_dock_menu(cx: &mut App, items: Option<&Value>) -> DesktopResult { - let model = match items { - Some(value) => menu_model::parse_menu(value)?, - None => MenuModel { items: Vec::new() }, - }; - #[cfg(target_os = "macos")] - cx.set_dock_menu(build_items(&model.items)); - #[cfg(not(target_os = "macos"))] - let _ = &model; - Ok(json!({"items": model.ids().len()})) -} - -pub fn update_item(cx: &mut App, id: &str, patch: &Value) -> DesktopResult { - let patch = patch - .as_object() - .ok_or_else(|| DesktopError::invalid_argument("a menu patch must be an object"))?; - { - let state = &mut cx.global_mut::().0; - let Some(item) = find_item_mut(&mut state.model.items, id) else { - return Err(DesktopError::not_found(format!( - "menu item {id} is not set" - ))); - }; - if let Some(label) = patch.get("label") { - item.label = label - .as_str() - .ok_or_else(|| DesktopError::invalid_argument("`label` must be a string"))? - .to_string(); - } - if let Some(enabled) = patch.get("enabled") { - item.enabled = enabled - .as_bool() - .ok_or_else(|| DesktopError::invalid_argument("`enabled` must be a boolean"))?; - } - if let Some(checked) = patch.get("checked") { - item.checked = checked - .as_bool() - .ok_or_else(|| DesktopError::invalid_argument("`checked` must be a boolean"))?; - } - } - schedule_rebuild(cx); - Ok(json!({"id": id})) -} - -/// Shows or hides the in-window menu bar of one window. -/// -/// Windows detaches the `muda` menu from the HWND rather than destroying it: the -/// menu stays alive in the global so the same items can be shown again, and -/// accelerators are GPUI key bindings that never went through the menu widget, so -/// they keep working either way. Linux skips attaching the bar and drops the -/// inset, which is what makes the React surface grow into the space. -pub fn set_menu_bar_visible(cx: &mut gpui::App, window_id: u32, visible: bool) -> DesktopResult { - crate::desktop::gpui_menu::set_menu_bar_visible(window_id, visible); - #[cfg(target_os = "windows")] - { - set_windows_menu_attached(cx, window_id, visible)?; - } - #[cfg(not(target_os = "windows"))] - { - let _ = cx; - } - // The surface size follows the bar, and the window has to relayout for the - // inset change to reach the React root. - crate::desktop::gpui_menu::resize_surfaces_for_menu_bar(cx, window_id); - Ok(json!({"windowId": window_id, "menuBarVisible": visible})) -} - -/// Reserves, or with `None` gives back, the room a window's React tree keeps for -/// the menu bar. The bar is then drawn there, and the top of the window stops -/// being a strip of its own. -pub fn set_menu_bar_slot( - cx: &mut gpui::App, - window_id: u32, - slot: Option, -) -> DesktopResult { - crate::desktop::gpui_menu::set_menu_bar_slot(window_id, slot); - crate::desktop::gpui_menu::resize_surfaces_for_menu_bar(cx, window_id); - Ok(json!({"windowId": window_id, "slot": slot.is_some()})) -} - -pub fn menu_json(cx: &App) -> Value { - let state = &cx.global::().0; - json!({ - "appName": state.app_name, - "userSet": state.user_set, - "items": nodes_json(&state.model.items), - // The main window's bar, which is the one an app asks about. A hidden - // bar is per window, so this reports the window the call is about. - "menuBarVisible": !crate::desktop::gpui_menu::menu_bar_hidden( - crate::desktop::windows::MAIN_WINDOW_KEY, - ), - }) -} - -fn nodes_json(items: &[MenuNode]) -> Vec { - items - .iter() - .map(|node| match node { - MenuNode::Separator => json!({"type": "separator"}), - MenuNode::StandardMenu(role) => { - json!({"type": "role", "role": role_name(*role)}) - } - MenuNode::Submenu(submenu) => json!({ - "type": "submenu", - "id": submenu.id, - "label": submenu.label, - "enabled": submenu.enabled, - "items": nodes_json(&submenu.items), - "icon": submenu.icon, - }), - MenuNode::Item(item) => json!({ - "type": "item", - "id": item.id, - "label": item.label, - "accelerator": item.accelerator, - "enabled": item.enabled, - "checked": item.checked, - "role": item.role.map(role_name), - "icon": item.icon, - }), - }) - .collect() -} - -fn role_name(role: MenuRole) -> &'static str { - match role { - MenuRole::About => "about", - MenuRole::Services => "services", - MenuRole::Hide => "hide", - MenuRole::HideOthers => "hideOthers", - MenuRole::ShowAll => "showAll", - MenuRole::Quit => "quit", - MenuRole::Undo => "undo", - MenuRole::Redo => "redo", - MenuRole::Cut => "cut", - MenuRole::Copy => "copy", - MenuRole::Paste => "paste", - MenuRole::PasteWithoutFormatting => "pasteWithoutFormatting", - MenuRole::SelectAll => "selectAll", - MenuRole::Minimize => "minimize", - MenuRole::Zoom => "zoom", - MenuRole::ZoomIn => "zoomIn", - MenuRole::ZoomOut => "zoomOut", - MenuRole::ResetZoom => "resetZoom", - MenuRole::ToggleFullscreen => "toggleFullscreen", - MenuRole::Close => "close", - MenuRole::Help => "help", - MenuRole::AppMenu => "appMenu", - MenuRole::EditMenu => "editMenu", - MenuRole::WindowMenu => "windowMenu", - MenuRole::HelpMenu => "helpMenu", - } -} - -fn find_item_mut<'a>(items: &'a mut [MenuNode], id: &str) -> Option<&'a mut MenuItemDef> { - for node in items { - match node { - MenuNode::Item(item) if item.id == id => return Some(item), - MenuNode::Submenu(submenu) => { - if let Some(found) = find_item_mut(&mut submenu.items, id) { - return Some(found); - } - } - _ => {} - } - } - None -} - -pub fn current_model(cx: &App) -> MenuModel { - cx.global::().0.model.clone() -} - -pub fn app_name(cx: &App) -> String { - cx.global::().0.app_name.clone() -} - -pub fn standard_menu_nodes(role: MenuRole, app_name: &str, dev_menu: bool) -> Vec { - let item = |role: MenuRole| { - MenuNode::Item(MenuItemDef { - id: role_action_id(role).to_string(), - label: role.default_label().to_string(), - accelerator: default_accelerator(role).map(str::to_string), - enabled: true, - checked: false, - role: Some(role), - icon: None, - }) - }; - let items = |roles: &[MenuRole]| roles.iter().map(|role| item(*role)).collect(); - match role { - MenuRole::AppMenu => vec![ - MenuNode::Item(MenuItemDef { - id: role_action_id(MenuRole::About).to_string(), - label: format!("About {app_name}"), - accelerator: None, - enabled: true, - checked: false, - role: Some(MenuRole::About), - icon: None, - }), - MenuNode::Separator, - item(MenuRole::Hide), - item(MenuRole::HideOthers), - item(MenuRole::ShowAll), - MenuNode::Separator, - item(MenuRole::Quit), - ], - MenuRole::EditMenu => { - let mut nodes: Vec = items(&[MenuRole::Undo, MenuRole::Redo]); - nodes.push(MenuNode::Separator); - nodes.extend(items(&[ - MenuRole::Cut, - MenuRole::Copy, - MenuRole::Paste, - MenuRole::SelectAll, - ])); - nodes - } - MenuRole::WindowMenu => items(&[ - MenuRole::Minimize, - MenuRole::Zoom, - MenuRole::ToggleFullscreen, - MenuRole::Close, - ]), - MenuRole::HelpMenu => { - let mut nodes = Vec::new(); - if dev_menu { - nodes.push(MenuNode::Submenu(SubmenuDef { - id: Some("dev".to_string()), - label: "Developer".to_string(), - enabled: true, - icon: None, - items: [ - (crate::desktop::dev_menu::RELOAD, "Reload"), - (crate::desktop::dev_menu::OPEN_DEVTOOLS, "Open DevTools"), - ( - crate::desktop::dev_menu::ELEMENT_INSPECTOR, - "Toggle Element Inspector", - ), - ( - crate::desktop::dev_menu::PERF_MONITOR, - "Toggle Perf Monitor", - ), - (crate::desktop::dev_menu::FAST_REFRESH, "Fast Refresh"), - ] - .into_iter() - .map(|(id, label)| { - MenuNode::Item(MenuItemDef { - id: id.to_string(), - label: label.to_string(), - accelerator: None, - enabled: true, - checked: false, - role: None, - icon: None, - }) - }) - .collect(), - })); - } - nodes - } - other => vec![item(other)], - } -} - -pub struct DevMenuEnabled(pub bool); -impl gpui::Global for DevMenuEnabled {} - -fn dev_menu_enabled(cx: &App) -> bool { - cx.try_global::().is_some_and(|flag| flag.0) -} - -pub fn default_menu(app_name: &str) -> MenuModel { - let mut app_items = vec![ - MenuNode::Item(role_item(MenuRole::About, &format!("About {app_name}"))), - MenuNode::Separator, - ]; - if cfg!(target_os = "macos") { - app_items.push(MenuNode::Item(role_item(MenuRole::Services, "Services"))); - app_items.push(MenuNode::Separator); - } - app_items.extend([ - MenuNode::Item(role_item(MenuRole::Hide, &format!("Hide {app_name}"))), - MenuNode::Item(role_item(MenuRole::HideOthers, "Hide Others")), - MenuNode::Item(role_item(MenuRole::ShowAll, "Show All")), - MenuNode::Separator, - MenuNode::Item(role_item(MenuRole::Quit, &format!("Quit {app_name}"))), - ]); - - MenuModel { - items: vec![ - MenuNode::Submenu(menu_model::SubmenuDef { - id: None, - label: app_name.to_string(), - enabled: true, - items: app_items, - icon: None, - }), - MenuNode::StandardMenu(MenuRole::EditMenu), - MenuNode::StandardMenu(MenuRole::WindowMenu), - MenuNode::StandardMenu(MenuRole::HelpMenu), - ], - } -} - -fn role_item(role: MenuRole, label: &str) -> MenuItemDef { - MenuItemDef { - id: format!("role:{}", role_name(role)), - label: label.to_string(), - accelerator: default_accelerator(role).map(str::to_string), - enabled: role.is_supported(), - checked: false, - role: Some(role), - icon: None, - } -} - -pub fn default_accelerator(role: MenuRole) -> Option<&'static str> { - Some(match role { - MenuRole::Undo => "secondary-z", - MenuRole::Redo => "secondary-shift-z", - MenuRole::Cut => "secondary-x", - MenuRole::Copy => "secondary-c", - MenuRole::Paste => "secondary-v", - MenuRole::PasteWithoutFormatting => "secondary-shift-v", - MenuRole::SelectAll => "secondary-a", - MenuRole::Minimize => "secondary-m", - MenuRole::Close => "secondary-w", - MenuRole::Quit => "secondary-q", - MenuRole::Hide => "secondary-h", - MenuRole::HideOthers => "secondary-alt-h", - MenuRole::ToggleFullscreen => "ctrl-cmd-f", - MenuRole::ZoomIn => "secondary-=", - MenuRole::ZoomOut => "secondary--", - MenuRole::ResetZoom => "secondary-0", - _ => return None, - }) -} - -fn apply(cx: &mut App, model: MenuModel, user_set: bool) -> Result<(), DesktopError> { - let app_name = app_name(cx); - let menus = build_menus(&model, &app_name, dev_menu_enabled(cx)); - let bindings = collect_bindings(dev_menu_enabled(cx), &model); - let accelerators = replace_accelerator_bindings(cx, &bindings); - // Windows has no `cx.set_menus()`; the model is attached to the HWND - // instead. Built twice because the menu builders are not - // cloneable. - #[cfg(target_os = "windows")] - { - let platform_menus = build_menus(&model, &app_name, dev_menu_enabled(cx)); - if let Some(handle) = crate::desktop::dev_menu::main_window(cx) { - let mut attached = None; - let _ = handle.update(cx, |_root: gpui::AnyView, window, _cx| { - attached = set_platform_menus(window, &platform_menus); - }); - if let Some((bar, hwnd)) = attached { - // Replacing the bar first detaches the previous window subclass, - // which still points into the old menu; only then is that menu - // dropped, so the window never calls through freed memory. - if let Some((previous, previous_hwnd)) = cx - .global_mut::() - .0 - .platform_menu - .replace((bar, hwnd)) - { - remove_platform_menu(previous, previous_hwnd); - } - } else { - log::warn!("[desktop] could not attach the Win32 menu bar"); - } - } - } - cx.set_menus(menus); - #[cfg(target_os = "macos")] - set_menu_bar_icons(&model); - let state = &mut cx.global_mut::().0; - state.model = model; - state.user_set = user_set; - state.bindings = bindings; - state.accelerators = accelerators; - state.rebuild_scheduled = false; - Ok(()) -} - -/// GPUI's menu items have no image, so the icons are set on the `NSMenu` it -/// just installed, matching items by title the way the model nests them. -#[cfg(target_os = "macos")] -fn set_menu_bar_icons(model: &MenuModel) { - use cocoa::base::{id, nil}; - use objc::{class, msg_send, sel, sel_impl}; - - const SIZE: f64 = 16.0; - - unsafe fn item_titled(menu: id, title: &str, from: &mut isize) -> id { - let count: isize = msg_send![menu, numberOfItems]; - while *from < count { - let item: id = msg_send![menu, itemAtIndex: *from]; - *from += 1; - let ns_title: id = msg_send![item, title]; - let utf8: *const std::os::raw::c_char = msg_send![ns_title, UTF8String]; - if !utf8.is_null() && std::ffi::CStr::from_ptr(utf8).to_str() == Ok(title) { - return item; - } - } - nil - } - - unsafe fn set_image(item: id, uri: &str) { - let Some(icon) = crate::desktop::icon::cached(uri) else { - return; - }; - let Some(image) = image::RgbaImage::from_raw(icon.width, icon.height, icon.rgba.clone()) - else { - return; - }; - let mut png = Vec::new(); - if image - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .is_err() - { - return; - } - let data: id = msg_send![class!(NSData), dataWithBytes: png.as_ptr() length: png.len()]; - let ns_image: id = msg_send![class!(NSImage), alloc]; - let ns_image: id = msg_send![ns_image, initWithData: data]; - if ns_image.is_null() { - return; - } - let _: () = msg_send![ns_image, setSize: cocoa::foundation::NSSize::new(SIZE, SIZE)]; - let _: () = msg_send![item, setImage: ns_image]; - let _: () = msg_send![ns_image, release]; - } - - unsafe fn walk(menu: id, nodes: &[MenuNode]) { - if menu.is_null() { - return; - } - let mut from = 0; - for node in nodes { - match node { - MenuNode::Item(item) => { - let ns_item = item_titled(menu, &item.label, &mut from); - if let (false, Some(uri)) = (ns_item.is_null(), item.icon.as_deref()) { - if !item.checked { - set_image(ns_item, uri); - } - } - } - MenuNode::Submenu(submenu) => { - let ns_item = item_titled(menu, &submenu.label, &mut from); - if ns_item.is_null() { - continue; - } - if let Some(uri) = submenu.icon.as_deref() { - set_image(ns_item, uri); - } - let child: id = msg_send![ns_item, submenu]; - walk(child, &submenu.items); - } - MenuNode::Separator | MenuNode::StandardMenu(_) => {} - } - } - } - - // SAFETY: called on the main thread right after GPUI installed the menu, - // which it keeps alive as the application's main menu. - unsafe { - let app: id = msg_send![class!(NSApplication), sharedApplication]; - let main_menu: id = msg_send![app, mainMenu]; - walk(main_menu, &model.items); - } -} - -/// The titles of the menu bar's items that show an image. macOS only; the -/// test driver reads it, because the bar's images live in AppKit. -pub fn menu_bar_image_titles() -> Vec { - #[cfg(target_os = "macos")] - { - use cocoa::base::id; - use objc::{class, msg_send, sel, sel_impl}; - - unsafe fn walk(menu: id, out: &mut Vec) { - if menu.is_null() { - return; - } - let count: isize = msg_send![menu, numberOfItems]; - for index in 0..count { - let item: id = msg_send![menu, itemAtIndex: index]; - let image: id = msg_send![item, image]; - if !image.is_null() { - let title: id = msg_send![item, title]; - let utf8: *const std::os::raw::c_char = msg_send![title, UTF8String]; - if !utf8.is_null() { - out.push( - std::ffi::CStr::from_ptr(utf8) - .to_string_lossy() - .into_owned(), - ); - } - } - let submenu: id = msg_send![item, submenu]; - walk(submenu, out); - } - } - - let mut out = Vec::new(); - // SAFETY: read on the main thread from the application's main menu. - unsafe { - let app: id = msg_send![class!(NSApplication), sharedApplication]; - let main_menu: id = msg_send![app, mainMenu]; - walk(main_menu, &mut out); - } - out - } - #[cfg(not(target_os = "macos"))] - Vec::new() -} - -fn schedule_rebuild(cx: &mut App) { - { - let state = &mut cx.global_mut::().0; - if state.rebuild_scheduled { - return; - } - state.rebuild_scheduled = true; - } - let Some(window) = cx.active_window() else { - rebuild_now(cx); - return; - }; - let _ = window.update(cx, |_root, window, _cx| { - window.on_next_frame(move |_window, cx| { - let scheduled = cx - .try_global::() - .is_some_and(|state| state.0.rebuild_scheduled); - if scheduled { - rebuild_now(cx); - } - }); - }); -} - -fn rebuild_now(cx: &mut App) { - let model = current_model(cx); - let app_name = app_name(cx); - let user_set = cx.global::().0.user_set; - let _ = apply(cx, model, user_set); - let _ = app_name; -} - -fn collect_bindings(dev_menu: bool, model: &MenuModel) -> Vec<(String, String)> { - let mut bindings = model.accelerators(); - collect_role_bindings(&model.items, &mut bindings); - if dev_menu { - bindings.push(( - crate::desktop::dev_menu::ACCELERATOR_ID.to_string(), - crate::desktop::dev_menu::ACCELERATOR.to_string(), - )); - } - bindings -} - -fn collect_role_bindings(items: &[MenuNode], out: &mut Vec<(String, String)>) { - for node in items { - match node { - MenuNode::Item(item) => { - if let Some(role) = item.role { - if let Some(accelerator) = default_accelerator(role) { - out.push((item.id.clone(), accelerator.to_string())); - } - } - } - MenuNode::Submenu(submenu) => collect_role_bindings(&submenu.items, out), - MenuNode::StandardMenu(role) => { - for (id, accelerator) in standard_menu_bindings(*role) { - out.push((id.to_string(), accelerator.to_string())); - } - } - _ => {} - } - } -} - -fn standard_menu_bindings(role: MenuRole) -> Vec<(&'static str, &'static str)> { - let roles: &[MenuRole] = match role { - MenuRole::EditMenu => &[ - MenuRole::Undo, - MenuRole::Redo, - MenuRole::Cut, - MenuRole::Copy, - MenuRole::Paste, - MenuRole::SelectAll, - ], - MenuRole::WindowMenu => &[ - MenuRole::Minimize, - MenuRole::Zoom, - MenuRole::ToggleFullscreen, - MenuRole::Close, - ], - _ => &[], - }; - roles - .iter() - .filter_map(|role| { - let accelerator = default_accelerator(*role)?; - Some((role_action_id(*role), accelerator)) - }) - .collect() -} - -pub fn role_action_id(role: MenuRole) -> &'static str { - match role { - MenuRole::Undo => "role:undo", - MenuRole::Redo => "role:redo", - MenuRole::Cut => "role:cut", - MenuRole::Copy => "role:copy", - MenuRole::Paste => "role:paste", - MenuRole::PasteWithoutFormatting => "role:pasteWithoutFormatting", - MenuRole::SelectAll => "role:selectAll", - MenuRole::Minimize => "role:minimize", - MenuRole::Zoom => "role:zoom", - MenuRole::ZoomIn => "role:zoomIn", - MenuRole::ZoomOut => "role:zoomOut", - MenuRole::ResetZoom => "role:resetZoom", - MenuRole::ToggleFullscreen => "role:toggleFullscreen", - MenuRole::Close => "role:close", - MenuRole::Quit => "role:quit", - MenuRole::Hide => "role:hide", - MenuRole::HideOthers => "role:hideOthers", - MenuRole::ShowAll => "role:showAll", - MenuRole::About => "role:about", - _ => "role:menu", - } -} - -fn is_desktop_action(action: &dyn Action) -> bool { - action.as_any().downcast_ref::().is_some() - || action.as_any().downcast_ref::().is_some() - || action.as_any().downcast_ref::().is_some() -} - -/// Windows: `muda` attaches a native Win32 menu to the window's HWND. -/// -/// Attaches or detaches the native menu bar on the window's HWND. -/// -/// `muda` 0.15 has no hide/show for an HWND, so this uses `SetMenu` directly and -/// keeps the `muda::Menu` alive in `AppMenuGlobal` either way: detaching is what -/// hiding means, and the same menu is re-attached to show it again. The window -/// subclass `muda` installed stays in place, so clicks still route back to the -/// same dispatch when the bar returns. -#[cfg(target_os = "windows")] -fn set_windows_menu_attached(cx: &mut gpui::App, window_id: u32, visible: bool) -> DesktopResult { - use muda::ContextMenu as _; - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - use windows_sys::Win32::UI::WindowsAndMessaging::{DrawMenuBar, SetMenu}; - - let menu = if visible { - // Re-attach the menu that is still held in the global: hiding detached it - // rather than destroying it, so the same items come back. `hpopupmenu` is - // on muda's `ContextMenu` trait, not on `Menu` itself. - cx.try_global::() - .and_then(|global| global.0.platform_menu.as_ref()) - .map(|(menu, _)| menu.hpopupmenu() as isize) - .unwrap_or(0) - } else { - 0 - }; - crate::desktop::windows::with_window(cx, window_id, move |window| { - let Ok(handle) = HasWindowHandle::window_handle(window) else { - return Err(DesktopError::failed("window has no handle")); - }; - let RawWindowHandle::Win32(win32) = handle.as_raw() else { - return Err(DesktopError::failed("window handle is not Win32")); - }; - // SAFETY: the `HWND` comes from the window's raw handle and `menu` is the live popup menu this module owns. - unsafe { - SetMenu(win32.hwnd.get() as _, menu as _); - // The client size changed, so the frame has to be redrawn; GPUI picks - // the new size up from the `WM_SIZE` that follows. - DrawMenuBar(win32.hwnd.get() as _); - } - Ok(()) - }) -} - -/// The built `muda::Menu` is returned rather than dropped: installing it leaves -/// a window subclass whose `dwRefData` points into the menu, so dropping it here -/// would leave the window calling through freed memory on its next message. -#[cfg(target_os = "windows")] -fn set_platform_menus(window: &mut gpui::Window, menus: &[Menu]) -> Option<(muda::Menu, isize)> { - use super::context_menu::MudaAppend as _; - use muda::{ - CheckMenuItem, Menu as MudaMenu, MenuItem as MudaItem, PredefinedMenuItem, Submenu, - }; - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - - // The id for a menu-bar item, so a click can be routed back to the action it - // stands for. `build_item` put the id in a `MenuAccelerator` action; that is - // the same value the accelerator table and the JS `menuPress` event use, so - // one id means one action however the user reached it. - fn action_id(action: &dyn gpui::Action) -> Option { - action - .as_any() - .downcast_ref::() - .map(|accelerator| accelerator.id.clone()) - } - - fn build(menu: &Menu, items: &mut Vec>) { - for item in &menu.items { - match item { - MenuItem::Separator => items.push(Box::new(PredefinedMenuItem::separator())), - MenuItem::Submenu(submenu) => { - let child = Submenu::new(submenu.name.to_string(), !submenu.disabled); - let mut child_items: Vec> = Vec::new(); - build(submenu, &mut child_items); - let refs: Vec<&dyn muda::IsMenuItem> = - child_items.iter().map(|item| item.as_ref()).collect(); - let _ = child.append_all(&refs); - items.push(Box::new(child)); - } - MenuItem::Action { - name, - action, - checked, - disabled, - .. - } => { - // The id travels as the muda item's id, which is what a - // `MenuEvent` reports. Without it a click on the menu bar is - // indistinguishable from any other item's, which is why - // nothing happened before. - // - // A checked item must be a `CheckMenuItem` in muda; a plain - // one has no `set_checked`. `disabled` is honoured for both: - // a checked-but-disabled item used to be enabled regardless. - let id = action_id(action.as_ref()); - match (*checked, id) { - (true, Some(id)) => items.push(Box::new(CheckMenuItem::with_id( - id, - name.to_string(), - !*disabled, - true, - None, - ))), - (true, None) => items.push(Box::new(CheckMenuItem::new( - name.to_string(), - !*disabled, - true, - None, - ))), - (false, Some(id)) => items.push(Box::new(MudaItem::with_id( - id, - name.to_string(), - !*disabled, - None, - ))), - (false, None) => { - items.push(Box::new(MudaItem::new(name.to_string(), !*disabled, None))) - } - } - } - // The Services menu is a macOS concept; there is no Windows - // equivalent to attach to the menu bar. - MenuItem::SystemMenu(_) => {} - } - } - } - - let handle = match HasWindowHandle::window_handle(window) { - Ok(handle) => handle, - Err(_) => return None, - }; - let hwnd = match handle.as_raw() { - RawWindowHandle::Win32(win32) => win32.hwnd.get() as isize, - _ => return None, - }; - let mut bar = MudaMenu::new(); - let mut bar_items: Vec> = Vec::new(); - for menu in menus { - let submenu = Submenu::new(menu.name.to_string(), !menu.disabled); - let mut menu_items: Vec> = Vec::new(); - build(menu, &mut menu_items); - let refs: Vec<&dyn muda::IsMenuItem> = - menu_items.iter().map(|item| item.as_ref()).collect(); - let _ = submenu.append_all(&refs); - bar_items.push(Box::new(submenu)); - } - let refs: Vec<&dyn muda::IsMenuItem> = bar_items.iter().map(|item| item.as_ref()).collect(); - let _ = bar.append_all(&refs); - // SAFETY: `hwnd` is the live window handle this menu bar is built for. - if unsafe { bar.init_for_hwnd(hwnd) }.is_err() { - return None; - } - // Route menu-bar clicks to the same dispatch an accelerator uses, so one id - // means one action however the user reached it. - // - // Registration goes through the app's single `muda` event route - // (`desktop::menu_events`), not a private handler: `muda` exposes one event - // channel and its handler setter is first-caller-wins, so a handler per menu - // system would silently starve the others. The predicate accepts everything, - // so it is registered last and acts as the fallback — a menu-bar id is - // authoritative here, and `trigger_item` already forwards an id it does not - // recognise to JS as a `menuPress` event. - crate::desktop::menu_events::register(Box::new(|id| { - if let Some(handler) = rn_gpui_sys::MENU_BAR_PERFORM_HANDLER.get() { - handler(id.to_string()); - return true; - } - false - })); - Some((bar, hwnd)) -} - -/// Windows: detaches an attached menu bar and drops it. -/// -/// `muda::Menu::remove_for_hwnd` clears the Win32 menu but leaves the window -/// subclass it installed in place; that subclass holds a raw pointer into the -/// menu. It has to be detached explicitly before the menu is dropped, otherwise -/// the next message the window receives calls into freed memory. -#[cfg(target_os = "windows")] -fn remove_platform_menu(mut menu: muda::Menu, hwnd: isize) { - use muda::ContextMenu as _; - // SAFETY: `hwnd` is the window the menu was attached to, and it is detached once. - unsafe { - menu.detach_menu_subclass_from_hwnd(hwnd); - let _ = menu.remove_for_hwnd(hwnd); - } -} - -fn replace_accelerator_bindings( - cx: &mut App, - bindings: &[(String, String)], -) -> Vec<(gpui::Keystroke, AcceleratorAction)> { - let keymap = cx.key_bindings(); - let kept: Vec = keymap - .borrow() - .bindings() - .filter(|binding| !is_desktop_action(binding.action())) - .cloned() - .collect(); - // Of two bindings for one key in one context the later one wins, and a - // shortcut has to win over a menu accelerator, so the shortcut bindings go - // back after the menu's. - let (shortcut_bindings, kept): (Vec, Vec) = kept - .into_iter() - .partition(|binding| crate::desktop::keymap::is_shortcut_action(binding.action())); - { - let mut keymap = keymap.borrow_mut(); - keymap.clear(); - keymap.add_bindings(kept); - } - - let mut new_bindings: Vec = Vec::with_capacity(bindings.len()); - let mut accelerators: Vec<(gpui::Keystroke, AcceleratorAction)> = Vec::new(); - for (id, keystroke) in bindings { - if keystroke.is_empty() { - continue; - } - let action = accelerator_action(id); - match binding_for(keystroke, &action, cx) { - Ok(binding) => new_bindings.push(binding), - Err(error) => log::warn!("[menu] {id} has unparseable keys {keystroke:?}: {error}"), - } - if let Ok(parsed) = - gpui::Keystroke::parse_with_os(keystroke, crate::desktop::keymap::host_os()) - { - accelerators.push((parsed, action)); - } - } - cx.bind_keys(new_bindings); - cx.key_bindings() - .borrow_mut() - .add_bindings(shortcut_bindings); - accelerators -} - -fn accelerator_action(id: &str) -> AcceleratorAction { - if id == crate::desktop::dev_menu::ACCELERATOR_ID { - return AcceleratorAction::Host("devMenu".to_string()); - } - if crate::desktop::dev_menu::is_command(id) { - return AcceleratorAction::Dev(id.to_string()); - } - if let Some(kind) = id.strip_prefix("role:") { - if matches!( - kind, - "undo" | "redo" | "cut" | "copy" | "paste" | "pasteWithoutFormatting" | "selectAll" - ) { - return AcceleratorAction::Edit(kind.to_string()); - } - if matches!( - kind, - "quit" - | "hide" - | "hideOthers" - | "showAll" - | "minimize" - | "zoom" - | "zoomIn" - | "zoomOut" - | "resetZoom" - | "toggleFullscreen" - | "close" - | "about" - ) { - return AcceleratorAction::Host(kind.to_string()); - } - } - AcceleratorAction::Press(id.to_string()) -} - -/// A menu accelerator, as a keymap binding in the app-wide context. -/// -/// The context matters. A shortcut belongs to a `ShortcutScope`, so its binding -/// matches at a greater depth than anything in the window root's `rn-app`; GPUI -/// dispatches the bindings for one keystroke in precedence order, so a scoped -/// shortcut consumes the key first and the menu item never runs. Without a -/// context the accelerator would tie with the window scope and win by being -/// added later, which is the behaviour this work set out to fix. -fn binding_for( - keystroke: &str, - action: &AcceleratorAction, - cx: &App, -) -> Result { - let context = std::rc::Rc::new( - gpui::KeyBindingContextPredicate::parse(crate::desktop::keymap::APP_CONTEXT) - .expect("the app context is a valid predicate"), - ); - let action: Box = match action { - AcceleratorAction::Press(id) | AcceleratorAction::Dev(id) => { - Box::new(MenuAccelerator { id: id.clone() }) - } - AcceleratorAction::Edit(kind) => Box::new(MenuEditAction { kind: kind.clone() }), - AcceleratorAction::Host(kind) => Box::new(MenuHostAction { kind: kind.clone() }), - }; - KeyBinding::load(keystroke, action, Some(context), false, None, cx) -} - -fn build_menus(model: &MenuModel, app_name: &str, dev_menu: bool) -> Vec { - model - .items - .iter() - .filter_map(|node| match node { - MenuNode::StandardMenu(role) => Some(standard_menu(*role, app_name, dev_menu)), - MenuNode::Submenu(submenu) => Some( - Menu::new(SharedString::from(submenu.label.clone())) - .items(build_items(&submenu.items)) - .disabled(!submenu.enabled), - ), - MenuNode::Item(item) => Some( - Menu::new(SharedString::from(item.label.clone())).items(vec![build_item(item)]), - ), - MenuNode::Separator => None, - }) - .collect() -} - -fn standard_menu(role: MenuRole, app_name: &str, dev_menu: bool) -> Menu { - let (name, items): (&str, Vec) = match role { - MenuRole::EditMenu => ( - "Edit", - vec![ - role_menu_item(MenuRole::Undo, None), - role_menu_item(MenuRole::Redo, None), - MenuItem::separator(), - role_menu_item(MenuRole::Cut, None), - role_menu_item(MenuRole::Copy, None), - role_menu_item(MenuRole::Paste, None), - role_menu_item(MenuRole::SelectAll, None), - ], - ), - MenuRole::WindowMenu => ( - "Window", - vec![ - role_menu_item(MenuRole::Minimize, None), - role_menu_item(MenuRole::Zoom, None), - MenuItem::separator(), - role_menu_item(MenuRole::ToggleFullscreen, None), - MenuItem::separator(), - role_menu_item(MenuRole::Close, None), - ], - ), - MenuRole::HelpMenu => ( - "Help", - if dev_menu { - vec![MenuItem::submenu( - Menu::new(SharedString::from("Developer")).items(dev_menu_items()), - )] - } else { - Vec::new() - }, - ), - MenuRole::AppMenu => ( - app_name, - vec![role_menu_item(MenuRole::About, Some(app_name))], - ), - _ => ("Menu", Vec::new()), - }; - Menu::new(SharedString::from(name)).items(items) -} - -fn build_items(items: &[MenuNode]) -> Vec { - items - .iter() - .filter_map(|node| match node { - MenuNode::Separator => Some(MenuItem::separator()), - MenuNode::StandardMenu(role) => Some(MenuItem::submenu(standard_menu( - *role, - role.default_label(), - false, - ))), - MenuNode::Submenu(submenu) => Some( - MenuItem::submenu( - Menu::new(SharedString::from(submenu.label.clone())) - .items(build_items(&submenu.items)), - ) - .disabled(!submenu.enabled), - ), - MenuNode::Item(item) => Some(build_item(item)), - }) - .collect() -} - -fn dev_menu_items() -> Vec { - use crate::desktop::dev_menu as dev; - [ - (dev::RELOAD, "Reload", false), - (dev::OPEN_DEVTOOLS, "Open DevTools", false), - (dev::ELEMENT_INSPECTOR, "Toggle Element Inspector", false), - (dev::PERF_MONITOR, "Toggle Perf Monitor", false), - (dev::FAST_REFRESH, "Fast Refresh", false), - ] - .into_iter() - .map(|(id, label, checked)| { - MenuItem::action( - SharedString::from(label), - MenuAccelerator { id: id.to_string() }, - ) - .checked(checked) - }) - .collect() -} - -fn build_item(item: &MenuItemDef) -> MenuItem { - if let Some(role) = item.role { - let mut built = role_menu_item(role, Some(&item.label)); - built = built.checked(item.checked); - return built.disabled(!item.enabled); - } - let mut built = MenuItem::action( - SharedString::from(item.label.clone()), - MenuAccelerator { - id: item.id.clone(), - }, - ); - built = built.checked(item.checked).disabled(!item.enabled); - built -} - -fn role_menu_item(role: MenuRole, label: Option<&str>) -> MenuItem { - let label = label.unwrap_or_else(|| role.default_label()); - match role { - MenuRole::Services => { - MenuItem::os_submenu(SharedString::from(label), SystemMenuType::Services) - } - MenuRole::Cut - | MenuRole::Copy - | MenuRole::Paste - | MenuRole::PasteWithoutFormatting - | MenuRole::SelectAll - | MenuRole::Undo - | MenuRole::Redo => MenuItem::action( - SharedString::from(label), - MenuEditAction { - kind: role_action_id(role).trim_start_matches("role:").to_string(), - }, - ), - MenuRole::About - | MenuRole::Hide - | MenuRole::HideOthers - | MenuRole::ShowAll - | MenuRole::Quit - | MenuRole::Minimize - | MenuRole::Zoom - | MenuRole::ZoomIn - | MenuRole::ZoomOut - | MenuRole::ResetZoom - | MenuRole::ToggleFullscreen - | MenuRole::Close => MenuItem::action( - SharedString::from(label), - MenuHostAction { - kind: role_action_id(role).trim_start_matches("role:").to_string(), - }, - ), - MenuRole::Help - | MenuRole::AppMenu - | MenuRole::EditMenu - | MenuRole::WindowMenu - | MenuRole::HelpMenu => MenuItem::action( - SharedString::from(label), - MenuHostAction { - kind: "noop".to_string(), - }, - ), - } -} - -fn emit_menu_press(cx: &mut App, id: &str) { - let Some(store) = store_from(cx) else { - return; - }; - let host = store.read(cx).host.clone(); - let window_id = active_window_key(cx).unwrap_or(1); - host.emit_device_event_json( - "gpuiDesktop:menuPress", - &json!({"id": id, "windowId": window_id}).to_string(), - ); -} - -fn active_window_key(cx: &App) -> Option { - let handle = cx.active_window()?; - let windows = cx.try_global::()?; - windows - .0 - .keys() - .into_iter() - .find(|key| windows.0.get(*key).map(|entry| entry.handle) == Some(handle)) -} - -/// Must not be called from inside a window update: a nested `update_window` -/// fails. -fn focused_text_input(cx: &mut App, window: gpui::AnyWindowHandle) -> Option> { - let debug = std::env::var_os("RN_GPUI_DEBUG_DESKTOP").is_some(); - let result = window.update(cx, |_root, window, cx| { - let focused = window.focused(cx)?; - let store = store_from(cx)?; - let node = { - let store = store.read(cx); - store - .nodes - .values() - .find(|node| node.read(cx).nearest_focus_handle(cx).as_ref() == Some(&focused)) - .cloned() - }; - if debug { - log::info!( - "[desktop][menu] focused node found={} (store nodes={})", - node.is_some(), - store.read(cx).nodes.len() - ); - } - node - }); - if let Err(error) = &result { - if debug { - log::info!("[desktop][menu] focus lookup failed: {error:?}"); - } - } - result.ok().flatten() -} - -/// Runs a standard menu role, as a menu item or accelerator would. -/// -/// A custom menu drawn in React is ordinary views, so nothing native performs its -/// role items. This is the one entry point that does, which is why it exists: -/// without it a custom "Copy" row would look right and do nothing. -/// -/// It goes through the same dispatch the native menu uses, so the action, the -/// window and the effect are identical however the user asked for it. -pub fn perform_role(cx: &mut App, role: &str) -> DesktopResult { - let handle = cx - .active_window() - .or_else(|| crate::desktop::windows::main_window_handle(cx)); - match role { - "undo" => perform_edit(cx, "undo", handle), - "redo" => perform_edit(cx, "redo", handle), - "cut" => perform_edit(cx, "cut", handle), - "copy" => perform_edit(cx, "copy", handle), - "paste" => perform_edit(cx, "paste", handle), - "pasteWithoutFormatting" => perform_edit(cx, "paste", handle), - "selectAll" => perform_edit(cx, "selectAll", handle), - "minimize" => { - if let Some(handle) = handle { - let _ = handle.update(cx, |_, window, _| window.minimize_window()); - } - } - "zoom" => { - if let Some(handle) = handle { - let _ = handle.update(cx, |_, window, _| window.zoom_window()); - } - } - "toggleFullscreen" => { - if let Some(handle) = handle { - let _ = handle.update(cx, |_, window, _| window.toggle_fullscreen()); - } - } - "zoomIn" | "zoomOut" | "resetZoom" => step_zoom(cx, role, handle), - "close" => { - if let Some(handle) = handle { - let _ = handle.update(cx, |_, window, _| window.remove_window()); - } - } - "quit" | "hide" | "hideOthers" | "showAll" | "about" => { - perform_host_action(cx, role, handle) - } - // A menu with no action of its own: nothing to do, and saying so is - // better than silently pretending. - other => { - return Err(DesktopError::failed(format!( - "{other} is not a role this platform can perform" - ))) - } - } - Ok(json!({"role": role})) -} - -fn perform_edit(cx: &mut App, kind: &str, handle: Option) { - let kind = kind.to_string(); - // Deferred: the action is dispatched from inside a window update, and GPUI - // forbids re-entering the same window. - cx.defer(move |cx| { - let debug = std::env::var_os("RN_GPUI_DEBUG_DESKTOP").is_some(); - let Some(window) = handle.or_else(|| cx.active_window()) else { - return; - }; - let focused = - focused_text_input(cx, window).filter(|node| node.read(cx).component == "TextInput"); - let Some(node) = focused else { - // Selected `Text` takes Copy and Select All when no input is focused. - if let Some(selected) = crate::builtins::text_select::active_node(cx) { - match kind.as_str() { - "copy" => { - crate::builtins::text_select::copy_active(cx); - } - "selectAll" => selected.update(cx, |node, cx| { - crate::builtins::text_select::select_all(node, cx) - }), - _ => {} - } - return; - } - if debug { - log::info!("[desktop][menu] edit {kind}: no focused text input"); - } - return; - }; - let _ = window.update(cx, move |_root, window, cx| { - node.update(cx, |node, cx| match kind.as_str() { - "copy" => { - crate::builtins::textinput::input::copy_selection(node, cx); - } - "cut" => { - crate::builtins::textinput::input::cut_selection(node, window, cx); - } - "paste" | "pasteWithoutFormatting" => { - crate::builtins::textinput::input::paste_clipboard(node, window, cx); - } - "selectAll" => { - crate::builtins::textinput::input::select_all(node, window, cx); - } - // TODO: undo/redo need an edit history in the GPUI text input. The - // item is present so an app can handle the press itself. - _ => {} - }); - if debug { - let node = node.read(cx); - log::info!( - "[desktop][menu] edit {kind} on {} selection={:?}", - node.component, - node.input().selection - ); - } - }); - }); -} - -/// Deferred: a menu action runs inside the platform's menu callback, and a -/// reload or a perf-monitor window must not start from there. -fn perform_dev_action(cx: &mut App, id: String) { - cx.defer(move |cx| crate::desktop::dev_menu::perform(cx, &id)); -} - -fn step_zoom(cx: &mut App, role: &str, handle: Option) { - let key = handle - .and_then(|handle| crate::desktop::windows::window_key_for_handle(cx, handle)) - .unwrap_or(crate::desktop::windows::MAIN_WINDOW_KEY); - let _ = crate::desktop::windows::step_zoom(cx, key, role); -} - -fn perform_host_action(cx: &mut App, kind: &str, handle: Option) { - match kind { - "quit" => cx.quit(), - "hide" => cx.hide(), - "hideOthers" => cx.hide_other_apps(), - "showAll" => cx.unhide_other_apps(), - "about" => show_about_panel(cx), - // Deferred: the accelerator runs inside the keystroke's window update. - "devMenu" => cx.defer(|cx| crate::desktop::dev_menu::show(cx)), - "zoomIn" | "zoomOut" | "resetZoom" => { - let kind = kind.to_string(); - cx.defer(move |cx| { - let handle = handle.or_else(|| cx.active_window()); - step_zoom(cx, &kind, handle); - }); - } - "minimize" | "zoom" | "toggleFullscreen" | "close" => { - let kind = kind.to_string(); - cx.defer(move |cx| { - let Some(window) = handle.or_else(|| cx.active_window()) else { - return; - }; - let _ = window.update(cx, move |_root, window, _cx| match kind.as_str() { - "minimize" => window.minimize_window(), - "zoom" => window.zoom_window(), - "toggleFullscreen" => window.toggle_fullscreen(), - "close" => window.remove_window(), - _ => {} - }); - }); - } - _ => {} - } -} - -#[cfg(target_os = "macos")] -fn show_about_panel(_cx: &mut App) { - use objc::{class, msg_send, sel, sel_impl}; - // SAFETY: `NSApplication` is messaged from the main thread. - unsafe { - let app: cocoa::base::id = msg_send![class!(NSApplication), sharedApplication]; - let _: () = - msg_send![app, orderFrontStandardAboutPanel: std::ptr::null::()]; - } -} - -#[cfg(not(target_os = "macos"))] -fn show_about_panel(_cx: &mut App) {} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn default_menu_has_the_standard_groups() { - let model = default_menu("Tester"); - assert!(model.has_help_menu()); - assert!(model.find("role:quit").is_some()); - let bindings = collect_bindings(false, &model); - assert!(bindings - .iter() - .any(|(id, key)| id == "role:copy" && key == "secondary-c")); - assert!(bindings - .iter() - .any(|(id, key)| id == "role:quit" && key == "secondary-q")); - } - - #[test] - fn standard_edit_menu_installs_accelerators() { - let model = MenuModel { - items: vec![MenuNode::StandardMenu(MenuRole::EditMenu)], - }; - let bindings = collect_bindings(false, &model); - assert_eq!(bindings.len(), 6); - assert!(bindings.iter().any(|(_, key)| key == "secondary-v")); - } - - #[test] - fn unsupported_roles_are_dropped_from_the_built_menu() { - let model = default_menu("Tester"); - let menus = build_menus(&model, "Tester", false); - assert!(!menus.is_empty()); - } - - #[test] - fn developer_items_run_on_the_host() { - use crate::desktop::dev_menu as dev; - for id in [ - dev::RELOAD, - dev::OPEN_DEVTOOLS, - dev::ELEMENT_INSPECTOR, - dev::PERF_MONITOR, - dev::FAST_REFRESH, - ] { - assert_eq!(accelerator_action(id), AcceleratorAction::Dev(id.into())); - } - assert_eq!( - accelerator_action(dev::ACCELERATOR_ID), - AcceleratorAction::Host("devMenu".into()) - ); - assert_eq!( - accelerator_action("dev:custom"), - AcceleratorAction::Press("dev:custom".into()) - ); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/app_state.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/app_state.rs deleted file mode 100644 index 6503160965..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/app_state.rs +++ /dev/null @@ -1,100 +0,0 @@ -//! `AppState`: whether the app is in front, behind other apps, or out of sight. -//! -//! Derived from the window state mirror. A change is reported a short moment -//! after the window that caused it, so moving focus from one app window to -//! another, which blurs the first before it focuses the second, reports -//! nothing. - -use gpui::App; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Mutex; -use std::time::Duration; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct WindowFacts { - pub focused: bool, - pub minimized: bool, - pub visible: bool, -} - -pub fn state_from(windows: &[WindowFacts]) -> &'static str { - if windows.iter().any(|window| window.focused) { - "active" - } else if windows - .iter() - .any(|window| window.visible && !window.minimized) - { - "inactive" - } else { - "background" - } -} - -static PENDING: AtomicBool = AtomicBool::new(false); -static LAST: Mutex<&'static str> = Mutex::new("active"); - -/// How long window changes are gathered before the state is re-evaluated. The -/// system delivers the blur of one window and the focus of the next separately, -/// and under load they can be several frames apart. -const SETTLE: Duration = Duration::from_millis(80); - -/// Re-evaluates the state once the windows have settled, however many changed. -pub fn schedule(cx: &mut App) { - if PENDING.swap(true, Ordering::AcqRel) { - return; - } - let timer = cx.background_executor().timer(SETTLE); - cx.spawn(async move |cx| { - timer.await; - PENDING.store(false, Ordering::Release); - cx.update(apply); - }) - .detach(); -} - -fn apply(cx: &mut App) { - let state = state_from(&super::window_mirror::facts()); - { - let mut last = LAST.lock().expect("app state poisoned"); - if *last == state { - return; - } - *last = state; - } - if let Some(store) = crate::store::store_from(cx) { - store.read(cx).host.set_app_state(state); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn window(focused: bool, minimized: bool, visible: bool) -> WindowFacts { - WindowFacts { - focused, - minimized, - visible, - } - } - - #[test] - fn a_focused_window_makes_the_app_active() { - assert_eq!( - state_from(&[window(false, false, true), window(true, false, true)]), - "active" - ); - } - - #[test] - fn visible_windows_without_focus_make_it_inactive() { - assert_eq!(state_from(&[window(false, false, true)]), "inactive"); - } - - #[test] - fn minimised_or_hidden_windows_make_it_background() { - assert_eq!(state_from(&[window(false, true, true)]), "background"); - assert_eq!(state_from(&[window(false, false, false)]), "background"); - assert_eq!(state_from(&[]), "background"); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/background.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/background.rs deleted file mode 100644 index 9ef3df6c84..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/background.rs +++ /dev/null @@ -1,150 +0,0 @@ -//! A run that must not disturb the person using the machine. -//! -//! With the test driver on, or `RN_GPUI_BACKGROUND=1`, the app never activates -//! itself, never becomes the frontmost application, and puts its windows behind -//! everything else instead of in front. Focus is logical: `setWindowActive` -//! gives a window focus and key events without the operating system's help. -//! `RN_GPUI_BACKGROUND=0` turns it off for a test run someone is watching. - -use gpui::WindowOptions; -use std::sync::OnceLock; - -/// Whether this run stays in the background. -pub fn enabled() -> bool { - static ENABLED: OnceLock = OnceLock::new(); - *ENABLED.get_or_init(|| { - resolve( - std::env::var("RN_GPUI_BACKGROUND").ok().as_deref(), - cfg!(feature = "test-driver") - && std::env::var_os("RN_GPUI_TEST_DRIVER").is_some_and(|value| value != "0"), - ) - }) -} - -fn resolve(background: Option<&str>, driver: bool) -> bool { - match background { - Some(value) => !matches!(value, "" | "0" | "false" | "no"), - None => driver, - } -} - -#[cfg(test)] -mod tests { - use super::resolve; - - #[test] - fn the_test_driver_turns_it_on_and_the_variable_decides_either_way() { - assert!(resolve(None, true)); - assert!(!resolve(None, false)); - assert!(resolve(Some("1"), false)); - assert!(!resolve(Some("0"), true)); - } -} - -/// Changes a window's options so that opening it takes no focus and shows -/// nothing in front. Returns whether the window is to be shown behind the -/// others once it is open (see [`show_behind`]). -pub fn prepare(options: &mut WindowOptions) -> bool { - if !enabled() { - return false; - } - options.focus = false; - if cfg!(target_os = "macos") { - let visible = options.show; - options.show = false; - return visible; - } - false -} - -/// Shows a window that [`prepare`] opened hidden, behind the others. -pub fn show_behind(window: &mut gpui::Window) { - if let Err(error) = super::platform_window::show_behind(window) { - log::debug!("[background] could not show a window behind the others: {error}"); - } -} - -/// The backing scale factor of the display with this id, where the platform can -/// say: how many device pixels a point is on that display. -#[cfg(target_os = "macos")] -pub(crate) fn display_scale(id: u64) -> Option { - use cocoa::base::{id as object, nil}; - use cocoa::foundation::{NSArray, NSString}; - use objc::{class, msg_send, sel, sel_impl}; - // SAFETY: AppKit is read on the main thread, where displays are chosen; the - // objects are autoreleased and only read here. - unsafe { - let displays: object = msg_send![class!(NSScreen), screens]; - let key = NSString::alloc(nil).init_str("NSScreenNumber"); - for index in 0..NSArray::count(displays) { - let screen: object = NSArray::objectAtIndex(displays, index); - let description: object = msg_send![screen, deviceDescription]; - let number: object = msg_send![description, objectForKey: key]; - if number == nil { - continue; - } - let screen_id: u32 = msg_send![number, unsignedIntValue]; - if u64::from(screen_id) == id { - let scale: f64 = msg_send![screen, backingScaleFactor]; - return Some(scale as f32); - } - } - } - None -} - -#[cfg(not(target_os = "macos"))] -pub(crate) fn display_scale(_id: u64) -> Option { - None -} - -/// The display a test window opens on: `RN_GPUI_TEST_DISPLAY` names an index -/// into the platform's list of displays, `main`, `secondary`, or `retina`, the -/// display with the highest scale factor when that is at least 2. A background -/// run opens on the secondary display when there is one. A display that does -/// not exist falls back to the main one, with a log line. -pub fn test_display(cx: &gpui::App) -> Option> { - let requested = std::env::var("RN_GPUI_TEST_DISPLAY").ok(); - if requested.is_none() && !enabled() { - return None; - } - // The test platform has its one display, and AppKit is not asked. - #[cfg(feature = "test-driver")] - if crate::headless::enabled() { - return None; - } - let displays = cx.displays(); - let primary = cx.primary_display()?; - let wanted = requested.as_deref().unwrap_or("secondary"); - let chosen = match wanted { - "main" | "primary" => Some(primary.clone()), - "retina" => displays - .iter() - .filter_map(|display| { - let scale = display_scale(display.id().into())?; - (scale >= 2.0).then_some((scale, display.clone())) - }) - .max_by(|a, b| a.0.total_cmp(&b.0)) - .map(|(_, display)| display), - "secondary" => displays - .iter() - .find(|display| display.id() != primary.id()) - .cloned(), - index => index - .parse::() - .ok() - .and_then(|index| displays.get(index).cloned()), - }; - match chosen { - Some(display) => Some(display), - None => { - if requested.is_some() { - log::info!( - "[background] RN_GPUI_TEST_DISPLAY={wanted} names no display of {}; using the main display", - displays.len() - ); - } - Some(primary) - } - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/button_layout.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/button_layout.rs deleted file mode 100644 index 2882cb776c..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/button_layout.rs +++ /dev/null @@ -1,118 +0,0 @@ -//! Where the window's caption buttons sit, as the desktop has it configured. -//! -//! The answer is a GTK `button-layout` string such as -//! `appmenu:minimize,maximize,close`: the names left of the colon go on the left -//! of the title bar, the ones after it on the right. - -/// GTK's own default, used where the desktop states nothing. -pub const DEFAULT_LAYOUT: &str = ":minimize,maximize,close"; -const DEFAULT_LAYOUT_LEFT: &str = "close,minimize,maximize:"; - -static FALLBACK_LEFT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - -/// Puts the buttons on the left where the desktop states no layout. Must run -/// before the first [`button_layout`] call. -pub fn set_fallback_left(left: bool) { - FALLBACK_LEFT.store(left, std::sync::atomic::Ordering::Relaxed); -} - -#[cfg(target_os = "linux")] -pub fn button_layout() -> String { - static LAYOUT: std::sync::OnceLock = std::sync::OnceLock::new(); - LAYOUT - .get_or_init(|| { - gnome_layout().or_else(kde_layout).unwrap_or_else(|| { - if FALLBACK_LEFT.load(std::sync::atomic::Ordering::Relaxed) { - DEFAULT_LAYOUT_LEFT.to_string() - } else { - DEFAULT_LAYOUT.to_string() - } - }) - }) - .clone() -} - -#[cfg(not(target_os = "linux"))] -pub fn button_layout() -> String { - DEFAULT_LAYOUT.to_string() -} - -/// The `org.gnome.desktop.wm.preferences` key, as GTK reads it: through -/// `gsettings`, so the session's own overrides apply. The settings portal gives -/// the schema default instead, which is not what GTK apps on the same desktop -/// show. -#[cfg(target_os = "linux")] -fn gnome_layout() -> Option { - let output = std::process::Command::new("gsettings") - .args(["get", "org.gnome.desktop.wm.preferences", "button-layout"]) - .stderr(std::process::Stdio::null()) - .output() - .ok() - .filter(|output| output.status.success())?; - let text = String::from_utf8(output.stdout).ok()?; - let layout = text.trim().trim_matches('\''); - (!layout.is_empty()).then(|| layout.to_string()) -} - -/// KDE keeps the buttons in `kwinrc` as letters: `M` menu, `I` minimize, -/// `A` maximize, `X` close. -#[cfg(target_os = "linux")] -fn kde_layout() -> Option { - let home = std::env::var_os("XDG_CONFIG_HOME") - .map(std::path::PathBuf::from) - .or_else(|| { - std::env::var_os("HOME").map(|home| std::path::Path::new(&home).join(".config")) - })?; - let text = std::fs::read_to_string(home.join("kwinrc")).ok()?; - kde_layout_from(&text) -} - -fn kde_layout_from(text: &str) -> Option { - let mut in_section = false; - let (mut left, mut right) = (None, None); - for line in text.lines() { - let line = line.trim(); - if let Some(section) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { - in_section = section == "org.kde.kdecoration2"; - } else if in_section { - if let Some(value) = line.strip_prefix("ButtonsOnLeft=") { - left = Some(value); - } else if let Some(value) = line.strip_prefix("ButtonsOnRight=") { - right = Some(value); - } - } - } - if left.is_none() && right.is_none() { - return None; - } - let names = |letters: &str| { - letters - .chars() - .filter_map(|letter| match letter { - 'M' => Some("menu"), - 'I' => Some("minimize"), - 'A' => Some("maximize"), - 'X' => Some("close"), - _ => None, - }) - .collect::>() - .join(",") - }; - Some(format!( - "{}:{}", - names(left.unwrap_or("M")), - names(right.unwrap_or("IAX")) - )) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn kwin_letters_become_a_gtk_layout() { - let text = "[org.kde.kdecoration2]\nButtonsOnLeft=XIA\nButtonsOnRight=\n"; - assert_eq!(kde_layout_from(text).unwrap(), "close,minimize,maximize:"); - assert_eq!(kde_layout_from("[General]\nx=1\n"), None); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/capabilities.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/capabilities.rs deleted file mode 100644 index 4d16266c0e..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/capabilities.rs +++ /dev/null @@ -1,261 +0,0 @@ -#[cfg(target_os = "linux")] -use std::sync::atomic::{AtomicU8, Ordering}; - -pub const fn native_app_menu() -> bool { - cfg!(any(target_os = "macos", target_os = "windows")) -} - -pub const fn native_context_menu() -> bool { - cfg!(any(target_os = "macos", target_os = "windows")) -} - -pub const fn tray() -> bool { - cfg!(any( - target_os = "macos", - target_os = "windows", - target_os = "linux" - )) -} - -/// Whether the tray popover can be placed at the icon, rather than wherever the -/// compositor decides. -/// -/// macOS places it natively. Linux is decided at run time: X11 can position a -/// window (`_NET_WM_WINDOW_TYPE_UTILITY` + `USPosition`), Wayland cannot. The -/// Wayland layer-shell path (KDE, wlroots, COSMIC) is not implemented yet; when -/// it lands this becomes true there too, and stays false on GNOME, which has no -/// layer-shell. Windows has no anchored popover. -pub fn tray_popover_anchored() -> bool { - #[cfg(target_os = "macos")] - { - true - } - #[cfg(target_os = "linux")] - { - !is_wayland() - } - #[cfg(not(any(target_os = "macos", target_os = "linux")))] - { - false - } -} - -/// Wayland has no absolute window positioning and no raise-above. -pub fn is_wayland() -> bool { - #[cfg(target_os = "linux")] - { - std::env::var_os("WAYLAND_DISPLAY").is_some() - } - #[cfg(not(target_os = "linux"))] - { - false - } -} - -pub fn window_position() -> bool { - !is_wayland() -} - -pub fn always_on_top() -> bool { - !is_wayland() -} - -/// Whether a window can be shown on every Space or workspace, which only macOS does yet. -pub fn visible_on_all_workspaces() -> bool { - cfg!(target_os = "macos") -} - -/// Whether a window can have its title bar removed while keeping the traffic -/// lights or the app's own caption buttons. -/// -/// macOS and Windows always can. Linux cannot on its own: the title bar belongs -/// to the window manager, and the only way to remove it is client-side -/// decorations, so the answer follows [`client_decorations`] there. Anywhere -/// else the shell does not run at all, so the answer is false rather than a -/// promise nothing can keep. -pub fn transparent_titlebar() -> bool { - #[cfg(target_os = "linux")] - { - client_decorations() - } - #[cfg(not(target_os = "linux"))] - { - cfg!(any(target_os = "macos", target_os = "windows")) - } -} - -/// Whether a frameless window can be frameless *and* still resized. -/// -/// macOS and Windows keep a native resize border around a title-bar-less window, -/// so a custom title bar needs nothing more from them. Linux has to ask the -/// compositor for client-side decorations, and only some window managers and -/// compositors grant that: X11 needs a compositor that advertises -/// `_GTK_FRAME_EXTENTS`, Wayland needs `zxdg_decoration_manager_v1`. Where the -/// request is refused the window keeps its server-side frame — and its title bar -/// — so an app must draw caption buttons only where this is true, or it draws a -/// second set beside the window manager's own. -/// -/// On Linux the answer comes from the window itself rather than a guess: the -/// bootstrap records what `window.window_decorations()` reported once the main -/// window exists, which is the only authority on whether the request was -/// granted. Before that the answer is "unknown", and the safe answer to an -/// unknown is false. -pub fn client_decorations() -> bool { - #[cfg(target_os = "linux")] - { - match OBSERVED_CLIENT_DECORATIONS.load(Ordering::Relaxed) { - DECORATIONS_CLIENT => true, - DECORATIONS_SERVER => false, - // A Wayland window starts on client-side decorations and only - // switches when the compositor insists, so before the first window - // exists that is the better guess. - _ => is_wayland(), - } - } - #[cfg(not(target_os = "linux"))] - { - // The same platforms `transparent_titlebar` is true on: a window only - // exists there, and both keep a native resize border when the caption is - // removed. - cfg!(any(target_os = "macos", target_os = "windows")) - } -} - -#[cfg(target_os = "linux")] -const DECORATIONS_UNKNOWN: u8 = 0; -#[cfg(target_os = "linux")] -const DECORATIONS_SERVER: u8 = 1; -#[cfg(target_os = "linux")] -const DECORATIONS_CLIENT: u8 = 2; - -/// What the compositor gave the windows opened so far. -/// -/// An atomic rather than a `OnceLock` because a second window can be refused -/// after the first was granted, and the later answer is the one that matters: -/// the caption buttons are drawn per window, but the capability is read once. -#[cfg(target_os = "linux")] -static OBSERVED_CLIENT_DECORATIONS: AtomicU8 = AtomicU8::new(DECORATIONS_UNKNOWN); - -/// Records whether a window ended up with client-side decorations. -#[cfg(target_os = "linux")] -pub fn note_window_decorations(decorations: gpui::Decorations) { - let value = match decorations { - gpui::Decorations::Client { .. } => DECORATIONS_CLIENT, - gpui::Decorations::Server => DECORATIONS_SERVER, - }; - OBSERVED_CLIENT_DECORATIONS.store(value, Ordering::Relaxed); - *DECORATIONS_NOTED - .0 - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = true; - DECORATIONS_NOTED.1.notify_all(); -} - -/// Set once any window has reported its decorations, with the condition the -/// JS thread waits on until then. -#[cfg(target_os = "linux")] -static DECORATIONS_NOTED: (std::sync::Mutex, std::sync::Condvar) = - (std::sync::Mutex::new(false), std::sync::Condvar::new()); - -/// Holds the caller until the first window has reported its decorations. -/// -/// The app starts rendering while its window is still being created, and a -/// `TitleBar` that read the answer before the window existed would take the -/// guess and draw caption buttons next to the compositor's own. The wait is on -/// the JS thread only, which has nothing to render into until the window exists -/// anyway; the main thread, which is making the window, is never held. The -/// timeout keeps a window that never opens from hanging the app. -#[cfg(target_os = "linux")] -pub fn wait_for_window_decorations() { - let (noted, signal) = &DECORATIONS_NOTED; - let guard = noted - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let _ = signal.wait_timeout_while(guard, std::time::Duration::from_millis(1500), |noted| { - !*noted - }); -} - -#[cfg(not(target_os = "linux"))] -pub fn wait_for_window_decorations() {} - -/// What the newest window's decorations are, once known. -#[cfg(target_os = "linux")] -pub fn observed_client_decorations() -> Option { - match OBSERVED_CLIENT_DECORATIONS.load(Ordering::Relaxed) { - DECORATIONS_CLIENT => Some(true), - DECORATIONS_SERVER => Some(false), - _ => None, - } -} - -/// Nothing to record: these platforms always have a native border to resize by. -#[cfg(not(target_os = "linux"))] -pub fn note_window_decorations(_decorations: gpui::Decorations) {} - -/// Whether the menu bar is drawn inside the window, so hiding it does something. -/// -/// macOS is false: its menu bar is the system's, at the top of the screen, and -/// nothing an app does can remove it. Windows and Linux draw theirs inside the -/// window, which is why `Menu.setMenuBarVisible` only means something there. -pub const fn menu_bar_in_window() -> bool { - cfg!(any(target_os = "windows", target_os = "linux")) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn macos_supports_native_menus_and_anchored_popovers() { - if cfg!(target_os = "macos") { - assert!(native_app_menu()); - assert!(native_context_menu()); - assert!(tray()); - assert!(tray_popover_anchored()); - assert!(transparent_titlebar()); - assert!(!menu_bar_in_window()); - } - } - - #[test] - fn the_menu_bar_is_only_in_window_where_it_can_be_hidden() { - if cfg!(any(target_os = "windows", target_os = "linux")) { - assert!(menu_bar_in_window()); - } - } - - #[test] - fn a_custom_title_bar_is_resizable_off_linux_without_asking_the_compositor() { - // Windows and macOS keep their native resize border when the caption is - // removed, so the capability is unconditional there and `TitleBar` can - // draw caption buttons on any window it is put in. - if cfg!(any(target_os = "macos", target_os = "windows")) { - assert!(client_decorations()); - } - } - - #[cfg(target_os = "linux")] - #[test] - fn linux_reports_what_the_compositor_actually_granted() { - // The bootstrap records the answer per window; until it does, an X11 - // session has to assume the request will be refused, because guessing - // "granted" would draw caption buttons next to the window manager's own. - note_window_decorations(gpui::Decorations::Server); - assert!(!client_decorations()); - - note_window_decorations(gpui::Decorations::Client { - tiling: gpui::Tiling::default(), - }); - assert!(client_decorations()); - - // A later window that was refused wins: the capability must describe - // what the newest window actually looks like. - note_window_decorations(gpui::Decorations::Server); - assert!(!client_decorations()); - // A transparent title bar is the same question on Linux: without - // client-side decorations the window manager keeps its own bar, and the - // app cannot remove it. - assert!(!transparent_titlebar()); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/client_frame.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/client_frame.rs deleted file mode 100644 index 0c9711c4a7..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/client_frame.rs +++ /dev/null @@ -1,160 +0,0 @@ -//! The invisible border that makes a frameless window resizable. -//! -//! A window with client-side decorations has no frame for the user to grab, so -//! the app draws one: eight invisible strips along and around the edges, each -//! starting a native resize when pressed. Only Linux needs this — macOS and -//! Windows keep a native resize border around a title-bar-less window — so the -//! element is only built there. The geometry and the cursor are -//! platform-independent and unit-tested everywhere, which is why the module is -//! not itself behind a `cfg`: the tests are what keep the numbers right, and they -//! have to run on the machine the change is made on. -#![allow(dead_code)] - -use gpui::{px, Bounds, CursorStyle, Pixels, Point, ResizeEdge, Size}; - -/// How thick the grab area is, in points. -/// -/// Eight is what GTK and winit use for a client-decorated edge: thinner and the -/// edge is hard to hit, thicker and it starts eating presses meant for content. -pub const BORDER: f32 = 8.0; - -/// Every edge, in the order the border draws them. -/// -/// The four sides come first and the corners last: a later child paints in -/// front, so where a corner overlaps the two sides it belongs to, the corner is -/// what the pointer hits. -pub const EDGES: [ResizeEdge; 8] = [ - ResizeEdge::Top, - ResizeEdge::Bottom, - ResizeEdge::Left, - ResizeEdge::Right, - ResizeEdge::TopLeft, - ResizeEdge::TopRight, - ResizeEdge::BottomLeft, - ResizeEdge::BottomRight, -]; - -/// Where one edge's grab area sits inside a window of this size. -/// -/// The thickness shrinks with a window smaller than two borders, so a tiny -/// window still lays out: two overlapping 8px strips that each claim half would -/// leave the middle unfindable. -pub fn border_bounds(edge: ResizeEdge, width: f32, height: f32) -> Bounds { - let width = width.max(0.0); - let height = height.max(0.0); - let thickness = BORDER.min(width / 2.0).min(height / 2.0); - let (x, y, w, h) = match edge { - ResizeEdge::Top => (0.0, 0.0, width, thickness), - ResizeEdge::Bottom => (0.0, height - thickness, width, thickness), - ResizeEdge::Left => (0.0, 0.0, thickness, height), - ResizeEdge::Right => (width - thickness, 0.0, thickness, height), - ResizeEdge::TopLeft => (0.0, 0.0, thickness, thickness), - ResizeEdge::TopRight => (width - thickness, 0.0, thickness, thickness), - ResizeEdge::BottomLeft => (0.0, height - thickness, thickness, thickness), - ResizeEdge::BottomRight => (width - thickness, height - thickness, thickness, thickness), - }; - Bounds::new(Point::new(px(x), px(y)), Size::new(px(w), px(h))) -} - -/// The cursor a resize edge shows, in the CSS spelling each edge means. -pub fn edge_cursor(edge: ResizeEdge) -> CursorStyle { - match edge { - ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown, - ResizeEdge::Left | ResizeEdge::Right => CursorStyle::ResizeLeftRight, - // `nwse-resize` runs from the top-left corner to the bottom-right one. - ResizeEdge::TopLeft | ResizeEdge::BottomRight => CursorStyle::ResizeUpRightDownLeft, - ResizeEdge::TopRight | ResizeEdge::BottomLeft => CursorStyle::ResizeUpLeftDownRight, - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn rect(edge: ResizeEdge, width: f32, height: f32) -> (f32, f32, f32, f32) { - let bounds = border_bounds(edge, width, height); - ( - f32::from(bounds.origin.x), - f32::from(bounds.origin.y), - f32::from(bounds.size.width), - f32::from(bounds.size.height), - ) - } - - #[test] - fn each_side_spans_the_window_and_sits_against_its_own_edge() { - assert_eq!(rect(ResizeEdge::Top, 400.0, 300.0), (0.0, 0.0, 400.0, 8.0)); - assert_eq!( - rect(ResizeEdge::Bottom, 400.0, 300.0), - (0.0, 292.0, 400.0, 8.0) - ); - assert_eq!(rect(ResizeEdge::Left, 400.0, 300.0), (0.0, 0.0, 8.0, 300.0)); - assert_eq!( - rect(ResizeEdge::Right, 400.0, 300.0), - (392.0, 0.0, 8.0, 300.0) - ); - } - - #[test] - fn a_corner_is_a_square_in_its_own_corner() { - assert_eq!( - rect(ResizeEdge::TopLeft, 400.0, 300.0), - (0.0, 0.0, 8.0, 8.0) - ); - assert_eq!( - rect(ResizeEdge::TopRight, 400.0, 300.0), - (392.0, 0.0, 8.0, 8.0) - ); - assert_eq!( - rect(ResizeEdge::BottomLeft, 400.0, 300.0), - (0.0, 292.0, 8.0, 8.0) - ); - assert_eq!( - rect(ResizeEdge::BottomRight, 400.0, 300.0), - (392.0, 292.0, 8.0, 8.0) - ); - } - - #[test] - fn the_border_shrinks_to_fit_a_tiny_window() { - // A window narrower than two borders would otherwise place the right - // strip at a negative x, outside the window it is meant to resize. - let (x, _, w, _) = rect(ResizeEdge::Right, 10.0, 10.0); - assert_eq!((x, w), (5.0, 5.0)); - let (x, y, w, h) = rect(ResizeEdge::BottomRight, 10.0, 6.0); - assert_eq!((x, y, w, h), (7.0, 3.0, 3.0, 3.0)); - } - - #[test] - fn an_empty_window_has_no_border() { - assert_eq!(rect(ResizeEdge::Right, 0.0, 0.0), (0.0, 0.0, 0.0, 0.0)); - assert_eq!(rect(ResizeEdge::Top, -5.0, 20.0), (0.0, 0.0, 0.0, 0.0)); - } - - #[test] - fn every_edge_has_the_cursor_that_matches_its_direction() { - assert_eq!(edge_cursor(ResizeEdge::Top), CursorStyle::ResizeUpDown); - assert_eq!(edge_cursor(ResizeEdge::Bottom), CursorStyle::ResizeUpDown); - assert_eq!(edge_cursor(ResizeEdge::Left), CursorStyle::ResizeLeftRight); - assert_eq!(edge_cursor(ResizeEdge::Right), CursorStyle::ResizeLeftRight); - // The two diagonals must not be swapped: a browser and a window manager - // disagree about nothing else here, and a wrong cursor is the visible - // symptom of a wrong resize direction. - assert_eq!( - edge_cursor(ResizeEdge::TopLeft), - CursorStyle::ResizeUpRightDownLeft - ); - assert_eq!( - edge_cursor(ResizeEdge::BottomRight), - CursorStyle::ResizeUpRightDownLeft - ); - assert_eq!( - edge_cursor(ResizeEdge::TopRight), - CursorStyle::ResizeUpLeftDownRight - ); - assert_eq!( - edge_cursor(ResizeEdge::BottomLeft), - CursorStyle::ResizeUpLeftDownRight - ); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/context_menu.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/context_menu.rs deleted file mode 100644 index ddca01cdd0..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/context_menu.rs +++ /dev/null @@ -1,515 +0,0 @@ -use crate::desktop::errors::DesktopError; -use crate::desktop::menu_model::{self, MenuModel, MenuNode}; -use crate::desktop::windows::DesktopWindowsGlobal; -use gpui::{AnyWindowHandle, App}; -use serde_json::{json, Value}; -use std::cell::RefCell; -use std::rc::Rc; - -pub struct ContextMenuRequest { - pub window: AnyWindowHandle, - pub x: f32, - pub y: f32, - pub model: MenuModel, - pub native_view: isize, -} - -/// Settles one context menu: the module's promise, or a caller's callback. -#[derive(Clone)] -pub enum Responder { - Desktop { reply: Rc>> }, - Callback(Rc)>>>>), -} - -/// Answers the promise a `contextMenuShow` call is waiting on. -pub type Reply = futures::channel::oneshot::Sender>; - -impl Responder { - pub fn desktop(reply: Reply) -> Self { - Self::Desktop { - reply: Rc::new(RefCell::new(Some(reply))), - } - } - - pub fn callback(callback: Box)>) -> Self { - Self::Callback(Rc::new(RefCell::new(Some(callback)))) - } - - pub fn resolve(&self, selection: Option<&str>) { - match self { - Self::Desktop { reply } => { - if let Some(reply) = reply.borrow_mut().take() { - let _ = reply.send(Ok(json!({"id": selection}))); - } - } - Self::Callback(callback) => { - if let Some(mut callback) = callback.borrow_mut().take() { - callback(selection.map(str::to_string)); - } - } - } - } - - pub fn reject(&self, error: DesktopError) { - match self { - Self::Desktop { reply } => { - if let Some(reply) = reply.borrow_mut().take() { - let _ = reply.send(Err(error)); - } - } - Self::Callback(callback) => { - if let Some(mut callback) = callback.borrow_mut().take() { - callback(None); - } - } - } - } -} - -pub fn target_window(cx: &mut App) -> Result<(AnyWindowHandle, isize), DesktopError> { - let window = cx - .active_window() - .or_else(|| { - cx.global::() - .0 - .get(crate::desktop::windows::MAIN_WINDOW_KEY) - .map(|entry| entry.handle) - }) - .ok_or_else(|| DesktopError::failed("no window for the context menu"))?; - let native_view = native_view_of(cx, window); - Ok((window, native_view)) -} - -pub trait ContextMenuPresenter: 'static { - fn show(&self, cx: &mut App, request: ContextMenuRequest, responder: Responder); - - fn name(&self) -> &'static str; -} - -pub struct ContextMenuPresenterGlobal(pub Rc); -impl gpui::Global for ContextMenuPresenterGlobal {} - -pub fn install(cx: &mut App) { - let fake = cfg!(feature = "test-driver") - && std::env::var("RN_GPUI_TEST_FAKE_NATIVE_UI").as_deref() == Ok("1"); - if fake { - let fake = Rc::new(FakeContextMenu::new()); - cx.set_global(FakeContextMenuGlobal(fake.clone())); - cx.set_global(ContextMenuPresenterGlobal(fake)); - } else if crate::desktop::gpui_menu::should_use_gpui() { - cx.set_global(ContextMenuPresenterGlobal(Rc::new(GpuiContextMenu))); - } else { - cx.set_global(ContextMenuPresenterGlobal(Rc::new(NativeContextMenu))); - } -} - -/// Answers through `reply` when the menu closes. -pub fn show( - cx: &mut App, - items: Value, - x: Option, - y: Option, - window_id: Option, - responder: Responder, -) -> Result<(), DesktopError> { - let model = menu_model::parse_menu(&items)?; - let window = match window_id { - Some(key) => cx - .global::() - .0 - .get(key) - .map(|entry| entry.handle) - .ok_or_else(|| DesktopError::not_found(format!("window {key} is not open")))?, - // A hidden or off-screen window is not the platform's active window, so - // fall back to the main window rather than failing. - None => cx - .active_window() - .or_else(|| { - cx.global::() - .0 - .get(crate::desktop::windows::MAIN_WINDOW_KEY) - .map(|entry| entry.handle) - }) - .ok_or_else(|| DesktopError::failed("no window for the context menu"))?, - }; - let native_view = native_view_of(cx, window); - let (x, y) = match (x, y) { - (Some(x), Some(y)) => (x as f32, y as f32), - _ => cursor_position(cx, window), - }; - let request = ContextMenuRequest { - window, - x, - y, - model, - native_view, - }; - let presenter = cx.global::().0.clone(); - presenter.show(cx, request, responder); - Ok(()) -} - -/// Presents an already-parsed model at a position in a known window. -/// -/// The split exists for the native `ContextMenuView`, which parses its own props -/// before it gets here and knows which window the press arrived in. Sharing the -/// tail means the JS command and the native path cannot disagree about which -/// window hosts the menu or how the platform view is found. -pub fn present( - cx: &mut App, - model: MenuModel, - window: AnyWindowHandle, - position: (f32, f32), - responder: Responder, -) { - let request = ContextMenuRequest { - window, - x: position.0, - y: position.1, - model, - native_view: native_view_of(cx, window), - }; - let presenter = cx.global::().0.clone(); - presenter.show(cx, request, responder); -} - -fn native_view_of(cx: &mut App, window: AnyWindowHandle) -> isize { - window - .update(cx, |_root, window, _cx| raw_view(window)) - .unwrap_or(0) -} - -#[cfg(target_os = "macos")] -fn raw_view(window: &gpui::Window) -> isize { - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - match HasWindowHandle::window_handle(window) { - Ok(handle) => match handle.as_raw() { - RawWindowHandle::AppKit(appkit) => appkit.ns_view.as_ptr() as isize, - _ => 0, - }, - Err(_) => 0, - } -} - -#[cfg(target_os = "windows")] -fn raw_view(window: &gpui::Window) -> isize { - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - match HasWindowHandle::window_handle(window) { - Ok(handle) => match handle.as_raw() { - RawWindowHandle::Win32(win32) => win32.hwnd.get() as isize, - _ => 0, - }, - Err(_) => 0, - } -} - -#[cfg(not(any(target_os = "macos", target_os = "windows")))] -fn raw_view(_window: &gpui::Window) -> isize { - 0 -} - -fn cursor_position(cx: &mut App, window: AnyWindowHandle) -> (f32, f32) { - window - .update(cx, |_root, window, _cx| { - let position = window.mouse_position(); - (f32::from(position.x), f32::from(position.y)) - }) - .unwrap_or((0.0, 0.0)) -} - -struct NativeContextMenu; - -impl ContextMenuPresenter for NativeContextMenu { - fn name(&self) -> &'static str { - "native" - } - - fn show(&self, cx: &mut App, request: ContextMenuRequest, responder: Responder) { - // The native call runs a modal tracking loop, so it is deferred: GPUI - // must not be inside an update while the menu is open. - cx.defer(move |_cx| { - if let Err(error) = native_show(&request, &responder) { - responder.reject(error); - } - }); - } -} - -struct GpuiContextMenu; - -impl ContextMenuPresenter for GpuiContextMenu { - fn name(&self) -> &'static str { - "gpui" - } - - fn show(&self, cx: &mut App, request: ContextMenuRequest, responder: Responder) { - if let Err(error) = crate::desktop::gpui_menu::present(cx, request, responder.clone()) { - responder.reject(DesktopError::failed(error)); - } - } -} - -#[cfg(any(target_os = "macos", target_os = "windows"))] -fn native_show(request: &ContextMenuRequest, responder: &Responder) -> Result<(), DesktopError> { - use muda::ContextMenu as _; - - let menu = muda::Menu::new(); - build_muda_menu(&menu, &request.model.items)?; - let position = muda::dpi::Position::Logical(muda::dpi::LogicalPosition::new( - f64::from(request.x), - f64::from(request.y), - )); - if request.native_view == 0 { - return Err(DesktopError::failed( - "the window has no platform view for a context menu", - )); - } - // `muda` has one event channel and the app installs a handler on it (the - // menu bar and the tray both need one), so a handler-displaced receiver - // would never see this selection. `with_context_menu` reserves the channel - // for the duration of the menu instead, and `show` blocks until the menu - // closes, so the id is already in hand when it returns. - let selection = crate::desktop::menu_events::with_context_menu(|| { - #[cfg(target_os = "macos")] - // SAFETY: `request.native_view` is the live `NSView` the request was made for, and this runs on the main thread. - unsafe { - menu.show_context_menu_for_nsview( - request.native_view as *const std::ffi::c_void, - Some(position), - ) - }; - #[cfg(target_os = "windows")] - // SAFETY: `request.native_view` is the live `HWND` the request was made for, and this runs on the window's thread. - unsafe { - menu.show_context_menu_for_hwnd(request.native_view, Some(position)) - }; - }); - responder.resolve(selection.as_deref()); - Ok(()) -} - -#[cfg(not(any(target_os = "macos", target_os = "windows")))] -fn native_show(_request: &ContextMenuRequest, _responder: &Responder) -> Result<(), DesktopError> { - Err(DesktopError::unsupported( - "native context menus are not implemented on this platform yet", - )) -} - -#[cfg(any(target_os = "macos", target_os = "windows"))] -/// `Menu` and `Submenu` both append items, but the `ContextMenu` trait does not -/// cover it, so builders (context menus and the Windows menu bar) are generic -/// over this. -pub(crate) trait MudaAppend { - fn append_all(&self, items: &[&dyn muda::IsMenuItem]) -> muda::Result<()>; -} - -#[cfg(any(target_os = "macos", target_os = "windows"))] -impl MudaAppend for muda::Menu { - fn append_all(&self, items: &[&dyn muda::IsMenuItem]) -> muda::Result<()> { - self.append_items(items) - } -} - -#[cfg(any(target_os = "macos", target_os = "windows"))] -impl MudaAppend for muda::Submenu { - fn append_all(&self, items: &[&dyn muda::IsMenuItem]) -> muda::Result<()> { - self.append_items(items) - } -} - -#[cfg(any(target_os = "macos", target_os = "windows"))] -fn build_muda_menu(menu: &impl MudaAppend, items: &[MenuNode]) -> Result<(), DesktopError> { - use muda::{CheckMenuItem, IconMenuItem, MenuItem, PredefinedMenuItem, Submenu}; - - let mut children: Vec> = Vec::new(); - for node in items { - match node { - MenuNode::Separator => { - children.push(Box::new(PredefinedMenuItem::separator())); - } - MenuNode::StandardMenu(_) => {} - MenuNode::Item(item) => { - if item.checked { - children.push(Box::new(CheckMenuItem::with_id( - item.id.clone(), - item.label.clone(), - item.enabled, - true, - None, - ))); - } else if let Some(icon) = item.icon.as_deref().and_then(muda_icon) { - children.push(Box::new(IconMenuItem::with_id( - item.id.clone(), - item.label.clone(), - item.enabled, - Some(icon), - None, - ))); - } else { - children.push(Box::new(MenuItem::with_id( - item.id.clone(), - item.label.clone(), - item.enabled, - None, - ))); - } - } - MenuNode::Submenu(submenu) => { - let child = Submenu::new(submenu.label.clone(), submenu.enabled); - build_muda_menu(&child, &submenu.items)?; - children.push(Box::new(child)); - } - } - } - let refs: Vec<&dyn muda::IsMenuItem> = children.iter().map(|item| item.as_ref()).collect(); - menu.append_all(&refs) - .map_err(|error| DesktopError::failed(format!("could not build the context menu: {error}"))) -} - -/// A menu item's icon, if `desktop::icon` has loaded it. -#[cfg(any(target_os = "macos", target_os = "windows"))] -pub(crate) fn muda_icon(uri: &str) -> Option { - let icon = crate::desktop::icon::cached(uri)?; - muda::Icon::from_rgba(icon.rgba.clone(), icon.width, icon.height).ok() -} - -pub struct FakeContextMenu { - state: RefCell, -} - -#[derive(Default)] -struct FakeContextMenuState { - model: Option, - responder: Option, - position: (f32, f32), - shown: u32, -} - -pub struct FakeContextMenuGlobal(pub Rc); -impl gpui::Global for FakeContextMenuGlobal {} - -impl FakeContextMenu { - pub fn new() -> Self { - Self { - state: RefCell::new(FakeContextMenuState::default()), - } - } -} - -impl ContextMenuPresenter for FakeContextMenu { - fn name(&self) -> &'static str { - "fake" - } - - fn show(&self, _cx: &mut App, request: ContextMenuRequest, responder: Responder) { - let mut state = self.state.borrow_mut(); - // A second show dismisses the first with `null`. - if let Some(previous) = state.responder.take() { - previous.resolve(None); - } - state.model = Some(json!({"items": nodes_json(&request.model.items)})); - state.position = (request.x, request.y); - state.shown += 1; - state.responder = Some(responder); - } -} - -pub fn nodes_json(items: &[MenuNode]) -> Vec { - items - .iter() - .map(|node| match node { - MenuNode::Separator => json!({"type": "separator"}), - MenuNode::StandardMenu(role) => json!({"type": "role", "role": format!("{role:?}")}), - MenuNode::Submenu(submenu) => json!({ - "type": "submenu", - "id": submenu.id, - "label": submenu.label, - "enabled": submenu.enabled, - "items": nodes_json(&submenu.items), - "icon": submenu.icon, - }), - MenuNode::Item(item) => json!({ - "type": "item", - "id": item.id, - "label": item.label, - "enabled": item.enabled, - "checked": item.checked, - "icon": item.icon, - "iconLoaded": item - .icon - .as_deref() - .is_some_and(|uri| crate::desktop::icon::cached(uri).is_some()), - }), - }) - .collect() -} - -pub fn presenter_name(cx: &App) -> &'static str { - cx.try_global::() - .map(|presenter| presenter.0.name()) - .unwrap_or("none") -} - -pub fn fake_model(cx: &App) -> Option { - let fake = cx.try_global::()?; - let state = fake.0.state.borrow(); - Some(json!({ - "items": state.model.as_ref().and_then(|value| value.get("items")).cloned().unwrap_or(Value::Null), - "x": state.position.0, - "y": state.position.1, - "shown": state.shown, - })) -} - -pub fn fake_select(cx: &App, id: &str) -> bool { - let Some(fake) = cx.try_global::() else { - return false; - }; - let responder = fake.0.state.borrow_mut().responder.take(); - match responder { - Some(responder) => { - responder.resolve(Some(id)); - true - } - None => false, - } -} - -pub fn fake_dismiss(cx: &App) -> bool { - let Some(fake) = cx.try_global::() else { - return false; - }; - let responder = fake.0.state.borrow_mut().responder.take(); - match responder { - Some(responder) => { - responder.resolve(None); - true - } - None => false, - } -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn rejects_a_malformed_model_before_presenting() { - let error = menu_model::parse_menu(&json!([{"id": "a"}])).expect_err("label is required"); - assert_eq!(error.code, crate::desktop::errors::codes::INVALID_ARGUMENT); - } - - #[test] - fn nodes_json_keeps_ids_and_checks() { - let model = menu_model::parse_menu(&json!([ - {"id": "open", "label": "Open"}, - {"type": "separator"}, - {"id": "pin", "label": "Pin", "checked": true} - ])) - .expect("valid"); - let value = nodes_json(&model.items); - assert_eq!(value.len(), 3); - assert_eq!(value[2]["checked"], json!(true)); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/deep_link.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/deep_link.rs deleted file mode 100644 index 2d2ee06b28..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/deep_link.rs +++ /dev/null @@ -1,562 +0,0 @@ -//! URLs that open the app: from the OS, from the command line, or from a second -//! launch that handed its arguments to this process. - -use crate::host::Host; -use serde_json::json; -use std::io::{BufRead, BufReader, Write}; -use std::path::Path; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Mutex; -use std::time::Duration; - -static INITIAL: Mutex> = Mutex::new(None); -static HOST: Mutex> = Mutex::new(None); -static READY: AtomicBool = AtomicBool::new(false); - -/// The first argument that is a URL with one of `schemes`. -pub fn url_in_args(args: I, schemes: &[String]) -> Option -where - I: IntoIterator, - S: AsRef, -{ - args.into_iter().find_map(|arg| { - let arg = arg.as_ref(); - let (scheme, _) = arg.split_once(':')?; - schemes - .iter() - .any(|candidate| candidate.eq_ignore_ascii_case(scheme)) - .then(|| arg.to_string()) - }) -} - -/// JS is loaded: URLs from now on are `url` events rather than the launch URL. -pub fn mark_ready(host: Host) { - *HOST.lock().expect("deep link host poisoned") = Some(host); - READY.store(true, Ordering::Release); -} - -/// A URL reached the app. Before JS is loaded it is the one that launched it. -pub fn handle_url(url: String) { - if READY.load(Ordering::Acquire) { - if let Some(host) = HOST.lock().expect("deep link host poisoned").as_ref() { - host.emit_device_event_json("url", &json!({ "url": url }).to_string()); - return; - } - } - let mut initial = INITIAL.lock().expect("deep link state poisoned"); - if initial.is_none() { - *initial = Some(url); - } -} - -/// Reports to JS that another launch handed its arguments to this process. -pub fn second_instance(args: &[String]) { - if READY.load(Ordering::Acquire) { - if let Some(host) = HOST.lock().expect("deep link host poisoned").as_ref() { - host.emit_device_event_json( - "gpuiDesktop:secondInstance", - &json!({ "args": args }).to_string(), - ); - } - } -} - -pub fn initial_url() -> Option { - INITIAL.lock().expect("deep link state poisoned").clone() -} - -/// Whether this process is the one running the app. -pub enum Instance { - Primary, - /// Another copy is running and has been handed the arguments. - Forwarded, -} - -/// Where the running copy listens: in the user's own runtime directory when -/// there is one (`XDG_RUNTIME_DIR` on Linux, the per-user `TMPDIR` on macOS), -/// whose permissions already keep other users out, else beside the app's data. -/// A socket path is limited to about a hundred bytes, so the name is a hash. -#[cfg(unix)] -fn socket_path(dir: &Path, app_id: &str) -> std::path::PathBuf { - use std::hash::{Hash, Hasher}; - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - app_id.hash(&mut hasher); - let runtime = ["XDG_RUNTIME_DIR", "TMPDIR"] - .iter() - .filter_map(|name| std::env::var_os(name)) - .map(std::path::PathBuf::from) - .find(|path| path.is_dir()); - runtime.unwrap_or_else(|| dir.to_path_buf()).join(format!( - "rngpui-{:012x}.sock", - hasher.finish() & 0xffff_ffff_ffff - )) -} - -/// The pipe a Windows copy listens on. Pipe names are machine-wide, so the user -/// is part of the name and two users can each run the app. -#[cfg(windows)] -fn pipe_name(app_id: &str) -> String { - use std::hash::{Hash, Hasher}; - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - app_id.hash(&mut hasher); - let user: String = std::env::var("USERNAME") - .unwrap_or_default() - .chars() - .filter(char::is_ascii_alphanumeric) - .collect(); - format!( - r"\\.\pipe\rngpui-{user}-{:012x}", - hasher.finish() & 0xffff_ffff_ffff - ) -} - -#[cfg(unix)] -fn forward(dir: &Path, app_id: &str, args: &[String]) -> bool { - let Ok(mut stream) = std::os::unix::net::UnixStream::connect(socket_path(dir, app_id)) else { - return false; - }; - let _ = stream.set_read_timeout(Some(Duration::from_secs(2))); - let message = json!({ "args": args }).to_string(); - if writeln!(stream, "{message}").is_err() { - return false; - } - let mut reply = String::new(); - BufReader::new(stream).read_line(&mut reply).is_ok() && reply.trim() == "ok" -} - -#[cfg(windows)] -fn forward(_dir: &Path, app_id: &str, args: &[String]) -> bool { - let name = pipe_name(app_id); - // Every instance of the pipe is busy while the running copy accepts another - // client; the name only disappears with the process. - const PIPE_BUSY: i32 = 231; - let deadline = std::time::Instant::now() + Duration::from_secs(2); - let file = loop { - match std::fs::OpenOptions::new() - .read(true) - .write(true) - .open(&name) - { - Ok(file) => break file, - Err(error) - if error.raw_os_error() == Some(PIPE_BUSY) - && std::time::Instant::now() < deadline => - { - std::thread::sleep(Duration::from_millis(20)); - } - Err(_) => return false, - } - }; - let message = json!({ "args": args }).to_string(); - let (sender, receiver) = std::sync::mpsc::channel(); - let spawned = std::thread::Builder::new() - .name("single-instance-client".into()) - .spawn(move || { - let mut file = file; - let mut reply = String::new(); - let sent = writeln!(file, "{message}").is_ok() - && BufReader::new(file).read_line(&mut reply).is_ok(); - let _ = sender.send(sent && reply.trim() == "ok"); - }); - spawned.is_ok() - && receiver - .recv_timeout(Duration::from_secs(2)) - .unwrap_or(false) -} - -/// Becomes the running instance, or hands `args` to the one that is. -/// -/// The first process listens on a Unix socket in the user's runtime directory, -/// which only that user can reach. On Windows it listens on a named pipe whose -/// access list names only the user, and which refuses remote clients. A later -/// launch connects, sends its arguments and exits. A socket whose process is -/// gone fails to connect, and the new process takes over; a pipe goes away with -/// its process. -#[cfg(unix)] -pub fn acquire( - dir: &Path, - app_id: &str, - args: &[String], - on_args: impl Fn(Vec) + Send + 'static, -) -> Instance { - use std::os::unix::fs::PermissionsExt; - if forward(dir, app_id, args) { - return Instance::Forwarded; - } - let path = socket_path(dir, app_id); - if std::fs::create_dir_all(dir).is_err() { - return Instance::Primary; - } - let _ = std::fs::remove_file(&path); - let Ok(listener) = std::os::unix::net::UnixListener::bind(&path) else { - return Instance::Primary; - }; - let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)); - let spawned = std::thread::Builder::new() - .name("single-instance".into()) - .spawn(move || { - for stream in listener.incoming().flatten() { - let _ = stream.set_read_timeout(Some(Duration::from_secs(1))); - serve(&stream, &stream, &on_args); - } - }); - if let Err(error) = spawned { - log::warn!("single instance listener not started: {error}"); - } - Instance::Primary -} - -#[cfg(windows)] -pub fn acquire( - dir: &Path, - app_id: &str, - args: &[String], - on_args: impl Fn(Vec) + Send + 'static, -) -> Instance { - if forward(dir, app_id, args) { - return Instance::Forwarded; - } - let name = pipe_name(app_id); - let Some(first) = pipe::create(&name, true) else { - return Instance::Primary; - }; - let on_args = std::sync::Arc::new(Mutex::new(on_args)); - let spawned = std::thread::Builder::new() - .name("single-instance".into()) - .spawn(move || { - let mut current = first; - loop { - pipe::connect(¤t); - // The next instance exists before this client is served, so a - // launch arriving meanwhile finds the pipe busy, not missing. - let Some(next) = pipe::create(&name, false) else { - return; - }; - let served = std::mem::replace(&mut current, next); - let on_args = on_args.clone(); - let _ = std::thread::Builder::new() - .name("single-instance-client".into()) - .spawn(move || { - serve(&served, &served, &|args| { - (on_args.lock().expect("single instance callback poisoned"))(args) - }); - }); - } - }); - if let Err(error) = spawned { - log::warn!("single instance listener not started: {error}"); - } - Instance::Primary -} - -#[cfg(windows)] -mod pipe { - use std::io::{Read, Write}; - use std::os::windows::io::{FromRawHandle, OwnedHandle}; - use windows_sys::Win32::{ - Foundation::{LocalFree, INVALID_HANDLE_VALUE}, - Security::{ - Authorization::{ - ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1, - }, - SECURITY_ATTRIBUTES, - }, - Storage::FileSystem::{ - FlushFileBuffers, ReadFile, WriteFile, FILE_FLAG_FIRST_PIPE_INSTANCE, - PIPE_ACCESS_DUPLEX, - }, - System::Pipes::{ - ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, PIPE_READMODE_BYTE, - PIPE_REJECT_REMOTE_CLIENTS, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, PIPE_WAIT, - }, - }; - - /// Owner rights only: the pipe's default access list also lets other users - /// read it. - const OWNER_ONLY: &str = "D:P(A;;GA;;;OW)"; - - /// One server-side instance of the pipe. - pub struct Instance(OwnedHandle); - - pub fn create(name: &str, first: bool) -> Option { - use std::os::windows::ffi::OsStrExt; - let wide = |text: &str| -> Vec { - std::ffi::OsStr::new(text) - .encode_wide() - .chain(Some(0)) - .collect() - }; - let mut descriptor = std::ptr::null_mut(); - // SAFETY: both strings are NUL-terminated and `descriptor` receives a - // LocalAlloc'd block that is freed below. - let converted = unsafe { - ConvertStringSecurityDescriptorToSecurityDescriptorW( - wide(OWNER_ONLY).as_ptr(), - SDDL_REVISION_1, - &mut descriptor, - std::ptr::null_mut(), - ) - }; - if converted == 0 { - return None; - } - let attributes = SECURITY_ATTRIBUTES { - nLength: std::mem::size_of::() as u32, - lpSecurityDescriptor: descriptor, - bInheritHandle: 0, - }; - let open_mode = PIPE_ACCESS_DUPLEX - | if first { - FILE_FLAG_FIRST_PIPE_INSTANCE - } else { - 0 - }; - // SAFETY: `wide` is NUL-terminated and `attributes` outlives the call. - let handle = unsafe { - CreateNamedPipeW( - wide(name).as_ptr(), - open_mode, - PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, - PIPE_UNLIMITED_INSTANCES, - 4096, - 4096, - 0, - &attributes, - ) - }; - // SAFETY: allocated by the conversion above and not used again. - unsafe { LocalFree(descriptor) }; - if handle == INVALID_HANDLE_VALUE { - return None; - } - // SAFETY: a valid handle this function owns. - Some(Instance(unsafe { - OwnedHandle::from_raw_handle(handle as _) - })) - } - - /// Blocks until a client has connected. - pub fn connect(instance: &Instance) { - use std::os::windows::io::AsRawHandle; - // SAFETY: the handle is a pipe instance owned by `instance`. A client that - // connected before this call makes it fail with ERROR_PIPE_CONNECTED, - // which also means the pipe is ready. - unsafe { ConnectNamedPipe(instance.0.as_raw_handle() as _, std::ptr::null_mut()) }; - } - - impl Read for &Instance { - fn read(&mut self, buffer: &mut [u8]) -> std::io::Result { - use std::os::windows::io::AsRawHandle; - let mut read = 0u32; - // SAFETY: `buffer` is valid for its length and the handle is open. - let ok = unsafe { - ReadFile( - self.0.as_raw_handle() as _, - buffer.as_mut_ptr(), - buffer.len().min(u32::MAX as usize) as u32, - &mut read, - std::ptr::null_mut(), - ) - }; - if ok == 0 { - // A client that closed its end reads as end of file. - return Ok(0); - } - Ok(read as usize) - } - } - - impl Write for &Instance { - fn write(&mut self, buffer: &[u8]) -> std::io::Result { - use std::os::windows::io::AsRawHandle; - let mut written = 0u32; - // SAFETY: `buffer` is valid for its length and the handle is open. - let ok = unsafe { - WriteFile( - self.0.as_raw_handle() as _, - buffer.as_ptr(), - buffer.len().min(u32::MAX as usize) as u32, - &mut written, - std::ptr::null_mut(), - ) - }; - if ok == 0 { - return Err(std::io::Error::last_os_error()); - } - Ok(written as usize) - } - - fn flush(&mut self) -> std::io::Result<()> { - use std::os::windows::io::AsRawHandle; - // SAFETY: the handle is open. - unsafe { FlushFileBuffers(self.0.as_raw_handle() as _) }; - Ok(()) - } - } - - impl Drop for Instance { - fn drop(&mut self) { - use std::os::windows::io::AsRawHandle; - // SAFETY: the handle is still open. Disconnecting discards what the - // client has not read, so the reply is flushed to it first. - unsafe { - FlushFileBuffers(self.0.as_raw_handle() as _); - DisconnectNamedPipe(self.0.as_raw_handle() as _); - } - } - } -} - -fn serve(reader: impl Read, mut writer: impl Write, on_args: &impl Fn(Vec)) { - let mut line = String::new(); - let mut reader = BufReader::new(reader).take(64 * 1024); - if reader.read_line(&mut line).is_err() { - return; - } - let Ok(message) = serde_json::from_str::(&line) else { - return; - }; - let args = message - .get("args") - .and_then(serde_json::Value::as_array) - .map(|args| { - args.iter() - .filter_map(|arg| arg.as_str().map(str::to_string)) - .collect() - }) - .unwrap_or_default(); - on_args(args); - let _ = writeln!(writer, "ok"); -} - -use std::io::Read; - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::mpsc; - - fn schemes() -> Vec { - vec!["myapp".to_string()] - } - - #[test] - fn the_url_among_the_arguments_is_found_by_scheme() { - let args = ["app", "--flag", "MYAPP://open/1", "other://x"]; - assert_eq!( - url_in_args(args, &schemes()).as_deref(), - Some("MYAPP://open/1") - ); - assert_eq!(url_in_args(["app", "https://x"], &schemes()), None); - } - - #[test] - fn a_second_launch_hands_its_arguments_to_the_first() { - let dir = std::env::temp_dir().join(format!("rngpui-instance-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let (sender, receiver) = mpsc::channel(); - let sender = Mutex::new(sender); - let first = acquire(&dir, "com.example.test", &[], move |args| { - let _ = sender.lock().unwrap().send(args); - }); - assert!(matches!(first, Instance::Primary)); - let second = acquire( - &dir, - "com.example.test", - &["app".to_string(), "myapp://hello".to_string()], - |_| panic!("the second launch must not become primary"), - ); - assert!(matches!(second, Instance::Forwarded)); - let received = receiver.recv_timeout(Duration::from_secs(2)).unwrap(); - assert_eq!( - url_in_args(&received, &schemes()).as_deref(), - Some("myapp://hello") - ); - #[cfg(unix)] - let _ = std::fs::remove_file(socket_path(&dir, "com.example.test")); - let _ = std::fs::remove_dir_all(&dir); - } - - #[cfg(unix)] - #[test] - fn a_stale_socket_is_taken_over() { - let dir = std::env::temp_dir().join(format!("rngpui-stale-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - // A socket file nothing listens on is what a crashed copy leaves behind. - let path = socket_path(&dir, "com.example.stale"); - let _ = std::fs::remove_file(&path); - drop(std::os::unix::net::UnixListener::bind(&path).unwrap()); - let instance = acquire(&dir, "com.example.stale", &[], |_| {}); - assert!(matches!(instance, Instance::Primary)); - let _ = std::fs::remove_file(&path); - let _ = std::fs::remove_dir_all(&dir); - } - - #[cfg(unix)] - #[test] - fn the_socket_is_reachable_only_by_its_owner() { - use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir().join(format!("rngpui-mode-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - acquire(&dir, "com.example.mode", &[], |_| {}); - let mode = std::fs::metadata(socket_path(&dir, "com.example.mode")) - .unwrap() - .permissions() - .mode(); - assert_eq!(mode & 0o077, 0); - let _ = std::fs::remove_file(socket_path(&dir, "com.example.mode")); - let _ = std::fs::remove_dir_all(&dir); - } - - #[cfg(windows)] - #[test] - fn simultaneous_launches_are_all_delivered() { - let dir = std::env::temp_dir(); - let (sender, receiver) = mpsc::channel(); - let sender = Mutex::new(sender); - let first = acquire(&dir, "com.example.parallel", &[], move |args| { - let _ = sender.lock().unwrap().send(args); - }); - assert!(matches!(first, Instance::Primary)); - let launches: Vec<_> = (0..8) - .map(|index| { - let dir = dir.clone(); - std::thread::spawn(move || { - acquire( - &dir, - "com.example.parallel", - &[format!("myapp://{index}")], - |_| panic!("a later launch must not become primary"), - ) - }) - }) - .collect(); - for launch in launches { - assert!(matches!(launch.join().unwrap(), Instance::Forwarded)); - } - let mut seen: Vec = (0..8) - .map(|_| { - receiver - .recv_timeout(Duration::from_secs(5)) - .unwrap() - .remove(0) - }) - .collect(); - seen.sort(); - let mut expected: Vec = (0..8).map(|index| format!("myapp://{index}")).collect(); - expected.sort(); - assert_eq!(seen, expected); - } - - #[cfg(windows)] - #[test] - fn a_second_first_instance_of_a_live_pipe_is_refused() { - let name = pipe_name("com.example.access"); - assert!(name.starts_with(r"\\.\pipe\rngpui-")); - let first = pipe::create(&name, true); - assert!(first.is_some()); - // A second "first" instance of a live pipe is refused. - assert!(pipe::create(&name, true).is_none()); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/dev_menu.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/dev_menu.rs deleted file mode 100644 index 6f8a161865..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/dev_menu.rs +++ /dev/null @@ -1,674 +0,0 @@ -use crate::desktop::menu_model::{MenuItemDef, MenuModel, MenuNode}; -use crate::desktop::perf_monitor; -use crate::desktop::windows::{DesktopWindowsGlobal, MAIN_WINDOW_KEY}; -use crate::store::store_from; -use gpui::{App, Global}; -use serde_json::{json, Value}; -use std::cell::RefCell; - -pub const RELOAD: &str = "dev:reload"; -pub const OPEN_DEVTOOLS: &str = "dev:openDevTools"; -pub const ELEMENT_INSPECTOR: &str = "dev:elementInspector"; -pub const PERF_MONITOR: &str = "dev:perfMonitor"; -pub const FAST_REFRESH: &str = "dev:fastRefresh"; -/// The id of the custom item at an index of `custom_items` is this and the index. -const CUSTOM_PREFIX: &str = "dev:item:"; -pub const ACCELERATOR: &str = "secondary-d"; -pub const ACCELERATOR_ID: &str = "dev:menu"; - -#[derive(Default)] -pub struct DevSettings { - pub installed: bool, - pub hot_loading: bool, - pub profiling: bool, - pub inspector: bool, - /// The titles `DevSettings.addMenuItem` added, in the order they came. - pub custom_items: Vec, -} - -pub struct DevSettingsGlobal(pub RefCell); -impl Global for DevSettingsGlobal {} - -pub fn is_installed(cx: &App) -> bool { - cx.try_global::() - .is_some_and(|state| state.0.borrow().installed) -} - -pub fn install(cx: &mut App, enabled: bool) { - cx.set_global(DevSettingsGlobal(RefCell::new(DevSettings { - installed: enabled, - hot_loading: true, - ..Default::default() - }))); -} - -pub fn menu_model(cx: &App) -> MenuModel { - let (hot_loading, inspector, custom) = cx - .try_global::() - .map(|state| { - let state = state.0.borrow(); - ( - state.hot_loading, - state.inspector, - state.custom_items.clone(), - ) - }) - .unwrap_or((false, false, Vec::new())); - let profiling = perf_monitor::is_enabled(cx); - let item = |id: &str, label: &str, checked: bool| { - MenuNode::Item(MenuItemDef { - id: id.to_string(), - label: label.to_string(), - accelerator: None, - enabled: true, - checked, - role: None, - icon: None, - }) - }; - let mut items = vec![ - item(RELOAD, "Reload", false), - item(OPEN_DEVTOOLS, "Open DevTools", false), - MenuNode::Separator, - item(ELEMENT_INSPECTOR, "Toggle Element Inspector", inspector), - item(PERF_MONITOR, "Toggle Perf Monitor", profiling), - item(FAST_REFRESH, "Fast Refresh", hot_loading), - ]; - if !custom.is_empty() { - items.push(MenuNode::Separator); - items.extend( - custom - .iter() - .enumerate() - .map(|(index, title)| item(&format!("{CUSTOM_PREFIX}{index}"), title, false)), - ); - } - MenuModel { items } -} - -pub fn show(cx: &mut App) { - if !is_installed(cx) { - log::warn!("[desktop][devmenu] the Dev Menu is not enabled in this build"); - return; - } - // The panel may have been closed since it was recorded, so liveness is - // asked of the window rather than remembered. - if let Some(handle) = open_panel(cx) { - let _ = handle.update(cx, |_root: gpui::AnyView, window, _cx| { - if !crate::desktop::background::enabled() { - window.activate_window(); - } - }); - return; - } - // `WindowKind::Dialog` is a sheet on macOS, so this is a normal window - // centred over the app window. - let size = gpui::size(gpui::px(380.0), gpui::px(460.0)); - let bounds = main_window(cx) - .and_then(|handle| { - handle - .update(cx, |_root: gpui::AnyView, window, _cx| window.bounds()) - .ok() - }) - .map(|parent| { - gpui::Bounds::new( - gpui::point( - parent.origin.x + (parent.size.width - size.width) / 2.0, - parent.origin.y + (parent.size.height - size.height) / 2.0, - ), - size, - ) - }) - .unwrap_or_else(|| gpui::Bounds::centered(None, size, cx)); - let options = gpui::WindowOptions { - window_bounds: Some(gpui::WindowBounds::Windowed(bounds)), - kind: gpui::WindowKind::Normal, - is_resizable: false, - window_min_size: Some(size), - titlebar: Some(gpui::TitlebarOptions { - title: Some("Dev Menu".into()), - appears_transparent: false, - traffic_light_position: None, - }), - ..Default::default() - }; - match cx.open_window(options, |_window, cx| { - gpui::AppContext::new(cx, |_cx| DevMenuPanel::new()) - }) { - Ok(handle) => { - let handle: gpui::AnyWindowHandle = handle.into(); - cx.set_global(DevMenuPanelGlobal(RefCell::new(Some(handle)))); - let _ = handle.update(cx, |_root: gpui::AnyView, window, _cx| { - crate::desktop::platform_window::disable_window_animation(window); - }); - log::info!("[desktop][devmenu] opened the panel"); - } - Err(error) => log::error!("[desktop][devmenu] could not open the panel: {error}"), - } -} - -pub fn hide(cx: &mut App) { - let Some(handle) = open_panel(cx) else { - forget_panel(cx); - return; - }; - forget_panel(cx); - let _ = handle.update(cx, |_root: gpui::AnyView, window, _cx| { - window.remove_window() - }); -} - -pub struct DevMenuPanelGlobal(pub RefCell>); -impl Global for DevMenuPanelGlobal {} - -fn open_panel(cx: &mut App) -> Option { - let handle = cx - .try_global::() - .and_then(|panel| *panel.0.borrow())?; - handle - .update(cx, |_root: gpui::AnyView, _window, _cx| ()) - .ok()?; - Some(handle) -} - -fn forget_panel(cx: &mut App) { - if let Some(panel) = cx.try_global::() { - panel.0.borrow_mut().take(); - } -} - -const DEFAULT_BUNDLER_PORT: u32 = 8081; - -fn parse_bundler(text: &str) -> Result<(String, u32), &'static str> { - let text = text.trim(); - let text = text - .strip_prefix("http://") - .or_else(|| text.strip_prefix("https://")) - .unwrap_or(text) - .trim_end_matches('/'); - let (host, port) = match text.rsplit_once(':') { - Some((host, port)) => ( - host, - port.parse::() - .ok() - .filter(|port| (1..=65535).contains(port)) - .ok_or("The port must be a number from 1 to 65535.")?, - ), - None => (text, DEFAULT_BUNDLER_PORT), - }; - if host.is_empty() { - return Err("Enter the bundler's address as host:port."); - } - Ok((host.to_string(), port)) -} - -fn is_bundler_char(c: char) -> bool { - c.is_ascii_alphanumeric() || matches!(c, '.' | ':' | '-' | '_' | '/' | '[' | ']') -} - -pub struct DevMenuPanel { - bundler: Option, - bundler_error: Option<&'static str>, - focus: Option, -} - -impl DevMenuPanel { - pub fn new() -> Self { - Self { - bundler: None, - bundler_error: None, - focus: None, - } - } - - fn render_bundler( - &mut self, - text: String, - window: &mut gpui::Window, - cx: &mut gpui::Context, - ) -> gpui::Stateful { - use gpui::{InteractiveElement, ParentElement, Styled}; - - let focus = self.focus.get_or_insert_with(|| cx.focus_handle()).clone(); - if !focus.is_focused(window) { - window.focus(&focus, cx); - } - gpui::div() - .id(gpui::SharedString::from("dev-menu-bundler")) - .track_focus(&focus) - .size_full() - .flex() - .flex_col() - .gap_2() - .p_3() - .bg(gpui::rgb(0xf4f5f7)) - .text_color(gpui::rgb(0x18212f)) - .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, window, cx| { - let Some(text) = this.bundler.as_mut() else { - return; - }; - let keystroke = &event.keystroke; - let command = keystroke.modifiers.platform || keystroke.modifiers.control; - match keystroke.key.as_str() { - "escape" => { - this.bundler = None; - this.bundler_error = None; - } - "backspace" => { - text.pop(); - this.bundler_error = None; - } - "enter" => match parse_bundler(text) { - Ok((host, port)) => { - let applied = store_from(cx).is_some_and(|store| { - store.read(cx).host.set_dev_server(&host, port) - }); - if applied { - log::info!( - "[desktop][devmenu] bundler set to {host}:{port}; reloading" - ); - forget_panel(cx); - window.remove_window(); - return; - } - this.bundler_error = - Some("This build is not connected to a dev server."); - } - Err(error) => this.bundler_error = Some(error), - }, - "v" if command => { - if let Some(pasted) = cx.read_from_clipboard().and_then(|item| item.text()) - { - text.extend(pasted.chars().filter(|c| is_bundler_char(*c))); - this.bundler_error = None; - } - } - _ if command => {} - _ => { - if let Some(typed) = keystroke.key_char.as_ref() { - text.extend(typed.chars().filter(|c| is_bundler_char(*c))); - this.bundler_error = None; - } - } - } - cx.stop_propagation(); - cx.notify(); - })) - .child( - gpui::div() - .px_3() - .py_2() - .text_size(gpui::px(18.0)) - .child("Configure Bundler"), - ) - .child( - gpui::div() - .px_3() - .text_size(gpui::px(13.0)) - .text_color(gpui::rgba(0x000000aa)) - .child("The Metro server to load the bundle from, as host:port."), - ) - .child( - gpui::div() - .mx_3() - .px_2() - .py_2() - .rounded(gpui::px(3.0)) - .border_1() - .border_color(gpui::rgb(0x3b82f6)) - .bg(gpui::white()) - .text_size(gpui::px(14.0)) - // The caret: the field is always at the end of the text. - .child(format!("{text}\u{2502}")), - ) - .children(self.bundler_error.map(|error| { - gpui::div() - .px_3() - .text_size(gpui::px(13.0)) - .text_color(gpui::rgb(0xb91c1c)) - .child(error) - })) - .child( - gpui::div() - .px_3() - .text_size(gpui::px(13.0)) - .text_color(gpui::rgba(0x00000099)) - .child("Enter applies it and reloads. Escape goes back."), - ) - } -} - -impl gpui::Render for DevMenuPanel { - fn render( - &mut self, - window: &mut gpui::Window, - cx: &mut gpui::Context, - ) -> impl gpui::IntoElement { - use gpui::{InteractiveElement, IntoElement, ParentElement, Styled}; - - window.on_window_should_close(cx, |_window, cx| { - forget_panel(cx); - true - }); - - if let Some(text) = self.bundler.clone() { - return self.render_bundler(text, window, cx); - } - let bundler = store_from(cx) - .map(|store| store.read(cx).host.dev_server_address()) - .unwrap_or_default(); - - let rows = menu_model(cx); - let mut elements: Vec = Vec::new(); - for node in rows.items { - match node { - MenuNode::Separator => { - elements.push( - gpui::div() - .h(gpui::px(1.0)) - .my_1() - .bg(gpui::rgba(0x00000022)) - .into_any_element() as gpui::AnyElement, - ); - } - MenuNode::Item(item) => { - let id = item.id.clone(); - elements.push( - gpui::div() - .id(gpui::SharedString::from(format!("dev-menu-{}", item.id))) - .flex() - .flex_row() - .items_center() - .justify_between() - .px_3() - .py_2() - .rounded(gpui::px(3.0)) - .text_size(gpui::px(14.0)) - .cursor_pointer() - .hover(|style| style.bg(gpui::rgba(0x00000011))) - .child(item.label.clone()) - .child(if item.checked { "✓" } else { "" }) - .on_mouse_down( - gpui::MouseButton::Left, - cx.listener(move |_this, _event, window, cx| { - if let Some(handler) = - rn_gpui_sys::DEV_MENU_PERFORM_HANDLER.get() - { - handler(id.clone()); - } - forget_panel(cx); - window.remove_window(); - }), - ) - .into_any_element(), - ); - } - MenuNode::Submenu(_) | MenuNode::StandardMenu(_) => {} - } - } - - gpui::div() - .id(gpui::SharedString::from("dev-menu-panel")) - .size_full() - .flex() - .flex_col() - .gap_1() - .p_3() - .bg(gpui::rgb(0xf4f5f7)) - .text_color(gpui::rgb(0x18212f)) - .child( - gpui::div() - .px_3() - .py_2() - .text_size(gpui::px(18.0)) - .child("Dev Menu"), - ) - .children(elements) - // Only with a dev server: a release bundle has nowhere else to - // load from. - .children((!bundler.is_empty()).then(|| { - gpui::div() - .id(gpui::SharedString::from("dev-menu-bundler-row")) - .flex() - .flex_row() - .items_center() - .justify_between() - .px_3() - .py_2() - .rounded(gpui::px(3.0)) - .text_size(gpui::px(14.0)) - .cursor_pointer() - .hover(|style| style.bg(gpui::rgba(0x00000011))) - .child("Configure Bundler…") - .child( - gpui::div() - .text_color(gpui::rgba(0x00000099)) - .child(bundler.clone()), - ) - .on_mouse_down( - gpui::MouseButton::Left, - cx.listener(move |this, _event, _window, cx| { - this.bundler = Some(bundler.clone()); - this.bundler_error = None; - cx.notify(); - }), - ) - })) - .child( - gpui::div() - .id(gpui::SharedString::from("dev-menu-close")) - .mt_2() - .px_3() - .py_2() - .rounded(gpui::px(3.0)) - .text_size(gpui::px(14.0)) - .text_color(gpui::rgba(0x00000099)) - .cursor_pointer() - .hover(|style| style.bg(gpui::rgba(0x00000011))) - .child("Close") - .on_mouse_down( - gpui::MouseButton::Left, - cx.listener(|_this, _event, window, cx| { - forget_panel(cx); - window.remove_window(); - }), - ), - ) - } -} - -pub fn is_command(id: &str) -> bool { - matches!( - id, - RELOAD | OPEN_DEVTOOLS | ELEMENT_INSPECTOR | PERF_MONITOR | FAST_REFRESH - ) || id.starts_with(CUSTOM_PREFIX) -} - -pub fn perform(cx: &mut App, id: &str) { - match id { - RELOAD => { - if let Some(store) = store_from(cx) { - store.read(cx).host.request_reload(); - } - } - OPEN_DEVTOOLS => { - if let Some(store) = store_from(cx) { - store.read(cx).host.open_debugger(); - } - emit(cx, "gpuiDesktop:devToolsRequested", json!({})); - } - ELEMENT_INSPECTOR => { - let enabled = toggle(cx, "inspector"); - // The event React Native's `AppContainer` listens for; every - // platform's dev menu toggles the inspector by emitting it. - emit(cx, "toggleElementInspector", json!({})); - emit( - cx, - "gpuiDesktop:elementInspector", - json!({"enabled": enabled}), - ); - } - PERF_MONITOR => { - let enabled = !perf_monitor::is_enabled(cx); - perf_monitor::set_enabled(cx, enabled); - } - FAST_REFRESH => { - let enabled = toggle(cx, "hotLoading"); - emit(cx, "gpuiDesktop:fastRefresh", json!({"enabled": enabled})); - } - custom => { - let title = custom - .strip_prefix(CUSTOM_PREFIX) - .and_then(|index| index.parse::().ok()) - .and_then(|index| { - cx.try_global::() - .and_then(|state| state.0.borrow().custom_items.get(index).cloned()) - }); - // The event `DevSettings` listens for on every platform. - if let Some(title) = title { - emit(cx, "didPressMenuItem", json!({ "title": title })); - } - } - } -} - -pub fn apply_setting(cx: &mut App, name: &str, enabled: bool) { - if let Some(title) = name.strip_prefix("menuItem:") { - if let Some(state) = cx.try_global::() { - let mut state = state.0.borrow_mut(); - if !state.custom_items.iter().any(|item| item == title) { - state.custom_items.push(title.to_string()); - } - } - return; - } - match name { - "profiling" => { - perf_monitor::set_enabled(cx, enabled); - } - "hotLoading" => { - if let Some(state) = cx.try_global::() { - state.0.borrow_mut().hot_loading = enabled; - } - emit(cx, "gpuiDesktop:fastRefresh", json!({"enabled": enabled})); - } - // `DevSettings.toggleElementInspector` has no value to pass. - "inspectorToggle" => { - let enabled = toggle(cx, "inspector"); - emit(cx, "toggleElementInspector", json!({})); - emit( - cx, - "gpuiDesktop:elementInspector", - json!({"enabled": enabled}), - ); - } - "inspector" => { - if let Some(state) = cx.try_global::() { - state.0.borrow_mut().inspector = enabled; - } - emit( - cx, - "gpuiDesktop:elementInspector", - json!({"enabled": enabled}), - ); - } - _ => {} - } -} - -fn toggle(cx: &App, which: &str) -> bool { - let Some(state) = cx.try_global::() else { - return false; - }; - let mut state = state.0.borrow_mut(); - let value = match which { - "inspector" => &mut state.inspector, - "hotLoading" => &mut state.hot_loading, - "profiling" => &mut state.profiling, - _ => return false, - }; - *value = !*value; - *value -} - -fn emit(cx: &App, name: &str, payload: Value) { - let Some(store) = store_from(cx) else { - return; - }; - store - .read(cx) - .host - .emit_device_event_json(name, &payload.to_string()); -} - -#[cfg_attr(not(target_os = "windows"), allow(dead_code))] -pub fn main_window(cx: &App) -> Option { - cx.try_global::() - .and_then(|windows| windows.0.get(MAIN_WINDOW_KEY).map(|entry| entry.handle)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn accelerator_is_command_or_control_d() { - assert_eq!(ACCELERATOR, "secondary-d"); - assert_eq!(ACCELERATOR_ID, "dev:menu"); - } - - #[test] - fn bundler_addresses_parse_with_and_without_a_port() { - assert_eq!( - parse_bundler("localhost:8082"), - Ok(("localhost".into(), 8082)) - ); - assert_eq!(parse_bundler(" 10.0.0.5 "), Ok(("10.0.0.5".into(), 8081))); - assert_eq!( - parse_bundler("http://my-mac.local:9000/"), - Ok(("my-mac.local".into(), 9000)) - ); - assert!(parse_bundler("").is_err()); - assert!(parse_bundler(":8081").is_err()); - assert!(parse_bundler("localhost:0").is_err()); - assert!(parse_bundler("localhost:port").is_err()); - } - - #[test] - fn dev_item_ids_are_unique() { - let ids = [ - RELOAD, - OPEN_DEVTOOLS, - ELEMENT_INSPECTOR, - PERF_MONITOR, - FAST_REFRESH, - ]; - let unique: std::collections::HashSet<_> = ids.iter().collect(); - assert_eq!(unique.len(), ids.len()); - } - - #[gpui::test] - fn an_added_menu_item_is_listed_once_and_is_a_command(cx: &mut gpui::TestAppContext) { - cx.update(|cx| { - install(cx, true); - apply_setting(cx, "menuItem:Show Secret Screen", true); - apply_setting(cx, "menuItem:Show Secret Screen", true); - apply_setting(cx, "menuItem:Other", true); - let labels: Vec = menu_model(cx) - .items - .iter() - .filter_map(|node| match node { - MenuNode::Item(item) if item.id.starts_with("dev:item:") => { - Some(format!("{} {}", item.id, item.label)) - } - _ => None, - }) - .collect(); - assert_eq!( - labels, - ["dev:item:0 Show Secret Screen", "dev:item:1 Other"] - ); - assert!(is_command("dev:item:1")); - }); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/display.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/display.rs deleted file mode 100644 index 4bc68a4d2e..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/display.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! The display a window is on and the system's text scale, for `Dimensions`. - -use gpui::{App, Window}; - -/// The system text scale. A test build can pin it with `RN_GPUI_TEST_FONT_SCALE`. -pub fn system_font_scale() -> f32 { - #[cfg(feature = "test-driver")] - if let Some(scale) = std::env::var("RN_GPUI_TEST_FONT_SCALE") - .ok() - .and_then(|value| value.parse::().ok()) - .filter(|scale| *scale > 0.0) - { - return scale; - } - os_font_scale() -} - -/// The user's text size preference as a multiplier; `1.0` where the OS has none. -#[cfg(target_os = "windows")] -fn os_font_scale() -> f32 { - use windows_sys::Win32::System::Registry::{RegGetValueW, HKEY_CURRENT_USER, RRF_RT_REG_DWORD}; - let subkey: Vec = "Software\\Microsoft\\Accessibility\0" - .encode_utf16() - .collect(); - let value: Vec = "TextScaleFactor\0".encode_utf16().collect(); - let mut percent: u32 = 0; - let mut size = std::mem::size_of::() as u32; - // SAFETY: both names are NUL-terminated and `percent` is a valid DWORD slot - // of `size` bytes. - let status = unsafe { - RegGetValueW( - HKEY_CURRENT_USER, - subkey.as_ptr(), - value.as_ptr(), - RRF_RT_REG_DWORD, - std::ptr::null_mut(), - (&mut percent as *mut u32).cast(), - &mut size, - ) - }; - if status == 0 { - parse_percent(percent) - } else { - 1.0 - } -} - -#[cfg(target_os = "linux")] -fn os_font_scale() -> f32 { - std::process::Command::new("gsettings") - .args(["get", "org.gnome.desktop.interface", "text-scaling-factor"]) - .output() - .ok() - .filter(|output| output.status.success()) - .and_then(|output| parse_factor(&String::from_utf8_lossy(&output.stdout))) - .unwrap_or(1.0) -} - -#[cfg(not(any(target_os = "windows", target_os = "linux")))] -fn os_font_scale() -> f32 { - 1.0 -} - -/// A registry percentage (`150`) as a multiplier, bounded to what a UI can lay out. -#[cfg_attr(not(target_os = "windows"), allow(dead_code))] -fn parse_percent(percent: u32) -> f32 { - (percent as f32 / 100.0).clamp(0.5, 4.0) -} - -/// `gsettings` prints a bare number, or `uint32 1.25`-style for some types. -#[cfg_attr(not(target_os = "linux"), allow(dead_code))] -fn parse_factor(output: &str) -> Option { - let factor: f32 = output.split_whitespace().last()?.parse().ok()?; - (factor.is_finite() && factor > 0.0).then(|| factor.clamp(0.5, 4.0)) -} - -/// The size of the display `window` is on, in points. -pub fn display_size(window: &Window, cx: &App) -> Option<(f32, f32)> { - let display = window.display(cx).or_else(|| cx.primary_display())?; - let size = display.bounds().size; - Some((f32::from(size.width), f32::from(size.height))) -} - -/// Tells `Dimensions` the display and text scale `window` sees now. -pub fn report(window: &Window, cx: &App, host: &crate::host::Host) { - let Some((width, height)) = display_size(window, cx) else { - return; - }; - host.set_display_metrics(width, height, system_font_scale()); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_percentage_becomes_a_multiplier() { - assert_eq!(parse_percent(100), 1.0); - assert_eq!(parse_percent(150), 1.5); - assert_eq!(parse_percent(0), 0.5); - assert_eq!(parse_percent(10_000), 4.0); - } - - #[test] - fn gsettings_output_is_read_as_a_factor() { - assert_eq!(parse_factor("1.25\n"), Some(1.25)); - assert_eq!(parse_factor("uint32 2\n"), Some(2.0)); - assert_eq!(parse_factor("garbage"), None); - assert_eq!(parse_factor("-1"), None); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/errors.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/errors.rs deleted file mode 100644 index 6ba05d82bd..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/errors.rs +++ /dev/null @@ -1,59 +0,0 @@ -//! A rejection is the JSON encoding of this struct: the C++ promise only -//! carries a string. - -#[derive(Clone, Debug)] -pub struct DesktopError { - pub code: &'static str, - pub message: String, -} - -pub mod codes { - pub const UNSUPPORTED: &str = "unsupported"; - pub const INVALID_ARGUMENT: &str = "invalid_argument"; - pub const NOT_FOUND: &str = "not_found"; - pub const RELOADED: &str = "reloaded"; - pub const FAILED: &str = "failed"; -} - -impl DesktopError { - pub fn new(code: &'static str, message: impl Into) -> Self { - Self { - code, - message: message.into(), - } - } - - pub fn unsupported(message: impl Into) -> Self { - Self::new(codes::UNSUPPORTED, message) - } - - pub fn invalid_argument(message: impl Into) -> Self { - Self::new(codes::INVALID_ARGUMENT, message) - } - - pub fn not_found(message: impl Into) -> Self { - Self::new(codes::NOT_FOUND, message) - } - - pub fn failed(message: impl Into) -> Self { - Self::new(codes::FAILED, message) - } - - pub fn to_json(&self) -> String { - serde_json::json!({"code": self.code, "message": self.message}).to_string() - } - - pub fn to_json_value(&self) -> serde_json::Value { - serde_json::json!({"error": {"code": self.code, "message": self.message}}) - } -} - -impl std::fmt::Display for DesktopError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}: {}", self.code, self.message) - } -} - -impl std::error::Error for DesktopError {} - -pub type DesktopResult = Result; diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/frame_probe.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/frame_probe.rs deleted file mode 100644 index 5207e89b36..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/frame_probe.rs +++ /dev/null @@ -1,646 +0,0 @@ -//! Measures the frame the desktop's own toolkit draws around a window. -//! -//! GTK 4 (with libadwaita when it is installed) is loaded at run time, a window -//! is rendered off-screen the way the desktop's apps are, and the corner radius, -//! the shadow and the border are read from the pixels rather than assumed. The -//! work runs in a short-lived child process (`--rn-gpui-probe-frame`), so the app -//! itself never links or loads GTK. -#![allow(dead_code)] - -use super::window_frame::Frame; - -/// An off-screen rendering of a window: premultiplied BGRA rows. -pub struct Image<'a> { - pub width: usize, - pub height: usize, - pub stride: usize, - pub data: &'a [u8], -} - -impl Image<'_> { - fn pixel(&self, x: usize, y: usize) -> [u8; 4] { - let at = y * self.stride + x * 4; - [ - self.data[at + 2], - self.data[at + 1], - self.data[at], - self.data[at + 3], - ] - } - - fn alpha(&self, x: usize, y: usize) -> u8 { - self.pixel(x, y)[3] - } -} - -/// How far into a row of a rounded corner the first covered pixel sits, for a -/// circle of `radius` whose row `row` lies `row + 0.5` below the top. -fn corner_offset(radius: f32, row: usize) -> f32 { - let rise = row as f32 + 0.5; - if rise >= radius { - return 0.0; - } - radius - (radius * radius - (radius - rise).powi(2)).sqrt() -} - -/// The radius whose corner best explains where each of the first rows starts. -fn fit_radius(offsets: &[f32]) -> f32 { - let mut best = (f32::MAX, 0.0); - let mut radius = 0.0; - while radius <= 40.0 { - let error: f32 = offsets - .iter() - .enumerate() - .map(|(row, offset)| (offset - corner_offset(radius, row)).powi(2)) - .sum(); - if error < best.0 { - best = (error, radius); - } - radius += 0.5; - } - if best.1 < 1.0 { - 0.0 - } else { - best.1 - } -} - -#[derive(Clone, Copy, Debug, Default)] -struct Shadow { - alpha: f32, - blur: f32, - spread: f32, - dy: f32, -} - -/// The standard normal's cumulative distribution (Abramowitz and Stegun 7.1.26). -fn normal_cdf(x: f32) -> f32 { - let t = 1.0 / (1.0 + 0.327_591_1 * (x.abs() / std::f32::consts::SQRT_2)); - let poly = t - * (0.254_829_6 - + t * (-0.284_496_74 + t * (1.421_413_7 + t * (-1.453_152_1 + t * 1.061_405_4)))); - let erf = 1.0 - poly * (-(x * x) / 2.0).exp(); - 0.5 * (1.0 + erf.copysign(x)) -} - -/// The opacity of a blurred shadow `distance` outside the edge of a box whose -/// shadow is grown by `spread` and shifted `shift` toward that edge. -fn shadow_at(distance: f32, alpha: f32, blur: f32, spread: f32, shift: f32) -> f32 { - alpha * (1.0 - normal_cdf((distance - spread - shift) / blur)) -} - -/// The one shadow, as GPUI draws it (opacity, blur as a standard deviation, -/// spread and a downward shift), that best explains how the opacity falls off -/// beside the left edge (no shift) and above and below the window (shifted). -/// Each slice starts one pixel outside its edge. -fn fit_shadow(left: &[f32], top: &[f32], bottom: &[f32]) -> Shadow { - let reach = left.len() as f32; - let mut best = (f32::MAX, Shadow::default()); - let mut blur = 0.5; - while blur <= reach { - let mut spread = -reach / 2.0; - while spread <= reach / 2.0 { - let mut dy = 0.0; - while dy <= reach / 2.0 { - let shapes: Vec<(f32, f32)> = [(left, 0.0), (top, dy), (bottom, -dy)] - .iter() - .flat_map(|(profile, shift)| { - profile.iter().enumerate().map(move |(at, observed)| { - let distance = at as f32 + 0.5; - (*observed, shadow_at(distance, 1.0, blur, spread, *shift)) - }) - }) - .collect(); - let dot: f32 = shapes.iter().map(|(seen, shape)| seen * shape).sum(); - let norm: f32 = shapes.iter().map(|(_, shape)| shape * shape).sum(); - if norm > 1e-6 { - let alpha = (dot / norm).clamp(0.0, 1.0); - let error: f32 = shapes - .iter() - .map(|(seen, shape)| (seen - alpha * shape).powi(2)) - .sum(); - if error < best.0 { - best = ( - error, - Shadow { - alpha, - blur, - spread, - dy, - }, - ); - } - } - dy += 0.5; - } - spread += 0.5; - } - blur += 0.5; - } - best.1 -} - -/// Reads the frame out of a rendering of an empty client-decorated window. -pub fn analyze(image: &Image) -> Option { - if image.width < 16 || image.height < 16 { - return None; - } - let (mid_x, mid_y) = (image.width / 2, image.height / 2); - // The window is either painted solid, or only its shadow is and the window - // is the hole inside it. The centre says which. - let hollow = image.alpha(mid_x, mid_y) <= 2; - let in_body = |alpha: u8| if hollow { alpha <= 2 } else { alpha >= 250 }; - let left = (1..=mid_x) - .find(|&step| !in_body(image.alpha(mid_x - step, mid_y))) - .map(|step| mid_x - step + 1)?; - let top = (1..=mid_y) - .find(|&step| !in_body(image.alpha(mid_x, mid_y - step))) - .map(|step| mid_y - step + 1)?; - let right = (1..image.width - mid_x) - .find(|&step| !in_body(image.alpha(mid_x + step, mid_y))) - .map(|step| image.width - (mid_x + step))?; - let bottom = (1..image.height - mid_y) - .find(|&step| !in_body(image.alpha(mid_x, mid_y + step))) - .map(|step| image.height - (mid_y + step))?; - - // The margin is the canvas the window was drawn into; what matters is how - // far the shadow visibly reaches beyond the edge. - let reach = |from: usize, step: isize, limit: usize| -> usize { - (1..=limit) - .take_while(|&distance| { - let x = (from as isize + step * distance as isize) as usize; - image.alpha(x.min(image.width - 1), mid_y) > 2 - }) - .count() - }; - let extent = reach(left, -1, left).max(reach(image.width - 1 - right, 1, right)); - let _ = (top, bottom); - - let shadow = if extent == 0 { - Shadow::default() - } else { - let beyond = |edge: usize, step: isize, horizontal: bool| -> Vec { - (1..=extent) - .map(|distance| { - let at = (edge as isize + step * distance as isize).max(0) as usize; - let (x, y) = if horizontal { - (at.min(image.width - 1), mid_y) - } else { - (mid_x, at.min(image.height - 1)) - }; - f32::from(image.alpha(x, y)) / 255.0 - }) - .collect() - }; - fit_shadow( - &beyond(left, -1, true), - &beyond(top, -1, false), - &beyond(image.height - 1 - bottom, 1, false), - ) - }; - - let offsets: Vec = (0..12) - .map_while(|row| { - let y = top + row; - (left..left + 48) - .find(|&x| { - let alpha = image.alpha(x, y); - if hollow { - alpha <= 2 - } else { - alpha >= 128 - } - }) - .map(|x| (x - left) as f32) - }) - .collect(); - let radius = if offsets.len() < 4 { - 0.0 - } else { - fit_radius(&offsets) - }; - - let border = if hollow { - 0 - } else { - border_over(image.pixel(left, mid_y), image.pixel(left + 4, mid_y)) - }; - - Some(Frame { - radius, - shadow_extent: extent as f32, - border, - shadow_alpha: shadow.alpha, - shadow_blur: shadow.blur, - shadow_spread: shadow.spread, - shadow_dy: shadow.dy, - }) -} - -/// The black or white line (`0xRRGGBBAA`) that turns `inside` into `edge`, or -/// zero when the edge is no different. -fn border_over(edge: [u8; 4], inside: [u8; 4]) -> u32 { - let level = |pixel: [u8; 4]| { - (u32::from(pixel[0]) + u32::from(pixel[1]) + u32::from(pixel[2])) as f32 / 3.0 - }; - let (edge_level, inside_level) = (level(edge), level(inside)); - let difference = (edge_level - inside_level).abs(); - if difference < 3.0 { - return 0; - } - if edge_level < inside_level { - let alpha = 1.0 - edge_level / inside_level.max(1.0); - (alpha * 255.0).round() as u32 - } else { - let alpha = (edge_level - inside_level) / (255.0 - inside_level).max(1.0); - 0xFFFF_FF00 | (alpha * 255.0).round() as u32 - } -} - -#[cfg(target_os = "linux")] -pub use gtk::run_and_exit; - -#[cfg(target_os = "linux")] -mod gtk { - use std::ffi::{c_char, c_double, c_int, c_void, CString}; - - use super::{analyze, Image}; - - type Widget = *mut c_void; - - #[repr(C)] - struct Rect { - x: f32, - y: f32, - width: f32, - height: f32, - } - - unsafe fn open(name: &str) -> *mut c_void { - let name = CString::new(name).unwrap_or_default(); - libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_GLOBAL) - } - - unsafe fn symbol(library: *mut c_void, name: &str) -> Option { - debug_assert_eq!(std::mem::size_of::(), std::mem::size_of::<*mut c_void>()); - let name = CString::new(name).ok()?; - let address = libc::dlsym(library, name.as_ptr()); - if address.is_null() { - trace(&format!("missing symbol {name:?}")); - return None; - } - Some(std::mem::transmute_copy(&address)) - } - - fn trace(message: &str) { - if std::env::var_os("RN_GPUI_FRAME_PROBE_DEBUG").is_some() { - eprintln!("[frame-probe] {message}"); - } - } - - /// Renders the window node with GTK 4, and libadwaita's stylesheet when asked. - unsafe fn measure_gtk4(use_adwaita: bool) -> Option { - let gtk = open("libgtk-4.so.1"); - if gtk.is_null() { - trace("libgtk-4 not found"); - return None; - } - let init_check: unsafe extern "C" fn() -> c_int = symbol(gtk, "gtk_init_check")?; - if init_check() == 0 { - trace("gtk_init_check failed"); - return None; - } - let adwaita = if use_adwaita { - open("libadwaita-1.so.0") - } else { - std::ptr::null_mut() - }; - if !adwaita.is_null() { - if let Some(init) = symbol::(adwaita, "adw_init") { - init(); - } - } - let window_new: unsafe extern "C" fn() -> Widget = symbol(gtk, "gtk_window_new")?; - let realize: unsafe extern "C" fn(Widget) = symbol(gtk, "gtk_widget_realize")?; - let add_css_class: unsafe extern "C" fn(Widget, *const c_char) = - symbol(gtk, "gtk_widget_add_css_class")?; - let style_context: unsafe extern "C" fn(Widget) -> *mut c_void = - symbol(gtk, "gtk_widget_get_style_context")?; - let snapshot_new: unsafe extern "C" fn() -> *mut c_void = symbol(gtk, "gtk_snapshot_new")?; - let render_background: unsafe extern "C" fn( - *mut c_void, - *mut c_void, - c_double, - c_double, - c_double, - c_double, - ) = symbol(gtk, "gtk_snapshot_render_background")?; - let render_frame: unsafe extern "C" fn( - *mut c_void, - *mut c_void, - c_double, - c_double, - c_double, - c_double, - ) = symbol(gtk, "gtk_snapshot_render_frame")?; - let free_to_node: unsafe extern "C" fn(*mut c_void) -> *mut c_void = - symbol(gtk, "gtk_snapshot_free_to_node")?; - let native_renderer: unsafe extern "C" fn(Widget) -> *mut c_void = - symbol(gtk, "gtk_native_get_renderer")?; - let render_texture: unsafe extern "C" fn( - *mut c_void, - *mut c_void, - *const Rect, - ) -> *mut c_void = symbol(gtk, "gsk_renderer_render_texture")?; - let texture_width: unsafe extern "C" fn(*mut c_void) -> c_int = - symbol(gtk, "gdk_texture_get_width")?; - let texture_height: unsafe extern "C" fn(*mut c_void) -> c_int = - symbol(gtk, "gdk_texture_get_height")?; - let texture_download: unsafe extern "C" fn(*mut c_void, *mut u8, usize) = - symbol(gtk, "gdk_texture_download")?; - - // The window's own CSS node, as a client-decorated toplevel carries it, - // drawn into a canvas with room around it for the shadow. - const MARGIN: f64 = 64.0; - const SIDE: f64 = 240.0; - let window = window_new(); - realize(window); - for class in ["csd", "background"] { - let class = CString::new(class).unwrap_or_default(); - add_css_class(window, class.as_ptr()); - } - let context = style_context(window); - let snapshot = snapshot_new(); - render_background(snapshot, context, MARGIN, MARGIN, SIDE, SIDE); - render_frame(snapshot, context, MARGIN, MARGIN, SIDE, SIDE); - let node = free_to_node(snapshot); - if node.is_null() { - trace("snapshot is empty"); - return None; - } - let renderer = native_renderer(window); - if renderer.is_null() { - trace("no renderer"); - return None; - } - let canvas = (SIDE + 2.0 * MARGIN) as f32; - let viewport = Rect { - x: 0.0, - y: 0.0, - width: canvas, - height: canvas, - }; - let texture = render_texture(renderer, node, &viewport); - if texture.is_null() { - trace("render_texture failed"); - return None; - } - let (w, h) = ( - texture_width(texture) as usize, - texture_height(texture) as usize, - ); - let stride = w * 4; - let mut data = vec![0u8; stride * h]; - texture_download(texture, data.as_mut_ptr(), stride); - analyze(&Image { - width: w, - height: h, - stride, - data: &data, - }) - } - - /// Renders a GTK 3 client-decorated window's `decoration` node with cairo. - unsafe fn measure_gtk3() -> Option { - let gtk = open("libgtk-3.so.0"); - if gtk.is_null() { - trace("libgtk-3 not found"); - return None; - } - let cairo = open("libcairo.so.2"); - if cairo.is_null() { - trace("libcairo not found"); - return None; - } - let init_check: unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int = - symbol(gtk, "gtk_init_check")?; - if init_check(std::ptr::null_mut(), std::ptr::null_mut()) == 0 { - trace("gtk_init_check failed"); - return None; - } - let window_type: unsafe extern "C" fn() -> usize = symbol(gtk, "gtk_window_get_type")?; - let path_new: unsafe extern "C" fn() -> *mut c_void = symbol(gtk, "gtk_widget_path_new")?; - let append_type: unsafe extern "C" fn(*mut c_void, usize) -> c_int = - symbol(gtk, "gtk_widget_path_append_type")?; - let set_object_name: unsafe extern "C" fn(*mut c_void, c_int, *const c_char) = - symbol(gtk, "gtk_widget_path_iter_set_object_name")?; - let add_class: unsafe extern "C" fn(*mut c_void, c_int, *const c_char) = - symbol(gtk, "gtk_widget_path_iter_add_class")?; - let context_new: unsafe extern "C" fn() -> *mut c_void = - symbol(gtk, "gtk_style_context_new")?; - let set_path: unsafe extern "C" fn(*mut c_void, *mut c_void) = - symbol(gtk, "gtk_style_context_set_path")?; - let render_background: unsafe extern "C" fn( - *mut c_void, - *mut c_void, - c_double, - c_double, - c_double, - c_double, - ) = symbol(gtk, "gtk_render_background")?; - let render_frame: unsafe extern "C" fn( - *mut c_void, - *mut c_void, - c_double, - c_double, - c_double, - c_double, - ) = symbol(gtk, "gtk_render_frame")?; - let surface_create: unsafe extern "C" fn(c_int, c_int, c_int) -> *mut c_void = - symbol(cairo, "cairo_image_surface_create")?; - let cairo_create: unsafe extern "C" fn(*mut c_void) -> *mut c_void = - symbol(cairo, "cairo_create")?; - let flush: unsafe extern "C" fn(*mut c_void) = symbol(cairo, "cairo_surface_flush")?; - let data: unsafe extern "C" fn(*mut c_void) -> *const u8 = - symbol(cairo, "cairo_image_surface_get_data")?; - let stride: unsafe extern "C" fn(*mut c_void) -> c_int = - symbol(cairo, "cairo_image_surface_get_stride")?; - - let path = path_new(); - let cstr = |text: &str| CString::new(text).unwrap_or_default(); - let (window_name, decoration_name) = (cstr("window"), cstr("decoration")); - append_type(path, window_type()); - set_object_name(path, -1, window_name.as_ptr()); - for class in ["background", "csd"] { - add_class(path, -1, cstr(class).as_ptr()); - } - append_type(path, window_type()); - set_object_name(path, -1, decoration_name.as_ptr()); - let context = context_new(); - set_path(context, path); - - const MARGIN: f64 = 64.0; - const SIDE: f64 = 240.0; - let canvas = (SIDE + 2.0 * MARGIN) as c_int; - let surface = surface_create(0, canvas, canvas); - let cr = cairo_create(surface); - render_background(context, cr, MARGIN, MARGIN, SIDE, SIDE); - render_frame(context, cr, MARGIN, MARGIN, SIDE, SIDE); - flush(surface); - let (width, height) = (canvas as usize, canvas as usize); - let stride = stride(surface) as usize; - let pixels = std::slice::from_raw_parts(data(surface), stride * height); - let covered = pixels.chunks_exact(4).filter(|pixel| pixel[3] > 0).count(); - trace(&format!( - "gtk3 canvas {width}x{height}, {covered} covered pixels" - )); - analyze(&Image { - width, - height, - stride, - data: pixels, - }) - } - - /// Tries the toolkits in turn: GTK 4 with libadwaita, GTK 4 alone, GTK 3. The - /// first that renders gives the answer. - unsafe fn measure(toolkit: &str) -> Option { - match toolkit { - "gtk4" => measure_gtk4(true), - "gtk4-plain" => measure_gtk4(false), - "gtk3" => measure_gtk3(), - _ => measure_gtk4(true).or_else(|| measure_gtk3()), - } - } - - /// Prints the measured frame as JSON (or `null`) and ends the process. - pub fn run_and_exit() -> ! { - // SAFETY: plain C calls into GTK, made once from a process that exists - // only to make them. - let toolkit = std::env::args().nth(2).unwrap_or_default(); - let frame = unsafe { measure(&toolkit) }; - let json = match frame { - Some(frame) => serde_json::json!({ - "radius": frame.radius, - "shadow_extent": frame.shadow_extent, - "border": frame.border, - "shadow_alpha": frame.shadow_alpha, - "shadow_blur": frame.shadow_blur, - "shadow_spread": frame.shadow_spread, - "shadow_dy": frame.shadow_dy, - }), - None => serde_json::Value::Null, - }; - println!("{json}"); - std::process::exit(0); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A window of `size` squared with a `margin` ring holding a gaussian-ish - /// shadow, `radius` corners and a darker one-pixel border. - fn render(size: usize, margin: usize, radius: f32, border: bool) -> Vec { - let mut data = vec![0u8; size * size * 4]; - for y in 0..size { - for x in 0..size { - let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5); - let (lo, hi) = (margin as f32, (size - margin) as f32); - let cx = fx.clamp(lo + radius, hi - radius); - let cy = fy.clamp(lo + radius, hi - radius); - let distance = ((fx - cx).powi(2) + (fy - cy).powi(2)).sqrt(); - let (a, level) = if distance <= radius && fx > lo && fx < hi && fy > lo && fy < hi { - let edge = (fx - lo).min(hi - fx).min(fy - lo).min(hi - fy); - let on_border = border && edge < 1.0; - (255u8, if on_border { 200u8 } else { 250u8 }) - } else { - let outside = distance - radius; - let falloff = (0.35 * (1.0 - outside / margin as f32)).clamp(0.0, 0.35); - ((falloff * 255.0) as u8, 0) - }; - let at = (y * size + x) * 4; - data[at..at + 4].copy_from_slice(&[level, level, level, a]); - } - } - data - } - - #[test] - fn a_rendered_frame_gives_back_its_radius_and_margin() { - let data = render(120, 14, 12.0, true); - let frame = analyze(&Image { - width: 120, - height: 120, - stride: 480, - data: &data, - }) - .unwrap(); - assert!( - (frame.shadow_extent - 14.0).abs() <= 2.0, - "extent {}", - frame.shadow_extent - ); - assert!( - (frame.radius - 12.0).abs() <= 1.5, - "radius {}", - frame.radius - ); - assert!(frame.shadow_alpha > 0.1 && frame.shadow_alpha <= 1.0); - assert!(frame.border & 0xFF > 0, "a darker edge reads as a border"); - } - - #[test] - fn a_window_drawn_as_a_hole_in_its_shadow_measures_the_same() { - let mut data = render(120, 14, 12.0, false); - for pixel in data.chunks_exact_mut(4) { - if pixel[3] == 255 { - pixel.copy_from_slice(&[0, 0, 0, 0]); - } - } - let frame = analyze(&Image { - width: 120, - height: 120, - stride: 480, - data: &data, - }) - .unwrap(); - assert!((frame.shadow_extent - 14.0).abs() <= 2.0); - assert!( - (frame.radius - 12.0).abs() <= 2.0, - "radius {}", - frame.radius - ); - assert_eq!(frame.border, 0); - } - - #[test] - fn a_blurred_offset_shadow_is_recovered_from_its_profile() { - let (alpha, blur, spread, dy) = (0.5_f32, 4.0_f32, 1.0_f32, 3.0_f32); - let profile = |shift: f32| -> Vec { - (0..20) - .map(|at| shadow_at(at as f32 + 0.5, alpha, blur, spread, shift)) - .collect() - }; - let fit = fit_shadow(&profile(0.0), &profile(dy), &profile(-dy)); - assert!((fit.alpha - alpha).abs() < 0.05, "{fit:?}"); - assert!((fit.blur - blur).abs() <= 1.0, "{fit:?}"); - assert!((fit.spread - spread).abs() <= 1.0, "{fit:?}"); - assert!((fit.dy - dy).abs() <= 1.0, "{fit:?}"); - } - - #[test] - fn a_square_window_has_no_radius() { - let data = render(100, 10, 0.0, false); - let frame = analyze(&Image { - width: 100, - height: 100, - stride: 400, - data: &data, - }) - .unwrap(); - assert_eq!(frame.radius, 0.0); - assert_eq!(frame.border, 0); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/global_shortcut.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/global_shortcut.rs deleted file mode 100644 index e4612a2f32..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/global_shortcut.rs +++ /dev/null @@ -1,427 +0,0 @@ -//! Shortcuts that fire while no window of the app has focus. -//! -//! They are registered with the operating system instead of GPUI's keymap, but -//! they are the same shortcuts: the same ids, the same key syntax, and a press -//! goes out as the `gpuiDesktop:shortcut` event, so the handlers and user -//! remapping of the registry apply unchanged. - -use std::collections::HashMap; -use std::sync::OnceLock; - -use global_hotkey::hotkey::{Code, HotKey, Modifiers}; -use global_hotkey::{GlobalHotKeyEvent, GlobalHotKeyManager, HotKeyState}; -use gpui::App; - -use crate::desktop::keymap::Shortcut; - -/// A shortcut the system would not register: another app owns the keys, or the -/// platform cannot do global shortcuts. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Failure { - pub id: String, - pub reason: String, -} - -struct Registered { - keys: String, - hotkey: HotKey, -} - -#[derive(Default)] -struct State { - manager: Option, - by_id: HashMap, - by_hotkey: HashMap, -} - -#[derive(Default)] -struct GlobalState(State); - -impl gpui::Global for GlobalState {} - -/// Where a press is sent from the thread the system reports it on. -pub static PRESS_HANDLER: OnceLock> = OnceLock::new(); - -/// Makes the registered shortcuts the given ones, and says which could not be -/// registered. Must run on the main thread: macOS and Windows tie a hotkey to -/// the thread that runs the event loop. -pub fn install(cx: &mut App, shortcuts: &[Shortcut]) -> Vec { - let wanted: Vec<&Shortcut> = shortcuts - .iter() - .filter(|shortcut| shortcut.enabled && shortcut.global) - .collect(); - // Wayland has no key grabs for a client: the desktop portal binds them. - #[cfg(target_os = "linux")] - if crate::desktop::capabilities::is_wayland() { - return install_with_portal(cx, &wanted); - } - if wanted.is_empty() && cx.try_global::().is_none() { - return Vec::new(); - } - if cx.try_global::().is_none() { - cx.set_global(GlobalState::default()); - GlobalHotKeyEvent::set_event_handler(Some(|event: GlobalHotKeyEvent| { - if event.state() == HotKeyState::Pressed { - if let Some(handler) = PRESS_HANDLER.get() { - handler(event.id()); - } - } - })); - } - let state = &mut cx.global_mut::().0; - let mut failures = Vec::new(); - - let stale: Vec = state - .by_id - .iter() - .filter(|(id, registered)| { - !wanted - .iter() - .any(|shortcut| &shortcut.id == *id && shortcut.keys == registered.keys) - }) - .map(|(id, _)| id.clone()) - .collect(); - for id in stale { - if let Some(registered) = state.by_id.remove(&id) { - state.by_hotkey.remove(®istered.hotkey.id()); - if let Some(manager) = &state.manager { - let _ = manager.unregister(registered.hotkey); - } - } - } - - for shortcut in wanted { - if state.by_id.contains_key(&shortcut.id) { - continue; - } - let hotkey = match hotkey_for(&shortcut.keys) { - Ok(hotkey) => hotkey, - Err(reason) => { - failures.push(Failure { - id: shortcut.id.clone(), - reason, - }); - continue; - } - }; - if state.manager.is_none() { - match GlobalHotKeyManager::new() { - Ok(manager) => state.manager = Some(manager), - Err(error) => { - failures.push(Failure { - id: shortcut.id.clone(), - reason: error.to_string(), - }); - continue; - } - } - } - let registered = state - .manager - .as_ref() - .map(|manager| manager.register(hotkey)); - match registered { - Some(Ok(())) => { - state.by_hotkey.insert(hotkey.id(), shortcut.id.clone()); - state.by_id.insert( - shortcut.id.clone(), - Registered { - keys: shortcut.keys.clone(), - hotkey, - }, - ); - } - Some(Err(error)) => failures.push(Failure { - id: shortcut.id.clone(), - reason: error.to_string(), - }), - None => {} - } - } - failures -} - -/// The connection to the desktop portal, once a global shortcut needed it. -#[cfg(target_os = "linux")] -#[derive(Default)] -struct PortalGlobal(Option); - -#[cfg(target_os = "linux")] -impl gpui::Global for PortalGlobal {} - -/// Asks the portal for the shortcuts, and returns the ones it can already tell -/// are impossible. A refusal from the user or the desktop arrives later, through -/// `report_failure`. -#[cfg(target_os = "linux")] -fn install_with_portal(cx: &mut App, wanted: &[&Shortcut]) -> Vec { - use crate::desktop::portal_shortcuts::{self, Binding}; - - if wanted.is_empty() && cx.try_global::().is_none() { - return Vec::new(); - } - if cx.try_global::().is_none() { - cx.set_global(PortalGlobal::default()); - } - if cx.global::().0.is_none() { - match portal_shortcuts::start(&crate::desktop::snapshot_app_id()) { - Ok(portal) => cx.global_mut::().0 = Some(portal), - Err(reason) => { - return wanted - .iter() - .map(|shortcut| Failure { - id: shortcut.id.clone(), - reason: reason.clone(), - }) - .collect() - } - } - } - let mut failures = Vec::new(); - let mut bindings = Vec::new(); - for shortcut in wanted { - match portal_trigger(&shortcut.keys) { - Ok(trigger) => bindings.push(Binding { - id: shortcut.id.clone(), - description: shortcut.id.clone(), - trigger, - }), - Err(reason) => failures.push(Failure { - id: shortcut.id.clone(), - reason, - }), - } - } - if let Some(portal) = &cx.global::().0 { - portal.set(bindings); - } - failures -} - -/// Sends a failure the portal reported after the fact to the app. -pub fn report_failure(cx: &mut App, id: &str, reason: &str) { - let Some(store) = crate::store::store_from(cx) else { - return; - }; - let host = store.read(cx).host.clone(); - host.emit_device_event_json( - "gpuiDesktop:shortcutFailure", - &serde_json::json!({ "id": id, "reason": reason }).to_string(), - ); -} - -/// Sends the shortcut with this id, which the portal reported pressed. -pub fn fire_named(cx: &mut App, id: &str) { - crate::desktop::keymap::emit_app_shortcut(cx, id, None); -} - -/// A shortcut's keys in the portal's spelling: modifiers in capitals joined by -/// `+`, then the key's X keysym name, as in `ALT+space` or `CTRL+SHIFT+k`. -pub fn portal_trigger(keys: &str) -> Result { - if keys.split_whitespace().count() > 1 { - return Err("a global shortcut cannot be a chord".to_string()); - } - let keystroke = gpui::Keystroke::parse_with_os(keys, crate::desktop::keymap::host_os()) - .map_err(|error| error.to_string())?; - if keystroke.modifiers.function { - return Err("a global shortcut cannot use the fn key".to_string()); - } - let key = keysym_for(&keystroke.key) - .ok_or_else(|| format!("{:?} cannot be the key of a global shortcut", keystroke.key))?; - let mut parts = Vec::new(); - if keystroke.modifiers.control { - parts.push("CTRL".to_string()); - } - if keystroke.modifiers.alt { - parts.push("ALT".to_string()); - } - if keystroke.modifiers.shift { - parts.push("SHIFT".to_string()); - } - if keystroke.modifiers.platform { - parts.push("LOGO".to_string()); - } - let function_key = matches!(keystroke.key.as_bytes(), [b'f', b'1'..=b'9', ..]); - if parts.is_empty() && !function_key { - return Err("a global shortcut needs a modifier key".to_string()); - } - parts.push(key); - Ok(parts.join("+")) -} - -fn keysym_for(key: &str) -> Option { - let key = key.to_ascii_lowercase(); - if let [letter @ b'a'..=b'z'] | [letter @ b'0'..=b'9'] = key.as_bytes() { - return Some((*letter as char).to_string()); - } - if let Some(number) = key.strip_prefix('f').and_then(|n| n.parse::().ok()) { - return (1..=24).contains(&number).then(|| format!("F{number}")); - } - Some( - match key.as_str() { - "space" => "space", - "enter" => "Return", - "tab" => "Tab", - "escape" => "Escape", - "backspace" => "BackSpace", - "delete" => "Delete", - "left" => "Left", - "right" => "Right", - "up" => "Up", - "down" => "Down", - "home" => "Home", - "end" => "End", - "pageup" => "Page_Up", - "pagedown" => "Page_Down", - "-" => "minus", - "=" => "equal", - "[" => "bracketleft", - "]" => "bracketright", - ";" => "semicolon", - "'" => "apostrophe", - "," => "comma", - "." => "period", - "/" => "slash", - "\\" => "backslash", - "`" => "grave", - _ => return None, - } - .to_string(), - ) -} - -/// Sends the shortcut a system hotkey press belongs to. -pub fn fire(cx: &mut App, hotkey: u32) { - let id = cx - .try_global::() - .and_then(|state| state.0.by_hotkey.get(&hotkey).cloned()); - if let Some(id) = id { - crate::desktop::keymap::emit_app_shortcut(cx, &id, None); - } -} - -/// The system hotkey for GPUI keystroke text such as `alt-space`. -fn hotkey_for(keys: &str) -> Result { - if keys.split_whitespace().count() > 1 { - return Err("a global shortcut cannot be a chord".to_string()); - } - let keystroke = gpui::Keystroke::parse_with_os(keys, crate::desktop::keymap::host_os()) - .map_err(|error| error.to_string())?; - let mut modifiers = Modifiers::empty(); - if keystroke.modifiers.control { - modifiers |= Modifiers::CONTROL; - } - if keystroke.modifiers.alt { - modifiers |= Modifiers::ALT; - } - if keystroke.modifiers.shift { - modifiers |= Modifiers::SHIFT; - } - if keystroke.modifiers.platform { - modifiers |= Modifiers::META; - } - if keystroke.modifiers.function { - return Err("a global shortcut cannot use the fn key".to_string()); - } - let code = code_for(&keystroke.key) - .ok_or_else(|| format!("{:?} cannot be the key of a global shortcut", keystroke.key))?; - let function_key = matches!(keystroke.key.as_bytes(), [b'f', b'1'..=b'9', ..]); - if modifiers.is_empty() && !function_key { - return Err("a global shortcut needs a modifier key".to_string()); - } - Ok(HotKey::new( - (!modifiers.is_empty()).then_some(modifiers), - code, - )) -} - -fn code_for(key: &str) -> Option { - use Code::*; - const LETTERS: [Code; 26] = [ - KeyA, KeyB, KeyC, KeyD, KeyE, KeyF, KeyG, KeyH, KeyI, KeyJ, KeyK, KeyL, KeyM, KeyN, KeyO, - KeyP, KeyQ, KeyR, KeyS, KeyT, KeyU, KeyV, KeyW, KeyX, KeyY, KeyZ, - ]; - const DIGITS: [Code; 10] = [ - Digit0, Digit1, Digit2, Digit3, Digit4, Digit5, Digit6, Digit7, Digit8, Digit9, - ]; - const FUNCTION_KEYS: [Code; 24] = [ - F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, - F21, F22, F23, F24, - ]; - let key = key.to_ascii_lowercase(); - if let [letter @ b'a'..=b'z'] = key.as_bytes() { - return Some(LETTERS[usize::from(letter - b'a')]); - } - if let [digit @ b'0'..=b'9'] = key.as_bytes() { - return Some(DIGITS[usize::from(digit - b'0')]); - } - if let Some(number) = key.strip_prefix('f').and_then(|n| n.parse::().ok()) { - return FUNCTION_KEYS.get(number.checked_sub(1)?).copied(); - } - Some(match key.as_str() { - "space" => Space, - "enter" => Enter, - "tab" => Tab, - "escape" => Escape, - "backspace" => Backspace, - "delete" => Delete, - "left" => ArrowLeft, - "right" => ArrowRight, - "up" => ArrowUp, - "down" => ArrowDown, - "home" => Home, - "end" => End, - "pageup" => PageUp, - "pagedown" => PageDown, - "-" => Minus, - "=" => Equal, - "[" => BracketLeft, - "]" => BracketRight, - ";" => Semicolon, - "'" => Quote, - "," => Comma, - "." => Period, - "/" => Slash, - "\\" => Backslash, - "`" => Backquote, - _ => return None, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_keystroke_becomes_a_system_hotkey() { - let hotkey = hotkey_for("alt-space").unwrap(); - assert_eq!(hotkey, HotKey::new(Some(Modifiers::ALT), Code::Space)); - let hotkey = hotkey_for("ctrl-shift-k").unwrap(); - assert_eq!( - hotkey, - HotKey::new(Some(Modifiers::CONTROL | Modifiers::SHIFT), Code::KeyK) - ); - } - - #[test] - fn a_keystroke_is_spelled_the_way_the_portal_asks() { - assert_eq!(portal_trigger("alt-space").unwrap(), "ALT+space"); - assert_eq!(portal_trigger("ctrl-shift-k").unwrap(), "CTRL+SHIFT+k"); - assert_eq!(portal_trigger("super-f5").unwrap(), "LOGO+F5"); - assert_eq!(portal_trigger("f5").unwrap(), "F5"); - assert_eq!(portal_trigger("alt-pageup").unwrap(), "ALT+Page_Up"); - assert!(portal_trigger("k").unwrap_err().contains("modifier")); - assert!(portal_trigger("ctrl-k ctrl-s") - .unwrap_err() - .contains("chord")); - } - - #[test] - fn what_a_system_cannot_register_is_refused_with_a_reason() { - assert!(hotkey_for("secondary-k secondary-s") - .unwrap_err() - .contains("chord")); - assert!(hotkey_for("k").unwrap_err().contains("modifier")); - assert!(hotkey_for("fn-k").is_err()); - assert!(hotkey_for("f5").is_ok()); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/gpui_menu.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/gpui_menu.rs deleted file mode 100644 index 3caba226c1..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/gpui_menu.rs +++ /dev/null @@ -1,1134 +0,0 @@ -//! Linux has no native menu GPUI can use (`muda` needs a GTK window), so GPUI -//! draws it. `RN_GPUI_CONTEXT_MENU=gpui` / `RN_GPUI_MENU_BAR=gpui` select it -//! on other platforms, for tests. - -use crate::desktop::context_menu::{ContextMenuRequest, Responder}; -use crate::desktop::menu_model::{MenuModel, MenuNode}; -use gpui::prelude::FluentBuilder as _; -use gpui::{ - point, px, size, App, AppContext, Bounds, Context, InteractiveElement, IntoElement, - ParentElement, Render, SharedString, Styled, Window, WindowBounds, WindowKind, WindowOptions, -}; -use std::cell::RefCell; - -pub const MENU_BAR_HEIGHT: f32 = 26.0; - -const ROW_HEIGHT: f32 = 26.0; -const PADDING: f32 = 6.0; -const MIN_WIDTH: f32 = 160.0; -const MAX_WIDTH: f32 = 420.0; - -/// A GPUI popup's elements are not RN nodes, so the test driver drives the -/// open popup through this. -pub struct PendingMenu { - pub window: gpui::AnyWindowHandle, - pub items: Vec, - pub responder: Responder, -} - -pub struct PendingMenuGlobal(pub RefCell>); -impl gpui::Global for PendingMenuGlobal {} - -/// Closes the menu currently tracked in `PendingMenuGlobal`, if any. -/// -/// Only one top-level GPUI menu is meant to be up at a time. Opening a second -/// one used to overwrite the global and orphan the first window: nothing else -/// reaps a popup, so it stayed on screen (and on top) until the process exited, -/// and a repeated right-click left a stack of them. Every opener runs this -/// first, so a new menu replaces the old one instead of joining it. -fn close_open_menu(cx: &mut App) { - let Some(pending) = cx.try_global::() else { - return; - }; - let taken = pending.0.borrow_mut().take(); - if let Some(menu) = taken { - let _ = menu - .window - .update(cx, |_root, window, _cx| window.remove_window()); - } -} - -pub fn should_use_gpui() -> bool { - match std::env::var("RN_GPUI_CONTEXT_MENU").ok().as_deref() { - Some("gpui") => true, - Some("native") => false, - _ => cfg!(target_os = "linux"), - } -} - -pub fn should_use_gpui_menu_bar() -> bool { - match std::env::var("RN_GPUI_MENU_BAR").ok().as_deref() { - Some("gpui") => true, - Some("native") => false, - _ => cfg!(target_os = "linux"), - } -} - -/// The inset the React surface leaves at the top of a window for the menu bar. -/// -/// This is the process-wide answer, for callers with no window in hand. A caller -/// that knows its window must use [`menu_bar_inset_for`], because the bar can be -/// hidden for one window and shown in another — the main window and a popover can -/// disagree, and the surface size has to follow the window it belongs to. -pub fn menu_bar_inset() -> f32 { - if should_use_gpui_menu_bar() { - MENU_BAR_HEIGHT - } else { - 0.0 - } -} - -/// The inset for one window, honouring a runtime hide. -pub fn menu_bar_inset_for(_cx: &gpui::App, window_id: u32) -> f32 { - menu_bar_inset_for_window_id(window_id) -} - -/// The inset for a window id, for callers with no `Context`. -/// -/// `ViewStore::resize_window` is one: it is handed an `AnyWindowHandle` and the -/// surface id, and the thread local holds the answer without needing `cx`. -pub fn menu_bar_inset_for_window_id(window_id: u32) -> f32 { - // A bar placed in a slot of the React tree takes its space from the tree, - // so nothing is reserved at the top of the window. - if !should_use_gpui_menu_bar() - || !has_menu_bar(window_id) - || menu_bar_hidden(window_id) - || menu_bar_slot(window_id).is_some() - { - 0.0 - } else { - MENU_BAR_HEIGHT - } -} - -/// Whether this window draws its menu bar. -/// -/// macOS answers `false` always: its menu bar is the system's, and there is -/// nothing in the window to hide. The capability `menuBarInWindow` reports the -/// same thing to JS, so an app can hide its own UI on the one platform where -/// hiding does nothing. -pub fn menu_bar_in_window(window_id: u32) -> bool { - should_use_gpui_menu_bar() && !menu_bar_hidden(window_id) -} - -pub fn menu_bar_hidden(window_id: u32) -> bool { - HIDDEN_MENU_BARS.with(|hidden| hidden.borrow().contains(&window_id)) -} - -/// Where a window's React tree reserved room for the menu bar, in window -/// coordinates, and the colours that suit what it sits on. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct MenuBarSlot { - pub x: f32, - pub y: f32, - pub width: f32, - pub height: f32, - /// `0xAARRGGBB`, as `processColor` gives it. - pub foreground: u32, - pub hover: u32, -} - -pub fn set_menu_bar_slot(window_id: u32, slot: Option) { - MENU_BAR_SLOTS.with(|slots| { - let mut slots = slots.borrow_mut(); - match slot { - Some(slot) => { - slots.insert(window_id, slot); - } - None => { - slots.remove(&window_id); - } - } - }); -} - -pub fn menu_bar_slot(window_id: u32) -> Option { - MENU_BAR_SLOTS.with(|slots| slots.borrow().get(&window_id).copied()) -} - -fn argb(color: u32) -> gpui::Rgba { - gpui::rgba(((color & 0x00ff_ffff) << 8) | (color >> 24)) -} - -thread_local! { - static MENU_BAR_SLOTS: std::cell::RefCell> = - std::cell::RefCell::new(std::collections::HashMap::new()); - - /// Windows whose bar was hidden, mirrored here so the answer is available - /// without a `Context` — `menu_bar_inset` is called from window plumbing that - /// has one, but the JS getter and the tests do not. - static HIDDEN_MENU_BARS: std::cell::RefCell> = - std::cell::RefCell::new(std::collections::HashSet::new()); - - /// Windows that carry a menu bar: the main window from the start, and any - /// other once its bar is prepared. A window without one reserves no room. - static BAR_WINDOWS: std::cell::RefCell> = - std::cell::RefCell::new(std::collections::HashSet::from([ - crate::desktop::windows::MAIN_WINDOW_KEY, - ])); -} - -fn has_menu_bar(window_id: u32) -> bool { - BAR_WINDOWS.with(|windows| windows.borrow().contains(&window_id)) -} - -/// Re-applies the surface size after the inset changed. -/// -/// The React surface is laid out to the window's size minus the inset, and the -/// window will not send a resize of its own just because the bar went away, so -/// the store has to be told the new answer. -pub fn resize_surfaces_for_menu_bar(cx: &mut gpui::App, window_id: u32) { - let Some(store) = cx.try_global::() else { - return; - }; - let store = store.0.clone(); - let handle = { - let windows = cx.global::(); - windows.0.get(window_id).map(|entry| entry.handle) - }; - let Some(handle) = handle else { - return; - }; - let size = handle - .update(cx, |_, window, _| window.viewport_size()) - .ok(); - let Some(size) = size else { - return; - }; - let scale = handle - .update(cx, |_, window, _| window.scale_factor()) - .unwrap_or(1.0); - store.update(cx, |store, cx| { - store.resize_window( - handle, - f32::from(size.width), - f32::from(size.height), - scale, - cx, - ); - store.notify_window_roots(handle, cx); - }); -} - -/// Shows or hides the menu bar of one window. -/// -/// The set lives in a thread local rather than in `AppMenuGlobal` because a global -/// is handed out by shared reference and the attached `muda::Menu` on Windows -/// makes the state impossible to clone and replace. One set, one source of truth: -/// the inset and the JS getter both read it. -pub fn set_menu_bar_visible(window_id: u32, visible: bool) { - HIDDEN_MENU_BARS.with(|hidden| { - let mut hidden = hidden.borrow_mut(); - if visible { - hidden.remove(&window_id); - } else { - hidden.insert(window_id); - } - }); -} - -pub struct MenuBar { - window_id: u32, -} - -impl MenuBar { - pub fn new(window_id: u32) -> Self { - Self { window_id } - } -} - -/// Creates the menu bar and its activation observer, without touching the root. -/// -/// Called from inside a `window.update` whose closure has already leased the -/// surface root, so this must not update the root: that panics with "cannot -/// update SurfaceRootView while it is already being updated". The observer is -/// registered on the menu bar entity (a fresh entity, safe to update here) and -/// its callback only dismisses the popup. -/// -/// The observer closes a menu left up when the user moves on: clicking anywhere -/// outside the app, another window taking focus, or the app being backgrounded. -/// The popup is an override-redirect window on X11, so it never receives that -/// click itself and there is no global grab to catch it; window activation is -/// the signal that is actually delivered (an X11 `FocusOut` calls -/// `set_active(false)`, which runs these observers). -pub fn prepare(window: &mut gpui::Window, cx: &mut App, window_id: u32) -> Option { - if !should_use_gpui_menu_bar() { - return None; - } - BAR_WINDOWS.with(|windows| windows.borrow_mut().insert(window_id)); - let menu_bar = cx.new(|_| MenuBar::new(window_id)); - let subscription = menu_bar.update(cx, |_menu_bar, cx| { - cx.observe_window_activation(window, |_menu_bar, window, cx| { - if window.is_window_active() { - return; - } - // On Windows the popup (and any submenu) is its own top-level - // window, so opening it can deactivate this one. Only dismiss once - // activation has left the app entirely. The popup's activation can - // arrive after this window's deactivation, so check a moment later. - cx.spawn(async move |_menu_bar, cx| { - cx.background_executor() - .timer(std::time::Duration::from_millis(100)) - .await; - let _ = cx.update(|cx| { - if cx.active_window().is_none() { - let _ = MenuPopup::dismiss(cx); - } - }); - }) - .detach(); - }) - }); - Some(PreparedMenuBar { - menu_bar, - subscription, - }) -} - -/// The menu bar `prepare` built, handed to `attach` once the root is free. -pub struct PreparedMenuBar { - pub menu_bar: gpui::Entity, - pub subscription: gpui::Subscription, -} - -pub fn attach( - cx: &mut App, - root: &gpui::Entity, - prepared: PreparedMenuBar, -) { - root.update(cx, |root, cx| { - root.menu_bar = Some(prepared.menu_bar); - root.menu_bar_activation_subscription = Some(prepared.subscription); - cx.notify(); - }); -} - -pub fn menu_bar_entries(cx: &App) -> Vec<(String, Vec)> { - use crate::desktop::app_menu; - use crate::desktop::menu_model::MenuRole; - - let model = app_menu::current_model(cx); - let app_name = app_menu::app_name(cx); - let dev_menu = crate::desktop::dev_menu::is_installed(cx); - let mut titles: Vec<(String, Vec)> = Vec::new(); - for node in &model.items { - match node { - MenuNode::StandardMenu(role) => { - let label = match role { - MenuRole::AppMenu => app_name.clone(), - other => other.default_label().to_string(), - }; - titles.push(( - label, - app_menu::standard_menu_nodes(*role, &app_name, dev_menu), - )); - } - MenuNode::Submenu(submenu) => { - titles.push((submenu.label.clone(), submenu.items.clone())); - } - _ => {} - } - } - titles -} - -fn menu_bar_responder() -> Responder { - Responder::callback(Box::new(|selection| { - if let Some(id) = selection { - if let Some(handler) = rn_gpui_sys::MENU_BAR_PERFORM_HANDLER.get() { - handler(id); - } - } - })) -} - -/// Opens a top-level menu and makes it the one `PendingMenuGlobal` tracks. -/// -/// The single place a root menu is opened: it first closes whatever menu is -/// already up, so a second open replaces the first instead of leaving its window -/// on screen, then records the new window so it can be closed or dismissed -/// later. A submenu (`depth > 0`) is opened with `open_menu_window` directly; it -/// belongs to the menu already up and must not close it. -fn open_tracked_menu( - cx: &mut App, - parent: gpui::AnyWindowHandle, - anchor: (f32, f32), - items: Vec, - responder: Responder, -) -> Result { - close_open_menu(cx); - let window = open_menu_window(cx, parent, anchor, items.clone(), responder.clone(), 0)?; - cx.set_global(PendingMenuGlobal(RefCell::new(Some(PendingMenu { - window, - items, - responder, - })))); - Ok(window) -} - -pub fn open_menu_bar_menu(cx: &mut App, title: &str) -> bool { - let entries = menu_bar_entries(cx); - let Some((_, items)) = entries.into_iter().find(|(label, _)| label == title) else { - return false; - }; - let (window, _) = match crate::desktop::context_menu::target_window(cx) { - Ok(target) => target, - Err(error) => { - log::error!("[gpui-menu] {error}"); - return false; - } - }; - match open_tracked_menu( - cx, - window, - (0.0, MENU_BAR_HEIGHT), - items, - menu_bar_responder(), - ) { - Ok(_) => true, - Err(error) => { - log::error!("[gpui-menu] {error}"); - false - } - } -} - -impl Render for MenuBar { - fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let titles = menu_bar_entries(cx); - let slot = menu_bar_slot(self.window_id); - let mut rows: Vec = Vec::new(); - for (label, items) in titles { - let id = label.clone(); - rows.push( - gpui::div() - .id(SharedString::from(format!("menu-bar-{id}"))) - .px_2() - .h(px(MENU_BAR_HEIGHT)) - .flex() - .items_center() - .text_size(px(13.0)) - .cursor_pointer() - .hover(|style| match slot { - Some(slot) => style.bg(argb(slot.hover)), - None => style.bg(gpui::rgba(0x00000014)), - }) - .on_mouse_down( - gpui::MouseButton::Left, - cx.listener(move |this, event: &gpui::MouseDownEvent, window, cx| { - // The bar can sit over a title bar, whose drag region - // would otherwise take this press and move the window. - cx.stop_propagation(); - let parent: gpui::AnyWindowHandle = window.window_handle(); - let responder = menu_bar_responder(); - let anchor = (f32::from(event.position.x), f32::from(event.position.y)); - let menu_items = items.clone(); - let _ = this; - // Deferred, not opened here: this handler runs inside the - // menu-bar window's own update, and the popup's fallback - // reads the parent's bounds with `parent.update(...)`. A - // re-entrant update of the window already on the stack is - // refused and reported as `WindowRemoved` ("window not - // found"), so the menu never opened. Deferring runs after - // the effect cycle, when the window is off the stack. - cx.defer(move |cx| { - if let Err(error) = - open_tracked_menu(cx, parent, anchor, menu_items, responder) - { - log::error!("[gpui-menu] {error}"); - } - }); - }), - ) - .child(label) - .into_any_element(), - ); - } - - match slot { - Some(slot) => gpui::div() - .id(SharedString::from("gpui-menu-bar")) - .size_full() - .flex() - .flex_row() - .items_center() - .text_color(argb(slot.foreground)) - .children(rows), - None => gpui::div() - .id(SharedString::from("gpui-menu-bar")) - .w_full() - .h(px(MENU_BAR_HEIGHT)) - .flex() - .flex_row() - .items_center() - .gap_0p5() - .px_1() - .bg(gpui::rgba(0xf4f5f7ff)) - .border_b_1() - .border_color(gpui::rgba(0x00000022)) - .text_color(gpui::rgb(0x18212f)) - .child( - gpui::div() - .text_size(px(11.0)) - .text_color(gpui::rgba(0x00000055)) - .px_1() - .child("‹window›"), - ) - .children(rows), - } - } -} - -/// An accelerator as a menu shows it: `secondary-shift-z` is `Ctrl+Shift+Z` on -/// the platforms that draw this menu. -fn accelerator_label(accelerator: &str) -> String { - accelerator - .split('-') - .map(|part| match part { - "secondary" | "control" | "ctrl" => "Ctrl".to_owned(), - "shift" => "Shift".to_owned(), - "alt" => "Alt".to_owned(), - "platform" | "cmd" | "super" => "Super".to_owned(), - key if key.chars().count() == 1 => key.to_uppercase(), - key => { - let mut chars = key.chars(); - chars - .next() - .map(|first| first.to_uppercase().collect::() + chars.as_str()) - .unwrap_or_default() - } - }) - .collect::>() - .join("+") -} - -pub fn present( - cx: &mut App, - request: ContextMenuRequest, - responder: Responder, -) -> Result<(), String> { - open_tracked_menu( - cx, - request.window, - (request.x, request.y), - request.model.items, - responder, - ) - .map(|_| ()) -} - -/// Open one dropdown. -/// -/// `AnchoredPopup` is the right window kind — the platform places it next to the -/// anchor and keeps it on screen — but macOS rejects it ("native popups are not -/// implemented on macOS yet"), so the fallback is a floating window placed at -/// the anchor's screen position. Linux (X11 and Wayland) and Windows take the -/// anchored path, which is what the plan asks for there. -fn open_menu_window( - cx: &mut App, - parent: gpui::AnyWindowHandle, - anchor: (f32, f32), - items: Vec, - responder: Responder, - depth: usize, -) -> Result { - let (width, height) = popup_size(&MenuModel { - items: items.clone(), - }); - let popup_options = gpui::popup::PopupOptions { - parent, - anchor_rect: Bounds::new(point(px(anchor.0), px(anchor.1)), size(px(1.0), px(1.0))), - anchor: if depth == 0 { - gpui::popup::PopupAnchor::BottomLeft - } else { - gpui::popup::PopupAnchor::TopRight - }, - gravity: gpui::popup::PopupGravity::BottomRight, - constraint_adjustment: gpui::popup::PopupConstraintAdjustment::SLIDE_X - | gpui::popup::PopupConstraintAdjustment::SLIDE_Y - | gpui::popup::PopupConstraintAdjustment::FLIP_X - | gpui::popup::PopupConstraintAdjustment::FLIP_Y, - offset: point(px(0.0), px(0.0)), - // Only the outermost menu grabs input; a submenu is dismissed with its - // parent. - grab: depth == 0, - }; - let anchored_items = items.clone(); - let anchored_responder = responder.clone(); - let anchored = cx.open_window( - WindowOptions { - window_bounds: Some(WindowBounds::Windowed(Bounds::new( - point(px(0.0), px(0.0)), - size(px(width), px(height)), - ))), - kind: WindowKind::AnchoredPopup(popup_options), - is_resizable: false, - ..Default::default() - }, - move |_window, cx| cx.new(|_| MenuPopup::new(anchored_items, anchored_responder, depth)), - ); - if let Ok(handle) = anchored { - let window: gpui::AnyWindowHandle = handle.into(); - log::info!("[gpui-menu] anchored popup {window:?} ({width}x{height})"); - return Ok(window); - } - - let origin = parent - .update(cx, |_root: gpui::AnyView, window, _cx| { - let bounds = window.bounds(); - ( - f32::from(bounds.origin.x) + anchor.0, - f32::from(bounds.origin.y) + anchor.1, - ) - }) - .map_err(|error| format!("the menu's window is gone: {error}"))?; - let floating = cx - .open_window( - WindowOptions { - window_bounds: Some(WindowBounds::Windowed(Bounds::new( - point(px(origin.0), px(origin.1)), - size(px(width), px(height)), - ))), - kind: WindowKind::PopUp, - is_resizable: false, - ..Default::default() - }, - move |_window, cx| cx.new(|_| MenuPopup::new(items, responder, depth)), - ) - .map_err(|error| format!("could not open the menu popup: {error}"))?; - let window: gpui::AnyWindowHandle = floating.into(); - log::info!("[gpui-menu] floating popup {window:?} at {origin:?}"); - Ok(window) -} - -fn popup_size(model: &MenuModel) -> (f32, f32) { - let mut rows = 0usize; - let mut widest = 0usize; - fn walk(items: &[MenuNode], rows: &mut usize, widest: &mut usize) { - for node in items { - *rows += 1; - match node { - MenuNode::Item(item) => { - let mut width = item.label.chars().count(); - if let Some(accelerator) = &item.accelerator { - width += accelerator_label(accelerator).chars().count() + 4; - } - *widest = (*widest).max(width); - } - MenuNode::Submenu(submenu) => { - *widest = (*widest).max(submenu.label.chars().count() + 2); - } - _ => {} - } - } - } - walk(&model.items, &mut rows, &mut widest); - let width = (widest as f32 * 8.0 + PADDING * 2.0 + 28.0).clamp(MIN_WIDTH, MAX_WIDTH); - let height = (rows as f32 * ROW_HEIGHT + PADDING * 2.0).max(ROW_HEIGHT); - (width, height) -} - -pub struct MenuPopup { - items: Vec, - responder: Responder, - depth: usize, - /// Set when this popup resolved the request, so a parent popup does not - /// resolve it a second time. - resolved: bool, -} - -impl MenuPopup { - fn new(items: Vec, responder: Responder, depth: usize) -> Self { - Self { - items, - responder, - depth, - resolved: false, - } - } - - fn close(window: &mut Window) { - window.remove_window(); - } - - fn choose(&mut self, id: &str, window: &mut Window, cx: &mut App) { - if self.resolved { - return; - } - self.resolved = true; - self.responder.resolve(Some(id)); - self.forget_if_tracked(cx); - Self::close(window); - } - - /// Forgets the tracked root menu if this popup *is* it. - /// - /// Called from a root popup as it resolves so `PendingMenuGlobal` does not - /// keep a removed window: a later `close_open_menu` would then try to update - /// a window that is already gone, and `pending()` would report a menu that - /// is no longer on screen. A submenu (`depth > 0`) is not the tracked window - /// and leaves the root alone. - fn forget_if_tracked(&self, cx: &mut App) { - if self.depth != 0 { - return; - } - if let Some(pending) = cx.try_global::() { - *pending.0.borrow_mut() = None; - } - } - - pub fn pending(cx: &App) -> Option<(gpui::AnyWindowHandle, Vec)> { - cx.try_global::().and_then(|pending| { - pending - .0 - .borrow() - .as_ref() - .map(|menu| (menu.window, menu.items.clone())) - }) - } - - pub fn select(cx: &mut App, id: &str) -> bool { - let Some(pending) = cx.try_global::() else { - return false; - }; - let taken = pending.0.borrow_mut().take(); - let Some(menu) = taken else { - return false; - }; - menu.responder.resolve(Some(id)); - let _ = menu - .window - .update(cx, |_root, window, _cx| window.remove_window()); - true - } - - pub fn dismiss(cx: &mut App) -> bool { - let Some(pending) = cx.try_global::() else { - return false; - }; - let taken = pending.0.borrow_mut().take(); - let Some(menu) = taken else { - return false; - }; - menu.responder.resolve(None); - let _ = menu - .window - .update(cx, |_root, window, _cx| window.remove_window()); - true - } - - fn open_submenu( - &self, - items: Vec, - x: f32, - y: f32, - window: &mut Window, - cx: &mut Context, - ) { - let parent: gpui::AnyWindowHandle = window.window_handle(); - let responder = self.responder.clone(); - let depth = self.depth + 1; - // Deferred for the same reason as the menu bar's handler: this runs - // inside the popup window's update, and the submenu's fallback reads the - // parent's bounds with a re-entrant `parent.update(...)`. - cx.defer(move |cx| { - if let Err(error) = open_menu_window(cx, parent, (x, y), items, responder, depth) { - log::error!("[gpui-menu] {error}"); - } - }); - } -} - -impl Render for MenuPopup { - fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { - let mut rows: Vec = Vec::new(); - // One icon gives every row the same leading column, so the labels stay - // aligned. - let icon_column = self.items.iter().any(|node| match node { - MenuNode::Item(item) => item.icon.is_some(), - MenuNode::Submenu(submenu) => submenu.icon.is_some(), - _ => false, - }); - for (index, node) in self.items.clone().into_iter().enumerate() { - match node { - MenuNode::Separator => { - rows.push( - gpui::div() - .h(px(1.0)) - .mx_2() - .my_1() - .bg(gpui::rgba(0x00000022)) - .into_any_element(), - ); - } - MenuNode::StandardMenu(_) => {} - MenuNode::Item(item) => { - let id = item.id.clone(); - let enabled = item.enabled; - // A stable id is what gives the row a hitbox: without it the - // `hover` style has no state to key on and only ever applied - // to the first row the pointer entered. - let mut row = gpui::div() - .id(SharedString::from(format!("menu-item-{id}"))) - .flex() - .flex_row() - .items_center() - .justify_between() - .gap_4() - .px_2() - .h(px(ROW_HEIGHT)) - .text_size(px(13.0)) - .child( - gpui::div() - .flex() - .flex_row() - .items_center() - .gap_1() - .child(leading(item.checked, item.icon.as_deref(), icon_column)) - .child(item.label.clone()), - ) - .child( - gpui::div().text_color(gpui::rgba(0x00000088)).child( - item.accelerator - .as_deref() - .map(accelerator_label) - .unwrap_or_default(), - ), - ); - if !enabled { - row = row.text_color(gpui::rgba(0x00000066)); - } else { - row = row - .cursor_pointer() - .hover(|style| style.bg(gpui::rgba(0x00000011))) - .on_mouse_down( - gpui::MouseButton::Left, - cx.listener(move |this, _event, window, cx| { - this.choose(&id, window, cx); - }), - ); - } - let _ = index; - rows.push(row.into_any_element()); - } - MenuNode::Submenu(submenu) => { - let items = submenu.items.clone(); - let enabled = submenu.enabled; - // An id for the same reason as a menu item's row: the hover - // style needs a hitbox to track. - let mut row = gpui::div() - .id(SharedString::from(format!( - "menu-submenu-{}", - submenu.label - ))) - .flex() - .flex_row() - .items_center() - .justify_between() - .px_2() - .h(px(ROW_HEIGHT)) - .text_size(px(13.0)) - .child( - gpui::div() - .flex() - .flex_row() - .items_center() - .gap_1() - .when(icon_column, |label| { - label.child(leading(false, submenu.icon.as_deref(), true)) - }) - .child(submenu.label.clone()), - ) - .child("›"); - if enabled { - row = row - .cursor_pointer() - .hover(|style| style.bg(gpui::rgba(0x00000011))) - .on_mouse_down( - gpui::MouseButton::Left, - cx.listener( - move |this, event: &gpui::MouseDownEvent, window, cx| { - this.open_submenu( - items.clone(), - f32::from(event.position.x), - f32::from(event.position.y), - window, - cx, - ); - }, - ), - ); - } - rows.push(row.into_any_element()); - } - } - } - - let responder = self.responder.clone(); - let resolved = self.resolved; - let depth = self.depth; - let _ = window; - - gpui::div() - .flex() - .flex_col() - .py(px(PADDING)) - .bg(gpui::white()) - .border_1() - .border_color(gpui::rgba(0x00000033)) - .rounded(px(6.0)) - .shadow_md() - .text_color(gpui::rgb(0x18212f)) - .on_key_down(move |event, window, cx| { - if event.keystroke.key == "escape" { - if !resolved { - responder.resolve(None); - } - // A root popup is the one `PendingMenuGlobal` tracks; clear - // it so a later open/dismiss does not touch a removed window. - if depth == 0 { - if let Some(pending) = cx.try_global::() { - *pending.0.borrow_mut() = None; - } - } - window.remove_window(); - } - }) - .children(rows) - } -} - -const ICON_SIZE: f32 = 16.0; - -/// The slot before a row's label: its check mark, else its icon. With -/// `icon_column` the slot is icon-wide on every row. -fn leading(checked: bool, icon: Option<&str>, icon_column: bool) -> gpui::AnyElement { - let image = (!checked) - .then(|| icon.and_then(crate::desktop::icon::cached)) - .flatten() - .and_then(|icon| icon.image.clone()); - if !icon_column { - return gpui::div() - .child(if checked { "✓" } else { " " }) - .into_any_element(); - } - let slot = gpui::div() - .flex() - .items_center() - .justify_center() - .size(px(ICON_SIZE)); - match image { - Some(image) => slot - .child(gpui::img(image).size(px(ICON_SIZE))) - .into_any_element(), - None => slot - .child(if checked { "✓" } else { "" }) - .into_any_element(), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::desktop::menu_model; - use serde_json::json; - - /// The mode comes from the process's environment, which the tests run - /// in parallel in. A test that sets it, or reads the answer more than once, - /// holds this so that nothing changes it in between. - static ENVIRONMENT: std::sync::Mutex<()> = std::sync::Mutex::new(()); - - fn environment() -> std::sync::MutexGuard<'static, ()> { - ENVIRONMENT - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - } - - #[test] - fn hiding_one_windows_bar_leaves_the_others_alone() { - // The inset is per window: a hidden bar in one window must not shrink - // another window's surface, which is why this is a set of ids rather than - // one flag. - set_menu_bar_visible(7, false); - assert!(menu_bar_hidden(7)); - assert!(!menu_bar_hidden(8)); - set_menu_bar_visible(7, true); - assert!(!menu_bar_hidden(7)); - } - - #[test] - fn the_inset_follows_the_windows_own_visibility() { - let _environment = environment(); - // Both ids are put into a known state first: another test may have - // hidden either of them already. - set_menu_bar_visible(9, true); - set_menu_bar_visible(10, true); - BAR_WINDOWS.with(|windows| windows.borrow_mut().extend([9, 10])); - - set_menu_bar_visible(9, false); - assert_eq!(menu_bar_inset_for_window_id(9), 0.0); - assert_eq!( - menu_bar_inset_for_window_id(10), - if should_use_gpui_menu_bar() { - MENU_BAR_HEIGHT - } else { - 0.0 - }, - "hiding one window's bar must not shrink another window", - ); - set_menu_bar_visible(9, true); - } - - #[test] - fn a_window_without_a_menu_bar_reserves_no_room_for_one() { - let _environment = environment(); - std::env::set_var("RN_GPUI_MENU_BAR", "gpui"); - assert_eq!(menu_bar_inset_for_window_id(13), 0.0); - assert_eq!( - menu_bar_inset_for_window_id(crate::desktop::windows::MAIN_WINDOW_KEY), - MENU_BAR_HEIGHT - ); - std::env::remove_var("RN_GPUI_MENU_BAR"); - } - - #[test] - fn an_accelerator_is_shown_the_way_a_menu_writes_it() { - assert_eq!(accelerator_label("secondary-shift-z"), "Ctrl+Shift+Z"); - assert_eq!(accelerator_label("secondary-c"), "Ctrl+C"); - assert_eq!(accelerator_label("alt-f4"), "Alt+F4"); - assert_eq!(accelerator_label("secondary-enter"), "Ctrl+Enter"); - } - - #[test] - fn a_slot_takes_the_inset_from_its_own_window_only() { - let _environment = environment(); - std::env::set_var("RN_GPUI_MENU_BAR", "gpui"); - set_menu_bar_visible(11, true); - set_menu_bar_visible(12, true); - BAR_WINDOWS.with(|windows| windows.borrow_mut().extend([11, 12])); - set_menu_bar_slot( - 11, - Some(MenuBarSlot { - x: 0.0, - y: 38.0, - width: 300.0, - height: MENU_BAR_HEIGHT, - foreground: 0xffff_ffff, - hover: 0x1fff_ffff, - }), - ); - assert_eq!(menu_bar_inset_for_window_id(11), 0.0); - assert_eq!(menu_bar_inset_for_window_id(12), MENU_BAR_HEIGHT); - set_menu_bar_slot(11, None); - assert_eq!(menu_bar_inset_for_window_id(11), MENU_BAR_HEIGHT); - std::env::remove_var("RN_GPUI_MENU_BAR"); - } - - #[test] - fn popup_size_grows_with_the_items() { - let one = menu_model::parse_menu(&json!([{"id": "a", "label": "A"}])).expect("valid"); - let two = menu_model::parse_menu(&json!([ - {"id": "a", "label": "A"}, - {"type": "separator"}, - {"id": "b", "label": "B"} - ])) - .expect("valid"); - let (_, one_height) = popup_size(&one); - let (_, two_height) = popup_size(&two); - assert!(two_height > one_height); - } - - #[test] - fn popup_width_is_clamped() { - let wide = menu_model::parse_menu(&json!([{ - "id": "a", - "label": "a very long label that would otherwise make the popup enormous indeed" - }])) - .expect("valid"); - let (width, _) = popup_size(&wide); - assert_eq!(width, MAX_WIDTH); - } - - #[test] - fn the_edit_menu_spells_out_its_roles() { - let nodes = crate::desktop::app_menu::standard_menu_nodes( - crate::desktop::menu_model::MenuRole::EditMenu, - "Tester", - false, - ); - let ids: Vec = nodes - .iter() - .filter_map(|node| match node { - MenuNode::Item(item) => Some(item.id.clone()), - _ => None, - }) - .collect(); - assert!(ids.contains(&"role:copy".to_string())); - assert!(ids.contains(&"role:selectAll".to_string())); - let copy = nodes - .iter() - .find_map(|node| match node { - MenuNode::Item(item) if item.id == "role:copy" => Some(item.clone()), - _ => None, - }) - .expect("copy is in the Edit menu"); - assert_eq!(copy.accelerator.as_deref(), Some("secondary-c")); - } - - #[test] - fn the_app_menu_is_labelled_with_the_app_name() { - let nodes = crate::desktop::app_menu::standard_menu_nodes( - crate::desktop::menu_model::MenuRole::AppMenu, - "Tester", - false, - ); - let about = nodes - .iter() - .find_map(|node| match node { - MenuNode::Item(item) - if item.role == Some(crate::desktop::menu_model::MenuRole::About) => - { - Some(item.label.clone()) - } - _ => None, - }) - .expect("the app menu has About"); - assert_eq!(about, "About Tester"); - } - - #[test] - fn the_help_menu_only_grows_a_developer_group_in_a_dev_build() { - use crate::desktop::menu_model::MenuRole; - let without = crate::desktop::app_menu::standard_menu_nodes(MenuRole::HelpMenu, "T", false); - assert!(without.is_empty()); - let with = crate::desktop::app_menu::standard_menu_nodes(MenuRole::HelpMenu, "T", true); - assert_eq!(with.len(), 1); - match &with[0] { - MenuNode::Submenu(submenu) => { - assert_eq!(submenu.label, "Developer"); - assert_eq!(submenu.items.len(), 5); - } - other => panic!("expected a submenu, got {other:?}"), - } - } - - #[test] - fn the_menu_bar_inset_follows_the_mode() { - let _environment = environment(); - std::env::set_var("RN_GPUI_MENU_BAR", "gpui"); - assert_eq!(menu_bar_inset(), MENU_BAR_HEIGHT); - std::env::set_var("RN_GPUI_MENU_BAR", "native"); - assert_eq!(menu_bar_inset(), 0.0); - std::env::remove_var("RN_GPUI_MENU_BAR"); - } - - #[test] - fn the_mode_follows_the_environment() { - let _environment = environment(); - std::env::set_var("RN_GPUI_CONTEXT_MENU", "gpui"); - assert!(should_use_gpui()); - std::env::set_var("RN_GPUI_CONTEXT_MENU", "native"); - assert!(!should_use_gpui()); - std::env::remove_var("RN_GPUI_CONTEXT_MENU"); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/icon.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/icon.rs deleted file mode 100644 index f3f0d7aee7..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/icon.rs +++ /dev/null @@ -1,257 +0,0 @@ -//! Icons for the tray and native menu items, loaded from the URIs an `Image` -//! source resolves to. -//! -//! The native menu builders are synchronous, so an icon is loaded before the -//! menu that shows it is built: each entry point awaits [`preload_menu`] and the -//! builders read [`cached`]. - -use gpui::http_client::HttpClient; -use serde_json::Value; -use std::collections::HashMap; -use std::sync::{Arc, Mutex, OnceLock}; - -/// Far more distinct icons than any app's menus hold; past it the cache starts -/// over instead of growing. -const MAX_CACHED_ICONS: usize = 256; - -pub struct DecodedIcon { - pub rgba: Vec, - pub width: u32, - pub height: u32, - /// The file as loaded, for the menus GPUI draws. - pub image: Option>, -} - -static ICONS: OnceLock>>> = OnceLock::new(); -static HTTP_CLIENT: OnceLock> = OnceLock::new(); - -fn icons() -> &'static Mutex>> { - ICONS.get_or_init(|| Mutex::new(HashMap::new())) -} - -/// Called once the app runs; Metro asset URLs are fetched with its client. -pub fn install(cx: &gpui::App) { - let _ = HTTP_CLIENT.set(cx.http_client()); -} - -pub fn cached(uri: &str) -> Option> { - icons().lock().ok()?.get(uri).cloned() -} - -pub fn decode(bytes: Vec) -> Result { - let format = image::guess_format(&bytes).map_err(|error| error.to_string())?; - let rgba = image::load_from_memory_with_format(&bytes, format) - .map_err(|error| error.to_string())? - .to_rgba8(); - let (width, height) = rgba.dimensions(); - let format = match format { - image::ImageFormat::Png => Some(gpui::ImageFormat::Png), - image::ImageFormat::Jpeg => Some(gpui::ImageFormat::Jpeg), - image::ImageFormat::WebP => Some(gpui::ImageFormat::Webp), - image::ImageFormat::Gif => Some(gpui::ImageFormat::Gif), - image::ImageFormat::Bmp => Some(gpui::ImageFormat::Bmp), - image::ImageFormat::Tiff => Some(gpui::ImageFormat::Tiff), - image::ImageFormat::Ico => Some(gpui::ImageFormat::Ico), - _ => None, - }; - Ok(DecodedIcon { - rgba: rgba.into_raw(), - width, - height, - image: format.map(|format| Arc::new(gpui::Image::from_bytes(format, bytes))), - }) -} - -pub async fn load(uri: &str) -> Result, String> { - if let Some(icon) = cached(uri) { - return Ok(icon); - } - let client = HTTP_CLIENT - .get() - .cloned() - .ok_or_else(|| "the desktop shell is not running".to_owned())?; - let bytes = crate::image_loader::load_bytes(uri, client).await?; - let icon = Arc::new(decode(bytes).map_err(|error| format!("{uri}: {error}"))?); - if let Ok(mut icons) = icons().lock() { - if icons.len() >= MAX_CACHED_ICONS { - icons.clear(); - } - icons.insert(uri.to_owned(), icon.clone()); - } - Ok(icon) -} - -/// The app's own icon, `desktop.json`'s `icon`, as a dev run is told it through -/// `RN_GPUI_APP_ICON`, scaled to the largest size a tray or a title bar shows. -/// -/// Read once. `None` when the variable is unset — a packaged app, which has its -/// icon in its executable and bundle instead — or the file cannot be read. -pub fn app_icon() -> Option> { - static APP_ICON: OnceLock>> = OnceLock::new(); - APP_ICON - .get_or_init(|| { - let path = std::env::var_os("RN_GPUI_APP_ICON")?; - let bytes = match std::fs::read(&path) { - Ok(bytes) => bytes, - Err(error) => { - log::warn!("[desktop] app icon {}: {error}", path.to_string_lossy()); - return None; - } - }; - match decode(bytes) { - Ok(icon) => Some(Arc::new(fit_within(icon, APP_ICON_EDGE))), - Err(error) => { - log::warn!("[desktop] app icon {}: {error}", path.to_string_lossy()); - None - } - } - }) - .clone() -} - -/// A tray icon is drawn at 16 to 32 points: the system scales anything larger -/// down with a plain filter, which leaves a 512-pixel logo ragged. Scaling it -/// here, once, with a good one keeps it crisp. -const APP_ICON_EDGE: u32 = 64; - -/// `icon` scaled so that neither side is longer than `edge`, or unchanged when -/// it already is smaller. The compressed source (`image`) is dropped: menus that -/// draw an icon themselves read the file, and this copy is only ever pixels. -fn fit_within(icon: DecodedIcon, edge: u32) -> DecodedIcon { - if icon.width <= edge && icon.height <= edge { - return icon; - } - let Some(source) = image::RgbaImage::from_raw(icon.width, icon.height, icon.rgba.clone()) - else { - return icon; - }; - let scale = f64::from(edge) / f64::from(icon.width.max(icon.height)); - let width = ((f64::from(icon.width) * scale).round() as u32).max(1); - let height = ((f64::from(icon.height) * scale).round() as u32).max(1); - let resized = image::imageops::resize(&source, width, height, image::imageops::Lanczos3); - DecodedIcon { - rgba: resized.into_raw(), - width, - height, - image: None, - } -} - -/// Loads every icon a menu payload names. A missing or broken icon is logged -/// and the item is shown without one, as an `Image` with a bad source would be. -pub async fn preload_menu(items: &Value) { - let mut uris = Vec::new(); - collect_uris(items, &mut uris); - for uri in uris { - if let Err(error) = load(&uri).await { - log::warn!("[desktop] menu icon {error}"); - } - } -} - -/// For menus that arrive as props rather than through an async call: starts -/// loading the icons that are not cached yet, so the menu has them by the time -/// it opens. -pub fn prefetch_menu(items: &Value) { - static PENDING: OnceLock>> = OnceLock::new(); - let mut uris = Vec::new(); - collect_uris(items, &mut uris); - let Ok(mut pending) = PENDING.get_or_init(Default::default).lock() else { - return; - }; - uris.retain(|uri| cached(uri).is_none() && pending.insert(uri.clone())); - if uris.is_empty() { - return; - } - crate::desktop::post_to_main(Box::new(move |cx| { - cx.background_executor() - .spawn(async move { - for uri in uris { - if let Err(error) = load(&uri).await { - log::warn!("[desktop] menu icon {error}"); - } - if let Some(pending) = PENDING.get() { - if let Ok(mut pending) = pending.lock() { - pending.remove(&uri); - } - } - } - }) - .detach(); - })); -} - -fn collect_uris(value: &Value, out: &mut Vec) { - match value { - Value::Array(items) => items.iter().for_each(|item| collect_uris(item, out)), - Value::Object(fields) => { - if let Some(Value::String(uri)) = fields.get("icon") { - if !out.contains(uri) { - out.push(uri.clone()); - } - } - if let Some(items) = fields.get("items") { - collect_uris(items, out); - } - } - _ => {} - } -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn a_menu_names_each_icon_once() { - let mut uris = Vec::new(); - collect_uris( - &json!([ - {"id": "a", "label": "A", "icon": "file:///a.png"}, - {"type": "submenu", "label": "S", "icon": "file:///s.png", "items": [ - {"id": "b", "label": "B", "icon": "file:///a.png"}, - ]}, - {"type": "separator"}, - ]), - &mut uris, - ); - assert_eq!(uris, ["file:///a.png", "file:///s.png"]); - } - - #[test] - fn decoding_yields_rgba_pixels() { - let mut png = Vec::new(); - image::RgbaImage::from_pixel(3, 2, image::Rgba([1, 2, 3, 4])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); - let icon = decode(png).unwrap(); - assert_eq!((icon.width, icon.height), (3, 2)); - assert_eq!(&icon.rgba[..4], &[1, 2, 3, 4]); - } - - fn solid(width: u32, height: u32) -> DecodedIcon { - DecodedIcon { - rgba: image::RgbaImage::from_pixel(width, height, image::Rgba([10, 20, 30, 255])) - .into_raw(), - width, - height, - image: None, - } - } - - #[test] - fn a_large_app_icon_is_scaled_down_keeping_its_proportions() { - let icon = fit_within(solid(512, 256), 64); - assert_eq!((icon.width, icon.height), (64, 32)); - assert_eq!(icon.rgba.len(), 64 * 32 * 4); - // A flat color stays that color through the filter. - assert_eq!(&icon.rgba[..4], &[10, 20, 30, 255]); - } - - #[test] - fn a_small_app_icon_is_left_alone() { - let icon = fit_within(solid(32, 32), 64); - assert_eq!((icon.width, icon.height), (32, 32)); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/keyboard.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/keyboard.rs deleted file mode 100644 index 5c5ee26912..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/keyboard.rs +++ /dev/null @@ -1,195 +0,0 @@ -//! The on-screen keyboard as `Keyboard` events: Windows reports the area the -//! touch keyboard covers through `InputPane`. Other desktop platforms have no -//! on-screen keyboard and emit nothing. - -use serde_json::json; - -/// A rectangle in DIPs, relative to the window's client area. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Occluded { - pub x: f32, - pub y: f32, - pub width: f32, - pub height: f32, -} - -/// The `DeviceEventEmitter` events React Native's `Keyboard` listens for, with -/// their JSON payloads, in the order they are sent. -pub fn keyboard_events(shown: bool, occluded: Occluded) -> Vec<(&'static str, String)> { - let rect = if shown { - occluded - } else { - Occluded { - height: 0.0, - width: occluded.width, - ..occluded - } - }; - let coordinates = json!({ - "screenX": rect.x, - "screenY": rect.y, - "width": rect.width, - "height": rect.height, - }); - let payload = json!({ - "duration": 0, - "easing": "keyboard", - "startCoordinates": coordinates, - "endCoordinates": coordinates, - "isEventFromThisApp": true, - }) - .to_string(); - let names: [&'static str; 4] = if shown { - [ - "keyboardWillChangeFrame", - "keyboardWillShow", - "keyboardDidChangeFrame", - "keyboardDidShow", - ] - } else { - [ - "keyboardWillChangeFrame", - "keyboardWillHide", - "keyboardDidChangeFrame", - "keyboardDidHide", - ] - }; - names - .into_iter() - .map(|name| (name, payload.clone())) - .collect() -} - -#[cfg(target_os = "windows")] -mod platform { - use super::{keyboard_events, Occluded}; - use crate::host::Host; - use windows::{ - core::{factory, Ref}, - Foundation::TypedEventHandler, - Win32::{Foundation::HWND, System::WinRT::IInputPaneInterop}, - UI::ViewManagement::{InputPane, InputPaneVisibilityEventArgs}, - }; - - thread_local! { - static PANES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; - } - - /// Subscribes to the window's input pane. The pane stays registered for the - /// life of the thread, which is the life of the window's UI. - pub fn watch(hwnd: isize, host: Host) { - if let Err(error) = subscribe(hwnd, host) { - log::warn!("input pane unavailable: {error}"); - } - } - - fn subscribe(hwnd: isize, host: Host) -> windows::core::Result<()> { - let interop = factory::()?; - // SAFETY: `hwnd` is the live handle of a window owned by this thread. - let pane: InputPane = unsafe { interop.GetForWindow(HWND(hwnd as _))? }; - for shown in [true, false] { - let host = host.clone(); - let handler = TypedEventHandler::new( - move |_: Ref<'_, InputPane>, args: Ref<'_, InputPaneVisibilityEventArgs>| { - let Some(args) = args.as_ref() else { - return Ok(()); - }; - let rect = args.OccludedRect()?; - let occluded = Occluded { - x: rect.X, - y: rect.Y, - width: rect.Width, - height: rect.Height, - }; - for (name, payload) in keyboard_events(shown, occluded) { - host.emit_device_event_json(name, &payload); - } - Ok(()) - }, - ); - if shown { - pane.Showing(&handler)?; - } else { - pane.Hiding(&handler)?; - } - } - PANES.with(|panes| panes.borrow_mut().push(pane)); - Ok(()) - } -} - -/// Starts reporting the on-screen keyboard of `window`. -#[cfg(target_os = "windows")] -pub fn watch(window: &gpui::Window, host: crate::host::Host) { - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - let Ok(handle) = HasWindowHandle::window_handle(window) else { - return; - }; - if let RawWindowHandle::Win32(win32) = handle.as_raw() { - platform::watch(win32.hwnd.get(), host); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - const RECT: Occluded = Occluded { - x: 0.0, - y: 420.0, - width: 800.0, - height: 180.0, - }; - - fn names(events: &[(&'static str, String)]) -> Vec<&'static str> { - events.iter().map(|(name, _)| *name).collect() - } - - #[test] - fn showing_sends_the_show_sequence() { - let events = keyboard_events(true, RECT); - assert_eq!( - names(&events), - [ - "keyboardWillChangeFrame", - "keyboardWillShow", - "keyboardDidChangeFrame", - "keyboardDidShow" - ] - ); - } - - #[test] - fn hiding_sends_the_hide_sequence() { - let events = keyboard_events(false, RECT); - assert_eq!( - names(&events), - [ - "keyboardWillChangeFrame", - "keyboardWillHide", - "keyboardDidChangeFrame", - "keyboardDidHide" - ] - ); - } - - #[test] - fn shown_end_coordinates_are_the_occluded_rect() { - let (_, payload) = &keyboard_events(true, RECT)[1]; - let value: serde_json::Value = serde_json::from_str(payload).unwrap(); - let end = &value["endCoordinates"]; - assert_eq!(end["screenX"], 0.0); - assert_eq!(end["screenY"], 420.0); - assert_eq!(end["width"], 800.0); - assert_eq!(end["height"], 180.0); - assert_eq!(value["isEventFromThisApp"], true); - } - - #[test] - fn hidden_end_coordinates_have_no_height() { - let (_, payload) = &keyboard_events(false, RECT)[1]; - let value: serde_json::Value = serde_json::from_str(payload).unwrap(); - assert_eq!(value["endCoordinates"]["height"], 0.0); - assert_eq!(value["endCoordinates"]["screenY"], 420.0); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/keymap.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/keymap.rs deleted file mode 100644 index 46a7c5a7d7..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/keymap.rs +++ /dev/null @@ -1,1239 +0,0 @@ -//! Keyboard shortcuts, as ordinary keymap bindings. -//! -//! `useShortcut('mod+s', …)` in JS becomes one `KeyBinding` here, and a -//! `` becomes a `key_context` on the element core already builds -//! for that node. Nothing intercepts keystrokes: the binding is resolved by -//! GPUI's own keymap, from the focused element's dispatch path, so -//! -//! * a shortcut consumes the key *before* a `TextInput`'s input handler sees -//! it (`window.rs` `dispatch_keystroke` only reaches the handler when -//! `cx.propagate_event` is still true), -//! * a binding in a deeper scope outranks one in a shallower scope -//! (`keymap.rs` `binding_enabled` returns the depth the predicate matched at, -//! and `bindings_for_input` sorts by depth), -//! * an inner scope can override an outer one, because every matching binding -//! is returned in precedence order and dispatched until one stops -//! propagation. -//! -//! A menu accelerator is then just another binding — in the app-wide context — -//! so a component can beat it, which the old `intercept_keystrokes` path could -//! never allow. - -use gpui::{Action, App, KeyBinding}; -use serde_json::{json, Value}; - -use crate::store::store_from; - -/// The key context a `TextInput` puts on its element. A shortcut that does not -/// ask for `allowInTextInput` excludes itself with `!rn-text-input`. -pub const TEXT_INPUT_CONTEXT: &str = "rn-text-input"; - -/// The context the window root carries, so an app-scope shortcut can match with -/// nothing focused. -/// -/// This is not decoration. `KeyBindingContextPredicate::eval_inner` returns -/// false for an *empty* context stack before it ever reaches a `Not`, so a -/// binding like `!rn-text-input` matches nothing when the focus path produces no -/// contexts at all — which is exactly the state a key arrives in when the window -/// has no focused element. A positive identifier on the root gives every key a -/// context to match against, and it is the weakest one the keymap can have, -/// which is what "the window scope may be overridden" means. -pub const APP_CONTEXT: &str = "rn-app"; - -/// Prefix for a scope's context, so a scope named `save` cannot collide with a -/// context core or a library already uses. -const SCOPE_PREFIX: &str = "rn-scope-"; - -/// The operating system whose spelling `secondary-` resolves to in keystroke -/// text parsed outside a context that has an `App` to ask. -pub fn host_os() -> gpui::OperatingSystem { - if cfg!(target_os = "macos") { - gpui::OperatingSystem::Mac - } else if cfg!(target_os = "windows") { - gpui::OperatingSystem::Windows - } else if cfg!(target_os = "freebsd") { - gpui::OperatingSystem::FreeBsd - } else { - gpui::OperatingSystem::Linux - } -} - -/// One shortcut, as JS declares it. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Shortcut { - /// The stable name a handler is registered under, e.g. `file.save`. - pub id: String, - /// GPUI keystroke text, already normalised: `secondary-s`, or - /// `secondary-k secondary-s` for a chord. - pub keys: String, - /// The `ShortcutScope` it belongs to, or `None` for the window/app scope. - pub scope: Option, - pub enabled: bool, - pub allow_in_text_input: bool, - /// Registered with the operating system, so it fires with no window of the - /// app focused. Such a shortcut has no scope and is not part of the keymap. - pub global: bool, -} - -impl Shortcut { - /// Whether `keystroke` is the (first, for a chord) key this shortcut binds. - pub fn key_matches(&self, keystroke: &gpui::Keystroke) -> bool { - match gpui::Keystroke::parse_with_os(&self.keys, host_os()) { - Ok(parsed) => parsed.should_match(&gpui::KeybindingKeystroke::from_keystroke( - keystroke.clone(), - )), - Err(_) => false, - } - } - - /// The context predicate this shortcut's bindings carry. - /// - /// `depth_of` returns the deepest prefix of the context stack the predicate - /// matches, which is what gives an inner scope precedence over an outer one. - /// A shortcut outside a text input appends `!rn-text-input`: `Not` scans the - /// whole stack, so it fails whenever a text input is anywhere on the focus - /// path — the inner editing keys keep the key and no binding consumes it. - pub fn context(&self) -> String { - let scope = self.scope.as_deref().map(scope_context); - match (scope, self.allow_in_text_input) { - (Some(scope), false) => format!("{scope} && !{TEXT_INPUT_CONTEXT}"), - (Some(scope), true) => scope, - (None, false) => format!("{APP_CONTEXT} && !{TEXT_INPUT_CONTEXT}"), - // The window/app scope. `rn-app` is on the window root, so this - // matches with nothing focused — and it is the shallowest context, - // so every scope overrides it. - (None, true) => APP_CONTEXT.to_string(), - } - } -} - -/// The `KeyContext` identifier for a scope name. -/// -/// GPUI identifiers are alphanumeric, `_` and `-` (`keymap/context.rs` -/// `is_identifier_char`), so a name with anything else is folded to `-`. The -/// prefix keeps a scope from shadowing a context somebody else defines. -pub fn scope_context(name: &str) -> String { - let mut out = String::with_capacity(SCOPE_PREFIX.len() + name.len()); - out.push_str(SCOPE_PREFIX); - for character in name.chars() { - if character.is_alphanumeric() || character == '_' { - out.push(character); - } else { - out.push('-'); - } - } - out -} - -/// Parses a JS shortcut spec into GPUI keystroke text. -/// -/// One key is a `+`-separated list of modifiers and a key; a chord is those -/// separated by whitespace. The result folds the spellings JS uses onto the ones -/// GPUI parses, so `mod` works on every platform and `ArrowLeft` means the same -/// as `left`. -pub fn parse_shortcut(spec: &str) -> Result { - let spec = spec.trim(); - if spec.is_empty() { - return Err("a shortcut cannot be empty".to_string()); - } - let mut chord = Vec::new(); - for key in spec.split_whitespace() { - chord.push(parse_key(key)?); - } - Ok(chord.join(" ")) -} - -/// One keystroke of a chord, e.g. `mod+shift+k` -> `secondary-shift-k`. -fn parse_key(key: &str) -> Result { - let mut parts: Vec<&str> = key.split('+').map(str::trim).collect(); - let key_name = parts - .pop() - .filter(|part| !part.is_empty()) - .ok_or_else(|| format!("invalid shortcut key: {key}"))?; - // `mod++` means the plus key; the split above turned it into an empty last - // part, so put the character back. - let key_name = if key_name.is_empty() { "+" } else { key_name }; - - // A modifier listed twice is one modifier; `mod` and `ctrl` on Linux are the - // same key, so they collapse too. - let mut modifiers: Vec<&'static str> = Vec::new(); - for part in parts { - if part.is_empty() { - // `cmd++` again: the trailing `+` is part of the key, not a - // separator, so this is only an error when the key is not `+`. - if key_name == "+" { - continue; - } - return Err(format!("invalid shortcut key: {key}")); - } - let modifier = match part.to_ascii_lowercase().as_str() { - // `mod` is Command on macOS and Control elsewhere, which is what - // GPUI's `secondary` already means. - "mod" | "cmdorctrl" | "commandorcontrol" | "cmdorcontrol" | "secondary" => "secondary", - "cmd" | "command" | "super" | "meta" | "win" => "cmd", - "ctrl" | "control" => "ctrl", - "alt" | "option" | "opt" => "alt", - "shift" => "shift", - other => return Err(format!("unknown shortcut modifier: {other}")), - }; - if !modifiers.contains(&modifier) { - modifiers.push(modifier); - } - } - - let key = normalise_key(key_name).ok_or_else(|| format!("unknown shortcut key: {key_name}"))?; - - let mut out = String::new(); - // `secondary` first so a binding reads the way it is written, then the rest in - // a fixed order: two spellings of the same chord must produce one string, or - // the same shortcut would be installed twice. - for modifier in ["secondary", "cmd", "ctrl", "alt", "shift", "fn"] { - if modifiers.contains(&modifier) { - out.push_str(modifier); - out.push('-'); - } - } - out.push_str(&key); - Ok(out) -} - -/// The GPUI key name for a JS or Electron spelling. -/// -/// GPUI keeps the lower-case name (`keystroke.key`) and only compares it; the -/// web names in `onKeyDown` are produced separately, in `normalise_web_key`. -fn normalise_key(token: &str) -> Option { - let lower = token.to_ascii_lowercase(); - if token.chars().count() == 1 { - let character = token.chars().next()?; - if character.is_ascii_alphanumeric() { - return Some(lower); - } - // Punctuation goes through as-is: GPUI parses it back, and `-` is - // handled by its own splitting rule. - return Some(character.to_string()); - } - let named = match lower.as_str() { - "enter" | "return" => "enter", - "escape" | "esc" => "escape", - "tab" => "tab", - "space" | "spacebar" | " " => "space", - "backspace" => "backspace", - "delete" | "del" => "delete", - "insert" | "ins" => "insert", - "up" | "arrowup" => "up", - "down" | "arrowdown" => "down", - "left" | "arrowleft" => "left", - "right" | "arrowright" => "right", - "home" => "home", - "end" => "end", - "pageup" | "page-up" => "pageup", - "pagedown" | "page-down" => "pagedown", - "comma" => ",", - "period" | "dot" => ".", - "slash" => "/", - "backslash" => "\\", - "semicolon" => ";", - "quote" | "apostrophe" => "'", - "backquote" => "`", - "bracketleft" => "[", - "bracketright" => "]", - "minus" => "-", - "plus" => "+", - "equal" => "=", - _ => { - // Function keys, `f1`..`f24`. GPUI has no list of valid names, so this - // only has to agree with what the platform reports. - if let Some(number) = lower.strip_prefix('f') { - if let Ok(number) = number.parse::() { - if (1..=24).contains(&number) { - return Some(format!("f{number}")); - } - } - } - return None; - } - }; - Some(named.to_string()) -} - -/// The web `key` name for a GPUI key, so `onKeyDown` reports `ArrowLeft` and -/// not `left`. -/// -/// `event.key` in the DOM is a single printable character for printable keys or -/// one of the named values; `Shift+A` is `"A"`, which needs the modifiers to say. -/// The GPUI spelling of a key name given in the W3C spelling (`ArrowDown`, -/// `PageUp`, `Escape`), or the name as it was for anything else. -pub fn gpui_key_name(key: &str) -> String { - match key.to_ascii_lowercase().as_str() { - "arrowup" => "up".to_string(), - "arrowdown" => "down".to_string(), - "arrowleft" => "left".to_string(), - "arrowright" => "right".to_string(), - other => other.to_string(), - } -} - -pub fn normalise_web_key(key: &str, shift: bool) -> String { - let named = match key { - "enter" => "Enter", - "escape" => "Escape", - "tab" => "Tab", - "space" => " ", - "backspace" => "Backspace", - "delete" => "Delete", - "insert" => "Insert", - "up" => "ArrowUp", - "down" => "ArrowDown", - "left" => "ArrowLeft", - "right" => "ArrowRight", - "home" => "Home", - "end" => "End", - "pageup" => "PageUp", - "pagedown" => "PageDown", - // `capslock` and friends: capitalise the first letter so a DOM consumer - // sees `CapsLock` rather than the GPUI spelling. - other => { - if other.chars().count() == 1 { - let character = other.chars().next().unwrap_or_default(); - return if shift { - character.to_uppercase().to_string() - } else { - character.to_string() - }; - } - let mut characters = other.chars(); - return match characters.next() { - Some(first) => first.to_uppercase().collect::() + characters.as_str(), - None => String::new(), - }; - } - }; - named.to_string() -} - -/// The DOM `code` for a GPUI key: the physical key, independent of layout and -/// of Shift. -pub fn web_code(key: &str) -> String { - match key { - "enter" => "Enter".to_string(), - "escape" => "Escape".to_string(), - "tab" => "Tab".to_string(), - "space" => "Space".to_string(), - "backspace" => "Backspace".to_string(), - "delete" => "Delete".to_string(), - "insert" => "Insert".to_string(), - "up" => "ArrowUp".to_string(), - "down" => "ArrowDown".to_string(), - "left" => "ArrowLeft".to_string(), - "right" => "ArrowRight".to_string(), - "home" => "Home".to_string(), - "end" => "End".to_string(), - "pageup" => "PageUp".to_string(), - "pagedown" => "PageDown".to_string(), - other => { - if other.chars().count() == 1 { - let character = other.chars().next().unwrap_or_default(); - return match character { - 'a'..='z' => format!("Key{}", character.to_ascii_uppercase()), - 'A'..='Z' => format!("Key{}", character.to_ascii_uppercase()), - '0'..='9' => format!("Digit{character}"), - ' ' => "Space".to_string(), - ',' => "Comma".to_string(), - '.' => "Period".to_string(), - '/' => "Slash".to_string(), - '\\' => "Backslash".to_string(), - ';' => "Semicolon".to_string(), - '\'' => "Quote".to_string(), - '`' => "Backquote".to_string(), - '[' => "BracketLeft".to_string(), - ']' => "BracketRight".to_string(), - '-' => "Minus".to_string(), - '=' => "Equal".to_string(), - // Not a physical key name the DOM defines; an empty string is - // what the DOM reports for a key it cannot name. - _ => String::new(), - }; - } - if let Some(number) = other.strip_prefix('f') { - if number.parse::().is_ok() { - return format!("F{number}"); - } - } - String::new() - } - } -} - -/// The legacy `keyCode` for a GPUI key, or 0 when the DOM has none. -pub fn key_code(key: &str) -> u32 { - match key { - "backspace" => 8, - "tab" => 9, - "enter" => 13, - "escape" => 27, - "space" => 32, - "pageup" => 33, - "pagedown" => 34, - "end" => 35, - "home" => 36, - "left" => 37, - "up" => 38, - "right" => 39, - "down" => 40, - "insert" => 45, - "delete" => 46, - other => { - if key.len() == 1 { - let character = key.as_bytes()[0]; - if character.is_ascii_lowercase() { - return u32::from(character.to_ascii_uppercase()); - } - if character.is_ascii_digit() { - return u32::from(character); - } - } - if let Some(number) = other.strip_prefix('f') { - if let Ok(number) = number.parse::() { - if (1..=24).contains(&number) { - return 111 + number; - } - } - } - // Punctuation: the DOM's `keyCode` is the ASCII code for the - // unshifted character, which is what we already have. - other - .chars() - .next() - .filter(|character| character.is_ascii()) - .map(|character| u32::from(character as u8)) - .unwrap_or(0) - } - } -} - -/// The shortcuts in a JSON array, as `GpuiShortcuts` installs them. -/// -/// A malformed entry is skipped with a log line rather than failing the whole -/// install: one bad shortcut must not leave an app with no working keys. -pub fn parse_shortcuts(value: &Value) -> Result, String> { - let array = value - .as_array() - .ok_or_else(|| "shortcuts must be an array".to_string())?; - let mut shortcuts = Vec::with_capacity(array.len()); - for entry in array { - let Some(object) = entry.as_object() else { - log::warn!("[shortcut] skipped a shortcut that is not an object"); - continue; - }; - let Some(id) = object.get("id").and_then(Value::as_str) else { - log::warn!("[shortcut] skipped a shortcut with no `id`"); - continue; - }; - let Some(keys) = object.get("keys").and_then(Value::as_str) else { - log::warn!("[shortcut] {id} has no `keys`; skipped"); - continue; - }; - let keys = match parse_shortcut(keys) { - Ok(keys) => keys, - Err(error) => { - log::warn!("[shortcut] {id} has invalid keys: {error}"); - continue; - } - }; - shortcuts.push(Shortcut { - id: id.to_string(), - keys, - scope: object - .get("scope") - .and_then(Value::as_str) - .map(str::to_string), - enabled: object - .get("enabled") - .and_then(Value::as_bool) - .unwrap_or(true), - allow_in_text_input: object - .get("allowInTextInput") - .and_then(Value::as_bool) - .unwrap_or(false), - global: object - .get("global") - .and_then(Value::as_bool) - .unwrap_or(false), - }); - } - Ok(shortcuts) -} - -/// The installed shortcuts as JSON, which is what `shortcutGet` answers with. -pub fn shortcuts_json(cx: &App) -> Value { - Value::Array( - shortcuts(cx) - .into_iter() - .map(|shortcut| { - json!({ - "id": shortcut.id, - "keys": shortcut.keys, - "scope": shortcut.scope, - "enabled": shortcut.enabled, - "allowInTextInput": shortcut.allow_in_text_input, - "global": shortcut.global, - }) - }) - .collect(), - ) -} - -/// A shortcut's action, carrying the id JS registered it under. -#[derive(Clone, Debug, PartialEq, gpui::Action)] -#[action(namespace = rn_gpui_shortcut, no_json, no_register)] -pub struct ShortcutAction { - pub id: String, -} - -/// The installed shortcut list, and what the keymap was last built from. -pub struct ShortcutState { - shortcuts: Vec, - /// The signature the current keymap bindings were built from. Rebuilding is - /// only worth doing when this changes: a re-render must not thrash the - /// keymap. - built: String, - /// A rebuild was asked for and a deferred one is already waiting. - scheduled: bool, -} - -impl Default for ShortcutState { - fn default() -> Self { - Self { - shortcuts: Vec::new(), - built: String::new(), - scheduled: false, - } - } -} - -pub struct ShortcutGlobal(pub ShortcutState); -impl gpui::Global for ShortcutGlobal {} - -impl Default for ShortcutGlobal { - fn default() -> Self { - Self(ShortcutState::default()) - } -} - -/// Installs a shortcut list, rebuilding the keymap only if it changed. -/// -/// `scope_tags` is the set of mounted scope tags in the focused surface: a -/// binding is only useful where its scope element exists, so this is part of the -/// signature that decides whether to rebuild. -/// -/// Returns the global shortcuts the system would not register. An unchanged list -/// returns none: JS was told about them the first time. -pub fn install( - cx: &mut App, - shortcuts: Vec, -) -> Vec { - let signature = signature(&shortcuts); - let state = &mut ensure_global(cx).0; - if state.built == signature { - return Vec::new(); - } - let failures = crate::desktop::global_shortcut::install(cx, &shortcuts); - let state = &mut ensure_global(cx).0; - state.shortcuts = shortcuts; - schedule_rebuild(cx); - failures -} - -/// The shortcuts currently installed. -pub fn shortcuts(cx: &App) -> Vec { - cx.try_global::() - .map(|state| state.0.shortcuts.clone()) - .unwrap_or_default() -} - -/// The ids that belong to `scope` (or to no scope, when `scope` is `None`). -pub fn ids_in_scope(cx: &App, scope: Option<&str>) -> Vec { - shortcuts(cx) - .into_iter() - .filter(|shortcut| shortcut.enabled && shortcut.scope.as_deref() == scope) - .map(|shortcut| shortcut.id) - .collect() -} - -/// Whether `id` is installed and enabled anywhere, so a `window`-scope action -/// from an element can be told apart from one it should pass on. -pub fn is_installed(cx: &App, id: &str) -> bool { - cx.try_global::().is_some_and(|state| { - state - .0 - .shortcuts - .iter() - .any(|shortcut| shortcut.enabled && shortcut.id == id) - }) -} - -/// Whether a scoped shortcut would consume `keystroke` from the focused element. -/// -/// Used by the menu interceptor, which runs before the keymap is consulted: it -/// has to know whether a shortcut outranks the menu accelerator it is about to -/// handle, or it would take the key away from a shortcut that is entitled to it. -/// -/// `window.context_stack()` is the public way to ask what the focused element's -/// context is, so the precedence is evaluated here the same way -/// `Keymap::bindings_for_input` does it: deepest matching context first, later -/// bindings before earlier ones. -/// -/// A scoped shortcut wins at a greater depth. A shortcut with no scope lives in -/// the same context as a menu accelerator and wins the tie, as the documented -/// order has it: shortcuts before menu accelerators. -/// The shortcut with no scope that `keystroke` belongs to when nothing in the -/// window has focus. The keymap resolves a key from the focused element's -/// context, so with no focus no binding can match, and neither would the -/// shortcut: it is taken here, ahead of the menu accelerator that would otherwise -/// take the key. -pub fn unfocused_app_shortcut( - cx: &App, - window: &gpui::Window, - keystroke: &gpui::Keystroke, -) -> Option { - if !window.context_stack().is_empty() { - return None; - } - shortcuts(cx) - .into_iter() - .find(|shortcut| { - shortcut.enabled - && !shortcut.global - && shortcut.scope.is_none() - && !shortcut.keys.contains(' ') - && shortcut.key_matches(keystroke) - }) - .map(|shortcut| shortcut.id) -} - -pub fn claims_keystroke(cx: &App, window: &gpui::Window, keystroke: &gpui::Keystroke) -> bool { - let stack = window.context_stack(); - // The menu accelerator this key would trigger is in the app context, which - // is the shallowest one. A shortcut that matches at a greater depth wins the - // key; a tie does not, so the menu keeps its behaviour there. - let app_depth = gpui::KeyBindingContextPredicate::parse(APP_CONTEXT) - .ok() - .and_then(|predicate| predicate.depth_of(&stack)) - .unwrap_or(0); - shortcuts(cx).iter().any(|shortcut| { - if !shortcut.enabled { - return false; - } - // The shortcut's *own* context, not a guessed one: a shortcut that opted - // into text inputs has no `!rn-text-input`, and evaluating anything else - // here would let an Edit-menu accelerator keep a key the shortcut is - // entitled to (`mod+a` and `selectAll` are exactly that pair). - let Some(depth) = gpui::KeyBindingContextPredicate::parse(&shortcut.context()) - .ok() - .and_then(|predicate| predicate.depth_of(&stack)) - else { - return false; - }; - let wins = if shortcut.scope.is_some() { - depth > app_depth - } else { - depth >= app_depth - }; - wins && shortcut.key_matches(keystroke) - }) -} - -/// Whether the shortcut `id` belongs to `scope`, so a scope element knows if an -/// action reaching it is its own or should be passed outward. -pub fn scope_owns(cx: &App, scope: &str, id: &str) -> bool { - cx.try_global::().is_some_and(|state| { - state.0.shortcuts.iter().any(|shortcut| { - shortcut.enabled && shortcut.id == id && shortcut.scope.as_deref() == Some(scope) - }) - }) -} - -/// Sends `topShortcut` to `tag`, which is the JS node for the scope that owns -/// the action. -pub fn dispatch_to(cx: &mut App, tag: i32, id: &str, window: Option<&mut gpui::Window>) { - let Some(store) = store_from(cx) else { - return; - }; - let host = store.read(cx).host.clone(); - host.dispatch_event(tag, "topShortcut", &json!({ "id": id })); - if let Some(window) = window { - store.read(cx).frame_hook.arm(window); - } -} - -/// Sends `gpuiDesktop:shortcut` for a shortcut with no scope element, which is -/// the window/app scope and any shortcut whose scope has not mounted. -pub(crate) fn emit_app_shortcut(cx: &mut App, id: &str, scope: Option<&str>) { - let Some(store) = store_from(cx) else { - return; - }; - let host = store.read(cx).host.clone(); - host.emit_device_event_json( - "gpuiDesktop:shortcut", - &json!({ "id": id, "scope": scope }).to_string(), - ); -} - -fn ensure_global(cx: &mut App) -> &mut ShortcutGlobal { - if cx.try_global::().is_none() { - cx.set_global(ShortcutGlobal::default()); - } - cx.global_mut::() -} - -/// A stable description of a shortcut list, so an unchanged list costs nothing. -fn signature(shortcuts: &[Shortcut]) -> String { - let mut rows: Vec = shortcuts - .iter() - .map(|shortcut| { - format!( - "{}|{}|{}|{}|{}|{}", - shortcut.id, - shortcut.keys, - shortcut.scope.as_deref().unwrap_or(""), - shortcut.enabled, - shortcut.allow_in_text_input, - shortcut.global - ) - }) - .collect(); - // Order is not meaning: two lists with the same shortcuts are the same - // keymap, whichever order JS happened to register them in. Sorted so a - // re-render that reorders the array does not rebuild. - rows.sort(); - rows.join("\n") -} - -/// Rebuilds once the current update has finished. -/// -/// Debounced because a render pass can install shortcuts several times — a -/// mount batch, a props update, a user keymap change — and each rebuild clears -/// and re-adds every binding in the app. -/// -/// Deferred on the app, not on a window's next frame: GPUI runs a window's -/// next-frame callbacks from the platform's frame request, and a hidden or -/// offscreen window (every e2e window on Windows) never gets one, so the -/// bindings would never be installed. -fn schedule_rebuild(cx: &mut App) { - if cx - .try_global::() - .is_some_and(|state| state.0.scheduled) - { - return; - } - ensure_global(cx).0.scheduled = true; - cx.defer(|cx| { - if cx - .try_global::() - .is_some_and(|state| state.0.scheduled) - { - rebuild_now(cx); - } - }); -} - -/// Replaces every `ShortcutAction` binding in the keymap with the current list. -fn rebuild_now(cx: &mut App) { - let shortcuts = cx - .try_global::() - .map(|state| state.0.shortcuts.clone()) - .unwrap_or_default(); - let signature = signature(&shortcuts); - - // `Keymap` has no per-binding removal, so the shortcut bindings are filtered - // out and the rest put back — the same approach the menu accelerators use. - let keymap = cx.key_bindings(); - let kept: Vec = keymap - .borrow() - .bindings() - .filter(|binding| !is_shortcut_action(binding.action())) - .cloned() - .collect(); - { - let mut keymap = keymap.borrow_mut(); - keymap.clear(); - keymap.add_bindings(kept); - } - - let mut bindings = Vec::with_capacity(shortcuts.len()); - for shortcut in &shortcuts { - if !shortcut.enabled || shortcut.global { - continue; - } - // `KeyBinding::new` panics on a malformed context, and a scope name is - // user data, so the predicate is parsed here and a bad one skips the - // binding rather than taking the app down. - let predicate = { - let context = shortcut.context(); - if context.is_empty() { - None - } else { - match gpui::KeyBindingContextPredicate::parse(&context) { - Ok(predicate) => Some(std::rc::Rc::new(predicate)), - Err(error) => { - log::warn!( - "[shortcut] {} has an invalid context {context:?}: {error}", - shortcut.id - ); - continue; - } - } - } - }; - let Ok(binding) = KeyBinding::load( - &shortcut.keys, - Box::new(ShortcutAction { - id: shortcut.id.clone(), - }), - predicate, - false, - None, - cx, - ) else { - log::warn!( - "[shortcut] {} has unparseable keys {:?}; skipped", - shortcut.id, - shortcut.keys - ); - continue; - }; - bindings.push(binding); - } - cx.bind_keys(bindings); - - let state = &mut ensure_global(cx).0; - state.built = signature; - state.scheduled = false; -} - -pub(crate) fn is_shortcut_action(action: &dyn Action) -> bool { - action.as_any().downcast_ref::().is_some() -} - -/// Installs the app-wide action handler. -/// -/// This is the last stop: it runs in the bubble phase after every element on the -/// focus path had a chance to claim the action, so a scoped shortcut never -/// reaches it. Anything that does is in the window/app scope. -pub fn register(cx: &mut App) { - ensure_global(cx); - cx.on_action(|action: &ShortcutAction, cx: &mut App| { - let id = action.id.clone(); - let scope = shortcuts(cx) - .into_iter() - .find(|shortcut| shortcut.id == id) - .and_then(|shortcut| shortcut.scope); - // A scoped shortcut that reached this handler has no scope element on - // the focus path, so there is no node to report to: it goes out as the - // device event, which the registry also listens to. - emit_app_shortcut(cx, &id, scope.as_deref()); - }); -} - -#[cfg(test)] -mod tests { - #[test] - fn a_w3c_key_name_maps_to_the_gpui_one() { - assert_eq!(super::gpui_key_name("ArrowDown"), "down"); - assert_eq!(super::gpui_key_name("arrowdown"), "down"); - assert_eq!(super::gpui_key_name("down"), "down"); - assert_eq!(super::gpui_key_name("Escape"), "escape"); - assert_eq!(super::gpui_key_name("a"), "a"); - } - - use super::*; - use gpui::Keystroke; - - #[test] - fn mod_is_secondary_on_every_platform() { - // `secondary` is what GPUI maps to Command on macOS and Control - // elsewhere, so one JS spelling works everywhere. - assert_eq!(parse_shortcut("mod+s").unwrap(), "secondary-s"); - assert_eq!( - parse_shortcut("CmdOrCtrl+Shift+K").unwrap(), - "secondary-shift-k" - ); - } - - #[test] - fn modifier_spellings_normalise() { - assert_eq!(parse_shortcut("Cmd+S").unwrap(), "cmd-s"); - assert_eq!(parse_shortcut("Meta+S").unwrap(), "cmd-s"); - assert_eq!(parse_shortcut("Ctrl+S").unwrap(), "ctrl-s"); - assert_eq!(parse_shortcut("Control+S").unwrap(), "ctrl-s"); - assert_eq!(parse_shortcut("Alt+S").unwrap(), "alt-s"); - assert_eq!(parse_shortcut("Option+S").unwrap(), "alt-s"); - // Order in the spec does not change the binding. - assert_eq!(parse_shortcut("Shift+Mod+K").unwrap(), "secondary-shift-k"); - assert_eq!(parse_shortcut("mod+shift+K").unwrap(), "secondary-shift-k"); - } - - #[test] - fn a_repeated_modifier_is_one_modifier() { - assert_eq!(parse_shortcut("mod+mod+s").unwrap(), "secondary-s"); - assert_eq!(parse_shortcut("Shift+shift+K").unwrap(), "shift-k"); - } - - #[test] - fn keys_fold_to_gpui_names() { - assert_eq!(parse_shortcut("Escape").unwrap(), "escape"); - assert_eq!(parse_shortcut("Esc").unwrap(), "escape"); - assert_eq!(parse_shortcut("ArrowLeft").unwrap(), "left"); - assert_eq!(parse_shortcut("Return").unwrap(), "enter"); - assert_eq!(parse_shortcut("Space").unwrap(), "space"); - assert_eq!(parse_shortcut("PageDown").unwrap(), "pagedown"); - assert_eq!(parse_shortcut("F5").unwrap(), "f5"); - assert_eq!(parse_shortcut("Cmd+,").unwrap(), "cmd-,"); - } - - #[test] - fn chords_keep_their_keys_in_order() { - assert_eq!( - parse_shortcut("mod+k mod+s").unwrap(), - "secondary-k secondary-s" - ); - assert_eq!( - parse_shortcut(" ctrl+x ctrl+y ").unwrap(), - "ctrl-x ctrl-y" - ); - } - - #[test] - fn bad_shortcuts_are_rejected_rather_than_panicking() { - assert!(parse_shortcut("").is_err()); - assert!(parse_shortcut(" ").is_err()); - assert!(parse_shortcut("Hyper+S").is_err()); - assert!(parse_shortcut("mod+UnknownKey").is_err()); - assert!(parse_shortcut("mod+f99").is_err()); - } - - #[test] - fn a_scope_becomes_a_prefixed_context() { - assert_eq!(scope_context("editor"), "rn-scope-editor"); - // Anything outside GPUI's identifier alphabet folds to `-`, so a scope - // named `a.b c` cannot produce a context that fails to parse. - assert_eq!(scope_context("a.b c"), "rn-scope-a-b-c"); - let parsed = gpui::KeyContext::parse(&scope_context("file view")).unwrap(); - assert!(parsed.contains("rn-scope-file-view")); - } - - #[test] - fn a_scoped_shortcut_excludes_text_inputs() { - let shortcut = Shortcut { - id: "file.save".to_string(), - keys: "secondary-s".to_string(), - scope: Some("editor".to_string()), - enabled: true, - allow_in_text_input: false, - global: false, - }; - assert_eq!(shortcut.context(), "rn-scope-editor && !rn-text-input"); - - let allowed = Shortcut { - allow_in_text_input: true, - ..shortcut.clone() - }; - assert_eq!(allowed.context(), "rn-scope-editor"); - } - - #[test] - fn the_window_scope_has_no_predicate() { - let shortcut = Shortcut { - id: "app.quit".to_string(), - keys: "secondary-q".to_string(), - scope: None, - enabled: true, - allow_in_text_input: true, - global: false, - }; - // The root context, which is the weakest binding in the keymap: any - // scope overrides it. - assert_eq!(shortcut.context(), APP_CONTEXT); - - let excluded = Shortcut { - allow_in_text_input: false, - ..shortcut - }; - assert_eq!( - excluded.context(), - format!("{APP_CONTEXT} && !{TEXT_INPUT_CONTEXT}") - ); - } - - /// A window-scope shortcut must fire with nothing focused. - /// - /// This is the bug the e2e caught and this unit test pins: an `empty` - /// context stack matches *nothing*, including a negation, so an app-scope - /// binding written as `!rn-text-input` could never fire before the root - /// carried `rn-app`. The predicate is evaluated against an empty stack here - /// on purpose, because that is what a window with no focused element - /// produces. - #[test] - fn the_window_scope_matches_with_nothing_focused() { - let shortcut = Shortcut { - id: "window.save".to_string(), - keys: "secondary-s".to_string(), - scope: None, - enabled: true, - allow_in_text_input: false, - global: false, - }; - let binding = KeyBinding::new( - "ctrl-s", - ShortcutAction { - id: shortcut.id.clone(), - }, - Some(&shortcut.context()), - ); - let mut keymap = gpui::Keymap::default(); - keymap.add_bindings([binding]); - let keystroke = Keystroke::parse("ctrl-s").unwrap(); - - // No root context at all: nothing matches. This is why `rn-app` exists. - let (bindings, _) = keymap.bindings_for_input(&[keystroke.clone()], &[]); - assert!( - bindings.is_empty(), - "an empty context stack matches no predicate, not even a negation" - ); - - // The window root provides `rn-app`, and now the shortcut resolves. - let root = vec![gpui::KeyContext::parse(APP_CONTEXT).unwrap()]; - let (bindings, _) = keymap.bindings_for_input(&[keystroke], &root); - assert_eq!(bindings.len(), 1); - } - - /// The root context must not outrank a scope: it is the shallowest one. - #[test] - fn a_scope_outranks_the_app_context() { - let window = KeyBinding::new( - "ctrl-j", - ShortcutAction { - id: "window".to_string(), - }, - Some(APP_CONTEXT), - ); - let scoped = KeyBinding::new( - "ctrl-j", - ShortcutAction { - id: "scoped".to_string(), - }, - Some("rn-scope-editor"), - ); - let mut keymap = gpui::Keymap::default(); - keymap.add_bindings([window, scoped]); - let contexts = vec![ - gpui::KeyContext::parse(APP_CONTEXT).unwrap(), - gpui::KeyContext::parse("rn-scope-editor").unwrap(), - ]; - let (bindings, _) = - keymap.bindings_for_input(&[Keystroke::parse("ctrl-j").unwrap()], &contexts); - assert_eq!( - bindings[0] - .action() - .as_any() - .downcast_ref::() - .unwrap() - .id, - "scoped" - ); - } - - /// The precedence rule the whole design rests on: a binding in a deeper - /// context matches at a greater depth, and `bindings_for_input` returns the - /// bindings sorted by it. - #[test] - fn an_inner_scope_outranks_an_outer_one() { - let outer = KeyBinding::new( - "ctrl-s", - ShortcutAction { - id: "outer".to_string(), - }, - Some("rn-scope-outer"), - ); - let inner = KeyBinding::new( - "ctrl-s", - ShortcutAction { - id: "inner".to_string(), - }, - Some("rn-scope-inner"), - ); - let mut keymap = gpui::Keymap::default(); - keymap.add_bindings([outer.clone(), inner.clone()]); - - let contexts = vec![ - gpui::KeyContext::parse("rn-scope-outer").unwrap(), - gpui::KeyContext::parse("rn-scope-inner").unwrap(), - ]; - let (bindings, pending) = - keymap.bindings_for_input(&[Keystroke::parse("ctrl-s").unwrap()], &contexts); - assert!(!pending); - assert_eq!(bindings.len(), 2); - // Innermost first: dispatch runs them in this order and stops at the - // first one that consumes the key. - assert_eq!( - bindings[0] - .action() - .as_any() - .downcast_ref::() - .unwrap() - .id, - "inner" - ); - } - - /// A shortcut that excludes text inputs does not match when a text input is - /// on the focus path, so the input's own editing keys keep the key. - #[test] - fn a_text_input_disables_a_shortcut_that_opts_out() { - let binding = KeyBinding::new( - "ctrl-a", - ShortcutAction { - id: "select.all".to_string(), - }, - Some(&format!("rn-scope-editor && !{TEXT_INPUT_CONTEXT}")), - ); - let mut keymap = gpui::Keymap::default(); - keymap.add_bindings([binding]); - - let in_editor = vec![ - gpui::KeyContext::parse("rn-scope-editor").unwrap(), - gpui::KeyContext::parse("rn-text-input").unwrap(), - ]; - let (bindings, _) = - keymap.bindings_for_input(&[Keystroke::parse("ctrl-a").unwrap()], &in_editor); - assert!( - bindings.is_empty(), - "a text input must keep a key the shortcut opted out of" - ); - - let outside = vec![gpui::KeyContext::parse("rn-scope-editor").unwrap()]; - let (bindings, _) = - keymap.bindings_for_input(&[Keystroke::parse("ctrl-a").unwrap()], &outside); - assert_eq!(bindings.len(), 1); - } - - #[test] - fn a_chord_needs_both_keys() { - let binding = KeyBinding::new( - "ctrl-k ctrl-s", - ShortcutAction { - id: "chord".to_string(), - }, - None, - ); - let mut keymap = gpui::Keymap::default(); - keymap.add_bindings([binding]); - let first = Keystroke::parse("ctrl-k").unwrap(); - let second = Keystroke::parse("ctrl-s").unwrap(); - - let (bindings, pending) = keymap.bindings_for_input(&[first.clone()], &[]); - assert!(bindings.is_empty()); - assert!(pending, "the first key must wait for the second"); - - let (bindings, pending) = keymap.bindings_for_input(&[first, second], &[]); - assert_eq!(bindings.len(), 1); - assert!(!pending); - } - - /// The six keys the old `dispatch_key` translated, plus the ones it did not. - /// - /// This is the stage-4 contract: every key gets a DOM `key`, a `code` and a - /// `keyCode`, where before only six names were mapped and everything else - /// went out as GPUI's spelling with `keyCode: 0`. - #[test] - fn every_key_gets_a_dom_name_code_and_key_code() { - for (gpui_key, web_key, code, legacy_code) in [ - ("left", "ArrowLeft", "ArrowLeft", 37), - ("up", "ArrowUp", "ArrowUp", 38), - ("right", "ArrowRight", "ArrowRight", 39), - ("down", "ArrowDown", "ArrowDown", 40), - ("enter", "Enter", "Enter", 13), - ("escape", "Escape", "Escape", 27), - ("backspace", "Backspace", "Backspace", 8), - ("delete", "Delete", "Delete", 46), - ("tab", "Tab", "Tab", 9), - ("space", " ", "Space", 32), - ("home", "Home", "Home", 36), - ("end", "End", "End", 35), - ("pageup", "PageUp", "PageUp", 33), - ("pagedown", "PageDown", "PageDown", 34), - ("a", "a", "KeyA", 65), - ("z", "z", "KeyZ", 90), - ("5", "5", "Digit5", 53), - ("f2", "F2", "F2", 113), - ] { - assert_eq!( - normalise_web_key(gpui_key, false), - web_key, - "key for {gpui_key}" - ); - assert_eq!(web_code(gpui_key), code, "code for {gpui_key}"); - assert_eq!(key_code(gpui_key), legacy_code, "keyCode for {gpui_key}"); - } - } - - #[test] - fn web_key_names_are_the_dom_ones() { - assert_eq!(normalise_web_key("left", false), "ArrowLeft"); - assert_eq!(normalise_web_key("up", false), "ArrowUp"); - assert_eq!(normalise_web_key("enter", false), "Enter"); - assert_eq!(normalise_web_key("escape", false), "Escape"); - assert_eq!(normalise_web_key("space", false), " "); - assert_eq!(normalise_web_key("a", false), "a"); - assert_eq!(normalise_web_key("a", true), "A"); - assert_eq!(normalise_web_key("f5", false), "F5"); - } - - #[test] - fn web_codes_are_physical_keys() { - assert_eq!(web_code("a"), "KeyA"); - assert_eq!(web_code("4"), "Digit4"); - assert_eq!(web_code("left"), "ArrowLeft"); - assert_eq!(web_code("space"), "Space"); - assert_eq!(web_code("f5"), "F5"); - } - - #[test] - fn key_codes_are_the_legacy_ones() { - assert_eq!(key_code("a"), 65); - assert_eq!(key_code("z"), 90); - assert_eq!(key_code("4"), 52); - assert_eq!(key_code("enter"), 13); - assert_eq!(key_code("escape"), 27); - assert_eq!(key_code("space"), 32); - assert_eq!(key_code("left"), 37); - assert_eq!(key_code("delete"), 46); - assert_eq!(key_code("f1"), 112); - assert_eq!(key_code("f12"), 123); - } - - #[test] - fn the_signature_ignores_order_but_not_content() { - let one = Shortcut { - id: "a".to_string(), - keys: "secondary-a".to_string(), - scope: None, - enabled: true, - allow_in_text_input: false, - global: false, - }; - let two = Shortcut { - id: "b".to_string(), - keys: "secondary-b".to_string(), - scope: Some("editor".to_string()), - enabled: true, - allow_in_text_input: false, - global: false, - }; - assert_eq!( - signature(&[one.clone(), two.clone()]), - signature(&[two.clone(), one.clone()]) - ); - assert_ne!(signature(&[one.clone()]), signature(&[two])); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/memory_pressure.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/memory_pressure.rs deleted file mode 100644 index 8ec962af9a..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/memory_pressure.rs +++ /dev/null @@ -1,157 +0,0 @@ -//! `AppState`'s `memoryWarning`: the OS saying memory is running low. - -use crate::host::Host; - -#[cfg(target_os = "macos")] -mod platform { - use super::Host; - use std::ffi::c_void; - use std::sync::Mutex; - - static HOST: Mutex> = Mutex::new(None); - - // DISPATCH_MEMORYPRESSURE_WARN | DISPATCH_MEMORYPRESSURE_CRITICAL - const PRESSURE_MASK: usize = 0x2 | 0x4; - - extern "C" { - static _dispatch_source_type_memorypressure: c_void; - fn dispatch_source_create( - source_type: *const c_void, - handle: usize, - mask: usize, - queue: *mut c_void, - ) -> *mut c_void; - fn dispatch_source_set_event_handler_f( - source: *mut c_void, - handler: extern "C" fn(*mut c_void), - ); - fn dispatch_get_global_queue(identifier: isize, flags: usize) -> *mut c_void; - fn dispatch_resume(object: *mut c_void); - } - - extern "C" fn on_pressure(_context: *mut c_void) { - if let Some(host) = HOST.lock().expect("memory pressure host poisoned").as_ref() { - host.emit_memory_warning(); - } - } - - pub fn start(host: Host) { - *HOST.lock().expect("memory pressure host poisoned") = Some(host); - // SAFETY: the source is created once, keeps running for the life of the - // process and is never released; the handler only reads `HOST`. - unsafe { - let queue = dispatch_get_global_queue(0, 0); - let source = dispatch_source_create( - &_dispatch_source_type_memorypressure, - 0, - PRESSURE_MASK, - queue, - ); - if source.is_null() { - log::warn!("memory pressure source unavailable"); - return; - } - dispatch_source_set_event_handler_f(source, on_pressure); - dispatch_resume(source); - } - } -} - -#[cfg(target_os = "linux")] -mod platform { - use super::Host; - use std::io::Write; - use std::os::fd::AsRawFd; - - /// A stall of 150 ms within a 1 s window: the kernel's own definition of - /// memory pressure worth telling an app about. - const TRIGGER: &str = "some 150000 1000000\0"; - - pub fn start(host: Host) { - let spawned = std::thread::Builder::new() - .name("memory-pressure".into()) - .spawn(move || { - let Ok(mut file) = std::fs::OpenOptions::new() - .read(true) - .write(true) - .open("/proc/pressure/memory") - else { - return; - }; - if file.write_all(TRIGGER.as_bytes()).is_err() { - return; - } - loop { - let mut descriptor = libc::pollfd { - fd: file.as_raw_fd(), - events: libc::POLLPRI, - revents: 0, - }; - // SAFETY: `descriptor` is one valid pollfd. - let ready = unsafe { libc::poll(&mut descriptor, 1, -1) }; - if ready < 0 { - return; - } - if descriptor.revents & libc::POLLERR != 0 { - return; - } - if descriptor.revents & libc::POLLPRI != 0 { - host.emit_memory_warning(); - } - } - }); - if let Err(error) = spawned { - log::warn!("memory pressure monitor not started: {error}"); - } - } -} - -#[cfg(target_os = "windows")] -mod platform { - use super::Host; - use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; - use windows_sys::Win32::System::Memory::{ - CreateMemoryResourceNotification, LowMemoryResourceNotification, - }; - use windows_sys::Win32::System::Threading::WaitForSingleObject; - - pub fn start(host: Host) { - let spawned = std::thread::Builder::new() - .name("memory-pressure".into()) - .spawn(move || { - // SAFETY: the handle is owned by this thread and closed on exit. - let handle = - unsafe { CreateMemoryResourceNotification(LowMemoryResourceNotification) }; - if handle.is_null() { - return; - } - loop { - // SAFETY: `handle` is a valid notification object. - let result = unsafe { WaitForSingleObject(handle, u32::MAX) }; - if result != WAIT_OBJECT_0 { - break; - } - host.emit_memory_warning(); - // The object stays signalled while memory is low. - std::thread::sleep(std::time::Duration::from_secs(30)); - } - // SAFETY: closes the handle opened above. - unsafe { CloseHandle(handle) }; - }); - if let Err(error) = spawned { - log::warn!("memory pressure monitor not started: {error}"); - } - } -} - -#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] -mod platform { - use super::Host; - - pub fn start(_host: Host) {} -} - -/// Starts watching for memory pressure; each warning reaches JS as `memoryWarning`. -pub fn start(host: Host) { - platform::start(host); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/menu_events.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/menu_events.rs deleted file mode 100644 index 2edd370469..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/menu_events.rs +++ /dev/null @@ -1,236 +0,0 @@ -//! One route for every `muda` menu event. -//! -//! `muda` has exactly one `MenuEvent` channel, and `MenuEvent::set_event_handler` -//! takes it over: its documentation is explicit that a handler installed with -//! `Some` means `MenuEvent::receiver()` **stops receiving events at all**. The -//! setter is backed by a `OnceLock`, so the first caller wins and every later -//! call is silently ignored. -//! -//! Three parts of this app build `muda` menus — the Win32 menu bar, the tray -//! menu, and native context menus. Each used to install its own handler or read -//! the receiver, so only one of them could ever work: whichever installed first -//! took the channel, a menu-bar click had nowhere to go because its items -//! carried no id at all, and a native context menu could not read its selection -//! once either of the others had installed a handler. -//! -//! This module owns the single handler. Consumers register a predicate and a -//! callback; each event is offered to the registered consumers in order and the -//! first predicate that claims the id handles it. A context menu that is -//! currently showing is offered every event first, because it is modal. - -use std::sync::{Mutex, OnceLock}; - -/// Claims an id and handles it. Returning `true` means this consumer took the -/// event and no later one should see it. -type Consumer = Box bool + Send + Sync>; - -/// Resolves the id a native context menu reported, while one is showing. -type ContextWaiter = Box; - -/// Who handled an event, for the tests and for a caller that wants to know. -#[derive(Debug, PartialEq, Eq)] -enum Handled { - /// A pending native context menu. - ContextMenu, - /// A registered consumer, by its position in the registration order. - Consumer(usize), - /// Nobody claimed the id; it was dropped. - Unclaimed, -} - -static CONSUMERS: Mutex> = Mutex::new(Vec::new()); -static CONTEXT_WAITER: Mutex> = Mutex::new(None); -static INSTALLED: OnceLock<()> = OnceLock::new(); - -/// Offers `id` to the consumers, in registration order, and returns who took it. -/// -/// This is the whole routing rule, and the installed handler is a thin wrapper -/// over it, so a test can exercise the real decision instead of a copy of it. -/// A context menu is checked first because it is modal: while one is showing it -/// is the only menu that can have produced an event. -fn route(id: &str) -> Handled { - if let Ok(mut slot) = CONTEXT_WAITER.lock() { - if let Some(callback) = slot.take() { - callback(id.to_string()); - return Handled::ContextMenu; - } - } - if let Ok(consumers) = CONSUMERS.lock() { - for (index, consumer) in consumers.iter().enumerate() { - if consumer(id) { - return Handled::Consumer(index); - } - } - } - Handled::Unclaimed -} - -/// Installs the single handler. Idempotent: the first call installs it and later -/// calls do nothing, which is what stops a second menu system from taking the -/// channel away from the first. -/// -/// Two crates deliver menu events, each with exactly one channel, and this app -/// builds menus with both: -/// -/// - `muda`, this crate's own dependency, builds the Win32 menu bar and the native -/// context menus on macOS and Windows. -/// - `tray_icon` bundles its own, newer `muda` and re-exports it as -/// `tray_icon::menu`, and the tray's menu is built with that copy on every -/// platform. The two are different versions — the lockfile holds both — so their -/// `MenuEvent`s are different channels even though the type has the same name, -/// and a selection from a tray menu arrives on `tray_icon`'s, never on `muda`'s. -/// Listening only on `muda`'s is what left a tray menu's items doing nothing on -/// macOS and Windows. -/// -/// Linux's GPUI-drawn menus (the menu bar and context menus) do not use an event -/// channel at all; they report through their own responder. -fn ensure_installed() { - INSTALLED.get_or_init(|| { - #[cfg(any(target_os = "macos", target_os = "windows"))] - { - let _ = muda::MenuEvent::set_event_handler(Some(|event: muda::MenuEvent| { - route(&event.id.0); - })); - } - let _ = tray_icon::menu::MenuEvent::set_event_handler(Some( - |event: tray_icon::menu::MenuEvent| { - route(&event.id.0); - }, - )); - }); -} - -/// Registers a consumer for menu ids it recognises. Registration order is the -/// order ids are offered in, so the first registration that claims an id wins. -pub fn register(consumer: Consumer) { - if let Ok(mut consumers) = CONSUMERS.lock() { - consumers.push(consumer); - } - ensure_installed(); -} - -/// Runs `show`, collecting the id the native context menu reports. -/// -/// The menu is modal and `show` returns when it closes, so the selection has -/// already arrived by the time this returns. Replacing a previous waiter is -/// deliberate: a stale one belongs to a menu that is no longer up. -pub fn with_context_menu(show: F) -> Option -where - F: FnOnce(), -{ - ensure_installed(); - let (sender, receiver) = std::sync::mpsc::channel::(); - if let Ok(mut slot) = CONTEXT_WAITER.lock() { - *slot = Some(Box::new(move |id| { - let _ = sender.send(id); - })); - } - show(); - // Clear the reservation whether or not anything was chosen, so a later - // application-menu event is not swallowed by a menu that has closed. - if let Ok(mut slot) = CONTEXT_WAITER.lock() { - *slot = None; - } - receiver.try_recv().ok() -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Each test owns the routing state it asserts on. The statics are - /// process-wide, so tests that share them would interleave; this replaces - /// the consumer list and the waiter for the duration of one test. - struct Isolated { - _guard: std::sync::MutexGuard<'static, ()>, - } - - static TEST_LOCK: Mutex<()> = Mutex::new(()); - - impl Isolated { - fn new() -> Self { - let guard = TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner()); - CONSUMERS.lock().unwrap().clear(); - *CONTEXT_WAITER.lock().unwrap() = None; - Self { _guard: guard } - } - } - - impl Drop for Isolated { - fn drop(&mut self) { - CONSUMERS.lock().unwrap().clear(); - *CONTEXT_WAITER.lock().unwrap() = None; - } - } - - #[test] - fn the_first_consumer_that_claims_an_id_handles_it() { - let _isolated = Isolated::new(); - register(Box::new(|id| id == "second-claims-this")); - register(Box::new(|id| id == "second-claims-this")); - register(Box::new(|_| false)); - // The first registration that claims it wins, so the second is never - // consulted for this id. - assert_eq!(route("second-claims-this"), Handled::Consumer(0)); - } - - #[test] - fn a_consumer_that_does_not_claim_an_id_is_passed_over() { - let _isolated = Isolated::new(); - register(Box::new(|id| id == "not-this-one")); - register(Box::new(|id| id == "mine")); - assert_eq!(route("mine"), Handled::Consumer(1)); - } - - #[test] - fn an_unclaimed_id_is_dropped_rather_than_misrouted() { - let _isolated = Isolated::new(); - register(Box::new(|id| id == "mine")); - // An unrelated menu's id must not be handed to this consumer: the two - // emit different JS events, so a misroute is a wrong action. - assert_eq!(route("someone-elses"), Handled::Unclaimed); - } - - #[test] - fn a_pending_context_menu_takes_every_event_and_then_stops() { - let _isolated = Isolated::new(); - register(Box::new(|_| true)); - // Reserve the channel the way `with_context_menu` does, then route an - // id: it goes to the context menu, not to the registered consumer. - let (sender, receiver) = std::sync::mpsc::channel::(); - *CONTEXT_WAITER.lock().unwrap() = Some(Box::new(move |id| { - let _ = sender.send(id); - })); - assert_eq!(route("cm-open"), Handled::ContextMenu); - assert_eq!(receiver.try_recv().ok().as_deref(), Some("cm-open")); - // The reservation is one-shot: the next event belongs to the normal - // route again, so a menu that has closed cannot swallow it. - assert_eq!(route("cm-open"), Handled::Consumer(0)); - } - - #[test] - fn with_context_menu_reports_the_selection_and_clears_itself() { - let _isolated = Isolated::new(); - register(Box::new(|_| true)); - // Simulate the menu closing with a choice: the callback is taken while - // `show` runs, exactly as `muda` does when the menu closes. - let selection = with_context_menu(|| { - if let Some(callback) = CONTEXT_WAITER.lock().unwrap().take() { - callback("cm-nested".to_string()); - } - }); - assert_eq!(selection.as_deref(), Some("cm-nested")); - assert!( - CONTEXT_WAITER.lock().unwrap().is_none(), - "the reservation must not outlive the menu" - ); - } - - #[test] - fn with_context_menu_reports_nothing_when_the_menu_is_dismissed() { - let _isolated = Isolated::new(); - let selection = with_context_menu(|| {}); - assert_eq!(selection, None); - assert!(CONTEXT_WAITER.lock().unwrap().is_none()); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/menu_model.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/menu_model.rs deleted file mode 100644 index 4c4e4f3987..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/menu_model.rs +++ /dev/null @@ -1,604 +0,0 @@ -use crate::desktop::errors::DesktopError; -use serde_json::Value; - -/// Nesting limit for submenus. Deeper than any real menu, shallow enough that a -/// malformed payload cannot recurse without bound. -pub const MAX_DEPTH: usize = 10; - -#[derive(Clone, Debug, PartialEq)] -pub enum MenuNode { - Item(MenuItemDef), - Submenu(SubmenuDef), - Separator, - StandardMenu(MenuRole), -} - -#[derive(Clone, Debug, PartialEq)] -pub struct MenuItemDef { - pub id: String, - pub label: String, - pub accelerator: Option, - pub enabled: bool, - pub checked: bool, - pub role: Option, - /// The URI of the item's icon, loaded by `desktop::icon`. - pub icon: Option, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct SubmenuDef { - pub id: Option, - pub label: String, - pub enabled: bool, - pub items: Vec, - pub icon: Option, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum MenuRole { - About, - Services, - Hide, - HideOthers, - ShowAll, - Quit, - Undo, - Redo, - Cut, - Copy, - Paste, - PasteWithoutFormatting, - SelectAll, - Minimize, - Zoom, - ZoomIn, - ZoomOut, - ResetZoom, - ToggleFullscreen, - Close, - Help, - AppMenu, - EditMenu, - WindowMenu, - HelpMenu, -} - -impl MenuRole { - pub fn parse(name: &str) -> Option { - Some(match name { - "about" => Self::About, - "services" => Self::Services, - "hide" => Self::Hide, - "hideOthers" => Self::HideOthers, - "showAll" => Self::ShowAll, - "quit" => Self::Quit, - "undo" => Self::Undo, - "redo" => Self::Redo, - "cut" => Self::Cut, - "copy" => Self::Copy, - "paste" => Self::Paste, - "pasteWithoutFormatting" => Self::PasteWithoutFormatting, - "selectAll" => Self::SelectAll, - "minimize" => Self::Minimize, - "zoom" => Self::Zoom, - "zoomIn" => Self::ZoomIn, - "zoomOut" => Self::ZoomOut, - "resetZoom" => Self::ResetZoom, - "toggleFullscreen" => Self::ToggleFullscreen, - "close" => Self::Close, - "help" => Self::Help, - "appMenu" => Self::AppMenu, - "editMenu" => Self::EditMenu, - "windowMenu" => Self::WindowMenu, - "helpMenu" => Self::HelpMenu, - _ => return None, - }) - } - - pub fn is_standard_menu(self) -> bool { - matches!( - self, - Self::AppMenu | Self::EditMenu | Self::WindowMenu | Self::HelpMenu - ) - } - - pub fn default_label(self) -> &'static str { - match self { - Self::About => "About", - Self::Services => "Services", - Self::Hide => "Hide", - Self::HideOthers => "Hide Others", - Self::ShowAll => "Show All", - Self::Quit => "Quit", - Self::Undo => "Undo", - Self::Redo => "Redo", - Self::Cut => "Cut", - Self::Copy => "Copy", - Self::Paste => "Paste", - Self::PasteWithoutFormatting => "Paste Without Formatting", - Self::SelectAll => "Select All", - Self::Minimize => "Minimize", - Self::Zoom => "Zoom", - Self::ZoomIn => "Zoom In", - Self::ZoomOut => "Zoom Out", - Self::ResetZoom => "Actual Size", - Self::ToggleFullscreen => "Toggle Full Screen", - Self::Close => "Close", - Self::Help => "Help", - Self::AppMenu => "App", - Self::EditMenu => "Edit", - Self::WindowMenu => "Window", - Self::HelpMenu => "Help", - } - } - - /// Whether this platform can implement the role. Roles with no meaning are - /// dropped from the built menu rather than shown disabled. - pub fn is_supported(self) -> bool { - match self { - Self::Services | Self::Hide | Self::HideOthers | Self::ShowAll => { - cfg!(target_os = "macos") - } - Self::About => cfg!(target_os = "macos"), - _ => true, - } - } -} - -#[derive(Clone, Debug, PartialEq, Default)] -pub struct MenuModel { - pub items: Vec, -} - -impl MenuModel { - pub fn ids(&self) -> Vec { - let mut ids = Vec::new(); - collect_ids(&self.items, &mut ids); - ids - } - - pub fn find(&self, id: &str) -> Option<&MenuItemDef> { - fn walk<'a>(items: &'a [MenuNode], id: &str) -> Option<&'a MenuItemDef> { - for node in items { - match node { - MenuNode::Item(item) if item.id == id => return Some(item), - MenuNode::Submenu(submenu) => { - if let Some(found) = walk(&submenu.items, id) { - return Some(found); - } - } - _ => {} - } - } - None - } - walk(&self.items, id) - } - - pub fn accelerators(&self) -> Vec<(String, String)> { - let mut bindings = Vec::new(); - collect_accelerators(&self.items, &mut bindings); - bindings - } - - pub fn has_help_menu(&self) -> bool { - self.items.iter().any(|node| match node { - MenuNode::StandardMenu(MenuRole::HelpMenu) => true, - MenuNode::Submenu(submenu) => submenu.label.eq_ignore_ascii_case("help"), - _ => false, - }) - } -} - -fn collect_ids(items: &[MenuNode], ids: &mut Vec) { - for node in items { - match node { - MenuNode::Item(item) => ids.push(item.id.clone()), - MenuNode::Submenu(submenu) => { - if let Some(id) = &submenu.id { - ids.push(id.clone()); - } - collect_ids(&submenu.items, ids); - } - _ => {} - } - } -} - -fn collect_accelerators(items: &[MenuNode], out: &mut Vec<(String, String)>) { - for node in items { - match node { - MenuNode::Item(item) => { - if let Some(accelerator) = &item.accelerator { - out.push((item.id.clone(), accelerator.clone())); - } - } - MenuNode::Submenu(submenu) => collect_accelerators(&submenu.items, out), - _ => {} - } - } -} - -pub fn parse_menu(value: &Value) -> Result { - let array = value - .as_array() - .ok_or_else(|| DesktopError::invalid_argument("a menu must be an array"))?; - let items = parse_items(array, 0)?; - let model = MenuModel { items }; - let mut seen = std::collections::HashSet::new(); - for id in model.ids() { - if !seen.insert(id.clone()) { - return Err(DesktopError::invalid_argument(format!( - "duplicate menu item id: {id}" - ))); - } - } - Ok(model) -} - -fn parse_items(array: &[Value], depth: usize) -> Result, DesktopError> { - if depth > MAX_DEPTH { - return Err(DesktopError::invalid_argument(format!( - "menus nest deeper than {MAX_DEPTH} levels" - ))); - } - let mut nodes = Vec::with_capacity(array.len()); - for entry in array { - nodes.push(parse_node(entry, depth)?); - } - Ok(nodes) -} - -fn parse_node(value: &Value, depth: usize) -> Result { - let object = value - .as_object() - .ok_or_else(|| DesktopError::invalid_argument("a menu item must be an object"))?; - let kind = object - .get("type") - .map(|value| { - value - .as_str() - .ok_or_else(|| DesktopError::invalid_argument("menu item `type` must be a string")) - }) - .transpose()? - .unwrap_or("item"); - - match kind { - "separator" => { - check_fields(object, &["type"])?; - Ok(MenuNode::Separator) - } - "submenu" => { - check_fields(object, &["type", "id", "label", "enabled", "items", "icon"])?; - let label = required_string(object, "label")?; - let enabled = optional_bool(object, "enabled")?.unwrap_or(true); - let items = object - .get("items") - .and_then(Value::as_array) - .ok_or_else(|| { - DesktopError::invalid_argument("a submenu requires an `items` array") - })?; - Ok(MenuNode::Submenu(SubmenuDef { - id: optional_string(object, "id")?, - label, - enabled, - items: parse_items(items, depth + 1)?, - icon: optional_string(object, "icon")?, - })) - } - "role" => { - check_fields(object, &["type", "id", "role", "label", "enabled"])?; - let role_name = required_string(object, "role")?; - let role = MenuRole::parse(&role_name).ok_or_else(|| { - DesktopError::invalid_argument(format!("unknown menu role: {role_name}")) - })?; - if role.is_standard_menu() { - return Ok(MenuNode::StandardMenu(role)); - } - Ok(MenuNode::Item(MenuItemDef { - id: optional_string(object, "id")?.unwrap_or_else(|| format!("role:{role_name}")), - label: optional_string(object, "label")? - .unwrap_or_else(|| role.default_label().to_string()), - accelerator: None, - enabled: optional_bool(object, "enabled")?.unwrap_or(true), - checked: false, - role: Some(role), - icon: None, - })) - } - "item" => { - check_fields( - object, - &[ - "type", - "id", - "label", - "accelerator", - "enabled", - "checked", - "role", - "icon", - ], - )?; - let role = match optional_string(object, "role")? { - Some(name) => Some(MenuRole::parse(&name).ok_or_else(|| { - DesktopError::invalid_argument(format!("unknown menu role: {name}")) - })?), - None => None, - }; - let label = match optional_string(object, "label")? { - Some(label) => label, - None => role - .map(|role| role.default_label().to_string()) - .ok_or_else(|| { - DesktopError::invalid_argument("a menu item requires a `label`") - })?, - }; - let id = match optional_string(object, "id")? { - Some(id) => id, - None if role.is_some() => format!("role:{}", label), - None => { - return Err(DesktopError::invalid_argument( - "a menu item requires an `id`", - )) - } - }; - let accelerator = match optional_string(object, "accelerator")? { - Some(spec) => Some(parse_accelerator(&spec)?), - None => None, - }; - Ok(MenuNode::Item(MenuItemDef { - id, - label, - accelerator, - enabled: optional_bool(object, "enabled")?.unwrap_or(true), - checked: optional_bool(object, "checked")?.unwrap_or(false), - role, - icon: optional_string(object, "icon")?, - })) - } - other => Err(DesktopError::invalid_argument(format!( - "unknown menu item type: {other}" - ))), - } -} - -fn check_fields( - object: &serde_json::Map, - allowed: &[&str], -) -> Result<(), DesktopError> { - for key in object.keys() { - if !allowed.contains(&key.as_str()) { - return Err(DesktopError::invalid_argument(format!( - "unknown menu item field: {key}" - ))); - } - } - Ok(()) -} - -fn required_string( - object: &serde_json::Map, - key: &str, -) -> Result { - optional_string(object, key)? - .ok_or_else(|| DesktopError::invalid_argument(format!("missing `{key}`"))) -} - -fn optional_string( - object: &serde_json::Map, - key: &str, -) -> Result, DesktopError> { - match object.get(key) { - None | Some(Value::Null) => Ok(None), - Some(Value::String(value)) => Ok(Some(value.clone())), - Some(_) => Err(DesktopError::invalid_argument(format!( - "`{key}` must be a string" - ))), - } -} - -fn optional_bool( - object: &serde_json::Map, - key: &str, -) -> Result, DesktopError> { - match object.get(key) { - None | Some(Value::Null) => Ok(None), - Some(Value::Bool(value)) => Ok(Some(*value)), - Some(_) => Err(DesktopError::invalid_argument(format!( - "`{key}` must be a boolean" - ))), - } -} - -/// `CmdOrCtrl` becomes GPUI's `secondary`: Command on macOS, Control elsewhere. -pub fn parse_accelerator(spec: &str) -> Result { - let trimmed = spec.trim(); - if trimmed.is_empty() { - return Err(DesktopError::invalid_argument( - "an accelerator cannot be empty", - )); - } - let mut parts: Vec<&str> = trimmed.split('+').map(str::trim).collect(); - let key_token = parts - .pop() - .filter(|key| !key.is_empty()) - .ok_or_else(|| DesktopError::invalid_argument(format!("invalid accelerator: {spec}")))?; - - let mut modifiers: Vec<&'static str> = Vec::new(); - for part in parts { - if part.is_empty() { - return Err(DesktopError::invalid_argument(format!( - "invalid accelerator: {spec}" - ))); - } - let modifier = match part.to_ascii_lowercase().as_str() { - "cmdorctrl" | "commandorcontrol" | "cmdorcontrol" | "controllorcmd" => "secondary", - "command" | "cmd" | "super" | "meta" => "cmd", - "control" | "ctrl" => "ctrl", - "alt" | "option" => "alt", - "shift" => "shift", - "altgr" => { - return Err(DesktopError::invalid_argument( - "AltGr is not supported in accelerators", - )) - } - other => { - return Err(DesktopError::invalid_argument(format!( - "unknown accelerator modifier: {other}" - ))) - } - }; - if !modifiers.contains(&modifier) { - modifiers.push(modifier); - } - } - - let key = accelerator_key(key_token).ok_or_else(|| { - DesktopError::invalid_argument(format!("unknown accelerator key: {key_token}")) - })?; - - let mut keystroke = String::new(); - for modifier in modifiers { - keystroke.push_str(modifier); - keystroke.push('-'); - } - keystroke.push_str(&key); - Ok(keystroke) -} - -fn accelerator_key(token: &str) -> Option { - let lower = token.to_ascii_lowercase(); - if token.chars().count() == 1 { - let character = token.chars().next()?; - if character.is_ascii_alphanumeric() { - return Some(lower); - } - return Some(character.to_string()); - } - if let Some(rest) = lower.strip_prefix('f') { - if let Ok(number) = rest.parse::() { - if (1..=24).contains(&number) { - return Some(format!("f{number}")); - } - } - } - Some( - match lower.as_str() { - "enter" | "return" => "enter", - "escape" | "esc" => "escape", - "tab" => "tab", - "space" | "spacebar" => "space", - "backspace" => "backspace", - "delete" | "del" => "delete", - "insert" | "ins" => "insert", - "up" | "arrowup" => "up", - "down" | "arrowdown" => "down", - "left" | "arrowleft" => "left", - "right" | "arrowright" => "right", - "home" => "home", - "end" => "end", - "pageup" => "pageup", - "pagedown" => "pagedown", - "plus" => "+", - "minus" => "-", - "comma" => ",", - "period" => ".", - "slash" => "/", - "backslash" => "\\", - "semicolon" => ";", - "quote" => "'", - "backquote" => "`", - "bracketleft" => "[", - "bracketright" => "]", - _ => return None, - } - .to_string(), - ) -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn parses_a_nested_menu() { - let model = parse_menu(&json!([ - {"label": "File", "type": "submenu", "items": [ - {"id": "new", "label": "New", "accelerator": "CmdOrCtrl+N"}, - {"type": "separator"}, - {"id": "quit", "label": "Quit", "role": "quit"} - ]}, - {"type": "role", "role": "editMenu"} - ])) - .expect("valid menu"); - assert_eq!(model.items.len(), 2); - assert_eq!(model.ids(), vec!["new".to_string(), "quit".to_string()]); - assert!(model.find("new").is_some()); - assert!(matches!( - model.items[1], - MenuNode::StandardMenu(MenuRole::EditMenu) - )); - } - - #[test] - fn rejects_duplicate_ids() { - let error = parse_menu(&json!([ - {"id": "a", "label": "A"}, - {"id": "a", "label": "Again"} - ])) - .expect_err("duplicate ids are rejected"); - assert_eq!(error.code, crate::desktop::errors::codes::INVALID_ARGUMENT); - assert!(error.message.contains("duplicate")); - } - - #[test] - fn rejects_unknown_fields() { - let error = parse_menu(&json!([{"id": "a", "label": "A", "typo": true}])) - .expect_err("unknown fields are rejected"); - assert!(error.message.contains("typo")); - } - - #[test] - fn rejects_unknown_types_and_roles() { - assert!(parse_menu(&json!([{"type": "magic"}])).is_err()); - assert!(parse_menu(&json!([{"type": "role", "role": "nope"}])).is_err()); - } - - #[test] - fn rejects_too_deep_nesting() { - let mut value = json!({"id": "leaf", "label": "leaf"}); - for _ in 0..MAX_DEPTH + 2 { - value = json!({"label": "sub", "type": "submenu", "items": [value]}); - } - assert!(parse_menu(&json!([value])).is_err()); - } - - #[test] - fn parses_accelerators() { - assert_eq!(parse_accelerator("CmdOrCtrl+N").unwrap(), "secondary-n"); - assert_eq!( - parse_accelerator("CmdOrCtrl+Shift+K").unwrap(), - "secondary-shift-k" - ); - assert_eq!(parse_accelerator("Ctrl+Alt+I").unwrap(), "ctrl-alt-i"); - assert_eq!(parse_accelerator("F5").unwrap(), "f5"); - assert_eq!(parse_accelerator("Cmd+,").unwrap(), "cmd-,"); - assert_eq!(parse_accelerator("Shift+Enter").unwrap(), "shift-enter"); - } - - #[test] - fn rejects_bad_accelerators() { - assert!(parse_accelerator("").is_err()); - assert!(parse_accelerator("Meta+UnknownKey").is_err()); - assert!(parse_accelerator("Hyper+K").is_err()); - } - - #[test] - fn role_menus_are_standard_menus() { - assert!(MenuRole::EditMenu.is_standard_menu()); - assert!(!MenuRole::Copy.is_standard_menu()); - assert!(!MenuRole::Copy.default_label().is_empty()); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/mod.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/mod.rs deleted file mode 100644 index df250d4274..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/mod.rs +++ /dev/null @@ -1,92 +0,0 @@ -pub mod app_dir; -pub mod app_menu; -pub mod app_state; -pub mod background; -pub mod button_layout; -pub mod capabilities; -pub mod client_frame; -pub mod context_menu; -pub mod deep_link; -pub mod dev_menu; -pub mod display; -pub mod errors; -pub mod frame_probe; -pub mod global_shortcut; -pub mod gpui_menu; -pub mod icon; -pub mod keyboard; -pub mod keymap; -pub mod memory_pressure; -pub mod menu_events; -pub mod menu_model; -pub mod module; -pub mod os_version; -pub mod perf_monitor; -pub mod platform_window; -pub mod popover_placement; -#[cfg(target_os = "linux")] -pub mod portal_shortcuts; -pub mod test_scale; -pub mod tray; -pub mod window_frame; -pub mod window_icons; -pub mod window_mirror; -pub mod windows; -#[cfg(target_os = "linux")] -pub mod work_area; -pub mod zoom; - -use gpui::App; -use std::sync::OnceLock; - -#[derive(Clone)] -pub struct Snapshot { - pub app_id: String, - pub platform: &'static str, -} - -static SNAPSHOT: OnceLock = OnceLock::new(); - -/// Install the snapshot the module's value methods read. Must run before -/// `load_script`, so a module that reads a capability during initialization sees -/// the real value. -pub fn install_snapshot(app_id: &str) { - let _ = SNAPSHOT.set(Snapshot { - app_id: app_id.to_string(), - platform: std::env::consts::OS, - }); -} - -/// The app id, or an empty string before `install_snapshot` ran. -pub fn snapshot_app_id() -> String { - SNAPSHOT - .get() - .map(|snapshot| snapshot.app_id.clone()) - .unwrap_or_default() -} - -pub fn snapshot_platform() -> String { - SNAPSHOT - .get() - .map(|snapshot| snapshot.platform.to_string()) - .unwrap_or_else(|| std::env::consts::OS.to_string()) -} - -/// The main loop's queue, installed by the bootstrap before the first command. -static COMMAND_SENDER: OnceLock> = - OnceLock::new(); - -pub(crate) fn set_command_sender(sender: async_channel::Sender) { - let _ = COMMAND_SENDER.set(sender); -} - -/// Queues one command for the GPUI main thread. The command answers through the -/// channel it was built with, which may be long after it returns: a context menu -/// answers when it closes. -pub fn post_to_main(command: Box) { - let Some(sender) = COMMAND_SENDER.get() else { - log::warn!("[desktop] the main loop is not running; command dropped"); - return; - }; - let _ = sender.send_blocking(crate::bootstrap::MainEvent::DesktopCommand(command)); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/module.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/module.rs deleted file mode 100644 index e79e685ba8..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/module.rs +++ /dev/null @@ -1,80 +0,0 @@ -//! The desktop-shell TurboModule: one method per command in -//! `src-gpui/src/private/specs/NativeGpuiDesktop.ts`. -//! -//! A command needs the GPUI app context, which only the main loop holds, so -//! each one is posted to the main thread and awaited here. The value methods -//! (`capabilities`, `platform`, `appId`) read immutable state and run inline on -//! the JS thread, which is what makes them synchronous. - -use rn_gpui_module::{ModuleError, ModuleThread}; - -use super::capabilities; - -pub struct GpuiDesktopModule; - -rn_gpui_module::include_specs!(); - -impl NativeGpuiDesktopSpec for GpuiDesktopModule { - /// Every command runs where the GPUI app context is. - const THREAD: ModuleThread = ModuleThread::Main; - - fn new(_events: NativeGpuiDesktopEvents) -> Self { - Self - } - - fn capabilities(&self) -> Result { - capabilities::wait_for_window_decorations(); - Ok(DesktopCapabilities { - native_app_menu: capabilities::native_app_menu(), - native_context_menu: capabilities::native_context_menu(), - tray: capabilities::tray(), - tray_popover_anchored: capabilities::tray_popover_anchored(), - window_position: capabilities::window_position(), - always_on_top: capabilities::always_on_top(), - visible_on_all_workspaces: capabilities::visible_on_all_workspaces(), - transparent_titlebar: capabilities::transparent_titlebar(), - menu_bar_in_window: capabilities::menu_bar_in_window(), - client_decorations: capabilities::client_decorations(), - }) - } - - fn platform(&self) -> Result { - Ok(super::snapshot_platform()) - } - - fn window_button_layout(&self) -> Result { - Ok(super::button_layout::button_layout()) - } - - fn window_button_icon(&self, action: String, color: String) -> Result { - Ok(super::window_icons::window_icon(&action, &color).unwrap_or_default()) - } - - fn platform_constants(&self) -> Result { - Ok(PlatformConstants { - os_version: super::os_version::os_version(), - is_testing: super::os_version::is_testing(), - }) - } - - fn app_id(&self) -> Result { - Ok(super::snapshot_app_id()) - } - - async fn app_info(&self) -> Result { - Ok(DesktopAppInfo { - platform: super::snapshot_platform(), - arch: std::env::consts::ARCH.to_string(), - capabilities: self.capabilities()?, - }) - } - - fn add_listener(&self, _event_name: String) {} - - fn remove_listeners(&self, _count: f64) {} -} - -/// Registers the desktop module. Called once, before the first JS runtime. -pub fn register() { - rn_gpui_module::register(native_gpui_desktop_module::()); -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/os_version.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/os_version.rs deleted file mode 100644 index 96c26f06da..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/os_version.rs +++ /dev/null @@ -1,126 +0,0 @@ -//! The host operating system's version as a string, for `Platform.Version`. - -/// `15.1` from `sw_vers -productVersion` output. -#[cfg_attr(not(target_os = "macos"), allow(dead_code))] -fn parse_product_version(output: &str) -> Option { - let version = output.trim(); - (!version.is_empty() && version.chars().all(|c| c.is_ascii_digit() || c == '.')) - .then(|| version.to_string()) -} - -/// The `VERSION_ID` of an os-release file, unquoted. -#[cfg_attr(not(target_os = "linux"), allow(dead_code))] -fn parse_os_release(contents: &str) -> Option { - contents.lines().find_map(|line| { - let value = line.strip_prefix("VERSION_ID=")?; - let value = value.trim().trim_matches(|c| c == '"' || c == '\''); - (!value.is_empty()).then(|| value.to_string()) - }) -} - -#[cfg_attr(not(target_os = "windows"), allow(dead_code))] -fn windows_version(major: u32, minor: u32, build: u32) -> String { - format!("{major}.{minor}.{build}") -} - -#[cfg(target_os = "macos")] -fn detect() -> Option { - let output = std::process::Command::new("sw_vers") - .arg("-productVersion") - .output() - .ok()?; - parse_product_version(&String::from_utf8_lossy(&output.stdout)) -} - -#[cfg(target_os = "linux")] -fn detect() -> Option { - std::fs::read_to_string("/etc/os-release") - .ok() - .and_then(|contents| parse_os_release(&contents)) - .or_else(|| { - std::fs::read_to_string("/proc/sys/kernel/osrelease") - .ok() - .map(|release| release.trim().to_string()) - .filter(|release| !release.is_empty()) - }) -} - -#[cfg(target_os = "windows")] -fn detect() -> Option { - #[repr(C)] - struct OsVersionInfo { - size: u32, - major: u32, - minor: u32, - build: u32, - platform: u32, - service_pack: [u16; 128], - } - #[link(name = "ntdll")] - extern "system" { - fn RtlGetVersion(info: *mut OsVersionInfo) -> i32; - } - let mut info = OsVersionInfo { - size: std::mem::size_of::() as u32, - major: 0, - minor: 0, - build: 0, - platform: 0, - service_pack: [0; 128], - }; - // SAFETY: `info` is a valid, correctly sized OSVERSIONINFOW. - let status = unsafe { RtlGetVersion(&mut info) }; - (status >= 0).then(|| windows_version(info.major, info.minor, info.build)) -} - -#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] -fn detect() -> Option { - None -} - -/// Resolved once: the version cannot change while the app runs. -pub fn os_version() -> String { - static VERSION: std::sync::OnceLock = std::sync::OnceLock::new(); - VERSION - .get_or_init(|| detect().unwrap_or_else(|| "unknown".to_string())) - .clone() -} - -/// Whether the e2e test driver is attached to this process. -pub fn is_testing() -> bool { - std::env::var("RN_GPUI_TEST_DRIVER").as_deref() == Ok("1") -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_macos_product_version_keeps_its_dots() { - assert_eq!(parse_product_version("15.1\n").as_deref(), Some("15.1")); - assert_eq!(parse_product_version("15.1.1\n").as_deref(), Some("15.1.1")); - assert_eq!(parse_product_version("garbage"), None); - assert_eq!(parse_product_version(""), None); - } - - #[test] - fn a_linux_version_id_is_read_unquoted() { - let release = "NAME=\"Ubuntu\"\nVERSION_ID=\"24.04\"\nID=ubuntu\n"; - assert_eq!(parse_os_release(release).as_deref(), Some("24.04")); - assert_eq!(parse_os_release("VERSION_ID=12\n").as_deref(), Some("12")); - assert_eq!(parse_os_release("NAME=Arch\n"), None); - } - - #[test] - fn a_windows_version_is_major_minor_build() { - assert_eq!(windows_version(10, 0, 26100), "10.0.26100"); - } - - #[test] - fn the_detected_version_is_never_empty() { - let version = os_version(); - assert!(!version.is_empty()); - #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))] - assert_ne!(version, "unknown"); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/perf_monitor.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/perf_monitor.rs deleted file mode 100644 index a137a19c37..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/perf_monitor.rs +++ /dev/null @@ -1,413 +0,0 @@ -//! A host-drawn GPUI overlay, not React Native views, so it does not disturb -//! what it measures. - -use crate::store::{store_from, SurfaceRootView}; -use gpui::{ - px, App, AppContext, Context, Entity, Global, IntoElement, ParentElement, Render, Styled, - Window, -}; -use serde_json::{json, Value}; -use std::cell::RefCell; -use std::collections::VecDeque; -use std::time::{Duration, Instant}; - -const WINDOW: Duration = Duration::from_secs(1); -const TEXT_REFRESH: Duration = Duration::from_millis(500); - -#[derive(Default)] -pub struct PerfMonitorState { - pub enabled: bool, - ui_frames: VecDeque, - js_ticks: VecDeque, - pub last_mount_ms: f32, - pub js_fps: f32, - js_probes_seen: u64, - js_probes_primed: bool, - memory: Option<(Instant, u64)>, - last_frame: Option, - /// The best rate seen since the monitor was enabled: the display's rate, - /// which is what a frame is late against. - peak_fps: f32, - dropped_frames: u64, - stutters: u64, -} - -const MIN_PEAK_FPS: f32 = 30.0; -/// React Native counts a stutter when at least this many frames drop at once. -const STUTTER_FRAMES: u64 = 4; - -fn missed_frames(gap: Duration, display_fps: f32) -> u64 { - if display_fps < MIN_PEAK_FPS { - return 0; - } - let refreshes = (gap.as_secs_f32() * display_fps).round(); - (refreshes - 1.0).max(0.0) as u64 -} - -pub struct PerfMonitorGlobal(pub RefCell); -impl Global for PerfMonitorGlobal {} - -impl PerfMonitorState { - fn prune(&mut self, now: Instant) { - while self - .ui_frames - .front() - .is_some_and(|at| now.duration_since(*at) > WINDOW) - { - self.ui_frames.pop_front(); - } - while self - .js_ticks - .front() - .is_some_and(|at| now.duration_since(*at) > WINDOW) - { - self.js_ticks.pop_front(); - } - } -} - -pub fn install(cx: &mut App) { - cx.set_global(PerfMonitorGlobal(RefCell::new(PerfMonitorState::default()))); -} - -pub fn set_enabled(cx: &mut App, enabled: bool) -> Value { - let was_enabled = { - let mut state = cx.global_mut::().0.borrow_mut(); - let previous = state.enabled; - state.enabled = enabled; - if !enabled { - state.ui_frames.clear(); - state.js_ticks.clear(); - state.js_fps = 0.0; - state.js_probes_primed = false; - state.last_frame = None; - state.dropped_frames = 0; - state.stutters = 0; - } - previous - }; - if enabled && !was_enabled { - cx.spawn(async move |cx| loop { - cx.background_executor().timer(TEXT_REFRESH).await; - let mut stop = false; - let _ = cx.update(|cx| { - if !is_enabled(cx) { - stop = true; - return; - } - let Some(store) = store_from(cx) else { - stop = true; - return; - }; - let monitor = store - .read(cx) - .roots - .get(&crate::store::APP_SURFACE_ID) - .and_then(|root| root.read(cx).perf_monitor.clone()); - if let Some(monitor) = monitor { - monitor.update(cx, |_monitor, cx| cx.notify()); - } - }); - if stop { - break; - } - }) - .detach(); - } - emit_enabled(cx, enabled); - let state = cx.global::().0.borrow(); - json!({"enabled": state.enabled}) -} - -fn emit_enabled(cx: &App, enabled: bool) { - let Some(store) = store_from(cx) else { - return; - }; - store.read(cx).host.emit_device_event_json( - "gpuiDesktop:perfMonitor", - &json!({"enabled": enabled}).to_string(), - ); -} - -pub fn is_enabled(cx: &App) -> bool { - cx.try_global::() - .is_some_and(|state| state.0.borrow().enabled) -} - -/// A presented frame. The overlay calls this once each time it is drawn, and -/// it is drawn once per frame while it is visible, so nothing else may call it: -/// a second caller would double the rate. -fn record_frame(cx: &App) { - let Some(global) = cx.try_global::() else { - return; - }; - let js_probes = store_from(cx).map(|store| store.read(cx).host.js_frame_probe()); - let mut state = global.0.borrow_mut(); - if !state.enabled { - return; - } - let now = Instant::now(); - state.prune(now); - state.ui_frames.push_back(now); - state.peak_fps = state.peak_fps.max(state.ui_frames.len() as f32); - if let Some(previous) = state.last_frame.replace(now) { - let missed = missed_frames(now.duration_since(previous), state.peak_fps); - state.dropped_frames += missed; - if missed >= STUTTER_FRAMES { - state.stutters += 1; - } - } - // One probe is posted to the JS thread per frame, and none while the - // previous one waits. Counting the ones that ran gives the rate the JS - // thread keeps up with: the frame rate when idle, less when it is busy. - if let Some(total) = js_probes { - let ran = total.saturating_sub(state.js_probes_seen); - state.js_probes_seen = total; - if state.js_probes_primed { - for _ in 0..ran.min(1000) { - state.js_ticks.push_back(now); - } - } - state.js_probes_primed = true; - } - state.js_fps = state.js_ticks.len() as f32; -} - -pub fn record_js_ticks(_cx: &App, _count: u32) {} - -pub fn record_mount(cx: &App, millis: f32) { - let Some(global) = cx.try_global::() else { - return; - }; - let mut state = global.0.borrow_mut(); - if state.enabled { - state.last_mount_ms = millis; - } -} - -pub fn metrics(cx: &App) -> Value { - let now = Instant::now(); - let (ui_fps, js_fps, mount_ms, enabled, dropped, stutters) = { - let Some(global) = cx.try_global::() else { - // The spec's metrics carry every field, so an app that never enabled - // the monitor reads zeros rather than a missing field. - return json!({ - "enabled": false, - "uiFps": 0.0, - "jsFps": 0.0, - "memoryBytes": 0, - "jsHeapBytes": 0, - "droppedFrames": 0, - "stutters": 0, - "mountedViews": 0, - "lastMountMs": 0.0, - }); - }; - let mut state = global.0.borrow_mut(); - state.prune(now); - // A JS thread that stopped running probes has no ticks left once the - // window passes; the stored rate would otherwise freeze at its last value. - state.js_fps = state.js_ticks.len() as f32; - ( - state.ui_frames.len() as f32, - state.js_fps, - state.last_mount_ms, - state.enabled, - state.dropped_frames, - state.stutters, - ) - }; - let memory = { - let global = cx.global::(); - let mut state = global.0.borrow_mut(); - match state.memory { - Some((at, bytes)) if now.duration_since(at) < TEXT_REFRESH => bytes, - _ => { - let bytes = resident_memory_bytes(); - state.memory = Some((now, bytes)); - bytes - } - } - }; - let (views, js_heap) = store_from(cx) - .map(|store| { - let store = store.read(cx); - (store.nodes.len(), store.host.js_heap_bytes()) - }) - .unwrap_or((0, 0)); - json!({ - "enabled": enabled, - "uiFps": ui_fps, - "jsFps": js_fps, - "memoryBytes": memory, - "jsHeapBytes": js_heap, - "droppedFrames": dropped, - "stutters": stutters, - "mountedViews": views, - "lastMountMs": mount_ms, - }) -} - -#[cfg(target_os = "macos")] -pub fn resident_memory_bytes() -> u64 { - // `task_info(TASK_BASIC_INFO)` reports `resident_size` in bytes. - #[repr(C)] - #[derive(Default)] - struct TaskBasicInfo { - virtual_size: u64, - resident_size: u64, - resident_size_max: u64, - user_time: [u32; 2], - system_time: [u32; 2], - policy: i32, - suspend_count: i32, - } - const TASK_BASIC_INFO: u32 = 4; - extern "C" { - fn mach_task_self() -> u32; - fn task_info(task: u32, flavor: u32, info: *mut TaskBasicInfo, count: *mut u32) -> i32; - } - let mut info = TaskBasicInfo::default(); - let mut count = (std::mem::size_of::() / std::mem::size_of::()) as u32; - // SAFETY: `info` and `count` are valid for `task_info` to write, and `count` is the buffer size in `u32`s. - let result = unsafe { task_info(mach_task_self(), TASK_BASIC_INFO, &mut info, &mut count) }; - if result == 0 { - info.resident_size - } else { - 0 - } -} - -#[cfg(target_os = "linux")] -pub fn resident_memory_bytes() -> u64 { - // `/proc/self/statm` field 2 is resident pages. - std::fs::read_to_string("/proc/self/statm") - .ok() - .and_then(|contents| { - contents - .split_whitespace() - .nth(1) - .and_then(|pages| pages.parse::().ok()) - }) - .map(|pages| pages * 4096) - .unwrap_or(0) -} - -#[cfg(not(any(target_os = "macos", target_os = "linux")))] -pub fn resident_memory_bytes() -> u64 { - // TODO: read `GetProcessMemoryInfo` on Windows. - 0 -} - -pub struct PerfMonitor { - window_id: u32, -} - -impl PerfMonitor { - pub fn new(window_id: u32) -> Self { - Self { window_id } - } -} - -fn format_bytes(bytes: u64) -> String { - const MB: f64 = 1024.0 * 1024.0; - if bytes == 0 { - "n/a".to_string() - } else { - format!("{:.0} MB", bytes as f64 / MB) - } -} - -impl Render for PerfMonitor { - fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { - if !is_enabled(cx) { - // Kept absolute so the hidden overlay is exactly 0x0 and cannot - // swallow input meant for the app behind it. - return gpui::div().absolute().top_0().left_0(); - } - // This runs once per presented frame while the overlay is visible. Asking - // for the next frame here is what keeps them coming, and it is legal - // from the paint phase (unlike from a timer). - record_frame(cx); - window.request_animation_frame(); - let value = metrics(cx); - let line = |label: &str, text: String| { - gpui::div() - .flex() - .gap_2() - .child(gpui::div().w(px(74.0)).child(label.to_string())) - .child(text) - }; - gpui::div() - .absolute() - .top(px(6.0)) - .right(px(6.0)) - .px_2() - .py_1() - .rounded(px(4.0)) - .bg(gpui::rgba(0x00000099)) - .text_color(gpui::white()) - .text_size(px(11.0)) - .flex() - .flex_col() - .gap_0p5() - .child(line( - "UI FPS", - format!("{:.0}", value["uiFps"].as_f64().unwrap_or(0.0)), - )) - .child(line( - "JS FPS", - format!("{:.0}", value["jsFps"].as_f64().unwrap_or(0.0)), - )) - .child(line( - "Dropped", - format!( - "{} ({} stutters)", - value["droppedFrames"].as_u64().unwrap_or(0), - value["stutters"].as_u64().unwrap_or(0) - ), - )) - .child(line("Views", format!("{}", value["mountedViews"]))) - .child(line( - "Mount", - format!("{:.1} ms", value["lastMountMs"].as_f64().unwrap_or(0.0)), - )) - .child(line( - "Memory", - format_bytes(value["memoryBytes"].as_u64().unwrap_or(0)), - )) - .child(line( - "JS heap", - format_bytes(value["jsHeapBytes"].as_u64().unwrap_or(0)), - )) - .child(line("Window", format!("#{}", self.window_id))) - } -} - -pub fn attach(cx: &mut App, root: &Entity, window_id: u32) { - let monitor = cx.new(|_| PerfMonitor::new(window_id)); - root.update(cx, |root, cx| { - root.perf_monitor = Some(monitor); - cx.notify(); - }); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn missed_frames_counts_refreshes_without_a_frame() { - let frame = Duration::from_secs_f32(1.0 / 120.0); - assert_eq!(missed_frames(frame, 120.0), 0); - assert_eq!(missed_frames(frame * 2, 120.0), 1); - assert_eq!(missed_frames(frame * 5, 120.0), 4); - assert_eq!(missed_frames(frame * 5, 0.0), 0); - } - - #[test] - fn format_bytes_reports_megabytes() { - assert_eq!(format_bytes(0), "n/a"); - assert_eq!(format_bytes(64 * 1024 * 1024), "64 MB"); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/platform_window.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/platform_window.rs deleted file mode 100644 index ec146f04de..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/platform_window.rs +++ /dev/null @@ -1,1478 +0,0 @@ -pub fn supports_position() -> bool { - crate::desktop::capabilities::window_position() -} - -#[cfg(target_os = "macos")] -mod imp { - use cocoa::base::id; - use cocoa::foundation::{NSPoint, NSSize}; - use objc::{msg_send, sel, sel_impl}; - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - - const FLOATING_WINDOW_LEVEL: i64 = 3; - const NORMAL_WINDOW_LEVEL: i64 = 0; - - pub(crate) fn ns_window(window: &gpui::Window) -> Result { - let handle = HasWindowHandle::window_handle(window) - .map_err(|error| format!("no platform window handle: {error}"))?; - match handle.as_raw() { - // SAFETY: `ns_view` comes from the window's raw handle, which GPUI keeps valid while the window lives. - RawWindowHandle::AppKit(appkit) => unsafe { - let ns_view = appkit.ns_view.as_ptr() as id; - let native: id = msg_send![ns_view, window]; - if native.is_null() { - Err("the AppKit window is gone".to_string()) - } else { - Ok(native) - } - }, - _ => Err("unexpected platform window handle".to_string()), - } - } - - /// Convert a GPUI top-left-origin screen point into an AppKit top-left point. - /// - /// GPUI's `bounds()` reports `x - screen.origin.x` and - /// `screen.height - appkit_y - frame_height + screen.origin.y`; this is the - /// inverse, so `set_position` round-trips through `window.bounds()`. - fn appkit_top_left(window: &gpui::Window, native: id, x: f32, y: f32) -> NSPoint { - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - let screen: id = msg_send![native, screen]; - let frame_height = f32::from(window.bounds().size.height); - if screen.is_null() { - return NSPoint::new(f64::from(x), f64::from(y)); - } - let screen_frame: cocoa::foundation::NSRect = msg_send![screen, frame]; - let appkit_x = x + screen_frame.origin.x as f32; - let appkit_y = screen_frame.size.height as f32 - (y - screen_frame.origin.y as f32); - NSPoint::new(f64::from(appkit_x), f64::from(appkit_y + frame_height)) - } - } - - pub fn set_position(window: &mut gpui::Window, x: f32, y: f32) -> Result<(), String> { - let native = ns_window(window)?; - let point = appkit_top_left(window, native, x, y); - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - let _: () = msg_send![native, setFrameTopLeftPoint: point]; - } - Ok(()) - } - - pub fn set_always_on_top(window: &mut gpui::Window, on: bool) -> Result<(), String> { - let native = ns_window(window)?; - let level = if on { - FLOATING_WINDOW_LEVEL - } else { - NORMAL_WINDOW_LEVEL - }; - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - let _: () = msg_send![native, setLevel: level]; - } - Ok(()) - } - - /// NSWindowCollectionBehavior bits. `FullScreenPrimary` and - /// `MoveToActiveSpace` each conflict with what is set here, and AppKit raises - /// an exception when they are combined. - const CAN_JOIN_ALL_SPACES: u64 = 1 << 0; - const MOVE_TO_ACTIVE_SPACE: u64 = 1 << 1; - const FULL_SCREEN_PRIMARY: u64 = 1 << 7; - const FULL_SCREEN_AUXILIARY: u64 = 1 << 8; - - pub fn set_visible_on_all_workspaces( - window: &mut gpui::Window, - visible: bool, - ) -> Result<(), String> { - let native = ns_window(window)?; - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - let current: u64 = msg_send![native, collectionBehavior]; - let wanted = CAN_JOIN_ALL_SPACES | FULL_SCREEN_AUXILIARY; - let next = if visible { - (current & !(MOVE_TO_ACTIVE_SPACE | FULL_SCREEN_PRIMARY)) | wanted - } else { - current & !wanted - }; - let _: () = msg_send![native, setCollectionBehavior: next]; - } - Ok(()) - } - - pub fn set_min_size(window: &mut gpui::Window, width: f32, height: f32) -> Result<(), String> { - let native = ns_window(window)?; - let size = NSSize::new(f64::from(width), f64::from(height)); - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - let _: () = msg_send![native, setContentMinSize: size]; - } - Ok(()) - } - - pub fn set_max_size(window: &mut gpui::Window, width: f32, height: f32) -> Result<(), String> { - let native = ns_window(window)?; - let size = NSSize::new(f64::from(width), f64::from(height)); - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - let _: () = msg_send![native, setContentMaxSize: size]; - } - Ok(()) - } - - const STYLE_MASK_RESIZABLE: u64 = 1 << 3; - - pub fn set_resizable(window: &mut gpui::Window, resizable: bool) -> Result<(), String> { - let native = ns_window(window)?; - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - let mask: u64 = msg_send![native, styleMask]; - let next = if resizable { - mask | STYLE_MASK_RESIZABLE - } else { - mask & !STYLE_MASK_RESIZABLE - }; - if next != mask { - let _: () = msg_send![native, setStyleMask: next]; - } - } - Ok(()) - } - - pub fn show(window: &mut gpui::Window) -> Result<(), String> { - let native = ns_window(window)?; - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - if crate::desktop::background::enabled() { - let _: () = msg_send![native, orderBack: std::ptr::null::()]; - } else { - let _: () = msg_send![native, orderFront: std::ptr::null::()]; - } - } - Ok(()) - } - - pub fn hide(window: &mut gpui::Window) -> Result<(), String> { - let native = ns_window(window)?; - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - let _: () = msg_send![native, orderOut: std::ptr::null::()]; - } - Ok(()) - } - - pub fn is_minimized(window: &gpui::Window) -> bool { - let Ok(native) = ns_window(window) else { - return false; - }; - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - let minimized: bool = msg_send![native, isMiniaturized]; - minimized - } - } - - /// `[NSWindow isZoomed]`. - /// - /// GPUI's own `Window::is_maximized` reads `NSScreen.visibleFrame` and - /// panics when the window has no screen (a hidden or off-screen window), - /// which the test driver creates, so the desktop shell asks AppKit instead. - pub fn is_maximized(window: &gpui::Window) -> bool { - let Ok(native) = ns_window(window) else { - return false; - }; - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - let screen: id = msg_send![native, screen]; - if screen.is_null() { - return false; - } - let zoomed: bool = msg_send![native, isZoomed]; - zoomed - } - } - - /// `style_as_popover` already configures the panel; nothing to set before - /// it is shown. - pub fn prepare_popover( - _window: &mut gpui::Window, - _x: f32, - _y: f32, - _width: f32, - _height: f32, - ) -> Result<(), String> { - Ok(()) - } - - pub fn activate_popover(_window: &gpui::Window) -> Result<(), String> { - Ok(()) - } -} - -#[cfg(target_os = "macos")] -pub use imp::*; - -/// Windows: `SetWindowPos` / `ShowWindow` / `IsIconic` / `IsZoomed` on the -/// HWND. -/// -/// TODO: never built or run on Windows. -#[cfg(target_os = "windows")] -mod imp { - use gpui::Window; - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - use windows_sys::Win32::Foundation::HWND; - use windows_sys::Win32::UI::WindowsAndMessaging::{ - IsIconic, IsWindowVisible, IsZoomed, SetWindowPos, ShowWindowAsync, HWND_NOTOPMOST, - HWND_TOPMOST, SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, - SW_HIDE, SW_RESTORE, SW_SHOW, - }; - - const UNSUPPORTED_MIN_MAX: &str = - "a runtime minimum/maximum size needs a WM_GETMINMAXINFO handler in GPUI's window procedure"; - - fn hwnd(window: &Window) -> Result { - let handle = HasWindowHandle::window_handle(window) - .map_err(|error| format!("no platform window handle: {error}"))?; - match handle.as_raw() { - RawWindowHandle::Win32(win32) => Ok(win32.hwnd.get() as HWND), - _ => Err("unexpected platform window handle".to_string()), - } - } - - pub fn set_position(window: &mut Window, x: f32, y: f32) -> Result<(), String> { - let hwnd = hwnd(window)?; - // GPUI's bounds are physical pixels, which is what SetWindowPos takes. - // SAFETY: `hwnd` is the live window handle `hwnd()` just returned, used on the window's own thread. - let result = unsafe { - SetWindowPos( - hwnd, - std::ptr::null_mut(), - x.round() as i32, - y.round() as i32, - 0, - 0, - SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, - ) - }; - if result == 0 { - Err("SetWindowPos failed".to_string()) - } else { - Ok(()) - } - } - - pub fn set_visible_on_all_workspaces( - _window: &mut Window, - _visible: bool, - ) -> Result<(), String> { - Ok(()) - } - - pub fn set_always_on_top(window: &mut Window, on: bool) -> Result<(), String> { - let hwnd = hwnd(window)?; - let insert_after = if on { HWND_TOPMOST } else { HWND_NOTOPMOST }; - // SAFETY: `hwnd` is the live window handle `hwnd()` just returned, used on the window's own thread. - let result = unsafe { - SetWindowPos( - hwnd, - insert_after, - 0, - 0, - 0, - 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE, - ) - }; - if result == 0 { - Err("SetWindowPos failed".to_string()) - } else { - Ok(()) - } - } - - pub fn set_min_size(_window: &mut Window, _width: f32, _height: f32) -> Result<(), String> { - Err(UNSUPPORTED_MIN_MAX.to_string()) - } - - pub fn set_max_size(_window: &mut Window, _width: f32, _height: f32) -> Result<(), String> { - Err(UNSUPPORTED_MIN_MAX.to_string()) - } - - /// Toggle the resize frame. GPUI applies the style flags it knows at - /// creation, so the change is pushed with `SWP_FRAMECHANGED`. - pub fn set_resizable(window: &mut Window, resizable: bool) -> Result<(), String> { - use windows_sys::Win32::UI::WindowsAndMessaging::{ - GetWindowLongPtrW, SetWindowLongPtrW, GWL_STYLE, WS_MAXIMIZEBOX, WS_THICKFRAME, - }; - let hwnd = hwnd(window)?; - // SAFETY: `hwnd` is the live window handle `hwnd()` just returned, used on the window's own thread. - unsafe { - let style = GetWindowLongPtrW(hwnd, GWL_STYLE) as u32; - let style = if resizable { - style | WS_THICKFRAME | WS_MAXIMIZEBOX - } else { - style & !(WS_THICKFRAME | WS_MAXIMIZEBOX) - }; - SetWindowLongPtrW(hwnd, GWL_STYLE, style as isize); - SetWindowPos( - hwnd, - std::ptr::null_mut(), - 0, - 0, - 0, - 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED, - ); - } - Ok(()) - } - - /// `ShowWindowAsync` rather than `ShowWindow`: the synchronous call delivers - /// `WM_SHOWWINDOW`/`WM_SIZE`/`WM_MOVE` before it returns, and GPUI's window - /// procedure re-enters the window state that the caller is inside, which - /// logs "RefCell already borrowed" (and drops the notification). The async - /// form queues the same messages and returns, which is what GPUI's own - /// `minimize` and `zoom` use. - pub fn show(window: &mut Window) -> Result<(), String> { - let hwnd = hwnd(window)?; - // SAFETY: `hwnd` is the live window handle `hwnd()` just returned, used on the window's own thread. - unsafe { - // A window hidden while minimized stays minimized under SW_SHOW. - let command = if IsIconic(hwnd) != 0 { - SW_RESTORE - } else { - SW_SHOW - }; - ShowWindowAsync(hwnd, command) - }; - Ok(()) - } - - pub fn hide(window: &mut Window) -> Result<(), String> { - let hwnd = hwnd(window)?; - // SAFETY: `hwnd` is the live window handle `hwnd()` just returned, used on the window's own thread. - unsafe { ShowWindowAsync(hwnd, SW_HIDE) }; - Ok(()) - } - - pub fn is_minimized(window: &Window) -> bool { - match hwnd(window) { - // SAFETY: `hwnd` is the live window handle `hwnd()` just returned, used on the window's own thread. - Ok(hwnd) => unsafe { IsIconic(hwnd) != 0 }, - Err(_) => false, - } - } - - /// Whether the window is not being presented. `IsWindowVisible` is false - /// for a window created with `show: false` (the offscreen test windows) and - /// after `ShowWindow(SW_HIDE)`, and stays true for a window that is merely - /// covered, which is what the test driver wants to distinguish. - pub fn is_hidden(window: &Window) -> bool { - match hwnd(window) { - // SAFETY: `hwnd` is the live window handle `hwnd()` just returned, used on the window's own thread. - Ok(hwnd) => unsafe { IsWindowVisible(hwnd) == 0 }, - Err(_) => false, - } - } - - pub fn is_maximized(window: &Window) -> bool { - match hwnd(window) { - // SAFETY: `hwnd` is the live window handle `hwnd()` just returned, used on the window's own thread. - Ok(hwnd) => unsafe { IsZoomed(hwnd) != 0 }, - Err(_) => false, - } - } - - /// Sets the popover up while it is still hidden: out of the taskbar and the - /// Alt+Tab list, above the other topmost windows, placed under (or over) its - /// tray icon, and at its own size. - /// - /// `x`, `y`, `width` and `height` are in points; `SetWindowPos` takes physical - /// pixels, so they are scaled by the window's own scale factor. - pub fn prepare_popover( - window: &mut Window, - x: f32, - y: f32, - width: f32, - height: f32, - ) -> Result<(), String> { - use windows_sys::Win32::UI::WindowsAndMessaging::{ - GetWindowLongPtrW, SetWindowLongPtrW, GWL_EXSTYLE, WS_EX_APPWINDOW, WS_EX_TOOLWINDOW, - }; - let hwnd = hwnd(window)?; - let scale = window.scale_factor(); - // SAFETY: `hwnd` is the live window handle `hwnd()` just returned, used on the window's own thread. - let placed = unsafe { - // A tool window has no taskbar button, which is also what a popover - // that shows the app's icon there would otherwise leave behind. - let style = GetWindowLongPtrW(hwnd, GWL_EXSTYLE) as u32; - SetWindowLongPtrW( - hwnd, - GWL_EXSTYLE, - ((style | WS_EX_TOOLWINDOW) & !WS_EX_APPWINDOW) as isize, - ); - // Topmost, because the windows a tray click leaves open are: the - // taskbar's hidden-icons flyout is a topmost window, and a normal - // window opened from an icon inside it would appear behind it. A - // topmost window shown later goes above the topmost ones already - // there. - SetWindowPos( - hwnd, - HWND_TOPMOST, - (x * scale).round() as i32, - (y * scale).round() as i32, - (width * scale).round() as i32, - (height * scale).round() as i32, - SWP_NOACTIVATE | SWP_FRAMECHANGED, - ) - }; - if placed == 0 { - Err("SetWindowPos failed".to_string()) - } else { - Ok(()) - } - } - - /// Shows the popover, which activates it, so it takes focus — and so loses it - /// when the user clicks elsewhere, which is what dismisses it. A window that - /// was created hidden stays hidden until this. - /// - /// `ShowWindowAsync`, like `show`: the synchronous calls (`ShowWindow`, - /// `SetForegroundWindow`) deliver the activation messages before they return, - /// into a window procedure that is already inside GPUI's window state, which - /// logs "RefCell already borrowed". - pub fn activate_popover(window: &Window) -> Result<(), String> { - let hwnd = hwnd(window)?; - // SAFETY: `hwnd` is the live window handle `hwnd()` just returned, used on the window's own thread. - unsafe { ShowWindowAsync(hwnd, SW_SHOW) }; - Ok(()) - } -} - -/// X11: the window calls GPUI does not expose, over a second X connection. -/// Wayland has no absolute positioning or raise, so a Wayland session reports -/// `unsupported`. -/// -/// TODO: never built or run on Linux. -#[cfg(target_os = "linux")] -mod imp { - use gpui::Window; - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - use x11_dl::xlib; - - const UNSUPPORTED_WAYLAND: &str = - "Wayland has no absolute window positioning or raise; use X11 for these calls"; - - fn wayland() -> bool { - crate::desktop::capabilities::is_wayland() - } - - fn window_id(window: &Window) -> Result { - let handle = HasWindowHandle::window_handle(window) - .map_err(|error| format!("no platform window handle: {error}"))?; - match handle.as_raw() { - RawWindowHandle::Xlib(xlib_handle) => Ok(xlib_handle.window as u64), - RawWindowHandle::Xcb(xcb) => Ok(xcb.window.get() as u64), - _ => Err("the session is not X11".to_string()), - } - } - - /// Run `f` with a fresh X connection. GPUI owns its own connection and does - /// not expose it, and the X protocol allows a second client to move and - /// raise another client's window. - fn with_display(f: impl FnOnce(&xlib::Xlib, *mut xlib::Display) -> R) -> Result { - if wayland() { - return Err(UNSUPPORTED_WAYLAND.to_string()); - } - let xlib = xlib::Xlib::open().map_err(|error| format!("no X11 library: {error}"))?; - // SAFETY: the display from `XOpenDisplay` is null-checked before use and closed once, after `f` returns. - unsafe { - let display = (xlib.XOpenDisplay)(std::ptr::null()); - if display.is_null() { - return Err("could not open an X11 display".to_string()); - } - let result = f(&xlib, display); - (xlib.XCloseDisplay)(display); - Ok(result) - } - } - - /// Xlib's functions live on the loaded library, so every call goes through - /// the `xlib` instance `with_display` hands to the closure. - fn with_window( - window: &Window, - f: impl FnOnce(&xlib::Xlib, *mut xlib::Display, xlib::Window) -> R, - ) -> Result { - let id = window_id(window)?; - with_display(|xlib, display| f(xlib, display, id as xlib::Window)) - } - - /// Asks the window manager not to decorate the window: `_MOTIF_WM_HINTS` with - /// no decorations, which Openbox, Xfwm, Mutter, KWin and most others honour. - /// For a window that asked for no chrome at all where the window manager - /// cannot leave the drawing to the app (no `_GTK_FRAME_EXTENTS`), so it would - /// otherwise keep its title bar. - pub fn remove_server_frame(window: &Window) -> Result<(), String> { - // SAFETY: `display` is an open connection and `id` a window id for the whole closure; `with_display` closes the connection afterwards. - with_window(window, |xlib, display, id| unsafe { - let motif = (xlib.XInternAtom)(display, b"_MOTIF_WM_HINTS\0".as_ptr() as *const _, 0); - if motif != 0 { - let data: [u32; 5] = [1 << 1, 0, 0, 0, 0]; - (xlib.XChangeProperty)( - display, - id, - motif, - motif, - 32, - xlib::PropModeReplace, - data.as_ptr() as *const std::os::raw::c_uchar, - 5, - ); - (xlib.XFlush)(display); - } - }) - } - - pub fn set_position(window: &mut Window, x: f32, y: f32) -> Result<(), String> { - // SAFETY: `display` is an open connection and `id` a window id for the whole closure; `with_display` closes the connection afterwards. - with_window(window, |xlib, display, id| unsafe { - (xlib.XMoveWindow)(display, id, x.round() as i32, y.round() as i32); - (xlib.XFlush)(display); - }) - } - - pub fn set_visible_on_all_workspaces( - _window: &mut Window, - _visible: bool, - ) -> Result<(), String> { - Ok(()) - } - - pub fn set_always_on_top(window: &mut Window, on: bool) -> Result<(), String> { - // SAFETY: `display` is an open connection and `id` a window id for the whole closure; `with_display` closes the connection afterwards. - with_window(window, |xlib, display, id| unsafe { - let root = (xlib.XDefaultRootWindow)(display); - let state = (xlib.XInternAtom)(display, b"_NET_WM_STATE\0".as_ptr() as *const _, 0); - let above = - (xlib.XInternAtom)(display, b"_NET_WM_STATE_ABOVE\0".as_ptr() as *const _, 0); - let mut event: xlib::XEvent = std::mem::zeroed(); - { - let message = &mut event.client_message; - message.type_ = xlib::ClientMessage; - message.display = display; - message.window = id; - message.message_type = state; - message.format = 32; - // data = [action (1 adds, 0 removes), property, 0, source indication] - message.data.set_long(0, i64::from(on)); - message.data.set_long(1, above as i64); - message.data.set_long(3, 1); - } - (xlib.XSendEvent)( - display, - root, - 0, - xlib::SubstructureRedirectMask | xlib::SubstructureNotifyMask, - &mut event, - ); - if on { - (xlib.XRaiseWindow)(display, id); - } - (xlib.XFlush)(display); - }) - } - - /// Keeps a mapped window out of the taskbar and the pager. - pub fn skip_taskbar(window: &mut Window) -> Result<(), String> { - // SAFETY: `display` is an open connection and `id` a window id for the whole closure; `with_display` closes the connection afterwards. - with_window(window, |xlib, display, id| unsafe { - let root = (xlib.XDefaultRootWindow)(display); - let atom = |name: &[u8]| (xlib.XInternAtom)(display, name.as_ptr() as *const _, 0); - let mut event: xlib::XEvent = std::mem::zeroed(); - { - let message = &mut event.client_message; - message.type_ = xlib::ClientMessage; - message.display = display; - message.window = id; - message.message_type = atom(b"_NET_WM_STATE\0"); - message.format = 32; - message.data.set_long(0, 1); - message - .data - .set_long(1, atom(b"_NET_WM_STATE_SKIP_TASKBAR\0") as i64); - message - .data - .set_long(2, atom(b"_NET_WM_STATE_SKIP_PAGER\0") as i64); - message.data.set_long(3, 1); - } - (xlib.XSendEvent)( - display, - root, - 0, - xlib::SubstructureRedirectMask | xlib::SubstructureNotifyMask, - &mut event, - ); - (xlib.XFlush)(display); - }) - } - - pub fn set_min_size(window: &mut Window, width: f32, height: f32) -> Result<(), String> { - // SAFETY: `display` is an open connection and `id` a window id for the whole closure; `with_display` closes the connection afterwards. - with_window(window, |xlib, display, id| unsafe { - let mut hints: xlib::XSizeHints = std::mem::zeroed(); - hints.flags = xlib::PMinSize; - hints.min_width = width.round() as i32; - hints.min_height = height.round() as i32; - (xlib.XSetWMNormalHints)(display, id, &mut hints); - (xlib.XFlush)(display); - }) - } - - pub fn set_max_size(window: &mut Window, width: f32, height: f32) -> Result<(), String> { - // SAFETY: `display` is an open connection and `id` a window id for the whole closure; `with_display` closes the connection afterwards. - with_window(window, |xlib, display, id| unsafe { - let mut hints: xlib::XSizeHints = std::mem::zeroed(); - hints.flags = xlib::PMaxSize; - hints.max_width = width.round() as i32; - hints.max_height = height.round() as i32; - (xlib.XSetWMNormalHints)(display, id, &mut hints); - (xlib.XFlush)(display); - }) - } - - pub fn set_resizable(_window: &mut Window, _resizable: bool) -> Result<(), String> { - // TODO: GPUI sets the size hints from `WindowOptions::is_resizable`; - // changing them at runtime needs the WM_NORMAL_HINTS pair above plus a - // `_MOTIF_WM_HINTS` update. - Err("changing resizability at runtime is not implemented on X11 yet".to_string()) - } - - pub fn show(window: &mut Window) -> Result<(), String> { - // SAFETY: `display` is an open connection and `id` a window id for the whole closure; `with_display` closes the connection afterwards. - with_window(window, |xlib, display, id| unsafe { - (xlib.XMapWindow)(display, id); - (xlib.XFlush)(display); - }) - } - - pub fn hide(window: &mut Window) -> Result<(), String> { - // SAFETY: `display` is an open connection and `id` a window id for the whole closure; `with_display` closes the connection afterwards. - with_window(window, |xlib, display, id| unsafe { - (xlib.XUnmapWindow)(display, id); - (xlib.XFlush)(display); - }) - } - - pub fn is_minimized(window: &Window) -> bool { - // `XGetWindowAttributes` reports `IsUnmapped` for a hidden window, but - // X11 has no "minimized" state of its own (the WM owns it). - // SAFETY: `display` is an open connection and `id` a window id for the whole closure; `with_display` closes the connection afterwards. - with_window(window, |xlib, display, id| unsafe { - let mut attributes: xlib::XWindowAttributes = std::mem::zeroed(); - if (xlib.XGetWindowAttributes)(display, id, &mut attributes) == 0 { - return false; - } - attributes.map_state == xlib::IsUnmapped - }) - .unwrap_or(false) - } - - pub fn is_maximized(window: &Window) -> bool { - // GPUI keeps the window manager's `_NET_WM_STATE` as it reports it. - window.is_maximized() - } - - /// Turns a just-created, still-unmapped window into a tray popover. - /// - /// The tray popover cannot be `WindowKind::PopUp`: GPUI makes that - /// override-redirect, so the window manager never focuses it, its - /// `install_activation_observer` never sees a deactivation, and it cannot be - /// dismissed by clicking away. It is instead an ordinary undecorated window - /// that the window manager manages — the same shape Electron's Linux tray - /// menu uses (a frameless window with skip-taskbar and always-on-top). The - /// properties below are set on the still-unmapped window so nothing flashes - /// in the taskbar or appears decorated first. - /// - /// Call before the window is mapped (see `windows::open_window`, which opens - /// the popover with `show: false` and maps it afterwards); `_NET_WM_STATE` - /// and `_NET_WM_WINDOW_TYPE` are read when the window is mapped. - pub fn prepare_popover( - window: &mut Window, - x: f32, - y: f32, - width: f32, - height: f32, - ) -> Result<(), String> { - // SAFETY: `display` is an open connection and `id` a window id for the whole closure; `with_display` closes the connection afterwards. - with_window(window, |xlib, display, id| unsafe { - // A hidden window is placed by the user, not the window manager: - // USPosition with the exact origin, so a WM that honours hints maps - // it where the tray icon is instead of centring it. - let mut hints: xlib::XSizeHints = std::mem::zeroed(); - hints.flags = xlib::USPosition | xlib::PSize; - hints.x = x.round() as i32; - hints.y = y.round() as i32; - hints.width = width.round() as i32; - hints.height = height.round() as i32; - (xlib.XSetWMNormalHints)(display, id, &mut hints); - - // `_NET_WM_WINDOW_TYPE_UTILITY`: a small tool window, which window - // managers keep out of the taskbar and alt-tab. `DIALOG` would want - // a `WM_TRANSIENT_FOR` parent and a tray-only app has none. - set_atoms( - xlib, - display, - id, - "_NET_WM_WINDOW_TYPE", - &["_NET_WM_WINDOW_TYPE_UTILITY"], - ); - - // `_NET_WM_STATE`: never in the taskbar or pager, always above. - set_atoms( - xlib, - display, - id, - "_NET_WM_STATE", - &[ - "_NET_WM_STATE_SKIP_TASKBAR", - "_NET_WM_STATE_SKIP_PAGER", - "_NET_WM_STATE_ABOVE", - ], - ); - - // Decorations off. GPUI's `request_decorations(Client)` already sets - // the motif hint for a frameless window; this is idempotent and also - // covers a server-decorations fallback. The five words are - // flags=MWM_HINTS_DECORATIONS, functions=0, decorations=0, ... - let motif = (xlib.XInternAtom)(display, b"_MOTIF_WM_HINTS\0".as_ptr() as *const _, 0); - if motif != 0 { - let data: [u32; 5] = [1 << 1, 0, 0, 0, 0]; - (xlib.XChangeProperty)( - display, - id, - motif, - motif, - 32, - xlib::PropModeReplace, - data.as_ptr() as *const std::os::raw::c_uchar, - 5, - ); - } - - (xlib.XFlush)(display); - }) - } - - /// Sets an `ATOM[]` property to the interned atoms named in `values`. - /// - /// Replaces the property (`PropModeReplace`), which is what the window - /// manager reads once, when the window is mapped. - /// - /// # Safety - /// - /// `display` must be an open X connection and `window` a valid window id on it. - unsafe fn set_atoms( - xlib: &xlib::Xlib, - display: *mut xlib::Display, - window: xlib::Window, - property: &str, - values: &[&str], - ) { - let property_atom = - (xlib.XInternAtom)(display, format!("{property}\0").as_ptr() as *const _, 0); - if property_atom == 0 { - return; - } - let atoms: Vec = values - .iter() - .map(|value| (xlib.XInternAtom)(display, format!("{value}\0").as_ptr() as *const _, 0)) - .filter(|atom| *atom != 0) - .collect(); - if atoms.is_empty() { - return; - } - (xlib.XChangeProperty)( - display, - window, - property_atom, - xlib::XA_ATOM, - 32, - xlib::PropModeReplace, - atoms.as_ptr() as *const std::os::raw::c_uchar, - atoms.len() as i32, - ); - } - - /// Asks the window manager to make `window` the active window. - /// - /// `activate_window()` sends `_NET_ACTIVE_WINDOW` with source indication 1 - /// (a normal application request) and `CurrentTime`. Both are the parts a - /// focus stealing prevention check distrusts: the request carries no - /// timestamp from the event that caused it (a tray click arrives over D-Bus, - /// which has no X timestamp), so a strict window manager may map the popover - /// without focusing it — and without focus the popover can never see the - /// deactivation that dismisses it. Source indication 2 (a pager / taskbar) - /// is trusted to set focus, and a fresh server timestamp avoids the - /// "timestamp in the past" rejection. - pub fn activate_popover(window: &Window) -> Result<(), String> { - // SAFETY: `display` is an open connection and `id` a window id for the whole closure; `with_display` closes the connection afterwards. - with_window(window, |xlib, display, id| unsafe { - let root = (xlib.XDefaultRootWindow)(display); - let atom = (xlib.XInternAtom)(display, b"_NET_ACTIVE_WINDOW\0".as_ptr() as *const _, 0); - let mut event: xlib::XEvent = std::mem::zeroed(); - { - let message = &mut event.client_message; - message.type_ = xlib::ClientMessage; - message.display = display; - message.window = id; - message.message_type = atom; - message.format = 32; - // data = [source indication, timestamp, requestor, 0, 0] - message.data.set_long(0, 2); - message.data.set_long(1, xlib::CurrentTime as i64); - message.data.set_long(2, id as i64); - } - (xlib.XSendEvent)( - display, - root, - 0, - xlib::SubstructureRedirectMask | xlib::SubstructureNotifyMask, - &mut event, - ); - (xlib.XFlush)(display); - }) - } -} - -#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))] -mod imp { - use gpui::Window; - - const UNSUPPORTED: &str = - "window positioning and raising are not implemented on this platform yet"; - - pub fn set_position(_window: &mut Window, _x: f32, _y: f32) -> Result<(), String> { - Err(UNSUPPORTED.to_string()) - } - pub fn set_always_on_top(_window: &mut Window, _on: bool) -> Result<(), String> { - Err(UNSUPPORTED.to_string()) - } - pub fn set_visible_on_all_workspaces( - _window: &mut Window, - _visible: bool, - ) -> Result<(), String> { - Err(UNSUPPORTED.to_string()) - } - pub fn set_min_size(_window: &mut Window, _w: f32, _h: f32) -> Result<(), String> { - Err(UNSUPPORTED.to_string()) - } - pub fn set_max_size(_window: &mut Window, _w: f32, _h: f32) -> Result<(), String> { - Err(UNSUPPORTED.to_string()) - } - pub fn set_resizable(_window: &mut Window, _resizable: bool) -> Result<(), String> { - Err(UNSUPPORTED.to_string()) - } - pub fn show(_window: &mut Window) -> Result<(), String> { - Err(UNSUPPORTED.to_string()) - } - pub fn hide(_window: &mut Window) -> Result<(), String> { - Err(UNSUPPORTED.to_string()) - } - pub fn is_minimized(_window: &Window) -> bool { - false - } - pub fn is_maximized(window: &Window) -> bool { - window.is_maximized() - } - pub fn prepare_popover( - _window: &mut Window, - _x: f32, - _y: f32, - _width: f32, - _height: f32, - ) -> Result<(), String> { - Err(UNSUPPORTED.to_string()) - } - pub fn activate_popover(_window: &Window) -> Result<(), String> { - Ok(()) - } -} - -#[cfg(not(target_os = "macos"))] -pub use imp::*; - -#[cfg(target_os = "macos")] -pub fn set_accessory_app(accessory: bool) { - use objc::{class, msg_send, sel, sel_impl}; - const REGULAR: isize = 0; - const ACCESSORY: isize = 1; - // SAFETY: the shared `NSApplication` is messaged from the main thread. - unsafe { - let app: cocoa::base::id = msg_send![class!(NSApplication), sharedApplication]; - let policy = if accessory { ACCESSORY } else { REGULAR }; - let _: bool = msg_send![app, setActivationPolicy: policy]; - } -} - -#[cfg(not(target_os = "macos"))] -pub fn set_accessory_app(_accessory: bool) {} - -/// Gives an unbundled run (`cargo run`) a Dock icon. A `.app` takes its icon -/// from its bundle, so a bundled run is left alone. -#[cfg(target_os = "macos")] -pub fn set_dock_icon(path: &std::path::Path) { - use cocoa::base::{id, nil}; - use cocoa::foundation::NSString; - use objc::{class, msg_send, sel, sel_impl}; - let Some(path) = path.to_str() else { - return; - }; - // SAFETY: the shared `NSApplication` and `NSBundle` are messaged from the - // main thread; the image is retained by the application once set. - unsafe { - let bundle: id = msg_send![class!(NSBundle), mainBundle]; - let bundle_path: id = msg_send![bundle, bundlePath]; - let suffix = NSString::alloc(nil).init_str(".app"); - let bundled: bool = msg_send![bundle_path, hasSuffix: suffix]; - let _: () = msg_send![suffix, release]; - if bundled { - return; - } - let file = NSString::alloc(nil).init_str(path); - let image: id = msg_send![class!(NSImage), alloc]; - let image: id = msg_send![image, initWithContentsOfFile: file]; - let _: () = msg_send![file, release]; - if image.is_null() { - log::warn!("[desktop] could not load the Dock icon {path}"); - return; - } - let app: id = msg_send![class!(NSApplication), sharedApplication]; - let _: () = msg_send![app, setApplicationIconImage: image]; - let _: () = msg_send![image, release]; - } -} - -#[cfg(not(target_os = "macos"))] -pub fn set_dock_icon(_path: &std::path::Path) {} - -/// Gives a window its icon on Windows, which is what the title bar and the -/// taskbar show. The executable carries no icon of its own in a dev build, so -/// without this the window keeps the default one. -/// -/// `WM_SETICON` takes an `HICON`, and Windows (Vista and later) builds one from -/// PNG bytes directly, so the file is passed through unchanged. One icon is -/// made per size: the large one for the taskbar, the small one for the title -/// bar. -#[cfg(target_os = "windows")] -pub fn set_window_icon(window: &gpui::Window, path: &std::path::Path) { - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - use windows_sys::Win32::UI::WindowsAndMessaging::{ - CreateIconFromResourceEx, GetSystemMetrics, SendMessageW, ICON_BIG, ICON_SMALL, - LR_DEFAULTCOLOR, SM_CXICON, SM_CXSMICON, WM_SETICON, - }; - - let Ok(bytes) = std::fs::read(path) else { - log::warn!( - "[desktop] could not read the window icon {}", - path.display() - ); - return; - }; - let Ok(handle) = HasWindowHandle::window_handle(window) else { - return; - }; - let RawWindowHandle::Win32(win32) = handle.as_raw() else { - return; - }; - let hwnd = win32.hwnd.get() as _; - // The icon resource version `CreateIconFromResourceEx` expects for an icon. - const ICON_VERSION: u32 = 0x0003_0000; - for (metric, which) in [(SM_CXICON, ICON_BIG), (SM_CXSMICON, ICON_SMALL)] { - // SAFETY: `bytes` is alive for the call and the length matches it; `hwnd` - // comes from the window's raw handle, which GPUI keeps valid while the - // window lives. The icon is handed to the window, which owns it after that. - unsafe { - let edge = GetSystemMetrics(metric); - let icon = CreateIconFromResourceEx( - bytes.as_ptr(), - bytes.len() as u32, - 1, - ICON_VERSION, - edge, - edge, - LR_DEFAULTCOLOR, - ); - if icon.is_null() { - log::warn!( - "[desktop] could not build the window icon from {}", - path.display() - ); - continue; - } - SendMessageW(hwnd, WM_SETICON, which as usize, icon as isize); - } - } -} - -#[cfg(not(target_os = "windows"))] -pub fn set_window_icon(_window: &gpui::Window, _path: &std::path::Path) {} - -/// Gives a window the app's icon, as a dev run is told it through -/// `RN_GPUI_APP_ICON`. For every window the app opens: the icon is per window on -/// Windows, so the one opened at startup is not enough. A packaged app has its -/// icon in its executable, and the variable is unset. -pub fn apply_app_icon(window: &gpui::Window) { - if let Some(icon) = std::env::var_os("RN_GPUI_APP_ICON") { - set_window_icon(window, std::path::Path::new(&icon)); - } -} - -#[cfg(target_os = "macos")] -pub fn disable_window_animation(window: &mut gpui::Window) { - use cocoa::base::id; - use objc::{msg_send, sel, sel_impl}; - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - - const NONE: i64 = 2; - let Ok(handle) = HasWindowHandle::window_handle(window) else { - return; - }; - if let RawWindowHandle::AppKit(appkit) = handle.as_raw() { - // SAFETY: `ns_view` comes from the window's raw handle, which GPUI keeps valid while the window lives. - unsafe { - let ns_view = appkit.ns_view.as_ptr() as id; - let native: id = msg_send![ns_view, window]; - if !native.is_null() { - let _: () = msg_send![native, setAnimationBehavior: NONE]; - } - } - } -} - -#[cfg(not(target_os = "macos"))] -pub fn disable_window_animation(_window: &mut gpui::Window) {} - -#[cfg(target_os = "macos")] -pub fn style_as_popover(window: &mut gpui::Window) { - use cocoa::base::{id, NO, YES}; - use objc::{msg_send, sel, sel_impl}; - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - - let Ok(handle) = HasWindowHandle::window_handle(window) else { - return; - }; - if let RawWindowHandle::AppKit(appkit) = handle.as_raw() { - // SAFETY: `ns_view` comes from the window's raw handle, which GPUI keeps valid while the window lives. - unsafe { - let ns_view = appkit.ns_view.as_ptr() as id; - let native: id = msg_send![ns_view, window]; - if native.is_null() { - return; - } - let _: () = msg_send![native, setMovable: NO]; - let _: () = msg_send![native, setMovableByWindowBackground: NO]; - let _: () = msg_send![native, setHasShadow: YES]; - // NSWindowCloseButton, NSWindowMiniaturizeButton, NSWindowZoomButton. - for button in 0..3u64 { - let button: id = msg_send![native, standardWindowButton: button]; - if !button.is_null() { - let _: () = msg_send![button, setHidden: YES]; - } - } - } - } -} - -#[cfg(not(target_os = "macos"))] -pub fn style_as_popover(_window: &mut gpui::Window) {} - -/// The parts of a window's chrome AppKit draws itself: the traffic lights, the -/// shadow and the line under the title bar. A window the app styles entirely -/// draws its own. -#[cfg(target_os = "macos")] -pub fn style_window( - window: &mut gpui::Window, - buttons: bool, - shadow: bool, - title_bar: crate::bootstrap::WindowTitleBar, -) { - use cocoa::base::{id, NO, YES}; - use objc::{msg_send, sel, sel_impl}; - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - - let custom_bar = title_bar.is_custom(); - if buttons && shadow && !custom_bar { - return; - } - let Ok(handle) = HasWindowHandle::window_handle(window) else { - return; - }; - if let RawWindowHandle::AppKit(appkit) = handle.as_raw() { - // SAFETY: `ns_view` comes from the window's raw handle, which GPUI keeps valid while the window lives. - unsafe { - let ns_view = appkit.ns_view.as_ptr() as id; - let native: id = msg_send![ns_view, window]; - if native.is_null() { - return; - } - if !shadow { - let _: () = msg_send![native, setHasShadow: NO]; - } - if custom_bar { - // NSTitlebarSeparatorStyleNone: the app draws what is under the bar. - let _: () = msg_send![native, setTitlebarSeparatorStyle: 1i64]; - } - if title_bar == crate::bootstrap::WindowTitleBar::Borderless { - // NSWindowStyleMaskBorderless: no title bar, border line or system - // corners. GPUI's window class still becomes key, so it takes input. - let _: () = msg_send![native, setStyleMask: 0u64]; - // Changing the mask resets the first responder, and key events - // go to it. - let _: () = msg_send![native, makeFirstResponder: ns_view]; - } - if !buttons { - // NSWindowCloseButton, NSWindowMiniaturizeButton, NSWindowZoomButton. - for button in 0..3u64 { - let button: id = msg_send![native, standardWindowButton: button]; - if !button.is_null() { - let _: () = msg_send![button, setHidden: YES]; - } - } - } - } - } -} - -#[cfg(not(target_os = "macos"))] -pub fn style_window( - _window: &mut gpui::Window, - _buttons: bool, - _shadow: bool, - _title_bar: crate::bootstrap::WindowTitleBar, -) { - // A window that asked for no chrome whose frame the window manager kept - // anyway (it cannot leave the drawing to the app) is stripped of it. - #[cfg(target_os = "linux")] - if _title_bar == crate::bootstrap::WindowTitleBar::Borderless - && !crate::desktop::capabilities::is_wayland() - && matches!(_window.window_decorations(), gpui::Decorations::Server) - { - let _ = remove_server_frame(_window); - } -} - -/// `tray-icon` reports physical pixels; windows and menus are placed in points. -#[cfg(target_os = "macos")] -pub fn primary_screen_scale() -> f32 { - use cocoa::base::id; - use objc::{class, msg_send, sel, sel_impl}; - - // SAFETY: `NSScreen` class messages return objects that are null-checked before use. - unsafe { - let screens: id = msg_send![class!(NSScreen), screens]; - let screen: id = msg_send![screens, firstObject]; - if screen.is_null() { - return 1.0; - } - let scale: f64 = msg_send![screen, backingScaleFactor]; - if scale > 0.0 { - scale as f32 - } else { - 1.0 - } - } -} - -/// Windows reports the tray icon's rectangle in physical pixels as well, and the -/// popover is placed in points, so the rectangle has to be divided by the scale -/// of the display the taskbar is on — the primary one. -#[cfg(target_os = "windows")] -pub fn primary_screen_scale() -> f32 { - use windows_sys::Win32::UI::HiDpi::GetDpiForSystem; - // SAFETY: `GetDpiForSystem` takes no arguments and only reads the process's DPI state. - let dpi = unsafe { GetDpiForSystem() }; - if dpi == 0 { - 1.0 - } else { - dpi as f32 / 96.0 - } -} - -#[cfg(not(any(target_os = "macos", target_os = "windows")))] -pub fn primary_screen_scale() -> f32 { - 1.0 -} - -/// The usable area of the display holding the point `(x, y)` — the screen minus -/// the taskbar — as `(x, y, width, height)` in points. `None` where it cannot be -/// asked, and the popover is then left where the icon puts it. -#[cfg(target_os = "windows")] -pub fn work_area_at(x: f32, y: f32) -> Option<(f32, f32, f32, f32)> { - use windows_sys::Win32::Foundation::POINT; - use windows_sys::Win32::Graphics::Gdi::{ - GetMonitorInfoW, MonitorFromPoint, MONITORINFO, MONITOR_DEFAULTTONEAREST, - }; - let scale = primary_screen_scale(); - let point = POINT { - x: (x * scale).round() as i32, - y: (y * scale).round() as i32, - }; - // SAFETY: `monitor` comes from `MonitorFromPoint` and is checked for null; `info` is a - // properly sized, initialised `MONITORINFO` that `GetMonitorInfoW` fills in. - unsafe { - let monitor = MonitorFromPoint(point, MONITOR_DEFAULTTONEAREST); - if monitor.is_null() { - return None; - } - let mut info: MONITORINFO = std::mem::zeroed(); - info.cbSize = std::mem::size_of::() as u32; - if GetMonitorInfoW(monitor, &mut info) == 0 { - return None; - } - let work = info.rcWork; - Some(( - work.left as f32 / scale, - work.top as f32 / scale, - (work.right - work.left) as f32 / scale, - (work.bottom - work.top) as f32 / scale, - )) - } -} - -#[cfg(target_os = "linux")] -pub fn work_area_at(_x: f32, _y: f32) -> Option<(f32, f32, f32, f32)> { - crate::desktop::work_area::read().map(|work| work.area) -} - -#[cfg(not(any(target_os = "windows", target_os = "linux")))] -pub fn work_area_at(_x: f32, _y: f32) -> Option<(f32, f32, f32, f32)> { - None -} - -/// What the OS itself has for a window: `(left, top, right, bottom, visible)`, in -/// physical pixels. GPUI's own bounds are what it believes, and for a window -/// created hidden on Windows the two have differed, so a test that wants to know -/// what a user sees asks the OS. -#[cfg(all(target_os = "windows", feature = "test-driver"))] -pub fn native_frame(window: &gpui::Window) -> Option<(i32, i32, i32, i32, bool)> { - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - use windows_sys::Win32::Foundation::RECT; - use windows_sys::Win32::UI::WindowsAndMessaging::{GetWindowRect, IsWindowVisible}; - let handle = HasWindowHandle::window_handle(window).ok()?; - let RawWindowHandle::Win32(win32) = handle.as_raw() else { - return None; - }; - let hwnd = win32.hwnd.get() as _; - let mut rect = RECT { - left: 0, - top: 0, - right: 0, - bottom: 0, - }; - // SAFETY: `hwnd` comes from the window's raw handle, which GPUI keeps valid while the window - // lives, and `rect` is a properly initialised `RECT` the call fills in. - unsafe { - if GetWindowRect(hwnd, &mut rect) == 0 { - return None; - } - Some(( - rect.left, - rect.top, - rect.right, - rect.bottom, - IsWindowVisible(hwnd) != 0, - )) - } -} - -/// Paints the window's own background, behind the content: `argb` is `0xAARRGGBB`. -#[cfg(target_os = "macos")] -pub fn set_background_color(window: &mut gpui::Window, argb: u32) -> Result<(), String> { - use cocoa::base::id; - use objc::{class, msg_send, sel, sel_impl}; - - let native = imp::ns_window(window)?; - let channel = |shift: u32| f64::from((argb >> shift) & 0xFF) / 255.0; - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - let color: id = msg_send![ - class!(NSColor), - colorWithSRGBRed: channel(16) - green: channel(8) - blue: channel(0) - alpha: channel(24) - ]; - let _: () = msg_send![native, setBackgroundColor: color]; - } - Ok(()) -} - -#[cfg(not(target_os = "macos"))] -pub fn set_background_color(_window: &mut gpui::Window, _argb: u32) -> Result<(), String> { - Err("window background colors are not supported on this platform".to_string()) -} - -/// Gives the window's native chrome (title bar, traffic lights) a light or dark -/// look, or `None` to follow the system. -#[cfg(target_os = "macos")] -pub fn set_chrome_appearance(window: &mut gpui::Window, dark: Option) -> Result<(), String> { - use cocoa::base::{id, nil}; - use cocoa::foundation::NSString; - use objc::{class, msg_send, sel, sel_impl}; - - let native = imp::ns_window(window)?; - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - let appearance: id = match dark { - None => nil, - Some(dark) => { - let name = if dark { - "NSAppearanceNameDarkAqua" - } else { - "NSAppearanceNameAqua" - }; - msg_send![class!(NSAppearance), appearanceNamed: NSString::alloc(nil).init_str(name)] - } - }; - let _: () = msg_send![native, setAppearance: appearance]; - } - Ok(()) -} - -#[cfg(not(target_os = "macos"))] -pub fn set_chrome_appearance( - _window: &mut gpui::Window, - _dark: Option, -) -> Result<(), String> { - Err("a window's chrome appearance is not supported on this platform".to_string()) -} - -/// Prepares to show a window, returning what does it. The operating system -/// reports activation and size changes while it shows a window, and those -/// reach GPUI's window callbacks, which borrow the window; so the caller runs -/// the returned action once its own borrow of the window has ended. -#[cfg(target_os = "macos")] -pub fn show_later(window: &mut gpui::Window) -> Result, String> { - use cocoa::base::{id, nil}; - use objc::{msg_send, sel, sel_impl}; - - let native = imp::ns_window(window)? as usize; - Ok(Box::new(move || { - let native = native as id; - // SAFETY: `native` is the `NSWindow` of a window that is still open, and AppKit is only messaged from the main thread. - unsafe { - let miniaturized: bool = msg_send![native, isMiniaturized]; - if miniaturized { - let _: () = msg_send![native, deminiaturize: nil]; - } - if crate::desktop::background::enabled() - && !std::env::var("RN_GPUI_TEST_ON_TOP").is_ok_and(|value| value == "1") - { - let _: () = msg_send![native, orderBack: nil]; - } else if crate::desktop::background::enabled() { - let visible: bool = msg_send![native, isVisible]; - if !visible { - let _: () = msg_send![native, setAlphaValue: 0.0f64]; - } - let _: () = msg_send![native, orderFrontRegardless]; - } else { - // A window that was hidden has drawn nothing yet: it is shown - // clear, and `reveal_window` makes it opaque once its first - // frame has had time to be presented. - let visible: bool = msg_send![native, isVisible]; - if !visible { - let _: () = msg_send![native, setAlphaValue: 0.0f64]; - } - let _: () = msg_send![native, orderFront: nil]; - } - } - })) -} - -/// Makes a window opaque again after [`show_later`] showed it clear. -#[cfg(target_os = "macos")] -pub fn reveal_window(window: &mut gpui::Window) -> Result<(), String> { - use objc::{msg_send, sel, sel_impl}; - let native = imp::ns_window(window)?; - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - let _: () = msg_send![native, setAlphaValue: 1.0f64]; - } - Ok(()) -} - -#[cfg(not(target_os = "macos"))] -pub fn reveal_window(_window: &mut gpui::Window) -> Result<(), String> { - Ok(()) -} - -/// The window's opacity, where the platform says: 0 while it is being revealed. -#[cfg(target_os = "macos")] -pub fn window_alpha(window: &gpui::Window) -> Option { - use objc::{msg_send, sel, sel_impl}; - let native = imp::ns_window(window).ok()?; - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - let alpha: f64 = unsafe { msg_send![native, alphaValue] }; - Some(alpha as f32) -} - -#[cfg(not(target_os = "macos"))] -pub fn window_alpha(_window: &gpui::Window) -> Option { - // No other platform hides a window being revealed by making it transparent. - Some(1.0) -} - -/// Shows a window behind every other window, without making it key. A window -/// that other windows cover is occluded, and macOS stops presenting frames for -/// it, so a test that reads the screen back asks for the window to go in front -/// with `RN_GPUI_TEST_ON_TOP=1`: `orderFrontRegardless` does not activate the -/// app or give the window focus. -#[cfg(target_os = "macos")] -pub fn show_behind(window: &mut gpui::Window) -> Result<(), String> { - use cocoa::base::id; - use objc::{msg_send, sel, sel_impl}; - let native = imp::ns_window(window)?; - let on_top = std::env::var("RN_GPUI_TEST_ON_TOP").is_ok_and(|value| value == "1"); - // SAFETY: `native` is the live `NSWindow` from `ns_window`, and AppKit is only messaged from the main thread. - unsafe { - if on_top { - let _: () = msg_send![native, orderFrontRegardless]; - } else { - let _: () = msg_send![native, orderBack: std::ptr::null::()]; - } - } - Ok(()) -} - -#[cfg(not(target_os = "macos"))] -pub fn show_behind(_window: &mut gpui::Window) -> Result<(), String> { - Ok(()) -} - -#[cfg(not(target_os = "macos"))] -pub fn show_later(window: &mut gpui::Window) -> Result, String> { - show(window)?; - Ok(Box::new(|| {})) -} - -/// Prepares to hide a window; see [`show_later`]. -#[cfg(target_os = "macos")] -pub fn hide_later(window: &mut gpui::Window) -> Result, String> { - use cocoa::base::{id, nil}; - use objc::{msg_send, sel, sel_impl}; - - let native = imp::ns_window(window)? as usize; - Ok(Box::new(move || { - // SAFETY: `native` is the `NSWindow` of a window that is still open, and AppKit is only messaged from the main thread. - unsafe { - let _: () = msg_send![native as id, orderOut: nil]; - } - })) -} - -#[cfg(not(target_os = "macos"))] -pub fn hide_later(window: &mut gpui::Window) -> Result, String> { - hide(window)?; - Ok(Box::new(|| {})) -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/popover_placement.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/popover_placement.rs deleted file mode 100644 index 3437efa12d..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/popover_placement.rs +++ /dev/null @@ -1,398 +0,0 @@ -//! Where a tray popover goes on a desktop that does not say where the icon is. -//! -//! Wayland gives an app neither the icon's position nor the right to place a -//! window. What can be read is the work area, the screen less the space panels -//! and docks reserve, and from it which edge holds a panel. The popover is then -//! drawn at the end of that edge, where the tray sits, inside a window covering -//! the work area. An app, or a user, can choose the corner instead. -#![allow(dead_code)] - -/// How far a popover keeps from the edges of the work area it is anchored to. -pub const MARGIN: f32 = 8.0; - -/// The corner of the work area a popover is drawn in. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum Anchor { - /// The end of the thinnest reserved edge, which is where a panel's tray is. - #[default] - Auto, - TopLeft, - TopRight, - BottomLeft, - BottomRight, - Center, -} - -impl Anchor { - pub fn parse(text: &str) -> Option { - Some(match text.trim().to_ascii_lowercase().as_str() { - "auto" | "" => Self::Auto, - "top-left" => Self::TopLeft, - "top-right" => Self::TopRight, - "bottom-left" => Self::BottomLeft, - "bottom-right" => Self::BottomRight, - "center" | "centre" => Self::Center, - _ => return None, - }) - } -} - -/// How much of each edge of the screen panels and docks reserve, in points. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct Reserved { - pub left: f32, - pub top: f32, - pub right: f32, - pub bottom: f32, -} - -/// The reserved edges, from the size of the whole screen and the work area -/// `(x, y, width, height)` inside it. -pub fn reserved(screen: (f32, f32), work: (f32, f32, f32, f32)) -> Reserved { - let (screen_width, screen_height) = screen; - let (x, y, width, height) = work; - Reserved { - left: x.max(0.0), - top: y.max(0.0), - right: (screen_width - (x + width)).max(0.0), - bottom: (screen_height - (y + height)).max(0.0), - } -} - -/// The corner a tray is in: at the end of the thinnest edge that reserves -/// anything, since a panel is thinner than a dock beside it. Horizontal panels -/// keep the tray at their right end, vertical ones at their bottom. -pub fn auto_anchor(reserved: Reserved) -> Anchor { - let edges = [ - (reserved.top, Anchor::TopRight), - (reserved.bottom, Anchor::BottomRight), - (reserved.left, Anchor::BottomLeft), - (reserved.right, Anchor::BottomRight), - ]; - edges - .iter() - .filter(|(thickness, _)| *thickness >= 1.0) - .min_by(|a, b| a.0.total_cmp(&b.0)) - .map_or(Anchor::Center, |(_, anchor)| *anchor) -} - -/// The edge of the screen a panel is on. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Edge { - Top, - Bottom, - Left, - Right, -} - -/// The thinnest edge that reserves anything, which is the panel's. -pub fn tray_edge(reserved: Reserved) -> Option { - [ - (reserved.top, Edge::Top), - (reserved.bottom, Edge::Bottom), - (reserved.left, Edge::Left), - (reserved.right, Edge::Right), - ] - .iter() - .filter(|(thickness, _)| *thickness >= 1.0) - .min_by(|a, b| a.0.total_cmp(&b.0)) - .map(|(_, edge)| *edge) -} - -/// The work area in logical points. XWayland reports it in device pixels on some -/// compositors (GNOME) and in logical points on others (KDE), so it is compared -/// with the logical size of the screen that GPUI reports, and divided by the ratio -/// when it is larger. -pub fn logical_work_area( - screen: (f32, f32), - area: (f32, f32, f32, f32), - logical_screen: (f32, f32), -) -> ((f32, f32), (f32, f32, f32, f32)) { - let ratio = if logical_screen.0 > 0.0 { - screen.0 / logical_screen.0 - } else { - 1.0 - }; - if ratio < 1.05 { - return (screen, area); - } - ( - (screen.0 / ratio, screen.1 / ratio), - ( - area.0 / ratio, - area.1 / ratio, - area.2 / ratio, - area.3 / ratio, - ), - ) -} - -/// A click's position in logical points. Panels disagree about the units they -/// send: GNOME sends logical points, and KDE sends device pixels, which at a -/// scale of 2 are twice the logical values. The icon that was clicked is on a -/// panel, so the reading that lands inside the screen, on a strip a panel -/// reserves, is the right one; when neither does, a click outside the screen -/// can only be in device pixels. -pub fn logical_click( - click: (f32, f32), - scale: f32, - screen: (f32, f32), - reserved: Reserved, -) -> (f32, f32) { - if scale <= 1.0 { - return click; - } - let device = (click.0 / scale, click.1 / scale); - let on_screen = |p: (f32, f32)| p.0 >= 0.0 && p.1 >= 0.0 && p.0 <= screen.0 && p.1 <= screen.1; - let on_panel = |p: (f32, f32)| { - on_screen(p) - && (p.0 <= reserved.left - || p.0 >= screen.0 - reserved.right - || p.1 <= reserved.top - || p.1 >= screen.1 - reserved.bottom) - }; - match (on_panel(click), on_panel(device)) { - (true, false) => click, - (false, true) => device, - _ if !on_screen(click) => device, - _ => click, - } -} - -/// The origin, in the work area's own coordinates, of a popover of `size` when the -/// click on the icon said where it is: against the panel's edge and centred on the -/// click along it. Without a panel edge there is nothing to rest against, and the -/// popover is centred. -pub fn place_near( - click: (f32, f32), - reserved: Reserved, - area: (f32, f32), - size: (f32, f32), - margin: f32, - offset: (f32, f32), -) -> (f32, f32) { - let (area_width, area_height) = area; - let (width, height) = size; - let (x, y) = match tray_edge(reserved) { - Some(Edge::Top) => (click.0 - width / 2.0, margin), - Some(Edge::Bottom) => (click.0 - width / 2.0, area_height - height - margin), - Some(Edge::Left) => (margin, click.1 - height / 2.0), - Some(Edge::Right) => (area_width - width - margin, click.1 - height / 2.0), - None => ((area_width - width) / 2.0, (area_height - height) / 2.0), - }; - let max_x = (area_width - width - margin).max(0.0); - let max_y = (area_height - height - margin).max(0.0); - ( - (x + offset.0).clamp(margin.min(max_x), max_x), - (y + offset.1).clamp(margin.min(max_y), max_y), - ) -} - -/// The origin, in the work area's own coordinates, of a popover of `size` in a -/// work area of `area`, `margin` away from the edges it is anchored to and moved -/// by `offset`. The result is kept inside the area. -pub fn place( - anchor: Anchor, - reserved: Reserved, - area: (f32, f32), - size: (f32, f32), - margin: f32, - offset: (f32, f32), -) -> (f32, f32) { - let anchor = match anchor { - Anchor::Auto => auto_anchor(reserved), - other => other, - }; - let (area_width, area_height) = area; - let (width, height) = size; - let (x, y) = match anchor { - Anchor::TopLeft => (margin, margin), - Anchor::TopRight | Anchor::Auto => (area_width - width - margin, margin), - Anchor::BottomLeft => (margin, area_height - height - margin), - Anchor::BottomRight => (area_width - width - margin, area_height - height - margin), - Anchor::Center => ((area_width - width) / 2.0, (area_height - height) / 2.0), - }; - let max_x = (area_width - width).max(0.0); - let max_y = (area_height - height).max(0.0); - ( - (x + offset.0).clamp(0.0, max_x), - (y + offset.1).clamp(0.0, max_y), - ) -} - -/// The anchor and offset a user set in the environment, over what the app chose: -/// `RN_GPUI_TRAY_POPOVER_ANCHOR` (`top-right`, …) and `RN_GPUI_TRAY_POPOVER_OFFSET` -/// (`x,y` in points). -pub fn with_environment(anchor: Anchor, offset: (f32, f32)) -> (Anchor, (f32, f32)) { - let anchor = std::env::var("RN_GPUI_TRAY_POPOVER_ANCHOR") - .ok() - .and_then(|text| Anchor::parse(&text)) - .unwrap_or(anchor); - let offset = std::env::var("RN_GPUI_TRAY_POPOVER_OFFSET") - .ok() - .and_then(|text| { - let (x, y) = text.split_once(',')?; - Some((x.trim().parse().ok()?, y.trim().parse().ok()?)) - }) - .unwrap_or(offset); - (anchor, offset) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_reserved_edges_follow_from_the_work_area() { - let gnome = reserved((1920.0, 1080.0), (67.0, 32.0, 1853.0, 1048.0)); - assert_eq!( - gnome, - Reserved { - left: 67.0, - top: 32.0, - right: 0.0, - bottom: 0.0 - } - ); - let plasma = reserved((1920.0, 1080.0), (0.0, 0.0, 1920.0, 1034.0)); - assert_eq!(plasma.bottom, 46.0); - } - - #[test] - fn the_tray_is_at_the_end_of_the_thinnest_reserved_edge() { - // A top panel with a dock on the left: the panel is the thinner. - assert_eq!( - auto_anchor(reserved((1920.0, 1080.0), (67.0, 32.0, 1853.0, 1048.0))), - Anchor::TopRight - ); - // A taskbar at the bottom. - assert_eq!( - auto_anchor(reserved((1920.0, 1080.0), (0.0, 0.0, 1920.0, 1034.0))), - Anchor::BottomRight - ); - // A panel on the left, with the tray at its bottom. - assert_eq!( - auto_anchor(reserved((1920.0, 1080.0), (48.0, 0.0, 1872.0, 1080.0))), - Anchor::BottomLeft - ); - // Nothing reserved: nowhere to be near. - assert_eq!(auto_anchor(Reserved::default()), Anchor::Center); - } - - #[test] - fn a_popover_sits_in_its_corner_and_stays_inside() { - let none = Reserved::default(); - let area = (1853.0, 1048.0); - let size = (320.0, 200.0); - assert_eq!( - place(Anchor::TopRight, none, area, size, 8.0, (0.0, 0.0)), - (1525.0, 8.0) - ); - assert_eq!( - place(Anchor::BottomLeft, none, area, size, 8.0, (0.0, 0.0)), - (8.0, 840.0) - ); - // An offset moves it, and a huge one is stopped at the edge. - assert_eq!( - place(Anchor::TopRight, none, area, size, 8.0, (-50.0, 10.0)), - (1475.0, 18.0) - ); - assert_eq!( - place(Anchor::TopLeft, none, area, size, 8.0, (-500.0, -500.0)), - (0.0, 0.0) - ); - // Bigger than the area: pinned to its start. - assert_eq!( - place( - Anchor::BottomRight, - none, - (200.0, 100.0), - size, - 8.0, - (0.0, 0.0) - ), - (0.0, 0.0) - ); - } - - #[test] - fn a_click_centres_the_popover_along_the_panel() { - let top = reserved((1920.0, 1080.0), (67.0, 32.0, 1853.0, 1048.0)); - let area = (1853.0, 1048.0); - let size = (320.0, 200.0); - // A click in the middle of the panel centres the popover on it. - assert_eq!( - place_near((1000.0, 0.0), top, area, size, 8.0, (0.0, 0.0)), - (840.0, 8.0) - ); - // Near the right end, where a tray is, it is held a margin inside the edge. - assert_eq!( - place_near((1730.0, 0.0), top, area, size, 8.0, (0.0, 0.0)), - (1525.0, 8.0) - ); - // A taskbar at the bottom: the popover rests on it. - let bottom = reserved((1920.0, 1080.0), (0.0, 0.0, 1920.0, 1034.0)); - assert_eq!( - place_near( - (1659.0, 0.0), - bottom, - (1920.0, 1034.0), - size, - 8.0, - (0.0, 0.0) - ), - (1499.0, 826.0) - ); - // A panel on the left: centred on the click down it. - let left = reserved((1920.0, 1080.0), (48.0, 0.0, 1872.0, 1080.0)); - assert_eq!( - place_near((0.0, 900.0), left, (1872.0, 1080.0), size, 8.0, (0.0, 0.0)), - (8.0, 800.0) - ); - } - - #[test] - fn a_work_area_in_device_pixels_is_brought_to_logical_points() { - // GNOME at a scale of 2: the screen and the work area are doubled. - let (screen, area) = logical_work_area( - (1920.0, 1080.0), - (134.0, 64.0, 1786.0, 1016.0), - (960.0, 540.0), - ); - assert_eq!(screen, (960.0, 540.0)); - assert_eq!(area, (67.0, 32.0, 893.0, 508.0)); - // KDE already reports points, so nothing changes. - let same = logical_work_area((960.0, 540.0), (46.0, 0.0, 914.0, 540.0), (960.0, 540.0)); - assert_eq!(same.1, (46.0, 0.0, 914.0, 540.0)); - } - - #[test] - fn a_click_in_device_pixels_is_brought_to_logical_points() { - // A 1920x1080 screen at a scale of 2, with a 46-point panel on the left. - let screen = (960.0, 540.0); - let panel = reserved(screen, (46.0, 0.0, 914.0, 540.0)); - // KDE: the click on the panel's icon, in device pixels. - assert_eq!( - logical_click((46.0, 618.0), 2.0, screen, panel), - (23.0, 309.0) - ); - // GNOME: already in points, and on the top panel. - let top = reserved(screen, (0.0, 32.0, 960.0, 508.0)); - assert_eq!( - logical_click((900.0, 12.0), 2.0, screen, top), - (900.0, 12.0) - ); - // At a scale of 1 nothing changes. - assert_eq!( - logical_click((46.0, 618.0), 1.0, screen, panel), - (46.0, 618.0) - ); - } - - #[test] - fn an_anchor_is_read_from_text() { - assert_eq!(Anchor::parse("Top-Right"), Some(Anchor::TopRight)); - assert_eq!(Anchor::parse("auto"), Some(Anchor::Auto)); - assert_eq!(Anchor::parse("middle"), None); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/portal_shortcuts.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/portal_shortcuts.rs deleted file mode 100644 index 747e2d1ca2..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/portal_shortcuts.rs +++ /dev/null @@ -1,328 +0,0 @@ -//! Global shortcuts on Wayland, through the desktop portal. -//! -//! A Wayland client cannot grab keys for itself, so `xdg-desktop-portal` does it: -//! the app opens a session on `org.freedesktop.portal.GlobalShortcuts`, asks for -//! the shortcuts it wants, and the desktop (GNOME, KDE and others) binds them, -//! asking the user first where it needs to. A press arrives as the portal's -//! `Activated` signal. The desktop owns the final key, so the user can move it. - -use std::collections::HashMap; -use std::sync::mpsc::{channel, Sender}; -use std::sync::OnceLock; -use std::thread; - -use zbus::blocking::{Connection, Proxy}; -use zbus::zvariant::{ObjectPath, OwnedValue, Value}; - -const DESTINATION: &str = "org.freedesktop.portal.Desktop"; -const PATH: &str = "/org/freedesktop/portal/desktop"; -const INTERFACE: &str = "org.freedesktop.portal.GlobalShortcuts"; - -/// Where a press is sent from the thread the portal's signal arrives on. -pub static ACTIVATED_HANDLER: OnceLock> = OnceLock::new(); - -/// Where a refusal the portal reports after the fact is sent: `(id, reason)`. -pub static FAILURE_HANDLER: OnceLock> = OnceLock::new(); - -/// One shortcut to ask the portal for. -pub struct Binding { - pub id: String, - pub description: String, - /// The preferred key, in the portal's spelling (`ALT+space`). - pub trigger: String, -} - -/// A connection to the portal, which takes the shortcuts to bind. -pub struct Portal { - commands: Sender>, -} - -impl Portal { - /// Replaces what is bound with `bindings`. - pub fn set(&self, bindings: Vec) { - let _ = self.commands.send(bindings); - } -} - -fn report(id: &str, reason: &str) { - if let Some(handler) = FAILURE_HANDLER.get() { - handler(id.to_string(), reason.to_string()); - } -} - -/// Connects to the portal, or says why it cannot. -pub fn start(app_id: &str) -> Result { - let connection = Connection::session().map_err(|error| error.to_string())?; - let proxy = - Proxy::new(&connection, DESTINATION, PATH, INTERFACE).map_err(|error| error.to_string())?; - let _version: u32 = proxy - .get_property("version") - .map_err(|_| "this desktop has no GlobalShortcuts portal".to_string())?; - register_app_id(&connection, app_id); - - let listening = connection.clone(); - thread::Builder::new() - .name("rn-gpui-portal-shortcuts".into()) - .spawn(move || listen(listening)) - .map_err(|error| error.to_string())?; - let (commands, receiver) = channel(); - thread::Builder::new() - .name("rn-gpui-portal-bind".into()) - .spawn(move || bind_loop(connection, receiver)) - .map_err(|error| error.to_string())?; - Ok(Portal { commands }) -} - -/// Tells the portal which app this is. A process that was not started through a -/// desktop file has no identity for it otherwise, and the portal refuses -/// shortcuts to an app it cannot name. The portal knows an app by an installed -/// desktop file called `.desktop`, so when there is none one is written -/// for the user, once. A sandbox gives the app its id itself, so there the call is -/// not needed, and an older portal does not have it. -fn register_app_id(connection: &Connection, app_id: &str) { - if app_id.is_empty() || std::env::var_os("FLATPAK_ID").is_some() { - return; - } - let register = || { - connection.call_method( - Some(DESTINATION), - PATH, - Some("org.freedesktop.host.portal.Registry"), - "Register", - &(app_id, HashMap::<&str, Value>::new()), - ) - }; - let Err(error) = register() else { - return; - }; - if error.to_string().contains("App info not found") && write_desktop_file(app_id) { - if let Err(error) = register() { - log::warn!("[desktop] could not register {app_id:?} with the portal: {error}"); - } - } else { - log::warn!("[desktop] could not register {app_id:?} with the portal: {error}"); - } -} - -/// The text of a minimal desktop file for an app that is run from `exec`. -fn desktop_entry(name: &str, exec: &str) -> String { - let exec = exec.replace('\\', "\\\\").replace('"', "\\\""); - format!( - "[Desktop Entry]\nType=Application\nName={name}\nExec=\"{exec}\"\nTerminal=false\nNoDisplay=true\n" - ) -} - -/// Writes `.desktop` into the user's applications folder unless a desktop -/// file of that name is already installed somewhere. Returns whether one was -/// written. -fn write_desktop_file(app_id: &str) -> bool { - let file_name = format!("{app_id}.desktop"); - let data_home = std::env::var_os("XDG_DATA_HOME") - .map(std::path::PathBuf::from) - .or_else(|| { - std::env::var_os("HOME").map(|home| std::path::Path::new(&home).join(".local/share")) - }); - let data_dirs = std::env::var("XDG_DATA_DIRS") - .unwrap_or_else(|_| "/usr/local/share:/usr/share".to_string()); - let installed = data_home - .iter() - .cloned() - .chain(data_dirs.split(':').map(std::path::PathBuf::from)) - .any(|dir| dir.join("applications").join(&file_name).exists()); - if installed { - return false; - } - let Some(directory) = data_home.map(|dir| dir.join("applications")) else { - return false; - }; - // An AppImage's own path is stable, while the executable's is a mount that - // changes on every run. - let executable = std::env::var_os("APPIMAGE") - .map(std::path::PathBuf::from) - .or_else(|| std::env::current_exe().ok()); - let Some(executable) = executable else { - return false; - }; - let name = executable - .file_stem() - .and_then(|stem| stem.to_str()) - .unwrap_or(app_id); - let entry = desktop_entry(name, &executable.to_string_lossy()); - std::fs::create_dir_all(&directory).is_ok() - && std::fs::write(directory.join(file_name), entry).is_ok() -} - -fn listen(connection: Connection) { - let Ok(proxy) = Proxy::new(&connection, DESTINATION, PATH, INTERFACE) else { - return; - }; - let Ok(signals) = proxy.receive_signal("Activated") else { - return; - }; - for message in signals { - let body = message.body(); - let Ok((_session, id, _time, _options)) = - body.deserialize::<(ObjectPath, String, u64, HashMap)>() - else { - continue; - }; - if let Some(handler) = ACTIVATED_HANDLER.get() { - handler(id); - } - } -} - -fn bind_loop(connection: Connection, receiver: std::sync::mpsc::Receiver>) { - let mut session: Option = None; - let mut serial = 0u32; - while let Ok(mut bindings) = receiver.recv() { - // Only the newest list matters when several queued up. - while let Ok(newer) = receiver.try_recv() { - bindings = newer; - } - if let Some(path) = session.take() { - close(&connection, &path); - } - if bindings.is_empty() { - continue; - } - serial += 1; - match bind(&connection, &bindings, serial) { - Ok((path, refused)) => { - session = Some(path); - for id in refused { - report(&id, "the desktop did not bind this shortcut"); - } - } - Err(reason) => { - for binding in &bindings { - report(&binding.id, &reason); - } - } - } - } -} - -fn close(connection: &Connection, session: &str) { - let _ = connection.call_method( - Some(DESTINATION), - session, - Some("org.freedesktop.portal.Session"), - "Close", - &(), - ); -} - -/// Opens a session and binds the shortcuts in it; returns the session and the ids -/// the portal left unbound. -fn bind( - connection: &Connection, - bindings: &[Binding], - serial: u32, -) -> Result<(String, Vec), String> { - let proxy = - Proxy::new(connection, DESTINATION, PATH, INTERFACE).map_err(|error| error.to_string())?; - - let created = request(connection, &format!("create{serial}"), |token| { - let mut options = HashMap::<&str, Value>::new(); - options.insert("handle_token", Value::from(token.to_string())); - options.insert( - "session_handle_token", - Value::from(format!("rngpui_session_{serial}")), - ); - proxy.call_method("CreateSession", &(options,)) - })?; - let session: String = created - .get("session_handle") - .and_then(|value| String::try_from(value.try_clone().ok()?).ok()) - .ok_or_else(|| "the portal gave no session".to_string())?; - - let shortcuts: Vec<(String, HashMap<&str, Value>)> = bindings - .iter() - .map(|binding| { - let mut details = HashMap::<&str, Value>::new(); - details.insert("description", Value::from(binding.description.clone())); - details.insert("preferred_trigger", Value::from(binding.trigger.clone())); - (binding.id.clone(), details) - }) - .collect(); - let session_path = ObjectPath::try_from(session.as_str()).map_err(|error| error.to_string())?; - let bound = request(connection, &format!("bind{serial}"), |token| { - let mut options = HashMap::<&str, Value>::new(); - options.insert("handle_token", Value::from(token.to_string())); - proxy.call_method( - "BindShortcuts", - &(session_path.clone(), shortcuts.clone(), "", options), - ) - }); - let bound = match bound { - Ok(bound) => bound, - Err(reason) => { - close(connection, &session); - return Err(reason); - } - }; - let granted: Option)>> = bound - .get("shortcuts") - .and_then(|value| value.try_clone().ok()) - .and_then(|value| value.try_into().ok()); - let refused = match granted { - Some(granted) => bindings - .iter() - .filter(|binding| !granted.iter().any(|(id, _)| *id == binding.id)) - .map(|binding| binding.id.clone()) - .collect(), - None => Vec::new(), - }; - Ok((session, refused)) -} - -/// Makes one portal request and waits for its `Response`. The signal is listened -/// for before the call, because the portal can answer before the call returns. -fn request( - connection: &Connection, - label: &str, - call: impl FnOnce(&str) -> zbus::Result, -) -> Result, String> { - let token = format!("rngpui_{label}"); - let sender = connection - .unique_name() - .map(|name| name.as_str().trim_start_matches(':').replace('.', "_")) - .ok_or_else(|| "no D-Bus name".to_string())?; - let path = format!("/org/freedesktop/portal/desktop/request/{sender}/{token}"); - let proxy = Proxy::new( - connection, - DESTINATION, - path, - "org.freedesktop.portal.Request", - ) - .map_err(|error| error.to_string())?; - let mut responses = proxy - .receive_signal("Response") - .map_err(|error| error.to_string())?; - call(&token).map_err(|error| error.to_string())?; - let message = responses - .next() - .ok_or_else(|| "the portal did not answer".to_string())?; - let body = message.body(); - let (code, results): (u32, HashMap) = - body.deserialize().map_err(|error| error.to_string())?; - match code { - 0 => Ok(results), - 1 => Err("the shortcut was declined".to_string()), - _ => Err("the desktop could not bind the shortcut".to_string()), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_desktop_file_names_the_app_and_how_to_run_it() { - let entry = desktop_entry("My App", "/opt/my app/bin"); - assert!(entry.starts_with("[Desktop Entry]\n")); - assert!(entry.contains("Name=My App\n")); - assert!(entry.contains("Exec=\"/opt/my app/bin\"\n")); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/test_scale.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/test_scale.rs deleted file mode 100644 index d2363bd512..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/test_scale.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! The window scale factor a test run asks for, on the platforms whose backend -//! reads it from the environment. -//! -//! `RN_GPUI_TEST_SCALE_FACTOR` names the scale every window reports. macOS -//! applies it itself (gpui-fast's `scale_override`); the X11 backend of GPUI -//! reads `GPUI_X11_SCALE_FACTOR` instead, so on Linux the request is handed over -//! under that name before the backend starts. A value the caller set for the -//! backend wins. - -/// Hands the requested scale to the platform backend. Call it before the -/// platform is created. -pub fn apply_to_environment() { - #[cfg(target_os = "linux")] - { - let Some(scale) = std::env::var("RN_GPUI_TEST_SCALE_FACTOR") - .ok() - .and_then(|value| value.parse::().ok()) - .filter(|scale| scale.is_finite() && *scale > 0.0) - else { - return; - }; - if std::env::var_os("GPUI_X11_SCALE_FACTOR").is_none() { - std::env::set_var("GPUI_X11_SCALE_FACTOR", scale.to_string()); - } - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/tray.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/tray.rs deleted file mode 100644 index f3ef70fe3d..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/tray.rs +++ /dev/null @@ -1,1363 +0,0 @@ -//! Windows has no anchored popover: the window opens at the click point. Linux -//! AppIndicator only supports menus, not click-to-popover. - -use crate::bootstrap::WindowTitleBar; -use crate::desktop::errors::{DesktopError, DesktopResult}; -use crate::desktop::menu_model::{self, MenuModel}; -use crate::desktop::windows::{self, OpenWindowOptions, WindowRoleOverride}; -use gpui::{App, Global}; -use serde_json::{json, Value}; -use std::cell::RefCell; -use std::collections::HashSet; - -#[derive(Clone)] -pub struct TrayConfig { - pub id: String, - pub tooltip: Option, - pub title: Option, - /// RGBA pixels for the icon. `None` uses a built-in template glyph. - pub icon: Option<(Vec, u32, u32)>, - pub icon_is_template: bool, - pub component: Option, - pub width: f32, - pub height: f32, - pub menu: Option, - pub menu_on_left_click: bool, - pub quit_on_last_window_closed: bool, - /// Hide the last window when it is closed instead of destroying it, so opening - /// the app again from the tray shows the same window with its state. Off by - /// default: a closed window is gone and a reopened one starts fresh. - pub hide_window_on_close: bool, - pub accessory: bool, - /// Where the popover is drawn when the desktop will not place it at the icon - /// (Wayland): a corner of the screen's work area, `Auto` meaning the end of - /// the panel's edge. - pub popover_anchor: crate::desktop::popover_placement::Anchor, - /// Moves the popover from its corner, in points. - pub popover_offset: (f32, f32), -} - -impl Default for TrayConfig { - fn default() -> Self { - Self { - id: "tray".to_string(), - tooltip: None, - title: None, - icon: None, - icon_is_template: true, - component: None, - width: 320.0, - height: 420.0, - menu: None, - menu_on_left_click: false, - quit_on_last_window_closed: false, - hide_window_on_close: false, - accessory: true, - popover_anchor: Default::default(), - popover_offset: (0.0, 0.0), - } - } -} - -impl TrayConfig { - #[must_use] - pub fn hide_window_on_close(mut self, hide: bool) -> Self { - self.hide_window_on_close = hide; - self - } - - #[must_use] - pub fn popover_anchor(mut self, anchor: crate::desktop::popover_placement::Anchor) -> Self { - self.popover_anchor = anchor; - self - } - - /// The corner by name (`"top-right"`, `"center"`, …), for configuration that - /// is text. An unknown name leaves the anchor as it was. - #[must_use] - pub fn popover_anchor_name(mut self, name: &str) -> Self { - if let Some(anchor) = crate::desktop::popover_placement::Anchor::parse(name) { - self.popover_anchor = anchor; - } - self - } - - #[must_use] - pub fn popover_offset(mut self, x: f32, y: f32) -> Self { - self.popover_offset = (x, y); - self - } - - #[must_use] - pub fn id(mut self, id: impl Into) -> Self { - self.id = id.into(); - self - } - - #[must_use] - pub fn tooltip(mut self, tooltip: impl Into) -> Self { - self.tooltip = Some(tooltip.into()); - self - } - - #[must_use] - pub fn component(mut self, component: impl Into) -> Self { - self.component = Some(component.into()); - self - } - - #[must_use] - pub fn size(mut self, width: f32, height: f32) -> Self { - self.width = width.max(120.0); - self.height = height.max(120.0); - self - } - - #[must_use] - pub fn icon_rgba(mut self, rgba: Vec, width: u32, height: u32) -> Self { - self.icon = Some((rgba, width, height)); - self - } - - /// An encoded image (PNG, JPEG, …), typically from `include_bytes!`. One - /// that does not decode is logged and the built-in glyph is used instead. - #[must_use] - pub fn icon_bytes(mut self, bytes: &[u8]) -> Self { - match crate::desktop::icon::decode(bytes.to_vec()) { - Ok(icon) => self.icon = Some((icon.rgba, icon.width, icon.height)), - Err(error) => log::error!("[desktop][tray] icon: {error}"), - } - self - } - - /// macOS: draw the icon as a template the menu bar tints for light and - /// dark mode. - #[must_use] - pub fn icon_template(mut self, template: bool) -> Self { - self.icon_is_template = template; - self - } - - #[must_use] - pub fn menu(mut self, menu: MenuModel) -> Self { - self.menu = Some(menu); - self - } - - #[must_use] - pub fn accessory(mut self, accessory: bool) -> Self { - self.accessory = accessory; - self - } -} - -pub struct TrayState { - icon: Option, - config: TrayConfig, - pub popover: Option, - visible: bool, - clicks: u32, - last_click: Option<(TrayButton, std::time::Instant)>, - pub popover_dismissed_at: Option, - /// The app's own quit-on-last-window policy, put back when the tray goes. - app_quits_on_last_window: Option, -} - -/// A click on the icon while the popover is open first dismisses it (it loses -/// activation) and then arrives here; within this window it must not reopen it. -const REOPEN_GUARD: std::time::Duration = std::time::Duration::from_millis(350); - -pub struct TrayGlobal(pub RefCell); -impl Global for TrayGlobal {} - -pub fn is_installed(cx: &App) -> bool { - cx.try_global::().is_some() -} - -/// Create the tray icon. Called once, after the app has started, because -/// `NSStatusItem` needs a running `NSApplication`. -pub fn install(cx: &mut App, config: TrayConfig) -> DesktopResult { - if is_installed(cx) { - return Err(DesktopError::failed("a tray icon is already installed")); - } - let app_quits_on_last_window = cx - .try_global::() - .map(|flag| flag.0); - cx.set_global(TrayGlobal(RefCell::new(TrayState { - icon: None, - config: config.clone(), - popover: None, - visible: true, - clicks: 0, - last_click: None, - popover_dismissed_at: None, - app_quits_on_last_window, - }))); - let quits_on_last_window = - config.quit_on_last_window_closed && app_quits_on_last_window.unwrap_or(true); - cx.set_global(crate::desktop::windows::QuitOnLastWindowClosed( - quits_on_last_window, - )); - // GPUI quits by itself when its last window closes on every platform but macOS, - // and our flag is only consulted after that: with the flag off, closing the - // main window still ended the app, tray and all. While a tray keeps the app - // alive, quitting is explicit — the tray's Exit, or the app asking — and - // `windows::maybe_quit` stays the one place that applies the flag. - cx.set_quit_mode(if quits_on_last_window { - gpui::QuitMode::Default - } else { - gpui::QuitMode::Explicit - }); - match build_icon(&config) { - Ok(icon) => { - attach_native_menu(&icon, &config); - cx.global_mut::().0.borrow_mut().icon = Some(icon); - log::info!("[desktop][tray] installed `{}`", config.id); - Ok(json!({"id": config.id})) - } - Err(error) => { - log::error!("[desktop][tray] could not create the icon: {error}"); - Err(DesktopError::failed(format!( - "could not create the tray icon: {error}" - ))) - } - } -} - -pub fn destroy(cx: &mut App) -> DesktopResult { - let (config, popover, app_quits_on_last_window) = { - let Some(tray) = cx.try_global::() else { - return Err(DesktopError::not_found("no tray icon is installed")); - }; - let mut tray = tray.0.borrow_mut(); - let popover = tray.popover.take(); - tray.icon = None; - NATIVE_MENU.store(0, std::sync::atomic::Ordering::Relaxed); - tray.visible = false; - ( - tray.config.id.clone(), - popover, - tray.app_quits_on_last_window, - ) - }; - if let Some(key) = popover { - let _ = windows::close_window(cx, key, true); - } - cx.remove_global::(); - if let Some(quit) = app_quits_on_last_window { - cx.set_global(crate::desktop::windows::QuitOnLastWindowClosed(quit)); - } - // Without a tray there is nothing left to keep the app alive: if no window is - // open either, the app ends, as it would have when its last window closed. - cx.set_quit_mode(gpui::QuitMode::Default); - windows::maybe_quit(cx); - Ok(json!({"id": config, "destroyed": true})) -} - -const DOUBLE_CLICK: std::time::Duration = std::time::Duration::from_millis(500); - -fn is_double_click( - last: Option<(TrayButton, std::time::Instant)>, - button: TrayButton, - now: std::time::Instant, -) -> bool { - last.is_some_and(|(previous, at)| previous == button && now.duration_since(at) <= DOUBLE_CLICK) -} - -fn emit_click(cx: &App, button: TrayButton, double: bool) { - let Some(store) = crate::store::store_from(cx) else { - return; - }; - let name = match button { - TrayButton::Left => "left", - TrayButton::Right => "right", - TrayButton::Middle => "middle", - }; - store.read(cx).host.emit_device_event_json( - "gpuiDesktop:trayClick", - &json!({"button": name, "double": double}).to_string(), - ); -} - -pub fn handle_click(cx: &mut App, rect: TrayRect, button: TrayButton) { - let (config, menu) = { - let Some(tray) = cx.try_global::() else { - return; - }; - let mut tray = tray.0.borrow_mut(); - tray.clicks += 1; - let now = std::time::Instant::now(); - let double = is_double_click(tray.last_click, button, now); - tray.last_click = (!double).then_some((button, now)); - drop(tray); - emit_click(cx, button, double); - let tray = cx.global::().0.borrow(); - (tray.config.clone(), tray.config.menu.clone()) - }; - if wants_menu(menu.is_some(), config.menu_on_left_click, button) { - if let Some(menu) = menu { - show_menu(cx, menu, rect); - } - return; - } - if config.component.is_some() { - toggle_popover(cx, rect); - return; - } - log::debug!("[desktop][tray] click with no popover component and no menu"); -} - -pub fn toggle_popover(cx: &mut App, rect: TrayRect) { - let open = cx - .try_global::() - .and_then(|tray| tray.0.borrow().popover); - if open.is_some() { - hide_popover(cx); - return; - } - let just_dismissed = cx.try_global::().is_some_and(|tray| { - tray.0 - .borrow() - .popover_dismissed_at - .is_some_and(|at| at.elapsed() < REOPEN_GUARD) - }); - if just_dismissed { - return; - } - show_popover(cx, rect); -} - -pub fn show_popover(cx: &mut App, rect: TrayRect) { - let config = match cx.try_global::() { - Some(tray) => tray.0.borrow().config.clone(), - None => return, - }; - let Some(component) = config.component.clone() else { - return; - }; - let work_area = crate::desktop::platform_window::work_area_at( - rect.x + rect.width / 2.0, - rect.y + rect.height / 2.0, - ); - let (x, y) = popover_origin(rect, config.width, config.height, work_area); - #[cfg(target_os = "linux")] - #[cfg(target_os = "linux")] - let overlay = { - let scale = display_scale(cx); - let logical = cx.primary_display().map(|display| { - let size = display.bounds().size; - (f32::from(size.width), f32::from(size.height)) - }); - wayland_overlay(&config, rect, scale, logical) - }; - let options = OpenWindowOptions { - component, - props: None, - title: Some(config.tooltip.clone().unwrap_or_else(|| config.id.clone())), - width: Some(config.width), - height: Some(config.height), - #[cfg(target_os = "linux")] - x: if overlay.is_some() { None } else { Some(x) }, - #[cfg(not(target_os = "linux"))] - x: Some(x), - #[cfg(target_os = "linux")] - y: if overlay.is_some() { None } else { Some(y) }, - #[cfg(not(target_os = "linux"))] - y: Some(y), - resizable: false, - // A popover has no title bar at all; `popup` is what makes it frameless. - title_bar: WindowTitleBar::Default, - background: Default::default(), - window_buttons: None, - shadow: None, - traffic_light_position: None, - role: WindowRoleOverride::TrayPopover, - popup: true, - #[cfg(target_os = "linux")] - overlay, - }; - match windows::open_window(cx, options) { - Ok(key) => { - cx.global_mut::().0.borrow_mut().popover = Some(key); - let _ = windows::focus(cx, key); - } - Err(error) => log::error!("[desktop][tray] could not open the popover: {error}"), - } -} - -/// The scale of the display the app's windows are on. -#[cfg(target_os = "linux")] -fn display_scale(cx: &mut App) -> f32 { - cx.windows() - .first() - .and_then(|handle| handle.update(cx, |_, window, _| window.scale_factor()).ok()) - .unwrap_or(1.0) -} - -/// Where the popover is drawn on Wayland, which neither says where the icon is nor -/// lets an app place a window: in a corner of a window covering the work area. The -/// corner is the app's choice or the user's, and otherwise the end of the edge a -/// panel reserves, when the work area can be read. Without it, and with no choice -/// made, the compositor places an ordinary window. -#[cfg(target_os = "linux")] -fn wayland_overlay( - config: &TrayConfig, - rect: TrayRect, - scale: f32, - logical_screen: Option<(f32, f32)>, -) -> Option { - use crate::desktop::popover_placement::{self, Anchor}; - if !crate::desktop::capabilities::is_wayland() { - return None; - } - let (anchor, offset) = - popover_placement::with_environment(config.popover_anchor, config.popover_offset); - let work = crate::desktop::work_area::read().map(|work| { - let (screen, area) = match logical_screen { - Some(logical) => popover_placement::logical_work_area(work.screen, work.area, logical), - None => (work.screen, work.area), - }; - crate::desktop::work_area::WorkArea { screen, area } - }); - let reserved = work.map(|work| popover_placement::reserved(work.screen, work.area)); - if reserved.is_none() && anchor == Anchor::Auto { - return None; - } - // Some panels send where the icon was clicked, in the screen's own - // coordinates, which is where the work area is read from as well. A click at - // the origin is a panel that sent nothing. - let click = (rect.x != 0.0 || rect.y != 0.0).then_some((rect.x, rect.y)); - let click = match (click, work) { - (Some(click), Some(work)) => Some(popover_placement::logical_click( - click, - scale, - work.screen, - reserved.unwrap_or_default(), - )), - (click, _) => click, - }; - Some(crate::desktop::window_frame::Placement { - anchor, - offset, - reserved: reserved.unwrap_or_default(), - size: (config.width, config.height), - click: click.filter(|_| work.is_some()), - work_origin: work.map_or((0.0, 0.0), |work| (work.area.0, work.area.1)), - bare: false, - }) -} - -/// Where a popover of `width` x `height` goes, in points: centred on the icon, -/// below it when there is room — a menu bar at the top of the screen — and above -/// it when there is not, which is where a taskbar at the bottom puts it. -/// -/// `work_area` is `(x, y, width, height)` of the usable part of the display, when -/// the platform can say. Without it the popover goes where the icon puts it, below -/// and centred, as it always did. With it, the popover is also kept inside the -/// area on every side, so an icon near a corner does not push it off the screen. -fn popover_origin( - rect: TrayRect, - width: f32, - height: f32, - work_area: Option<(f32, f32, f32, f32)>, -) -> (f32, f32) { - let x = rect.x + rect.width / 2.0 - width / 2.0; - let below = rect.y + rect.height; - let Some((area_x, area_y, area_width, area_height)) = work_area else { - return (x, below); - }; - let above = rect.y - height; - let fits_below = below + height <= area_y + area_height; - let y = if fits_below || above < area_y { - below - } else { - above - }; - let max_x = (area_x + area_width - width).max(area_x); - let max_y = (area_y + area_height - height).max(area_y); - (x.clamp(area_x, max_x), y.clamp(area_y, max_y)) -} - -pub fn hide_popover(cx: &mut App) { - let open = cx - .try_global::() - .and_then(|tray| tray.0.borrow_mut().popover.take()); - if let Some(key) = open { - // Closed, not hidden: every show opens a new window, and a hidden one - // would stay behind with its surface (and come back on screen when a - // pending activation reaches it). - let _ = windows::close_window(cx, key, true); - } -} - -/// Show `menu` through the context-menu presenter. A real click on macOS and -/// Windows never gets here: the status item shows its attached menu itself. -pub fn show_menu(cx: &mut App, menu: MenuModel, rect: TrayRect) { - let request = crate::desktop::context_menu::ContextMenuRequest { - window: match crate::desktop::context_menu::target_window(cx) { - Ok((window, _)) => window, - Err(error) => { - log::warn!("[desktop][tray] {error}"); - return; - } - }, - x: rect.x, - y: rect.y + rect.height, - model: menu, - native_view: crate::desktop::context_menu::target_window(cx) - .map(|(_, view)| view) - .unwrap_or(0), - }; - let responder = crate::desktop::context_menu::Responder::callback(Box::new(|selection| { - if let Some(id) = selection { - if let Some(handler) = rn_gpui_sys::TRAY_MENU_PERFORM_HANDLER.get() { - handler(id); - } - } - })); - let presenter = cx - .global::() - .0 - .clone(); - presenter.show(cx, request, responder); -} - -pub fn set_tooltip(cx: &mut App, tooltip: Option<&str>) -> DesktopResult { - let tray = installed(cx)?; - let icon = tray.0.borrow().icon.clone(); - if let Some(icon) = icon { - let _ = icon.set_tooltip(tooltip); - } - tray.0.borrow_mut().config.tooltip = tooltip.map(str::to_string); - Ok(json!({"tooltip": tooltip})) -} - -/// Where the icon is, for a popover the app asks for rather than one a click -/// opened: the platform's own answer where it has one (macOS and Windows), and -/// otherwise what a click would have given. -fn icon_rect(cx: &App) -> TrayRect { - let rect = cx - .try_global::() - .and_then(|tray| tray.0.borrow().icon.as_ref().and_then(|icon| icon.rect())) - .unwrap_or(tray_icon::Rect { - position: tray_icon::dpi::PhysicalPosition::new(0.0, 0.0), - size: tray_icon::dpi::PhysicalSize::new(0, 0), - }); - let scale = f64::from(crate::desktop::platform_window::primary_screen_scale()); - tray_click_rect(rect, tray_icon::dpi::PhysicalPosition::new(0.0, 0.0), scale) -} - -/// The tray's popover, or an error when the tray has none to show. -fn popover_ready(cx: &App) -> DesktopResult { - let tray = installed(cx)?; - if tray.0.borrow().config.component.is_none() { - return Err(DesktopError::invalid_argument( - "the tray has no popover component", - )); - } - Ok(json!({})) -} - -/// Opens the popover when the app asks, the same way a click on the icon does. -pub fn open_popover(cx: &mut App) -> DesktopResult { - popover_ready(cx)?; - let open = installed(cx)?.0.borrow().popover.is_some(); - if !open { - let rect = icon_rect(cx); - show_popover(cx, rect); - } - Ok(json!({"shown": true})) -} - -pub fn close_popover(cx: &mut App) -> DesktopResult { - installed(cx)?; - hide_popover(cx); - Ok(json!({"shown": false})) -} - -pub fn flip_popover(cx: &mut App) -> DesktopResult { - popover_ready(cx)?; - let rect = icon_rect(cx); - toggle_popover(cx, rect); - Ok(json!({})) -} - -/// Changes where the popover is drawn the next time it opens, on desktops that -/// leave that to the app (Wayland). -pub fn set_popover_position( - cx: &mut App, - anchor: Option, - offset: Option<(f32, f32)>, -) -> DesktopResult { - let tray = installed(cx)?; - let mut tray = tray.0.borrow_mut(); - if let Some(anchor) = anchor { - tray.config.popover_anchor = anchor; - } - if let Some(offset) = offset { - tray.config.popover_offset = offset; - } - Ok(json!({})) -} - -pub fn set_visible(cx: &mut App, visible: bool) -> DesktopResult { - let tray = installed(cx)?; - let icon = tray.0.borrow().icon.clone(); - if let Some(icon) = icon { - let _ = icon.set_visible(visible); - } - tray.0.borrow_mut().visible = visible; - Ok(json!({"visible": visible})) -} - -pub fn set_icon( - cx: &mut App, - icon: &crate::desktop::icon::DecodedIcon, - template: bool, -) -> DesktopResult { - let tray = installed(cx)?; - let native = tray_icon::Icon::from_rgba(icon.rgba.clone(), icon.width, icon.height) - .map_err(|error| DesktopError::invalid_argument(format!("{error}")))?; - let handle = tray.0.borrow().icon.clone(); - if let Some(handle) = handle { - #[cfg(target_os = "macos")] - let applied = if template { - handle.set_icon_templated(Some(native)) - } else { - handle.set_icon(Some(native)) - }; - #[cfg(not(target_os = "macos"))] - let applied = handle.set_icon(Some(native)); - applied.map_err(|error| DesktopError::failed(format!("{error}")))?; - } - // Kept, so a tray rebuilt from its config shows the same icon. - let mut state = tray.0.borrow_mut(); - state.config.icon = Some((icon.rgba.clone(), icon.width, icon.height)); - state.config.icon_is_template = template; - Ok(json!({"width": icon.width, "height": icon.height, "template": template})) -} - -/// Text beside the icon; Windows trays have none. -pub fn set_title(cx: &mut App, title: Option<&str>) -> DesktopResult { - let tray = installed(cx)?; - let icon = tray.0.borrow().icon.clone(); - if let Some(icon) = icon { - icon.set_title(title); - } - tray.0.borrow_mut().config.title = title.map(str::to_string); - Ok(json!({"title": title})) -} - -/// `None` clears the menu. -pub fn set_menu(cx: &mut App, items: Option<&Value>) -> DesktopResult { - let tray = installed(cx)?; - let menu = match items { - Some(items) => Some(menu_model::parse_menu(items)?), - None => None, - }; - tray.0.borrow_mut().config.menu = menu; - { - let tray = tray.0.borrow(); - if let Some(icon) = &tray.icon { - attach_native_menu(icon, &tray.config); - } - } - Ok(json!({"items": items.and_then(Value::as_array).map(Vec::len)})) -} - -/// The tray global, or the error every setter reports when there is none. -fn installed(cx: &App) -> Result<&TrayGlobal, DesktopError> { - cx.try_global::() - .ok_or_else(|| DesktopError::not_found("no tray icon is installed")) -} - -pub fn state(cx: &App) -> Value { - let Some(tray) = cx.try_global::() else { - return json!({"installed": false}); - }; - let tray = tray.0.borrow(); - json!({ - "installed": true, - "id": tray.config.id, - "tooltip": tray.config.tooltip, - "visible": tray.visible, - "component": tray.config.component, - "popover": tray.popover, - "clicks": tray.clicks, - "hasMenu": tray.config.menu.is_some(), - "hideWindowOnClose": tray.config.hide_window_on_close, - "title": tray.config.title, - "icon": tray.config.icon.as_ref().map(|(_, width, height)| json!({ - "width": width, - "height": height, - "template": tray.config.icon_is_template, - })), - // Whether a StatusNotifier host is watching the session bus, so a caller - // can tell "the icon is there and the panel is showing it" from "the app - // is publishing an icon that this desktop has nowhere to draw". Only - // Linux has the distinction; elsewhere it is always true. - "hostAvailable": tray_host_available(), - "menuItems": tray - .config - .menu - .as_ref() - .map(|menu| crate::desktop::context_menu::nodes_json(&menu.items)) - .unwrap_or_default(), - }) -} - -/// Whether a StatusNotifier host owns `org.kde.StatusNotifierWatcher`. -/// -/// The tray icon is published over StatusNotifierItem; a panel (or a -/// GNOME AppIndicator extension) has to be *hosting* that protocol for anything -/// to appear. A desktop that does not host it — stock GNOME, or an LXQt panel -/// built without its `statusnotifier` plugin — shows no icon for any -/// StatusNotifierItem app (ours, rustdesk, an Electron app), which is worth -/// reporting rather than looking like a failure in the app. Some desktops -/// (Electron included) additionally keep the retired XEmbed tray, but no -/// maintained crate offers that without GTK, and it is absent from GNOME 3.26+ -/// and from the X11-less Wayland sessions. -/// -/// Reads the session bus with `zbus` (already a dependency, via `ksni`). The -/// query is synchronous and cheap, but only consulted when a caller asks for -/// the tray state, never on a timer. -#[cfg(target_os = "linux")] -fn tray_host_available() -> bool { - use zbus::blocking::Connection; - let Ok(connection) = Connection::session() else { - return false; - }; - connection - .call_method( - Some("org.freedesktop.DBus"), - "/org/freedesktop/DBus", - Some("org.freedesktop.DBus"), - "NameHasOwner", - &("org.kde.StatusNotifierWatcher",), - ) - .ok() - .and_then(|reply| reply.body().deserialize::().ok()) - .unwrap_or(false) -} - -#[cfg(not(target_os = "linux"))] -fn tray_host_available() -> bool { - true -} - -#[derive(Clone, Copy, Debug, Default)] -pub struct TrayRect { - pub x: f32, - pub y: f32, - pub width: f32, - pub height: f32, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum TrayButton { - Left, - Right, - Middle, -} - -fn build_icon(config: &TrayConfig) -> Result { - use tray_icon::{TrayIconBuilder, TrayIconEvent}; - - let icon = match &config.icon { - Some((rgba, width, height)) => tray_icon::Icon::from_rgba(rgba.clone(), *width, *height) - .map_err(|error| error.to_string())?, - None => fallback_icon()?, - }; - let mut builder = TrayIconBuilder::new() - .with_id(config.id.clone()) - .with_menu_on_left_click(false); - // Template mode is a macOS menu-bar concept; every other platform draws - // the icon as-is. The built-in glyph is always a template. - #[cfg(target_os = "macos")] - { - builder = if config.icon.is_none() || config.icon_is_template { - builder.with_icon_templated(icon) - } else { - builder.with_icon(icon) - }; - } - #[cfg(not(target_os = "macos"))] - { - builder = builder.with_icon(icon); - } - if let Some(tooltip) = &config.tooltip { - builder = builder.with_tooltip(tooltip.clone()); - } - if let Some(title) = &config.title { - builder = builder.with_title(title.clone()); - } - let tray = builder.build().map_err(|error| error.to_string())?; - - // The handler runs on the platform's event thread; the click is forwarded - // to the GPUI main thread through the shared queue. - TrayIconEvent::set_event_handler(Some(move |event| { - // One click is a press and a release, and each is its own event; acting - // on both would open the popover and close it again. - let (rect, position, button) = match event { - TrayIconEvent::Click { - rect, - position, - button, - button_state: tray_icon::MouseButtonState::Up, - .. - } => (rect, position, button), - _ => return, - }; - let button = match button { - tray_icon::MouseButton::Left => TrayButton::Left, - tray_icon::MouseButton::Right => TrayButton::Right, - tray_icon::MouseButton::Middle => TrayButton::Middle, - }; - // The status item shows an attached menu itself, anchored to the icon; - // forwarding that click as well would show it a second time. The Linux - // backend also reports a right-click, but the panel has already put the - // D-Bus menu up by then, so it is dropped for the same reason. - let native_menu = NATIVE_MENU.load(std::sync::atomic::Ordering::Relaxed); - if native_menu & MENU_ATTACHED != 0 - && (button == TrayButton::Right || native_menu & MENU_ON_LEFT_CLICK != 0) - { - return; - } - // `tray-icon` reports physical pixels; everything here is in points. - let scale = f64::from(crate::desktop::platform_window::primary_screen_scale()); - let rect = tray_click_rect(rect, position, scale); - if let Some(handler) = rn_gpui_sys::TRAY_CLICK_HANDLER.get() { - handler(rect.x, rect.y, rect.width, rect.height, button as u8); - } - })); - Ok(tray) -} - -/// The icon's rectangle in points, from what a backend reported. -/// -/// macOS and Windows report the icon's own rect, so it is used directly. The -/// Linux `ksni` backend has no rect to report — the panel owns the icon — so it -/// fills `rect` with zeros and puts the click's screen position in `position` -/// (`platform_impl/ksni/mod.rs`). Falling back to the position keeps the popover -/// at the click instead of centred on the top-left corner (0,0). Some panels -/// report `(0,0)` even then; the pointer's own position is the last resort. -fn tray_click_rect( - rect: tray_icon::Rect, - position: tray_icon::dpi::PhysicalPosition, - scale: f64, -) -> TrayRect { - if rect.size.width > 0 || rect.size.height > 0 { - return TrayRect { - x: (rect.position.x / scale) as f32, - y: (rect.position.y / scale) as f32, - width: (f64::from(rect.size.width) / scale) as f32, - height: (f64::from(rect.size.height) / scale) as f32, - }; - } - let (x, y) = if position.x != 0.0 || position.y != 0.0 { - (position.x, position.y) - } else { - // XWayland only follows the pointer over X windows, so on Wayland the - // answer would be stale: no position is better than a wrong one. - if crate::desktop::capabilities::is_wayland() { - (0.0, 0.0) - } else { - pointer_position().unwrap_or((0.0, 0.0)) - } - }; - TrayRect { - x: (x / scale) as f32, - y: (y / scale) as f32, - width: 0.0, - height: 0.0, - } -} - -/// The pointer's screen position in physical pixels, where the platform can -/// answer. Only X11 needs it (see `tray_click_rect`); elsewhere the backend -/// always reports a real rect. -#[cfg(target_os = "linux")] -fn pointer_position() -> Option<(f64, f64)> { - let xlib = x11_dl::xlib::Xlib::open().ok()?; - // SAFETY: the display from `XOpenDisplay` is null-checked before use and closed before returning. - unsafe { - let display = (xlib.XOpenDisplay)(std::ptr::null()); - if display.is_null() { - return None; - } - let root = (xlib.XDefaultRootWindow)(display); - let mut root_return = 0; - let mut child_return = 0; - let mut root_x = 0; - let mut root_y = 0; - let mut win_x = 0; - let mut win_y = 0; - let mut mask = 0; - let found = (xlib.XQueryPointer)( - display, - root, - &mut root_return, - &mut child_return, - &mut root_x, - &mut root_y, - &mut win_x, - &mut win_y, - &mut mask, - ); - (xlib.XCloseDisplay)(display); - if found != 0 { - Some((root_x as f64, root_y as f64)) - } else { - None - } - } -} - -#[cfg(not(target_os = "linux"))] -fn pointer_position() -> Option<(f64, f64)> { - None -} - -/// Whether the status item has a native menu, and which button opens it. Read -/// by the click handler, which runs on the platform's event thread. -static NATIVE_MENU: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); -const MENU_ATTACHED: u8 = 1; -const MENU_ON_LEFT_CLICK: u8 = 2; - -/// Attaches the menu the platform shows itself, anchored to the icon. -/// -/// Every platform does this through `tray-icon`: macOS and Windows build a -/// native menu, and Linux's `ksni` backend turns the *same* `muda` menu into a -/// D-Bus `com.canonical.dbusmenu` the panel draws (the panel owns the popup, so -/// there is no separate window for us to place). `tray-icon` re-exports the -/// matching `muda`, so one builder serves all three. -fn attach_native_menu(icon: &tray_icon::TrayIcon, config: &TrayConfig) { - use std::sync::atomic::Ordering; - use tray_icon::menu::Menu; - - let fallback = default_menu(); - let model = match &config.menu { - Some(model) => Some(model), - None if default_menu_applies() => Some(&fallback), - None => None, - }; - let Some(model) = model else { - icon.set_menu(None); - *TRAY_MENU_IDS - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = HashSet::new(); - NATIVE_MENU.store(0, Ordering::Relaxed); - return; - }; - let menu = Menu::new(); - if let Err(error) = build_tray_menu(&menu, &model.items) { - log::error!("[desktop][tray] could not build the menu: {error}"); - icon.set_menu(None); - *TRAY_MENU_IDS - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = HashSet::new(); - NATIVE_MENU.store(0, Ordering::Relaxed); - return; - } - icon.set_menu(Some(Box::new(menu))); - icon.set_show_menu_on_left_click(config.menu_on_left_click); - NATIVE_MENU.store( - MENU_ATTACHED - | if config.menu_on_left_click { - MENU_ON_LEFT_CLICK - } else { - 0 - }, - Ordering::Relaxed, - ); - // The ids this menu answers for, so the app's single `muda` event route can - // tell a tray selection from a menu-bar one. `tray_icon` forwards mudas - // events, and the app installs one handler on that channel for every menu it - // builds; a second installer here would be ignored (the setter is - // first-caller-wins) and the tray would then never be called. - let mut ids = HashSet::new(); - collect_menu_ids(&model.items, &mut ids); - *TRAY_MENU_IDS - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = ids; - crate::desktop::menu_events::register(Box::new(|id| { - let owned = TRAY_MENU_IDS - .lock() - .map(|ids| ids.contains(id)) - .unwrap_or(false); - if !owned { - return false; - } - if let Some(handler) = rn_gpui_sys::TRAY_MENU_PERFORM_HANDLER.get() { - handler(id.to_string()); - return true; - } - false - })); -} - -/// Every id the tray menu answers for, so a tray selection can be told from a -/// menu-bar one on the shared event route. -fn collect_menu_ids(items: &[menu_model::MenuNode], ids: &mut HashSet) { - use menu_model::MenuNode; - for node in items { - match node { - MenuNode::Item(item) => { - ids.insert(item.id.clone()); - } - MenuNode::Submenu(submenu) => collect_menu_ids(&submenu.items, ids), - MenuNode::Separator | MenuNode::StandardMenu(_) => {} - } - } -} - -/// The ids of the tray menu currently attached, if any. -static TRAY_MENU_IDS: std::sync::LazyLock>> = - std::sync::LazyLock::new(|| std::sync::Mutex::new(HashSet::new())); - -trait TrayMenuAppend { - fn append_all(&self, items: &[&dyn tray_icon::menu::IsMenuItem]) - -> tray_icon::menu::Result<()>; -} - -impl TrayMenuAppend for tray_icon::menu::Menu { - fn append_all( - &self, - items: &[&dyn tray_icon::menu::IsMenuItem], - ) -> tray_icon::menu::Result<()> { - self.append_items(items) - } -} - -impl TrayMenuAppend for tray_icon::menu::Submenu { - fn append_all( - &self, - items: &[&dyn tray_icon::menu::IsMenuItem], - ) -> tray_icon::menu::Result<()> { - self.append_items(items) - } -} - -/// The tray's menu in `tray-icon`'s own menu types. It bundles a newer `muda` -/// than the context menus use, so `context_menu`'s builder cannot be shared. -fn build_tray_menu( - menu: &impl TrayMenuAppend, - items: &[menu_model::MenuNode], -) -> Result<(), String> { - use menu_model::MenuNode; - use tray_icon::menu::{ - CheckMenuItem, IconMenuItem, IsMenuItem, MenuItem, PredefinedMenuItem, Submenu, - }; - let icon = |uri: &Option| { - let icon = crate::desktop::icon::cached(uri.as_deref()?)?; - tray_icon::menu::Icon::from_rgba(icon.rgba.clone(), icon.width, icon.height).ok() - }; - - let mut children: Vec> = Vec::new(); - for node in items { - match node { - MenuNode::Separator => children.push(Box::new(PredefinedMenuItem::separator())), - MenuNode::StandardMenu(_) => {} - MenuNode::Item(item) if item.checked => { - children.push(Box::new(CheckMenuItem::with_id( - item.id.clone(), - item.label.clone(), - item.enabled, - true, - None, - ))) - } - MenuNode::Item(item) => match icon(&item.icon) { - Some(icon) => children.push(Box::new(IconMenuItem::with_id( - item.id.clone(), - item.label.clone(), - item.enabled, - Some(icon), - None, - ))), - None => children.push(Box::new(MenuItem::with_id( - item.id.clone(), - item.label.clone(), - item.enabled, - None, - ))), - }, - MenuNode::Submenu(submenu) => { - let child = Submenu::new(submenu.label.clone(), submenu.enabled); - if let Some(icon) = icon(&submenu.icon) { - child.set_icon(Some(icon)); - } - build_tray_menu(&child, &submenu.items)?; - children.push(Box::new(child)); - } - } - } - let refs: Vec<&dyn IsMenuItem> = children.iter().map(|item| item.as_ref()).collect(); - menu.append_all(&refs).map_err(|error| error.to_string()) -} - -/// The icon for a tray that was not given one: the app's own where the platform -/// draws a tray icon as-is, and the built-in glyph where it does not or the app -/// has none. -fn fallback_icon() -> Result { - #[cfg(not(target_os = "macos"))] - if let Some(icon) = crate::desktop::icon::app_icon() { - return tray_icon::Icon::from_rgba(icon.rgba.clone(), icon.width, icon.height) - .map_err(|error| error.to_string()); - } - default_icon() -} - -/// The glyph a tray shows when the app has no icon: an outline a macOS menu bar -/// tints for light and dark, and elsewhere a filled disc that shows on a dark -/// and on a light panel alike. -fn default_icon() -> Result { - const SIZE: u32 = 22; - let mut rgba = vec![0u8; (SIZE * SIZE * 4) as usize]; - for y in 0..SIZE { - for x in 0..SIZE { - let index = ((y * SIZE + x) * 4) as usize; - #[cfg(target_os = "macos")] - { - let outer = x >= 3 && x < SIZE - 3 && y >= 4 && y < SIZE - 4; - let inner = x >= 6 && x < SIZE - 6 && y >= 7 && y < SIZE - 7; - if outer && !inner { - rgba[index..index + 4].copy_from_slice(&[0, 0, 0, 255]); - } - } - #[cfg(not(target_os = "macos"))] - { - let dx = x as f32 + 0.5 - SIZE as f32 / 2.0; - let dy = y as f32 + 0.5 - SIZE as f32 / 2.0; - let distance = (dx * dx + dy * dy).sqrt(); - if distance <= 9.0 { - let pixel: [u8; 4] = if distance <= 3.5 { - [255, 255, 255, 255] - } else { - [124, 139, 161, 255] - }; - rgba[index..index + 4].copy_from_slice(&pixel); - } - } - } - } - tray_icon::Icon::from_rgba(rgba, SIZE, SIZE).map_err(|error| error.to_string()) -} - -fn wants_menu(has_menu: bool, menu_on_left_click: bool, button: TrayButton) -> bool { - has_menu && (button == TrayButton::Right || menu_on_left_click) -} - -fn has_popover(cx: &App) -> bool { - cx.try_global::() - .is_some_and(|tray| tray.0.borrow().config.component.is_some()) -} - -/// Whether the installed tray asked for the last window to be hidden, not -/// destroyed, when it is closed. -pub fn hides_window_on_close(cx: &App) -> bool { - cx.try_global::() - .is_some_and(|tray| tray.0.borrow().config.hide_window_on_close) -} - -/// The id of the built-in menu's "Open" item. -const DEFAULT_OPEN_ID: &str = "rn-gpui:tray:open"; -/// The id of the built-in menu's "Exit" item. -const DEFAULT_EXIT_ID: &str = "rn-gpui:tray:exit"; - -/// What a right-click on a tray icon shows when the app gave it no menu: Open and -/// Exit, which is what users expect of a tray icon on Windows and Linux. Without -/// it there is no way to bring a closed window back, or to end an app that keeps -/// running in the background, short of the task manager. -fn default_menu() -> MenuModel { - use menu_model::{MenuItemDef, MenuNode}; - let item = |id: &str, label: &str| { - MenuNode::Item(MenuItemDef { - id: id.to_string(), - label: label.to_string(), - accelerator: None, - enabled: true, - checked: false, - role: None, - icon: None, - }) - }; - MenuModel { - items: vec![ - item(DEFAULT_OPEN_ID, "Open"), - MenuNode::Separator, - item(DEFAULT_EXIT_ID, "Exit"), - ], - } -} - -/// macOS status items do not carry an Open/Exit menu by convention — the Dock and -/// the app menu do that — so only the other platforms get the built-in one. -fn default_menu_applies() -> bool { - cfg!(not(target_os = "macos")) -} - -/// A selection from the tray's menu. The built-in items act here; everything else -/// is the app's, and reaches JavaScript. -pub fn perform_menu(cx: &mut App, id: &str) { - match id { - DEFAULT_OPEN_ID if has_popover(cx) => { - // A panel that shows only the menu, such as GNOME's, never reports - // a click, so the menu is the way to the popover. - if let Some(handler) = rn_gpui_sys::TRAY_CLICK_HANDLER.get() { - handler(0.0, 0.0, 0.0, 0.0, TrayButton::Left as u8); - } - } - DEFAULT_OPEN_ID => windows::reopen(cx), - DEFAULT_EXIT_ID => cx.quit(), - _ => emit_menu_press(cx, id), - } -} - -pub fn emit_menu_press(cx: &App, id: &str) { - let Some(store) = crate::store::store_from(cx) else { - return; - }; - store - .read(cx) - .host - .emit_device_event_json("gpuiDesktop:trayMenuPress", &json!({"id": id}).to_string()); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_second_click_of_the_same_button_in_time_is_a_double_click() { - let now = std::time::Instant::now(); - let first = Some((TrayButton::Left, now)); - let soon = now + std::time::Duration::from_millis(300); - let late = now + std::time::Duration::from_millis(800); - assert!(is_double_click(first, TrayButton::Left, soon)); - assert!(!is_double_click(first, TrayButton::Left, late)); - assert!(!is_double_click(first, TrayButton::Right, soon)); - assert!(!is_double_click(None, TrayButton::Left, soon)); - } - - #[test] - fn the_default_icon_is_a_valid_template() { - let icon = default_icon().expect("the built-in glyph is valid"); - let _ = icon; - } - - #[test] - fn a_tray_config_defaults_to_a_popover_with_no_menu() { - let config = TrayConfig::default(); - assert!(config.component.is_none()); - assert!(config.menu.is_none()); - assert!(!config.quit_on_last_window_closed); - assert_eq!(config.id, "tray"); - } - - #[test] - fn a_right_click_opens_the_menu_only_when_one_exists() { - assert!(wants_menu(true, false, TrayButton::Right)); - assert!(!wants_menu(false, false, TrayButton::Right)); - assert!(!wants_menu(true, false, TrayButton::Left)); - assert!(!wants_menu(true, false, TrayButton::Middle)); - } - - #[test] - fn menu_on_left_click_moves_the_menu_to_the_primary_button() { - assert!(wants_menu(true, true, TrayButton::Left)); - assert!(wants_menu(true, true, TrayButton::Right)); - assert!(!wants_menu(false, true, TrayButton::Left)); - } - - #[test] - fn the_built_in_menu_offers_open_and_exit() { - let menu = default_menu(); - assert_eq!(menu.ids(), [DEFAULT_OPEN_ID, DEFAULT_EXIT_ID]); - assert_eq!( - menu.find(DEFAULT_OPEN_ID).map(|i| i.label.as_str()), - Some("Open") - ); - assert_eq!( - menu.find(DEFAULT_EXIT_ID).map(|i| i.label.as_str()), - Some("Exit") - ); - assert!(menu.find(DEFAULT_OPEN_ID).is_some_and(|item| item.enabled)); - } - - #[test] - fn the_built_in_ids_cannot_be_an_apps_own() { - // They would be swallowed by `perform_menu` instead of reaching the app. - assert!(DEFAULT_OPEN_ID.starts_with("rn-gpui:")); - assert!(DEFAULT_EXIT_ID.starts_with("rn-gpui:")); - assert_ne!(DEFAULT_OPEN_ID, DEFAULT_EXIT_ID); - } - - const ICON: TrayRect = TrayRect { - x: 1200.0, - y: 740.0, - width: 24.0, - height: 28.0, - }; - // A 1280x768 display whose bottom 40 points are the taskbar. - const WORK_AREA: Option<(f32, f32, f32, f32)> = Some((0.0, 0.0, 1280.0, 728.0)); - - #[test] - fn without_a_work_area_a_popover_goes_below_and_centred_as_before() { - assert_eq!( - popover_origin(ICON, 320.0, 200.0, None), - (1200.0 + 12.0 - 160.0, 768.0) - ); - } - - #[test] - fn a_taskbar_at_the_bottom_puts_the_popover_above_it() { - // Below the icon is the bottom of the screen; above has room. The icon - // is inside the taskbar, so the popover rests on the work area's edge - // (728), not on the icon (740) — that would overlap the taskbar. - let (_, y) = popover_origin(ICON, 320.0, 200.0, WORK_AREA); - assert_eq!(y, 728.0 - 200.0); - } - - #[test] - fn a_menu_bar_at_the_top_puts_the_popover_below_its_icon() { - let icon = TrayRect { - x: 600.0, - y: 0.0, - width: 24.0, - height: 24.0, - }; - let (x, y) = popover_origin(icon, 320.0, 200.0, Some((0.0, 24.0, 1280.0, 744.0))); - assert_eq!((x, y), (600.0 + 12.0 - 160.0, 24.0)); - } - - #[test] - fn the_popover_stays_inside_the_work_area_at_a_corner() { - let (x, _) = popover_origin(ICON, 320.0, 200.0, WORK_AREA); - // Centring on an icon 76 points from the right edge would overhang it. - assert_eq!(x, 1280.0 - 320.0); - let corner = TrayRect { - x: 0.0, - y: 0.0, - width: 20.0, - height: 20.0, - }; - assert_eq!( - popover_origin(corner, 320.0, 200.0, Some((0.0, 0.0, 1280.0, 768.0))), - (0.0, 20.0) - ); - } - - #[test] - fn a_popover_taller_than_the_room_is_kept_at_the_top_of_the_area() { - let (_, y) = popover_origin(ICON, 320.0, 900.0, WORK_AREA); - assert_eq!(y, 0.0); - } - - #[test] - fn the_builder_sizes_are_clamped() { - let config = TrayConfig::default().size(10.0, 10.0); - assert_eq!(config.width, 120.0); - assert_eq!(config.height, 120.0); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/window_frame.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/window_frame.rs deleted file mode 100644 index 0395376802..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/window_frame.rs +++ /dev/null @@ -1,507 +0,0 @@ -//! The frame a client-decorated window draws for itself: rounded corners, a -//! hairline border and a shadow, in a margin around the content. -//! -//! Only Linux asks the app for these: the compositor draws none of it for a -//! window that has taken its decorations over. Elsewhere every function answers -//! "no frame", so callers need no platform checks. - -use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; - -/// How far the content is pushed in from each side of the window. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct Insets { - pub left: f32, - pub top: f32, - pub right: f32, - pub bottom: f32, -} - -impl Insets { - pub fn horizontal(self) -> f32 { - self.left + self.right - } - - pub fn vertical(self) -> f32 { - self.top + self.bottom - } -} - -/// What the frame looks like. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Frame { - /// Corner radius of the window, in points. - pub radius: f32, - /// How far the shadow reaches beyond the window, and so the margin around it. - pub shadow_extent: f32, - /// `0xRRGGBBAA`, painted as a one-point line just inside the edge. - pub border: u32, - /// Opacity of the shadow at its densest, 0 to 1. - pub shadow_alpha: f32, - /// Standard deviation of the shadow's blur, in points. - pub shadow_blur: f32, - /// How far the shadow grows beyond the window before it blurs, in points. - pub shadow_spread: f32, - /// How far the shadow is shifted down, in points. - pub shadow_dy: f32, -} - -/// Used where the desktop's own frame has not been measured. -const DEFAULT: Frame = Frame { - radius: 12.0, - shadow_extent: 14.0, - border: 0x0000_0040, - shadow_alpha: 0.35, - shadow_blur: 7.0, - shadow_spread: 0.0, - shadow_dy: 0.0, -}; - -static FALLBACK_RADIUS: AtomicU32 = AtomicU32::new(0); -static FRAME_ENABLED: AtomicBool = AtomicBool::new(true); - -/// Whether a window gets the frame at all. A window that asked for no shadow, for -/// no system chrome, or for a see-through background draws its own look: the -/// frame's shadow sits under the content, so it would show through, and its -/// rounding and margin are not what such a window wants. -pub fn wanted(opaque: bool, shadow: bool, borderless: bool) -> bool { - opaque && shadow && !borderless -} - -/// Applies the `desktop.json` window options: the radius to use when the -/// desktop's cannot be measured, and whether to draw the shadow. -pub fn configure(fallback_radius: Option, shadow: bool) { - FALLBACK_RADIUS.store(fallback_radius.unwrap_or(0.0).to_bits(), Ordering::Relaxed); - FRAME_ENABLED.store(shadow, Ordering::Relaxed); -} - -/// The frame to draw. -pub fn frame() -> Frame { - let mut frame = measured().unwrap_or(DEFAULT); - let fallback = f32::from_bits(FALLBACK_RADIUS.load(Ordering::Relaxed)); - if measured().is_none() && fallback > 0.0 { - frame.radius = fallback; - } - if !FRAME_ENABLED.load(Ordering::Relaxed) { - frame.shadow_extent = 0.0; - frame.shadow_alpha = 0.0; - frame.shadow_blur = 0.0; - frame.shadow_spread = 0.0; - frame.shadow_dy = 0.0; - } - frame -} - -static MEASURED: std::sync::OnceLock> = std::sync::OnceLock::new(); - -fn measured() -> Option { - MEASURED.get().copied().flatten() -} - -/// Measures the desktop's frame, or reads the last measurement while nothing it -/// depends on has changed. Runs once, before the first window, and costs a -/// child process only on a first launch or after a theme or library update. -pub fn load(app_id: &str) { - #[cfg(target_os = "linux")] - cache::name_for(app_id); - #[cfg(not(target_os = "linux"))] - let _ = app_id; - MEASURED.get_or_init(measure_or_cached); -} - -#[cfg(not(target_os = "linux"))] -fn measure_or_cached() -> Option { - None -} - -#[cfg(target_os = "linux")] -fn measure_or_cached() -> Option { - if std::env::var_os("RN_GPUI_FRAME_PROBE").is_some_and(|value| value == "off") - || std::env::var_os("RN_GPUI_TEST_OFFSCREEN").is_some() - { - return None; - } - let key = cache::key(); - if let Some(cached) = cache::read(&key) { - return cached; - } - // A probe that could not run is not kept: the next launch tries again. - let frame = cache::probe()?; - cache::write(&key, frame); - frame -} - -#[cfg(target_os = "linux")] -mod cache { - use std::io::Read; - use std::path::PathBuf; - use std::process::{Command, Stdio}; - use std::time::{Duration, Instant}; - - use super::Frame; - - const PROBE_TIMEOUT: Duration = Duration::from_millis(2500); - - static APP_DIRECTORY: std::sync::OnceLock = std::sync::OnceLock::new(); - - /// The app's own folder in the cache: its id, with anything a file name should - /// not hold replaced, so each app keeps its own measurement. - pub fn name_for(app_id: &str) { - let name: String = app_id - .chars() - .map(|c| { - if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') { - c - } else { - '_' - } - }) - .collect(); - let _ = APP_DIRECTORY.set(if name.trim_matches('.').is_empty() { - "react-native-gpui".to_string() - } else { - name - }); - } - - fn path() -> Option { - let base = crate::desktop::app_dir::data_dir_override() - .map(|dir| dir.join("cache")) - .or_else(|| std::env::var_os("XDG_CACHE_HOME").map(PathBuf::from)) - .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache")))?; - let directory = APP_DIRECTORY - .get() - .map_or("react-native-gpui", String::as_str); - Some(base.join(directory).join("window-frame.json")) - } - - fn setting(schema: &str, key: &str) -> String { - Command::new("gsettings") - .args(["get", schema, key]) - .stderr(Stdio::null()) - .output() - .ok() - .and_then(|output| String::from_utf8(output.stdout).ok()) - .unwrap_or_default() - .trim() - .to_string() - } - - /// `size:modified` of the first of `candidates` that exists. - fn stamp(candidates: &[String]) -> String { - candidates - .iter() - .find_map(|path| std::fs::metadata(path).ok()) - .map(|meta| { - let modified = meta - .modified() - .ok() - .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok()) - .map_or(0, |elapsed| elapsed.as_secs()); - format!("{}:{modified}", meta.len()) - }) - .unwrap_or_default() - } - - /// Everything the measurement depends on: the toolkit and theme in use, the - /// libraries that draw it, and this runtime. - pub fn key() -> String { - let theme = setting("org.gnome.desktop.interface", "gtk-theme"); - let scheme = setting("org.gnome.desktop.interface", "color-scheme"); - let libraries = [ - "lib", - "lib64", - "lib/x86_64-linux-gnu", - "lib/aarch64-linux-gnu", - ]; - let find = |name: &str| -> Vec { - libraries - .iter() - .map(|dir| format!("/usr/{dir}/{name}")) - .collect() - }; - let theme_files: Vec = { - let name = theme.trim_matches('\''); - let home = std::env::var("HOME").unwrap_or_default(); - let roots = [ - format!("{home}/.themes"), - format!("{home}/.local/share/themes"), - "/usr/share/themes".to_string(), - ]; - let mut files = Vec::new(); - for version in ["gtk-4.0", "gtk-3.0"] { - for file in ["gtk.css", "gtk.gresource"] { - files.extend( - roots - .iter() - .map(|root| format!("{root}/{name}/{version}/{file}")), - ); - } - } - files - }; - format!( - "v2|{}|{theme}|{scheme}|gtk:{}|adw:{}|css:{}", - env!("CARGO_PKG_VERSION"), - stamp(&find("libgtk-4.so.1")), - stamp(&find("libadwaita-1.so.0")), - theme_files - .iter() - .map(|file| stamp(std::slice::from_ref(file))) - .collect::>() - .join(","), - ) - } - - /// `Some(frame)` for a stored measurement of the same `key`, where `frame` - /// is `None` if the toolkit could not be measured then. - pub fn read(key: &str) -> Option> { - let text = std::fs::read_to_string(path()?).ok()?; - let value: serde_json::Value = serde_json::from_str(&text).ok()?; - if value.get("key")?.as_str()? != key { - return None; - } - match value.get("frame")? { - serde_json::Value::Null => Some(None), - frame => parse(frame).map(Some), - } - } - - pub fn write(key: &str, frame: Option) { - let Some(path) = path() else { return }; - let value = serde_json::json!({ - "key": key, - "frame": frame.map(|frame| serde_json::json!({ - "radius": frame.radius, - "shadow_extent": frame.shadow_extent, - "border": frame.border, - "shadow_alpha": frame.shadow_alpha, - "shadow_blur": frame.shadow_blur, - "shadow_spread": frame.shadow_spread, - "shadow_dy": frame.shadow_dy, - })), - }); - if let Some(parent) = path.parent() { - let _ = std::fs::create_dir_all(parent); - } - let _ = std::fs::write(path, value.to_string()); - } - - fn parse(value: &serde_json::Value) -> Option { - Some(Frame { - radius: value.get("radius")?.as_f64()? as f32, - shadow_extent: value.get("shadow_extent")?.as_f64()? as f32, - border: u32::try_from(value.get("border")?.as_u64()?).ok()?, - shadow_alpha: value.get("shadow_alpha")?.as_f64()? as f32, - shadow_blur: value.get("shadow_blur")?.as_f64()? as f32, - shadow_spread: value.get("shadow_spread")?.as_f64()? as f32, - shadow_dy: value.get("shadow_dy")?.as_f64()? as f32, - }) - } - - /// Runs this executable as the probe and reads what it prints, giving up - /// after a short while so a toolkit that hangs cannot hold the app back. - /// - /// `None` means the probe could not be run or did not finish, which says - /// nothing about the toolkit; `Some(None)` is the probe's own answer that - /// there is nothing to measure. - pub fn probe() -> Option> { - let mut child = Command::new(std::env::current_exe().ok()?) - .arg("--rn-gpui-probe-frame") - .env("GSK_RENDERER", "cairo") - .env("GTK_CSD", "1") - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .spawn() - .ok()?; - let started = Instant::now(); - loop { - match child.try_wait() { - Ok(Some(status)) if status.success() => break, - Ok(Some(_)) | Err(_) => return None, - Ok(None) if started.elapsed() > PROBE_TIMEOUT => { - let _ = child.kill(); - let _ = child.wait(); - return None; - } - Ok(None) => std::thread::sleep(Duration::from_millis(10)), - } - } - let mut output = String::new(); - child.stdout.take()?.read_to_string(&mut output).ok()?; - let value: serde_json::Value = serde_json::from_str(output.lines().last()?).ok()?; - match value { - serde_json::Value::Null => Some(None), - frame => parse(&frame).map(Some), - } - } -} - -#[cfg(target_os = "linux")] -pub use linux::*; - -#[cfg(target_os = "linux")] -mod linux { - use std::cell::RefCell; - use std::collections::HashMap; - - use gpui::{Decorations, Window}; - - use super::{frame, Insets}; - use crate::desktop::popover_placement::{self, Anchor, Reserved}; - - /// A popover drawn at a corner of a window that covers the work area, instead - /// of being a window the compositor places. - #[derive(Clone, Copy, Debug, PartialEq)] - pub struct Placement { - pub anchor: Anchor, - pub offset: (f32, f32), - pub reserved: Reserved, - /// The popover's own size, which is the size of its content. - pub size: (f32, f32), - /// Where the click on the icon was, on the screen, when the desktop said, - /// and where the work area starts on it. - pub click: Option<(f32, f32)>, - pub work_origin: (f32, f32), - /// The window draws its own look, so the overlay adds no frame to it. - pub bare: bool, - } - - thread_local! { - /// The windows that draw a frame, by surface id, and their current margin. - static WINDOWS: RefCell> = RefCell::new(HashMap::new()); - static PLACEMENTS: RefCell> = RefCell::new(HashMap::new()); - static LAUNCHERS: RefCell> = RefCell::new(Default::default()); - } - - /// Records the window of `surface_id` as a launcher, which closes when it - /// loses focus. - pub fn mark_launcher(surface_id: i32) { - LAUNCHERS.with(|launchers| launchers.borrow_mut().insert(surface_id)); - } - - pub fn is_launcher(surface_id: i32) -> bool { - LAUNCHERS.with(|launchers| launchers.borrow().contains(&surface_id)) - } - - /// Makes the window of `surface_id` an overlay with the popover placed in it. - pub fn place(surface_id: i32, placement: Placement) { - enroll(surface_id); - PLACEMENTS.with(|placements| placements.borrow_mut().insert(surface_id, placement)); - } - - pub fn placement_of(surface_id: i32) -> Option { - PLACEMENTS.with(|placements| placements.borrow().get(&surface_id).copied()) - } - - /// Makes the window of `surface_id` draw the frame. - pub fn enroll(surface_id: i32) { - WINDOWS.with(|windows| { - windows.borrow_mut().entry(surface_id).or_default(); - }); - } - - pub fn is_framed(surface_id: i32) -> bool { - WINDOWS.with(|windows| windows.borrow().contains_key(&surface_id)) - } - - /// The margin around a window's content as last synced; none for a window - /// that draws no frame. - pub fn insets_of(surface_id: i32) -> Insets { - WINDOWS.with(|windows| { - windows - .borrow() - .get(&surface_id) - .copied() - .unwrap_or_default() - }) - } - - /// The margin a window gets: the shadow's reach on every side it does not - /// share with the screen or a neighbour, none while the compositor draws the - /// frame. - pub fn insets_for(window: &Window, surface_id: i32) -> Insets { - if let Some(placement) = placement_of(surface_id) { - let view = window.viewport_size(); - let (width, height) = (f32::from(view.width), f32::from(view.height)); - let (x, y) = match placement.click { - Some((click_x, click_y)) if placement.anchor == Anchor::Auto => { - popover_placement::place_near( - ( - click_x - placement.work_origin.0, - click_y - placement.work_origin.1, - ), - placement.reserved, - (width, height), - placement.size, - popover_placement::MARGIN, - placement.offset, - ) - } - _ => popover_placement::place( - placement.anchor, - placement.reserved, - (width, height), - placement.size, - popover_placement::MARGIN, - placement.offset, - ), - }; - return Insets { - left: x, - top: y, - right: (width - x - placement.size.0).max(0.0), - bottom: (height - y - placement.size.1).max(0.0), - }; - } - let Decorations::Client { tiling } = window.window_decorations() else { - return Insets::default(); - }; - let extent = frame().shadow_extent; - let side = |tiled: bool| if tiled { 0.0 } else { extent }; - Insets { - left: side(tiling.left), - top: side(tiling.top), - right: side(tiling.right), - bottom: side(tiling.bottom), - } - } - - /// Records the margin of an enrolled window; true when it changed. - pub fn sync(window: &Window, surface_id: i32) -> bool { - if !is_framed(surface_id) { - return false; - } - let insets = insets_for(window, surface_id); - WINDOWS.with(|windows| windows.borrow_mut().insert(surface_id, insets)) != Some(insets) - } -} - -#[cfg(not(target_os = "linux"))] -pub fn insets_of(_surface_id: i32) -> Insets { - Insets::default() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_window_that_draws_its_own_look_gets_no_frame() { - assert!(wanted(true, true, false)); - assert!(!wanted(false, true, false)); - assert!(!wanted(true, false, false)); - assert!(!wanted(true, true, true)); - } - - #[test] - fn the_options_shape_the_unmeasured_frame() { - configure(Some(6.0), true); - assert_eq!(frame().radius, 6.0); - configure(None, true); - assert_eq!(frame().radius, DEFAULT.radius); - configure(None, false); - assert_eq!(frame().shadow_extent, 0.0); - configure(None, true); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/window_icons.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/window_icons.rs deleted file mode 100644 index ebf9a4f7d1..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/window_icons.rs +++ /dev/null @@ -1,190 +0,0 @@ -//! The caption button icons of the desktop's icon theme. -//! -//! A theme ships `window-close-symbolic.svg` and its siblings: single-colour -//! shapes meant to take the colour of the text around them. They are looked up -//! the way GTK does, through the theme and the themes it inherits from, and -//! recoloured here because the app's images cannot. - -use std::path::{Path, PathBuf}; - -const FALLBACK_THEMES: [&str; 3] = ["Adwaita", "breeze", "hicolor"]; -const MAX_DEPTH: usize = 4; - -/// The icon for a caption button (`close`, `minimize`, `maximize`, `restore`) -/// as an SVG data URI painted in `color` (`#rrggbb`), or `None` when no theme -/// has one. -pub fn window_icon(action: &str, color: &str) -> Option { - use base64::Engine; - if !matches!(action, "close" | "minimize" | "maximize" | "restore") { - return None; - } - let file = find_icon(&format!("window-{action}-symbolic.svg"))?; - let icon = recolored(&std::fs::read_to_string(file).ok()?, color); - Some(format!( - "data:image/svg+xml;base64,{}", - base64::engine::general_purpose::STANDARD.encode(icon) - )) -} - -fn find_icon(file_name: &str) -> Option { - let roots = icon_roots(); - let mut themes = Vec::new(); - for theme in current_theme() - .into_iter() - .chain(FALLBACK_THEMES.map(String::from)) - { - add_with_parents(&roots, &theme, &mut themes); - } - themes.iter().find_map(|theme| { - roots - .iter() - .find_map(|root| search(&root.join(theme), file_name, 0)) - }) -} - -/// Appends `theme` and the themes it inherits, once each, nearest first. -fn add_with_parents(roots: &[PathBuf], theme: &str, themes: &mut Vec) { - if themes.iter().any(|known| known == theme) { - return; - } - themes.push(theme.to_string()); - let parents = roots.iter().find_map(|root| { - let text = std::fs::read_to_string(root.join(theme).join("index.theme")).ok()?; - text.lines() - .find_map(|line| line.strip_prefix("Inherits=")) - .map(|list| { - list.split(',') - .map(|name| name.trim().to_string()) - .collect::>() - }) - }); - for parent in parents.into_iter().flatten() { - add_with_parents(roots, &parent, themes); - } -} - -fn icon_roots() -> Vec { - let home = std::env::var_os("HOME").map(PathBuf::from); - let data_home = std::env::var_os("XDG_DATA_HOME") - .map(PathBuf::from) - .or_else(|| home.as_ref().map(|home| home.join(".local/share"))); - let data_dirs = std::env::var("XDG_DATA_DIRS") - .unwrap_or_else(|_| "/usr/local/share:/usr/share".to_string()); - let mut roots: Vec = home.iter().map(|home| home.join(".icons")).collect(); - roots.extend(data_home.map(|dir| dir.join("icons"))); - roots.extend( - data_dirs - .split(':') - .filter(|dir| !dir.is_empty()) - .map(|dir| Path::new(dir).join("icons")), - ); - roots -} - -fn search(dir: &Path, file_name: &str, depth: usize) -> Option { - let direct = dir.join(file_name); - if direct.is_file() { - return Some(direct); - } - if depth >= MAX_DEPTH { - return None; - } - let mut children: Vec = std::fs::read_dir(dir) - .ok()? - .filter_map(|entry| entry.ok()) - .map(|entry| entry.path()) - .filter(|path| path.is_dir()) - .collect(); - children.sort(); - children - .iter() - .find_map(|child| search(child, file_name, depth + 1)) -} - -/// The icon theme in use: GTK's `icon-theme` setting, or KDE's `kdeglobals`. -fn current_theme() -> Option { - gsettings_theme().or_else(kde_theme) -} - -fn gsettings_theme() -> Option { - let output = std::process::Command::new("gsettings") - .args(["get", "org.gnome.desktop.interface", "icon-theme"]) - .stderr(std::process::Stdio::null()) - .output() - .ok() - .filter(|output| output.status.success())?; - let text = String::from_utf8(output.stdout).ok()?; - let name = text.trim().trim_matches('\''); - (!name.is_empty()).then(|| name.to_string()) -} - -fn kde_theme() -> Option { - let config = std::env::var_os("XDG_CONFIG_HOME") - .map(PathBuf::from) - .or_else(|| std::env::var_os("HOME").map(|home| Path::new(&home).join(".config")))?; - let text = std::fs::read_to_string(config.join("kdeglobals")).ok()?; - let mut in_icons = false; - for line in text.lines() { - let line = line.trim(); - if let Some(section) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { - in_icons = section == "Icons"; - } else if in_icons { - if let Some(name) = line.strip_prefix("Theme=") { - return Some(name.to_string()); - } - } - } - None -} - -/// Paints every fill of a symbolic icon in `color`, in attributes and in `style` -/// declarations, and gives the root a fill for shapes that have none. -fn recolored(source: &str, color: &str) -> String { - let mut out = replace_values(source, "fill=\"", '"', color); - out = replace_values(&out, "fill:", ';', color); - match out.find(" { - out.insert_str(at + 4, &format!(" fill=\"{color}\"")); - out - } - None => out, - } -} - -/// Replaces the value that follows each `prefix` up to `end`, except `none`. -fn replace_values(text: &str, prefix: &str, end: char, color: &str) -> String { - let mut out = String::with_capacity(text.len()); - let mut rest = text; - while let Some(at) = rest.find(prefix) { - let value_start = at + prefix.len(); - out.push_str(&rest[..value_start]); - let tail = &rest[value_start..]; - let stop = tail - .find(|c| c == end || c == '"' || c == '}') - .unwrap_or(tail.len()); - if &tail[..stop] == "none" { - out.push_str("none"); - } else { - out.push_str(color); - } - rest = &tail[stop..]; - } - out.push_str(rest); - out -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn every_fill_takes_the_colour_but_none() { - let source = r#""#; - let out = recolored(source, "#fff"); - assert!(out.starts_with(r##" &'static Mutex>> { - static MIRROR: OnceLock>>> = OnceLock::new(); - MIRROR.get_or_init(|| Mutex::new(HashMap::new())) -} - -/// Replaces a window's whole state. -pub fn set(key: u32, state: &Value) { - if let Some(fields) = state.as_object() { - mirror() - .lock() - .expect("window mirror poisoned") - .insert(key, fields.clone()); - } -} - -/// Changes some fields of a window's state, leaving the rest. -pub fn patch(key: u32, fields: &[(&str, Value)]) { - let mut windows = mirror().lock().expect("window mirror poisoned"); - let state = windows.entry(key).or_default(); - for (name, value) in fields { - state.insert((*name).to_string(), value.clone()); - } -} - -/// What the app's state is derived from, for every known window. -pub fn facts() -> Vec { - let flag = |state: &serde_json::Map, name: &str, default: bool| { - state.get(name).and_then(Value::as_bool).unwrap_or(default) - }; - mirror() - .lock() - .expect("window mirror poisoned") - .values() - .map(|state| super::app_state::WindowFacts { - focused: flag(state, "isFocused", false), - minimized: flag(state, "isMinimized", false), - visible: flag(state, "isVisible", true), - }) - .collect() -} - -pub fn remove(key: u32) { - mirror() - .lock() - .expect("window mirror poisoned") - .remove(&key); -} - -/// The last state reported for a window, or `None` for an unknown one. -pub fn get(key: u32) -> Option { - let windows = mirror().lock().expect("window mirror poisoned"); - let state = windows.get(&key)?; - if !state.contains_key("bounds") { - return None; - } - let mut state = state.clone(); - state.insert("windowId".to_string(), json!(key)); - Some(Value::Object(state)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_patch_changes_only_its_fields() { - let key = 9001; - set( - key, - &json!({"bounds": {"x": 0, "y": 0, "width": 10, "height": 10}, "isFocused": false}), - ); - patch(key, &[("isFocused", json!(true))]); - let state = get(key).unwrap(); - assert_eq!(state["isFocused"], json!(true)); - assert_eq!(state["bounds"]["width"], json!(10)); - assert_eq!(state["windowId"], json!(key)); - remove(key); - assert!(get(key).is_none()); - } - - #[test] - fn a_window_with_no_bounds_is_unknown() { - let key = 9002; - patch(key, &[("isFocused", json!(true))]); - assert!(get(key).is_none()); - remove(key); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/windows.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/windows.rs deleted file mode 100644 index 581ccba26b..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/windows.rs +++ /dev/null @@ -1,1842 +0,0 @@ -//! One `ViewStore` owns every window: Fabric tags are unique across the -//! surfaces of a React instance, so nodes stay in one map. - -use crate::bootstrap::{WindowBackground, WindowTitleBar}; -use crate::desktop::errors::{DesktopError, DesktopResult}; -use crate::desktop::platform_window; -use crate::store::{store_from, StoreGlobal, SurfaceRootView}; -use gpui::{ - point, px, size, AnyWindowHandle, App, AppContext, Bounds, Global, Subscription, - TitlebarOptions, WindowBounds, WindowDecorations, WindowKind, WindowOptions, -}; -use serde_json::{json, Value}; -use std::collections::BTreeMap; -use std::collections::HashMap; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum WindowRole { - Main, - Secondary, - TrayPopover, -} - -pub struct WindowEntry { - pub key: u32, - pub handle: AnyWindowHandle, - pub surface_id: i32, - pub component: String, - pub props: Value, - pub role: WindowRole, - pub intercept_close: bool, - pub title: String, - pub subscriptions: Vec, -} - -pub struct DesktopWindows { - by_key: BTreeMap, - by_surface: HashMap, - next_key: u32, - next_surface: i32, -} - -pub struct DesktopWindowsGlobal(pub DesktopWindows); -impl Global for DesktopWindowsGlobal {} - -impl DesktopWindows { - pub fn new() -> Self { - Self { - by_key: BTreeMap::new(), - by_surface: HashMap::new(), - next_key: 2, - next_surface: 3, - } - } - - fn alloc_key(&mut self) -> u32 { - let key = self.next_key; - self.next_key += 1; - key - } - - /// Surface ids are odd. A surface id is also the tag of its root view, and - /// React numbers the views it creates 2, 4, 6…: an even surface id is the - /// tag of some view of another surface, and the new window's content is - /// then mounted inside that view instead of in its own window. - fn alloc_surface(&mut self) -> i32 { - let surface = self.next_surface; - self.next_surface += 2; - surface - } - - pub fn get(&self, key: u32) -> Option<&WindowEntry> { - self.by_key.get(&key) - } - - pub fn get_mut(&mut self, key: u32) -> Option<&mut WindowEntry> { - self.by_key.get_mut(&key) - } - - pub fn entry_for_surface(&self, surface_id: i32) -> Option<&WindowEntry> { - self.by_surface - .get(&surface_id) - .and_then(|key| self.by_key.get(key)) - } - - pub fn keys(&self) -> Vec { - self.by_key.keys().copied().collect() - } - - pub fn len(&self) -> usize { - self.by_key.len() - } - - pub fn adopt( - &mut self, - key: u32, - handle: AnyWindowHandle, - surface_id: i32, - component: String, - props: Value, - role: WindowRole, - ) { - self.by_key.insert( - key, - WindowEntry { - key, - handle, - surface_id, - component, - props, - role, - intercept_close: false, - title: String::new(), - subscriptions: Vec::new(), - }, - ); - self.by_surface.insert(surface_id, key); - } - - fn insert(&mut self, entry: WindowEntry) { - self.by_surface.insert(entry.surface_id, entry.key); - self.by_key.insert(entry.key, entry); - } - - fn remove(&mut self, key: u32) -> Option { - let entry = self.by_key.remove(&key)?; - self.by_surface.remove(&entry.surface_id); - Some(entry) - } -} - -impl Default for DesktopWindows { - fn default() -> Self { - Self::new() - } -} - -pub const MAIN_WINDOW_KEY: u32 = 1; - -#[derive(Clone, Debug, Default)] -pub struct OpenWindowOptions { - pub component: String, - pub props: Option, - pub title: Option, - pub width: Option, - pub height: Option, - pub x: Option, - pub y: Option, - pub resizable: bool, - /// What kind of title bar the window asks for. `Default` keeps the - /// platform's, which is what a secondary window gets unless it says - /// otherwise. - pub title_bar: WindowTitleBar, - pub background: WindowBackground, - /// `None` keeps the traffic lights and the shadow. - pub window_buttons: Option, - pub shadow: Option, - pub traffic_light_position: Option<(f32, f32)>, - pub role: WindowRoleOverride, - pub popup: bool, - /// Draw a popover at a corner of a window that covers the work area, for a - /// compositor that will not place it (Wayland). - #[cfg(target_os = "linux")] - pub overlay: Option, -} - -/// A window that is nothing but its own content (no system chrome, a see-through -/// background) and asks for no position is a launcher or a palette: it belongs in -/// the middle of the screen, and it goes away when the user turns to something -/// else. -#[cfg(target_os = "linux")] -fn is_launcher(options: &OpenWindowOptions) -> bool { - !options.popup - && options.x.is_none() - && options.y.is_none() - && options.title_bar == crate::bootstrap::WindowTitleBar::Borderless - && !matches!( - options.background, - crate::bootstrap::WindowBackground::Opaque - ) -} - -/// Wayland will not place a window, so a launcher is drawn in the middle of a -/// window covering the work area, which the compositor puts on the monitor it -/// chooses for a new window. -#[cfg(target_os = "linux")] -fn launcher_overlay( - options: &OpenWindowOptions, -) -> Option { - use crate::desktop::popover_placement::{Anchor, Reserved}; - if !is_launcher(options) || !crate::desktop::capabilities::is_wayland() { - return None; - } - Some(crate::desktop::window_frame::Placement { - anchor: Anchor::Center, - offset: (0.0, 0.0), - reserved: Reserved::default(), - size: ( - options.width.unwrap_or(800.0).max(120.0), - options.height.unwrap_or(600.0).max(120.0), - ), - click: None, - work_origin: (0.0, 0.0), - bare: true, - }) -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum WindowRoleOverride { - #[default] - Secondary, - TrayPopover, -} - -impl OpenWindowOptions { - fn role(&self) -> WindowRole { - match self.role { - WindowRoleOverride::Secondary => WindowRole::Secondary, - WindowRoleOverride::TrayPopover => WindowRole::TrayPopover, - } - } -} - -pub fn open_window(cx: &mut App, mut options: OpenWindowOptions) -> Result { - if options.component.is_empty() { - return Err(DesktopError::invalid_argument( - "window.open requires a component name", - )); - } - let store = - store_from(cx).ok_or_else(|| DesktopError::failed("the view store is not initialized"))?; - let (host, frame_hook) = { - let store = store.read(cx); - (store.host.clone(), store.frame_hook.clone()) - }; - let (key, surface_id) = { - let windows = &mut cx.global_mut::().0; - (windows.alloc_key(), windows.alloc_surface()) - }; - set_custom_title_bar(key, options.title_bar.is_custom()); - #[cfg(target_os = "linux")] - { - if options.overlay.is_none() { - options.overlay = launcher_overlay(&options); - } - if is_launcher(&options) { - crate::desktop::window_frame::mark_launcher(surface_id); - } - } - let framed = crate::desktop::window_frame::wanted( - matches!( - options.background, - crate::bootstrap::WindowBackground::Opaque - ), - options.shadow.unwrap_or(true), - options.title_bar == crate::bootstrap::WindowTitleBar::Borderless, - ); - #[cfg(target_os = "linux")] - match options.overlay { - Some(placement) => crate::desktop::window_frame::place(surface_id, placement), - None if framed || options.popup => crate::desktop::window_frame::enroll(surface_id), - None => {} - } - - let width = options.width.unwrap_or(800.0).max(120.0); - let height = options.height.unwrap_or(600.0).max(120.0); - // A popover's content is the size the app asked for, so on Linux the window - // is grown by the margin its frame needs, and placed that much earlier. - #[cfg(target_os = "linux")] - let overlay = options.overlay; - #[cfg(not(target_os = "linux"))] - let overlay: Option<()> = None; - let margin = if cfg!(target_os = "linux") && options.popup && overlay.is_none() { - crate::desktop::window_frame::frame().shadow_extent - } else { - 0.0 - }; - let (window_width, window_height) = if overlay.is_some() { - // Only a size to restore to: the window is maximized to the work area. - (1024.0, 768.0) - } else { - (width + 2.0 * margin, height + 2.0 * margin) - }; - let bounds = match (options.x, options.y) { - (Some(x), Some(y)) => Bounds::new( - point(px(x - margin), px(y - margin)), - size(px(window_width), px(window_height)), - ), - _ => Bounds::centered(None, size(px(window_width), px(window_height)), cx), - }; - // The placed origin, in points: what the popover's own window hints use. - let placed_origin = (f32::from(bounds.origin.x), f32::from(bounds.origin.y)); - let title = options - .title - .clone() - .unwrap_or_else(|| options.component.clone()); - let window_options = WindowOptions { - window_bounds: Some(if overlay.is_some() { - WindowBounds::Maximized(bounds) - } else { - WindowBounds::Windowed(bounds) - }), - // A popup (a tray popover) is a bare panel: with a title bar it is - // just another window that happens to open under the icon. - titlebar: (!options.popup).then(|| TitlebarOptions { - title: Some(title.clone().into()), - // macOS and Windows express "the app draws the bar" as a transparent - // title bar. Linux has no such flag and uses the decorations request - // below instead. - appears_transparent: options.title_bar.is_custom(), - traffic_light_position: options.traffic_light_position.map(|(x, y)| { - let (x, y) = crate::bootstrap::clamp_traffic_light_position(x, y, width, height); - point(px(x), px(y)) - }), - }), - is_resizable: options.resizable, - window_background: if cfg!(target_os = "linux") - && (options.title_bar.is_custom() || options.popup) - && (framed || options.popup) - && matches!( - options.background, - crate::bootstrap::WindowBackground::Opaque - ) { - gpui::WindowBackgroundAppearance::Transparent - } else { - options.background.appearance() - }, - is_movable: !options.popup && overlay.is_none(), - window_min_size: Some(size(px(120.0), px(120.0))), - // The tray popover is a normal, undecorated window on every platform, - // not `WindowKind::PopUp`: GPUI makes that override-redirect on X11, so - // the window manager never focuses it and it can never see the - // deactivation that dismisses it (see `platform_window::prepare_popover`). - // A frameless window with no decorations is what Electron's Linux tray - // menu uses too. `WindowDecorations::Client` is GPUI's frameless mode. - // A custom title bar asks for the same thing: on X11 and Wayland it is - // what removes the window manager's frame, and the app draws both the bar - // and the resize border itself. - kind: WindowKind::Normal, - window_decorations: (options.popup || options.title_bar.is_custom()) - .then_some(WindowDecorations::Client), - // The popover is mapped after it is prepared: the X11 window manager - // reads `_NET_WM_WINDOW_TYPE`, `_NET_WM_STATE` and the size hints when - // the window is mapped, so they are set on it while it is still hidden. - show: !options.popup || overlay.is_some(), - // A custom title bar means the app draws and moves the bar itself. - app_owns_titlebar_drag: options.title_bar.is_custom(), - ..Default::default() - }; - - let mut window_options = window_options; - let show_behind = crate::desktop::background::prepare(&mut window_options); - if !options.popup { - if let Some(display) = crate::desktop::background::test_display(cx) { - window_options.display_id = Some(display.id()); - window_options.window_bounds = Some(WindowBounds::Windowed(Bounds::centered( - Some(display.id()), - bounds.size, - cx, - ))); - } - } - let store_for_root = store; - crate::app_hooks::run_app_init(cx); - let handle = crate::app_hooks::open_root_window(cx, window_options, move |window, cx| { - let root = cx.new(|_| SurfaceRootView::new(surface_id)); - let window_handle: AnyWindowHandle = window.window_handle().into(); - store_for_root.update(cx, |store, cx| { - store.register_root(surface_id, root.clone()); - store.register_window(surface_id, window_handle); - cx.notify(); - }); - root - }) - .map_err(|error| DesktopError::failed(format!("could not open the window: {error}")))?; - if show_behind { - let _ = handle.update(cx, |_root, window, _cx| { - crate::desktop::background::show_behind(window); - }); - } - - let (w, h, scale, gave_back) = handle - .update(cx, |_root, window, _cx| { - #[cfg_attr(not(target_os = "linux"), allow(unused_mut))] - let mut gave_back = false; - // A compositor can refuse the decorations request for one window and - // grant it for another, so the capability follows the newest window. - crate::desktop::capabilities::note_window_decorations(window.window_decorations()); - #[cfg(target_os = "linux")] - { - // X11 window managers place a window as they like unless told its - // position was the user's, so the position asked for (or centred) - // is applied directly. Wayland has no such thing, and the call - // is refused there. - if !options.popup { - let _ = platform_window::set_position(window, placed_origin.0, placed_origin.1); - } - if is_launcher(&options) { - let _ = platform_window::skip_taskbar(window); - } - crate::desktop::window_frame::sync(window, surface_id); - // A compositor that left the decorations to itself draws no - // frame, so the margin the popover was grown by is given back. - if options.popup - && margin > 0.0 - && crate::desktop::window_frame::insets_of(surface_id).horizontal() == 0.0 - { - window.resize(size(px(width), px(height))); - if let (Some(x), Some(y)) = (options.x, options.y) { - // The window was created `margin` up and to the left. - let _ = platform_window::set_position(window, x, y); - } - gave_back = true; - } - } - let size = window.viewport_size(); - let frame = crate::desktop::window_frame::insets_of(surface_id); - ( - (f32::from(size.width) - frame.horizontal()).max(1.0), - (f32::from(size.height) - frame.vertical()).max(1.0), - window.scale_factor(), - gave_back, - ) - }) - .unwrap_or((width, height, 2.0, false)); - // A popover is created hidden, and a window that has not been shown has not - // had its first `WM_SIZE`, so what `viewport_size` reports for it is not - // something to start a surface from. The popover's own size is known, so the - // surface starts at that, and `prepare_popover` gives the window the same one. - #[cfg(any(target_os = "windows", target_os = "linux"))] - let (w, h) = if options.popup || overlay.is_some() { - (width, height) - } else { - (w, h) - }; - - let mut props = options.props.clone().unwrap_or_else(|| json!({})); - if !props.is_object() { - return Err(DesktopError::invalid_argument( - "window.open props must be an object", - )); - } - if let Some(object) = props.as_object_mut() { - object.insert("windowId".to_string(), json!(key)); - } - host.start_surface_with_props( - surface_id, - &options.component, - &props.to_string(), - w, - h, - scale, - ); - - let subscriptions = handle - .update(cx, |_root, window, cx| { - let mut subscriptions = Vec::new(); - if !options.popup { - crate::desktop::platform_window::style_window( - window, - options.window_buttons.unwrap_or(true), - options.shadow.unwrap_or(true), - options.title_bar, - ); - } - if options.popup { - crate::desktop::platform_window::style_as_popover(window); - // Set the popover's window hints while it is still unmapped, - // then ask the window manager to map and focus it. Failures are - // not fatal: a platform that needs none of this (or a Wayland - // session, which has no absolute placement) still gets a working - // window, just placed by the compositor. - // A popover whose frame margin was given back is placed by its - // content, which is where the margin had put the window's corner. - let (hint_x, hint_y, hint_width, hint_height) = if gave_back { - ( - placed_origin.0 + margin, - placed_origin.1 + margin, - width, - height, - ) - } else { - ( - placed_origin.0, - placed_origin.1, - window_width, - window_height, - ) - }; - if let Err(error) = crate::desktop::platform_window::prepare_popover( - window, - hint_x, - hint_y, - hint_width, - hint_height, - ) { - log::debug!("[desktop] popover window hints: {error}"); - } - } else { - // Every window of the app carries its icon, not only the first: - // on Windows it belongs to the window, so one opened later — a - // reopen from the tray, a secondary window — would show the - // default on its taskbar button. A popover has no button. - platform_window::apply_app_icon(window); - } - frame_hook.arm(window); - let ((bounds, state, activation), keep_alive) = - crate::app_hooks::observer_context(cx, |observers| { - let bounds = install_bounds_observer(window, observers, surface_id); - let state = install_state_observer(window, observers); - let activation = install_activation_observer(window, observers, key); - install_close_hook(window, observers, key); - (bounds, state, activation) - }); - subscriptions.extend([bounds, state, activation, keep_alive]); - subscriptions - }) - .map_err(|error| { - DesktopError::failed(format!("could not configure the window: {error}")) - })?; - - if options.popup { - // Map the popover and make it active, so it takes focus (and therefore - // can be dismissed when it loses it). The tray's own `focus` call - // already activates; this uses the pager source indication the window - // manager trusts, which is needed because a tray click arrives over - // D-Bus and carries no X timestamp. - let _ = handle.update(cx, |_root, window, _cx| { - window.activate_window(); - if let Err(error) = crate::desktop::platform_window::activate_popover(window) { - log::debug!("[desktop] popover activation: {error}"); - } - }); - } - - let role = options.role(); - let component = options.component.clone(); - let entry = WindowEntry { - key, - handle: handle.into(), - surface_id, - component, - props: options.props.take().unwrap_or_else(|| json!({})), - role, - intercept_close: false, - title, - subscriptions, - }; - cx.global_mut::().0.insert(entry); - if let Ok(state) = window_state(cx, key) { - super::window_mirror::set(key, &state); - } - super::app_state::schedule(cx); - log::info!( - "[desktop] opened window {key} (surface {surface_id}, {})", - options.component - ); - emit_window_event(cx, "gpuiDesktop:windowOpened", json!({"windowId": key})); - Ok(key) -} - -/// Without `force`, a window whose JS listener registered a veto emits -/// `closeRequested` and stays open. -pub fn close_window(cx: &mut App, key: u32, force: bool) -> DesktopResult { - let entry = { - let windows = &mut cx.global_mut::().0; - windows.remove(key) - }; - let Some(entry) = entry else { - return Err(DesktopError::not_found(format!("window {key} is not open"))); - }; - if !force && entry.intercept_close && entry.role != WindowRole::TrayPopover { - // Put it back and ask JS: the veto listener answers with - // `DesktopWindow.close({force: true})` or does nothing to keep it open. - let surface_id = entry.surface_id; - cx.global_mut::().0.insert(entry); - if let Some(store) = store_from(cx) { - let store = store.read(cx); - store.host.emit_device_event_json( - "gpuiDesktop:closeRequested", - &json!({"windowId": key}).to_string(), - ); - log::info!("[desktop] window {key} close deferred to JS (surface {surface_id})"); - } - return Ok(json!({"windowId": key, "deferred": true})); - } - finish_close(cx, key, entry, true); - Ok(json!({"windowId": key})) -} - -/// `remove_window` is false when the platform is already closing the window: -/// GPUI must not be asked to remove it again from inside that callback. -fn finish_close(cx: &mut App, key: u32, entry: WindowEntry, remove_window: bool) { - set_custom_title_bar(key, false); - super::window_mirror::remove(key); - super::app_state::schedule(cx); - let surface_id = entry.surface_id; - super::zoom::forget(surface_id); - let handle = entry.handle; - if let Some(store) = store_from(cx) { - // Only the registry entry is dropped here. `stop_surface` goes through - // Fabric's `SurfaceManager`, which can re-enter the JS thread while this - // update holds the store's lease; a mount batch for the surface that is - // still in the channel then has to wait for a lease that cannot be - // released until the stop returns. Deferring the stop lets queued - // batches apply first, which is also the order React Native expects: - // stop is the last thing a closing surface sees. - store.update(cx, |store, _cx| store.unregister_window(surface_id)); - let host = store.read(cx).host.clone(); - cx.defer(move |_cx| host.stop_surface(surface_id)); - } - if remove_window { - let _ = handle.update(cx, |_root, window, _cx| window.remove_window()); - } - log::info!("[desktop] closed window {key} (surface {surface_id})"); - emit_window_event(cx, "gpuiDesktop:windowClosed", json!({"windowId": key})); - // The closed window may have been covering its siblings; repaint them so no - // stale pixels are left where it used to be. - cx.refresh_windows(); - maybe_quit(cx); -} - -pub(crate) fn maybe_quit(cx: &mut App) { - if !quit_on_last_window_closed(cx) { - return; - } - let remaining = cx - .try_global::() - .map(|windows| windows.0.len()) - .unwrap_or(0); - if remaining == 0 { - cx.quit(); - } -} - -pub fn os_close(cx: &mut App, key: u32) -> bool { - let entry = if cx.has_global::() { - cx.global_mut::().0.remove(key) - } else { - None - }; - let Some(entry) = entry else { - return false; - }; - finish_close(cx, key, entry, false); - true -} - -pub fn install_close_hook_for(cx: &mut App, handle: AnyWindowHandle, key: u32) { - let _ = handle.update(cx, |_root, window, cx| { - crate::app_hooks::observer_context_for_good(cx, |observers| { - install_close_hook(window, observers, key); - }); - }); -} - -/// Reports the main window's bounds, state and focus to JS and to the state -/// mirror, as `open_window` does for the windows it creates. The main window -/// resizes the store through its own observer in `bootstrap`, so this only -/// reports. -static MAIN_STARTED_HIDDEN: std::sync::atomic::AtomicBool = - std::sync::atomic::AtomicBool::new(false); - -/// The main window was opened without being shown (`window.visible: false` or -/// `--hidden`), so it reports itself as not visible until it is shown. -pub fn note_main_started_hidden() { - MAIN_STARTED_HIDDEN.store(true, std::sync::atomic::Ordering::Relaxed); -} - -pub fn install_main_window_events(cx: &mut App, handle: AnyWindowHandle, key: u32) { - if let Ok(state) = window_state(cx, key) { - super::window_mirror::set(key, &state); - } - if MAIN_STARTED_HIDDEN.load(std::sync::atomic::Ordering::Relaxed) { - super::window_mirror::patch(key, &[("isVisible", json!(false))]); - } - super::app_state::schedule(cx); - let _ = handle.update(cx, |_root, window, app| { - crate::app_hooks::observer_context_for_good(app, |cx| { - let last = std::rc::Rc::new(std::cell::Cell::new(None::<(f32, f32, f32, f32)>)); - cx.observe_window_bounds(window, move |_root, window, cx| { - let bounds = window.bounds(); - let now = ( - f32::from(bounds.origin.x), - f32::from(bounds.origin.y), - f32::from(bounds.size.width), - f32::from(bounds.size.height), - ); - let previous = last.replace(Some(now)); - if previous == Some(now) { - return; - } - super::window_mirror::patch( - key, - &[ - ( - "bounds", - json!({"x": now.0, "y": now.1, "width": now.2, "height": now.3}), - ), - ("scaleFactor", json!(window.scale_factor())), - ("topInset", json!(top_inset(window, key))), - ], - ); - let Some(store) = cx.try_global::() else { - return; - }; - let host = store.0.read(cx).host.clone(); - if key == MAIN_WINDOW_KEY { - super::display::report(window, cx, &host); - } - emit_geometry(&host, key, previous, now); - }) - .detach(); - install_activation_observer(window, cx, key).detach(); - #[cfg(target_os = "windows")] - if let Some(store) = cx.try_global::() { - let host = store.0.read(cx).host.clone(); - super::keyboard::watch(window, host); - } - // Windows installs its own state observer for the main window. - if !cfg!(windows) { - install_state_observer(window, cx).detach(); - } - }); - }); -} - -fn quit_on_last_window_closed(cx: &App) -> bool { - !cx.try_global::() - .is_some_and(|flag| !flag.0) -} - -pub struct QuitOnLastWindowClosed(pub bool); -impl Global for QuitOnLastWindowClosed {} - -/// The window reopening the app opens once its last window is gone: the main -/// component, as the main window was configured. -pub struct ReopenWindow(pub OpenWindowOptions); -impl Global for ReopenWindow {} - -/// The Dock icon was clicked (or the app launched again) with no visible -/// window. A window that is only hidden or minimized is brought back; with none -/// left, the main component opens in a new one. -pub fn reopen(cx: &mut App) { - let existing = cx.try_global::().and_then(|windows| { - windows - .0 - .by_key - .values() - .find(|entry| entry.role != WindowRole::TrayPopover) - .map(|entry| entry.key) - }); - if let Some(key) = existing { - let _ = show(cx, key); - let _ = focus(cx, key); - return; - } - let Some(options) = cx.try_global::().map(|spec| spec.0.clone()) else { - return; - }; - match open_window(cx, options) { - Ok(key) => { - let _ = focus(cx, key); - } - Err(error) => log::error!("[desktop] reopen: {}", error.message), - } -} - -pub fn close(cx: &mut App, key: u32, force: bool) -> DesktopResult { - close_window(cx, key, force) -} - -pub fn focus(cx: &mut App, key: u32) -> DesktopResult { - let Some(entry) = cx.global::().0.get(key) else { - return Err(DesktopError::not_found(format!("window {key} is not open"))); - }; - let handle = entry.handle; - if crate::desktop::background::enabled() { - #[cfg(feature = "test-driver")] - return simulate_activation(cx, key, true); - #[cfg(not(feature = "test-driver"))] - return Ok(json!({"windowId": key, "focused": false})); - } - handle - .update(cx, |_root, window, _cx| window.activate_window()) - .map_err(|error| DesktopError::failed(format!("window {key} is gone: {error}")))?; - Ok(json!({"windowId": key, "focused": true})) -} - -pub(crate) fn with_window( - cx: &mut App, - key: u32, - action: impl FnOnce(&mut gpui::Window) -> Result<(), DesktopError>, -) -> DesktopResult { - let Some(entry) = cx.global::().0.get(key) else { - return Err(DesktopError::not_found(format!("window {key} is not open"))); - }; - let handle = entry.handle; - handle - .update(cx, |_root, window, _cx| action(window)) - .map_err(|error| DesktopError::failed(format!("window {key} is gone: {error}")))??; - Ok(json!({"windowId": key})) -} - -pub fn set_title(cx: &mut App, key: u32, title: String) -> DesktopResult { - if let Some(entry) = cx.global_mut::().0.get_mut(key) { - entry.title.clone_from(&title); - } - let changed = json!(title); - let result = with_window(cx, key, move |window| { - window.set_window_title(&title); - Ok(()) - }); - if result.is_ok() { - report_state_change(cx, key, &[("title", changed)]); - } - result -} - -/// Records fields of a window's state that no platform observer reports, and -/// tells JS they changed. -fn report_state_change(cx: &mut App, key: u32, fields: &[(&str, Value)]) { - super::window_mirror::patch(key, fields); - let mut payload = serde_json::Map::new(); - payload.insert("windowId".to_string(), json!(key)); - for (name, value) in fields { - payload.insert((*name).to_string(), value.clone()); - } - emit_window_event(cx, "gpuiDesktop:windowStateChange", Value::Object(payload)); -} - -const ZOOM_STEPS: [f32; 17] = [ - 0.25, 0.33, 0.5, 0.67, 0.75, 0.8, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0, -]; - -/// The factor one step from `current` in `direction`: `zoomIn`, `zoomOut`, or -/// `resetZoom` for 1. The steps are the ones a browser offers. -pub(crate) fn zoom_step(current: f32, direction: &str) -> f32 { - match direction { - "zoomIn" => ZOOM_STEPS - .iter() - .copied() - .find(|step| *step > current + 0.001) - .unwrap_or(5.0), - "zoomOut" => ZOOM_STEPS - .iter() - .rev() - .copied() - .find(|step| *step < current - 0.001) - .unwrap_or(0.25), - _ => 1.0, - } -} - -/// Zooms a window in or out by a step, or back to its natural size. -pub fn main_window_handle(cx: &App) -> Option { - cx.global::() - .0 - .get(MAIN_WINDOW_KEY) - .map(|entry| entry.handle) -} - -pub fn step_zoom(cx: &mut App, key: u32, direction: &str) -> DesktopResult { - let Some(entry) = cx.global::().0.get(key) else { - return Err(DesktopError::not_found(format!("window {key} is not open"))); - }; - let factor = zoom_step(super::zoom::get(entry.surface_id), direction); - set_zoom_factor(cx, key, factor) -} - -/// Scales a window's content, `1.0` being its natural size. The factor is -/// clamped to 0.25 to 5 and lasts until the window closes: remembering it across -/// launches is up to the app. -pub fn set_zoom_factor(cx: &mut App, key: u32, factor: f32) -> DesktopResult { - let Some(entry) = cx.global::().0.get(key) else { - return Err(DesktopError::not_found(format!("window {key} is not open"))); - }; - let (handle, surface_id) = (entry.handle, entry.surface_id); - let factor = super::zoom::set(surface_id, factor); - let Some(store) = store_from(cx) else { - return Ok(json!({"windowId": key})); - }; - handle - .update(cx, |_root, window, cx| { - let (size, scale) = (window.viewport_size(), window.scale_factor()); - store.update(cx, |store, cx| { - store.resize_window( - window.window_handle().into(), - f32::from(size.width), - f32::from(size.height), - scale, - cx, - ); - if let Some(root) = store.roots.get(&surface_id) { - root.update(cx, |_, cx| cx.notify()); - } - store.frame_hook.arm(window); - }); - }) - .map_err(|error| DesktopError::failed(format!("window {key} is gone: {error}")))?; - report_state_change(cx, key, &[("zoomFactor", json!(factor))]); - Ok(json!({"windowId": key})) -} - -/// Paints the window's own background, behind the content. -pub fn set_background_color(cx: &mut App, key: u32, argb: u32) -> DesktopResult { - with_window(cx, key, move |window| { - platform_window::set_background_color(window, argb).map_err(DesktopError::unsupported) - }) -} - -/// Gives the window's native chrome a light or dark look; `None` follows the system. -pub fn set_chrome_appearance(cx: &mut App, key: u32, dark: Option) -> DesktopResult { - with_window(cx, key, move |window| { - platform_window::set_chrome_appearance(window, dark).map_err(DesktopError::unsupported) - }) -} - -pub fn set_size(cx: &mut App, key: u32, width: f32, height: f32) -> DesktopResult { - with_window(cx, key, move |window| { - window.resize(gpui::size(px(width), px(height))); - Ok(()) - }) -} - -pub fn set_position(cx: &mut App, key: u32, x: f32, y: f32) -> DesktopResult { - if !platform_window::supports_position() { - return Err(DesktopError::unsupported( - "this session cannot position windows (Wayland has no absolute placement)", - )); - } - with_window(cx, key, move |window| { - platform_window::set_position(window, x, y).map_err(DesktopError::failed) - }) -} - -pub fn set_min_size(cx: &mut App, key: u32, width: f32, height: f32) -> DesktopResult { - with_window(cx, key, move |window| { - platform_window::set_min_size(window, width, height).map_err(DesktopError::unsupported) - }) -} - -pub fn set_max_size(cx: &mut App, key: u32, width: f32, height: f32) -> DesktopResult { - with_window(cx, key, move |window| { - platform_window::set_max_size(window, width, height).map_err(DesktopError::unsupported) - }) -} - -pub fn set_resizable(cx: &mut App, key: u32, resizable: bool) -> DesktopResult { - with_window(cx, key, move |window| { - platform_window::set_resizable(window, resizable).map_err(DesktopError::unsupported) - }) -} - -pub fn set_always_on_top(cx: &mut App, key: u32, on: bool) -> DesktopResult { - with_window(cx, key, move |window| { - platform_window::set_always_on_top(window, on).map_err(DesktopError::unsupported) - }) -} - -pub fn set_visible_on_all_workspaces(cx: &mut App, key: u32, visible: bool) -> DesktopResult { - with_window(cx, key, move |window| { - platform_window::set_visible_on_all_workspaces(window, visible) - .map_err(DesktopError::unsupported) - }) -} - -pub fn minimize(cx: &mut App, key: u32) -> DesktopResult { - let result = with_window(cx, key, |window| { - window.minimize_window(); - Ok(()) - }); - recheck_window_state_later(cx, key); - result -} - -pub fn move_focus(cx: &mut App, key: u32, backwards: bool) -> DesktopResult { - let Some(entry) = cx.global::().0.get(key) else { - return Err(DesktopError::not_found(format!("window {key} is not open"))); - }; - entry - .handle - .update(cx, |_root, window, cx| { - if backwards { - window.focus_prev(cx); - } else { - window.focus_next(cx); - } - }) - .map_err(|error| DesktopError::failed(format!("window {key} is gone: {error}")))?; - Ok(json!({"windowId": key})) -} - -pub fn maximize(cx: &mut App, key: u32) -> DesktopResult { - with_window(cx, key, |window| { - if !platform_window::is_maximized(window) { - window.zoom_window(); - } - Ok(()) - }) -} - -pub fn unmaximize(cx: &mut App, key: u32) -> DesktopResult { - with_window(cx, key, |window| { - if platform_window::is_maximized(window) { - window.zoom_window(); - } - Ok(()) - }) -} - -pub fn toggle_maximize(cx: &mut App, key: u32) -> DesktopResult { - with_window(cx, key, |window| { - window.zoom_window(); - Ok(()) - }) -} - -pub fn set_fullscreen(cx: &mut App, key: u32, fullscreen: bool) -> DesktopResult { - with_window(cx, key, move |window| { - if window.is_fullscreen() != fullscreen { - window.toggle_fullscreen(); - } - Ok(()) - }) -} - -/// Runs a native window operation once the update that asked for it has ended. -/// The operating system reports the change while it makes it, and GPUI's window -/// callbacks need the `App` that the update still holds. -fn run_outside_update(cx: &mut App, run: Box) { - cx.spawn(async move |_| run()).detach(); -} - -pub fn show(cx: &mut App, key: u32) -> DesktopResult { - let later = std::cell::RefCell::new(None); - let result = with_window(cx, key, |window| { - *later.borrow_mut() = - Some(platform_window::show_later(window).map_err(DesktopError::unsupported)?); - Ok(()) - }); - if let Some(run) = later.take() { - run_outside_update(cx, run); - recheck_window_state_later(cx, key); - reveal_later(cx, key); - } - if result.is_ok() { - report_state_change(cx, key, &[("isVisible", json!(true))]); - super::app_state::schedule(cx); - } - result -} - -/// The longest a window that was hidden is kept clear after it is shown. It is -/// revealed sooner, when the frames that follow the show have been drawn. -const REVEAL_LIMIT: std::time::Duration = std::time::Duration::from_millis(80); - -static LAST_REVEAL: std::sync::Mutex> = std::sync::Mutex::new(None); - -/// What made the last revealed window opaque: `frame` when the frames after the -/// show had been drawn, `timeout` when the limit came first. -pub fn last_reveal() -> Option<&'static str> { - *LAST_REVEAL.lock().expect("reveal state poisoned") -} - -/// Makes a window that was shown clear opaque once its first frame has been -/// drawn and handed to the compositor. The first frame callback runs as the -/// first frame after the show begins, the second as the next one begins, so the -/// first has been drawn by then. The limit covers a window that gets no frames, -/// such as one that other windows cover. -fn reveal_later(cx: &mut App, key: u32) { - *LAST_REVEAL.lock().expect("reveal state poisoned") = None; - let done = std::rc::Rc::new(std::cell::Cell::new(false)); - let reveal = { - let done = done.clone(); - move |window: &mut gpui::Window, reason: &'static str| { - if done.replace(true) { - return; - } - let _ = platform_window::reveal_window(window); - *LAST_REVEAL.lock().expect("reveal state poisoned") = Some(reason); - } - }; - let _ = with_window(cx, key, { - let reveal = reveal.clone(); - move |window| { - window.refresh(); - window.on_next_frame(move |window, _| { - window.on_next_frame(move |window, _| reveal(window, "frame")); - window.refresh(); - }); - Ok(()) - } - }); - cx.spawn(async move |cx| { - cx.background_executor().timer(REVEAL_LIMIT).await; - let _ = cx.update(|cx| { - let _ = with_window(cx, key, |window| { - reveal(window, "timeout"); - Ok(()) - }); - }); - }) - .detach(); -} - -pub fn hide(cx: &mut App, key: u32) -> DesktopResult { - let later = std::cell::RefCell::new(None); - let result = with_window(cx, key, |window| { - *later.borrow_mut() = - Some(platform_window::hide_later(window).map_err(DesktopError::unsupported)?); - Ok(()) - }); - if let Some(run) = later.take() { - run_outside_update(cx, run); - } - if result.is_ok() { - report_state_change(cx, key, &[("isVisible", json!(false))]); - super::app_state::schedule(cx); - } - result -} - -pub fn start_dragging(cx: &mut App, key: u32) -> DesktopResult { - with_window(cx, key, |window| { - window.start_window_move(); - Ok(()) - }) -} - -pub fn emit_window_event(cx: &App, name: &str, payload: Value) { - let Some(store) = store_from(cx) else { - return; - }; - let host = store.read(cx).host.clone(); - host.emit_device_event_json(name, &payload.to_string()); -} - -pub fn window_state(cx: &mut App, key: u32) -> DesktopResult { - let Some(entry) = cx.global::().0.get(key) else { - return Err(DesktopError::not_found(format!("window {key} is not open"))); - }; - let handle = entry.handle; - let surface_id = entry.surface_id; - let title = entry.title.clone(); - let visible = super::window_mirror::get(key) - .and_then(|state| state["isVisible"].as_bool()) - .unwrap_or(true); - handle - .update(cx, |_root, window, _cx| { - let bounds = window.bounds(); - json!({ - "windowId": key, - "bounds": { - "x": f32::from(bounds.origin.x), - "y": f32::from(bounds.origin.y), - "width": f32::from(bounds.size.width), - "height": f32::from(bounds.size.height), - }, - "isMaximized": platform_window::is_maximized(window), - "isFullscreen": window.is_fullscreen(), - "isFocused": is_active(window, key), - "isMinimized": platform_window::is_minimized(window), - "isVisible": visible, - "title": title, - "zoomFactor": super::zoom::get(surface_id), - "scaleFactor": window.scale_factor(), - "topInset": top_inset(window, key), - }) - }) - .map_err(|error| DesktopError::failed(format!("window {key} is gone: {error}"))) -} - -/// Windows whose title bar the app draws, by key. -static CUSTOM_TITLE_BARS: std::sync::Mutex> = - std::sync::Mutex::new(std::collections::BTreeSet::new()); - -pub fn set_custom_title_bar(key: u32, custom: bool) { - let mut keys = CUSTOM_TITLE_BARS.lock().expect("title bars poisoned"); - if custom { - keys.insert(key); - } else { - keys.remove(&key); - } -} - -/// The height of the `TitleBar` component, which is the bar an app draws under -/// a window without the platform's own. -const TITLE_BAR_HEIGHT: f32 = 38.0; - -/// How far the title bar reaches into the content area. On macOS that is the -/// system bar under a transparent title bar. Elsewhere it is the bar the app -/// draws: nonzero for a custom title bar, and on Linux only once the -/// compositor has agreed to client-side decorations. -pub fn top_inset(window: &gpui::Window, key: u32) -> f32 { - #[cfg(target_os = "macos")] - { - let _ = key; - crate::native_view::window_top_inset(window) - } - #[cfg(not(target_os = "macos"))] - { - let custom = CUSTOM_TITLE_BARS - .lock() - .expect("title bars poisoned") - .contains(&key); - #[cfg(target_os = "linux")] - let drawn_by_app = matches!( - window.window_decorations(), - gpui::Decorations::Client { .. } - ); - #[cfg(not(target_os = "linux"))] - let drawn_by_app = { - let _ = window; - true - }; - app_bar_inset(custom, drawn_by_app) - } -} - -#[cfg_attr(target_os = "macos", allow(dead_code))] -fn app_bar_inset(custom: bool, drawn_by_app: bool) -> f32 { - if custom && drawn_by_app { - TITLE_BAR_HEIGHT - } else { - 0.0 - } -} - -#[cfg(test)] -mod inset_tests { - use super::*; - - #[test] - fn only_a_bar_the_app_draws_takes_room() { - assert_eq!(app_bar_inset(true, true), TITLE_BAR_HEIGHT); - assert_eq!(app_bar_inset(true, false), 0.0); - assert_eq!(app_bar_inset(false, true), 0.0); - } - - #[test] - fn a_closed_window_forgets_its_bar() { - set_custom_title_bar(9_001, true); - assert!(CUSTOM_TITLE_BARS.lock().unwrap().contains(&9_001)); - set_custom_title_bar(9_001, false); - assert!(!CUSTOM_TITLE_BARS.lock().unwrap().contains(&9_001)); - } -} - -/// The OS's own frame for a window, in physical pixels, for the test driver: -/// `{left, top, right, bottom, visible}`, or `null` where the platform cannot say. -#[cfg(feature = "test-driver")] -pub fn native_frame_json(cx: &mut App, key: u32) -> Value { - #[cfg(target_os = "windows")] - { - let Some(entry) = cx.global::().0.get(key) else { - return Value::Null; - }; - let handle = entry.handle; - return handle - .update(cx, |_root, window, _cx| { - platform_window::native_frame(window).map(|(left, top, right, bottom, visible)| { - json!({ - "left": left, - "top": top, - "right": right, - "bottom": bottom, - "visible": visible, - }) - }) - }) - .ok() - .flatten() - .unwrap_or(Value::Null); - } - #[cfg(not(target_os = "windows"))] - { - let _ = (cx, key); - Value::Null - } -} - -pub fn list_windows(cx: &App) -> DesktopResult { - let windows = &cx.global::().0; - let list: Vec = windows - .keys() - .into_iter() - .filter_map(|key| { - let entry = windows.get(key)?; - Some(json!({ - "windowId": key, - "component": entry.component, - "role": match entry.role { - WindowRole::Main => "main", - WindowRole::Secondary => "secondary", - WindowRole::TrayPopover => "trayPopover", - }, - })) - }) - .collect(); - Ok(json!({"windows": list})) -} - -fn install_bounds_observer( - window: &mut gpui::Window, - cx: &mut gpui::Context, - surface_id: i32, -) -> Subscription { - let last = std::rc::Rc::new(std::cell::Cell::new(None::<(f32, f32, f32, f32)>)); - cx.observe_window_bounds(window, move |_root, window, cx| { - let size = window.viewport_size(); - let bounds = window.bounds(); - let (width, height) = (f32::from(size.width), f32::from(size.height)); - let (x, y) = (f32::from(bounds.origin.x), f32::from(bounds.origin.y)); - let scale = window.scale_factor(); - #[cfg(target_os = "linux")] - let frame_changed = crate::desktop::window_frame::sync(window, surface_id); - #[cfg(not(target_os = "linux"))] - let frame_changed = { - let _ = surface_id; - false - }; - let previous = last.replace(Some((x, y, width, height))); - if !frame_changed && previous == Some((x, y, width, height)) { - return; - } - let handle: AnyWindowHandle = window.window_handle().into(); - let Some(store) = cx.try_global::() else { - return; - }; - let store = store.0.clone(); - store.update(cx, |store, cx| { - store.resize_window(handle, width, height, scale, cx) - }); - let frame_hook = store.read(cx).frame_hook.clone(); - frame_hook.arm(window); - if let Some(key) = window_key_for_handle(cx, handle) { - super::window_mirror::patch( - key, - &[ - ( - "bounds", - json!({ - "x": x, - "y": y, - "width": f32::from(bounds.size.width), - "height": f32::from(bounds.size.height), - }), - ), - ("scaleFactor", json!(scale)), - ("topInset", json!(top_inset(window, key))), - ], - ); - let host = store.read(cx).host.clone(); - emit_geometry(&host, key, previous, (x, y, width, height)); - } - }) -} - -/// Sends `windowResize` and `windowMove` for what changed between two -/// `(x, y, width, height)` bounds: a drag only moves, a resize from the -/// bottom-right edge only resizes. -fn emit_geometry( - host: &crate::host::Host, - key: u32, - previous: Option<(f32, f32, f32, f32)>, - now: (f32, f32, f32, f32), -) { - let (x, y, width, height) = now; - if previous.is_none_or(|(_, _, w, h)| (w, h) != (width, height)) { - host.emit_device_event_json( - "gpuiDesktop:windowResize", - &json!({"windowId": key, "width": width, "height": height}).to_string(), - ); - } - if previous.is_none_or(|(px, py, _, _)| (px, py) != (x, y)) { - host.emit_device_event_json( - "gpuiDesktop:windowMove", - &json!({"windowId": key, "x": x, "y": y}).to_string(), - ); - } -} - -pub(crate) fn window_key_for_handle(cx: &gpui::App, handle: AnyWindowHandle) -> Option { - let windows = cx.try_global::()?; - windows - .0 - .keys() - .into_iter() - .find(|key| windows.0.get(*key).map(|entry| entry.handle) == Some(handle)) -} - -/// Sends `gpuiDesktop:windowStateChange` when the window is maximized, restored, -/// minimized or made fullscreen. -/// -/// `DesktopWindow`'s `stateChange` listeners wait on it, and so does a caption -/// button's maximize glyph, which has to turn into the restore glyph however the -/// window got maximized — a double click on the title bar, Win+Up, a snap — not -/// only when the button itself was pressed. Every one of those resizes the -/// window, so the bounds observer is where the change is seen. -pub(crate) fn install_state_observer( - window: &mut gpui::Window, - cx: &mut gpui::Context, -) -> Subscription { - let state_of = |window: &gpui::Window| { - ( - platform_window::is_maximized(window), - platform_window::is_minimized(window), - window.is_fullscreen(), - ) - }; - let mut last = state_of(window); - cx.observe_window_bounds(window, move |_root, window, cx| { - let state = state_of(window); - if state == last { - return; - } - last = state; - let handle: AnyWindowHandle = window.window_handle().into(); - let Some(key) = window_key_for_handle(cx, handle) else { - return; - }; - publish_window_state(cx, key, state); - }) -} - -fn publish_window_state(cx: &mut App, key: u32, state: (bool, bool, bool)) { - super::window_mirror::patch( - key, - &[ - ("isMaximized", json!(state.0)), - ("isMinimized", json!(state.1)), - ("isFullscreen", json!(state.2)), - ], - ); - super::app_state::schedule(cx); - let Some(store) = cx.try_global::() else { - return; - }; - let host = store.0.read(cx).host.clone(); - host.emit_device_event_json( - "gpuiDesktop:windowStateChange", - &json!({ - "windowId": key, - "isMaximized": state.0, - "isMinimized": state.1, - "isFullscreen": state.2, - }) - .to_string(), - ); -} - -/// Reads the window's maximized, minimized and fullscreen state again a moment -/// after a command, and publishes it if it changed. A window that is not key, -/// as in a background run, does not always send the bounds change that the -/// observer waits for when it is minimized or brought back. -fn recheck_window_state_later(cx: &mut App, key: u32) { - cx.spawn(async move |cx| { - for delay in [250u64, 750, 1500] { - cx.background_executor() - .timer(std::time::Duration::from_millis(delay)) - .await; - let _ = cx.update(|cx| { - let Some(handle) = cx - .global::() - .0 - .get(key) - .map(|entry| entry.handle) - else { - return; - }; - let state = handle - .update(cx, |_root, window, _cx| { - ( - platform_window::is_maximized(window), - platform_window::is_minimized(window), - window.is_fullscreen(), - ) - }) - .ok(); - let Some(state) = state else { - return; - }; - let known = super::window_mirror::get(key); - let flag = |name: &str| { - known - .as_ref() - .and_then(|value| value.get(name)) - .and_then(Value::as_bool) - }; - if flag("isMaximized") != Some(state.0) - || flag("isMinimized") != Some(state.1) - || flag("isFullscreen") != Some(state.2) - { - publish_window_state(cx, key, state); - } - }); - } - }) - .detach(); -} - -/// Reports focus changes to the mirror and to JS. JS can mount before the -/// window's state is published and then holds no state, so the window counts as -/// not focused until it is reported: one check runs once the install has -/// finished and reports a window that is already active. -fn install_activation_observer( - window: &mut gpui::Window, - cx: &mut gpui::Context, - key: u32, -) -> Subscription { - let last = std::rc::Rc::new(std::cell::Cell::new(false)); - window.defer(cx, { - let last = last.clone(); - move |window, cx| report_activation(window, cx, key, &last) - }); - cx.observe_window_activation(window, move |_root, window, cx| { - if !window.is_window_active() { - crate::tooltip::dismiss(window, cx); - } - report_activation(window, cx, key, &last); - }) -} - -/// What a test says a window's activation is, in place of the operating -/// system's answer. -#[cfg(feature = "test-driver")] -fn simulated_activation(key: u32) -> Option { - SIMULATED_ACTIVATION - .lock() - .expect("simulated activation poisoned") - .get(&key) - .copied() -} - -#[cfg(not(feature = "test-driver"))] -fn simulated_activation(_key: u32) -> Option { - None -} - -#[cfg(feature = "test-driver")] -static SIMULATED_ACTIVATION: std::sync::Mutex> = - std::sync::Mutex::new(BTreeMap::new()); - -fn is_active(window: &gpui::Window, key: u32) -> bool { - simulated_activation(key).unwrap_or_else(|| window.is_window_active()) -} - -/// Makes a window active or inactive as far as the app can tell, whatever the -/// operating system thinks, so a test does not depend on which application is in -/// front. The window then ignores real activation changes. -#[cfg(feature = "test-driver")] -pub fn simulate_activation(cx: &mut App, key: u32, active: bool) -> DesktopResult { - SIMULATED_ACTIVATION - .lock() - .expect("simulated activation poisoned") - .insert(key, active); - let Some(entry) = cx.global::().0.get(key) else { - return Err(DesktopError::not_found(format!("window {key} is not open"))); - }; - let handle = entry.handle; - handle - .update(cx, |_root, window, cx| { - report_activation(window, cx, key, &std::cell::Cell::new(!active)); - }) - .map_err(|error| DesktopError::failed(format!("window {key} is gone: {error}")))?; - Ok(json!({"windowId": key})) -} - -fn report_activation( - window: &mut gpui::Window, - cx: &mut App, - key: u32, - last: &std::cell::Cell, -) { - let active = is_active(window, key); - if active == last.get() { - return; - } - last.set(active); - if !active { - crate::events::cancel_presses(window, cx); - } - super::window_mirror::patch(key, &[("isFocused", json!(active))]); - super::app_state::schedule(cx); - let Some(store) = cx.try_global::() else { - return; - }; - let host = store.0.read(cx).host.clone(); - if active && key == MAIN_WINDOW_KEY { - // The text scale is changed in system settings, outside the app. - super::display::report(window, cx, &host); - } - let name = if active { - "gpuiDesktop:windowFocus" - } else { - "gpuiDesktop:windowBlur" - }; - host.emit_device_event_json(name, &json!({"windowId": key}).to_string()); - if !active { - let is_popover = cx - .try_global::() - .is_some_and(|tray| { - let mut tray = tray.0.borrow_mut(); - if tray.popover == Some(key) { - tray.popover = None; - tray.popover_dismissed_at = Some(std::time::Instant::now()); - true - } else { - false - } - }); - // A launcher closes when the user turns to another window. On Wayland it - // could not stay above that window anyway, and would be left behind it, - // invisible and still open. - #[cfg(target_os = "linux")] - let is_launcher = cx - .try_global::() - .and_then(|windows| windows.0.get(key)) - .is_some_and(|entry| crate::desktop::window_frame::is_launcher(entry.surface_id)); - #[cfg(not(target_os = "linux"))] - let is_launcher = false; - if is_popover || is_launcher { - // Deferred: this runs inside the activation change's window update, - // and closing a window from there re-enters it, which GPUI reports - // as "RefCell already borrowed". - cx.defer(move |cx| { - let _ = close_window(cx, key, true); - }); - } - } -} - -/// Asks the Modal shown last to close itself, as `onRequestClose`, and says -/// whether one was shown. -pub(crate) fn request_modal_close(window: &mut gpui::Window, cx: &mut gpui::App) -> bool { - let Some(store) = crate::store::store_from(cx) else { - return false; - }; - let target = { - let store = store.read(cx); - store - .nodes - .iter() - .filter_map(|(tag, node)| { - let node = node.read(cx); - let portal = - crate::extensions::component_portal(&node.component, node.extension_props())?; - portal - .visible - .then_some(portal.close_request_event) - .flatten() - .map(|event| (*tag, event)) - }) - .max_by_key(|(tag, _)| *tag) - }; - let Some((tag, event)) = target else { - return false; - }; - let store = store.read(cx); - store - .host - .dispatch_event(tag, &event, &serde_json::json!({})); - store.frame_hook.arm(window); - true -} - -fn install_close_hook(window: &mut gpui::Window, cx: &mut gpui::Context, key: u32) { - let last_request: std::rc::Rc>> = - std::rc::Rc::new(std::cell::Cell::new(None)); - window.on_window_should_close(cx, move |window, cx| { - // A visible Modal answers the close button first, as it answers the - // Escape key: `onRequestClose` decides, and the window stays. - if request_modal_close(window, cx) { - return false; - } - let intercept = cx - .try_global::() - .and_then(|windows| windows.0.get(key).map(|entry| entry.intercept_close)) - .unwrap_or(false); - // A second close request within three seconds closes the window even if - // JS never answered, so a hung or mid-reload app can always be quit. - let unanswered = intercept - && last_request.get().is_some_and(|previous| { - std::time::Instant::now().duration_since(previous) - < std::time::Duration::from_secs(3) - }); - // A tray that asked for it keeps the last window: hidden, not destroyed, so - // that opening the app again shows it with its state. JavaScript's own - // veto (`closeRequested`) comes first, below, and decides for itself. - if !intercept && hides_on_close(cx, key) { - if let Err(error) = platform_window::hide(window) { - log::warn!("[desktop] could not hide window {key}: {error}"); - } else { - log::info!("[desktop] hid window {key} instead of closing it"); - return false; - } - } - if !intercept || unanswered { - if unanswered { - log::warn!("[desktop] window {key} close was not answered by JS; closing"); - } - // The OS is closing it: run the same teardown as `close_window`, - // without asking GPUI to remove a window it is already removing. - let entry = if cx.has_global::() { - cx.global_mut::().0.remove(key) - } else { - None - }; - if let Some(entry) = entry { - finish_close(cx, key, entry, false); - } - return true; - } - last_request.set(Some(std::time::Instant::now())); - emit_close_requested(cx, window, key); - false - }); -} - -/// Whether closing window `key` should hide it instead. -fn hides_on_close(cx: &App, key: u32) -> bool { - let Some(windows) = cx.try_global::() else { - return false; - }; - let Some(entry) = windows.0.get(key) else { - return false; - }; - let other_windows_open = windows - .0 - .by_key - .values() - .any(|other| other.key != key && other.role != WindowRole::TrayPopover); - should_hide_on_close( - crate::desktop::tray::hides_window_on_close(cx), - quit_on_last_window_closed(cx), - entry.role, - other_windows_open, - ) -} - -/// The decision, apart from where its inputs come from. -/// -/// Only the last window the user can close is hidden: closing one of several -/// closes it, as it always did. A popover is never hidden — it is closed so each -/// show opens a fresh one. And an app that quits when its last window closes is -/// not asking for a window to be kept, whatever else it set. -fn should_hide_on_close( - hide_requested: bool, - quits_on_last_window: bool, - role: WindowRole, - other_windows_open: bool, -) -> bool { - hide_requested - && !quits_on_last_window - && role != WindowRole::TrayPopover - && !other_windows_open -} - -fn emit_close_requested(cx: &mut App, window: &mut gpui::Window, key: u32) { - let Some(store) = cx.try_global::() else { - return; - }; - let host = store.0.read(cx).host.clone(); - host.emit_device_event_json( - "gpuiDesktop:closeRequested", - &json!({"windowId": key}).to_string(), - ); - store.0.read(cx).frame_hook.arm(window); -} - -pub fn window_id_for_surface(cx: &App, surface_id: i32) -> Option { - cx.try_global::().and_then(|windows| { - windows - .0 - .entry_for_surface(surface_id) - .map(|entry| entry.key) - }) -} - -#[cfg(test)] -mod tests { - #[test] - fn zoom_steps_follow_the_browser_levels() { - assert_eq!(zoom_step(1.0, "zoomIn"), 1.1); - assert_eq!(zoom_step(1.0, "zoomOut"), 0.9); - assert_eq!(zoom_step(1.3, "zoomIn"), 1.5); - assert_eq!(zoom_step(5.0, "zoomIn"), 5.0); - assert_eq!(zoom_step(0.25, "zoomOut"), 0.25); - assert_eq!(zoom_step(2.0, "resetZoom"), 1.0); - } - - use super::*; - - #[test] - fn keys_and_surfaces_are_allocated_without_collisions() { - let mut windows = DesktopWindows::new(); - assert_eq!(windows.alloc_key(), 2); - assert_eq!(windows.alloc_key(), 3); - assert_eq!(windows.alloc_surface(), 3); - assert_eq!(windows.alloc_surface(), 5); - assert_eq!(windows.alloc_surface(), 7); - assert!(windows.keys().is_empty()); - assert!(windows.get(1).is_none()); - assert!(windows.entry_for_surface(1).is_none()); - } - - #[test] - fn the_last_window_is_hidden_when_the_tray_asked_for_it() { - assert!(should_hide_on_close(true, false, WindowRole::Main, false)); - assert!(should_hide_on_close( - true, - false, - WindowRole::Secondary, - false - )); - } - - #[test] - fn nothing_is_hidden_unless_it_was_asked_for() { - assert!(!should_hide_on_close(false, false, WindowRole::Main, false)); - } - - #[test] - fn closing_one_of_several_windows_still_closes_it() { - assert!(!should_hide_on_close(true, false, WindowRole::Main, true)); - } - - #[test] - fn a_popover_is_closed_never_hidden() { - assert!(!should_hide_on_close( - true, - false, - WindowRole::TrayPopover, - false - )); - } - - #[test] - fn an_app_that_quits_with_its_last_window_keeps_none() { - assert!(!should_hide_on_close(true, true, WindowRole::Main, false)); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/work_area.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/work_area.rs deleted file mode 100644 index a09a6884b6..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/work_area.rs +++ /dev/null @@ -1,89 +0,0 @@ -//! The screen's work area on Linux: what is left once panels and docks have -//! taken their space. -//! -//! The X11 window manager publishes it on the root window as `_NET_WORKAREA`, -//! and the compositor's XWayland does the same on Wayland, where a client has no -//! other way to learn it. Reading it needs no window of our own. - -use std::os::raw::{c_int, c_long, c_uchar, c_ulong}; - -/// The whole screen and the work area inside it, in the units X reports, which -/// are points at a scale of one. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct WorkArea { - pub screen: (f32, f32), - /// `(x, y, width, height)`. - pub area: (f32, f32, f32, f32), -} - -pub fn read() -> Option { - let xlib = x11_dl::xlib::Xlib::open().ok()?; - // SAFETY: the display is opened and closed within this function, the atoms and - // properties are read through the library's own calls, and every pointer the - // calls fill in is freed with `XFree`. - unsafe { - let display = (xlib.XOpenDisplay)(std::ptr::null()); - if display.is_null() { - return None; - } - let root = (xlib.XDefaultRootWindow)(display); - let area = cardinals(&xlib, display, root, "_NET_WORKAREA", 4); - let screen = cardinals(&xlib, display, root, "_NET_DESKTOP_GEOMETRY", 2); - (xlib.XCloseDisplay)(display); - let (area, screen) = (area?, screen?); - let result = WorkArea { - screen: (screen[0] as f32, screen[1] as f32), - area: ( - area[0] as f32, - area[1] as f32, - area[2] as f32, - area[3] as f32, - ), - }; - (result.area.2 > 0.0 && result.area.3 > 0.0 && result.screen.0 > 0.0).then_some(result) - } -} - -/// The first `count` values of a 32-bit property of a window. -unsafe fn cardinals( - xlib: &x11_dl::xlib::Xlib, - display: *mut x11_dl::xlib::Display, - window: c_ulong, - name: &str, - count: usize, -) -> Option> { - let name = std::ffi::CString::new(name).ok()?; - let atom = (xlib.XInternAtom)(display, name.as_ptr(), 1); - if atom == 0 { - return None; - } - let mut actual_type: c_ulong = 0; - let mut actual_format: c_int = 0; - let mut items: c_ulong = 0; - let mut remaining: c_ulong = 0; - let mut data: *mut c_uchar = std::ptr::null_mut(); - let status = (xlib.XGetWindowProperty)( - display, - window, - atom, - 0, - count as c_long, - 0, - 0, - &mut actual_type, - &mut actual_format, - &mut items, - &mut remaining, - &mut data, - ); - let values = if status == 0 && actual_format == 32 && items as usize >= count && !data.is_null() - { - Some(std::slice::from_raw_parts(data as *const c_long, count).to_vec()) - } else { - None - }; - if !data.is_null() { - (xlib.XFree)(data as *mut _); - } - values -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/zoom.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/zoom.rs deleted file mode 100644 index ff1327bec1..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/desktop/zoom.rs +++ /dev/null @@ -1,58 +0,0 @@ -//! A window's zoom factor: how much its content is scaled up or down. -//! -//! The surface is laid out at the window's size divided by the factor, with the -//! factor folded into the scale React sees, and drawn under a matrix that scales -//! it back up. Pointer positions are divided by the factor on their way in. - -use std::cell::RefCell; -use std::collections::HashMap; - -pub const MIN: f32 = 0.25; -pub const MAX: f32 = 5.0; - -thread_local! { - static FACTORS: RefCell> = RefCell::new(HashMap::new()); -} - -/// The factor of the window a surface is shown in, `1.0` when never set. -pub fn get(surface_id: i32) -> f32 { - FACTORS.with_borrow(|factors| factors.get(&surface_id).copied().unwrap_or(1.0)) -} - -/// Records a factor, clamped to the supported range, and returns it. -pub fn set(surface_id: i32, factor: f32) -> f32 { - let factor = if factor.is_finite() { - factor.clamp(MIN, MAX) - } else { - 1.0 - }; - FACTORS.with_borrow_mut(|factors| { - if (factor - 1.0).abs() < f32::EPSILON { - factors.remove(&surface_id); - } else { - factors.insert(surface_id, factor); - } - }); - factor -} - -pub fn forget(surface_id: i32) { - FACTORS.with_borrow_mut(|factors| { - factors.remove(&surface_id); - }); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_factor_is_clamped_and_one_is_forgotten() { - assert_eq!(set(9101, 100.0), MAX); - assert_eq!(get(9101), MAX); - assert_eq!(set(9101, 0.0), MIN); - assert_eq!(set(9101, f32::NAN), 1.0); - assert_eq!(get(9101), 1.0); - forget(9101); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/drag_drop.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/drag_drop.rs deleted file mode 100644 index 832a5175e5..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/drag_drop.rs +++ /dev/null @@ -1,373 +0,0 @@ -//! Dragging a view to another view inside the app. -//! -//! A left press on a `draggable` view is remembered. Once the pointer has moved -//! `THRESHOLD` points the drag starts: the press is cancelled for React, the -//! source gets `onDragStart`, and from then on every pointer move retargets the -//! drag, wherever the pointer is. The nearest `droppable` view on the path under -//! the pointer gets `onDragEnter`, `onDragOver` and `onDragLeave`, and the -//! release sends it `onDrop`. The source gets `onDrag` with each move and -//! `onDragEnd` at the end. -//! -//! The payload lives in JavaScript: it is set in `onDragStart`, and the events -//! here arrive in order, so it is there before the first enter. The same moves -//! are emitted as `gpuiDesktop:dragStart`, `gpuiDesktop:dragMove` and -//! `gpuiDesktop:dragEnd` device events, which is what a drag preview and -//! auto-scrolling follow. - -use crate::events::Target; -use crate::store::StoreGlobal; -use gpui::{App, Pixels, Point, Window}; -use serde_json::{json, Value}; -use std::cell::{Cell, RefCell}; - -const THRESHOLD: f32 = 4.0; - -struct Pending { - source: i32, - start: Point, - origin: Target, -} - -struct Active { - source: i32, - id: u64, - origin: Target, - target: Option, - last_target: Option, - position: Point, -} - -enum Session { - Pending(Pending), - Active(Active), -} - -thread_local! { - static SESSION: RefCell> = const { RefCell::new(None) }; - static NEXT_ID: Cell = const { Cell::new(1) }; -} - -/// Whether a press on a draggable view is held, started dragging or not. -pub(crate) fn tracking() -> bool { - SESSION.with_borrow(Option::is_some) -} - -/// A left press landed on `target`. The nearest draggable view on its path, the -/// target first, becomes the source if the pointer moves. -pub(crate) fn press(cx: &App, target: &Target, position: Point) { - let source = target - .chain - .iter() - .copied() - .find(|tag| node_flag(cx, *tag, |node| node.draggable())); - SESSION.with_borrow_mut(|session| { - *session = source.map(|source| { - Session::Pending(Pending { - source, - start: position, - origin: target.clone(), - }) - }); - }); -} - -fn node_flag(cx: &App, tag: i32, flag: impl Fn(&crate::node_view::RNNodeView) -> bool) -> bool { - cx.try_global::().is_some_and(|store| { - store - .0 - .read(cx) - .nodes - .get(&tag) - .is_some_and(|node| flag(node.read(cx))) - }) -} - -fn droppable_view(cx: &App, target: &Target) -> Option { - target - .chain - .iter() - .copied() - .find(|tag| node_flag(cx, *tag, |node| node.droppable())) -} - -/// The pointer moved with the button held. `target` is the node under it, if -/// any node answered. -pub(crate) fn moved( - window: &mut Window, - cx: &mut App, - target: Option<&Target>, - position: Point, - pressed: bool, -) { - if !pressed { - return; - } - let start = SESSION.with_borrow_mut(|session| match session { - Some(Session::Pending(pending)) => { - let dx = f32::from(position.x - pending.start.x); - let dy = f32::from(position.y - pending.start.y); - if (dx * dx + dy * dy).sqrt() < THRESHOLD { - return None; - } - let id = NEXT_ID.replace(NEXT_ID.get() + 1); - let active = Active { - source: pending.source, - id, - origin: pending.origin.clone(), - target: None, - last_target: None, - position, - }; - let started = (active.source, id, active.origin.clone()); - *session = Some(Session::Active(active)); - Some(started) - } - _ => None, - }); - if let Some((source, id, origin)) = start { - crate::events::cancel_active_touch(window, cx, position); - let page = origin.page(position); - notify(window, cx, "topDragStart", source, &origin, position, None); - emit( - cx, - "gpuiDesktop:dragStart", - json!({ "source": source, "id": id, "x": f32::from(page.x), "y": f32::from(page.y) }), - ); - } - let Some((source, id, origin)) = SESSION.with_borrow(|session| match session { - Some(Session::Active(active)) => Some((active.source, active.id, active.origin.clone())), - _ => None, - }) else { - return; - }; - retarget(window, cx, target, position, true); - notify(window, cx, "topDrag", source, &origin, position, None); - let page = origin.page(position); - let over = SESSION.with_borrow(|session| match session { - Some(Session::Active(active)) => active.target, - _ => None, - }); - emit( - cx, - "gpuiDesktop:dragMove", - json!({ - "source": source, - "id": id, - "x": f32::from(page.x), - "y": f32::from(page.y), - "over": over, - }), - ); -} - -/// The left button was released over `target`, if a node answered. -/// Whether a drag was under way and this ended it. A press that never became a -/// drag is only forgotten, and the release still belongs to the touch. -pub(crate) fn released( - window: &mut Window, - cx: &mut App, - target: Option<&Target>, - position: Point, -) -> bool { - let Some(session) = SESSION.with_borrow_mut(Option::take) else { - return false; - }; - let Session::Active(active) = session else { - return false; - }; - let accepting = target.and_then(|target| droppable_view(cx, target)); - if let (Some(tag), Some(target)) = (accepting, target) { - deliver( - window, - cx, - "topDrop", - tag, - target, - position, - Some(active.source), - ); - } - crate::interaction::set_drag(None, cx); - finish(window, cx, active, position, accepting.is_some()); - true -} - -/// The drag ended without a drop. -pub(crate) fn cancel(window: &mut Window, cx: &mut App) -> bool { - let Some(session) = SESSION.with_borrow_mut(Option::take) else { - return false; - }; - let Session::Active(active) = session else { - return false; - }; - let position = active.position; - let last = active.last_target.clone(); - if let (Some(tag), Some(last)) = (active.target, last.as_ref()) { - deliver( - window, - cx, - "topDragLeave", - tag, - last, - position, - Some(active.source), - ); - } - crate::interaction::set_drag(None, cx); - finish(window, cx, active, position, false); - true -} - -fn finish( - window: &mut Window, - cx: &mut App, - active: Active, - position: Point, - dropped: bool, -) { - notify( - window, - cx, - "topDragEnd", - active.source, - &active.origin, - position, - Some(dropped), - ); - let page = active.origin.page(position); - emit( - cx, - "gpuiDesktop:dragEnd", - json!({ - "source": active.source, - "id": active.id, - "x": f32::from(page.x), - "y": f32::from(page.y), - "dropped": dropped, - }), - ); -} - -fn retarget( - window: &mut Window, - cx: &mut App, - target: Option<&Target>, - position: Point, - over: bool, -) { - let accepting = target.and_then(|target| droppable_view(cx, target)); - let Some((previous, last, source)) = SESSION.with_borrow_mut(|session| match session { - Some(Session::Active(active)) => { - active.position = position; - let previous = std::mem::replace(&mut active.target, accepting); - let last = active.last_target.clone(); - if let Some(target) = target { - active.last_target = Some(target.clone()); - } - Some((previous, last, active.source)) - } - _ => None, - }) else { - return; - }; - if previous != accepting { - if let (Some(tag), Some(from)) = (previous, last.as_ref().or(target)) { - deliver( - window, - cx, - "topDragLeave", - tag, - from, - position, - Some(source), - ); - } - if let (Some(tag), Some(target)) = (accepting, target) { - deliver( - window, - cx, - "topDragEnter", - tag, - target, - position, - Some(source), - ); - } - crate::interaction::set_drag(accepting, cx); - } - if let (true, Some(tag), Some(target)) = (over, accepting, target) { - deliver( - window, - cx, - "topDragOver", - tag, - target, - position, - Some(source), - ); - } -} - -fn deliver( - window: &mut Window, - cx: &mut App, - name: &str, - tag: i32, - target: &Target, - position: Point, - source: Option, -) { - let Some(store) = cx.try_global::().map(|store| store.0.clone()) else { - return; - }; - let page = target.page(position); - let local = target.local_position(page); - let payload = json!({ - "target": tag, - "x": f32::from(local.x), - "y": f32::from(local.y), - "pageX": f32::from(page.x), - "pageY": f32::from(page.y), - "files": Vec::::new(), - "source": source, - }); - let store = store.read(cx); - store.host.dispatch_event(tag, name, &payload); - store.frame_hook.arm(window); -} - -fn notify( - window: &mut Window, - cx: &mut App, - name: &str, - source: i32, - origin: &Target, - position: Point, - dropped: Option, -) { - let Some(store) = cx.try_global::().map(|store| store.0.clone()) else { - return; - }; - let page = origin.page(position); - let mut payload = json!({ - "target": source, - "pageX": f32::from(page.x), - "pageY": f32::from(page.y), - }); - if let Some(dropped) = dropped { - payload["dropped"] = json!(dropped); - } - let store = store.read(cx); - store.host.dispatch_event(source, name, &payload); - store.frame_hook.arm(window); -} - -fn emit(cx: &App, name: &str, payload: Value) { - if let Some(store) = cx.try_global::() { - store - .0 - .read(cx) - .host - .emit_device_event_json(name, &payload.to_string()); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/events.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/events.rs deleted file mode 100644 index b47e4776b3..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/events.rs +++ /dev/null @@ -1,1309 +0,0 @@ -//! Pointer, touch and hover events. -//! -//! `Pressable` consumes touch events (`ResponderEventPlugin`); pointer events -//! are sent alongside. Hover enter/leave and `pointerEvents` are implemented -//! here: RN's `PointerEventsProcessor` only runs for typed `PointerEvent` -//! payloads and never reads `pointerEvents`. - -use crate::node_view::RNNodeView; -use crate::store::{store_from, StoreGlobal}; -use gpui::{point, px, App, Pixels, Point, WeakEntity, Window}; -use serde_json::{json, Map, Value}; - -const POINTER_ID: i32 = 1; - -pub const POINTER_EVENTS_AUTO: u8 = 0; -pub const POINTER_EVENTS_NONE: u8 = 1; -pub const POINTER_EVENTS_BOX_NONE: u8 = 2; -pub const POINTER_EVENTS_BOX_ONLY: u8 = 3; - -thread_local! { - /// Whether the press (or release) being dispatched belongs to the window: - /// it landed in a title bar's drag area or on a caption button. On Windows - /// the OS only moves the window, maximizes it on a double click or presses - /// the button when no node consumes the press — and a press bubbles from - /// the node under the pointer to every ancestor, each of which would - /// otherwise start a touch of its own and consume it. - static WINDOW_OWNS_PRESS: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -/// Clears the mark before a press or release reaches any node: the surface's -/// root calls it in the capture phase, which runs ahead of every node's own -/// listener. -pub(crate) fn begin_press_dispatch() { - WINDOW_OWNS_PRESS.with(|owned| owned.set(false)); - PRESS_CLAIMED.with(|claimed| claimed.set(false)); -} - -thread_local! { - static PRESS_CLAIMED: std::cell::Cell = const { std::cell::Cell::new(false) }; - static NATIVE_PRESS: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -/// Clears the marks before a press reaches any node, including whether the -/// press is over native content, which lasts until the next press so its moves -/// and its release keep reaching the native elements. -pub(crate) fn begin_press() { - begin_press_dispatch(); - NATIVE_PRESS.with(|native| native.set(false)); -} - -/// Marks the press as over native content (a native root's tree), whose GPUI -/// elements handle it too: a text selection that starts with a drag, or a -/// click that clears one. React Native nodes it bubbles to still get their -/// touch, but none stops it from reaching those elements. -pub(crate) fn mark_native_press() { - NATIVE_PRESS.with(|native| native.set(true)); -} - -/// Whether the current press began over native content. -pub(crate) fn native_press() -> bool { - NATIVE_PRESS.with(std::cell::Cell::get) -} - -/// Marks the press as taken by a React Native node, for a node whose press must -/// still reach the GPUI elements around it: the nodes it bubbles to read this -/// instead of the press being stopped. -pub(crate) fn claim_press() { - PRESS_CLAIMED.with(|claimed| claimed.set(true)); -} - -/// Whether a node nearer the pointer already took this press. -pub(crate) fn press_claimed() -> bool { - PRESS_CLAIMED.with(std::cell::Cell::get) -} - -/// Marks the press as the window's. The node under the pointer is the first to -/// see a press in the bubble phase, so its ancestors read this afterwards. -pub(crate) fn hand_press_to_window() { - WINDOW_OWNS_PRESS.with(|owned| owned.set(true)); -} - -/// Whether a node nearer the pointer already handed this press to the window. -pub(crate) fn press_belongs_to_window() -> bool { - WINDOW_OWNS_PRESS.with(std::cell::Cell::get) -} - -thread_local! { - static RETARGETING: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -#[derive(Clone, Copy, Debug)] -pub enum Phase { - Start, - Move, - End, - Cancel, -} - -/// Process-relative, like the typed `TouchEventEmitter` path: RN only uses -/// differences. -pub fn now_ms() -> f64 { - use std::sync::OnceLock; - static START: OnceLock = OnceLock::new(); - START - .get_or_init(std::time::Instant::now) - .elapsed() - .as_secs_f64() - * 1000.0 -} - -/// Precomputed because the node whose handler is running is being updated by -/// GPUI, and reading it from the entity map panics. -#[derive(Clone, Debug)] -pub struct Target { - pub tag: i32, - pub origin: Point, - /// How far the window's pointer positions run ahead of the surface's: the - /// menu bar GPUI draws above it, when the surface's origin does not hold it. - window_offset: f32, - window_offset_x: f32, - /// The window's zoom factor: window pointer positions run ahead of the - /// surface's by this much. - zoom: f32, - scale_x: f32, - scale_y: f32, - /// Inverses of the matrices GPUI draws the target under, outermost first. - inverses: Vec, - /// The target and its ancestors, innermost first: RN's hover path - /// (`PointerHoverTracker::getEventPathTargets`), the surface root excluded. - pub chain: Vec, -} - -pub fn active_touch_target(cx: &App) -> Option { - store_from(cx).and_then(|store| store.read(cx).active_touch_target.clone()) -} - -impl Target { - /// A pointer position of the window in the surface's space, which is where - /// React's page coordinates and the node origins are. - pub(crate) fn page(&self, position: Point) -> Point { - point( - (position.x - px(self.window_offset_x)) / self.zoom, - (position.y - px(self.window_offset)) / self.zoom, - ) - } - - /// A position of the surface's space in the window, the inverse of `page`. - pub(crate) fn window_point(&self, page: Point) -> Point { - point( - page.x * self.zoom + px(self.window_offset_x), - page.y * self.zoom + px(self.window_offset), - ) - } - - pub(crate) fn zoom(&self) -> f32 { - self.zoom - } - - pub(crate) fn local_position(&self, position: Point) -> Point { - let position = self.inverses.iter().fold(position, |position, inverse| { - inverse.transform_logical_point(position) - }); - point( - px(f32::from(position.x - self.origin.x) / self.scale_x.max(0.0001)), - px(f32::from(position.y - self.origin.y) / self.scale_y.max(0.0001)), - ) - } -} - -#[cfg(test)] -mod transform_tests { - use super::Target; - use gpui::{point, px}; - - #[test] - fn pointer_location_is_reported_in_untransformed_target_coordinates() { - let target = Target { - tag: 7, - origin: point(px(30.0), px(40.0)), - window_offset: 0.0, - window_offset_x: 0.0, - zoom: 1.0, - scale_x: 2.0, - scale_y: 0.5, - inverses: Vec::new(), - chain: vec![7], - }; - let local = target.local_position(point(px(70.0), px(60.0))); - assert_eq!(f32::from(local.x), 20.0); - assert_eq!(f32::from(local.y), 40.0); - } - - #[test] - fn pointer_location_undoes_the_matrices_a_target_is_drawn_under() { - use gpui::TransformationMatrix; - let quarter = TransformationMatrix { - rotation_scale: [[0.0, -1.0], [1.0, 0.0]], - translation: [0.0, 0.0], - }; - let about = TransformationMatrix::about(50.0, 50.0, quarter); - let target = Target { - tag: 7, - origin: point(px(20.0), px(35.0)), - window_offset: 0.0, - window_offset_x: 0.0, - zoom: 1.0, - scale_x: 1.0, - scale_y: 1.0, - inverses: vec![about.inverse().unwrap()], - chain: vec![7], - }; - let local = target.local_position(about.transform_logical_point(point(px(30.0), px(50.0)))); - assert!((f32::from(local.x) - 10.0).abs() < 0.001); - assert!((f32::from(local.y) - 15.0).abs() < 0.001); - } -} - -struct Step { - tag: i32, - pointer_events: u8, - entity: Option>, - parent: Option>, -} - -/// Mirrors RN's native `hitTest`: `auto` is a candidate (the deepest wins), -/// `box-none` is never a target but its children are, `box-only` overrides any -/// deeper candidate, `none` kills the whole subtree. -/// The node that owns the context menu for a press on `hit_node`. -/// -/// Right-clicking a `Text` inside a `View` with `onContextMenu` must open that -/// view's menu. GPUI bubbles mouse events from the innermost hitbox outwards, so -/// relying on bubbling means every node between the two needs a listener — and a -/// node that takes pointer input stops the press before it reaches the owner. -/// That is what made a right click on the text stop working. -/// -/// So the innermost node that handles the press walks its ancestors instead. The -/// walk follows the same `pointerEvents` rules as `target`: `none` ends it, and -/// `box-only` is a candidate but its ancestors are not. -/// -/// The result is the nearest ancestor-or-self that asked for a context menu — -/// either a `View` with the prop or an extension component whose `InputSpec` -/// does. `None` means nothing in the chain wants one, and the press is only a -/// pointer event. -pub fn context_menu_owner(cx: &App, hit_node: &RNNodeView) -> Option { - let mut tag = hit_node.tag; - let mut wants = node_wants_context_menu(cx, hit_node); - let mut pointer_events = hit_node.view.pointer_events; - let mut parent = hit_node.parent.clone(); - // `None` for the hit node itself, which the caller already has. - let mut entity: Option> = None; - loop { - if pointer_events == POINTER_EVENTS_NONE { - return None; - } - if wants { - return Some(ContextMenuOwner { tag, entity }); - } - // `box-only` claims the press for itself, so the search ends with it - // whether or not it wants a menu. - if pointer_events == POINTER_EVENTS_BOX_ONLY { - return None; - } - let Some(next) = parent.clone() else { - return None; - }; - let Some(node) = next.upgrade() else { - return None; - }; - let node = node.read(cx); - tag = node.tag; - wants = node_wants_context_menu(cx, node); - pointer_events = node.view.pointer_events; - parent = node.parent.clone(); - entity = Some(next); - } -} - -/// Whether this node wants a context menu: the View prop, or an extension -/// component whose `InputSpec` asks for one. -fn node_wants_context_menu(cx: &App, node: &RNNodeView) -> bool { - if node.view.on_context_menu { - return true; - } - let Some(renderer) = crate::extensions::component_renderer(&node.component) else { - return false; - }; - let component_node = node.renderer_node(&*renderer, cx); - renderer.input(&component_node).context_menu -} - -/// Who owns a context menu for a press. -#[derive(Clone)] -pub struct ContextMenuOwner { - pub tag: i32, - /// The owning node, or `None` when it is the hit node itself. - pub entity: Option>, -} - -pub fn target(cx: &App, hit_node: &RNNodeView) -> Option { - let mut steps = vec![Step { - tag: hit_node.tag, - pointer_events: hit_node.view.pointer_events, - entity: None, - parent: hit_node.parent.clone(), - }]; - loop { - let Some(ancestor) = steps.last().and_then(|step| step.parent.clone()) else { - break; - }; - let Some(node) = ancestor.upgrade() else { - break; - }; - let (tag, pointer_events, parent) = { - let node = node.read(cx); - (node.tag, node.view.pointer_events, node.parent.clone()) - }; - steps.push(Step { - tag, - pointer_events, - entity: Some(ancestor), - parent, - }); - } - let mut chosen: Option = None; - for (index, step) in steps.iter().enumerate() { - match step.pointer_events { - POINTER_EVENTS_NONE => return None, - POINTER_EVENTS_AUTO => { - if chosen.is_none() { - chosen = Some(index); - } - } - POINTER_EVENTS_BOX_NONE => {} - POINTER_EVENTS_BOX_ONLY => chosen = Some(index), - other => { - log::warn!("[events] unknown pointerEvents {other}; treating it as auto"); - if chosen.is_none() { - chosen = Some(index); - } - } - } - } - let index = chosen?; - let (origin, scale_x, scale_y, inverses) = if index == 0 { - let (scale_x, scale_y) = hit_node.cumulative_scale(cx); - ( - hit_node.absolute_origin(cx), - scale_x, - scale_y, - hit_node.transform_inverses(cx), - ) - } else { - let node = steps[index].entity.as_ref()?.upgrade()?; - let node = node.read(cx); - let (scale_x, scale_y) = node.cumulative_scale(cx); - ( - node.absolute_origin(cx), - scale_x, - scale_y, - node.transform_inverses(cx), - ) - }; - let chain = steps[index..].iter().map(|step| step.tag).collect(); - let placed = hit_node.surface_is_placed(); - Some(Target { - tag: steps[index].tag, - origin, - window_offset: if placed { - 0.0 - } else { - crate::desktop::gpui_menu::menu_bar_inset_for_window_id(hit_node.surface_id as u32) - + crate::desktop::window_frame::insets_of(hit_node.surface_id).top - }, - window_offset_x: if placed { - 0.0 - } else { - crate::desktop::window_frame::insets_of(hit_node.surface_id).left - }, - zoom: crate::desktop::zoom::get(hit_node.surface_id), - scale_x, - scale_y, - inverses, - chain, - }) -} - -/// One touch object: exactly the keys `setTouchPayloadOnObject` writes -/// (`ReactCommon/react/renderer/components/view/BaseTouch.cpp`). -fn touch_json(tag: i32, page: Point, location: Point, timestamp: f64) -> Value { - let (x, y) = (f32::from(page.x), f32::from(page.y)); - json!({ - "identifier": POINTER_ID, - "target": tag, - "pageX": x, - "pageY": y, - "locationX": f32::from(location.x), - "locationY": f32::from(location.y), - "screenX": x, - "screenY": y, - "timestamp": timestamp, - "force": 0.0, - }) -} - -/// `touches` must be empty for `topTouchEnd`: `ResponderTouchHistoryStore` -/// reads its length as the number of active touches. -fn touch_payload( - tag: i32, - page: Point, - location: Point, - active: bool, - modifiers: ModifierState, -) -> Value { - let touch = touch_json(tag, page, location, now_ms()); - let mut payload = touch.as_object().cloned().unwrap_or_else(Map::new); - // A desktop extension: the keys held, as on the pointer events, so a press - // handler can tell a shift or meta click from a plain one. - payload.insert("shiftKey".into(), modifiers.shift.into()); - payload.insert("ctrlKey".into(), modifiers.ctrl.into()); - payload.insert("altKey".into(), modifiers.alt.into()); - payload.insert("metaKey".into(), modifiers.meta.into()); - let list = |touch: &Value| Value::Array(if active { vec![touch.clone()] } else { vec![] }); - payload.insert("touches".into(), list(&touch)); - payload.insert("changedTouches".into(), Value::Array(vec![touch.clone()])); - payload.insert("targetTouches".into(), list(&touch)); - Value::Object(payload) -} - -/// Delivers only the DOM pointer events for a button, with no touch or responder -/// side effects. -/// -/// This is the path a middle or right press takes. `send` also dispatches -/// `topTouchStart` and feeds RN's responder system, which would make a -/// `Pressable` react to a right click; a non-primary button must not do that. -pub fn send_pointer( - window: &mut Window, - cx: &mut App, - target: &Target, - position: Point, - phase: Phase, - button: Option

WKWebView native surface

This page is rendered by WebKit in an AppKit view attached to the GPUI composition surface.

Resize the window and use the GPUI overlay control above this area.

"#; - -pub struct NativeViewCompositionProbe { - surface: WindowCompositionSurface, - view: id, - last_bounds: Cell>>, -} - -impl NativeViewCompositionProbe { - pub fn new(window: &Window, kind: NativeContentKind) -> Result { - let composition = window.enable_window_composition()?; - let surface = composition.create_native_surface()?; - let container = surface - .platform_surface()? - .platform_handle()? - .downcast::() - .map(|handle| *handle as id) - .map_err(|_| anyhow::anyhow!("native composition surface is not an AppKit view"))?; - - // SAFETY: the views are created and configured on the main thread and owned by the returned probe. - unsafe { - let frame = NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)); - let view: id = match kind { - NativeContentKind::AppKitView => { - let view: id = msg_send![class!(NSView), alloc]; - msg_send![view, initWithFrame: frame] - } - NativeContentKind::WebView => { - let configuration: id = msg_send![class!(WKWebViewConfiguration), new]; - let allocated: id = msg_send![class!(WKWebView), alloc]; - let view: id = - msg_send![allocated, initWithFrame: frame configuration: configuration]; - let _: () = msg_send![configuration, release]; - view - } - }; - anyhow::ensure!(!view.is_null(), "failed to create native composition view"); - - let _: () = msg_send![view, setWantsLayer: YES]; - let _: () = msg_send![ - view, - setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable - ]; - let layer: id = msg_send![view, layer]; - let _: () = msg_send![layer, setCornerRadius: 12.0]; - let _: () = msg_send![layer, setMasksToBounds: YES]; - if matches!(kind, NativeContentKind::AppKitView) { - let color: id = msg_send![ - class!(NSColor), - colorWithSRGBRed: 0.08 - green: 0.48 - blue: 0.68 - alpha: 1.0 - ]; - let color: id = msg_send![color, CGColor]; - let _: () = msg_send![layer, setBackgroundColor: color]; - } else { - #[allow( - clippy::disallowed_methods, - reason = "NSString is released after WebKit copies the HTML" - )] - let html = NSString::alloc(nil).init_str(WEBVIEW_HTML); - let _: id = msg_send![view, loadHTMLString: html baseURL: nil]; - let _: () = msg_send![html, release]; - } - let _: () = msg_send![container, addSubview: view]; - - log::info!( - "[native-view-probe] attached {:?} to composition surface", - match kind { - NativeContentKind::AppKitView => "AppKit NSView", - NativeContentKind::WebView => "WKWebView", - } - ); - Ok(Self { - surface, - view, - last_bounds: Cell::new(None), - }) - } - } - - fn set_bounds(&self, bounds: Bounds, scale_factor: f32) -> Result<()> { - let device_bounds = bounds.to_device_pixels(scale_factor); - if self.last_bounds.get() != Some(device_bounds) { - log::info!("[native-view-probe] device bounds={device_bounds:?}"); - self.last_bounds.set(Some(device_bounds)); - } - self.surface - .platform_surface()? - .set_bounds(device_bounds) - .context("setting AppKit test surface bounds") - } -} - -impl Drop for NativeViewCompositionProbe { - fn drop(&mut self) { - // SAFETY: `self.view` is the owned view created in `new`; it is detached and released once, on drop. - unsafe { - NSView::removeFromSuperview(self.view); - let _: () = msg_send![self.view, release]; - } - } -} - -pub struct NativeViewCompositionProbeView { - fixture: Option>, - overlay_visible: bool, - kind: NativeContentKind, -} - -impl NativeViewCompositionProbeView { - pub fn new(kind: NativeContentKind) -> Self { - Self { - fixture: None, - overlay_visible: false, - kind, - } - } -} - -impl Render for NativeViewCompositionProbeView { - fn render(&mut self, window: &mut Window, _cx: &mut Context) -> impl IntoElement { - if self.fixture.is_none() { - match NativeViewCompositionProbe::new(window, self.kind) { - Ok(fixture) => self.fixture = Some(Rc::new(fixture)), - Err(error) => log::error!("[native-view-probe] initialization failed: {error:#}"), - } - } - - let mut root = div().absolute().inset_0().size_full(); - if let Some(fixture) = self.fixture.clone() { - root = root.child( - div() - .absolute() - .left(px(32.)) - .right(px(32.)) - .top(px(260.)) - .bottom(px(24.)) - .child(NativeViewSurfaceElement { fixture }), - ); - } - - let label = if self.overlay_visible { - "Hide composition overlay" - } else { - "Show composition overlay" - }; - root = root.child( - div() - .absolute() - .left(px(32.)) - .top(px(190.)) - .px_4() - .py_2() - .rounded_md() - .bg(rgb(0x26384a)) - .text_color(rgb(0xffffff)) - .cursor_pointer() - .on_mouse_down( - MouseButton::Left, - _cx.listener(|this, _, _, cx| { - this.overlay_visible = !this.overlay_visible; - log::info!( - "[native-view-probe] overlay visible={}", - this.overlay_visible - ); - cx.notify(); - }), - ) - .child(label), - ); - - if self.overlay_visible { - root = root.child( - deferred( - div() - .absolute() - .left(px(92.)) - .top(px(316.)) - .w(px(420.)) - .h(px(116.)) - .flex() - .flex_col() - .justify_center() - .gap_2() - .px_5() - .rounded_lg() - .border_2() - .border_color(rgb(0xffffff)) - .bg(rgb(0xffffff).opacity(0.82)) - .text_color(rgb(0x18212f)) - .child(match self.kind { - NativeContentKind::AppKitView => { - "GPUI overlay above the blue AppKit NSView" - } - NativeContentKind::WebView => "GPUI overlay above the WKWebView", - }) - .child("Native content should remain visible through this panel."), - ) - .priority(100), - ); - } - root - } -} - -struct NativeViewSurfaceElement { - fixture: Rc, -} - -impl IntoElement for NativeViewSurfaceElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - -impl Element for NativeViewSurfaceElement { - type RequestLayoutState = (); - type PrepaintState = (); - - fn id(&self) -> Option { - None - } - - fn source_location(&self) -> Option<&'static core::panic::Location<'static>> { - None - } - - fn request_layout( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&gpui::InspectorElementId>, - window: &mut Window, - cx: &mut App, - ) -> (LayoutId, Self::RequestLayoutState) { - let mut style = Style::default(); - style.size.width = relative(1.).into(); - style.size.height = relative(1.).into(); - (window.request_layout(style, [], cx), ()) - } - - fn prepaint( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&gpui::InspectorElementId>, - bounds: Bounds, - _request_layout: &mut Self::RequestLayoutState, - _window: &mut Window, - _cx: &mut App, - ) -> Self::PrepaintState { - if let Err(error) = self.fixture.set_bounds(bounds, _window.scale_factor()) { - log::error!("[native-view-probe] updating surface bounds failed: {error:#}"); - } - } - - fn paint( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&gpui::InspectorElementId>, - _bounds: Bounds, - _request_layout: &mut Self::RequestLayoutState, - _prepaint: &mut Self::PrepaintState, - _window: &mut Window, - _cx: &mut App, - ) { - } -} - -pub fn create_probe_entity(cx: &mut App) -> Entity { - cx.new(|_| NativeViewCompositionProbeView::new(NativeContentKind::AppKitView)) -} - -pub fn create_webview_probe_entity(cx: &mut App) -> Entity { - cx.new(|_| NativeViewCompositionProbeView::new(NativeContentKind::WebView)) -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/node_view.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/node_view.rs deleted file mode 100644 index af091c8307..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/node_view.rs +++ /dev/null @@ -1,7017 +0,0 @@ -//! One GPUI view per Fabric node. No flex property is ever set: every frame -//! comes from RN's Yoga pass. - -use crate::pointer_area::{Node, PointerArea, PointerHandlers}; -use crate::style; -use crate::view_props::ViewProps; -use gpui::{ - div, point, prelude::*, px, size, AnyElement, App, Context, Display, Entity, Fill, FocusHandle, - IntoElement, KeyDownEvent, KeyUpEvent, MouseButton, MouseDownEvent, MouseMoveEvent, - MouseUpEvent, Pixels, Point, Position, Refineable, Role, Subscription, Task, WeakEntity, - Window, -}; -use rn_gpui_sys::ffi::{MountOp, ParagraphFlat, RectF}; -use std::cell::Cell; -use std::collections::HashMap; -use std::rc::Rc; -#[cfg(all(target_os = "macos", feature = "visual-capture"))] -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::{AtomicBool, Ordering}; -#[cfg(feature = "test-driver")] -use std::sync::Mutex; -use std::sync::OnceLock; -use std::time::{Duration, Instant}; - -static ACCESSIBILITY_ACTIVE: AtomicBool = AtomicBool::new(false); -static ACCESSIBILITY_ACTIVE_INITIALIZED: AtomicBool = AtomicBool::new(false); - -#[no_mangle] -pub extern "C" fn rn_gpui_accessibility_active() -> bool { - ACCESSIBILITY_ACTIVE.load(Ordering::Relaxed) -} - -fn debug_render_counts_enabled() -> bool { - static ENABLED: OnceLock = OnceLock::new(); - *ENABLED.get_or_init(|| std::env::var_os("RN_GPUI_DEBUG_RENDER_COUNTS").is_some()) -} - -fn elapsed_since_first_render_ms() -> u128 { - static START: std::sync::OnceLock = std::sync::OnceLock::new(); - START - .get_or_init(std::time::Instant::now) - .elapsed() - .as_millis() -} - -pub struct RNNodeView { - pub tag: i32, - render_count: u64, - /// Whether the pointer was over this node at the last hover sample. - /// - /// Kept here rather than in the mouse listener because GPUI clears - /// `mouse_listeners` on every frame: a listener-local flag would reset at each - /// paint, so a component would be told it was entered repeatedly and never - /// told the pointer left. - hovered: bool, - /// The pointer listeners built for this node and what they were built - /// from. See [`RNNodeView::pointer_handlers`]. - pointer_handlers: Option<(PointerHandlersKey, Rc)>, - pub surface_id: i32, - pub component: gpui::SharedString, - /// Whether this node's own content is composited by the OS rather than - /// painted by GPUI. Decided once, when the node is created, from its - /// registry entry. - pub(crate) renders_native_surface: bool, - /// How many nodes in this subtree render a native surface, this node - /// included. - pub(crate) native_surface_descendants: u32, - /// Whether this node's contribution has been added to its ancestors. - pub(crate) native_surface_counted: bool, - /// How many nodes in this subtree are painted as a group of their own - /// (see `forms_effect_group`), this node included. A scroll container - /// holding one does not cache its content as a layer. - pub(crate) effect_group_descendants: u32, - /// Whether this node counts itself in `effect_group_descendants`. - forms_effect_group: bool, - pub(crate) extension_props: std::sync::Arc, - /// The hash of the JSON `extension_props` was parsed from. - extension_props_hash: u64, - /// A native slot's content is painted where its placeholder is, not where - /// layout put it; this is the difference, kept up to date by the placeholder. - pub(crate) slot_shift: Option>>>, - /// The composition surface hosting the OS view of a `nativeSurface` - /// component, created when the node is first painted. - native_surface: Option>, - /// The host component rendering this node, when its op carried a registry - /// index. Created on the main thread when the node is mounted, and the only - /// thing about the component this node ever looks up: from here on it is a - /// vtable call, never a name lookup. - host_component: Option>, - /// The registry index the host component was created from, for the - /// declaration (container, native surface) the node needs while rendering. - host_index: i32, - /// Whether the host component is a container: core paints its React children - /// between its chrome and its overlay. - host_container: bool, - /// Whether the first child masks the others (`maskChildren`). - mask_children: bool, - /// The intrinsic size this node's host component last reported. Exposed to - /// the test driver and to diagnostics; Yoga has the authoritative copy, in - /// the shadow node's state. - intrinsic_size: Option<(f32, f32)>, - /// The store's report queue, shared by every node. A method's context writes - /// here; the store is the one place that applies what is written. - host_reports: crate::store::HostReportQueue, - /// Where this node's surface is in its window. Zero for a window's own root - /// surface; a `ReactSurface` placed by GPUI writes its box here. - surface_origin: crate::surface::SurfaceOrigin, - pub frame: RectF, - pub(crate) parent_tag_cache: std::rc::Rc>>, - pub view: ViewProps, - animated_transform: Option>, - animated_background_color: Option, - gradient_cache: Option>, - animated_text_color: Option, - animated_opacity: bool, - focused: Cell, - focus_visible: Cell, - /// The text color a state style gives this node's text: its own, or the - /// nearest ancestor's. - state_text_color: Option, - own_state_color: Option, - state_styles: Option>, - pub paragraph: Option, - /// A `TextInput`'s own state; other nodes have none. - text_input: Option>, - /// The paragraph shaped off the main thread, valid while the paragraph is - /// the one it was shaped from. - pub(crate) prepared_paragraph: Option, - pub(crate) text_selection: std::ops::Range, - pub(crate) text_selection_anchor: Option, - pub(crate) caret_blink_task: Task<()>, - pub(crate) transition: Option<(crate::extensions::Transition, Instant)>, - pub(crate) transition_forward: bool, - transition_progress_sent: Option<(Instant, f32)>, - transition_end_refreshed: Option, - pub(crate) scroll: Option>, - /// The state of a scroll view, which other nodes go without. - scroll_parts: Option>, - /// The mode `onModeChange` last reported, for a `VirtualView`. - pub(crate) virtual_view_mode: Cell>, - pub focusable: bool, - pub(crate) pending_text_input_focus: Option, - pub children: Vec<(i32, Entity)>, - pub parent: Option>, - pub(crate) renderer_frame: Option, - pub(crate) renderer_decoration: Option, - pub(crate) inherited: Inherited, - pub(crate) focus_handle: Option, - pub(crate) focus_subscriptions: Vec, -} - -static A11Y_TREE_DUMP_SCHEDULED: AtomicBool = AtomicBool::new(false); -static A11Y_TREE_DUMP_COMPLETE: AtomicBool = AtomicBool::new(false); -#[cfg(all(target_os = "macos", feature = "visual-capture"))] -static A11Y_TREE_DUMP_ATTEMPTS: AtomicUsize = AtomicUsize::new(0); - -/// The DOM view of the modifiers held during an event. -pub(crate) fn modifier_state(modifiers: gpui::Modifiers) -> crate::events::ModifierState { - crate::events::ModifierState::from_gpui(&modifiers) -} - -/// Which `ComponentRenderer` hook to run for a button press or release. -#[derive(Clone, Copy)] -enum ComponentHook { - Down, - Up, -} - -/// Runs a component renderer's mouse hook for one event. -/// -/// The node and the renderer are resolved here rather than captured, because a -/// component can be re-rendered between the event and the hook: a captured -/// `ComponentNode` would describe the tree as it was when the listener was built. -#[allow(clippy::too_many_arguments)] -fn run_component_hook( - node: &gpui::WeakEntity, - captured: &crate::extensions::ComponentNode, - window: &mut gpui::Window, - cx: &mut gpui::App, - position: gpui::Point, - button: crate::events::Button, - click_count: usize, - modifiers: gpui::Modifiers, - hook: ComponentHook, -) { - let Some(node) = node.upgrade() else { - return; - }; - let component = node.read(cx).component.clone(); - let Some(renderer) = crate::extensions::component_renderer(&component) else { - return; - }; - let (origin, window_offset) = { - let node = node.read(cx); - let offset = if node.surface_is_placed() { - 0.0 - } else { - crate::desktop::gpui_menu::menu_bar_inset_for_window_id(node.surface_id as u32) - + crate::desktop::window_frame::insets_of(node.surface_id).top - }; - (node.absolute_origin(cx), offset) - }; - let offset_x = if node.read(cx).surface_is_placed() { - 0.0 - } else { - crate::desktop::window_frame::insets_of(node.read(cx).surface_id).left - }; - let local = gpui::point( - position.x - origin.x - gpui::px(offset_x), - position.y - origin.y - gpui::px(window_offset), - ); - let event = crate::extensions::input::MouseEvent { - position, - local, - button, - buttons: button.mask(), - click_count, - modifiers: modifier_state(modifiers), - }; - let mut context = crate::extensions::input::InputContext { - node: captured, - window, - cx, - captured: false, - }; - let propagation = match hook { - ComponentHook::Down => renderer.on_mouse_down(captured, &event, &mut context), - ComponentHook::Up => renderer.on_mouse_up(captured, &event, &mut context), - }; - if propagation == crate::extensions::input::Propagation::Stop { - context.cx.stop_propagation(); - } -} - -/// Handles a right press: reports the pointer event, then opens the nearest -/// context menu. -/// -/// One press, one node. The pointer event goes to the innermost target so RN -/// bubbles it through the JS tree; the menu goes to the nearest ancestor-or-self -/// that owns one, found by an explicit walk rather than by GPUI's bubbling. That -/// walk is what lets a `Text` inside an `onContextMenu` view still open the -/// parent's menu. -fn dispatch_right_press( - node: &gpui::WeakEntity, - event: &MouseDownEvent, - window: &mut gpui::Window, - cx: &mut gpui::App, -) { - let Some(entity) = node.upgrade() else { - return; - }; - if right_press_seen(event) { - return; - } - let (owner, target) = { - let this = entity.read(cx); - ( - crate::events::context_menu_owner(cx, this), - crate::events::target(cx, this), - ) - }; - if let Some(target) = target.as_ref() { - crate::events::send_pointer( - window, - cx, - target, - event.position, - crate::events::Phase::Start, - Some(crate::events::Button::Right), - crate::events::Button::Right.mask(), - modifier_state(event.modifiers), - ); - } - let modifiers = modifier_state(event.modifiers); - let claimed = owner.is_some(); - if crate::events::mouse_context_menu_trigger( - crate::events::Button::Right, - modifiers, - std::env::consts::OS, - ) - .is_some() - { - let shown = - crate::builtins::textinput::input::show_text_menu(&entity, event.position, window, cx) - || crate::builtins::text_select::show_menu(&entity, event.position, window, cx); - if shown { - cx.stop_propagation(); - return; - } - if let Some(owner) = owner { - // A component that asked for context menus owns the press and renders - // its own; a `View` with the prop dispatches to JS. The hook has to be - // preferred, or a `ContextMenuView` would both open natively and tell - // JS about a press it already handled. - if !run_component_context_menu(&owner, event.position, false, modifiers, window, cx) { - dispatch_context_menu( - owner.tag, - event.position, - crate::events::Button::Right, - modifiers, - "mouse", - window, - cx, - ); - } - } - } - if !claimed && inside_extension_component(&entity, cx) { - // Nothing in the React tree claims the press, so the extension - // component around this node may handle it natively. - return; - } - cx.stop_propagation(); -} - -thread_local! { - static LAST_RIGHT_PRESS: std::cell::Cell, std::time::Instant)>> = - const { std::cell::Cell::new(None) }; -} - -/// Whether an enclosing node already dispatched this press. One press reaches -/// every node it bubbles through within a few microseconds. -fn right_press_seen(event: &MouseDownEvent) -> bool { - let now = std::time::Instant::now(); - LAST_RIGHT_PRESS.with(|last| { - let seen = last.get().is_some_and(|(position, at)| { - position == event.position - && now.duration_since(at) < std::time::Duration::from_millis(5) - }); - if !seen { - last.set(Some((event.position, now))); - } - seen - }) -} - -fn inside_extension_component(entity: &gpui::Entity, cx: &gpui::App) -> bool { - let mut parent = entity.read(cx).parent.clone(); - while let Some(node) = parent.and_then(|weak| weak.upgrade()) { - let node = node.read(cx); - if node.host_index >= 0 || crate::extensions::component_renderer(&node.component).is_some() - { - return true; - } - parent = node.parent.clone(); - } - false -} - -/// Runs a component's `on_context_menu` hook, if the owner is a component. -/// -/// Returns whether the hook handled the press. `false` means the owner is a plain -/// `View` with `onContextMenu`, which the caller dispatches to JS instead. -fn run_component_context_menu( - owner: &crate::events::ContextMenuOwner, - position: gpui::Point, - is_keyboard: bool, - modifiers: crate::events::ModifierState, - window: &mut gpui::Window, - cx: &mut gpui::App, -) -> bool { - let Some(entity) = owner.entity.clone() else { - return false; - }; - let Some(node) = entity.upgrade() else { - return false; - }; - let component = node.read(cx).component.clone(); - let Some(renderer) = crate::extensions::component_renderer(&component) else { - return false; - }; - let component_node = node.read(cx).renderer_node(&*renderer, cx); - if !renderer.input(&component_node).context_menu { - return false; - } - let local = gpui::point( - position.x - gpui::px(component_node.frame.x), - position.y - gpui::px(component_node.frame.y), - ); - let trigger = crate::extensions::input::ContextMenuTrigger { - source: if is_keyboard { - crate::events::ContextMenuTriggerSource::Keyboard - } else { - crate::events::ContextMenuTriggerSource::Mouse - }, - position, - local, - button: crate::events::Button::Right, - modifiers, - }; - let mut context = crate::extensions::input::InputContext { - node: &component_node, - window, - cx, - captured: false, - }; - let propagation = renderer.on_context_menu(&component_node, &trigger, &mut context); - if propagation == crate::extensions::input::Propagation::Stop { - context.cx.stop_propagation(); - } - true -} - -/// Sends the DOM pointer events for one non-primary button press. -/// -/// Shared by the middle and right listeners so the two cannot diverge; the -/// button's mask is the only thing that differs. -/// Opens the context menu a Ctrl + left press asks for, as a right press would, -/// returning whether it did (and stopped the press there). -fn ctrl_click_context_menu( - node: &WeakEntity, - event: &MouseDownEvent, - os_owns_press: bool, - window: &mut Window, - cx: &mut App, -) -> bool { - if os_owns_press || crate::events::press_belongs_to_window() { - return false; - } - let modifiers = modifier_state(event.modifiers); - if crate::events::mouse_context_menu_trigger( - crate::events::Button::Left, - modifiers, - std::env::consts::OS, - ) - .is_none() - { - return false; - } - let Some(entity) = node.upgrade() else { - return false; - }; - let owner = { - let this = entity.read(cx); - crate::events::context_menu_owner(cx, this) - }; - let Some(owner) = owner else { - return false; - }; - if !run_component_context_menu(&owner, event.position, false, modifiers, window, cx) { - dispatch_context_menu( - owner.tag, - event.position, - crate::events::Button::Left, - modifiers, - "mouse", - window, - cx, - ); - } - cx.stop_propagation(); - true -} - -fn dispatch_pointer_button( - node: &gpui::WeakEntity, - event: &MouseDownEvent, - button: crate::events::Button, - window: &mut gpui::Window, - cx: &mut gpui::App, -) { - let Some(node) = node.upgrade() else { - return; - }; - let target = { - let this = node.read(cx); - crate::events::target(cx, this) - }; - let Some(target) = target else { - return; - }; - crate::events::send_pointer( - window, - cx, - &target, - event.position, - crate::events::Phase::Start, - Some(button), - button.mask(), - modifier_state(event.modifiers), - ); - cx.stop_propagation(); -} - -fn dispatch_pointer_release( - node: &gpui::WeakEntity, - event: &MouseUpEvent, - button: crate::events::Button, - window: &mut gpui::Window, - cx: &mut gpui::App, -) { - let Some(node) = node.upgrade() else { - return; - }; - let Some(store) = crate::store::store_from(cx) else { - return; - }; - let pressed = store.read(cx).button_target.borrow().clone(); - let held = store.read(cx).buttons_held.get() & button.mask() != 0; - if !held { - return; - } - let target = pressed.or_else(|| { - let this = node.read(cx); - crate::events::target(cx, this) - }); - let Some(target) = target else { - return; - }; - crate::events::send_pointer( - window, - cx, - &target, - event.position, - crate::events::Phase::End, - Some(button), - button.mask(), - modifier_state(event.modifiers), - ); - cx.stop_propagation(); -} - -/// Dispatches `topContextMenu` for a press, once `events` says it is a trigger. -/// -/// `is_left` distinguishes the Ctrl + click case from the right click so the same -/// listener body serves both; the trigger rule itself is in -/// `events::mouse_context_menu_trigger`, so this and the extension hooks cannot -/// disagree. -fn dispatch_context_menu( - tag: i32, - position: gpui::Point, - button: crate::events::Button, - modifiers: crate::events::ModifierState, - trigger: &str, - window: &mut gpui::Window, - cx: &mut gpui::App, -) { - let x = f32::from(position.x); - let y = f32::from(position.y); - // The window is resolved from the window the press arrived in, not from the - // pressed node's surface id: the owner may be several levels up and its - // surface is the same one either way. - let window_id = crate::desktop::windows::window_key_for_handle(cx, window.window_handle()) - .unwrap_or(crate::desktop::windows::MAIN_WINDOW_KEY); - if let Some(store) = cx.try_global::() { - let store = store.0.read(cx); - store.host.dispatch_event( - tag, - "topContextMenu", - &serde_json::json!({ - "x": x, - "y": y, - "pageX": x, - "pageY": y, - "windowId": window_id, - "button": button.number(), - "ctrlKey": modifiers.ctrl, - "shiftKey": modifiers.shift, - "altKey": modifiers.alt, - "metaKey": modifiers.meta, - "trigger": trigger, - }), - ); - store.frame_hook.arm(window); - } -} - -/// Whether a newly created node's own content is composited by the OS. -fn renders_native_surface_for_op(op: &MountOp) -> bool { - if op.host_index >= 0 && crate::host_component::renders_native_surface(op.host_index as u32) { - return true; - } - crate::extensions::any_component_renderers() - && crate::extensions::component_renders_native_surface(&op.component) -} - -static NO_TEXT_INPUT: crate::builtins::textinput::input::TextInputState = - crate::builtins::textinput::input::TextInputState::EMPTY; - -/// The op's paragraph without the handle of its prepared layout, which the node -/// takes. -fn paragraph_of(op: &MountOp) -> ParagraphFlat { - let mut paragraph = op.paragraph.clone(); - paragraph.prepared = 0; - paragraph -} - -impl RNNodeView { - /// The node's text input state: its own for a `TextInput`, an empty one - /// for every other node. - pub(crate) fn input(&self) -> &crate::builtins::textinput::input::TextInputState { - self.text_input.as_deref().unwrap_or(&NO_TEXT_INPUT) - } - - /// The node's text input state, made for a node that has none. - pub(crate) fn input_mut(&mut self) -> &mut crate::builtins::textinput::input::TextInputState { - self.text_input.get_or_insert_with(|| { - Box::new(crate::builtins::textinput::input::TextInputState::EMPTY) - }) - } - - pub(crate) fn accessibility_focus_handle(&self) -> Option { - self.focus_handle.clone() - } - - pub(crate) fn set_accessibility_tab_stop_allowed(&mut self, allowed: bool) { - if let Some(handle) = self.focus_handle.take() { - self.focus_handle = Some(handle.tab_stop( - allowed - && (self.focusable || self.view.accessibility_has_escape_listener) - && !self.view.accessibility_disabled - && self.view.accessibility_responds_to_interaction - && !self.view.accessibility_hidden - && self.view.accessibility_important != 3 - && !self.view.display_none, - )); - } - } - pub(crate) fn focus_for_accessibility(&mut self, window: &mut Window, cx: &mut Context) { - if let Some(handle) = self.focus_handle.as_ref() { - handle.focus(window, cx); - log::info!( - "[accessibility] focused tag {} from native request", - self.tag - ); - } else { - log::warn!( - "[accessibility] cannot focus tag {} because it has no focus handle", - self.tag - ); - } - } - - /// `ref.focus()` and `ref.blur()` on a text input or a focusable view. - pub fn apply_text_input_focus_command( - &mut self, - focus: bool, - window: &mut Window, - cx: &mut Context, - ) { - if self.component != "TextInput" && !self.takes_focus() { - return; - } - let Some(handle) = self.focus_handle.as_ref().cloned() else { - // Fabric can deliver autoFocus immediately after mount, before - // GPUI's first render has created the entity's FocusHandle. - self.pending_text_input_focus = Some(focus); - cx.notify(); - return; - }; - if focus { - handle.focus(window, cx); - } else if handle.is_focused(window) { - window.blur(cx); - } - } - - pub fn set_animated_opacity(&mut self, opacity: f32) { - self.animated_opacity = true; - self.view.opacity = opacity.clamp(0.0, 1.0); - } - - /// What this view's state styles amount to right now, the later layer - /// winning a property: focus, focus visible, group hover, hover, group - /// active, active. The pointer states come from the hit path (see - /// `interaction`), focus from what the node last reported, so a state - /// change repaints without JS and without React rendering again. - pub(crate) fn resolved_state(&self) -> Option { - let mut resolved: Option = None; - for (_, layer, applies) in self.state_layers() { - if let (Some(layer), true) = (layer, applies) { - resolved.get_or_insert_with(Default::default).merge(layer); - } - } - resolved - } - - /// The names of the state styles that hold right now, in the order they - /// are layered. - #[cfg(feature = "test-driver")] - pub(crate) fn active_state_names(&self) -> Vec<&'static str> { - self.state_layers() - .into_iter() - .filter(|(_, layer, applies)| layer.is_some() && *applies) - .map(|(name, _, _)| name) - .collect() - } - - fn state_layers(&self) -> [(&'static str, Option<&style::StateStyle>, bool); 7] { - let none = [("", None, false); 7]; - let Some(styles) = self.state_styles.as_ref() else { - return none; - }; - // `none` and `box-none` views are not pointer targets themselves. - let targeted = !matches!(self.view.pointer_events, 1 | 2); - let tag = self.tag; - let focused = self.focused.get(); - [ - ("focus", styles.focus.as_ref(), focused), - ( - "focusVisible", - styles.focus_visible.as_ref(), - focused && self.focus_visible.get(), - ), - ( - "groupHover", - styles.group_hover.as_ref().map(|grouped| &grouped.style), - crate::interaction::group_hovered(tag), - ), - ( - "hover", - styles.hover.as_ref(), - targeted && crate::interaction::node_hovered(tag), - ), - ( - "dragOver", - styles.drag_over.as_ref(), - crate::interaction::node_dragged_over(tag), - ), - ( - "groupActive", - styles.group_active.as_ref().map(|grouped| &grouped.style), - crate::interaction::group_pressed(tag), - ), - ( - "active", - styles.active.as_ref(), - targeted && crate::interaction::node_pressed(tag), - ), - ] - } - - /// The matrix a state style asks for, unless an animation owns it. - fn effective_transform(&self) -> Option<[f32; 16]> { - if let Some(animated) = self.animated_transform.as_deref() { - return Some(*animated); - } - if let Some(state) = self.resolved_state().and_then(|state| state.transform()) { - return Some(state); - } - self.view.has_transform.then_some(self.view.transform) - } - - /// The color a state style gives this view's own text. - pub(crate) fn own_text_color(&self) -> Option { - self.resolved_state()?.text_color() - } - - pub(crate) fn has_text_color_style(&self) -> bool { - self.state_styles - .as_ref() - .is_some_and(|styles| styles.sets_color()) - } - - pub(crate) fn set_state_text_color( - &mut self, - own: Option, - inherited: Option, - ) -> bool { - let before = self.state_text_color; - self.own_state_color = own; - self.state_text_color = own.or(inherited); - before != self.state_text_color - } - - pub(crate) fn state_text_color(&self) -> Option { - self.state_text_color - } - - pub(crate) fn own_state_color(&self) -> Option { - self.own_state_color - } - - /// Reads whether the node has focus, which a state style depends on. Reading - /// it while rendering is what has gpui-fast render the node again when - /// focus moves. - fn sync_focus(&self, window: &Window, cx: &mut Context) { - let Some(handle) = &self.focus_handle else { - return; - }; - let focused = handle.is_focused(window); - if self.focused.replace(focused) == focused { - return; - } - self.focus_visible - .set(focused && window.last_input_was_keyboard()); - if self.has_text_color_style() { - cx.defer(crate::interaction::refresh_text_colors); - } - } - - pub(crate) fn group_name(&self) -> Option { - self.state_styles.as_ref()?.group.clone() - } - - /// Whether this node has a hover style, or a press style when `press`. - pub(crate) fn has_pointer_style(&self, kind: crate::interaction::Kind) -> bool { - use crate::interaction::Kind; - self.state_styles.as_ref().is_some_and(|styles| match kind { - Kind::Press => styles.active.is_some() || styles.group_active.is_some(), - Kind::Hover => styles.hover.is_some() || styles.group_hover.is_some(), - Kind::Drag => styles.drag_over.is_some(), - }) - } - - /// The group this node's hover (or press) style follows. - pub(crate) fn pointer_style_group( - &self, - kind: crate::interaction::Kind, - ) -> Option { - use crate::interaction::Kind; - let styles = self.state_styles.as_ref()?; - let grouped = match kind { - Kind::Press => styles.group_active.as_ref(), - Kind::Hover => styles.group_hover.as_ref(), - Kind::Drag => None, - }; - Some(grouped?.group.clone()) - } - - /// Whether this view takes files dropped from the operating system. - pub(crate) fn accepts_files(&self) -> bool { - self.view.accepts_files - } - - pub(crate) fn tooltip(&self) -> &str { - &self.view.tooltip - } - - pub(crate) fn draggable(&self) -> bool { - self.view.draggable - } - - pub(crate) fn droppable(&self) -> bool { - self.view.droppable - } - - pub fn set_animated_transform(&mut self, transform: Option<[f32; 16]>) { - self.animated_transform = transform.map(Box::new); - } - - pub fn set_animated_background_color(&mut self, color: u32) { - self.animated_background_color = Some(color); - } - - pub fn set_animated_text_color(&mut self, color: u32) { - self.animated_text_color = Some(color); - } - - fn start_caret_blink(&mut self, cx: &mut Context) { - if self.component != "TextInput" { - return; - } - self.input_mut().caret_visible = true; - self.caret_blink_task = cx.spawn(async move |this, cx| loop { - cx.background_executor() - .timer(Duration::from_millis(530)) - .await; - if this - .update(cx, |view, cx| { - view.input_mut().caret_visible = !view.input().caret_visible; - cx.notify(); - }) - .is_err() - { - break; - } - }); - } - - fn stop_caret_blink(&mut self) { - if let Some(input) = self.text_input.as_deref_mut() { - input.caret_visible = false; - } - self.caret_blink_task = Task::ready(()); - } - - pub(crate) fn reset_text_input_caret(&mut self, cx: &mut Context) { - self.start_caret_blink(cx); - } - - #[cfg(any(test, debug_assertions))] - fn hidden_by_modal_sibling_walked(&self, cx: &App) -> bool { - let mut child_tag = self.tag; - let mut parent = self.parent.clone(); - while let Some(parent_entity) = parent.and_then(|parent| parent.upgrade()) { - let parent_view = parent_entity.read(cx); - if parent_view.children.iter().any(|(sibling_tag, sibling)| { - *sibling_tag != child_tag && sibling.read(cx).view.accessibility_modal - }) { - return true; - } - child_tag = parent_view.tag; - parent = parent_view.parent.clone(); - } - false - } - - #[cfg(any(test, debug_assertions))] - fn hidden_by_hidden_ancestor_walked(&self, cx: &App) -> bool { - let mut parent = self.parent.clone(); - while let Some(entity) = parent.and_then(|parent| parent.upgrade()) { - let node = entity.read(cx); - if node.view.accessibility_hidden - || node.view.accessibility_important == 3 - || node.view.display_none - { - return true; - } - parent = node.parent.clone(); - } - false - } - - fn accessibility_escape_target(&self, cx: &App) -> Option { - if self.view.accessibility_has_escape_listener { - return Some(self.tag); - } - let mut parent = self.parent.clone(); - while let Some(entity) = parent.and_then(|parent| parent.upgrade()) { - let node = entity.read(cx); - if node.view.accessibility_has_escape_listener { - return Some(node.tag); - } - parent = node.parent.clone(); - } - None - } - - #[cfg(any(test, debug_assertions))] - fn hidden_by_accessible_ancestor_walked(&self, cx: &App) -> bool { - if self.focusable || self.view.accessible { - return false; - } - let mut parent = self.parent.clone(); - while let Some(parent_entity) = parent.and_then(|parent| parent.upgrade()) { - let parent_view = parent_entity.read(cx); - if parent_view.view.accessible { - return true; - } - parent = parent_view.parent.clone(); - } - false - } - - #[cfg(any(test, debug_assertions))] - fn hidden_by_hiding_ancestor_walked(&self, cx: &App) -> bool { - let mut parent = self.parent.clone(); - while let Some(parent_entity) = parent.and_then(|parent| parent.upgrade()) { - let parent_view = parent_entity.read(cx); - if parent_view.inherited.hides_subtree_self { - return true; - } - parent = parent_view.parent.clone(); - } - false - } - - fn accessible_group_text(&self, cx: &App) -> String { - let Some(store) = cx.try_global::() else { - return String::new(); - }; - fn collect( - tag: i32, - active_tag: i32, - nodes: &HashMap>, - cx: &App, - output: &mut String, - ) { - if tag == active_tag { - return; - } - let Some(entity) = nodes.get(&tag) else { - return; - }; - let view = entity.read(cx); - if view.component == "Paragraph" { - if view.view.accessibility_hidden || view.view.accessibility_important == 3 { - return; - } - if let Some(paragraph) = &view.paragraph { - if !output.is_empty() { - output.push(' '); - } - for fragment in ¶graph.fragments { - output.push_str(&fragment.text); - } - } - return; - } - if view.view.accessible || view.focusable { - return; - } - let children = view - .children - .iter() - .map(|(tag, _)| *tag) - .collect::>(); - for child_tag in children { - collect(child_tag, active_tag, nodes, cx, output); - } - } - let store = store.0.read(cx); - let mut text = String::new(); - let children = self - .children - .iter() - .map(|(tag, _)| *tag) - .collect::>(); - for tag in children { - collect(tag, self.tag, &store.nodes, cx, &mut text); - } - text - } - - fn accessibility_labelled_by_text(&self, cx: &App) -> String { - if self.view.accessibility_labelled_by.is_empty() { - return String::new(); - } - let Some(store) = cx.try_global::() else { - return String::new(); - }; - let store = store.0.read(cx); - fn collect( - tag: i32, - active_tag: i32, - nodes: &HashMap>, - cx: &App, - output: &mut String, - ) { - if tag == active_tag { - return; - } - let Some(entity) = nodes.get(&tag) else { - return; - }; - let view = entity.read(cx); - if !view.view.accessibility_label.is_empty() { - output.push_str(&view.view.accessibility_label); - return; - } - if view.component == "Paragraph" { - if let Some(paragraph) = &view.paragraph { - for fragment in ¶graph.fragments { - output.push_str(&fragment.text); - } - } - return; - } - let children = view - .children - .iter() - .map(|(tag, _)| *tag) - .collect::>(); - for child_tag in children { - collect(child_tag, active_tag, nodes, cx, output); - } - } - let mut labels = Vec::new(); - for native_id in &self.view.accessibility_labelled_by { - let Some(tag) = store.nodes.iter().find_map(|(tag, entity)| { - if *tag == self.tag { - return None; - } - let view = entity.read(cx); - (view.view.accessibility_native_id == *native_id).then_some(*tag) - }) else { - continue; - }; - let mut label = String::new(); - collect(tag, self.tag, &store.nodes, cx, &mut label); - if !label.is_empty() { - labels.push(label); - } - } - labels.join(" ") - } - - fn accessibility_role(&self) -> Option { - // GPUI rejects `Role::GenericContainer` with a debug assertion, so - // `importantForAccessibility="no"` exposes no role at all. - if self.view.accessibility_important == 2 { - return None; - } - if self.component == "Paragraph" && self.view.accessibility_role.is_empty() { - return Some(Role::Label); - } - if self.component == "Image" && self.view.accessibility_role.is_empty() { - return if self.view.accessible || !self.view.accessibility_label.is_empty() { - Some(Role::Image) - } else { - None - }; - } - if self.component == "TextInput" && self.view.accessibility_role.is_empty() { - return Some(if self.input().secure_text { - Role::PasswordInput - } else if self.input().multiline { - Role::MultilineTextInput - } else { - Role::TextInput - }); - } - if self.view.accessibility_role.is_empty() { - let traits = self.view.accessibility_traits; - let trait_role = if traits & (1 << 0) != 0 { - Some(Role::Button) - } else if traits & (1 << 1) != 0 { - Some(Role::Link) - } else if traits & (1 << 2) != 0 { - Some(Role::Image) - } else if traits & (1 << 5) != 0 { - Some(Role::Keyboard) - } else if traits & (1 << 6) != 0 { - Some(Role::Label) - } else if traits & (1 << 7) != 0 { - Some(Role::Note) - } else if traits & (1 << 9) != 0 { - Some(Role::Search) - } else if traits & (1 << 12) != 0 { - Some(Role::Slider) - } else if traits & (1 << 15) != 0 { - Some(Role::Heading) - } else if traits & (1 << 16) != 0 { - Some(Role::Switch) - } else { - None - }; - if trait_role.is_some() { - return trait_role; - } - } - role_for_accessibility_role(&self.view.accessibility_role, self.view.accessible) - } - - #[cfg(feature = "test-driver")] - pub(crate) fn test_render_count(&self) -> u64 { - self.render_count - } - - /// The node's focus handle, created with its focus and blur subscriptions - /// the first time it is needed. - pub(crate) fn ensure_focus_handle( - &mut self, - window: &mut Window, - cx: &mut Context, - ) -> FocusHandle { - if let Some(handle) = &self.focus_handle { - return handle.clone(); - } - let handle = cx - .focus_handle() - .tab_stop(self.focusable || self.view.accessibility_has_escape_listener) - .tab_index(if self.inherited.in_native_slot { - 0 - } else { - self.tag as isize - }); - if let Some(store) = cx.try_global::() { - let host = store.0.read(cx).host.clone(); - let tag = self.tag; - let is_text_input = self.component == "TextInput"; - let focused_host = host.clone(); - self.focus_subscriptions - .push(cx.on_focus(&handle, window, move |this, window, cx| { - if is_text_input { - this.start_caret_blink(cx); - if this.input().select_on_focus { - this.input_mut().select_all_until = Some( - std::time::Instant::now() + std::time::Duration::from_millis(300), - ); - cx.defer_in(window, |this, window, cx| { - crate::builtins::textinput::input::select_all(this, window, cx); - }); - } - } - focused_host.dispatch_event( - tag, - if is_text_input { "topFocus" } else { "focus" }, - &serde_json::json!({ - "focusVisible": window.last_input_was_keyboard(), - }), - ); - if let Some(store) = cx.try_global::() { - store.0.read(cx).frame_hook.arm(window); - } - })); - self.focus_subscriptions - .push(cx.on_blur(&handle, window, move |this, window, cx| { - if is_text_input { - this.stop_caret_blink(); - cx.notify(); - } - if is_text_input { - host.dispatch_event( - tag, - "topEndEditing", - &serde_json::json!({ - "text": this.input().text, - "eventCount": this.input().event_count, - }), - ); - } - host.dispatch_event( - tag, - if is_text_input { "topBlur" } else { "blur" }, - &serde_json::json!({}), - ); - if let Some(store) = cx.try_global::() { - store.0.read(cx).frame_hook.arm(window); - } - })); - } - self.focus_handle = Some(handle.clone()); - handle - } - - /// Whether this node's handle exists only for accessibility and can wait - /// until something focuses it: a leaf such as a `Text` that takes no - /// focus of its own. It is never on the focus path to another node. - fn defers_focus_handle(&self) -> bool { - !self.takes_focus() && self.children.is_empty() - } - - /// The handle a press on `node` focuses, creating the node's own deferred - /// accessibility handle when no focusable node is around it. - pub(crate) fn press_focus_handle( - node: &Entity, - window: &mut Window, - cx: &mut App, - ) -> Option { - let (focusable, defers) = { - let this = node.read(cx); - ( - this.nearest_focus_handle_where(cx, true), - this.focus_handle.is_none() - && this.defers_focus_handle() - && this.has_accessibility_focus_target(), - ) - }; - if focusable.is_some() { - return focusable; - } - if defers { - return Some(node.update(cx, |this, cx| { - let handle = this.ensure_focus_handle(window, cx); - cx.notify(); - handle - })); - } - node.read(cx).nearest_focus_handle(cx) - } - - fn has_accessibility_focus_target(&self) -> bool { - self.view.accessible || self.accessibility_role().is_some() - } - - fn takes_focus(&self) -> bool { - self.focusable || self.view.accessibility_has_escape_listener - } - - /// The handle a press focuses: the nearest focusable node's, or failing - /// that the nearest node's that only has one for accessibility. - pub(crate) fn nearest_focus_handle(&self, cx: &App) -> Option { - self.nearest_focus_handle_where(cx, true) - .or_else(|| self.nearest_focus_handle_where(cx, false)) - } - - fn nearest_focus_handle_where(&self, cx: &App, focusable_only: bool) -> Option { - let usable = |node: &Self| { - node.focus_handle - .as_ref() - .filter(|_| !focusable_only || node.takes_focus()) - .cloned() - }; - if let Some(handle) = usable(self) { - return Some(handle); - } - let mut parent = self.parent.clone(); - while let Some(node) = parent.and_then(|node| node.upgrade()) { - let node = node.read(cx); - if let Some(handle) = usable(node) { - return Some(handle); - } - parent = node.parent.clone(); - } - None - } - - pub(crate) fn from_op( - op: &MountOp, - surface_id: i32, - host_reports: crate::store::HostReportQueue, - app: Option<&mut gpui::App>, - ) -> Self { - let renders_native_surface = renders_native_surface_for_op(op); - // `core-private:` TextInput reads its own props out of the module JSON. - let text_input = - crate::builtins::textinput::input::TextInputProps::from_json(&op.extension_props_json); - let extension_props = crate::extensions::parse_extension_props(&op.extension_props_json); - // `core-private:` a scrolling component's starting offset comes from the - // module JSON as well. - let scroll = crate::extensions::component_scroll(&op.component, &extension_props); - let scroll_parts = scroll - .as_ref() - .map(|scroll| Box::new(ScrollParts::at(point(scroll.offset.0, scroll.offset.1)))); - let (host_component, host_container, mask_children) = - Self::create_host_component(op, &host_reports, surface_id, app); - let mut view = Self { - tag: op.tag, - render_count: 0, - hovered: false, - pointer_handlers: None, - surface_id, - component: intern_component(&op.component), - slot_shift: (op.component == crate::builtins::native_slot::COMPONENT).then(|| { - crate::builtins::native_slot::register_host(&extension_props, op.tag); - Rc::new(Cell::new(point(0.0, 0.0))) - }), - extension_props_hash: json_hash(&op.extension_props_json), - native_surface: None, - renders_native_surface, - native_surface_descendants: u32::from(renders_native_surface), - native_surface_counted: false, - effect_group_descendants: 0, - forms_effect_group: false, - host_component, - host_index: op.host_index, - host_container, - mask_children, - intrinsic_size: None, - host_reports, - surface_origin: crate::surface::SurfaceOrigin::default(), - frame: if crate::extensions::component_portal(&op.component, &extension_props).is_some() - { - rn_gpui_sys::ffi::RectF { - x: 0.0, - y: 0.0, - ..op.frame - } - } else { - op.frame - }, - parent_tag_cache: std::rc::Rc::new(std::cell::Cell::new(None)), - view: ViewProps::from(&op.view), - animated_transform: None, - animated_background_color: None, - gradient_cache: None, - animated_text_color: None, - animated_opacity: false, - focused: Cell::new(false), - focus_visible: Cell::new(false), - state_text_color: None, - own_state_color: None, - state_styles: None, - paragraph: op.has_paragraph.then(|| paragraph_of(op)), - prepared_paragraph: op - .has_paragraph - .then(|| { - crate::text::take_prepared(op.paragraph.prepared, op.paragraph.prepared_width) - }) - .flatten(), - // `core-private:` the text-input fields come from the module's own - text_input: (op.component == "TextInput").then(|| { - Box::new(crate::builtins::textinput::input::TextInputState { - text: text_input.text.clone(), - placeholder: text_input.placeholder.clone(), - placeholder_mode: text_input.text.is_empty(), - selection_color: text_input.selection_color, - text_color: op - .paragraph - .fragments - .first() - .map(|fragment| fragment.color) - .filter(|color| *color != 0) - .unwrap_or(0xff000000), - multiline: text_input.multiline, - editable: text_input.editable, - placeholder_color: crate::builtins::textinput::input::placeholder_color( - text_input.placeholder_color, - ), - caret_hidden: text_input.caret_hidden, - select_on_focus: text_input.select_on_focus, - submit_behavior: text_input.submit_behavior, - max_length: text_input.max_length, - context_menu_hidden: text_input.context_menu_hidden, - secure_text: text_input.secure, - ..crate::builtins::textinput::input::TextInputState::EMPTY - }) - }), - text_selection: 0..0, - text_selection_anchor: None, - caret_blink_task: Task::ready(()), - transition: None, - transition_forward: false, - transition_progress_sent: None, - transition_end_refreshed: None, - // `core-private:` a scroll view starts at the offset the module's - scroll: scroll.map(Box::new), - virtual_view_mode: Cell::new(None), - scroll_parts, - focusable: op.view.focusable || op.component == "TextInput", - pending_text_input_focus: None, - children: Vec::new(), - parent: None, - renderer_frame: None, - renderer_decoration: None, - inherited: Inherited::default(), - focus_handle: None, - focus_subscriptions: Vec::new(), - extension_props: shared_extension_props(extension_props), - }; - if view.component == "TextInput" { - view.input_mut().selection = crate::builtins::textinput::input::reconcile_selection( - &view.input().text, - 0..0, - text_input.selection, - true, - ); - view.sync_input_paragraph(); - } - view.apply_switch_state(); - view.state_styles = style::StateStyles::from_flat(&view.view); - view.sync_effect_group(); - view - } - - /// The gradients of `backgroundImage`, painted in the node's box. - fn gradient_element(&mut self, frame: RectF, scale: (f32, f32)) -> Option { - let json = &self.view.background_json; - if json.is_empty() { - self.gradient_cache = None; - return None; - } - let size = ( - (frame.w * 10.0).round() as u32, - (frame.h * 10.0).round() as u32, - ); - let stale = self - .gradient_cache - .as_ref() - .is_none_or(|cache| cache.json != *json || cache.size != size); - if stale { - let image = crate::gradient::Background::parse(json).map(|background| { - let (width, height, mut bytes) = - background.render(frame.w, frame.h, GRADIENT_RASTER_LIMIT); - for pixel in bytes.chunks_exact_mut(4) { - pixel.swap(0, 2); - } - let buffer = image::RgbaImage::from_raw(width, height, bytes); - buffer.map(|buffer| { - std::sync::Arc::new(gpui::RenderImage::new(vec![image::Frame::new(buffer)])) - }) - }); - self.gradient_cache = Some(Box::new(GradientCache { - json: json.clone(), - size, - image: image.flatten(), - })); - } - let image = self.gradient_cache.as_ref()?.image.clone()?; - let radii = self.view.border_radii; - let corners = gpui::Corners { - top_left: px(radii.tl * scale.0), - top_right: px(radii.tr * scale.0), - bottom_right: px(radii.br * scale.0), - bottom_left: px(radii.bl * scale.0), - }; - Some( - gpui::canvas( - |_, _, _| (), - move |bounds, (), window, _cx| { - let _ = window.paint_image(bounds, bounds, corners, image.clone(), 0, false); - }, - ) - .absolute() - .top_0() - .left_0() - .size_full() - .into_any_element(), - ) - } - - /// A switch reports whether it is on, which RN's `Switch` does not put in - /// `accessibilityState` on iOS and so on desktop. - fn apply_switch_state(&mut self) { - if self.component != "Switch" { - return; - } - let on = self - .extension_props - .get("value") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false); - self.view.accessibility_checked = if on { 2 } else { 1 }; - } - - /// Applies the groups of an op's view that layout changed, leaving the rest - /// of the node's view as it is. - fn patch_layout_view(&mut self, op: &MountOp) { - let patch = op.layout_patch; - if patch & 1 != 0 { - self.view.content_insets = op.view.content_insets; - self.view.display_none = op.view.display_none; - } - if patch & 2 != 0 { - self.view.border_widths = op.view.border_widths; - } - if patch & 4 != 0 { - self.view.border_radii = op.view.border_radii; - } - if patch & 8 != 0 { - self.view.transform = op.view.transform; - self.view.has_transform = op.view.has_transform; - self.view.transform_origin_set = op.view.transform_origin_set; - } - } - - /// The first frame and layout groups an insert carries for a view created - /// before its layout was known. - pub fn apply_insert_layout(&mut self, op: &MountOp) { - self.frame = op.frame; - if op.layout_patch & 15 != 0 { - self.patch_layout_view(op); - } - } - - pub fn update_from_op(&mut self, op: &MountOp, app: Option<&mut gpui::App>) { - let extension_props = crate::extensions::parse_extension_props(&op.extension_props_json); - self.frame = - if crate::extensions::component_portal(&op.component, &extension_props).is_some() { - rn_gpui_sys::ffi::RectF { - x: 0.0, - y: 0.0, - ..op.frame - } - } else { - op.frame - }; - if op.props_changed { - self.view = ViewProps::from(&op.view); - self.focusable = op.view.focusable - || self.component == "TextInput" - || crate::extensions::component_renderer(&self.component) - .is_some_and(|renderer| renderer.focusable_by_default()); - if !self.focusable { - self.focus_handle = None; - self.focus_subscriptions.clear(); - } - self.state_styles = style::StateStyles::from_flat(&self.view); - self.animated_opacity = false; - if self.component == "TextInput" { - crate::builtins::textinput::input::apply_update(self, op); - } - } - if !op.props_changed && op.layout_patch & 15 != 0 { - self.patch_layout_view(op); - } - if op.layout_patch & 16 != 0 { - if let Some(paragraph) = self.paragraph.as_mut() { - paragraph.selectable = op.paragraph.selectable; - } - } - if op.layout_patch & 32 != 0 && !op.props_changed { - self.extension_props_hash = json_hash(&op.extension_props_json); - self.extension_props = shared_extension_props(extension_props.clone()); - if self.component == "TextInput" { - crate::builtins::textinput::input::apply_update(self, op); - } - } - if op.has_paragraph { - self.prepared_paragraph = - crate::text::take_prepared(op.paragraph.prepared, op.paragraph.prepared_width); - self.paragraph = Some(paragraph_of(op)); - if let (Some(fragment), Some(input)) = ( - op.paragraph.fragments.first(), - self.text_input.as_deref_mut(), - ) { - if fragment.color != 0 && !input.placeholder_mode { - input.text_color = fragment.color; - } - } - } - if self.component == "TextInput" { - self.sync_input_paragraph(); - } - if let Some(next) = crate::extensions::component_scroll(&op.component, &extension_props) { - if let Some(previous) = &mut self.scroll { - previous.content_size = next.content_size; - previous.horizontal = next.horizontal; - previous.enabled = next.enabled; - previous.indicator = next.indicator; - previous.snap = next.snap; - } else { - self.scroll = Some(Box::new(next)); - } - self.parts_mut().handle_stale = true; - } - if self.host_component.is_none() && op.host_emitter_handle != 0 { - // The component was mounted before its emitter existed. - let (component, container, mask_children) = - Self::create_host_component(op, &self.host_reports, self.surface_id, app); - self.host_component = component; - self.host_container = container; - self.mask_children = mask_children; - } else { - self.update_host_component(op, app); - } - if op.props_changed { - self.extension_props = shared_extension_props(extension_props); - self.extension_props_hash = json_hash(&op.extension_props_json); - } - self.apply_switch_state(); - } - - /// Creates the host component an op names by registry index, if it names - /// one. Returns it with whether it is a container and whether it masks its - /// children. - fn create_host_component( - op: &MountOp, - host_reports: &crate::store::HostReportQueue, - surface_id: i32, - app: Option<&mut gpui::App>, - ) -> ( - Option>, - bool, - bool, - ) { - // SAFETY: C++ made these handles for this op and gave them to Rust; this - let (props, emitter) = unsafe { Self::claim_host_handles(op) }; - let Some(entry) = (op.host_index >= 0) - .then(|| crate::host_component::entry(op.host_index as u32)) - .flatten() - else { - return (None, false, false); - }; - let missing_props = props.is_none(); - let (Some(props), Some(emitter)) = (props, emitter) else { - // Without an emitter the node mounts empty; its update brings it. - if missing_props && entry.is_registered() { - log::error!( - "[host-component] {} (tag {}) was created without its props or emitter", - entry.name, - op.tag - ); - } - return (None, entry.options.container, entry.options.mask_children); - }; - let cx = crate::host_component::HostContext::queued(op.tag, host_reports.clone()) - .on_surface(surface_id); - let (cx, _scope) = cx.enter_with(app); - let object = entry.create(props, emitter, cx); - if object.is_none() && !entry.options.mask_children { - log::error!( - "[host-component] {} is declared but no package registered it; the node renders nothing", - entry.name - ); - } - (object, entry.options.container, entry.options.mask_children) - } - - /// Takes ownership of the handles an op carried, so they are released when - /// the result drops. - /// - /// # Safety - /// - /// The handles must have been made by C++ for this op and not claimed before. - unsafe fn claim_host_handles( - op: &MountOp, - ) -> ( - Option, - Option, - ) { - let props = (op.host_props_handle != 0) - .then(|| crate::host_component::PropsHandle::from_raw(op.host_props_handle)); - let emitter = (op.host_emitter_handle != 0) - .then(|| crate::host_component::EmitterHandle::from_raw(op.host_emitter_handle)); - (props, emitter) - } - - /// Hands the component its new props, when C++ found its own props changed. - fn update_host_component(&mut self, op: &MountOp, mut app: Option<&mut gpui::App>) { - if op.host_props_handle == 0 { - return; - } - // SAFETY: as in `create_host_component`; an `Update` op's props handle is - let props = unsafe { crate::host_component::PropsHandle::from_raw(op.host_props_handle) }; - let (cx, view_cx) = (self.host_context(), self.host_context()); - let Some(component) = self.host_component.as_mut() else { - return; - }; - let mut changed = Vec::with_capacity(1 + op.host_changed_more.len()); - changed.push(op.host_changed); - changed.extend_from_slice(&op.host_changed_more); - crate::counters::bump(crate::counters::Counter::HostUpdateCalls); - { - let (cx, _scope) = cx.enter_with(app.as_deref_mut()); - component.update(props, &changed, cx); - } - if let Some(surface) = &self.native_surface { - let (cx, _scope) = view_cx.enter_with(app); - component.update_view(surface.view(), &changed, cx); - } - } - - /// Creates the OS view of a `nativeSurface` component the first time the - /// node is painted, and shows or hides its composition surface with the node. - fn show_native_surface(&mut self, visible: bool, window: &mut Window, cx: &mut Context) { - if !self.renders_native_surface { - return; - } - if self.native_surface.is_none() && visible { - let host_cx = self.host_context(); - let Some(component) = self.host_component.as_mut() else { - return; - }; - let created = - crate::native_surface::NativeSurface::new(window, cx).and_then(|surface| { - let (host_cx, _scope) = host_cx.enter(&mut *cx); - let view = component.create_view(&surface.parent(), window, host_cx)?; - surface.attach(view)?; - Ok(surface) - }); - match created { - Ok(surface) => { - self.native_surface = Some(std::rc::Rc::new(surface)); - self.notify_ancestors(cx); - } - Err(error) => log::error!( - "[native-view] tag {} ({}) initialization failed: {error:#}", - self.tag, - self.component - ), - } - } - if let Some(surface) = &self.native_surface { - if let Err(error) = surface.set_visible(visible) { - log::error!("[native-view] tag {} visibility: {error:#}", self.tag); - } - } - } - - pub(crate) fn set_parent(&mut self, parent: Option>, tag: Option) { - self.parent = parent; - self.parent_tag_cache.set(tag); - } - - pub fn insert_child(&mut self, index: usize, tag: i32, child: Entity) { - let index = index.min(self.children.len()); - self.children.insert(index, (tag, child)); - } - - pub fn remove_child(&mut self, tag: i32) { - self.children.retain(|(child_tag, _)| *child_tag != tag); - } - - /// Whether any node in this subtree, this one included, renders a native - /// surface. - /// A native slot's content is sized by the tree that places it, so the node - /// that shows the tree repaints when the slot's frame changes. - pub(crate) fn notify_slot_owner(&self, cx: &mut Context) { - if self.component != crate::builtins::native_slot::COMPONENT { - return; - } - if let Some(parent) = self.parent.as_ref().and_then(|parent| parent.upgrade()) { - parent.update(cx, |_, cx| cx.notify()); - } - } - - /// Asks every ancestor to render again, so that what they paint after this - /// node reads its new composition surface. - fn notify_ancestors(&self, cx: &mut Context) { - let mut parent = self.parent.as_ref().and_then(|parent| parent.upgrade()); - while let Some(entity) = parent { - entity.update(cx, |_, cx| cx.notify()); - parent = entity - .read(cx) - .parent - .as_ref() - .and_then(|parent| parent.upgrade()); - } - } - - /// The GPUI surface that what is painted after this subtree belongs on, when - /// the subtree hosts a native view: the surface above its last one. - fn surface_after(&self, cx: &App) -> Option { - if let Some(surface) = &self.native_surface { - return Some(surface.above()); - } - if self.native_surface_descendants == 0 { - return None; - } - self.children - .iter() - .rev() - .find_map(|(_, child)| child.read(cx).surface_after(cx)) - } - - /// The children as elements, those painted after a native view moved onto - /// the surface above it so that they cover it. - fn child_elements( - children: &[(i32, Entity)], - has_native: bool, - cx: &App, - ) -> Vec { - let mut above = None; - children - .iter() - .filter(|(_, child)| { - child.read(cx).component != crate::builtins::native_slot::COMPONENT - }) - .map(|(_, child)| { - let element = child.clone().into_any_element(); - let element = match above { - Some(surface) => { - crate::native_surface::OnSurface::new(element, surface).into_any_element() - } - None => element, - }; - if has_native { - above = child.read(cx).surface_after(cx).or(above); - } - element - }) - .collect() - } - - /// The composition surface hosting this node's OS view, once painted. - #[cfg(feature = "test-driver")] - pub(crate) fn native_surface(&self) -> Option<&crate::native_surface::NativeSurface> { - self.native_surface.as_deref() - } - - /// Whether a scroll container holding this node cannot cache its content - /// as a layer: the node is painted as a group of its own, which a layer's - /// tiles do not draw. - pub(crate) fn subtree_forms_effect_group(&self) -> bool { - self.effect_group_descendants > 0 - } - - /// Whether this node's props make its content a group of its own: a - /// translucent view, a blur or drop shadow, a blend mode or isolation. - fn props_form_effect_group(&self) -> bool { - self.view.opacity < 1.0 - || self.view.mix_blend_mode != 0 - || self.view.isolate - || self.mask_children - || self.view.filter_json.contains("\"blur\"") - || self.view.filter_json.contains("\"dropShadow\"") - } - - /// Brings this node's own count in line with its props, and returns the - /// change in the subtree's count. - pub(crate) fn sync_effect_group(&mut self) -> i64 { - let forms = self.props_form_effect_group(); - if forms == self.forms_effect_group { - return 0; - } - self.forms_effect_group = forms; - if forms { - self.effect_group_descendants += 1; - 1 - } else { - self.effect_group_descendants = self.effect_group_descendants.saturating_sub(1); - -1 - } - } - - pub(crate) fn add_effect_group_descendants(&mut self, delta: u32) -> bool { - let before = self.effect_group_descendants; - self.effect_group_descendants = before.saturating_add(delta); - before == 0 && self.effect_group_descendants != 0 - } - - pub(crate) fn sub_effect_group_descendants(&mut self, delta: u32) -> bool { - let before = self.effect_group_descendants; - self.effect_group_descendants = before.saturating_sub(delta); - before != 0 && self.effect_group_descendants == 0 - } - - /// Hands Fabric the scroll offset it has not been given yet, so that a - /// measurement taken now is in the window's coordinates. - pub(crate) fn flush_scroll_state(&self, host: &crate::host::Host) { - let Some(parts) = &self.scroll_parts else { - return; - }; - if parts.sync_pending.replace(false) { - let offset = parts.position.get(); - host.set_scroll_offset(self.tag, offset.x, offset.y); - } - } - - /// Whether a host component that holds React children, such as a container - /// with its own GPUI chrome, is among this node's ancestors. - /// Whether native content (a `NativeRoot`'s tree, or a host component's) - /// lies under this node's pointer area. - pub(crate) fn shares_pointer_with_native(&self, cx: &App) -> bool { - self.component == crate::builtins::native_root::COMPONENT || self.in_host_container(cx) - } - - pub(crate) fn in_host_container(&self, cx: &App) -> bool { - let mut parent = self.parent.clone(); - while let Some(weak) = parent { - let Some(node) = weak.upgrade() else { - return false; - }; - let node = node.read(cx); - if node.host_container && node.host_component.is_some() { - return true; - } - parent = node.parent.clone(); - } - false - } - - /// Where this view lies in the content of the scroll view around it, that - /// scroll view's viewport in the same space, and whether it scrolls - /// sideways; `None` when no scroll view is around it. - pub(crate) fn virtual_view_geometry( - &self, - cx: &App, - ) -> Option<(crate::virtual_view::Rect, crate::virtual_view::Rect, bool)> { - let mut parent = self.parent.clone(); - while let Some(weak) = parent { - let node = weak.upgrade()?; - let node = node.read(cx); - if let Some(scroll) = &node.scroll { - let offset = node.scroll_offset(); - let (x, y) = ( - self.inherited.origin_unscrolled.0 - node.inherited.origin_unscrolled.0, - self.inherited.origin_unscrolled.1 - node.inherited.origin_unscrolled.1, - ); - return Some(( - crate::virtual_view::Rect { - x, - y, - w: self.frame.w, - h: self.frame.h, - }, - crate::virtual_view::Rect { - x: offset.x, - y: offset.y, - w: node.frame.w, - h: node.frame.h, - }, - scroll.horizontal, - )); - } - parent = node.parent.clone(); - } - None - } - - pub(crate) fn subtree_renders_native_surface(&self) -> bool { - self.native_surface_descendants > 0 - } - - /// Claims this node's contribution, so a second `Remove` or a `Delete` - /// after a `Remove` subtracts nothing. - pub(crate) fn take_native_surface_contribution(&mut self) -> u32 { - if !self.native_surface_counted { - return 0; - } - self.native_surface_counted = false; - self.native_surface_descendants - } - - /// Records that this node's contribution is now part of its ancestors' - /// counts. - pub(crate) fn mark_native_surface_counted(&mut self) { - self.native_surface_counted = true; - } - - /// Adds `delta` to this subtree's count. - /// Adds `delta` to this subtree's count. - pub(crate) fn add_native_surface_descendants(&mut self, delta: u32) -> bool { - let before = self.native_surface_descendants; - self.native_surface_descendants = before.saturating_add(delta); - before == 0 && self.native_surface_descendants != 0 - } - - /// Removes `delta` from this subtree's count. - pub(crate) fn sub_native_surface_descendants(&mut self, delta: u32) -> bool { - let before = self.native_surface_descendants; - self.native_surface_descendants = before.saturating_sub(delta); - before != 0 && self.native_surface_descendants == 0 - } - - fn local_transform(&self) -> (f32, f32, f32, f32) { - if self.effective_transform().is_none() { - return (1.0, 1.0, 0.0, 0.0); - } - // GPUI draws the node's subtree under its matrix, so layout, borders, - // text and scroll offsets below it stay in unscaled units. - (1.0, 1.0, 0.0, 0.0) - } - - /// `backfaceVisibility: 'hidden'` while the node is turned to face away. - fn backface_hidden(&self) -> bool { - self.view.backface_hidden - && self - .effective_transform() - .is_some_and(|matrix| crate::transform::faces_away(&matrix)) - } - - /// The matrix GPUI draws this node's subtree under. - fn gpui_transform(&self, scale: (f32, f32)) -> Option { - let m = self.effective_transform()?; - if crate::transform::is_three_dimensional(&m) { - log::debug!( - "[transform] tag={} has perspective or a turn about x or y; drawn flat", - self.tag - ); - } - let mut matrix = crate::transform::affine(&m)?; - matrix.translation[0] *= scale.0; - matrix.translation[1] *= scale.1; - if !self.view.transform_origin_set { - // Without a `transformOrigin` a view turns about its centre. - matrix = gpui::TransformationMatrix::about( - self.frame.w * scale.0 / 2.0, - self.frame.h * scale.1 / 2.0, - matrix, - ); - } - Some(matrix) - } - - pub(crate) fn stable_paint_tree<'a>(&'a self, cx: &'a App) -> crate::extensions::TreeView<'a> { - static NO_NODES: std::sync::OnceLock> = - std::sync::OnceLock::new(); - static NO_RETAINED: std::sync::OnceLock>> = - std::sync::OnceLock::new(); - crate::extensions::TreeView { - nodes: std::borrow::Cow::Borrowed(NO_NODES.get_or_init(HashMap::new)), - root_tags: Vec::new(), - top_inset: self.inherited.window_top_inset, - animations_enabled: !cx.reduce_motion() - && !crate::animation_policy::animations_disabled(), - current: Some((self.tag, self.snapshot())), - retained: NO_RETAINED.get_or_init(HashMap::new), - } - } - - fn origin_frame(&self, cx: &App) -> (f32, f32) { - let frame = self.own_layout_frame(cx); - (frame.x, frame.y) - } - - /// [`Self::layout_frame`] against a tree of this node alone, which is - /// built only when a component renderer may place the node. - fn own_layout_frame(&self, cx: &App) -> RectF { - match self.renderer_frame { - Some(frame) => frame, - None if crate::extensions::component_renderer(&self.component).is_some() => { - self.layout_frame(&self.stable_paint_tree(cx)) - } - None => self.frame, - } - } - - /// `refresh_inherited` runs while `ViewStore` is being updated, so the inset - /// is passed in instead of read back from the global. - pub(crate) fn transition_state(&self) -> Option { - let (transition, started_at) = self.transition?; - Some(crate::extensions::TransitionState { - transition, - started_at, - progress: transition.progress_now(started_at), - }) - } - - pub(crate) fn transition_active(&self, cx: &App) -> bool { - if cx.reduce_motion() || crate::animation_policy::animations_disabled() { - return false; - } - self.transition - .is_some_and(|(transition, started_at)| transition.progress_now(started_at) < 1.0) - } - - pub(crate) fn decoration(&self, cx: &App) -> crate::extensions::Decoration { - if let Some(decoration) = self.renderer_decoration { - return decoration; - } - let Some(renderer) = crate::extensions::component_renderer(&self.component) else { - return crate::extensions::Decoration::default(); - }; - let nodes = HashMap::default(); - let retained = HashMap::default(); - let tree = crate::extensions::TreeView { - nodes: std::borrow::Cow::Borrowed(&nodes), - root_tags: Vec::new(), - top_inset: self.inherited.window_top_inset, - animations_enabled: !cx.reduce_motion() - && !crate::animation_policy::animations_disabled(), - current: Some((self.tag, self.snapshot())), - retained: &retained, - }; - renderer.decorate(&self.component_node_shallow(), &tree) - } - - pub(crate) fn layout_frame(&self, tree: &crate::extensions::TreeView) -> RectF { - if let Some(frame) = self.renderer_frame { - return frame; - } - crate::extensions::component_renderer(&self.component) - .and_then(|renderer| renderer.layout_frame(&self.component_node_shallow(), tree)) - .unwrap_or(self.frame) - } - - /// Whether this node is the first child of a masked view, which only - /// shapes what its siblings show. - fn is_mask(&self, cx: &App) -> bool { - self.parent - .as_ref() - .and_then(|parent| parent.upgrade()) - .is_some_and(|parent| { - let parent = parent.read(cx); - parent.mask_children - && parent - .children - .first() - .is_some_and(|(tag, _)| *tag == self.tag) - }) - } - - fn is_mask_in(&self, tree: &crate::extensions::TreeView) -> bool { - self.parent_tag_cache.get().is_some_and(|parent| { - tree.nodes.get(&parent).is_some_and(|parent| { - parent.mask_children && parent.children.first() == Some(&self.tag) - }) - }) - } - - pub(crate) fn hides_subtree(&self, tree: &crate::extensions::TreeView) -> bool { - crate::extensions::component_renderer(&self.component) - .is_some_and(|renderer| renderer.hides_subtree(&self.component_node_shallow(), tree)) - } - - pub(crate) fn origin_frame_with_tree(&self, tree: &crate::extensions::TreeView) -> (f32, f32) { - let frame = self.layout_frame(tree); - (frame.x, frame.y) - } - - pub(crate) fn inherit_input(&self, tree: &crate::extensions::TreeView) -> InheritInput { - InheritInput { - origin_frame: self.origin_frame_with_tree(tree), - transform: self.local_transform(), - scroll: self - .scroll - .as_ref() - .and(self.scroll_parts.as_ref()) - .map(|parts| parts.position.clone()), - slot_shift: self.slot_shift.clone(), - accessible: self.view.accessible, - hides_descendants: self.view.accessibility_hidden - || self.view.accessibility_important == 3 - || self.view.display_none - || self.is_mask_in(tree), - hides_subtree: self.hides_subtree(tree), - other_modal_child: false, - focusable_or_accessible: self.focusable || self.view.accessible, - window_control: self.window_control_role(), - } - } - - /// How far the window's own coordinates are from this node's: the menu bar - /// and the frame the window draws around its content. - pub(crate) fn window_offset(&self) -> (f32, f32) { - if self.surface_is_placed() { - return (0.0, 0.0); - } - let insets = crate::desktop::window_frame::insets_of(self.surface_id); - ( - insets.left, - crate::desktop::gpui_menu::menu_bar_inset_for_window_id(self.surface_id as u32) - + insets.top, - ) - } - - pub fn absolute_origin(&self, _cx: &App) -> Point { - let (mut x, mut y) = self.inherited.origin_unscrolled; - for link in self.inherited.scrollers.iter() { - let offset = link.position.get(); - x -= link.scale.0 * offset.x; - y -= link.scale.1 * offset.y; - } - let (surface_x, surface_y) = self.surface_origin.get(); - point(px(x + surface_x), px(y + surface_y)) - } - - /// Whether GPUI placed this node's surface, so its frames are window - /// coordinates. - pub(crate) fn surface_is_placed(&self) -> bool { - self.surface_origin.is_placed() - } - - /// Shares `origin` with the other nodes of this node's surface. - pub(crate) fn with_surface_origin(mut self, origin: crate::surface::SurfaceOrigin) -> Self { - self.surface_origin = origin; - self - } - - #[cfg(any(test, debug_assertions))] - pub fn absolute_origin_walked(&self, cx: &App) -> Point { - let mut chain = vec![OriginStep { - frame: self.origin_frame(cx), - transform: self.local_transform(), - scroll: (self.scroll_offset().x, self.scroll_offset().y), - is_scroll: self.scroll.is_some(), - }]; - let mut parent = self.parent.clone(); - while let Some(weak) = parent { - let Some(node) = weak.upgrade() else { break }; - let node = node.read(cx); - chain.push(OriginStep { - frame: node.origin_frame(cx), - transform: node.local_transform(), - scroll: (node.scroll_offset().x, node.scroll_offset().y), - is_scroll: node.scroll.is_some(), - }); - parent = node.parent.clone(); - } - chain.reverse(); - let (x, y) = accumulate_origin(&chain); - let (surface_x, surface_y) = self.surface_origin.get(); - point(px(x + surface_x), px(y + surface_y)) - } - - /// The inverse of every matrix GPUI draws this node under, outermost - /// first, each about its node's origin. Applying them in order maps a point - /// of the window into the space the layout (and `absolute_origin`) uses. - pub(crate) fn transform_inverses(&self, cx: &App) -> Vec { - let mut inverses = Vec::new(); - let mut push = |node: &RNNodeView| { - if let Some(matrix) = node.gpui_transform(node.inherited.parent_scale) { - let origin = node.absolute_origin(cx); - let about = gpui::TransformationMatrix::about( - f32::from(origin.x), - f32::from(origin.y), - matrix, - ); - if let Some(inverse) = about.inverse() { - inverses.push(inverse); - } - } - }; - push(self); - let mut parent = self.parent.clone(); - while let Some(weak) = parent { - let Some(node) = weak.upgrade() else { break }; - let node = node.read(cx); - push(node); - parent = node.parent.clone(); - } - inverses.reverse(); - inverses - } - - /// Where the window shows `rect` (in layout space): the bounds of its - /// corners under every matrix GPUI draws this node under. - pub(crate) fn transformed_bounds( - &self, - cx: &App, - rect: (f32, f32, f32, f32), - ) -> (f32, f32, f32, f32) { - let inverses = self.transform_inverses(cx); - if inverses.is_empty() { - return rect; - } - let forwards: Vec<_> = inverses - .iter() - .rev() - .filter_map(|inverse| inverse.inverse()) - .collect(); - let (x, y, w, h) = rect; - let corners = [(x, y), (x + w, y), (x, y + h), (x + w, y + h)].map(|(cx_, cy)| { - forwards - .iter() - .fold(point(px(cx_), px(cy)), |p, m| m.transform_logical_point(p)) - }); - let xs = corners.map(|p| f32::from(p.x)); - let ys = corners.map(|p| f32::from(p.y)); - let (min_x, max_x) = xs - .iter() - .fold((f32::MAX, f32::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v))); - let (min_y, max_y) = ys - .iter() - .fold((f32::MAX, f32::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v))); - (min_x, min_y, max_x - min_x, max_y - min_y) - } - - pub(crate) fn cumulative_scale(&self, _cx: &App) -> (f32, f32) { - (self.inherited.scale.0.abs(), self.inherited.scale.1.abs()) - } - - #[cfg(any(test, debug_assertions))] - pub(crate) fn cumulative_scale_walked(&self, cx: &App) -> (f32, f32) { - let mut sx = 1.0; - let mut sy = 1.0; - let mut parent = self.parent.clone(); - let mut chain = Vec::new(); - while let Some(weak) = parent { - let Some(node) = weak.upgrade() else { break }; - let node = node.read(cx); - chain.push(node.local_transform()); - parent = node.parent.clone(); - } - chain.reverse(); - chain.push(self.local_transform()); - for (local_sx, local_sy, _, _) in chain { - sx *= local_sx; - sy *= local_sy; - } - (sx.abs(), sy.abs()) - } - - /// `RN_GPUI_VERIFY_INHERITED=1`: checks the cached `Inherited` against the - /// walking versions. - #[cfg(debug_assertions)] - fn verify_inherited(&self, cx: &App) { - let walked = self.absolute_origin_walked(cx); - let cached = self.absolute_origin(cx); - for (field, walked, cached) in [ - ("origin.x", f32::from(walked.x), f32::from(cached.x)), - ("origin.y", f32::from(walked.y), f32::from(cached.y)), - ] { - if (walked - cached).abs() > 0.01 { - log::error!( - "[inherited] mismatch tag={} field={field} cached={cached} walked={walked}", - self.tag - ); - } - } - let (walked_scale_x, walked_scale_y) = self.cumulative_scale_walked(cx); - let (cached_scale_x, cached_scale_y) = self.cumulative_scale(cx); - for (field, walked, cached) in [ - ("scale.x", walked_scale_x, cached_scale_x), - ("scale.y", walked_scale_y, cached_scale_y), - ( - "hidden_by_accessible_ancestor", - f32::from(self.hidden_by_accessible_ancestor_walked(cx)), - f32::from(self.inherited.hidden_by_accessible_ancestor), - ), - ( - "hidden_by_hidden_ancestor", - f32::from(self.hidden_by_hidden_ancestor_walked(cx)), - f32::from(self.inherited.hidden_by_hidden_ancestor), - ), - ( - "hidden_by_modal_sibling", - f32::from(self.hidden_by_modal_sibling_walked(cx)), - f32::from(self.inherited.hidden_by_modal_sibling), - ), - ( - "hidden_by_hiding_ancestor", - f32::from(self.hidden_by_hiding_ancestor_walked(cx)), - f32::from(self.inherited.hidden_by_hiding_ancestor), - ), - ] { - if (walked - cached).abs() > 0.01 { - log::error!( - "[inherited] mismatch tag={} field={field} cached={cached} walked={walked}", - self.tag - ); - } - } - } -} - -#[cfg(debug_assertions)] -fn verify_inherited_enabled() -> bool { - static ENABLED: OnceLock = OnceLock::new(); - *ENABLED.get_or_init(|| std::env::var_os("RN_GPUI_VERIFY_INHERITED").is_some()) -} - -pub(crate) fn role_for_accessibility_role(role: &str, accessible: bool) -> Option { - Some(match role { - "none" | "presentation" => return None, - "button" | "imagebutton" | "togglebutton" => Role::Button, - "image" | "img" => Role::Image, - "link" => Role::Link, - "header" | "heading" => Role::Heading, - "adjustable" => Role::Slider, - "dropdownlist" | "combobox" => Role::ComboBox, - "keyboardkey" => Role::Keyboard, - "checkbox" => Role::CheckBox, - "radio" => Role::RadioButton, - "radiogroup" => Role::RadioGroup, - "switch" => Role::Switch, - "search" => Role::SearchInput, - // AccessKit maps Label to the platform's static-text role; TextInput - // would incorrectly announce read-only RN text as an editable field. - "text" => Role::Label, - "summary" => Role::Note, - "toolbar" => Role::Toolbar, - "menu" | "iconmenu" => Role::Menu, - "menubar" => Role::MenuBar, - "menuitem" => Role::MenuItem, - "progressbar" => Role::ProgressIndicator, - "scrollbar" => Role::ScrollBar, - "tab" => Role::Tab, - "tabbar" => Role::TabPanel, - "tablist" => Role::TabList, - "timer" => Role::Timer, - "alert" => Role::Alert, - "dialog" => Role::Dialog, - "alertdialog" => Role::AlertDialog, - "application" => Role::Application, - "article" => Role::Article, - "banner" => Role::Banner, - "complementary" => Role::Complementary, - "contentinfo" => Role::ContentInfo, - "definition" => Role::Definition, - "directory" => Role::List, - "feed" => Role::Feed, - "figure" => Role::Figure, - "form" => Role::Form, - "log" => Role::Log, - "main" => Role::Main, - "marquee" => Role::Marquee, - "math" => Role::Math, - "meter" => Role::Meter, - "navigation" => Role::Navigation, - "option" => Role::ListBoxOption, - "region" => Role::Region, - "rowgroup" => Role::RowGroup, - "rowheader" => Role::RowHeader, - "columnheader" => Role::ColumnHeader, - "searchbox" => Role::SearchInput, - "separator" => Role::Splitter, - "status" => Role::Status, - "tabpanel" => Role::TabPanel, - "term" => Role::Term, - "tooltip" => Role::Tooltip, - "tree" => Role::Tree, - "treegrid" => Role::TreeGrid, - "treeitem" => Role::TreeItem, - "textbox" => Role::TextInput, - "generic" | "group" => Role::Group, - "list" => Role::List, - "listitem" => Role::ListItem, - "grid" => Role::Grid, - "row" => Role::Row, - "cell" => Role::Cell, - "table" => Role::Table, - "paragraph" => Role::Paragraph, - "label" => Role::Label, - "pager" | "scrollview" | "horizontalscrollview" => Role::ScrollView, - "viewgroup" | "slidingdrawer" => Role::Group, - "drawerlayout" => Role::Pane, - "webview" => Role::WebView, - "spinbutton" => Role::SpinButton, - _ if !role.is_empty() || accessible => Role::Group, - _ => return None, - }) -} - -fn accessibility_action_for_name(name: &str) -> Option { - Some(match name { - "activate" => gpui::AccessibleAction::Click, - "increment" => gpui::AccessibleAction::Increment, - "decrement" => gpui::AccessibleAction::Decrement, - "longpress" => gpui::AccessibleAction::ShowContextMenu, - "expand" => gpui::AccessibleAction::Expand, - "collapse" => gpui::AccessibleAction::Collapse, - _ => return None, - }) -} - -fn dispatch_accessibility_event( - tag: i32, - event: &str, - payload: &serde_json::Value, - window: &mut Window, - cx: &mut App, -) { - let Some(store) = cx.try_global::() else { - return; - }; - let (host, frame_hook) = { - let store = store.0.read(cx); - (store.host.clone(), store.frame_hook.clone()) - }; - host.dispatch_event(tag, event, payload); - frame_hook.arm(window); -} - -fn focus_adjacent_semantic_sibling( - view: &RNNodeView, - key: &str, - window: &mut Window, - cx: &mut App, -) -> bool { - let Some(role @ (Role::RadioButton | Role::Tab)) = view.accessibility_role() else { - return false; - }; - let direction = match key { - "left" | "up" => -1, - "right" | "down" => 1, - _ => return false, - }; - let Some(parent) = view.parent.as_ref().and_then(WeakEntity::upgrade) else { - return false; - }; - let parent = parent.read(cx); - let mut siblings = Vec::new(); - for (tag, entity) in &parent.children { - if *tag == view.tag { - if let Some(focus) = view.focus_handle.clone() { - siblings.push((*tag, focus)); - } - continue; - } - let sibling = entity.read(cx); - if sibling.accessibility_role() == Some(role) - && sibling.focusable - && sibling.view.accessibility_responds_to_interaction - && !sibling.view.accessibility_disabled - && !sibling.view.accessibility_hidden - && !sibling.view.display_none - { - if let Some(focus) = sibling.focus_handle.clone() { - siblings.push((*tag, focus)); - } - } - } - let Some(current_index) = siblings.iter().position(|(tag, _)| *tag == view.tag) else { - return false; - }; - if siblings.len() < 2 { - return false; - } - let next_index = if direction > 0 { - (current_index + 1) % siblings.len() - } else { - (current_index + siblings.len() - 1) % siblings.len() - }; - let (tag, focus_handle) = &siblings[next_index]; - let tag = *tag; - let focus_handle = focus_handle.clone(); - window.on_next_frame(move |window, cx| { - focus_handle.focus(window, cx); - dispatch_accessibility_event(tag, "click", &serde_json::json!({}), window, cx); - }); - true -} - -#[cfg(test)] -mod accessibility_role_tests { - use super::role_for_accessibility_role; - use gpui::Role; - - #[test] - fn maps_react_native_087_roles_to_accesskit_roles() { - for (rn_role, expected) in [ - ("button", Role::Button), - ("dropdownlist", Role::ComboBox), - ("togglebutton", Role::Button), - ("link", Role::Link), - ("search", Role::SearchInput), - ("image", Role::Image), - ("keyboardkey", Role::Keyboard), - ("text", Role::Label), - ("adjustable", Role::Slider), - ("imagebutton", Role::Button), - ("header", Role::Heading), - ("summary", Role::Note), - ("alert", Role::Alert), - ("checkbox", Role::CheckBox), - ("combobox", Role::ComboBox), - ("menu", Role::Menu), - ("menubar", Role::MenuBar), - ("menuitem", Role::MenuItem), - ("progressbar", Role::ProgressIndicator), - ("radio", Role::RadioButton), - ("radiogroup", Role::RadioGroup), - ("scrollbar", Role::ScrollBar), - ("spinbutton", Role::SpinButton), - ("switch", Role::Switch), - ("tab", Role::Tab), - ("tabbar", Role::TabPanel), - ("tablist", Role::TabList), - ("timer", Role::Timer), - ("list", Role::List), - ("toolbar", Role::Toolbar), - ("grid", Role::Grid), - ("pager", Role::ScrollView), - ("scrollview", Role::ScrollView), - ("horizontalscrollview", Role::ScrollView), - ("viewgroup", Role::Group), - ("webview", Role::WebView), - ("drawerlayout", Role::Pane), - ("slidingdrawer", Role::Group), - ("iconmenu", Role::Menu), - ("listitem", Role::ListItem), - ("row", Role::Row), - ("cell", Role::Cell), - ("table", Role::Table), - ("paragraph", Role::Paragraph), - ("label", Role::Label), - ] { - assert_eq!( - role_for_accessibility_role(rn_role, false), - Some(expected), - "{rn_role}" - ); - } - } - - #[test] - fn presentation_and_unknown_roles_keep_their_accessibility_semantics() { - assert_eq!(role_for_accessibility_role("none", true), None); - assert_eq!(role_for_accessibility_role("presentation", true), None); - assert_eq!( - role_for_accessibility_role("unknown", false), - Some(Role::Group) - ); - assert_eq!( - role_for_accessibility_role("unknown", true), - Some(Role::Group) - ); - } -} - -#[derive(Clone)] -pub(crate) struct ScrollLink { - pub(crate) position: Rc>>, - pub(crate) scale: (f32, f32), -} - -fn json_hash(json: &str) -> u64 { - use std::hash::{Hash, Hasher}; - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - json.hash(&mut hasher); - hasher.finish() -} - -/// The component name `name`, shared with every node of that component. -fn intern_component(name: &str) -> gpui::SharedString { - thread_local! { - static NAMES: std::cell::RefCell> = - std::cell::RefCell::default(); - } - NAMES.with_borrow_mut(|names| { - if let Some(name) = names.get(name) { - return name.clone(); - } - let name = gpui::SharedString::from(name.to_string()); - names.insert(name.clone()); - name - }) -} - -/// A node's parsed extension props, every node without any sharing one `null`. -fn shared_extension_props(props: serde_json::Value) -> std::sync::Arc { - static NULL: std::sync::LazyLock> = - std::sync::LazyLock::new(|| std::sync::Arc::new(serde_json::Value::Null)); - if props.is_null() { - NULL.clone() - } else { - std::sync::Arc::new(props) - } -} - -thread_local! { - /// The listeners of nodes without a component renderer, one set for each - /// key: they take the node they run for, so nodes alike share them. - static SHARED_POINTER_HANDLERS: std::cell::RefCell)>> = - const { std::cell::RefCell::new(Vec::new()) }; -} - -/// What a node's pointer listeners are built from, besides the node itself. -#[derive(Clone, Copy, PartialEq)] -struct PointerHandlersKey { - role: WindowControlRole, - inherited_area: Option, - pointer_events: u8, - drags: bool, - os_owns_press: bool, -} - -/// What a node does with a press, as far as the window's own controls go. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum WindowControlRole { - /// A drag region or a caption button: the press is the window's. - Claims(gpui::WindowControlArea), - /// A button, a text input, a scroll view: the press is the node's. - TakesPress, - /// Neither: the press belongs to whatever area contains the node. - Passive, -} - -#[derive(Clone)] -pub(crate) struct Inherited { - /// The window-control area a passive node falls inside, from its nearest - /// ancestor that either claims one or takes the press itself. - pub(crate) window_control_area: Option, - pub(crate) window_top_inset: f32, - pub(crate) hides_subtree_self: bool, - pub(crate) parent_scale: (f32, f32), - pub(crate) scale: (f32, f32), - pub(crate) origin_unscrolled: (f32, f32), - pub(crate) scrollers: Rc<[ScrollLink]>, - pub(crate) accessible_ancestor: bool, - pub(crate) hidden_by_accessible_ancestor: bool, - pub(crate) hidden_by_hidden_ancestor: bool, - pub(crate) hidden_by_modal_sibling: bool, - pub(crate) hidden_by_hiding_ancestor: bool, - /// Whether the node is inside the content of a native slot. - pub(crate) in_native_slot: bool, -} - -impl Default for Inherited { - fn default() -> Self { - Self { - window_control_area: None, - window_top_inset: 0.0, - parent_scale: (1.0, 1.0), - scale: (1.0, 1.0), - origin_unscrolled: (0.0, 0.0), - scrollers: Rc::from(Vec::new()), - accessible_ancestor: false, - hidden_by_accessible_ancestor: false, - hidden_by_hidden_ancestor: false, - hidden_by_modal_sibling: false, - hidden_by_hiding_ancestor: false, - in_native_slot: false, - hides_subtree_self: false, - } - } -} - -impl Inherited { - pub(crate) fn same(&self, other: &Inherited) -> bool { - self.same_render_affecting(other) - && self.origin_unscrolled == other.origin_unscrolled - && self.scrollers.len() == other.scrollers.len() - && self - .scrollers - .iter() - .zip(other.scrollers.iter()) - .all(|(left, right)| { - Rc::ptr_eq(&left.position, &right.position) && left.scale == right.scale - }) - } - - pub(crate) fn same_render_affecting(&self, other: &Inherited) -> bool { - self.window_control_area == other.window_control_area - && self.parent_scale == other.parent_scale - && self.scale == other.scale - && self.accessible_ancestor == other.accessible_ancestor - && self.hidden_by_accessible_ancestor == other.hidden_by_accessible_ancestor - && self.hidden_by_hidden_ancestor == other.hidden_by_hidden_ancestor - && self.hidden_by_modal_sibling == other.hidden_by_modal_sibling - && self.hidden_by_hiding_ancestor == other.hidden_by_hiding_ancestor - } -} - -#[derive(Clone)] -pub(crate) struct InheritInput { - pub(crate) origin_frame: (f32, f32), - pub(crate) transform: (f32, f32, f32, f32), - pub(crate) scroll: Option>>>, - /// For a native slot: how far its content is moved from where layout put it. - pub(crate) slot_shift: Option>>>, - pub(crate) accessible: bool, - pub(crate) hides_descendants: bool, - pub(crate) hides_subtree: bool, - pub(crate) other_modal_child: bool, - pub(crate) focusable_or_accessible: bool, - pub(crate) window_control: WindowControlRole, -} - -pub(crate) fn inherit( - parent: Option<(&Inherited, &InheritInput)>, - own: &InheritInput, -) -> Inherited { - let mut inherited = Inherited { - parent_scale: parent.map_or((1.0, 1.0), |(parent, _)| parent.scale), - ..Inherited::default() - }; - match parent { - Some((parent, input)) => { - // This is `accumulate_origin` with the parent's scroll forced to - // zero, so the offset stays a live value the input path subtracts. - inherited.origin_unscrolled = ( - parent.origin_unscrolled.0 - + inherited.parent_scale.0 * (own.origin_frame.0 + own.transform.2), - parent.origin_unscrolled.1 - + inherited.parent_scale.1 * (own.origin_frame.1 + own.transform.3), - ); - inherited.scrollers = match &input.scroll { - Some(position) => { - let mut links = parent.scrollers.to_vec(); - links.push(ScrollLink { - position: position.clone(), - scale: inherited.parent_scale, - }); - Rc::from(links) - } - None => parent.scrollers.clone(), - }; - inherited.in_native_slot = parent.in_native_slot || own.slot_shift.is_some(); - if let Some(shift) = &own.slot_shift { - let mut links = inherited.scrollers.to_vec(); - links.push(ScrollLink { - position: shift.clone(), - scale: inherited.parent_scale, - }); - inherited.scrollers = Rc::from(links); - } - inherited.accessible_ancestor = parent.accessible_ancestor || input.accessible; - inherited.hidden_by_hidden_ancestor = - parent.hidden_by_hidden_ancestor || input.hides_descendants; - inherited.hidden_by_modal_sibling = - parent.hidden_by_modal_sibling || input.other_modal_child; - inherited.hidden_by_hiding_ancestor = - parent.hidden_by_hiding_ancestor || input.hides_subtree; - inherited.window_control_area = match input.window_control { - WindowControlRole::Claims(area) => Some(area), - WindowControlRole::TakesPress => None, - WindowControlRole::Passive => parent.window_control_area, - }; - } - None => { - inherited.origin_unscrolled = ( - own.origin_frame.0 + own.transform.2, - own.origin_frame.1 + own.transform.3, - ); - } - } - inherited.scale = ( - inherited.parent_scale.0 * own.transform.0, - inherited.parent_scale.1 * own.transform.1, - ); - inherited.hidden_by_accessible_ancestor = - !own.focusable_or_accessible && inherited.accessible_ancestor; - inherited -} - -#[derive(Clone, Copy)] -struct OriginStep { - frame: (f32, f32), - transform: (f32, f32, f32, f32), - scroll: (f32, f32), - is_scroll: bool, -} - -fn accumulate_origin(chain: &[OriginStep]) -> (f32, f32) { - let (mut x, mut y, mut scale_x, mut scale_y) = (0.0f32, 0.0f32, 1.0f32, 1.0f32); - let mut parent_scroll = (0.0f32, 0.0f32); - for step in chain { - let (local_scale_x, local_scale_y, translate_x, translate_y) = step.transform; - x += scale_x * (step.frame.0 - parent_scroll.0 + translate_x); - y += scale_y * (step.frame.1 - parent_scroll.1 + translate_y); - scale_x *= local_scale_x; - scale_y *= local_scale_y; - parent_scroll = if step.is_scroll { - step.scroll - } else { - (0.0, 0.0) - }; - } - (x, y) -} - -thread_local! { - /// How many node copies a `TreeView` has taken, for the test that guards - /// against copying the whole tree once per mount operation. - #[cfg(test)] - static SNAPSHOT_COUNT: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Starts counting node copies from zero. -#[cfg(test)] -pub(crate) fn reset_snapshot_count() { - SNAPSHOT_COUNT.with(|count| count.set(0)); -} - -/// How many node copies have been taken since the last reset. -#[cfg(test)] -pub(crate) fn snapshot_count() -> usize { - SNAPSHOT_COUNT.with(|count| count.get()) -} - -#[cfg(test)] -mod transform_matrix_tests { - use super::{accumulate_origin, OriginStep}; - - #[test] - fn nested_scaled_origins_apply_parent_scroll_and_translation() { - let chain = [ - OriginStep { - frame: (10.0, 20.0), - transform: (2.0, 2.0, 3.0, 4.0), - scroll: (5.0, 6.0), - is_scroll: true, - }, - OriginStep { - frame: (30.0, 40.0), - transform: (0.5, 0.5, 1.0, 2.0), - scroll: (0.0, 0.0), - is_scroll: false, - }, - ]; - - assert_eq!(accumulate_origin(&chain), (65.0, 96.0)); - } -} - -#[cfg(test)] -mod inherited_tests { - use super::{ - accumulate_origin, inherit, InheritInput, Inherited, OriginStep, WindowControlRole, - }; - use gpui::point; - use std::cell::Cell; - use std::rc::Rc; - - fn node(origin_frame: (f32, f32), transform: (f32, f32, f32, f32)) -> InheritInput { - InheritInput { - origin_frame, - transform, - scroll: None, - slot_shift: None, - accessible: false, - hides_descendants: false, - hides_subtree: false, - other_modal_child: false, - focusable_or_accessible: false, - window_control: WindowControlRole::Passive, - } - } - - fn with_role(role: WindowControlRole) -> InheritInput { - InheritInput { - window_control: role, - ..plain() - } - } - - #[test] - fn a_passive_node_falls_inside_the_drag_region_around_it() { - // A title bar's spacer and its title text sit in front of the bar, so - // unless they answer for it the window cannot be dragged by them. - let inherited = inherited(&[ - with_role(WindowControlRole::Claims(gpui::WindowControlArea::Drag)), - plain(), - plain(), - ]); - assert_eq!( - inherited.window_control_area, - Some(gpui::WindowControlArea::Drag) - ); - } - - #[test] - fn a_node_inside_a_button_belongs_to_the_button() { - // The label inside a Pressable in the title bar must press the button, - // not drag the window. - let inherited = inherited(&[ - with_role(WindowControlRole::Claims(gpui::WindowControlArea::Drag)), - with_role(WindowControlRole::TakesPress), - plain(), - ]); - assert_eq!(inherited.window_control_area, None); - } - - #[test] - fn a_caption_buttons_glyph_falls_inside_the_caption_button() { - let inherited = inherited(&[ - with_role(WindowControlRole::Claims(gpui::WindowControlArea::Drag)), - with_role(WindowControlRole::Claims(gpui::WindowControlArea::Close)), - plain(), - ]); - assert_eq!( - inherited.window_control_area, - Some(gpui::WindowControlArea::Close) - ); - } - - fn plain() -> InheritInput { - node((0.0, 0.0), (1.0, 1.0, 0.0, 0.0)) - } - - fn scrolling( - origin_frame: (f32, f32), - transform: (f32, f32, f32, f32), - offset: (f32, f32), - ) -> InheritInput { - InheritInput { - scroll: Some(Rc::new(Cell::new(point(offset.0, offset.1)))), - ..node(origin_frame, transform) - } - } - - fn inherited(chain: &[InheritInput]) -> Inherited { - let mut parent: Option<(Inherited, InheritInput)> = None; - let mut last = Inherited::default(); - for own in chain { - last = inherit( - parent.as_ref().map(|(inherited, input)| (inherited, input)), - own, - ); - parent = Some((last.clone(), own.clone())); - } - last - } - - fn cached_origin(chain: &[InheritInput]) -> (f32, f32) { - let inherited = inherited(chain); - let (mut x, mut y) = inherited.origin_unscrolled; - for link in inherited.scrollers.iter() { - let offset = link.position.get(); - x -= link.scale.0 * offset.x; - y -= link.scale.1 * offset.y; - } - (x, y) - } - - fn walked_origin(chain: &[InheritInput]) -> (f32, f32) { - let steps: Vec = chain - .iter() - .map(|input| OriginStep { - frame: input.origin_frame, - transform: input.transform, - scroll: input - .scroll - .as_ref() - .map(|position| (position.get().x, position.get().y)) - .unwrap_or_default(), - is_scroll: input.scroll.is_some(), - }) - .collect(); - accumulate_origin(&steps) - } - - fn assert_same_origin(chain: &[InheritInput]) { - let cached = cached_origin(chain); - let walked = walked_origin(chain); - assert!( - (cached.0 - walked.0).abs() < 0.01 && (cached.1 - walked.1).abs() < 0.01, - "cached {cached:?} != walked {walked:?}" - ); - } - - #[test] - fn plain_nesting_accumulates_origins() { - let chain = [ - node((10.0, 20.0), (1.0, 1.0, 0.0, 0.0)), - node((5.0, 7.0), (1.0, 1.0, 0.0, 0.0)), - ]; - assert_same_origin(&chain); - assert_eq!(inherited(&chain).origin_unscrolled, (15.0, 27.0)); - assert_eq!(inherited(&chain).scale, (1.0, 1.0)); - } - - #[test] - fn a_scaled_parent_scales_its_children() { - let chain = [ - node((100.0, 0.0), (2.0, 2.0, 0.0, 0.0)), - node((10.0, 20.0), (1.0, 1.0, 3.0, 4.0)), - ]; - assert_same_origin(&chain); - assert_eq!(inherited(&chain).origin_unscrolled, (126.0, 48.0)); - assert_eq!(inherited(&chain).scale, (2.0, 2.0)); - } - - #[test] - fn a_scrollview_offset_moves_only_its_descendants() { - let chain = [ - scrolling((0.0, 0.0), (1.0, 1.0, 0.0, 0.0), (0.0, 100.0)), - node((10.0, 20.0), (1.0, 1.0, 0.0, 0.0)), - ]; - assert_same_origin(&chain); - assert_eq!(cached_origin(&chain), (10.0, -80.0)); - assert_eq!(inherited(&chain[..1]).origin_unscrolled, (0.0, 0.0)); - } - - #[test] - fn a_scrollview_inside_a_scaled_parent_scrolls_at_that_scale() { - let chain = [ - node((0.0, 0.0), (2.0, 2.0, 0.0, 0.0)), - scrolling((0.0, 0.0), (1.0, 1.0, 0.0, 0.0), (0.0, 50.0)), - node((0.0, 10.0), (1.0, 1.0, 0.0, 0.0)), - ]; - assert_same_origin(&chain); - let inherited = inherited(&chain); - assert_eq!(inherited.scrollers.len(), 1); - assert_eq!(inherited.scrollers[0].scale, (2.0, 2.0)); - assert_eq!(cached_origin(&chain), (0.0, -80.0)); - } - - #[test] - fn nested_scrollviews_keep_both_offsets_outermost_first() { - let chain = [ - scrolling((0.0, 0.0), (1.0, 1.0, 0.0, 0.0), (0.0, 10.0)), - node((0.0, 0.0), (2.0, 2.0, 0.0, 0.0)), - scrolling((0.0, 0.0), (1.0, 1.0, 0.0, 0.0), (0.0, 20.0)), - node((0.0, 5.0), (1.0, 1.0, 0.0, 0.0)), - ]; - assert_same_origin(&chain); - let inherited = inherited(&chain); - assert_eq!(inherited.scrollers.len(), 2); - assert_eq!(inherited.scrollers[0].scale, (1.0, 1.0)); - assert_eq!(inherited.scrollers[1].scale, (2.0, 2.0)); - assert_eq!(cached_origin(&chain), (0.0, -40.0)); - } - - #[test] - fn a_scroll_offset_never_changes_the_cached_value() { - let position = Rc::new(Cell::new(point(0.0, 0.0))); - let mut root = plain(); - root.scroll = Some(position.clone()); - let child = plain(); - let before = inherited(&[root.clone(), child.clone()]); - assert_eq!(cached_origin(&[root.clone(), child.clone()]), (0.0, 0.0)); - position.set(point(0.0, 40.0)); - let after = inherited(&[root.clone(), child.clone()]); - assert!(before.same(&after)); - assert_eq!(cached_origin(&[root, child]), (0.0, -40.0)); - } - - #[test] - fn hidden_by_hidden_ancestor_follows_the_running_flag() { - let mut root = plain(); - root.hides_descendants = true; - let chain = [root.clone(), plain(), plain()]; - assert!(inherited(&chain).hidden_by_hidden_ancestor); - assert!(!inherited(&[root]).hidden_by_hidden_ancestor); - assert!(!inherited(&[plain(), plain()]).hidden_by_hidden_ancestor); - } - - #[test] - fn hidden_by_hiding_ancestor_follows_the_running_flag() { - let mut root = plain(); - root.hides_subtree = true; - assert!(inherited(&[root.clone(), plain()]).hidden_by_hiding_ancestor); - assert!(!inherited(&[root]).hidden_by_hiding_ancestor); - assert!(!inherited(&[plain(), plain()]).hidden_by_hiding_ancestor); - } - - #[test] - fn hidden_by_modal_sibling_is_set_by_the_parent_for_each_child() { - let mut root = plain(); - root.other_modal_child = true; - assert!(inherited(&[root.clone(), plain()]).hidden_by_modal_sibling); - assert!(!inherited(&[root]).hidden_by_modal_sibling); - assert!(!inherited(&[plain(), plain()]).hidden_by_modal_sibling); - } - - #[test] - fn hidden_by_accessible_ancestor_spares_focusable_and_accessible_nodes() { - let mut root = plain(); - root.accessible = true; - let child = plain(); - assert!(inherited(&[root.clone(), child.clone()]).hidden_by_accessible_ancestor); - - let mut focusable = plain(); - focusable.focusable_or_accessible = true; - assert!(!inherited(&[root.clone(), focusable]).hidden_by_accessible_ancestor); - - let mut accessible = plain(); - accessible.accessible = true; - accessible.focusable_or_accessible = true; - assert!(!inherited(&[root, accessible]).hidden_by_accessible_ancestor); - - assert!(!inherited(&[child.clone(), child]).hidden_by_accessible_ancestor); - } -} - -impl RNNodeView { - pub(crate) fn sync_input_paragraph(&mut self) { - let Some(input) = self.text_input.as_deref_mut() else { - return; - }; - let show_placeholder = input.text.is_empty(); - let visible = if show_placeholder { - &input.placeholder - } else { - &input.text - }; - let Some(paragraph) = self.paragraph.as_mut() else { - return; - }; - if paragraph.fragments.is_empty() { - if visible.is_empty() { - return; - } - paragraph - .fragments - .push(rn_gpui_sys::ffi::TextFragmentFlat { - text: visible.clone(), - font_family: String::new(), - font_size: 14.0, - font_weight: 400, - italic: false, - color: if show_placeholder { - input.placeholder_color - } else { - input.text_color - }, - line_height: 0.0, - letter_spacing: 0.0, - underline: false, - strikethrough: false, - text_transform: 0, - font_variant: 0, - background_color: 0, - }); - } else { - paragraph.fragments[0].text.clone_from(visible); - if show_placeholder && !input.placeholder_mode { - input.text_color = paragraph.fragments[0].color; - } - paragraph.fragments[0].color = if show_placeholder { - input.placeholder_color - } else if input.placeholder_mode { - input.text_color - } else { - paragraph.fragments[0].color - }; - paragraph.fragments.truncate(1); - } - input.placeholder_mode = show_placeholder; - } -} - -/// Reports a key to JS with the names the DOM uses. -/// -/// `key` is the DOM's `KeyboardEvent.key`: `ArrowLeft`, `Enter`, `Escape`, a -/// single printable character, or `" "` for space. `code` is the physical key -/// (`KeyA`, `Digit4`, `ArrowLeft`) and `keyCode` the legacy number. Before this, -/// only six keys were translated and everything else went out as GPUI's own -/// spelling with `keyCode: 0`, so JS could not tell `ArrowLeft` from an unknown -/// key. -/// -/// The GPUI spelling is kept in `gpuiKey` for anything that still matches on it. -/// Nothing in core reads the payload back — the internal handling matches on -/// `event.keystroke.key` before this runs — so this is purely what JS sees. -fn dispatch_key(tag: i32, event_type: &str, key: &gpui::Keystroke, repeat: bool, cx: &App) { - let Some(store) = cx.try_global::() else { - return; - }; - let host = store.0.read(cx).host.clone(); - let key_name = crate::desktop::keymap::normalise_web_key(&key.key, key.modifiers.shift); - host.dispatch_event( - tag, - event_type, - &serde_json::json!({ - "key": key_name, - "gpuiKey": key.key.as_str(), - "code": crate::desktop::keymap::web_code(&key.key), - "keyCode": crate::desktop::keymap::key_code(&key.key), - "repeat": repeat, - "shiftKey": key.modifiers.shift, - "ctrlKey": key.modifiers.control, - "altKey": key.modifiers.alt, - "metaKey": key.modifiers.platform, - }), - ); -} - -pub(crate) static RENDER_COUNT: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); - -/// Queues one delivery of the host reports made during this frame's renders. -fn schedule_frame_host_report_flush( - reports: &crate::store::HostReportQueue, - window: &mut Window, - cx: &mut Context, -) { - if reports.is_empty() || reports.claim_flush() { - return; - } - let reports = reports.clone(); - window.defer(cx, move |_window, cx| { - reports.release_flush(); - match crate::store::store_from(cx) { - Some(store) => { - store.update(cx, |store, cx| store.flush_host_reports(cx)); - } - None => { - let _ = reports.take(); - } - } - }); -} - -impl RNNodeView { - /// A `ScrollBar` styles the nearest scroll view above it. It renders when it - /// mounts and when its props change, which is when the scroll view needs to - /// hear about it. - fn hand_scrollbar_to_scroll_view(&self, cx: &mut Context) { - let spec = crate::scroll_indicator::ScrollbarSpec::from_props(&self.extension_props); - let (bar, tag) = (cx.entity(), self.tag); - let mut ancestor = self.parent.clone(); - while let Some(node) = ancestor.and_then(|weak| weak.upgrade()) { - if node.read(cx).scroll.is_some() { - node.update(cx, |scroll_view, cx| { - scroll_view.take_scrollbar(spec, &bar, tag, cx) - }); - return; - } - ancestor = node.read(cx).parent.clone(); - } - } - - fn take_scrollbar( - &mut self, - spec: crate::scroll_indicator::ScrollbarSpec, - bar: &Entity, - tag: i32, - cx: &mut Context, - ) { - if self - .parts_mut() - .scrollbar_release - .as_ref() - .map(|(id, _)| *id) - != Some(bar.entity_id()) - { - let release = cx.observe_release(bar, |scroll_view, _, cx| { - scroll_view.parts_mut().scrollbar = Default::default(); - scroll_view.parts_mut().scrollbar_tag = None; - scroll_view.parts_mut().scrollbar_release = None; - cx.notify(); - }); - self.parts_mut().scrollbar_release = Some((bar.entity_id(), release)); - } - if self.parts_mut().scrollbar != spec || self.parts_mut().scrollbar_tag != Some(tag) { - self.parts_mut().scrollbar = spec; - self.parts_mut().scrollbar_tag = Some(tag); - cx.notify(); - } - } -} - -impl Render for RNNodeView { - fn render(&mut self, window: &mut Window, cx: &mut Context) -> AnyElement { - RENDER_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - self.render_count += 1; - if self.component == crate::builtins::desktop_scroll_bar::COMPONENT { - self.hand_scrollbar_to_scroll_view(cx); - } - let accessibility_active = window.is_a11y_active(); - let was_initialized = ACCESSIBILITY_ACTIVE_INITIALIZED.swap(true, Ordering::Relaxed); - let previous_accessibility_active = - ACCESSIBILITY_ACTIVE.swap(accessibility_active, Ordering::Relaxed); - if cfg!(not(target_os = "macos")) - && was_initialized - && previous_accessibility_active != accessibility_active - { - if let Some(store) = cx.try_global::() { - store - .0 - .read(cx) - .host - .emit_device_event_bool("screenReaderChanged", accessibility_active); - } - } - if std::env::var_os("RN_GPUI_DEBUG_A11Y_TREE").is_some() - && !A11Y_TREE_DUMP_COMPLETE.load(Ordering::Relaxed) - && A11Y_TREE_DUMP_SCHEDULED - .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed) - .is_ok() - { - window.on_next_frame(|window, _cx| { - #[cfg(all(target_os = "macos", feature = "visual-capture"))] - let attempts = A11Y_TREE_DUMP_ATTEMPTS.fetch_add(1, Ordering::Relaxed); - if let Some(tree) = window.debug_a11y_tree_json() { - log::info!("[a11y-tree] {tree}"); - A11Y_TREE_DUMP_COMPLETE.store(true, Ordering::Relaxed); - } else { - #[cfg(all(target_os = "macos", feature = "visual-capture"))] - { - if attempts >= 10 { - log::error!("[a11y-tree] provider did not activate after 10 frames"); - A11Y_TREE_DUMP_COMPLETE.store(true, Ordering::Relaxed); - return; - } - crate::native_view::activate_accessibility_probe(window); - A11Y_TREE_DUMP_SCHEDULED.store(false, Ordering::Relaxed); - window.refresh(); - } - #[cfg(not(all(target_os = "macos", feature = "visual-capture")))] - { - log::info!("[a11y-tree] unavailable (no active AccessKit client)"); - A11Y_TREE_DUMP_COMPLETE.store(true, Ordering::Relaxed); - } - } - }); - } - if debug_render_counts_enabled() { - log::info!( - "[retention] RNNodeView::render elapsed_ms={} tag={} component={} count={}", - elapsed_since_first_render_ms(), - self.tag, - self.component, - self.render_count - ); - } - let hidden_portal = - crate::extensions::component_portal(&self.component, &self.extension_props) - .is_some_and(|portal| !portal.visible); - let hidden = self.view.display_none || hidden_portal || self.backface_hidden(); - self.show_native_surface(!hidden, window, cx); - if hidden { - return div().id(self.tag).size_0().into_any_element(); - } - let frame = self.own_layout_frame(cx); - let (scale_x, scale_y) = self.cumulative_scale(cx); - // Yoga's child frames are relative to the parent's border box, and the - // element has no GPUI border widths of its own (borders are painted as - // rules), so GPUI's origin for absolute children is that box as well. - let (parent_scale_x, parent_scale_y) = self.inherited.parent_scale; - let (origin_x, origin_y) = (frame.x, frame.y); - let (_, _, translate_x, translate_y) = self.local_transform(); - // No parent scroll offset here: the ScrollView moves all its children at once - // through its content wrapper. - let base_left = parent_scale_x * (origin_x + translate_x); - let base_top = parent_scale_y * (origin_y + translate_y); - #[cfg(debug_assertions)] - if verify_inherited_enabled() { - self.verify_inherited(cx); - } - let transition = if cx.reduce_motion() || crate::animation_policy::animations_disabled() { - None - } else { - self.transition - }; - let transition_started_at = transition.map(|(_, started_at)| started_at); - let transition_progress = - transition.map(|(transition, started_at)| transition.progress_now(started_at)); - if let (Some((_transition, started_at)), Some(progress)) = (transition, transition_progress) - { - let sample = (started_at, progress); - if self.transition_progress_sent != Some(sample) { - self.transition_progress_sent = Some(sample); - if let Some(store) = cx.try_global::() { - let handle = crate::extensions::StoreHandle::new(store.0.downgrade()); - for observer in crate::extensions::store_observers() { - observer.on_transition_frame(self.tag, progress, &handle, cx); - } - } - } - } - if transition_progress.is_some_and(|progress| progress < 1.0) { - let node = cx.entity().downgrade(); - window.on_next_frame(move |_, cx| { - let _ = node.update(cx, |_, cx| cx.notify()); - }); - window.request_animation_frame(); - } else if let Some(started) = transition_started_at { - if self.transition_end_refreshed != Some(started) { - self.transition_end_refreshed = Some(started); - let surface_id = self.surface_id; - cx.defer(move |cx| { - if let Some(store) = crate::store::store_from(cx) { - store.update(cx, |store, cx| { - store.refresh_inherited(surface_id, cx); - }); - } - }); - } - } - let scroll = self.scroll.clone(); - let is_scroll = scroll.is_some(); - let ordered_children = self.children.clone(); - let has_native = self.native_surface_descendants > 0; - if let Some(renderer) = crate::extensions::component_renderer(&self.component) { - let node = self.renderer_node(&*renderer, cx); - let handle = crate::extensions::NodeHandle::new(cx.entity().downgrade()); - let painted = - crate::extensions::render_with_node(handle, || renderer.render(&node, window, cx)); - if let Some(painted) = painted { - // The renderer paints the node's whole appearance, but core still - // owns where the node is: without this box the element is an - // unpositioned flow child of the parent, and a `size_full()` - // image fills the parent instead of the node's frame. - let mut placed = div().id(self.tag); - *placed.style() = { - let mut style = style::to_refinement(&self.view); - style.position = Some(Position::Absolute); - style.inset.left = Some(px(base_left).into()); - style.inset.top = Some(px(base_top).into()); - style.size.width = Some(px(frame.w * scale_x).into()); - style.size.height = Some(px(frame.h * scale_y).into()); - style - }; - return placed.child(painted).into_any_element(); - } - } - let mut element = div().id(self.tag); - // Everything that puts this node into keymap resolution goes through one - // `KeyContext`, because `Div::key_context` *assigns*: a second call would - // silently replace the first. Building one context and merging into it - // means a node that is both a scope and a text input keeps both markers, - // instead of one vanishing with no warning. - // - // This is also the only place a context can go: GPUI keeps it on the - // element and pushes it onto the dispatch tree at paint, which is what - // makes the focus path's context stack — and so the scope precedence — - // real. - let key_context = { - let mut context = gpui::KeyContext::default(); - let mut claimed = false; - if let Some(renderer) = crate::extensions::component_renderer(&self.component) { - let node = self.component_node_shallow(); - if let Some(declared) = renderer.key_context(&node) { - match gpui::KeyContext::parse(&declared) { - Ok(parsed) => { - context.extend(&parsed); - claimed = true; - } - Err(error) => { - log::warn!( - "[shortcut] {} has an invalid key context {declared:?}: {error}", - self.component - ); - } - } - } - } - // A `TextInput` marks itself so a shortcut that did not ask for - // `allowInTextInput` can exclude itself with `!rn-text-input`. The - // marker is on the node's own element, so it is on the focus path of - // every key the input handles. - if self.component == "TextInput" { - if let Ok(marker) = - gpui::KeyContext::parse(crate::desktop::keymap::TEXT_INPUT_CONTEXT) - { - context.extend(&marker); - claimed = true; - } - } - claimed.then_some(context) - }; - if let Some(context) = key_context { - element = element.key_context(context); - } - // A shortcut scope owns the `ShortcutAction`s whose ids it registered. - // The listener is in the bubble phase, innermost node first, so the - // deepest scope on the focus path claims the action and an outer one - // never sees it — which is the "innermost wins" rule. A scope that does - // not own the id propagates, so an outer scope, or the app-wide handler, - // still gets its turn. - if self.component == crate::builtins::shortcut_scope::COMPONENT { - let tag = self.tag; - let scope = crate::builtins::shortcut_scope::scope_name(&self.component_node_shallow()); - element = element.on_action(cx.listener( - move |_this, action: &crate::desktop::keymap::ShortcutAction, window, cx| { - if !crate::desktop::keymap::scope_owns(cx, &scope, &action.id) { - cx.propagate(); - return; - } - crate::desktop::keymap::dispatch_to(cx, tag, &action.id, Some(window)); - }, - )); - } - let decoration = self.decoration(cx); - if decoration.clip { - element = element.overflow_hidden().overflow_clips_corners(); - } - if let Some(background) = decoration.background { - element = element.bg(gpui::rgb(background)); - } - // One helper decides the area, so a `View` drag region and a component - // that claims a caption button cannot disagree — and the component wins - // its own box, which is what makes a `WindowControl` inside a title bar - // act as a button rather than drag the window. - if let Some(area) = self.window_control_area(cx) { - element = element.window_control_area(area); - } - let accessibility_id = if self.view.accessibility_native_id.is_empty() { - &self.view.test_id - } else { - &self.view.accessibility_native_id - }; - if !accessibility_id.is_empty() { - element = element.accessibility_id(accessibility_id.clone()); - } - if !self.view.accessibility_label.is_empty() { - element = element.aria_label(self.view.accessibility_label.clone()); - } - if self.view.accessibility_hint.is_empty() && !self.view.tooltip.is_empty() { - element = element.aria_description(self.view.tooltip.clone()); - } else if !self.view.accessibility_hint.is_empty() { - element = element.aria_description(self.view.accessibility_hint.clone()); - } - if self.view.accessibility_label.is_empty() { - let labelled_by = if accessibility_active { - self.accessibility_labelled_by_text(cx) - } else { - String::new() - }; - let label = if !labelled_by.is_empty() { - labelled_by - } else if self.view.accessible && accessibility_active { - self.accessible_group_text(cx) - } else { - String::new() - }; - if !label.is_empty() { - element = element.aria_label(label); - } - } - if self.component == "Paragraph" && self.view.accessibility_label.is_empty() { - if let Some(paragraph) = &self.paragraph { - let text = paragraph - .fragments - .iter() - .map(|fragment| fragment.text.as_str()) - .collect::(); - if !text.is_empty() { - element = element.aria_value(text); - } - } - } - if !self.view.accessibility_value_text.is_empty() { - element = element.aria_value(self.view.accessibility_value_text.clone()); - } - if self.view.accessibility_has_value_min { - element = element.aria_min_numeric_value(f64::from(self.view.accessibility_value_min)); - } - if self.view.accessibility_has_value_max { - element = element.aria_max_numeric_value(f64::from(self.view.accessibility_value_max)); - } - if self.view.accessibility_has_value_now { - element = element.aria_numeric_value(f64::from(self.view.accessibility_value_now)); - } - if self.component == "TextInput" { - if !self.input().placeholder.is_empty() { - element = element.aria_placeholder(self.input().placeholder.clone()); - } - if !self.input().secure_text && !self.input().text.is_empty() { - element = element.aria_value(self.input().text.clone()); - } - } - if let Some(role) = self.accessibility_role() { - element = element.role(role); - } else if accessibility_active && !self.view.tooltip.is_empty() { - element = element.role(Role::Group); - } - if accessibility_active && self.accessibility_role() == Some(Role::ListItem) { - if let Some(parent) = self.parent.as_ref().and_then(|parent| parent.upgrade()) { - let parent = parent.read(cx); - let mut position = None; - let mut size = 0; - for (tag, sibling) in &parent.children { - // Render already leases self. Never read it through Entity. - let is_item = *tag == self.tag - || sibling.read(cx).accessibility_role() == Some(Role::ListItem); - if is_item { - size += 1; - if *tag == self.tag { - position = Some(size); - } - } - } - if let Some(position) = position { - element = element - .aria_position_in_set(position) - .aria_size_of_set(size); - } - } - } - let hidden_image = self.component == "Image" - && self.view.accessibility_label.is_empty() - && self.view.accessibility_role.is_empty() - && !self.view.accessible; - let hidden_by_accessible_ancestor = self.inherited.hidden_by_accessible_ancestor; - let hidden_by_hidden_ancestor = self.inherited.hidden_by_hidden_ancestor; - let hidden_by_modal_sibling = self.inherited.hidden_by_modal_sibling; - let hidden_by_active_modal = crate::accessibility::hidden_by_active_modal(self.tag, cx); - let hidden_by_hiding_ancestor = self.inherited.hidden_by_hiding_ancestor; - let hidden_by_decoration = decoration.a11y_hidden || self.is_mask(cx); - let hidden_display_none = self.view.display_none; - let accessibility = self.view.clone(); - #[cfg(feature = "visual-capture")] - let accessibility_tag = self.tag; - let input_editable = self.input().editable; - let input_secure_text = self.input().secure_text; - let is_text_input = self.component == "TextInput"; - let input_text = self.input().text.clone(); - let input_placeholder = self.input().placeholder.clone(); - element = element.a11y_synthetic_children(move |builder| { - let node = builder.parent_node(); - if accessibility.accessibility_important == 3 - || accessibility.accessibility_hidden - || hidden_image - || hidden_image - || hidden_by_accessible_ancestor - || hidden_by_hidden_ancestor - || hidden_by_modal_sibling - || hidden_by_active_modal - || hidden_by_hiding_ancestor - || hidden_by_decoration - || hidden_display_none - { - node.set_hidden(); - } - if accessibility.accessibility_modal { - node.set_modal(); - } - if accessibility.accessibility_busy { - node.set_busy(); - } - if accessibility.accessibility_disabled - || !accessibility.accessibility_responds_to_interaction - { - node.set_disabled(); - } - if accessibility.accessibility_selected { - node.set_selected(true); - } - if accessibility.accessibility_expanded >= 0 { - node.set_expanded(accessibility.accessibility_expanded != 0); - } - match accessibility.accessibility_checked { - 1 => node.set_toggled(gpui::Toggled::False), - 2 => node.set_toggled(gpui::Toggled::True), - 3 => node.set_toggled(gpui::Toggled::Mixed), - _ => {} - } - if !accessibility.accessibility_language.is_empty() { - node.set_language(accessibility.accessibility_language.clone()); - } - match accessibility.accessibility_live_region { - 1 => node.set_live(gpui::accesskit::Live::Polite), - 2 => node.set_live(gpui::accesskit::Live::Assertive), - _ => {} - } - if accessibility.accessibility_has_value_min { - node.set_min_numeric_value(f64::from(accessibility.accessibility_value_min)); - } - if accessibility.accessibility_has_value_max { - node.set_max_numeric_value(f64::from(accessibility.accessibility_value_max)); - } - if accessibility.accessibility_has_value_now { - node.set_numeric_value(f64::from(accessibility.accessibility_value_now)); - } - let value = if is_text_input { - if input_secure_text || input_text.is_empty() { - None - } else { - Some(input_text.as_str()) - } - } else if !accessibility.accessibility_value_text.is_empty() { - Some(accessibility.accessibility_value_text.as_str()) - } else { - None - }; - if let Some(value) = value { - node.set_value(value); - } - if is_text_input && !input_placeholder.is_empty() { - node.set_placeholder(input_placeholder); - } - if is_text_input { - if !input_editable { - node.set_read_only(); - } - if input_secure_text { - node.set_value(""); - } - } - node.set_custom_actions( - accessibility - .accessibility_actions - .iter() - .filter(|action| accessibility_action_for_name(&action.name).is_none()) - .enumerate() - .map(|(index, action)| gpui::accesskit::CustomAction { - id: index as i32, - description: if action.label.is_empty() { - action.name.clone().into_boxed_str() - } else { - action.label.clone().into_boxed_str() - }, - }) - .collect::>(), - ); - #[cfg(feature = "visual-capture")] - if std::env::var_os("RN_GPUI_DEBUG_A11Y_TREE").is_some() { - let snapshot = serde_json::json!({ - "tag": accessibility_tag, - "id": accessibility.test_id, - "role": format!("{:?}", node.role()), - "label": node.label(), - "value": node.value(), - "hidden": node.is_hidden(), - "disabled": node.is_disabled(), - "modal": node.is_modal(), - "escapeListener": accessibility.accessibility_has_escape_listener, - "language": node.language(), - "live": node.live().map(|value| format!("{value:?}")), - "position": node.position_in_set(), - "size": node.size_of_set(), - "customActions": node.custom_actions().iter().map(|action| action.description.as_ref()).collect::>(), - }).to_string(); - static SNAPSHOTS: OnceLock>> = OnceLock::new(); - let mut snapshots = SNAPSHOTS.get_or_init(Mutex::default).lock().unwrap(); - if snapshots.get(&accessibility_tag) != Some(&snapshot) { - log::info!("[a11y-node] {snapshot}"); - snapshots.insert(accessibility_tag, snapshot); - } - } - }); - let has_accessibility_focus_target = self.has_accessibility_focus_target(); - let deferred_focus = - self.focus_handle.is_none() && !accessibility_active && self.defers_focus_handle(); - let mut focus_child = None; - if (self.focusable - || self.view.accessibility_has_escape_listener - || has_accessibility_focus_target) - && !deferred_focus - { - self.ensure_focus_handle(window, cx); - self.set_accessibility_tab_stop_allowed( - !hidden_by_active_modal - && !hidden_by_modal_sibling - && !hidden_by_hiding_ancestor - && !self.inherited.hidden_by_hidden_ancestor - && !self.inherited.hidden_by_accessible_ancestor, - ); - if let Some(handle) = &self.focus_handle { - if accessibility_active || is_scroll || self.component == "TextInput" { - // The accessibility tree needs the role, the label and the focus on one - // element. - element = element.track_focus(handle); - } else { - // `track_focus` forces a div hitbox, and a div asks whether it is hovered - // while painting; a zero-sized child's hitbox is never hovered. - focus_child = Some(div().absolute().size_0().track_focus(handle)); - } - } - element = element - .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| { - // gpui offers a key to every focusable node on the path to the - // focused one; React bubbles the event from the target itself, - // so only the focused node sends it. - let is_target = this - .focus_handle - .as_ref() - .is_some_and(|handle| handle.is_focused(window)); - if is_target { - dispatch_key(this.tag, "topKeyDown", &event.keystroke, event.is_held, cx); - if this.component == "TextInput" { - dispatch_key( - this.tag, - "topKeyPress", - &event.keystroke, - event.is_held, - cx, - ); - } - } - if !event.is_held - && focus_adjacent_semantic_sibling(this, &event.keystroke.key, window, cx) - { - cx.stop_propagation(); - } - if !event.is_held - && matches!(event.keystroke.key.as_str(), "enter" | "space") - && this.component != "TextInput" - && (this.view.accessible - || matches!( - this.accessibility_role(), - Some( - Role::Button - | Role::DefaultButton - | Role::CheckBox - | Role::RadioButton - | Role::Switch - | Role::Link - ) - )) - { - let activated = crate::extensions::component_renderer(&this.component) - .zip( - cx.try_global::() - .map(|s| s.0.clone()), - ) - .is_some_and(|(renderer, store)| { - let handle = crate::extensions::StoreHandle::new(store.downgrade()); - renderer.activate( - &this.component_node_shallow(), - &handle, - window, - cx, - ) - }); - if !activated { - dispatch_accessibility_event( - this.tag, - "click", - &serde_json::json!({}), - window, - cx, - ); - } - cx.stop_propagation(); - } - if event.keystroke.key == "escape" { - #[cfg(feature = "visual-capture")] - log::info!( - "[accessibility] Escape tag={} target={:?}", - this.tag, - this.accessibility_escape_target(cx) - ); - if let Some(tag) = this.accessibility_escape_target(cx) { - dispatch_accessibility_event( - tag, - "accessibilityEscape", - &serde_json::json!({}), - window, - cx, - ); - cx.stop_propagation(); - } - } - let primary_modifier = if cfg!(target_os = "macos") { - event.keystroke.modifiers.platform - } else { - event.keystroke.modifiers.control - }; - if this.component == "TextInput" - && primary_modifier - && event.keystroke.key == "a" - && !event.keystroke.modifiers.alt - { - crate::builtins::textinput::input::select_all(this, window, cx); - cx.stop_propagation(); - } - if this.component == "TextInput" - && crate::builtins::textinput::input::handle_key( - this, - &event.keystroke.key, - event.keystroke.modifiers.shift, - window, - cx, - ) - { - cx.stop_propagation(); - } - if let Some(store) = cx.try_global::() { - store.0.read(cx).frame_hook.arm(window); - } - if event.keystroke.key == "tab" { - if event.keystroke.modifiers.shift { - window.focus_prev(cx); - } else { - window.focus_next(cx); - } - cx.stop_propagation(); - } - })) - .on_key_up(cx.listener(|this, event: &KeyUpEvent, window, cx| { - if this - .focus_handle - .as_ref() - .is_some_and(|handle| handle.is_focused(window)) - { - dispatch_key(this.tag, "topKeyUp", &event.keystroke, false, cx); - } - if let Some(store) = cx.try_global::() { - store.0.read(cx).frame_hook.arm(window); - } - })); - if let Some(focus) = self.pending_text_input_focus.take() { - if let Some(handle) = self.focus_handle.as_ref() { - if focus { - handle.focus(window, cx); - } else if handle.is_focused(window) { - window.blur(cx); - } - } - } - } - if self.view.accessibility_responds_to_interaction && !self.view.accessibility_disabled { - let tag = self.tag; - let actions = self.view.accessibility_actions.clone(); - let has_activate_action = actions.iter().any(|action| action.name == "activate"); - if !has_activate_action - && (self.focusable - || self.view.accessibility_has_tap_listener - || matches!( - self.accessibility_role(), - Some( - Role::Button - | Role::DefaultButton - | Role::CheckBox - | Role::RadioButton - | Role::Switch - | Role::Link - | Role::Tab - | Role::MenuItem - ) - )) - { - let has_tap_listener = self.view.accessibility_has_tap_listener; - element = element.on_a11y_action( - gpui::AccessibleAction::Click, - move |_data, window, cx| { - dispatch_accessibility_event( - tag, - "click", - &serde_json::json!({}), - window, - cx, - ); - if has_tap_listener { - dispatch_accessibility_event( - tag, - "accessibilityTap", - &serde_json::json!({}), - window, - cx, - ); - } - }, - ); - } - for action in actions.iter().filter_map(|action| { - accessibility_action_for_name(&action.name) - .map(|native_action| (native_action, action.name.clone())) - }) { - let (native_action, name) = action; - let dispatch = self.view.accessibility_has_action_listener; - let tap = name == "activate" && self.view.accessibility_has_tap_listener; - element = element.on_a11y_action(native_action, move |_data, window, cx| { - if name == "activate" { - dispatch_accessibility_event( - tag, - "click", - &serde_json::json!({}), - window, - cx, - ); - } - if dispatch { - dispatch_accessibility_event( - tag, - "accessibilityAction", - &serde_json::json!({"actionName": name}), - window, - cx, - ); - } - if tap { - dispatch_accessibility_event( - tag, - "accessibilityTap", - &serde_json::json!({}), - window, - cx, - ); - } - }); - } - let custom_actions = actions - .into_iter() - .filter(|action| accessibility_action_for_name(&action.name).is_none()) - .collect::>(); - if !custom_actions.is_empty() && self.view.accessibility_has_action_listener { - let tag = self.tag; - element = element.on_a11y_action( - gpui::AccessibleAction::CustomAction, - move |data, window, cx| { - let Some(gpui::accesskit::ActionData::CustomAction(id)) = data else { - return; - }; - let Some(action) = custom_actions.get(*id as usize) else { - return; - }; - dispatch_accessibility_event( - tag, - "accessibilityAction", - &serde_json::json!({"actionName": action.name}), - window, - cx, - ); - }, - ); - } - } - if let Some(close_event) = - crate::extensions::component_portal(&self.component, &self.extension_props) - .filter(|portal| portal.visible) - .and_then(|portal| portal.close_request_event) - { - element = - element.on_key_down(cx.listener(move |this, event: &KeyDownEvent, window, cx| { - if event.keystroke.key != "escape" { - return; - } - if let Some(store) = cx.try_global::() { - let store = store.0.read(cx); - store - .host - .dispatch_event(this.tag, &close_event, &serde_json::json!({})); - store.frame_hook.arm(window); - } - cx.stop_propagation(); - })); - } - if crate::extensions::component_renderer(&self.component) - .is_some_and(|renderer| renderer.handles_keys(&self.component_node_shallow())) - { - element = element.on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| { - let Some(renderer) = crate::extensions::component_renderer(&this.component) else { - return; - }; - let Some(store_entity) = cx - .try_global::() - .map(|store| store.0.clone()) - else { - return; - }; - let (top_inset, animations_enabled) = { - let store = store_entity.read(cx); - ( - store.top_inset, - !cx.reduce_motion() && !crate::animation_policy::animations_disabled(), - ) - }; - let handle = crate::extensions::StoreHandle::new(store_entity.downgrade()); - let node = this.component_node_shallow(); - // `retained` is the only borrow left, so it is copied out too; - // every node is a snapshot, so the tree never touches an entity - // while the handler below holds the app mutably. - let self_tag = this.tag; - let (nodes, root_tags, retained) = store_entity.read_with(cx, |store, cx| { - // This node is leased by the listener that is running, and - // the tree already carries it as `current`, so it is skipped - // here rather than read back through the entity map. - let nodes: HashMap = store - .nodes - .iter() - .filter(|(tag, _)| **tag != self_tag) - .map(|(tag, entity)| (*tag, entity.read(cx).snapshot())) - .collect(); - let root_tags = store - .roots - .values() - .flat_map(|root| root.read(cx).children.iter().map(|(tag, _)| *tag)) - .collect(); - (nodes, root_tags, store.retained_subtrees.clone()) - }); - let tree = crate::extensions::TreeView { - nodes: std::borrow::Cow::Owned(nodes), - root_tags, - top_inset, - animations_enabled, - current: Some((this.tag, this.snapshot())), - retained: &retained, - }; - let handled = - renderer.on_key_down(&node, &event.keystroke.key, &tree, &handle, window, cx); - if handled { - cx.stop_propagation(); - } - })); - } - let mut group_opacity = None; - let mut blend = gpui::BlendMode::Normal; - let mut isolated = false; - *element.style() = { - let mut style = style::to_refinement(&self.view); - if let Some(color) = self.animated_background_color { - style.background = Some(Fill::from(style::color(color))); - } - let radius_scale = scale_x.min(scale_y); - style.corner_radii.top_left = Some(px(self.view.border_radii.tl * radius_scale).into()); - style.corner_radii.top_right = - Some(px(self.view.border_radii.tr * radius_scale).into()); - style.corner_radii.bottom_right = - Some(px(self.view.border_radii.br * radius_scale).into()); - style.corner_radii.bottom_left = - Some(px(self.view.border_radii.bl * radius_scale).into()); - if let Some(shadows) = style.box_shadow.as_mut() { - for shadow in shadows { - shadow.offset.x = px(f32::from(shadow.offset.x) * scale_x); - shadow.offset.y = px(f32::from(shadow.offset.y) * scale_y); - shadow.blur_radius = px(f32::from(shadow.blur_radius) * radius_scale); - shadow.spread_radius = px(f32::from(shadow.spread_radius) * radius_scale); - } - } - style.position = Some(Position::Absolute); - if decoration.display == Some(false) { - style.display = Some(Display::None); - } - let transitioning_out = transition.is_some_and(|(transition, _)| { - transition.to.opacity < 1.0 - && transition_progress.is_some_and(|progress| progress < 1.0) - }); - let _ = transitioning_out; - let mut transition_offset_x = 0.0; - if let (Some((transition, _)), Some(progress)) = (transition, transition_progress) { - let pose = transition.pose_at(progress); - transition_offset_x = pose.offset_x * frame.w; - style.opacity = Some(style.opacity.unwrap_or(1.0) * pose.opacity); - } - style.inset.left = Some(px(base_left + transition_offset_x).into()); - style.inset.top = Some(px(base_top).into()); - style.size.width = Some(px(frame.w * scale_x).into()); - style.size.height = Some(px(frame.h * scale_y).into()); - // Content under a translucent node fades as one picture, not - // primitive by primitive. - if !self.children.is_empty() { - group_opacity = style.opacity.take().filter(|opacity| *opacity < 1.0); - } - // A blend mode combines the node's picture with what is beneath - // it; isolation keeps its content's blend modes to itself. - blend = crate::filter::blend_mode(self.view.mix_blend_mode); - isolated = self.view.isolate; - style - }; - if self.state_styles.is_some() { - self.sync_focus(window, cx); - } - let resolved = self.resolved_state(); - if let Some(state) = &resolved { - let animating = style::Animating { - background: self.animated_background_color.is_some(), - opacity: self.animated_opacity, - }; - element - .style() - .refine(&state.refinement((scale_x, scale_y), animating)); - } - // The listeners live on a `PointerArea` around the node's div, not on the div - // itself: a div with a hitbox records a hover read while painting, which makes - // a scroll under a still pointer rebuild every row. It shares the div's layout - // node and inserts its hitbox before the div's children insert theirs. - // The window-control area a press here lands in: the bar of a title bar, - // or one of its caption buttons. On Windows a left press there belongs to - // the OS: the hit-test answered `HTCAPTION` (or a caption button), and - // the window backend only lets `DefWindowProc` act on that — move the - // window, maximize it on a double click, snap it, press the button — when - // the app leaves the press unhandled. So nothing here may consume it. - let control_area = self.window_control_area(cx); - let os_owns_press = cfg!(target_os = "windows") && control_area.is_some(); - let handlers = self.pointer_handlers(control_area, os_owns_press, cx); - let claims_area = control_area.is_some(); - let node = cx.entity().downgrade(); - if is_scroll || claims_area { - // The direct-listener path needs one registration per button, and - // the middle and side buttons go through it too, so a scroll - // container reports them the same way a pointer area does. - for (button, down, up) in [ - ( - MouseButton::Right, - handlers.right_down.clone(), - handlers.right_up.clone(), - ), - ( - MouseButton::Left, - handlers.left_down.clone(), - handlers.left_up.clone(), - ), - ( - MouseButton::Middle, - handlers.middle_down.clone(), - handlers.middle_up.clone(), - ), - ] { - for handler in down { - let node = node.clone(); - element = element.on_mouse_down(button, move |event, window, cx| { - handler(&node, event, window, cx) - }); - } - for handler in up { - let node = node.clone(); - element = element.on_mouse_up(button, move |event, window, cx| { - handler(&node, event, window, cx) - }); - } - } - for handler in handlers.mouse_move.iter().cloned() { - let node = node.clone(); - element = element - .on_mouse_move(move |event, window, cx| handler(&node, event, window, cx)); - } - // GPUI's own `on_hover` reports an edge by tracking the hovered state - // itself, so this path needs no bookkeeping of its own — and it takes - // only one listener, so the handlers are chained rather than added. - if !handlers.hover.is_empty() { - let chained = handlers.hover.clone(); - let node = node.clone(); - element = element.on_hover(move |hovered: &bool, window, cx| { - for handler in &chained { - handler(&node, *hovered, window, cx); - } - }); - } - } - let pointer_area = (!is_scroll && !claims_area && !handlers.is_empty()).then_some(handlers); - // Not for a scroll container, which never had one: its content is - // re-parented into the scrolling child and a focus handle here would sit - // outside it. - if !is_scroll { - if let Some(focus_child) = focus_child { - element = element.child(focus_child); - } - } - if let Some(surface) = &self.native_surface { - element = element.child(crate::native_surface::NativeSurfaceElement { - surface: surface.clone(), - }); - } - if let Some(gradient) = self.gradient_element(frame, (scale_x, scale_y)) { - element = element.child(gradient); - } - let mut text_overlay = None; - if let Some(paragraph) = &self.paragraph { - let mut scaled_paragraph = paragraph.clone(); - scaled_paragraph.shadow_dx *= scale_x; - scaled_paragraph.shadow_dy *= scale_y; - scaled_paragraph.shadow_radius *= scale_x; - for fragment in &mut scaled_paragraph.fragments { - fragment.font_size = scaled_font_size(fragment.font_size, scale_y); - fragment.line_height *= scale_y; - fragment.letter_spacing *= scale_x; - if let Some(color) = self.animated_text_color.or(self.state_text_color) { - fragment.color = color; - } - } - // `core-private:` a text field paints its own paragraph, in its own - if self.component == "TextInput" { - element = crate::builtins::textinput::render::paragraph_content( - self, - element, - &scaled_paragraph, - (scale_x, scale_y), - frame, - window, - ); - } else { - let prepared = self.prepared_paragraph.as_ref().filter(|_| { - scale_x == 1.0 - && scale_y == 1.0 - && self.animated_text_color.or(self.state_text_color).is_none() - }); - // Painted by a wrapper rather than a child canvas, so the text costs - // no layout node, unless the div does more to its children than the - // wrapper can: hide them, fade them, or clip them to rounded corners. - let radii = self.view.border_radii; - let clip = decoration.clip || self.view.overflow_hidden; - let overlay = (!clip - || (radii.tl <= 0.0 && radii.tr <= 0.0 && radii.br <= 0.0 && radii.bl <= 0.0)) - && element.style().display != Some(Display::None) - && element.style().opacity.is_none_or(|opacity| opacity >= 1.0); - let (with_text, overlay) = crate::builtins::textinput::render::plain_paragraph( - self, - element, - &scaled_paragraph, - (scale_x, scale_y), - frame, - overlay, - prepared, - ); - element = with_text; - text_overlay = overlay.map(|parts| (parts, clip)); - } - } - // `core-private:` the caret and the selection are drawn from the - if self.component == "TextInput" { - element = crate::builtins::textinput::render::caret_canvas( - self, - element, - cx.entity(), - (scale_x, scale_y), - ); - } - if let Some(scroll) = scroll { - let (content_width, content_height) = scroll.content_size; - let mut content = div() - .relative() - .flex_none() - .w(px(content_width.max(frame.w))) - .h(px(content_height.max(frame.h))); - content = content.children(Self::child_elements(&ordered_children, has_native, cx)); - // The handle is only written when React or a layout change moved - // the offset. Writing it on every render would count as a scroll. - if std::mem::take(&mut self.parts_mut().handle_stale) { - let offset = self.scroll_offset(); - self.parts_mut() - .handle - .set_offset(point(px(-offset.x * scale_x), px(-offset.y * scale_y))); - } - let strategy = crate::scroll_layers::scroll_strategy( - self.subtree_renders_native_surface() || self.subtree_forms_effect_group(), - ); - let mut thumb_apply: Option = None; - // A manual-offset container's handle is not tracked by an element, so - // its viewport and furthest offset come from the layout instead. - let manual = matches!(strategy, crate::scroll_layers::ScrollStrategy::ManualOffset); - let manual_extents = manual.then(|| { - ( - size(px(frame.w * scale_x), px(frame.h * scale_y)), - point( - px((content_width - frame.w).max(0.0) * scale_x), - px((content_height - frame.h).max(0.0) * scale_y), - ), - ) - }); - if scroll.enabled { - let scroller = Rc::new(Scroller { - tag: self.tag, - position: self.parts_mut().position.clone(), - handle: self.parts_mut().handle.clone(), - sync_generation: self.parts_mut().sync_generation.clone(), - sync_pending: self.parts_mut().sync_pending.clone(), - emit: self.parts_mut().emit.clone(), - event_throttle: std::time::Duration::from_secs_f32( - scroll.event_throttle_ms.max(0.0) / 1000.0, - ), - content_size: scroll.content_size, - viewport: (frame.w, frame.h), - scale: (scale_x, scale_y), - event: scroll.event.clone(), - horizontal: scroll.horizontal, - snap: scroll.snap.clone(), - gesture: self.parts_mut().gesture.clone(), - deceleration: scroll.deceleration, - max_offset: manual_extents.map(|(_, max)| max), - }); - // A manual-offset container only follows its node's own render. - let view = cx.entity(); - let dragged = scroller.clone(); - thumb_apply = Some(Rc::new(move |offset, window, cx| { - dragged.handle.set_offset(offset); - dragged.sync(window, cx); - if manual { - let _ = view.update(cx, |_, cx| cx.notify()); - } - })); - content = content.on_scroll(move |event: &gpui::ScrollEvent, window, cx| { - scroller.on_wheel(event, window, cx); - let scroller = scroller.clone(); - window.defer(cx, move |window, cx| scroller.sync(window, cx)); - }); - } - // The scrolling container is a child filling this node, not the - // node's own element: whatever sits inside a scrolling container - // moves with its content, and the indicator must not. - let mut scroller = div().id("scroller").absolute().top_0().left_0().size_full(); - match strategy { - crate::scroll_layers::ScrollStrategy::GpuiLayer => { - scroller = if !scroll.enabled { - scroller.overflow_hidden() - } else if scroll.horizontal { - scroller.overflow_x_scroll().overflow_y_hidden() - } else { - scroller.overflow_y_scroll().overflow_x_hidden() - }; - scroller = scroller.restrict_scroll_to_axis(); - element = element.overflow_hidden().overflow_clips_corners().child( - scroller - .track_scroll(&self.parts_mut().handle) - .child(content), - ); - } - crate::scroll_layers::ScrollStrategy::ManualOffset => { - let (offset_x, offset_y) = (self.scroll_offset().x, self.scroll_offset().y); - let moved = div() - .relative() - .flex_none() - .left(px(-offset_x * scale_x)) - .top(px(-offset_y * scale_y)) - .w(px(scroll.content_size.0.max(frame.w))) - .h(px(scroll.content_size.1.max(frame.h))) - .children(Self::child_elements(&ordered_children, has_native, cx)); - if scroll.enabled { - let horizontal = scroll.horizontal; - let max = ( - (scroll.content_size.0 - frame.w).max(0.0), - (scroll.content_size.1 - frame.h).max(0.0), - ); - let position = self.parts_mut().position.clone(); - let handle = self.parts_mut().handle.clone(); - let scale = (scale_x, scale_y); - let view = cx.entity(); - scroller = - scroller.on_scroll(move |event: &gpui::ScrollEvent, _window, _cx| { - let delta = event.delta.pixel_delta(px(20.)); - let (dx, dy) = if horizontal { - let swapped = - f32::from(delta.x) == 0.0 && event.modifiers.shift; - (f32::from(if swapped { delta.y } else { delta.x }), 0.0) - } else { - (0.0, f32::from(delta.y)) - }; - let current = position.get(); - let next = point( - (current.x - dx / scale.0.max(f32::EPSILON)).clamp(0.0, max.0), - (current.y - dy / scale.1.max(f32::EPSILON)).clamp(0.0, max.1), - ); - if (next.x - current.x).abs() < 0.01 - && (next.y - current.y).abs() < 0.01 - { - return; - } - position.set(next); - handle.set_offset(point( - px(-next.x * scale.0), - px(-next.y * scale.1), - )); - let _ = view.update(_cx, |_, cx| cx.notify()); - }); - } - scroller = scroller.overflow_hidden().child(moved); - element = element - .overflow_hidden() - .overflow_clips_corners() - .child(scroller); - } - } - if scroll.indicator && scroll.enabled { - let horizontal = scroll.horizontal; - if self - .parts_mut() - .indicator - .as_ref() - .is_none_or(|indicator| indicator.read(cx).horizontal() != horizontal) - { - let handle = self.parts_mut().handle.clone(); - let programmatic = self.parts_mut().programmatic.clone(); - self.parts_mut().indicator = Some(cx.new(|_| { - crate::scroll_indicator::ScrollIndicator::new( - handle, - horizontal, - programmatic, - ) - })); - } - let tag = self.tag; - let parts = self.parts_mut(); - if let (Some(indicator), Some(apply)) = (parts.indicator.clone(), thumb_apply) { - let (bar_tag, position) = (parts.scrollbar_tag, parts.position.clone()); - let emit: crate::scroll_indicator::EmitEvent = Rc::new(move |event, cx| { - let Some(store) = cx.try_global::() else { - return; - }; - let offset = position.get(); - let payload = serde_json::json!({ - "contentOffset": {"x": offset.x, "y": offset.y}, - }); - let host = &store.0.read(cx).host; - // The scroll view declares `onScrollBarDrag*`; a ScrollBar - // child declares its own `onDrag*` under other event names. - host.dispatch_event(tag, event, &payload); - if let Some(bar_tag) = bar_tag { - let thumb = event.replacen("topScrollBar", "topScrollBarThumb", 1); - host.dispatch_event(bar_tag, &thumb, &payload); - } - }); - let spec = parts.scrollbar.clone(); - indicator.update(cx, |indicator, _| { - indicator.configure(spec, apply, emit, manual_extents) - }); - } - element = element.children(self.parts_mut().indicator.clone()); - } else { - self.parts_mut().indicator = None; - } - } else if self.host_component.is_some() { - let chrome_cx = self.host_context(); - let overlay_cx = self.host_context(); - let container = self.host_container; - let (chrome, overlay) = match self.host_component.as_mut() { - Some(component) => { - let chrome = { - let (chrome_cx, _scope) = chrome_cx.enter(&mut *cx); - component.render(window, chrome_cx) - }; - let overlay = if container { - let (overlay_cx, _scope) = overlay_cx.enter(&mut *cx); - component.render_overlay(window, overlay_cx) - } else { - None - }; - (Some(chrome), overlay) - } - None => (None, None), - }; - schedule_frame_host_report_flush(&self.host_reports, window, cx); - element = element - .children(chrome) - .children(Self::child_elements(&ordered_children, has_native, cx)) - .children(overlay); - } else { - let renderer = crate::extensions::component_renderer(&self.component).map(|renderer| { - let node = self.renderer_node(&*renderer, cx); - (renderer, node) - }); - let content = renderer - .as_ref() - .and_then(|(renderer, node)| renderer.content(node, window, cx)); - let painted: Vec = content - .into_iter() - .chain(Self::child_elements(&ordered_children, has_native, cx)) - .collect(); - let painted = match &renderer { - Some((renderer, node)) => renderer.children(node, painted, window, cx), - None => painted, - }; - if self.mask_children && !painted.is_empty() { - let mut painted = painted.into_iter(); - let mask = painted.next().expect("a mask child"); - element = element.child(crate::filter::Masked::new(mask, painted.collect())); - } else { - element = element.children(painted); - } - if self.component == "TextInput" && self.input().multiline { - element = element.on_scroll(cx.listener( - |this, event: &gpui::ScrollEvent, _window, cx| { - let delta = match &event.delta { - gpui::ScrollDelta::Pixels(delta) => f32::from(delta.y), - gpui::ScrollDelta::Lines(lines) => lines.y * 40.0, - }; - let before = this.input().scroll_y; - crate::builtins::textinput::input::scroll_input_to( - this, - before - delta, - cx, - ); - if this.input().scroll_y != before { - cx.stop_propagation(); - } - }, - )); - } - if self.component == "TextInput" && !self.input().multiline { - element = element.on_scroll(cx.listener( - |this, event: &gpui::ScrollEvent, window, cx| { - let delta = match &event.delta { - gpui::ScrollDelta::Pixels(delta) => { - let x = f32::from(delta.x); - if x.abs() > 0.0 { - x - } else { - f32::from(delta.y) - } - } - gpui::ScrollDelta::Lines(lines) => { - if lines.x.abs() > 0.0 { - lines.x * 40.0 - } else { - lines.y * 40.0 - } - } - }; - let viewport = (this.frame.w - - this.view.content_insets.left - - this.view.content_insets.right) - .max(0.0); - let natural_width = this - .paragraph - .as_ref() - .map(|paragraph| { - let line = this.input().text.split('\n').next().unwrap_or_default(); - crate::text::input_caret_x( - window.text_system(), - paragraph, - line, - line.len(), - ) - }) - .unwrap_or(0.0); - let max_offset = (natural_width - viewport).max(0.0); - let next = (this.input().scroll_x - delta).clamp(0.0, max_offset); - if (next - this.input().scroll_x).abs() > f32::EPSILON { - this.input_mut().scroll_x = next; - cx.notify(); - cx.stop_propagation(); - } - }, - )); - } - } - let width = frame.w * scale_x; - let height = frame.h * scale_y; - let edges = [ - ( - 0, - 0.0, - 0.0, - height, - self.view.border_widths.left * scale_x, - false, - ), - ( - 1, - 0.0, - 0.0, - width, - self.view.border_widths.top * scale_y, - true, - ), - ( - 2, - width - self.view.border_widths.right * scale_x, - 0.0, - height, - self.view.border_widths.right * scale_x, - false, - ), - ( - 3, - 0.0, - height - self.view.border_widths.bottom * scale_y, - width, - self.view.border_widths.bottom * scale_y, - true, - ), - ]; - let border_colors = resolved.as_ref().map_or(self.view.border_colors, |state| { - state.border_colors(self.view.border_colors) - }); - let radii = self.view.border_radii; - let rounded = radii.tl > 0.0 || radii.tr > 0.0 || radii.br > 0.0 || radii.bl > 0.0; - let uniform_border = rounded - && border_colors[0] != 0 - && border_colors.iter().all(|c| *c == border_colors[0]) - && self.view.border_styles.iter().all(|s| *s == 0) - && self.view.border_widths.left > 0.0 - && self.view.border_widths.left == self.view.border_widths.top - && self.view.border_widths.left == self.view.border_widths.right - && self.view.border_widths.left == self.view.border_widths.bottom; - let mut border_rules = Vec::new(); - for (edge, x, y, length, thickness, horizontal) in edges { - if uniform_border { - break; - } - let color = border_colors[edge]; - if color != 0 && thickness > 0.0 { - border_rules.extend(rule_segments( - x, - y, - length, - thickness, - horizontal, - color, - self.view.border_styles[edge], - )); - } - } - if uniform_border { - // Strips cannot follow a rounded corner; GPUI paints a rounded border itself. - let mut ring = div() - .absolute() - .top_0() - .left_0() - .size_full() - .border(px(self.view.border_widths.left * scale_x.min(scale_y))) - .border_color(style::color(border_colors[0])); - let radii = &mut ring.style().corner_radii; - let scale = scale_x.min(scale_y); - radii.top_left = Some(px(self.view.border_radii.tl * scale).into()); - radii.top_right = Some(px(self.view.border_radii.tr * scale).into()); - radii.bottom_right = Some(px(self.view.border_radii.br * scale).into()); - radii.bottom_left = Some(px(self.view.border_radii.bl * scale).into()); - element = element.child(ring); - } - if !border_rules.is_empty() { - let mut border_clip = div() - .absolute() - .top_0() - .left_0() - .size_full() - .overflow_hidden(); - { - let radii = &mut border_clip.style().corner_radii; - radii.top_left = Some(px(self.view.border_radii.tl * scale_x.min(scale_y)).into()); - radii.top_right = Some(px(self.view.border_radii.tr * scale_x.min(scale_y)).into()); - radii.bottom_right = - Some(px(self.view.border_radii.br * scale_x.min(scale_y)).into()); - radii.bottom_left = - Some(px(self.view.border_radii.bl * scale_x.min(scale_y)).into()); - } - element = element.child(border_clip.children(border_rules)); - } - let (outline_color, outline_width, outline_offset) = resolved.as_ref().map_or( - ( - self.view.outline_color, - self.view.outline_width, - self.view.outline_offset, - ), - |state| { - state.outline(( - self.view.outline_color, - self.view.outline_width, - self.view.outline_offset, - )) - }, - ); - let mut outline_rules = Vec::new(); - let outline_radii = [ - self.view.border_radii.tl, - self.view.border_radii.tr, - self.view.border_radii.br, - self.view.border_radii.bl, - ]; - let rounded_outline = self.view.outline_style == 0 - && outline_color != 0 - && outline_width > 0.0 - && outline_radii.iter().any(|radius| *radius > 0.0); - if rounded_outline { - outline_rules.push(rounded_ring( - width, - height, - outline_offset, - outline_width, - outline_color, - outline_radii, - scale_x.min(scale_y), - )); - } else if outline_color != 0 && outline_width > 0.0 { - let outline_width_x = outline_width * scale_x; - let outline_width_y = outline_width * scale_y; - let offset_x = outline_offset * scale_x; - let offset_y = outline_offset * scale_y; - let x = -offset_x - outline_width_x; - let y = -offset_y - outline_width_y; - outline_rules.extend(rule_segments( - x, - y, - width + 2.0 * (offset_x + outline_width_x), - outline_width_y, - true, - outline_color, - self.view.outline_style, - )); - outline_rules.extend(rule_segments( - x, - height + offset_y, - width + 2.0 * (offset_x + outline_width_x), - outline_width_y, - true, - outline_color, - self.view.outline_style, - )); - outline_rules.extend(rule_segments( - x, - y + outline_width_y, - height + 2.0 * offset_y, - outline_width_x, - false, - outline_color, - self.view.outline_style, - )); - outline_rules.extend(rule_segments( - width + offset_x, - y + outline_width_y, - height + 2.0 * offset_y, - outline_width_x, - false, - outline_color, - self.view.outline_style, - )); - } - // A text input shows its caret, and an app that sets an outline draws its - // own ring; the keyboard focus ring is for everything else. - let app_outline = outline_color != 0 && outline_width > 0.0; - if self.component != "TextInput" - && !app_outline - && self - .focus_handle - .as_ref() - .is_some_and(|focus| focus.is_focused(window)) - && window.last_input_was_keyboard() - { - let focus_color = 0xff60a5fa; - let ring = 2.0; - let radii = [ - self.view.border_radii.tl, - self.view.border_radii.tr, - self.view.border_radii.br, - self.view.border_radii.bl, - ]; - if radii.iter().any(|radius| *radius > 0.0) { - outline_rules.push(rounded_ring( - width, - height, - 0.0, - ring, - focus_color, - radii, - scale_x.min(scale_y), - )); - } else { - outline_rules.extend(rule_segments( - -ring, - -ring, - width + ring * 2.0, - ring, - true, - focus_color, - 0, - )); - outline_rules.extend(rule_segments( - -ring, - height, - width + ring * 2.0, - ring, - true, - focus_color, - 0, - )); - outline_rules.extend(rule_segments( - -ring, - 0.0, - height, - ring, - false, - focus_color, - 0, - )); - outline_rules.extend(rule_segments( - width, - 0.0, - height, - ring, - false, - focus_color, - 0, - )); - } - } - let element = element.children(outline_rules); - let element = match text_overlay { - Some(((painter, offset, size), clip)) => { - crate::text::ParagraphOverlay::new(element, painter, offset, size, clip) - .into_any_element() - } - None => element.into_any_element(), - }; - let element = match pointer_area { - Some(handlers) => PointerArea::new( - element, - node, - handlers, - self.view.hit_slop, - crate::style::cursor_style(self.view.cursor), - ) - .into_any_element(), - None => element.into_any_element(), - }; - let element = match self.gpui_transform((scale_x, scale_y)) { - Some(matrix) => crate::transform::Transformed::new(element, matrix).into_any_element(), - None => element, - }; - let element = crate::filter::parse(&self.view.filter_json) - .into_iter() - .fold(element, |element, step| match step { - crate::filter::Step::Color(filter) => { - crate::filter::Filtered::new(element, filter).into_any_element() - } - step => crate::filter::Grouped::with_step(element, step).into_any_element(), - }); - if group_opacity.is_some() || blend != gpui::BlendMode::Normal || isolated { - crate::filter::Grouped::blended(element, group_opacity.unwrap_or(1.0), blend, isolated) - .into_any_element() - } else { - element - } - } -} - -fn rounded_ring( - width: f32, - height: f32, - offset: f32, - ring: f32, - argb: u32, - radii: [f32; 4], - scale: f32, -) -> gpui::Div { - let reach = (offset + ring) * scale; - let mut element = div() - .absolute() - .left(px(-reach)) - .top(px(-reach)) - .w(px(width + 2.0 * reach)) - .h(px(height + 2.0 * reach)) - .border(px(ring * scale)) - .border_color(style::color(argb)); - let corners = &mut element.style().corner_radii; - let outer = |radius: f32| { - if radius > 0.0 { - px(((radius + offset).max(0.0) + ring) * scale).into() - } else { - px(0.0).into() - } - }; - corners.top_left = Some(outer(radii[0])); - corners.top_right = Some(outer(radii[1])); - corners.bottom_right = Some(outer(radii[2])); - corners.bottom_left = Some(outer(radii[3])); - element -} - -fn rule_segments( - x: f32, - y: f32, - length: f32, - thickness: f32, - horizontal: bool, - argb: u32, - style: u8, -) -> Vec { - let mut rules = Vec::new(); - for (offset, painted) in rule_segment_spans(length, thickness, style) { - let (left, top, width, height) = if horizontal { - (x + offset, y, painted, thickness) - } else { - (x, y + offset, thickness, painted) - }; - rules.push( - div() - .absolute() - .left(px(left)) - .top(px(top)) - .w(px(width)) - .h(px(height)) - .bg(style::color(argb)), - ); - } - rules -} - -fn rule_segment_spans(length: f32, thickness: f32, style: u8) -> Vec<(f32, f32)> { - if !length.is_finite() || !thickness.is_finite() || length <= 0.0 || thickness <= 0.0 { - return Vec::new(); - } - let (segment, gap) = match style { - 1 => (thickness, thickness), - 2 => (thickness * 3.0, thickness * 2.0), - _ => (length, 0.0), - }; - let mut spans = Vec::new(); - let mut offset = 0.0; - while offset < length { - let painted = segment.min(length - offset); - spans.push((offset, painted)); - offset += painted + gap; - } - spans -} - -/// The node's side of a host component: it is created from -/// the registry index on its op, handed new props only when C++ sent a handle, -/// and never looks the component up by name. -#[cfg(test)] -mod host_component_node_tests { - use super::*; - use crate::host_component::{ - declare_host_component, register_component, EmitterHandle, HostArg, HostComponentOptions, - HostComponentSpec, HostContext, HostObject, PropsHandle, TEST_HANDLE, - }; - use gpui::AppContext as _; - use rn_gpui_sys::ffi::{MountKind, ParagraphFlat}; - use std::cell::RefCell; - - thread_local! { - static LOG: RefCell> = const { RefCell::new(Vec::new()) }; - } - - fn log() -> Vec { - LOG.with(|log| log.borrow().clone()) - } - - struct Fake; - - impl HostObject for Fake { - fn update(&mut self, _props: PropsHandle, changed: &[u64], _cx: HostContext) { - LOG.with(|log| log.borrow_mut().push(format!("update {changed:?}"))); - } - - fn render(&mut self, _window: &mut Window, _cx: HostContext) -> AnyElement { - gpui::IntoElement::into_any_element(gpui::div()) - } - - fn render_overlay(&mut self, _window: &mut Window, _cx: HostContext) -> Option { - None - } - - fn command(&mut self, index: u32, args: &[HostArg], _cx: HostContext) { - LOG.with(|log| log.borrow_mut().push(format!("command {index} {args:?}"))); - } - } - - struct FakeSpec; - - impl HostComponentSpec for FakeSpec { - const NAME: &'static str = "NodeTestFake"; - - fn create( - _props: PropsHandle, - _emitter: EmitterHandle, - mut cx: HostContext, - ) -> Box { - LOG.with(|log| log.borrow_mut().push("create".to_string())); - cx.set_intrinsic_size(7.0, 9.0); - Box::new(Fake) - } - } - - const REGISTERED: u32 = 960; - const UNREGISTERED: u32 = 961; - - fn declare() { - declare_host_component( - REGISTERED, - FakeSpec::NAME, - HostComponentOptions { - container: true, - ..Default::default() - }, - ); - register_component(FakeSpec); - declare_host_component( - UNREGISTERED, - "NodeTestUnregistered", - HostComponentOptions::default(), - ); - } - - fn op(kind: MountKind, index: i32) -> MountOp { - MountOp { - kind, - tag: 42, - parent_tag: -1, - index: 0, - component: "NodeTestFake".into(), - frame: RectF { - x: 0.0, - y: 0.0, - w: 10.0, - h: 10.0, - }, - props_changed: true, - view: rn_gpui_sys::ffi::ViewPropsFlat::default(), - extension_props_json: String::new(), - host_index: index, - host_props_handle: 0, - host_emitter_handle: 0, - host_changed: 0, - host_changed_more: Vec::new(), - has_paragraph: false, - paragraph: ParagraphFlat::default(), - layout_changed: false, - layout_patch: 0, - } - } - - fn queue() -> crate::store::HostReportQueue { - std::rc::Rc::new(crate::host_component::HostReports::default()) - } - - #[test] - fn a_node_creates_its_component_from_the_index_on_its_op() { - declare(); - LOG.with(|log| log.borrow_mut().clear()); - let mut create = op(MountKind::Create, REGISTERED as i32); - create.host_props_handle = TEST_HANDLE; - create.host_emitter_handle = TEST_HANDLE; - let reports = queue(); - let node = RNNodeView::from_op(&create, 1, reports.clone(), None); - assert!(node.host_component.is_some()); - assert!( - node.host_container, - "the declaration says it is a container" - ); - assert_eq!(log(), vec!["create".to_string()]); - assert_eq!(reports.take().len(), 1); - } - - #[test] - fn an_op_without_a_host_index_never_touches_the_registry() { - declare(); - let node = RNNodeView::from_op(&op(MountKind::Create, -1), 1, queue(), None); - assert!(node.host_component.is_none()); - assert!(!node.host_container); - } - - #[test] - fn a_declaration_nobody_registered_leaves_the_node_empty() { - declare(); - let mut create = op(MountKind::Create, UNREGISTERED as i32); - create.host_props_handle = TEST_HANDLE; - create.host_emitter_handle = TEST_HANDLE; - let node = RNNodeView::from_op(&create, 1, queue(), None); - assert!(node.host_component.is_none()); - } - - #[test] - fn an_update_reaches_the_component_only_when_c_plus_plus_sent_props() { - declare(); - LOG.with(|log| log.borrow_mut().clear()); - let mut create = op(MountKind::Create, REGISTERED as i32); - create.host_props_handle = TEST_HANDLE; - create.host_emitter_handle = TEST_HANDLE; - let mut node = RNNodeView::from_op(&create, 1, queue(), None); - - node.update_from_op(&op(MountKind::Update, REGISTERED as i32), None); - assert_eq!(log(), vec!["create".to_string()]); - - let mut update = op(MountKind::Update, REGISTERED as i32); - update.host_props_handle = TEST_HANDLE; - update.host_changed = 0b101; - update.host_changed_more = vec![0b1]; - node.update_from_op(&update, None); - assert_eq!( - log(), - vec!["create".to_string(), "update [5, 1]".to_string()] - ); - } - - struct AppProbe { - counter: Option>, - } - - impl HostObject for AppProbe { - fn update(&mut self, _props: PropsHandle, _changed: &[u64], mut cx: HostContext) { - LOG.with(|log| { - log.borrow_mut() - .push(format!("update app {}", cx.app().is_some())) - }); - } - - fn render(&mut self, _window: &mut Window, _cx: HostContext) -> AnyElement { - gpui::IntoElement::into_any_element(gpui::div()) - } - - fn render_overlay(&mut self, _window: &mut Window, _cx: HostContext) -> Option { - None - } - - fn command(&mut self, _index: u32, _args: &[HostArg], mut cx: HostContext) { - if cx.app().is_none() { - LOG.with(|log| log.borrow_mut().push("command without app".to_string())); - return; - } - let counter = self.counter.clone().expect("created with an app"); - let with_window = cx.window().is_some(); - let Some(app) = cx.app() else { - return; - }; - LOG.with(|log| { - log.borrow_mut() - .push(format!("command window {with_window}")) - }); - counter.update(app, |value, _| *value += 1); - let value = *counter.read(app); - LOG.with(|log| log.borrow_mut().push(format!("counter {value}"))); - } - } - - struct AppProbeSpec; - - impl HostComponentSpec for AppProbeSpec { - const NAME: &'static str = "NodeTestAppProbe"; - - fn create( - _props: PropsHandle, - _emitter: EmitterHandle, - mut cx: HostContext, - ) -> Box { - let counter = cx.app().map(|app| app.new(|_| 41u32)); - let window = cx.with_window(|_, _| ()).is_some(); - LOG.with(|log| { - log.borrow_mut() - .push(format!("create app {} window {window}", counter.is_some())) - }); - Box::new(AppProbe { counter }) - } - } - - const APP_PROBE: u32 = 962; - - #[gpui::test] - fn a_component_gets_the_app_to_create_an_entity_and_use_it_later( - cx: &mut gpui::TestAppContext, - ) { - declare_host_component( - APP_PROBE, - AppProbeSpec::NAME, - HostComponentOptions::default(), - ); - register_component(AppProbeSpec); - LOG.with(|log| log.borrow_mut().clear()); - let mut create = op(MountKind::Create, APP_PROBE as i32); - create.host_props_handle = TEST_HANDLE; - create.host_emitter_handle = TEST_HANDLE; - let node = cx.update(|app| { - let mut node = RNNodeView::from_op(&create, 1, queue(), Some(app)); - let mut update = op(MountKind::Update, APP_PROBE as i32); - update.host_props_handle = TEST_HANDLE; - update.host_changed = 1; - node.update_from_op(&update, Some(app)); - node.dispatch_host_command(0, &[], None, app); - node.dispatch_host_command(0, &[], None, app); - node - }); - assert_eq!( - log(), - vec![ - "create app true window false".to_string(), - "update app true".to_string(), - "command window false".to_string(), - "counter 42".to_string(), - "command window false".to_string(), - "counter 43".to_string(), - ] - ); - drop(node); - } - - #[gpui::test] - fn a_component_reaches_the_window_of_its_surface_and_the_window_of_a_command( - cx: &mut gpui::TestAppContext, - ) { - declare_host_component( - APP_PROBE, - AppProbeSpec::NAME, - HostComponentOptions::default(), - ); - register_component(AppProbeSpec); - let window = cx.add_window(|_, _| gpui::Empty); - crate::store::note_surface_window(1, Some(window.into())); - LOG.with(|log| log.borrow_mut().clear()); - let mut create = op(MountKind::Create, APP_PROBE as i32); - create.host_props_handle = TEST_HANDLE; - create.host_emitter_handle = TEST_HANDLE; - let mut node = cx.update(|app| RNNodeView::from_op(&create, 1, queue(), Some(app))); - cx.update(|app| { - window - .update(app, |_, window, app| { - node.dispatch_host_command(0, &[], Some(window), app); - }) - .unwrap(); - }); - crate::store::note_surface_window(1, None); - assert_eq!( - log(), - vec![ - "create app true window true".to_string(), - "command window true".to_string(), - "counter 42".to_string(), - ] - ); - } - - #[test] - fn without_an_app_the_component_gets_none() { - declare_host_component( - APP_PROBE, - AppProbeSpec::NAME, - HostComponentOptions::default(), - ); - register_component(AppProbeSpec); - LOG.with(|log| log.borrow_mut().clear()); - let mut create = op(MountKind::Create, APP_PROBE as i32); - create.host_props_handle = TEST_HANDLE; - create.host_emitter_handle = TEST_HANDLE; - let _node = RNNodeView::from_op(&create, 1, queue(), None); - assert_eq!(log(), vec!["create app false window false".to_string()]); - } -} - -#[cfg(test)] -mod border_segment_tests { - use super::rule_segment_spans; - - #[test] - fn solid_rule_is_one_segment() { - assert_eq!(rule_segment_spans(25.0, 3.0, 0), vec![(0.0, 25.0)]); - } - - #[test] - fn dotted_and_dashed_rules_clamp_the_last_segment() { - assert_eq!( - rule_segment_spans(10.0, 3.0, 1), - vec![(0.0, 3.0), (6.0, 3.0)] - ); - assert_eq!( - rule_segment_spans(20.0, 3.0, 2), - vec![(0.0, 9.0), (15.0, 5.0)] - ); - } - - #[test] - fn nonpositive_or_nonfinite_geometry_is_empty() { - assert!(rule_segment_spans(0.0, 2.0, 2).is_empty()); - assert!(rule_segment_spans(2.0, 0.0, 2).is_empty()); - assert!(rule_segment_spans(f32::INFINITY, 2.0, 2).is_empty()); - } -} - -const SCROLL_STATE_SYNC_DELAY: std::time::Duration = std::time::Duration::from_millis(100); - -fn scroll_payload( - offset: Point, - content: (f32, f32), - viewport: (f32, f32), -) -> serde_json::Value { - serde_json::json!({ - "contentOffset": {"x": offset.x, "y": offset.y}, - "contentSize": {"width": content.0, "height": content.1}, - "layoutMeasurement": {"width": viewport.0, "height": viewport.1}, - "zoomScale": 1 - }) -} - -/// How long an offset rests before `onScroll` hears it once more. -const SCROLL_REST_REPORT_DELAY: Duration = Duration::from_millis(150); - -/// Sends the offset in `position` once more when nothing has moved it, as -/// `generation` counts, for [`SCROLL_REST_REPORT_DELAY`]. A wheel or a -/// scrollbar stops without the momentum events a fling ends with, so an offset -/// a list ignored while it adjusted for items above it changing size would -/// otherwise stay its last. -fn report_rest( - cx: &App, - generation: Rc>, - position: Rc>>, - send: impl FnOnce(Point) + 'static, -) { - let expected = generation.get(); - let executor = cx.background_executor().clone(); - cx.foreground_executor() - .spawn(async move { - executor.timer(SCROLL_REST_REPORT_DELAY).await; - if generation.get() == expected { - send(position.get()); - } - }) - .detach(); -} - -impl RNNodeView { - /// The listeners this node's pointer area registers. Only a component's - /// input changes them from one render to the next, so for a node without a - /// component renderer they are built once and kept until what they depend - /// on changes. - fn pointer_handlers( - &mut self, - control_area: Option, - os_owns_press: bool, - cx: &mut Context, - ) -> Rc { - let cacheable = crate::extensions::component_renderer(&self.component).is_none(); - let key = PointerHandlersKey { - role: self.window_control_role(), - inherited_area: self.inherited.window_control_area, - pointer_events: self.view.pointer_events, - drags: control_area == Some(gpui::WindowControlArea::Drag), - os_owns_press, - }; - if let Some((cached, handlers)) = &self.pointer_handlers { - if cacheable && *cached == key { - return handlers.clone(); - } - } - if cacheable { - let shared = SHARED_POINTER_HANDLERS.with_borrow(|shared| { - shared - .iter() - .find(|(shared_key, _)| *shared_key == key) - .map(|(_, handlers)| handlers.clone()) - }); - if let Some(handlers) = shared { - self.pointer_handlers = Some((key, handlers.clone())); - return handlers; - } - } - let mut handlers = PointerHandlers::default(); - // A component renderer that asked for input gets it through the same - // handlers the View props use, so ordering with RN's touch handling and - // the scroll-container case stays as it was. - let input_spec = crate::extensions::component_renderer(&self.component).map(|renderer| { - let node = self.renderer_node(&*renderer, cx); - let spec = renderer.input(&node); - (spec, node) - }); - // A component that owns the press has its left-button hooks run before the - // ones that start a React Native touch, which would otherwise stop the - // press first: GPUI runs listeners in reverse order of registration. - let claims_press = input_spec.is_some() - && crate::extensions::component_renderer(&self.component) - .is_some_and(|renderer| renderer.claims_press(&self.component_node_shallow())); - let mut late_left_down: Vec> = - Vec::new(); - let mut late_left_up: Vec> = Vec::new(); - if let Some((spec, node)) = input_spec { - for button in [ - crate::events::Button::Left, - crate::events::Button::Middle, - crate::events::Button::Right, - crate::events::Button::Back, - crate::events::Button::Forward, - ] { - if !spec.mouse_buttons.contains(button) { - continue; - } - let down_node = cx.entity().downgrade(); - let down_component = node.clone(); - let handler: crate::pointer_area::PointerHandler = - Rc::new(move |_: &Node, event: &MouseDownEvent, window, cx| { - run_component_hook( - &down_node, - &down_component, - window, - cx, - event.position, - button, - event.click_count, - event.modifiers, - ComponentHook::Down, - ); - }); - match button { - crate::events::Button::Left if claims_press => late_left_down.push(handler), - crate::events::Button::Left => handlers.left_down.push(handler), - crate::events::Button::Middle => handlers.middle_down.push(handler), - crate::events::Button::Right => handlers.right_down.push(handler), - crate::events::Button::Back => handlers.back_down.push(handler), - crate::events::Button::Forward => handlers.forward_down.push(handler), - } - let up_node = cx.entity().downgrade(); - let up_component = node.clone(); - let handler: crate::pointer_area::PointerHandler = - Rc::new(move |_: &Node, event: &MouseUpEvent, window, cx| { - run_component_hook( - &up_node, - &up_component, - window, - cx, - event.position, - button, - event.click_count, - event.modifiers, - ComponentHook::Up, - ); - }); - match button { - crate::events::Button::Left if claims_press => late_left_up.push(handler), - crate::events::Button::Left => handlers.left_up.push(handler), - crate::events::Button::Middle => handlers.middle_up.push(handler), - crate::events::Button::Right => handlers.right_up.push(handler), - crate::events::Button::Back => handlers.back_up.push(handler), - crate::events::Button::Forward => handlers.forward_up.push(handler), - } - } - if spec.hover { - // The edge is decided here, on the entity, because the listener - // that reports the sample is rebuilt on every paint. - let hover_node = cx.entity().downgrade(); - let hover_component = node; - handlers - .hover - .push(Rc::new(move |_: &Node, hovered: bool, window, cx| { - let Some(entity) = hover_node.upgrade() else { - return; - }; - let component = entity.read(cx).component.clone(); - let Some(renderer) = crate::extensions::component_renderer(&component) - else { - return; - }; - let changed = entity.update(cx, |this, _| { - if this.hovered == hovered { - return false; - } - this.hovered = hovered; - true - }); - if !changed { - return; - } - let mut context = crate::extensions::input::InputContext { - node: &hover_component, - window, - cx, - captured: false, - }; - renderer.on_hover(&hover_component, hovered, &mut context); - })); - } - } - // `none` and `box-none` never take a press for themselves: the press falls - // through to what is behind them, or to the nearest ancestor that takes it, - // and a child of a `box-none` view still takes its own. - // The glyph inside a caption button is part of the button: the press has - // to reach the button's own hook, so it must not start a touch and stop - // there. Windows hands these presses to the OS instead. - let inside_caption_button = !cfg!(target_os = "windows") - && matches!(self.window_control_role(), WindowControlRole::Passive) - && matches!( - self.inherited.window_control_area, - Some( - gpui::WindowControlArea::Min - | gpui::WindowControlArea::Max - | gpui::WindowControlArea::Close - ) - ); - if !inside_caption_button - && !matches!( - self.view.pointer_events, - crate::events::POINTER_EVENTS_NONE | crate::events::POINTER_EVENTS_BOX_NONE - ) - { - handlers.left_down.push(Rc::new( - move |down_node: &Node, event: &MouseDownEvent, window, cx| { - // Ctrl + click is the macOS equivalent of a right click. It is a - // left press, so it must not also start a touch, or a `Pressable` - // would fire; the check happens before any touch dispatch. - if ctrl_click_context_menu(down_node, event, os_owns_press, window, cx) { - return; - } - // No touch either: the release never comes back once the OS - // has taken the press into its move loop. The ancestors this - // press bubbles to are told, so none of them starts one. - if os_owns_press { - crate::events::hand_press_to_window(); - return; - } - if crate::events::press_belongs_to_window() || crate::events::press_claimed() { - return; - } - let Some(node) = down_node.upgrade() else { - return; - }; - if node.read(cx).shares_pointer_with_native(cx) { - crate::events::mark_native_press(); - } - let (target, is_text_input, selectable_text) = { - let this = node.read(cx); - ( - crate::events::target(cx, this), - this.component == "TextInput", - crate::builtins::text_select::is_selectable(this), - ) - }; - if selectable_text { - node.update(cx, |this, cx| { - crate::builtins::text_select::begin( - this, - event.position, - event.click_count, - cx, - ); - }); - } else { - crate::builtins::text_select::clear_active(cx); - } - let Some(target) = target else { - return; - }; - if let Some(handle) = RNNodeView::press_focus_handle(&node, window, cx) { - window.focus(&handle, cx); - } - if is_text_input { - node.update(cx, |this, cx| { - if event.click_count >= 2 { - crate::builtins::textinput::input::select_all(this, window, cx); - } else { - crate::builtins::textinput::input::select_at_point( - this, - event.position, - false, - window, - cx, - ); - } - }); - } - crate::events::send( - window, - cx, - &target, - event.position, - crate::events::Phase::Start, - Some(crate::events::Button::Left), - modifier_state(event.modifiers), - ); - crate::drag_drop::press(cx, &target, event.position); - if node.read(cx).shares_pointer_with_native(cx) { - crate::events::claim_press(); - } else if !crate::events::native_press() { - cx.stop_propagation(); - } - }, - )); - // Every other button reports the DOM pointer events only, with no - // touch or responder involvement, so `Pressable` never fires for a - // middle or right click. The right button is only wired here when the - // view has no `onContextMenu`, since that handler owns the press - // otherwise and stopping there would hide the pointer event too. - handlers.middle_down.push(Rc::new( - move |middle_node: &Node, event: &MouseDownEvent, window, cx| { - dispatch_pointer_button( - &middle_node, - event, - crate::events::Button::Middle, - window, - cx, - ); - }, - )); - handlers.middle_up.push(Rc::new( - move |middle_up_node: &Node, event: &MouseUpEvent, window, cx| { - dispatch_pointer_release( - &middle_up_node, - event, - crate::events::Button::Middle, - window, - cx, - ); - }, - )); - handlers.right_up.push(Rc::new( - move |right_up_node: &Node, event: &MouseUpEvent, window, cx| { - dispatch_pointer_release( - &right_up_node, - event, - crate::events::Button::Right, - window, - cx, - ); - }, - )); - // Every node that takes pointer input handles the right button, whether - // or not it owns a context menu. One press must do both jobs: report - // `topPointerDown` for the innermost node, and open the nearest - // ancestor's menu. Splitting them across two nodes is what broke a - // right click on a `Text` inside a view with `onContextMenu` — the - // text's listener stopped the press before the parent's ran. - handlers.right_down.push(Rc::new( - move |right_node: &Node, event: &MouseDownEvent, window, cx| { - dispatch_right_press(&right_node, event, window, cx); - }, - )); - // Not `cx.listener`: a listener updates its entity every time it runs, and - // gpui-fast rebuilds any view that read an updated entity. - handlers.mouse_move.push(Rc::new( - move |move_node: &Node, event: &MouseMoveEvent, window, cx| { - let Some(node) = move_node.upgrade() else { - return; - }; - let (hit_target, selecting, selecting_text) = { - let this = node.read(cx); - ( - crate::events::target(cx, this), - this.component == "TextInput" - && this.input().selection_anchor.is_some(), - this.text_selection_anchor.is_some(), - ) - }; - if crate::drag_drop::tracking() { - crate::drag_drop::moved( - window, - cx, - hit_target.as_ref(), - event.position, - event.pressed_button.is_some(), - ); - cx.stop_propagation(); - return; - } - if crate::file_drop::active() { - crate::file_drop::over(window, cx, hit_target.as_ref(), event.position); - cx.stop_propagation(); - return; - } - if event.pressed_button.is_some() { - if selecting_text { - node.update(cx, |this, cx| { - crate::builtins::text_select::extend(this, event.position, cx); - }); - } - if selecting { - node.update(cx, |this, cx| { - crate::builtins::textinput::input::select_at_point( - this, - event.position, - true, - window, - cx, - ); - }); - } - // RN keeps the touch target fixed from mouse-down to - // release, including when the pointer leaves the view. - crate::events::move_pressed( - window, - cx, - hit_target.as_ref(), - event.position, - modifier_state(event.modifiers), - ); - } else { - crate::events::hover(window, cx, hit_target.as_ref(), event.position); - crate::events::move_hovered( - window, - cx, - hit_target.as_ref(), - event.position, - modifier_state(event.modifiers), - ); - } - let active_target = crate::events::active_touch_target(cx); - // A press that began over native content keeps its moves - // reaching the native elements (a text selection drag). - let native_press = crate::events::native_press() - || active_target.as_ref().is_some_and(|target| { - crate::store::store_from(cx) - .and_then(|store| store.read(cx).nodes.get(&target.tag).cloned()) - .is_some_and(|node| node.read(cx).shares_pointer_with_native(cx)) - }); - if (hit_target.is_some() || active_target.is_some()) - && !(native_press && event.pressed_button.is_some()) - { - cx.stop_propagation(); - } - }, - )); - handlers.left_up.push(Rc::new( - move |node: &Node, event: &MouseUpEvent, window, cx| { - // The release of a caption button is what the OS acts on. - if os_owns_press { - crate::events::hand_press_to_window(); - return; - } - if crate::events::press_belongs_to_window() || crate::events::press_claimed() { - return; - } - let Some(node) = node.upgrade() else { - return; - }; - if crate::drag_drop::tracking() { - let target = crate::events::target(cx, node.read(cx)); - if crate::drag_drop::released(window, cx, target.as_ref(), event.position) { - return; - } - } - if crate::file_drop::active() { - let target = crate::events::target(cx, node.read(cx)); - crate::file_drop::landing(target, event.position); - return; - } - let active_target = crate::events::active_touch_target(cx); - if let Some(target) = active_target.as_ref() { - crate::events::send( - window, - cx, - target, - event.position, - crate::events::Phase::End, - Some(crate::events::Button::Left), - modifier_state(event.modifiers), - ); - } - let is_touch_target = { - let this = node.read(cx); - crate::events::target(cx, this).is_some() - }; - if active_target.is_some() || is_touch_target { - if node.read(cx).in_host_container(cx) { - crate::events::claim_press(); - } else if !crate::events::native_press() { - cx.stop_propagation(); - } - } - }, - )); - } - // Registered after every other press handler, which GPUI runs in reverse - // order: this one has to see the press before a touch or a context menu - // consumes it. - // Anywhere in a drag area — the region itself, or a node inside it that - // does not take the press — moves the window, and a double click zooms. - // macOS and Linux do not consult the hit-test, so the move starts here. - // Windows moves the window itself from the `HTCAPTION` press. - if control_area == Some(gpui::WindowControlArea::Drag) && !os_owns_press { - handlers.left_down.push(Rc::new( - move |_: &Node, event: &MouseDownEvent, window, cx| { - if event.click_count >= 2 { - window.titlebar_double_click(); - } else { - window.start_window_move(); - } - cx.stop_propagation(); - }, - )); - } - handlers.left_down.extend(late_left_down); - handlers.left_up.extend(late_left_up); - // A child of a scrolling container moves with its content, so a pointer area - // here would drift off the viewport. A node that claims a window-control - // area has the same problem for a different reason: the platform asks - // which element is under the pointer, and an overlay child sits in front - // of its own parent, so the area would never be consulted and the window - // could not be dragged by the node that asked to be draggable. - if os_owns_press { - // What is left is a component's own hook — a caption button reporting - // its pressed state — which may stop propagation; the press still has - // to reach the OS, which performs the button's action. - handlers.left_down = handlers - .left_down - .into_iter() - .map( - |handler| -> crate::pointer_area::PointerHandler { - Rc::new(move |node: &Node, event: &MouseDownEvent, window, cx| { - handler(node, event, window, cx); - cx.propagate(); - }) - }, - ) - .collect(); - handlers.left_up = handlers - .left_up - .into_iter() - .map( - |handler| -> crate::pointer_area::PointerHandler { - Rc::new(move |node: &Node, event: &MouseUpEvent, window, cx| { - handler(node, event, window, cx); - cx.propagate(); - }) - }, - ) - .collect(); - } - let handlers = Rc::new(handlers); - if cacheable { - SHARED_POINTER_HANDLERS.with_borrow_mut(|shared| shared.push((key, handlers.clone()))); - self.pointer_handlers = Some((key, handlers.clone())); - } - handlers - } - - /// The intrinsic size Fabric last reported, if the component measures. - pub fn intrinsic_size(&self) -> Option<(f32, f32)> { - self.intrinsic_size - } - - /// Records the size the store just delivered, for the test driver and for - /// diagnostics. Yoga reads the shadow node's state, not this. - pub(crate) fn set_intrinsic_size(&mut self, width: f32, height: f32) { - self.intrinsic_size = Some((width, height)); - } - - /// A context whose reports go to the store's queue. - pub(crate) fn host_reports(&self) -> crate::store::HostReportQueue { - self.host_reports.clone() - } - - fn host_context(&self) -> crate::host_component::HostContext { - crate::host_component::HostContext::queued(self.tag, self.host_reports.clone()) - .on_surface(self.surface_id) - } - - /// The same, with the store handle a command can act through. - fn host_context_with_handle( - &self, - handle: crate::extensions::StoreHandle, - ) -> crate::host_component::HostContext { - crate::host_component::HostContext::queued_with_handle( - self.tag, - self.host_reports.clone(), - handle, - ) - .on_surface(self.surface_id) - } - - pub fn scroll_offset(&self) -> Point { - self.scroll_parts - .as_ref() - .map_or_else(Point::default, |parts| parts.position.get()) - } - - /// `maintainVisibleContentPosition`: the first index kept in place, and the - /// distance from the start within which new items scroll into view. - pub(crate) fn maintain_visible(&self) -> Option<(usize, Option)> { - self.scroll.as_ref()?; - let min = self.extension_props.get("maintainMinIndex")?.as_i64()?; - let threshold = self - .extension_props - .get("maintainAutoscrollThreshold") - .and_then(serde_json::Value::as_f64) - .map(|value| value as f32); - Some((min.max(0) as usize, threshold)) - } - - /// The tag of the first item at or after `min_index` that reaches into the - /// viewport, with its start along the scroll axis. - pub(crate) fn visible_anchor(&self, min_index: usize, cx: &App) -> Option<(i32, f32)> { - let horizontal = self.scroll.as_ref()?.horizontal; - let offset = self.scroll_offset(); - let start = if horizontal { offset.x } else { offset.y }; - let (_, content) = self.children.first()?; - let content = content.read(cx); - content - .children - .iter() - .skip(min_index) - .find_map(|(tag, child)| { - let frame = child.read(cx).frame; - let (from, length) = if horizontal { - (frame.x, frame.w) - } else { - (frame.y, frame.h) - }; - (from + length > start).then_some((*tag, from)) - }) - } - - /// The start along the scroll axis of one of this node's items. - pub(crate) fn item_start(&self, tag: i32, cx: &App) -> Option { - let horizontal = self.scroll.as_ref()?.horizontal; - let (_, content) = self.children.first()?; - let content = content.read(cx); - let (_, child) = content.children.iter().find(|(child, _)| *child == tag)?; - let frame = child.read(cx).frame; - Some(if horizontal { frame.x } else { frame.y }) - } - - /// Moves the offset by what an item above the viewport's start moved. - pub(crate) fn keep_anchor( - &mut self, - anchor: i32, - before: f32, - threshold: Option, - host: &crate::host::Host, - cx: &mut Context, - ) { - let Some(after) = self.item_start(anchor, cx) else { - return; - }; - let delta = after - before; - if delta.abs() < 0.5 { - return; - } - let horizontal = self.scroll.as_ref().is_some_and(|scroll| scroll.horizontal); - let current = self.scroll_offset(); - let along = if horizontal { current.x } else { current.y }; - let max = self.max_scroll(); - let max = if horizontal { max.0 } else { max.1 }; - let next = if delta > 0.0 && threshold.is_some_and(|limit| along <= limit) { - 0.0 - } else { - (along + delta).clamp(0.0, max) - }; - let target = if horizontal { - point(next, current.y) - } else { - point(current.x, next) - }; - self.set_scroll_offset(target, host, cx); - } - - /// The largest offset the scroll content allows. - fn max_scroll(&self) -> (f32, f32) { - let content = self.scroll.as_ref().map_or((0.0, 0.0), |s| s.content_size); - ( - (content.0 - self.frame.w).max(0.0), - (content.1 - self.frame.h).max(0.0), - ) - } - - /// Whether this scroll view's thumb is shown right now, for the test driver. - pub(crate) fn scroll_indicator_shown(&self, cx: &App) -> bool { - self.scroll_parts - .as_ref() - .and_then(|parts| parts.indicator.as_ref()) - .is_some_and(|indicator| indicator.read(cx).shown()) - } - - /// Runs `scrollTo`, `scrollToEnd` and `flashScrollIndicators`. - pub(crate) fn scroll_command( - &mut self, - name: &str, - args: &serde_json::Value, - cx: &mut Context, - ) -> bool { - let Some(scroll) = self.scroll.as_ref() else { - return false; - }; - let number = |index: usize| args.get(index).and_then(serde_json::Value::as_f64); - let flag = |index: usize| { - args.get(index) - .and_then(serde_json::Value::as_bool) - .unwrap_or(true) - }; - let current = self.scroll_offset(); - let max = self.max_scroll(); - let (target, animated) = match name { - "scrollTo" => ( - point( - number(0).map_or(current.x, |x| x as f32), - number(1).map_or(current.y, |y| y as f32), - ), - flag(2), - ), - "scrollToEnd" => ( - if scroll.horizontal { - point(max.0, current.y) - } else { - point(current.x, max.1) - }, - flag(0), - ), - "flashScrollIndicators" => { - if let Some(indicator) = self.parts_mut().indicator.clone() { - indicator.update(cx, |indicator, cx| indicator.flash(cx)); - } - return true; - } - _ => return false, - }; - let target = point(target.x.clamp(0.0, max.0), target.y.clamp(0.0, max.1)); - let Some(host) = crate::store::store_from(cx).map(|store| store.read(cx).host.clone()) - else { - return false; - }; - self.scroll_to(target, animated, host, cx); - true - } - - /// Moves the scroll offset the way `scrollTo` does: reported through - /// `onScroll`, and handed to Fabric once it settles. - pub(crate) fn scroll_to( - &mut self, - target: Point, - animated: bool, - host: crate::host::Host, - cx: &mut Context, - ) { - const STEPS: u32 = 10; - let generation = { - let mut gesture = self.parts_mut().gesture.borrow_mut(); - gesture.generation += 1; - gesture.generation - }; - let from = self.parts_mut().position.get(); - if !animated || (from.x - target.x).abs() + (from.y - target.y).abs() < 0.5 { - self.parts_mut().programmatic.set(true); - self.set_scroll_offset(target, &host, cx); - return; - } - let programmatic = self.parts_mut().programmatic.clone(); - let gesture = self.parts_mut().gesture.clone(); - cx.spawn(async move |this, cx| { - for step in 1..=STEPS { - cx.background_executor() - .timer(std::time::Duration::from_millis(15)) - .await; - if gesture.borrow().generation != generation { - return; - } - let t = step as f32 / STEPS as f32; - let eased = 1.0 - (1.0 - t) * (1.0 - t); - let next = point( - from.x + (target.x - from.x) * eased, - from.y + (target.y - from.y) * eased, - ); - programmatic.set(true); - if this - .update(cx, |node, cx| node.set_scroll_offset(next, &host, cx)) - .is_err() - { - return; - } - } - }) - .detach(); - } - - fn set_scroll_offset( - &mut self, - offset: Point, - host: &crate::host::Host, - cx: &mut Context, - ) { - self.parts_mut().position.set(offset); - self.parts_mut().handle_stale = true; - cx.notify(); - let host = host.clone(); - let content = self.scroll.as_ref().map_or((0.0, 0.0), |s| s.content_size); - if let Some(event) = self.scroll.as_ref().and_then(|s| s.event.as_ref()) { - host.dispatch_event( - self.tag, - event, - &serde_json::json!({ - "contentOffset": {"x": offset.x, "y": offset.y}, - "contentSize": {"width": content.0, "height": content.1}, - "layoutMeasurement": {"width": self.frame.w, "height": self.frame.h}, - "zoomScale": 1 - }), - ); - } - let generation = self.parts_mut().sync_generation.get() + 1; - self.parts_mut().sync_generation.set(generation); - self.parts_mut().sync_pending.set(true); - if let Some(event) = self.scroll.as_ref().and_then(|s| s.event.clone()) { - let (host, tag, viewport) = (host.clone(), self.tag, (self.frame.w, self.frame.h)); - report_rest( - cx, - self.parts_mut().sync_generation.clone(), - self.parts_mut().position.clone(), - move |offset| { - host.dispatch_event(tag, &event, &scroll_payload(offset, content, viewport)) - }, - ); - } - let (tag, position, sync_generation, pending) = ( - self.tag, - self.parts_mut().position.clone(), - self.parts_mut().sync_generation.clone(), - self.parts_mut().sync_pending.clone(), - ); - cx.spawn(async move |_, cx| { - cx.background_executor() - .timer(SCROLL_STATE_SYNC_DELAY) - .await; - if sync_generation.get() == generation && pending.replace(false) { - let offset = position.get(); - host.set_scroll_offset(tag, offset.x, offset.y); - } - }) - .detach(); - } - - /// Runs a Fabric command on this node's host component. - pub(crate) fn dispatch_host_command( - &mut self, - command: u32, - args: &[crate::host_component::HostArg], - window: Option<&mut Window>, - cx: &mut gpui::App, - ) { - if self.host_component.is_none() { - log::debug!( - "[host-component] command {command} for tag {} with no component", - self.tag - ); - return; - } - let handle = crate::store::store_from(cx) - .map(|store| crate::extensions::StoreHandle::new(store.downgrade())); - let host = match handle { - Some(handle) => self.host_context_with_handle(handle), - None => self.host_context(), - }; - if let Some(component) = self.host_component.as_mut() { - let (host, _scope) = host.enter(&mut *cx); - let (host, _window_scope) = match window { - Some(window) => { - let (host, scope) = host.enter_window(window); - (host, Some(scope)) - } - None => (host, None), - }; - component.command(command, args, host); - } - if !self.host_reports.is_empty() { - if let Some(store) = crate::store::store_from(cx) { - cx.defer(move |cx| { - store.update(cx, |store, cx| store.flush_host_reports(cx)); - }); - } - } - } - - /// How this node scrolls its content, by name, if it scrolls. - pub(crate) fn scroll_strategy_name(&self) -> Option<&'static str> { - self.scroll.as_ref()?; - Some( - match crate::scroll_layers::scroll_strategy( - self.subtree_renders_native_surface() || self.subtree_forms_effect_group(), - ) { - crate::scroll_layers::ScrollStrategy::GpuiLayer => "GpuiLayer", - crate::scroll_layers::ScrollStrategy::ManualOffset => "ManualOffset", - }, - ) - } - - pub(crate) fn extension_props(&self) -> &serde_json::Value { - &self.extension_props - } - - /// Whether `json` is the extension props this node was last given. - pub(crate) fn has_extension_props_json(&self, json: &str) -> bool { - self.extension_props_hash == json_hash(json) - } - - /// The window-control area a press on this node lands in, if any. - /// - /// The node's own area when it claims one. Otherwise, a node that does not - /// take the press itself answers for the area around it: the platform asks - /// for the frontmost element under the pointer, and every node paints in - /// front of its parent, so a title bar's spacer, its title text, or the glyph - /// inside a caption button would otherwise answer "client" over the very - /// area that contains it — no drag, no double-click to maximize, and on - /// Windows no caption button either, since the OS performs those actions - /// from the hit-test. A node that does take the press (a `Pressable`, a text - /// input, a scroll view) stays client, so a button inside a title bar is - /// still a button, and so is everything inside it. - fn window_control_area(&self, _cx: &gpui::App) -> Option { - match self.window_control_role() { - WindowControlRole::Claims(area) => Some(area), - WindowControlRole::TakesPress => None, - // Inherited by the store's pass rather than walked here: this runs - // while rendering, when an ancestor may be the entity being updated, - // and reading it then panics. - WindowControlRole::Passive => self.inherited.window_control_area, - } - } - - /// What this node does with a press, as far as window controls are concerned. - pub(crate) fn window_control_role(&self) -> WindowControlRole { - if let Some(area) = self.own_window_control_area() { - WindowControlRole::Claims(area) - } else if self.takes_own_press() { - WindowControlRole::TakesPress - } else { - WindowControlRole::Passive - } - } - - /// Whether a press on this node belongs to it rather than to a window-control - /// area around it. - /// - /// `box-none` never takes a press for itself. Otherwise a node owns it when - /// it can act on it: focusable (what `Pressable` sets), a tap or context-menu - /// listener, a scroll view, or a component that asked for mouse input. - /// `accessibilityRespondsToUserInteraction` is not a signal: Fabric defaults - /// it to true on every view, so it would make all of them take the press. - fn takes_own_press(&self) -> bool { - if matches!( - self.view.pointer_events, - crate::events::POINTER_EVENTS_BOX_NONE | crate::events::POINTER_EVENTS_NONE - ) { - return false; - } - if self.focusable - || self.view.accessibility_has_tap_listener - || self.view.on_context_menu - || self.scroll.is_some() - { - return true; - } - crate::extensions::component_renderer(&self.component).is_some_and(|renderer| { - let spec = renderer.input(&self.component_node_shallow()); - spec.hover || spec.mouse_buttons != crate::extensions::input::ButtonSet::NONE - }) - } - - /// The area this node claims for itself: a caption button's, or a drag - /// region's. - /// - /// A component's `window_control()` hook is the only way to claim a caption - /// button now that `desktopWindowControl` is gone. `desktopDragRegion` still - /// marks a drag area, and a component that claimed a button overrides it so a - /// button inside a title bar acts as a button and does not drag the window. - fn own_window_control_area(&self) -> Option { - let claimed = crate::extensions::component_renderer(&self.component) - .and_then(|renderer| renderer.window_control(&self.component_node_shallow())); - match claimed { - Some(crate::extensions::input::WindowControl::Minimize) => { - Some(gpui::WindowControlArea::Min) - } - Some(crate::extensions::input::WindowControl::Maximize) => { - Some(gpui::WindowControlArea::Max) - } - Some(crate::extensions::input::WindowControl::Close) => { - Some(gpui::WindowControlArea::Close) - } - Some(crate::extensions::input::WindowControl::Drag) => { - Some(gpui::WindowControlArea::Drag) - } - None if self.view.desktop_drag_region => Some(gpui::WindowControlArea::Drag), - None => None, - } - } - - pub(crate) fn component_node_shallow(&self) -> crate::extensions::ComponentNode { - crate::extensions::ComponentNode { - component: self.component.to_string(), - tag: self.tag, - frame: self.frame, - scale: (self.inherited.scale.0.abs(), self.inherited.scale.1.abs()), - props: self.extension_props.clone(), - parent: self.parent_tag_cached(), - children: Vec::new(), - } - } - - pub(crate) fn child_tags(&self) -> Vec { - self.children.iter().map(|(tag, _)| *tag).collect() - } - - /// What a `TreeView` keeps about this node, copied so the tree never reads - /// an entity a hook may be updating. - pub(crate) fn snapshot(&self) -> crate::extensions::NodeSnapshot { - #[cfg(test)] - SNAPSHOT_COUNT.with(|count| count.set(count.get() + 1)); - self.snapshot_inner() - } - - fn snapshot_inner(&self) -> crate::extensions::NodeSnapshot { - crate::extensions::NodeSnapshot { - component: self.component.clone(), - tag: self.tag, - frame: self.frame, - scale: (self.inherited.scale.0.abs(), self.inherited.scale.1.abs()), - props: self.extension_props.clone(), - parent: self.parent_tag_cached(), - children: self.child_tags(), - mask_children: self.mask_children, - surface_id: self.surface_id, - transition: self.transition_state(), - } - } - - /// The node handed to `renderer`'s hooks: with its subtree only when the - /// renderer reads it. - pub(crate) fn renderer_node( - &self, - renderer: &dyn crate::extensions::ComponentRenderer, - cx: &App, - ) -> crate::extensions::ComponentNode { - if renderer.reads_children() { - self.component_node(cx) - } else { - self.component_node_shallow() - } - } - - pub(crate) fn component_node(&self, cx: &App) -> crate::extensions::ComponentNode { - crate::extensions::ComponentNode { - component: self.component.to_string(), - tag: self.tag, - frame: self.frame, - scale: (self.inherited.scale.0.abs(), self.inherited.scale.1.abs()), - props: self.extension_props.clone(), - parent: self.parent_tag_cached(), - children: self - .children - .iter() - .map(|(_, child)| child.read(cx).component_node(cx)) - .collect(), - } - } - - pub(crate) fn parent_tag_cached(&self) -> Option { - self.parent_tag_cache.get() - } -} - -/// The `backgroundImage` of a node, drawn for one box size. -struct GradientCache { - json: String, - size: (u32, u32), - image: Option>, -} - -/// The longest side, in pixels, a gradient is drawn at before the renderer -/// scales it up to the box. -const GRADIENT_RASTER_LIMIT: u32 = 512; - -/// What a scroll view keeps besides its spec. -struct ScrollParts { - /// Outside the entity so a scroll can move it without updating this view: - /// gpui-fast rebuilds every view that read an updated entity. - position: Rc>>, - indicator: Option>, - programmatic: Rc>, - /// The settings of the `ScrollBar` inside this scroll view and the tag its - /// events go out on, handed over by that node when it renders. - scrollbar: crate::scroll_indicator::ScrollbarSpec, - scrollbar_tag: Option, - scrollbar_release: Option<(gpui::EntityId, Subscription)>, - sync_generation: Rc>, - /// Whether Fabric's copy of the offset is behind the node's own. - sync_pending: Rc>, - /// When the last scroll event went out, and whether one is waiting for the - /// throttle to pass. - emit: Rc, - handle: gpui::ScrollHandle, - handle_stale: bool, - gesture: Rc>, -} - -impl ScrollParts { - fn at(position: Point) -> Self { - Self { - position: Rc::new(Cell::new(position)), - indicator: None, - programmatic: Rc::new(Cell::new(false)), - scrollbar: crate::scroll_indicator::ScrollbarSpec::default(), - scrollbar_tag: None, - scrollbar_release: None, - sync_generation: Rc::new(Cell::new(0)), - sync_pending: Rc::new(Cell::new(false)), - emit: Rc::default(), - handle: gpui::ScrollHandle::new(), - handle_stale: true, - gesture: Rc::default(), - } - } -} - -impl RNNodeView { - /// This node's scroll state, made at offset zero the first time a node - /// that was not a scroll view needs it. - fn parts_mut(&mut self) -> &mut ScrollParts { - self.scroll_parts - .get_or_insert_with(|| Box::new(ScrollParts::at(Point::default()))) - } -} - -/// What the pointer is doing to a scroll view, so drag and momentum can be -/// reported. A trackpad sends `Started`, `Moved` and `Ended` while the fingers -/// are down; the momentum that follows arrives as more `Moved` events with no -/// `Started`. A mouse wheel sends `Moved` only. -#[derive(Default)] -pub(crate) struct ScrollGesture { - dragging: bool, - after_drag: bool, - momentum: bool, - wheel: bool, - generation: u64, - drag_start: Option, - /// Recent touchpad deltas along the scroll axis, for the speed of a flick. - samples: Vec<(std::time::Instant, f32)>, -} - -/// What `scrollEventThrottle` needs to remember between scroll events. -#[derive(Default)] -pub(crate) struct ScrollEmit { - last: Cell>, - waiting: Cell, -} - -/// More than a frame between events is a throttle; a frame or less is not. -const FRAME: std::time::Duration = std::time::Duration::from_millis(17); - -/// How long without a wheel event before the scroll counts as over. -const SCROLL_IDLE: std::time::Duration = std::time::Duration::from_millis(120); - -/// How long without a touchpad event before a flick counts as lifted. -#[cfg(not(target_os = "macos"))] -const FLICK_IDLE: std::time::Duration = std::time::Duration::from_millis(40); - -struct Scroller { - tag: i32, - position: Rc>>, - handle: gpui::ScrollHandle, - sync_generation: Rc>, - sync_pending: Rc>, - emit: Rc, - event_throttle: std::time::Duration, - content_size: (f32, f32), - event: Option, - viewport: (f32, f32), - scale: (f32, f32), - horizontal: bool, - snap: Option, - gesture: Rc>, - deceleration: f32, - /// Set when no element tracks `handle`, whose own maximum is then unmeasured. - max_offset: Option>, -} - -impl Scroller { - fn payload(&self) -> serde_json::Value { - let offset = self.position.get(); - serde_json::json!({ - "contentOffset": {"x": offset.x, "y": offset.y}, - "contentSize": {"width": self.content_size.0, "height": self.content_size.1}, - "layoutMeasurement": {"width": self.viewport.0, "height": self.viewport.1}, - "velocity": {"x": 0, "y": 0}, - "zoomScale": 1 - }) - } - - fn emit(&self, event: &str, cx: &App) { - if let Some(store) = cx.try_global::() { - store - .0 - .read(cx) - .host - .dispatch_event(self.tag, event, &self.payload()); - } - } - - /// The wheel's movement along this scroll view's axis in points. A - /// horizontal one also takes a vertical wheel while shift is held, as a - /// browser does. - fn wheel_along(&self, event: &gpui::ScrollEvent) -> f32 { - let delta = event.delta.pixel_delta(px(20.)); - if !self.horizontal { - f32::from(delta.y) - } else if f32::from(delta.x) == 0.0 && event.modifiers.shift { - f32::from(delta.y) - } else { - f32::from(delta.x) - } - } - - fn main_offset(&self) -> f32 { - let offset = self.position.get(); - if self.horizontal { - offset.x - } else { - offset.y - } - } - - /// Reports the drag and momentum a wheel event is part of, and snaps once - /// the scroll has come to rest. - fn on_wheel(self: &Rc, event: &gpui::ScrollEvent, window: &mut Window, cx: &mut App) { - let along = self.wheel_along(event); - if self.horizontal && event.modifiers.shift { - let delta = event.delta.pixel_delta(px(20.)); - if f32::from(delta.x) == 0.0 && f32::from(delta.y) != 0.0 { - let max = self.handle.max_offset(); - let mut offset = self.handle.offset(); - offset.x = (offset.x + delta.y).clamp(-max.x, px(0.0)); - self.handle.set_offset(offset); - } - } - let generation = { - let mut gesture = self.gesture.borrow_mut(); - gesture.generation += 1; - match event.touch_phase { - gpui::TouchPhase::Started => { - if gesture.momentum { - gesture.momentum = false; - self.emit("topMomentumScrollEnd", cx); - } - gesture.dragging = true; - gesture.after_drag = false; - gesture.wheel = false; - gesture.drag_start = Some(self.main_offset()); - self.emit("topScrollBeginDrag", cx); - } - gpui::TouchPhase::Moved => { - if gesture.dragging { - } else if gesture.after_drag { - if !gesture.momentum { - gesture.momentum = true; - self.emit("topMomentumScrollBegin", cx); - } - } else { - gesture.wheel = true; - if matches!(event.delta, gpui::ScrollDelta::Pixels(_)) { - crate::scroll_momentum::push_sample( - &mut gesture.samples, - std::time::Instant::now(), - along, - ); - } - } - } - _ => { - if gesture.dragging { - gesture.dragging = false; - gesture.after_drag = true; - self.emit("topScrollEndDrag", cx); - } - } - } - gesture.generation - }; - let handle = window.window_handle(); - // macOS sends its own momentum. Elsewhere a flick ends when the - // touchpad goes quiet, and the scroll view carries it on. - #[cfg(not(target_os = "macos"))] - { - let scroller = self.clone(); - cx.spawn(async move |cx| { - cx.background_executor().timer(FLICK_IDLE).await; - let _ = cx.update_window(handle, |_, window, cx| { - scroller.carry_on(generation, window, cx) - }); - }) - .detach(); - } - let scroller = self.clone(); - cx.spawn(async move |cx| { - cx.background_executor().timer(SCROLL_IDLE).await; - let _ = cx.update_window(handle, |_, window, cx| { - scroller.settle(generation, window, cx) - }); - }) - .detach(); - } - - /// The touchpad went quiet after a flick: keeps the content moving at the - /// speed it had, slowing at the scroll view's `decelerationRate`. - #[cfg(not(target_os = "macos"))] - fn carry_on(self: &Rc, generation: u64, window: &mut Window, cx: &mut App) { - let speed = { - let mut gesture = self.gesture.borrow_mut(); - if gesture.generation != generation || gesture.dragging || !gesture.wheel { - return; - } - let samples = std::mem::take(&mut gesture.samples); - let Some(speed) = crate::scroll_momentum::flick_speed(&samples) else { - return; - }; - gesture.momentum = true; - speed - }; - self.emit("topMomentumScrollBegin", cx); - let handle = window.window_handle(); - let scroller = self.clone(); - cx.spawn(async move |cx| { - const TICK: u64 = 16; - let mut speed = speed; - loop { - cx.background_executor() - .timer(std::time::Duration::from_millis(TICK)) - .await; - let (distance, next) = - crate::scroll_momentum::step(speed, scroller.deceleration, TICK as f32); - speed = next; - let carried = cx - .update_window(handle, |_, window, cx| { - // A wheel event since means the user took over. - if scroller.gesture.borrow().generation != generation { - return false; - } - let moved = scroller.shift_by(distance); - if moved { - scroller.sync(window, cx); - } - moved && !crate::scroll_momentum::stopped(speed) - }) - .unwrap_or(false); - if !carried { - break; - } - } - let _ = cx.update_window(handle, |_, window, cx| { - scroller.settle(generation, window, cx) - }); - }) - .detach(); - } - - /// Moves the content `distance` along the scroll axis, in the direction - /// of the wheel deltas, and says whether it went anywhere. - #[cfg(not(target_os = "macos"))] - fn shift_by(&self, distance: f32) -> bool { - let current = self.handle.offset(); - let max = self.handle.max_offset(); - let mut next = current; - if self.horizontal { - next.x = (current.x + px(distance)).clamp(-max.x, px(0.0)); - } else { - next.y = (current.y + px(distance)).clamp(-max.y, px(0.0)); - } - if next == current { - return false; - } - self.handle.set_offset(next); - true - } - - /// The scroll went quiet: end any momentum, then snap. - fn settle(self: &Rc, generation: u64, window: &mut Window, cx: &mut App) { - let (moved_by_wheel, drag_start) = { - let mut gesture = self.gesture.borrow_mut(); - if gesture.generation != generation || gesture.dragging { - return; - } - if gesture.momentum { - gesture.momentum = false; - self.emit("topMomentumScrollEnd", cx); - if let Some(store) = cx.try_global::() { - store.0.read(cx).frame_hook.arm(window); - } - } - let result = (gesture.wheel, gesture.drag_start.take()); - gesture.after_drag = false; - gesture.wheel = false; - result - }; - let _ = moved_by_wheel; - let Some(snap) = self.snap.as_ref() else { - return; - }; - let (viewport, content) = if self.horizontal { - (self.viewport.0, self.content_size.0) - } else { - (self.viewport.1, self.content_size.1) - }; - let from = self.main_offset(); - let target = snap.target(from, drag_start, viewport, content); - if (target - from).abs() < 0.5 { - return; - } - self.animate_to(from, target, window, cx); - } - - /// Eases the offset from `from` to `to` over a short time, reporting each - /// step as a scroll. - fn animate_to(self: &Rc, from: f32, to: f32, window: &mut Window, cx: &mut App) { - const STEPS: u32 = 10; - let handle = window.window_handle(); - let scroller = self.clone(); - let generation = self.gesture.borrow().generation; - cx.spawn(async move |cx| { - for step in 1..=STEPS { - cx.background_executor() - .timer(std::time::Duration::from_millis(15)) - .await; - if scroller.gesture.borrow().generation != generation { - return; - } - let t = step as f32 / STEPS as f32; - let eased = 1.0 - (1.0 - t) * (1.0 - t); - let value = from + (to - from) * eased; - let _ = cx.update_window(handle, |_, window, cx| { - let current = scroller.handle.offset(); - let next = if scroller.horizontal { - point(px(-value * scroller.scale.0), current.y) - } else { - point(current.x, px(-value * scroller.scale.1)) - }; - scroller.handle.set_offset(next); - scroller.sync(window, cx); - }); - } - }) - .detach(); - } - - fn sync(&self, window: &mut Window, cx: &mut App) { - // The handle only clamps while painting, so a wheel event past the end - // leaves an offset beyond the content until the next frame. - let max = self.max_offset.unwrap_or_else(|| self.handle.max_offset()); - let scrolled = self.handle.offset(); - let scrolled = point( - scrolled.x.clamp(-max.x, px(0.0)), - scrolled.y.clamp(-max.y, px(0.0)), - ); - let offset = point( - -f32::from(scrolled.x) / self.scale.0.max(f32::EPSILON), - -f32::from(scrolled.y) / self.scale.1.max(f32::EPSILON), - ); - let old = self.position.get(); - if (offset.x - old.x).abs() < 0.01 && (offset.y - old.y).abs() < 0.01 { - return; - } - self.position.set(offset); - let Some(store) = cx.try_global::() else { - return; - }; - let (host, frame_hook) = { - let store = store.0.read(cx); - (store.host.clone(), store.frame_hook.clone()) - }; - let payload = serde_json::json!({ - "contentOffset": {"x": offset.x, "y": offset.y}, - "contentSize": {"width": self.content_size.0, "height": self.content_size.1}, - "layoutMeasurement": {"width": self.viewport.0, "height": self.viewport.1}, - "zoomScale": 1 - }); - if let Some(event) = &self.event { - let since = self.emit.last.get().map(|at| at.elapsed()); - match since { - Some(since) if self.event_throttle > FRAME && since < self.event_throttle => { - // Too soon: one event carrying the offset it has then - // goes out when the throttle has passed. - if !self.emit.waiting.replace(true) { - let (emit, position, host, event, tag) = ( - self.emit.clone(), - self.position.clone(), - host.clone(), - event.clone(), - self.tag, - ); - let (content, viewport) = (self.content_size, self.viewport); - let wait = self.event_throttle - since; - let sent_before = self.emit.last.get(); - cx.spawn(async move |cx| { - cx.background_executor().timer(wait).await; - emit.waiting.set(false); - // A scroll that came once the throttle had passed - // but before this ran has already sent the offset - // in this slot: a second would break the throttle. - if emit.last.get() != sent_before { - return; - } - emit.last.set(Some(std::time::Instant::now())); - let offset = position.get(); - host.dispatch_event( - tag, - &event, - &serde_json::json!({ - "contentOffset": {"x": offset.x, "y": offset.y}, - "contentSize": {"width": content.0, "height": content.1}, - "layoutMeasurement": {"width": viewport.0, "height": viewport.1}, - "zoomScale": 1 - }), - ); - }) - .detach(); - } - } - _ => { - self.emit.last.set(Some(std::time::Instant::now())); - host.dispatch_event(self.tag, event, &payload); - } - } - } - crate::virtual_view::update(cx); - frame_hook.arm(window); - // Fabric's copy of the offset costs a commit per update, so it follows once - // scrolling pauses. - let generation = self.sync_generation.get() + 1; - self.sync_generation.set(generation); - self.sync_pending.set(true); - if let Some(event) = self.event.clone() { - let (host, tag) = (host.clone(), self.tag); - let (content, viewport) = (self.content_size, self.viewport); - report_rest( - cx, - self.sync_generation.clone(), - self.position.clone(), - move |offset| { - host.dispatch_event(tag, &event, &scroll_payload(offset, content, viewport)) - }, - ); - } - let (tag, position, sync_generation, pending) = ( - self.tag, - self.position.clone(), - self.sync_generation.clone(), - self.sync_pending.clone(), - ); - cx.spawn(async move |cx| { - cx.background_executor() - .timer(SCROLL_STATE_SYNC_DELAY) - .await; - if sync_generation.get() == generation && pending.replace(false) { - let offset = position.get(); - host.set_scroll_offset(tag, offset.x, offset.y); - } - }) - .detach(); - } -} - -pub(crate) fn decode_data_image(data: &str) -> Option { - use base64::Engine; - let (metadata, payload) = data.split_once(',')?; - if !metadata.ends_with(";base64") { - return None; - } - let bytes = base64::engine::general_purpose::STANDARD - .decode(payload) - .ok()?; - let mime = metadata.strip_prefix("image/")?.trim_end_matches(";base64"); - let format = match mime { - "png" => gpui::ImageFormat::Png, - "jpeg" | "jpg" => gpui::ImageFormat::Jpeg, - "webp" => gpui::ImageFormat::Webp, - "gif" => gpui::ImageFormat::Gif, - "svg+xml" | "svg" => gpui::ImageFormat::Svg, - "bmp" => gpui::ImageFormat::Bmp, - "tiff" | "tif" => gpui::ImageFormat::Tiff, - "ico" => gpui::ImageFormat::Ico, - _ => return None, - }; - Some(gpui::Image::from_bytes(format, bytes)) -} - -/// A transform scales text by shaping it at a scaled font size. GPUI keeps the -/// glyphs of every size it has drawn, so a scale animation that produced a new -/// size each frame would grow the glyph atlas without bound; snapping the size -/// to quarter points keeps the set of sizes small. -fn scaled_font_size(font_size: f32, scale: f32) -> f32 { - if scale == 1.0 { - return font_size; - } - (font_size * scale * 4.0).round() / 4.0 -} - -#[cfg(test)] -mod scaled_font_size_tests { - use super::scaled_font_size; - - #[test] - fn unscaled_text_keeps_its_size() { - assert_eq!(scaled_font_size(13.3, 1.0), 13.3); - } - - #[test] - fn a_scale_animation_draws_a_bounded_set_of_sizes() { - let sizes: std::collections::BTreeSet = (0..10_000) - .map(|step| 0.7 + 0.7 * step as f32 / 10_000.0) - .map(|scale| (scaled_font_size(14.0, scale) * 4.0) as u32) - .collect(); - assert!(sizes.len() <= 40, "{} sizes", sizes.len()); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/pointer_area.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/pointer_area.rs deleted file mode 100644 index 41e2d41f9f..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/pointer_area.rs +++ /dev/null @@ -1,590 +0,0 @@ -//! A `div` with listeners asks `hitbox.is_hovered` while painting, and gpui-fast -//! records that read as a dependency. This element inserts the same hitbox but -//! asks only inside its event handlers, where nothing is recorded. - -use gpui::{ - point, prelude::*, px, size, AnyElement, App, Bounds, DispatchPhase, Element, ElementId, - GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId, LayoutId, MouseButton, - MouseDownEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection, Pixels, Window, -}; -use std::rc::Rc; - -/// The node a pointer area belongs to, which every handler is given. Handlers -/// take it rather than capture it, so nodes alike share one set of handlers. -pub(crate) type Node = gpui::WeakEntity; - -pub(crate) type PointerHandler = Rc; - -/// A hover sample: whether the pointer is over the area now, then the context. -/// -/// It is a sample rather than an edge because the edge is decided by whoever owns -/// the previous state, which cannot live in here — `mouse_listeners` is cleared on -/// every frame, so this closure is rebuilt each paint. -pub(crate) type HoverHandler = Rc; - -/// The buttons a listener can be registered for. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub(crate) enum PointerButton { - Left, - Right, - Middle, - Back, - Forward, -} - -impl PointerButton { - pub(crate) fn from_gpui(button: MouseButton) -> Option { - match button { - MouseButton::Left => Some(PointerButton::Left), - MouseButton::Right => Some(PointerButton::Right), - MouseButton::Middle => Some(PointerButton::Middle), - // The two side buttons arrive as one variant plus a direction. - MouseButton::Navigate(direction) => Some(match direction { - NavigationDirection::Back => PointerButton::Back, - NavigationDirection::Forward => PointerButton::Forward, - }), - } - } - - /// The DOM's button number, which is what `events::Button` reports too. - pub(crate) fn number(self) -> i32 { - match self { - PointerButton::Left => 0, - PointerButton::Middle => 1, - PointerButton::Right => 2, - PointerButton::Back => 3, - PointerButton::Forward => 4, - } - } -} - -/// Every button, in the order the DOM numbers them, so the listeners for one -/// element fire in a stable order regardless of registration. -const POINTER_BUTTONS: [PointerButton; 5] = [ - PointerButton::Left, - PointerButton::Middle, - PointerButton::Right, - PointerButton::Back, - PointerButton::Forward, -]; - -/// In registration order; the bubble phase runs them in reverse. -pub(crate) struct PointerHandlers { - pub(crate) left_down: Vec>, - pub(crate) right_down: Vec>, - pub(crate) left_up: Vec>, - pub(crate) right_up: Vec>, - pub(crate) middle_down: Vec>, - pub(crate) middle_up: Vec>, - /// The side buttons, which are rare enough not to deserve a field each. - pub(crate) back_down: Vec>, - pub(crate) forward_down: Vec>, - pub(crate) back_up: Vec>, - pub(crate) forward_up: Vec>, - pub(crate) mouse_move: Vec>, - /// Hover samples: each handler is told whether the pointer is over the area - /// and decides for itself whether that is a change. - pub(crate) hover: Vec>, -} - -impl Default for PointerHandlers { - fn default() -> Self { - Self { - left_down: Vec::new(), - right_down: Vec::new(), - left_up: Vec::new(), - right_up: Vec::new(), - middle_down: Vec::new(), - middle_up: Vec::new(), - back_down: Vec::new(), - forward_down: Vec::new(), - back_up: Vec::new(), - forward_up: Vec::new(), - mouse_move: Vec::new(), - hover: Vec::new(), - } - } -} - -impl PointerHandlers { - pub(crate) fn is_empty(&self) -> bool { - POINTER_BUTTONS - .iter() - .all(|button| self.down(*button).is_empty() && self.up(*button).is_empty()) - && self.mouse_move.is_empty() - && self.hover.is_empty() - } - - fn down(&self, button: PointerButton) -> &Vec> { - match button { - PointerButton::Left => &self.left_down, - PointerButton::Right => &self.right_down, - PointerButton::Middle => &self.middle_down, - PointerButton::Back => &self.back_down, - PointerButton::Forward => &self.forward_down, - } - } - - fn up(&self, button: PointerButton) -> &Vec> { - match button { - PointerButton::Left => &self.left_up, - PointerButton::Right => &self.right_up, - PointerButton::Middle => &self.middle_up, - PointerButton::Back => &self.back_up, - PointerButton::Forward => &self.forward_up, - } - } -} - -/// How far past its box a node takes a press, in points: left, top, right, -/// bottom. Presses, moves and hover all reach this far, and so does the cursor. -pub(crate) type HitSlop = [f32; 4]; - -/// `child` taking pointer input over its own box, plus `slop`, without a -/// layout node of its own. The hitbox goes in before the child's, as a first -/// child's would, so the child's descendants stay in front of it. -pub(crate) struct PointerArea { - child: AnyElement, - target: Rc<(N, Rc>)>, - slop: HitSlop, - cursor: Option, -} - -impl PointerArea { - pub(crate) fn new( - child: impl IntoElement, - node: N, - handlers: Rc>, - slop: HitSlop, - cursor: Option, - ) -> Self { - Self { - child: child.into_any_element(), - target: Rc::new((node, handlers)), - slop, - cursor, - } - } -} - -impl IntoElement for PointerArea { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - -impl Element for PointerArea { - type RequestLayoutState = (); - type PrepaintState = Hitbox; - - fn id(&self) -> Option { - None - } - - fn source_location(&self) -> Option<&'static core::panic::Location<'static>> { - None - } - - fn request_layout( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&InspectorElementId>, - window: &mut Window, - cx: &mut App, - ) -> (LayoutId, Self::RequestLayoutState) { - (self.child.request_layout(window, cx), ()) - } - - fn prepaint( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&InspectorElementId>, - bounds: Bounds, - _request_layout: &mut Self::RequestLayoutState, - window: &mut Window, - cx: &mut App, - ) -> Self::PrepaintState { - let slop = self.slop; - let reach = Bounds { - origin: point(bounds.origin.x - px(slop[0]), bounds.origin.y - px(slop[1])), - size: size( - bounds.size.width + px(slop[0] + slop[2]), - bounds.size.height + px(slop[1] + slop[3]), - ), - }; - let hitbox = window.insert_hitbox(reach, HitboxBehavior::Normal); - self.child.prepaint(window, cx); - hitbox - } - - fn paint( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&InspectorElementId>, - _bounds: Bounds, - _request_layout: &mut Self::RequestLayoutState, - press_box: &mut Self::PrepaintState, - window: &mut Window, - cx: &mut App, - ) { - register_listeners(&self.target, press_box, self.slop, self.cursor, window); - self.child.paint(window, cx); - } -} - -fn register_listeners( - target: &Rc<(N, Rc>)>, - press_box: &Hitbox, - slop: HitSlop, - cursor: Option, - window: &mut Window, -) { - if let Some(cursor) = cursor { - if slop != [0.0; 4] { - window.set_cursor_style(cursor, press_box); - } - } - let hitbox = press_box.id; - let handlers = &target.1; - // An event has one button, so while no button has more than one handler, - // one listener for presses and one for releases run exactly the handler - // a listener per handler would. - if POINTER_BUTTONS - .iter() - .all(|button| handlers.down(*button).len() <= 1 && handlers.up(*button).len() <= 1) - { - if POINTER_BUTTONS - .iter() - .any(|button| !handlers.down(*button).is_empty()) - { - let target = target.clone(); - window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| { - if phase != DispatchPhase::Bubble { - return; - } - let Some(button) = PointerButton::from_gpui(event.button) else { - return; - }; - if let Some(handler) = target.1.down(button).first() { - if hitbox.is_hovered(window) { - handler(&target.0, event, window, cx); - } - } - }); - } - if POINTER_BUTTONS - .iter() - .any(|button| !handlers.up(*button).is_empty()) - { - let target = target.clone(); - window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| { - if phase != DispatchPhase::Bubble { - return; - } - let Some(button) = PointerButton::from_gpui(event.button) else { - return; - }; - if let Some(handler) = target.1.up(button).first() { - if hitbox.is_hovered(window) { - handler(&target.0, event, window, cx); - } - } - }); - } - } else { - register_button_listeners(target, hitbox, window); - } - for index in 0..handlers.mouse_move.len() { - let target = target.clone(); - window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| { - if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) { - target.1.mouse_move[index](&target.0, event, window, cx); - } - }); - } - // Enter and leave: GPUI reports hovered state per hitbox, so the - // transition is an edge detected by the handler rather than an event. - // The handler decides, because the previous state has to outlive this - // closure: GPUI clears `mouse_listeners` on every frame, so a - // `was_hovered` local here would reset at each paint and the leave edge - // would never fire. - for index in 0..handlers.hover.len() { - let target = target.clone(); - window.on_mouse_event(move |_event: &MouseMoveEvent, phase, window, cx| { - if phase != DispatchPhase::Bubble { - return; - } - let hovered = hitbox.is_hovered(window); - target.1.hover[index](&target.0, hovered, window, cx); - }); - } -} - -/// A listener per handler, each holding the shared handlers and its index, so -/// GPUI stops between the handlers of one button when one stops propagation. -fn register_button_listeners( - target: &Rc<(N, Rc>)>, - hitbox: gpui::HitboxId, - window: &mut Window, -) { - let handlers = &target.1; - for button in POINTER_BUTTONS { - for index in 0..handlers.down(button).len() { - let target = target.clone(); - window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| { - if phase == DispatchPhase::Bubble - && PointerButton::from_gpui(event.button) == Some(button) - && hitbox.is_hovered(window) - { - target.1.down(button)[index](&target.0, event, window, cx); - } - }); - } - for index in 0..handlers.up(button).len() { - let target = target.clone(); - window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| { - if phase == DispatchPhase::Bubble - && PointerButton::from_gpui(event.button) == Some(button) - && hitbox.is_hovered(window) - { - target.1.up(button)[index](&target.0, event, window, cx); - } - }); - } - } -} - -#[cfg(test)] -mod hover_tests { - use super::*; - use std::cell::RefCell; - use std::rc::Rc; - - /// A root view holding one pointer area, so a test can draw it and dispatch - /// moves at it. `PointerArea` is an element, not a `Render`, so it needs a - /// view to live in — the same shape `store.rs` uses for its surface root. - struct HoverProbe { - handlers: RefCell>>, - } - - impl gpui::Render for HoverProbe { - fn render( - &mut self, - _window: &mut Window, - _cx: &mut gpui::Context, - ) -> impl IntoElement { - let handlers = self.handlers.borrow_mut().take().unwrap_or_default(); - PointerArea::new( - gpui::div().size_full(), - (), - Rc::new(handlers), - [0.0; 4], - None, - ) - } - } - - /// Records every hover sample the listener reports, and edges them the way a - /// real caller does — with the previous state owned outside the listener. - fn recorder() -> (Rc>>, HoverHandler<()>) { - let seen = Rc::new(RefCell::new(Vec::new())); - let sink = seen.clone(); - let previous = Rc::new(std::cell::Cell::new(false)); - let handler: HoverHandler<()> = Rc::new(move |_: &(), hovered: bool, _window, _cx| { - if previous.get() == hovered { - return; - } - previous.set(hovered); - sink.borrow_mut().push(hovered); - }); - (seen, handler) - } - - /// Mounts a pointer area filling the window, draws one frame, then moves the - /// pointer to `position` and reads what the listener saw. - fn move_pointer(cx: &mut gpui::TestAppContext, handlers: PointerHandlers<()>, x: f32, y: f32) { - let window = cx.open_window(gpui::size(gpui::px(200.0), gpui::px(200.0)), move |_, _| { - HoverProbe { - handlers: RefCell::new(Some(handlers)), - } - }); - window - .update(cx, |_, window, app| { - // A frame first: the listener is registered while painting, so a - // move before the first draw has nothing to hit. - let needs_clear = window.draw(app); - needs_clear.clear(app); - window.dispatch_event( - gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent { - position: gpui::point(gpui::px(x), gpui::px(y)), - pressed_button: None, - ..Default::default() - }), - app, - ); - }) - .unwrap(); - } - - #[gpui::test] - fn a_hover_handler_reports_enter_when_the_pointer_arrives(cx: &mut gpui::TestAppContext) { - // The question this answers: does a synthetic move reach a hover listener - // at all? If this fails, the problem is native; if it passes, it is the - // test driver or the JS event path. - let (seen, handler) = recorder(); - let handlers = PointerHandlers { - hover: vec![handler], - ..PointerHandlers::default() - }; - // PointerHandlers is not Clone, so the recorder is read through the Rc the - // handler owns; moving it in does not lose the other reference. - move_pointer(cx, handlers, 50.0, 50.0); - assert_eq!(*seen.borrow(), vec![true], "expected one enter"); - } - - #[gpui::test] - fn leaving_reports_leave_across_a_repaint(cx: &mut gpui::TestAppContext) { - // This is the reported bug. `was_hovered` used to live inside the - // listener, and GPUI registers fresh listeners on every paint, so a - // repaint reset it to `false` and the leave edge was never seen — the - // hovered state stayed on forever. - let (seen, handler) = recorder(); - let handlers = PointerHandlers { - hover: vec![handler], - ..PointerHandlers::default() - }; - let window = cx.open_window(gpui::size(gpui::px(200.0), gpui::px(200.0)), move |_, _| { - HoverProbe { - handlers: RefCell::new(Some(handlers)), - } - }); - window - .update(cx, |_, window, app| { - let draw_and_move = |window: &mut gpui::Window, app: &mut gpui::App, x, y| { - let needs_clear = window.draw(app); - needs_clear.clear(app); - window.dispatch_event( - gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent { - position: gpui::point(gpui::px(x), gpui::px(y)), - pressed_button: None, - ..Default::default() - }), - app, - ); - }; - draw_and_move(window, app, 50.0, 50.0); - // A repaint between the two moves: this is what reset the old - // closure's state. - draw_and_move(window, app, 50.0, 50.0); - // Now leave the window entirely. - draw_and_move(window, app, 400.0, 400.0); - }) - .unwrap(); - assert_eq!( - *seen.borrow(), - vec![true, false], - "enter once, then leave once, with the repaint in between ignored", - ); - } - - /// A 40 by 40 box at (60, 60) holding a pointer area with `slop`. - struct SlopProbe { - handlers: RefCell>>, - slop: HitSlop, - } - - impl gpui::Render for SlopProbe { - fn render( - &mut self, - _window: &mut Window, - _cx: &mut gpui::Context, - ) -> impl IntoElement { - let handlers = self.handlers.borrow_mut().take().unwrap_or_default(); - gpui::div().size_full().child(PointerArea::new( - gpui::div() - .absolute() - .left(gpui::px(60.0)) - .top(gpui::px(60.0)) - .size(gpui::px(40.0)), - (), - Rc::new(handlers), - self.slop, - None, - )) - } - } - - /// Whether a press at (x, y) reaches a handler on a box with `slop`, and - /// whether a move there is seen as hover. - fn press_and_hover( - cx: &mut gpui::TestAppContext, - slop: HitSlop, - x: f32, - y: f32, - ) -> (bool, bool) { - let pressed = Rc::new(std::cell::Cell::new(false)); - let hovered = Rc::new(std::cell::Cell::new(false)); - let (sink, hover_sink) = (pressed.clone(), hovered.clone()); - let handlers = PointerHandlers { - left_down: vec![Rc::new(move |_: &(), _: &MouseDownEvent, _, _| { - sink.set(true) - })], - hover: vec![Rc::new(move |_: &(), over: bool, _, _| { - if over { - hover_sink.set(true); - } - })], - ..PointerHandlers::default() - }; - let window = cx.open_window(gpui::size(gpui::px(200.0), gpui::px(200.0)), move |_, _| { - SlopProbe { - handlers: RefCell::new(Some(handlers)), - slop, - } - }); - window - .update(cx, |_, window, app| { - let needs_clear = window.draw(app); - needs_clear.clear(app); - let position = gpui::point(gpui::px(x), gpui::px(y)); - window.dispatch_event( - gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent { - position, - pressed_button: None, - ..Default::default() - }), - app, - ); - window.dispatch_event( - gpui::PlatformInput::MouseDown(gpui::MouseDownEvent { - position, - button: gpui::MouseButton::Left, - ..Default::default() - }), - app, - ); - }) - .unwrap(); - (pressed.get(), hovered.get()) - } - - #[gpui::test] - fn a_press_or_hover_in_the_slop_reaches_the_handler(cx: &mut gpui::TestAppContext) { - let slop = [10.0, 20.0, 30.0, 40.0]; - // Inside the box. - assert_eq!(press_and_hover(cx, slop, 80.0, 80.0), (true, true)); - // Left of the box by 5 (slop 10), above it by 15 (slop 20). - assert_eq!(press_and_hover(cx, slop, 55.0, 80.0), (true, true)); - assert_eq!(press_and_hover(cx, slop, 80.0, 45.0), (true, true)); - // Right of the box by 25 (slop 30), below it by 35 (slop 40). - assert_eq!(press_and_hover(cx, slop, 125.0, 80.0), (true, true)); - assert_eq!(press_and_hover(cx, slop, 80.0, 135.0), (true, true)); - // Past the slop on each side. - assert_eq!(press_and_hover(cx, slop, 45.0, 80.0), (false, false)); - assert_eq!(press_and_hover(cx, slop, 80.0, 35.0), (false, false)); - assert_eq!(press_and_hover(cx, slop, 135.0, 80.0), (false, false)); - assert_eq!(press_and_hover(cx, slop, 80.0, 145.0), (false, false)); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/resources.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/resources.rs deleted file mode 100644 index 0b434378af..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/resources.rs +++ /dev/null @@ -1,278 +0,0 @@ -//! Where a release build finds its JavaScript bundle and assets. -//! -//! In development the bundle and assets come from environment variables that -//! the CLI sets, and they point into the source tree. A packaged app has no -//! source tree: the files sit in whatever layout its installer chose, so the -//! paths are derived from the executable instead. -//! -//! | OS | Bundle | Assets | -//! | --- | --- | --- | -//! | macOS | `/../Resources/index.bundle` | `/../Resources/assets` | -//! | Windows | `/index.bundle` | `/assets` | -//! | Linux | `/../lib//index.bundle` | `/assets` | -//! -//! Inside an AppImage the executable is at `usr/bin` and the libraries at -//! `usr/lib/`, and `$APPDIR` names the mount root. -use std::path::{Path, PathBuf}; - -/// The operating system whose install layout applies. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Host { - Macos, - Windows, - Linux, - Other, -} - -impl Host { - /// The OS this binary was built for. - pub fn current() -> Self { - if cfg!(target_os = "macos") { - Self::Macos - } else if cfg!(target_os = "windows") { - Self::Windows - } else if cfg!(target_os = "linux") { - Self::Linux - } else { - Self::Other - } - } -} - -/// The directory holding the bundle and the assets, given an executable path. -/// -/// `app_name` is the crate name the Linux installers use for the library -/// directory. `appdir` is `$APPDIR`, set only inside an AppImage. Pure: every -/// path it needs is passed in. -pub fn resource_dir(host: Host, exe: &Path, app_name: &str, appdir: Option<&Path>) -> PathBuf { - let exe_dir = exe.parent().unwrap_or_else(|| Path::new(".")); - match host { - // A macOS app bundle puts the executable in Contents/MacOS and the - // resources in Contents/Resources. - Host::Macos => exe_dir - .parent() - .map(|contents| contents.join("Resources")) - .unwrap_or_else(|| exe_dir.join("Resources")), - Host::Windows | Host::Other => exe_dir.to_path_buf(), - Host::Linux => { - // An AppImage mounts itself and sets APPDIR; the executable reports - // its path inside that mount. - if let Some(appdir) = appdir { - return appdir.join("usr").join("lib").join(app_name); - } - exe_dir - .parent() - .map(|prefix| prefix.join("lib").join(app_name)) - .unwrap_or_else(|| exe_dir.join("lib").join(app_name)) - } - } -} - -/// The bundle in `directory`. -/// -/// One name, always: a packaged release ships exactly one bundle and calls it -/// `index.bundle`, whether its content is Hermes bytecode or plain JavaScript. -/// Nothing here branches on the extension, and neither does the loader — Hermes -/// identifies its output by content, so a `.bundle` holding bytecode loads as -/// bytecode. -pub fn bundle_in(directory: &Path) -> PathBuf { - directory.join("index.bundle") -} - -/// The assets directory in `directory`. -pub fn assets_in(directory: &Path) -> PathBuf { - directory.join("assets") -} - -/// The directory this executable's resources live in, or `None` when the -/// executable path cannot be read. -/// -/// The Linux library directory is named after the binary: the installers put -/// the executable at `bin/` and its libraries at `lib/`, so the -/// executable's own file name is the name to use, with nothing to plumb through. -pub fn packaged_resource_dir() -> Option { - let exe = std::env::current_exe().ok()?; - let app_name = exe - .file_stem() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_default(); - let appdir = std::env::var_os("APPDIR").map(PathBuf::from); - Some(resource_dir( - Host::current(), - &exe, - &app_name, - appdir.as_deref(), - )) -} - -/// The bundle path a build should use. -/// -/// `RN_GPUI_BUNDLE` wins: the CLI sets it in development, pointing into the -/// source tree. A release build with the variable unset is a packaged app, and -/// looks beside its own executable. -pub fn default_bundle(fallback: &str) -> String { - if let Some(bundle) = std::env::var_os("RN_GPUI_BUNDLE") { - return bundle.to_string_lossy().into_owned(); - } - resolve_bundle(fallback, !cfg!(debug_assertions), packaged_resource_dir()) -} - -/// The decision `default_bundle` makes, with its inputs passed in. -/// -/// Split out so a debug test run can check the release path, which -/// `cfg!(debug_assertions)` would otherwise make unreachable. -fn resolve_bundle(fallback: &str, release: bool, resources: Option) -> String { - match (release, resources) { - (true, Some(directory)) => bundle_in(&directory).to_string_lossy().into_owned(), - _ => fallback.to_string(), - } -} - -/// The assets directory a build should use, or `None` when it has none. -/// -/// `RN_GPUI_ASSETS_DIR` wins, for the same reason as [`default_bundle`]. -pub fn default_assets_dir() -> Option { - if let Some(assets) = std::env::var_os("RN_GPUI_ASSETS_DIR") { - return Some(PathBuf::from(assets)); - } - resolve_assets_dir(!cfg!(debug_assertions), packaged_resource_dir()) -} - -/// The decision `default_assets_dir` makes, with its inputs passed in. -fn resolve_assets_dir(release: bool, resources: Option) -> Option { - match (release, resources) { - (true, Some(directory)) => Some(assets_in(&directory)), - _ => None, - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_macos_bundle_reads_from_contents_resources() { - let dir = resource_dir( - Host::Macos, - Path::new("/Applications/My App.app/Contents/MacOS/my-app"), - "my-app", - None, - ); - assert_eq!( - dir, - Path::new("/Applications/My App.app/Contents/Resources") - ); - } - - #[test] - fn windows_reads_beside_the_executable() { - // The separator has to be the host's: `Path` on Unix does not treat a - // backslash as one, so a Windows path only splits into components when - // this runs on Windows. - #[cfg(windows)] - let (exe, expected) = ( - r"C:\Program Files\My App\my-app.exe", - r"C:\Program Files\My App", - ); - #[cfg(not(windows))] - let (exe, expected) = ("/Program Files/My App/my-app.exe", "/Program Files/My App"); - let dir = resource_dir(Host::Windows, Path::new(exe), "my-app", None); - assert_eq!(dir, Path::new(expected)); - } - - #[test] - fn linux_reads_from_the_install_lib_directory() { - let dir = resource_dir(Host::Linux, Path::new("/usr/bin/my-app"), "my-app", None); - assert_eq!(dir, Path::new("/usr/lib/my-app")); - } - - #[test] - fn an_appimage_reads_from_inside_its_mount() { - // Inside an AppImage the executable reports a path in the temporary - // mount, and APPDIR names that mount's root. - let dir = resource_dir( - Host::Linux, - Path::new("/tmp/.mount_myapp/usr/bin/my-app"), - "my-app", - Some(Path::new("/tmp/.mount_myapp")), - ); - assert_eq!(dir, Path::new("/tmp/.mount_myapp/usr/lib/my-app")); - } - - #[test] - fn a_bare_executable_name_still_resolves() { - // `current_exe` rarely returns a bare name, but the function must not - // panic on one. - assert_eq!( - resource_dir(Host::Windows, Path::new("my-app.exe"), "my-app", None), - Path::new("") - ); - } - - #[test] - fn a_debug_build_keeps_the_value_it_was_given() { - // Development reads from the source tree, through the variable or the - // built-in default; it must not go looking beside the executable. - let resources = Some(PathBuf::from("/opt/my-app/Resources")); - assert_eq!( - resolve_bundle("build/index.bundle", false, resources.clone()), - "build/index.bundle" - ); - assert_eq!(resolve_assets_dir(false, resources), None); - } - - #[test] - fn a_release_build_with_no_resources_does_not_name_a_checkout() { - // `bootstrap` passes a bare file name as the fallback. A release binary - // must never carry an absolute path to the machine that built it: on the - // installing machine that path does not exist, and the app cannot start. - let fallback = resolve_bundle("index.bundle", true, None); - assert_eq!(fallback, "index.bundle"); - assert!(!fallback.contains('/'), "fallback must not be a path"); - } - - #[test] - fn a_release_build_looks_beside_the_executable() { - let root = - std::env::temp_dir().join(format!("rn-gpui-resources-release-{}", std::process::id())); - std::fs::create_dir_all(&root).unwrap(); - let resources = Some(root.clone()); - assert_eq!( - resolve_bundle("build/index.bundle", true, resources.clone()), - root.join("index.bundle").to_string_lossy() - ); - assert_eq!( - resolve_assets_dir(true, resources), - Some(root.join("assets")) - ); - std::fs::remove_dir_all(&root).ok(); - } - - #[test] - fn a_release_build_with_no_executable_path_falls_back() { - assert_eq!( - resolve_bundle("build/index.bundle", true, None), - "build/index.bundle" - ); - assert_eq!(resolve_assets_dir(true, None), None); - } - - #[test] - fn a_bytecode_bundle_is_preferred_when_present() { - let root = std::env::temp_dir().join(format!( - "rn-gpui-resources-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or_default() - )); - std::fs::create_dir_all(&root).unwrap(); - assert_eq!(bundle_in(&root), root.join("index.bundle")); - // A stray bytecode-named file must not win: the packaged name is fixed, - // and a second candidate is exactly how the wrong file got shipped before. - std::fs::write(root.join("index.bundle.hbc"), b"bytecode").unwrap(); - assert_eq!(bundle_in(&root), root.join("index.bundle")); - std::fs::remove_dir_all(&root).ok(); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/runtime.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/runtime.rs deleted file mode 100644 index 5975d6b4ac..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/runtime.rs +++ /dev/null @@ -1,94 +0,0 @@ -//! The runtime handle a GPUI-first app is given. -//! -//! A GPUI-first app is one whose windows are its own GPUI trees, with React -//! content where it places a [`ReactSurface`](crate::ReactSurface): -//! -//! ```ignore -//! run_with(DesktopAppConfig::from_env().gpui_first(|cx, runtime| { -//! // Any GPUI tree, with React content where it wants it: -//! cx.new(|cx| { -//! let sidebar = cx.new(|cx| ReactSurface::new("Sidebar", cx)); -//! let details = cx.new(|cx| { -//! ReactSurface::new("Details", cx).sizing(SurfaceSizing::fit_content()) -//! }); -//! Root { sidebar, details } -//! }) -//! .into() -//! })); -//! ``` -//! -//! [`DesktopAppConfig::gpui_first`](crate::DesktopAppConfig::gpui_first) is the -//! entry point. The runtime boots the way [`run_with`](crate::run_with) always -//! does — the JS engine, the bundle, the modules and the store — and then the -//! main window shows the app's view instead of a React tree started on surface 1. -//! The boot cannot be separated from that window any further: the store that -//! routes mount batches needs a window to exist, so the app supplies the window's -//! content rather than a window of its own making. -//! -//! What makes several surfaces work is that a surface is not tied to a window: a -//! `ReactSurface` asks for its own odd id, mount batches are routed by surface -//! id, and the store keeps one root per surface. One window can hold several -//! surfaces, and [`ReactRuntime::open_window`] opens more windows that hold -//! their own. - -use gpui::{App, Bounds, Render, Size, Window, WindowBounds, WindowOptions}; - -/// What a GPUI-first app needs from the runtime once JS is running. -#[derive(Clone, Copy, Debug)] -pub struct ReactRuntime { - scale: f32, -} - -impl ReactRuntime { - /// A handle for a runtime that started at `scale`. - pub(crate) fn new(scale: f32) -> Self { - Self { scale } - } - - /// The scale the runtime started at: what a surface is told until its own - /// window reports one. - pub fn scale(&self) -> f32 { - self.scale - } - - /// Opens another GPUI window whose root `build` makes, and returns it. - pub fn open_window( - &self, - cx: &mut App, - title: impl Into, - size: impl Into>, - build: impl FnOnce(&mut Window, &mut App) -> gpui::Entity + 'static, - ) -> gpui::WindowHandle { - let mut options = WindowOptions { - window_bounds: Some(WindowBounds::Windowed(Bounds::centered( - None, - size.into(), - cx, - ))), - ..Default::default() - }; - options.titlebar = Some(gpui::TitlebarOptions { - title: Some(title.into().into()), - ..Default::default() - }); - cx.open_window(options, build) - .expect("failed to open a GPUI window") - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_handle_reports_the_scale_the_runtime_started_at() { - assert_eq!(ReactRuntime::new(2.0).scale(), 2.0); - } - - #[test] - fn the_handle_is_a_cheap_copy() { - let runtime = ReactRuntime::new(1.5); - let copy = runtime; - assert_eq!(runtime.scale(), copy.scale()); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroll_indicator.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroll_indicator.rs deleted file mode 100644 index df3665038f..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroll_indicator.rs +++ /dev/null @@ -1,548 +0,0 @@ -//! A view of its own, outside the scrolling container: it reads the scroll -//! offset while rendering, and gpui-fast rebuilds whatever view did that on -//! every scroll. - -use gpui::{ - canvas, div, prelude::*, px, App, Context, DragMoveEvent, MouseButton, MouseDownEvent, - MouseUpEvent, Pixels, Point, ScrollHandle, Size, Task, Window, -}; -use serde_json::Value; -use std::cell::Cell; -use std::rc::Rc; -use std::time::{Duration, Instant}; - -/// Moves the scroll view to an offset, in the handle's own units, and reports it. -pub(crate) type ApplyOffset = Rc, &mut Window, &mut App)>; - -/// The viewport and the furthest offset, for a scroll view whose handle is not -/// tracked by an element and so never measures them. -pub(crate) type Extents = (Size, Point); - -/// Sends a scrollbar event to React with the scroll view's current offset. -pub(crate) type EmitEvent = Rc; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Visibility { - /// Shown while scrolling and while the pointer is at the edge. - Auto, - /// Shown whenever the content can scroll. - Always, - /// Shown only while the pointer is at the edge or dragging. - Hover, -} - -/// What the scrollbar looks like and does, from the `ScrollBar` component's props. -#[derive(Clone, Debug, PartialEq)] -pub struct ScrollbarSpec { - pub thickness: f32, - pub min_length: f32, - /// Space kept at either end of the track and between the thumb and the edge. - pub margin: f32, - pub color: u32, - pub radius: Option, - pub track_color: Option, - pub visibility: Visibility, - pub auto_hide: Duration, - pub interactive: bool, - /// Whether the props set the visibility and the thickness, which the style of - /// the platform's scrollers does not override. - pub visibility_set: bool, - pub thickness_set: bool, -} - -impl Default for ScrollbarSpec { - fn default() -> Self { - Self { - thickness: 6.0, - min_length: 24.0, - margin: 2.0, - color: 0xb080_8080, - radius: None, - track_color: None, - visibility: Visibility::Auto, - auto_hide: Duration::from_millis(1200), - interactive: true, - visibility_set: false, - thickness_set: false, - } - } -} - -impl ScrollbarSpec { - /// Reads the props of a scrollbar component; anything it leaves out keeps - /// its default. - pub fn from_props(bar: &Value) -> Self { - let mut spec = Self::default(); - let number = |key: &str| bar.get(key).and_then(Value::as_f64).map(|n| n as f32); - let color = |key: &str| bar.get(key).and_then(Value::as_u64).map(|n| n as u32); - let flag = |key: &str| bar.get(key).and_then(Value::as_bool); - spec.thickness_set = number("thickness").is_some(); - spec.visibility_set = bar.get("visibility").is_some(); - spec.thickness = number("thickness").unwrap_or(spec.thickness).max(1.0); - spec.min_length = number("minLength").unwrap_or(spec.min_length).max(0.0); - spec.margin = number("margin").unwrap_or(spec.margin).max(0.0); - spec.color = color("color").unwrap_or(spec.color); - spec.radius = number("radius").map(|radius| radius.max(0.0)); - spec.track_color = color("trackColor"); - spec.visibility = match bar.get("visibility").and_then(Value::as_str) { - Some("always") => Visibility::Always, - Some("hover") => Visibility::Hover, - _ => Visibility::Auto, - }; - if let Some(ms) = number("autoHideDelay") { - spec.auto_hide = Duration::from_millis(ms.max(0.0) as u64); - } - spec.interactive = flag("interactive").unwrap_or(spec.interactive); - spec - } - - /// This spec as the platform's scrollers are drawn: with legacy scrollers, - /// a bar that is always shown on a track, unless the props say otherwise. - fn styled(&self) -> ScrollbarSpec { - let mut spec = self.clone(); - if crate::scroller_style::legacy() { - if !spec.visibility_set { - spec.visibility = Visibility::Always; - } - if !spec.thickness_set { - spec.thickness = 12.0; - } - if spec.track_color.is_none() { - spec.track_color = Some(0x0f00_0000); - } - } - spec - } - - fn radius(&self) -> f32 { - self.radius.unwrap_or(self.thickness / 2.0) - } -} - -/// Payload of a thumb drag, so only the thumb's own drag moves the content. -struct ThumbDrag; - -struct DragGhost; - -impl Render for DragGhost { - fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { - div() - } -} - -/// Where the pointer and the content were when the thumb was pressed. -#[derive(Clone, Copy)] -struct DragStart { - pointer: f32, - offset: f32, - /// Whether the pointer has moved since, which is what a drag is. - moved: bool, -} - -pub(crate) struct ScrollIndicator { - handle: ScrollHandle, - horizontal: bool, - spec: ScrollbarSpec, - last_offset: Point, - visible_until: Option, - hovered: bool, - drag: Option, - apply: Option, - emit: Option, - extents: Option, - /// The overlay's window position, recorded while painting. - origin: Rc>>, - hide_task: Task<()>, - /// Set by a scroll that the app asked for (`scrollTo`, `scrollToEnd`), which - /// moves the content without showing the thumb, as a script's scroll does - /// under a browser's overlay scrollbars. - programmatic: Rc>, -} - -impl ScrollIndicator { - pub(crate) fn new( - handle: ScrollHandle, - horizontal: bool, - programmatic: Rc>, - ) -> Self { - Self { - programmatic, - last_offset: handle.offset(), - handle, - horizontal, - spec: ScrollbarSpec::default(), - visible_until: None, - hovered: false, - drag: None, - apply: None, - emit: None, - extents: None, - origin: Rc::default(), - hide_task: Task::ready(()), - } - } - - pub(crate) fn horizontal(&self) -> bool { - self.horizontal - } - - pub(crate) fn configure( - &mut self, - spec: ScrollbarSpec, - apply: ApplyOffset, - emit: EmitEvent, - extents: Option, - ) { - self.spec = spec; - self.apply = Some(apply); - self.emit = Some(emit); - self.extents = extents; - } - - fn spec(&self) -> ScrollbarSpec { - self.spec.styled() - } - - /// Whether the thumb is shown right now. - pub(crate) fn shown(&self) -> bool { - let (viewport, max_offset) = self.main_extents(); - if thumb(&self.spec(), viewport, max_offset, self.main_offset()).is_none() { - return false; - } - match self.spec().visibility { - Visibility::Always => true, - Visibility::Auto | Visibility::Hover => { - self.hovered - || self - .visible_until - .is_some_and(|until| Instant::now() < until) - } - } - } - - /// Shows the thumb for its auto-hide delay, as `flashScrollIndicators` does. - pub(crate) fn flash(&mut self, cx: &mut Context) { - self.reveal(cx); - cx.notify(); - } - - /// Shows the thumb, and hides it again once nothing has touched it. - fn reveal(&mut self, cx: &mut Context) { - let delay = self.spec.auto_hide; - self.visible_until = Some(Instant::now() + delay); - self.hide_task = cx.spawn(async move |this, cx| { - cx.background_executor() - .timer(delay + Duration::from_millis(30)) - .await; - let _ = this.update(cx, |_, cx| cx.notify()); - }); - } - - fn axis(&self, position: Point) -> f32 { - f32::from(if self.horizontal { - position.x - } else { - position.y - }) - } - - /// The scroll offset along the axis, as a positive distance from the start. - fn main_offset(&self) -> f32 { - let offset = self.handle.offset(); - -f32::from(if self.horizontal { offset.x } else { offset.y }) - } - - fn main_extents(&self) -> (f32, f32) { - let (viewport, max_offset) = self - .extents - .unwrap_or_else(|| (self.handle.bounds().size, self.handle.max_offset())); - if self.horizontal { - (f32::from(viewport.width), f32::from(max_offset.x)) - } else { - (f32::from(viewport.height), f32::from(max_offset.y)) - } - } - - fn emit(&self, event: &str, cx: &App) { - if let Some(emit) = &self.emit { - emit(event, cx); - } - } - - fn press(&mut self, event: &MouseDownEvent, cx: &mut Context) { - self.drag = Some(DragStart { - pointer: self.axis(event.position), - offset: self.main_offset(), - moved: false, - }); - cx.stop_propagation(); - } - - fn drag_to( - &mut self, - event: &DragMoveEvent, - window: &mut Window, - cx: &mut Context, - ) { - // A move without the button held is a hover retarget, not the drag. - if event.event.pressed_button != Some(MouseButton::Left) { - return; - } - let Some(mut start) = self.drag else { - return; - }; - let (viewport, max_offset) = self.main_extents(); - let Some((_, length)) = thumb(&self.spec(), viewport, max_offset, 0.0) else { - return; - }; - let track = viewport - 2.0 * self.spec.margin; - if track - length <= 0.0 { - return; - } - if !start.moved { - start.moved = true; - self.drag = Some(start); - self.emit("topScrollBarDragStart", cx); - } - let delta = self.axis(event.event.position) - start.pointer; - self.scroll_to( - start.offset + delta * max_offset / (track - length), - window, - cx, - ); - self.emit("topScrollBarDrag", cx); - self.reveal(cx); - cx.notify(); - } - - /// Moves the content to `next`, a distance from the start along the axis. - fn scroll_to(&self, next: f32, window: &mut Window, cx: &mut Context) { - let (_, max_offset) = self.main_extents(); - let next = next.clamp(0.0, max_offset); - let current = self.handle.offset(); - let offset = if self.horizontal { - Point::new(px(-next), current.y) - } else { - Point::new(current.x, px(-next)) - }; - match &self.apply { - Some(apply) => apply(offset, window, cx), - None => self.handle.set_offset(offset), - } - } - - /// A press on the track outside the thumb moves a page towards the - /// pointer, as a browser's scrollbar does. - fn page(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context) { - let (viewport, max_offset) = self.main_extents(); - let offset = self.main_offset(); - let Some((start, length)) = thumb(&self.spec(), viewport, max_offset, offset) else { - return; - }; - let pointer = self.axis(event.position) - self.axis(self.origin.get()); - let step = (viewport * PAGE_FRACTION).max(1.0); - let next = if pointer < start { - offset - step - } else if pointer > start + length { - offset + step - } else { - return; - }; - cx.stop_propagation(); - self.scroll_to(next, window, cx); - self.reveal(cx); - cx.notify(); - } - - fn release(&mut self, cx: &mut Context) { - if let Some(start) = self.drag.take() { - if start.moved { - self.emit("topScrollBarDragEnd", cx); - } - self.reveal(cx); - cx.notify(); - } - } -} - -/// The part of the viewport a track press scrolls by, as in Chromium. -const PAGE_FRACTION: f32 = 0.875; - -fn thumb(spec: &ScrollbarSpec, viewport: f32, max_offset: f32, offset: f32) -> Option<(f32, f32)> { - if viewport <= 0.0 || max_offset <= 0.5 { - return None; - } - let track = viewport - 2.0 * spec.margin; - let length = (track * viewport / (viewport + max_offset)) - .max(spec.min_length) - .min(track); - let progress = (offset / max_offset).clamp(0.0, 1.0); - Some((spec.margin + (track - length) * progress, length)) -} - -impl Render for ScrollIndicator { - fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let offset = self.handle.offset(); - let now = Instant::now(); - if offset != self.last_offset { - self.last_offset = offset; - if self.programmatic.replace(false) { - } else if self.spec.visibility != Visibility::Hover { - self.reveal(cx); - } - } - let origin = self.origin.clone(); - let overlay = div().absolute().top_0().left_0().size_full().child( - canvas( - move |bounds, _, _| origin.set(bounds.origin), - |_, _, _, _| {}, - ) - .absolute() - .size_full(), - ); - let (viewport, max_offset) = self.main_extents(); - let spec = self.spec(); - let Some((start, length)) = thumb(&spec, viewport, max_offset, self.main_offset()) else { - return overlay; - }; - let recent = self.visible_until.is_some_and(|until| now < until); - let shown = match spec.visibility { - Visibility::Always => true, - Visibility::Auto | Visibility::Hover => self.hovered || recent, - }; - let overlay = if spec.interactive { - let strip = div() - .id("scroll-hover-strip") - .absolute() - .on_hover(cx.listener(|this, hovered: &bool, _window, cx| { - this.hovered = *hovered; - if !*hovered { - this.reveal(cx); - } - cx.notify(); - })); - let strip = if shown { - strip.on_mouse_down( - MouseButton::Left, - cx.listener(|this, event: &MouseDownEvent, window, cx| { - this.page(event, window, cx); - }), - ) - } else { - strip - }; - let reach = spec.thickness + 2.0 * spec.margin + 6.0; - overlay.child(if self.horizontal { - strip.left_0().bottom_0().w_full().h(px(reach)) - } else { - strip.top_0().right_0().h_full().w(px(reach)) - }) - } else { - overlay - }; - if !shown { - return overlay; - } - let radius = px(spec.radius()); - let edge = px(spec.margin); - let overlay = match spec.track_color { - Some(color) => { - let track = div() - .absolute() - .rounded(radius) - .bg(crate::style::color(color)); - overlay.child(if self.horizontal { - track - .left(edge) - .right(edge) - .bottom(edge) - .h(px(spec.thickness)) - } else { - track - .top(edge) - .bottom(edge) - .right(edge) - .w(px(spec.thickness)) - }) - } - None => overlay, - }; - let bar = div() - .id("scroll-thumb") - .absolute() - .rounded(radius) - .bg(crate::style::color(spec.color)) - .when(spec.interactive, |bar| { - bar.on_mouse_down( - MouseButton::Left, - cx.listener(|this, event: &MouseDownEvent, _window, cx| { - this.press(event, cx); - }), - ) - .on_mouse_up( - MouseButton::Left, - cx.listener(|this, _: &MouseUpEvent, _window, cx| this.release(cx)), - ) - .on_mouse_up_out( - MouseButton::Left, - cx.listener(|this, _: &MouseUpEvent, _window, cx| this.release(cx)), - ) - .on_drag(ThumbDrag, |_, _, _, cx| cx.new(|_| DragGhost)) - .on_drag_move(cx.listener( - |this, event: &DragMoveEvent, window, cx| { - this.drag_to(event, window, cx); - }, - )) - }); - overlay.child(if self.horizontal { - bar.left(px(start)) - .bottom(edge) - .w(px(length)) - .h(px(spec.thickness)) - } else { - bar.top(px(start)) - .right(edge) - .w(px(spec.thickness)) - .h(px(length)) - }) - } -} - -#[cfg(test)] -mod tests { - use super::{thumb, ScrollbarSpec, Visibility}; - use serde_json::json; - - #[test] - fn content_that_fits_has_no_thumb() { - let spec = ScrollbarSpec::default(); - assert_eq!(thumb(&spec, 400.0, 0.0, 0.0), None); - assert_eq!(thumb(&spec, 0.0, 100.0, 0.0), None); - } - - #[test] - fn thumb_length_follows_the_visible_fraction_and_stays_on_the_track() { - let spec = ScrollbarSpec::default(); - let (start, length) = thumb(&spec, 404.0, 404.0, 0.0).unwrap(); - assert_eq!((start, length), (2.0, 200.0)); - let (start, length) = thumb(&spec, 404.0, 404.0, 404.0).unwrap(); - assert_eq!(start + length, 402.0); - let (start, length) = thumb(&spec, 404.0, 100_000.0, 200_000.0).unwrap(); - assert_eq!(length, 24.0); - assert_eq!(start + length, 402.0); - } - - #[test] - fn the_spec_reads_what_is_set_and_defaults_the_rest() { - let spec = ScrollbarSpec::from_props(&json!({ - "thickness": 10, "visibility": "always" - })); - assert_eq!(spec.thickness, 10.0); - assert_eq!(spec.visibility, Visibility::Always); - assert_eq!(spec.min_length, 24.0); - assert_eq!( - ScrollbarSpec::from_props(&json!({})), - ScrollbarSpec::default() - ); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroll_layers.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroll_layers.rs deleted file mode 100644 index b0b1858ee9..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroll_layers.rs +++ /dev/null @@ -1,312 +0,0 @@ -//! Whether a native surface inside a scrolling node keeps up with the scroll. - -/// How a scrolling node moves its content. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum ScrollStrategy { - /// GPUI scrolls the container itself: `overflow_*_scroll` plus - /// `track_scroll`. gpui-fast may cache the content as a scroll layer and - /// composite it on frames that only scroll. - GpuiLayer, - /// The node offsets the content itself, inside a clipped box. No element - /// reports `Overflow::Scroll`, so gpui-fast never makes the container a - /// layer and the content is prepainted on every frame — which is what a - /// native surface inside it needs, because its bounds are set in - /// `prepaint`. - ManualOffset, -} - -/// Which strategy a scrolling node must use. -pub(crate) fn scroll_strategy(contains_native_surface: bool) -> ScrollStrategy { - if contains_native_surface { - ScrollStrategy::ManualOffset - } else { - ScrollStrategy::GpuiLayer - } -} - -#[cfg(test)] -mod tests { - use super::{scroll_strategy, ScrollStrategy}; - use gpui::{ - div, point, prelude::*, px, size, AnyElement, App, AppContext, Bounds, Context, Element, - ElementId, GlobalElementId, IntoElement, LayoutId, Pixels, PlatformInput, Render, - ScrollDelta, ScrollEvent, ScrollHandle, Style, TestAppContext, Window, WindowHandle, - }; - use std::cell::RefCell; - use std::rc::Rc; - - const VIEWPORT: (f32, f32) = (200.0, 100.0); - const CONTENT_HEIGHT: f32 = 2000.0; - - /// Stands in for a native surface: records the bounds of every `prepaint` - /// it is given, exactly where `NativeSurfaceElement` calls `set_bounds`. - struct BoundsProbe { - prepaints: Rc>>, - } - - impl IntoElement for BoundsProbe { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } - } - - impl Element for BoundsProbe { - type RequestLayoutState = (); - type PrepaintState = (); - - fn id(&self) -> Option { - None - } - - fn source_location(&self) -> Option<&'static core::panic::Location<'static>> { - None - } - - fn request_layout( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&gpui::InspectorElementId>, - window: &mut Window, - cx: &mut App, - ) -> (LayoutId, Self::RequestLayoutState) { - let mut style = Style::default(); - style.size.width = px(40.).into(); - style.size.height = px(40.).into(); - (window.request_layout(style, [], cx), ()) - } - - fn prepaint( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&gpui::InspectorElementId>, - bounds: Bounds, - _request_layout: &mut Self::RequestLayoutState, - _window: &mut Window, - _cx: &mut App, - ) -> Self::PrepaintState { - self.prepaints.borrow_mut().push(bounds.origin.y); - } - - fn paint( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&gpui::InspectorElementId>, - _bounds: Bounds, - _request_layout: &mut Self::RequestLayoutState, - _prepaint: &mut Self::PrepaintState, - _window: &mut Window, - _cx: &mut App, - ) { - } - } - - /// A scrolling node holding a probe, rendered the way the runtime renders - /// one: `GpuiLayer` means GPUI scrolls it, `ManualOffset` means the node - /// offsets its own content inside a clipped box. - struct ScrollFixture { - handle: ScrollHandle, - strategy: ScrollStrategy, - probe: Rc>>, - /// The offset the content is drawn at, in `ManualOffset`. - offset: f32, - } - - impl Render for ScrollFixture { - fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let mut content = div() - .relative() - .flex_none() - .w(px(VIEWPORT.0)) - .h(px(CONTENT_HEIGHT)); - if self.strategy == ScrollStrategy::ManualOffset { - content = content.top(px(-self.offset)); - } - content = content.child(div().h(px(500.))).child(BoundsProbe { - prepaints: self.probe.clone(), - }); - let mut scroller = div().id("scroller").absolute().top_0().left_0().size_full(); - scroller = match self.strategy { - ScrollStrategy::GpuiLayer => scroller - .overflow_y_scroll() - .track_scroll(&self.handle) - .child(content), - ScrollStrategy::ManualOffset => { - let has_scroll = self.handle.offset().y != px(0.) || self.offset != 0.; - scroller = scroller.overflow_hidden(); - let _ = has_scroll; - let entity = cx.entity().downgrade(); - scroller - .on_scroll(move |event: &ScrollEvent, _window, cx| { - let dy = match &event.delta { - ScrollDelta::Pixels(delta) => f32::from(delta.y), - ScrollDelta::Lines(lines) => lines.y * 20.0, - }; - let _ = entity.update(cx, |this, cx| { - let max = (CONTENT_HEIGHT - VIEWPORT.1).max(0.0); - this.offset = (this.offset - dy).clamp(0.0, max); - cx.notify(); - }); - }) - .child(content) - } - }; - div() - .relative() - .w(px(VIEWPORT.0)) - .h(px(VIEWPORT.1)) - .bg(gpui::rgb(0xffffff)) - .child(scroller) - } - } - - fn open(cx: &mut TestAppContext, strategy: ScrollStrategy) -> WindowHandle { - let window = cx.add_window(move |_, _| ScrollFixture { - handle: ScrollHandle::new(), - strategy, - probe: Rc::new(RefCell::new(Vec::new())), - offset: 0.0, - }); - cx.update_window(window.into(), |_, window, cx| { - window.set_scroll_layers(true); - window.resize(size(px(VIEWPORT.0), px(VIEWPORT.1))); - window.dispatch_event(mouse_move(), cx); - window.draw(cx).clear(cx); - }) - .unwrap(); - window - } - - fn mouse_move() -> PlatformInput { - PlatformInput::MouseMove(gpui::MouseMoveEvent { - position: point(px(20.), px(20.)), - pressed_button: None, - ..Default::default() - }) - } - - /// How many times the probe was prepainted so far. - fn prepaints(window: WindowHandle, cx: &mut TestAppContext) -> usize { - window - .read_with(cx, |fixture, _| fixture.probe.borrow().len()) - .unwrap() - } - - fn last_probe_y( - window: WindowHandle, - cx: &mut TestAppContext, - ) -> Option { - window - .read_with(cx, |fixture, _| fixture.probe.borrow().last().copied()) - .unwrap() - } - - /// Scrolls one frame down by `dy` pixels and draws it. - fn scroll_frame(window: WindowHandle, cx: &mut TestAppContext, dy: f32) { - cx.update_window(window.into(), |_, window, cx| { - window.dispatch_event(mouse_move(), cx); - window.dispatch_event( - PlatformInput::Scroll(ScrollEvent { - position: point(px(20.), px(20.)), - delta: ScrollDelta::Pixels(point(px(0.), px(dy))), - modifiers: Default::default(), - touch_phase: gpui::TouchPhase::Moved, - source: gpui::ScrollSource::Pointer, - }), - cx, - ); - window.draw(cx).clear(cx); - }) - .unwrap(); - } - - /// The design's §5.4 question, answered: a native surface inside a GPUI - /// scroll container stops tracking once the container is composited as a - /// scroll layer, because a scroll-only frame prepaints no children. - #[gpui::test] - fn a_gpui_scrolled_container_stops_prepainting_its_content_once_composited( - cx: &mut TestAppContext, - ) { - let window = open(cx, ScrollStrategy::GpuiLayer); - assert!( - prepaints(window, cx) >= 1, - "the first frame prepaints the content" - ); - - let mut saw_a_frame_without_prepaint = false; - let mut offset_moved_while_prepaint_stale = false; - let mut previous_y = last_probe_y(window, cx).expect("the probe was prepainted"); - let mut trace = Vec::new(); - for step in 0..8 { - let before = prepaints(window, cx); - scroll_frame(window, cx, -6.0); - let after = prepaints(window, cx); - let y = last_probe_y(window, cx).expect("the probe was prepainted"); - trace.push((before, after, y)); - if after == before { - saw_a_frame_without_prepaint = true; - if y == previous_y && step > 1 { - offset_moved_while_prepaint_stale = true; - } - } - previous_y = y; - } - - assert!( - saw_a_frame_without_prepaint, - "a scroll-only frame must skip prepainting the content; the probe was \ - prepainted on every frame, so the layer path was never taken: {trace:?}" - ); - assert!( - offset_moved_while_prepaint_stale, - "the native surface's bounds must be seen to go stale while the window scrolls" - ); - } - - /// The other half: when the node offsets its own content, no element - /// reports `Overflow::Scroll`, so there is no layer to composite and the - /// content — and with it a native surface's bounds — is prepainted every - /// frame. - #[gpui::test] - fn a_manually_offset_container_prepaints_its_content_on_every_scrolled_frame( - cx: &mut TestAppContext, - ) { - let window = open(cx, ScrollStrategy::ManualOffset); - let start = last_probe_y(window, cx).expect("the probe was prepainted"); - - let mut ys = Vec::new(); - for _ in 0..8 { - let before = prepaints(window, cx); - scroll_frame(window, cx, -6.0); - assert_eq!( - prepaints(window, cx), - before + 1, - "every scrolled frame must prepaint the content" - ); - ys.push(last_probe_y(window, cx).expect("the probe was prepainted")); - } - - assert!( - ys.iter().all(|y| *y < start), - "the prepainted bounds must move up with the scroll: {ys:?} from {start:?}" - ); - assert!( - ys.windows(2).all(|pair| pair[0] > pair[1]), - "the bounds must track every frame, not jump: {ys:?}" - ); - } - - #[test] - fn a_native_surface_opts_a_scroll_container_out_of_the_composite_path() { - assert_eq!(scroll_strategy(true), ScrollStrategy::ManualOffset); - assert_eq!(scroll_strategy(false), ScrollStrategy::GpuiLayer); - } - - /// `AnyElement` is what a scroll container's content is built from, so the - /// test fixture must stay representable that way. - #[allow(dead_code)] - fn _probe_is_an_element(probe: Rc>>) -> AnyElement { - BoundsProbe { prepaints: probe }.into_any_element() - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroll_momentum.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroll_momentum.rs deleted file mode 100644 index 529f637f3f..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroll_momentum.rs +++ /dev/null @@ -1,194 +0,0 @@ -//! The momentum of a touchpad flick where the system sends none: how fast the -//! scroll was going when the fingers lifted, and how it slows after. -//! -//! macOS delivers the momentum as wheel events of its own. Windows and Linux -//! deliver the finger movement and then stop, so the scroll view carries on. - -use serde_json::Value; -use std::time::{Duration, Instant}; - -/// React Native's `decelerationRate` for `normal` and `fast`. -const NORMAL: f32 = 0.998; -const FAST: f32 = 0.99; - -/// The wheel samples this far back make up the speed of the flick. -const WINDOW: Duration = Duration::from_millis(100); -/// Fewer samples, or samples closer together than this, are not a flick. -const MIN_SAMPLES: usize = 3; -const MIN_SPAN: Duration = Duration::from_millis(24); -/// Slower than this, in points per millisecond, there is no momentum. -const MIN_SPEED: f32 = 0.3; -/// Where the flick has slowed enough to stop. -const STOP_SPEED: f32 = 0.02; - -/// The deceleration a `decelerationRate` prop asks for: a number, or `normal` -/// or `fast`. It is the fraction of its speed the scroll keeps each -/// millisecond, kept within what is a deceleration at all. -pub(crate) fn deceleration_from(props: &Value) -> f32 { - let rate = match props.get("decelerationRate") { - Some(Value::Number(number)) => number.as_f64().map_or(NORMAL, |rate| rate as f32), - Some(Value::String(name)) if name == "fast" => FAST, - _ => NORMAL, - }; - rate.clamp(0.9, 0.9999) -} - -/// Adds a wheel delta to the samples of the flick in progress. A delta that -/// reverses the direction starts a new flick, so scrolling back after a long -/// scroll is not carried on in the direction it came from. -pub(crate) fn push_sample(samples: &mut Vec<(Instant, f32)>, at: Instant, delta: f32) { - if samples - .last() - .is_some_and(|(_, last)| last.signum() != delta.signum()) - { - samples.clear(); - } - samples.push((at, delta)); - if samples.len() > 32 { - samples.remove(0); - } -} - -/// The speed at the end of `samples`, in points per millisecond with the sign -/// of the deltas, or `None` when it was not a flick. -pub(crate) fn flick_speed(samples: &[(Instant, f32)]) -> Option { - let last = samples.last()?.0; - let recent: Vec<&(Instant, f32)> = samples - .iter() - .filter(|(at, _)| last.duration_since(*at) <= WINDOW) - .collect(); - let first = recent.first()?.0; - let span = last.duration_since(first); - if recent.len() < MIN_SAMPLES || span < MIN_SPAN { - return None; - } - // The first sample only marks when the movement began. - let moved: f32 = recent.iter().skip(1).map(|(_, delta)| delta).sum(); - let speed = moved / span.as_secs_f32() / 1000.0; - (speed.abs() >= MIN_SPEED).then_some(speed) -} - -/// One step of `elapsed_ms`: how far the scroll goes, and its speed after. -pub(crate) fn step(speed: f32, rate: f32, elapsed_ms: f32) -> (f32, f32) { - let next = speed * rate.powf(elapsed_ms); - // The distance of a speed that decays exponentially over the step. - let distance = if (1.0 - rate).abs() < f32::EPSILON { - speed * elapsed_ms - } else { - (speed - next) / -rate.ln() - }; - (distance, next) -} - -/// Whether a speed is too slow to go on. -pub(crate) fn stopped(speed: f32) -> bool { - speed.abs() < STOP_SPEED -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn at(start: Instant, ms: u64) -> Instant { - start + Duration::from_millis(ms) - } - - #[test] - fn the_prop_is_a_number_or_a_name() { - assert_eq!(deceleration_from(&json!({})), NORMAL); - assert_eq!( - deceleration_from(&json!({"decelerationRate": "fast"})), - FAST - ); - assert_eq!(deceleration_from(&json!({"decelerationRate": 0.95})), 0.95); - assert_eq!(deceleration_from(&json!({"decelerationRate": 5.0})), 0.9999); - } - - #[test] - fn a_reversal_starts_a_new_flick() { - let start = Instant::now(); - let mut samples = Vec::new(); - for i in 0..4 { - push_sample(&mut samples, at(start, i * 8), -500.0); - } - push_sample(&mut samples, at(start, 40), 30.0); - assert_eq!(samples.len(), 1); - assert_eq!(flick_speed(&samples), None); - for i in 0..40 { - push_sample(&mut samples, at(start, 48 + i), 30.0); - } - assert_eq!(samples.len(), 32); - } - - #[test] - fn a_steady_run_of_deltas_is_a_flick_at_its_speed() { - let start = Instant::now(); - // 12 points every 8 ms: 1.5 points per millisecond. - let samples: Vec<_> = (0..6).map(|i| (at(start, i * 8), 12.0)).collect(); - let speed = flick_speed(&samples).unwrap(); - assert!((speed - 1.5).abs() < 0.01, "{speed}"); - } - - #[test] - fn a_leftward_flick_has_a_negative_speed() { - let start = Instant::now(); - let samples: Vec<_> = (0..6).map(|i| (at(start, i * 8), -12.0)).collect(); - assert!(flick_speed(&samples).unwrap() < 0.0); - } - - #[test] - fn a_few_events_at_once_are_not_a_flick() { - let start = Instant::now(); - let samples: Vec<_> = (0..40).map(|_| (start, 100.0)).collect(); - assert_eq!(flick_speed(&samples), None); - assert_eq!(flick_speed(&[(start, 100.0), (at(start, 30), 100.0)]), None); - } - - #[test] - fn a_slow_drag_is_not_a_flick() { - let start = Instant::now(); - let samples: Vec<_> = (0..6).map(|i| (at(start, i * 8), 0.4)).collect(); - assert_eq!(flick_speed(&samples), None); - } - - #[test] - fn only_the_last_hundred_milliseconds_count() { - let start = Instant::now(); - let mut samples: Vec<_> = (0..4).map(|i| (at(start, i * 8), 40.0)).collect(); - samples.extend((0..6).map(|i| (at(start, 500 + i * 8), 8.0))); - let speed = flick_speed(&samples).unwrap(); - assert!((speed - 1.0).abs() < 0.01, "{speed}"); - } - - #[test] - fn the_speed_decays_and_the_distance_adds_up() { - let (mut speed, mut travelled) = (2.0f32, 0.0f32); - for _ in 0..100 { - let (distance, next) = step(speed, NORMAL, 16.0); - assert!(next < speed && distance > 0.0); - travelled += distance; - speed = next; - } - // The whole run is speed / -ln(rate) however it is cut up. - let total = 2.0 / -NORMAL.ln(); - assert!( - travelled < total && travelled > total * 0.6, - "{travelled} of {total}" - ); - } - - #[test] - fn fast_stops_sooner_than_normal() { - let travelled = |rate: f32| { - let (mut speed, mut sum) = (2.0f32, 0.0f32); - while !stopped(speed) { - let (distance, next) = step(speed, rate, 16.0); - sum += distance; - speed = next; - } - sum - }; - assert!(travelled(FAST) < travelled(NORMAL) / 2.0); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroll_snap.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroll_snap.rs deleted file mode 100644 index 3df550f24a..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroll_snap.rs +++ /dev/null @@ -1,179 +0,0 @@ -//! Where a scroll view comes to rest when it snaps: `pagingEnabled`, -//! `snapToInterval`, `snapToOffsets`, `snapToStart` and `snapToEnd`. - -use serde_json::Value; - -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum SnapAlignment { - Start, - Center, - End, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct SnapSpec { - pub paging: bool, - pub interval: f32, - pub offsets: Vec, - pub start: bool, - pub end: bool, - pub alignment: SnapAlignment, - pub disable_interval_momentum: bool, -} - -impl SnapSpec { - /// The snapping the props ask for, or `None` when none is configured. - pub fn from_props(props: &Value) -> Option { - let flag = - |key: &str, default: bool| props.get(key).and_then(Value::as_bool).unwrap_or(default); - let paging = flag("pagingEnabled", false); - let interval = props - .get("snapToInterval") - .and_then(Value::as_f64) - .unwrap_or(0.0) as f32; - let offsets: Vec = props - .get("snapToOffsets") - .and_then(Value::as_array) - .map(|values| { - values - .iter() - .filter_map(|value| value.as_f64().map(|offset| offset as f32)) - .collect() - }) - .unwrap_or_default(); - if !paging && interval <= 0.0 && offsets.is_empty() { - return None; - } - let alignment = match props.get("snapToAlignment").and_then(Value::as_str) { - Some("center") => SnapAlignment::Center, - Some("end") => SnapAlignment::End, - _ => SnapAlignment::Start, - }; - Some(Self { - paging, - interval, - offsets, - start: flag("snapToStart", true), - end: flag("snapToEnd", true), - alignment, - disable_interval_momentum: flag("disableIntervalMomentum", false), - }) - } - - /// The offsets a scroll can come to rest at, along one axis. - fn stops(&self, viewport: f32, content: f32) -> Vec { - let max = (content - viewport).max(0.0); - let align = |offset: f32, size: f32| match self.alignment { - SnapAlignment::Start => offset, - SnapAlignment::Center => offset - (viewport - size) / 2.0, - SnapAlignment::End => offset - (viewport - size), - }; - let mut stops = Vec::new(); - if self.paging && viewport > 0.0 { - let mut offset = 0.0; - while offset < max + 0.5 { - stops.push(offset); - offset += viewport; - } - } else if self.interval > 0.0 { - let mut offset = 0.0; - while offset < content + 0.5 { - stops.push(align(offset, self.interval)); - offset += self.interval; - } - } - stops.extend(self.offsets.iter().map(|offset| align(*offset, 0.0))); - if self.start { - stops.push(0.0); - } - if self.end { - stops.push(max); - } - stops - .iter_mut() - .for_each(|stop| *stop = stop.clamp(0.0, max)); - stops.sort_by(f32::total_cmp); - stops.dedup_by(|a, b| (*a - *b).abs() < 0.5); - stops - } - - /// The stop nearest `offset`. With `disableIntervalMomentum` a scroll that - /// began at `drag_start` rests no further than one interval from it. - pub fn target(&self, offset: f32, drag_start: Option, viewport: f32, content: f32) -> f32 { - let reach = if self.paging { viewport } else { self.interval }; - let mut stops = self.stops(viewport, content); - if let (true, Some(start)) = (self.disable_interval_momentum, drag_start) { - if reach > 0.0 { - let bounded: Vec = stops - .iter() - .copied() - .filter(|stop| (stop - start).abs() <= reach + 0.5) - .collect(); - if !bounded.is_empty() { - stops = bounded; - } - } - } - stops - .into_iter() - .min_by(|a, b| (a - offset).abs().total_cmp(&(b - offset).abs())) - .unwrap_or(offset) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn nothing_is_configured_without_a_snapping_prop() { - assert_eq!(SnapSpec::from_props(&json!({"horizontal": true})), None); - } - - #[test] - fn paging_rests_on_a_multiple_of_the_viewport() { - let spec = SnapSpec::from_props(&json!({"pagingEnabled": true})).unwrap(); - assert_eq!(spec.target(130.0, None, 100.0, 500.0), 100.0); - assert_eq!(spec.target(160.0, None, 100.0, 500.0), 200.0); - assert_eq!(spec.target(999.0, None, 100.0, 500.0), 400.0); - } - - #[test] - fn an_interval_can_align_to_the_centre() { - let spec = SnapSpec::from_props(&json!({ - "snapToInterval": 100.0, - "snapToAlignment": "center", - "snapToStart": false, - "snapToEnd": false - })) - .unwrap(); - // Items of 100 in a 300 viewport: the centre of item 3 is offset 200. - assert_eq!(spec.target(190.0, None, 300.0, 1000.0), 200.0); - } - - #[test] - fn offsets_and_the_ends_are_stops() { - let spec = SnapSpec::from_props(&json!({"snapToOffsets": [150.0, 420.0]})).unwrap(); - assert_eq!(spec.target(140.0, None, 100.0, 500.0), 150.0); - assert_eq!(spec.target(10.0, None, 100.0, 500.0), 0.0); - assert_eq!(spec.target(395.0, None, 100.0, 500.0), 400.0); - let spec = SnapSpec::from_props(&json!({ - "snapToOffsets": [150.0], - "snapToStart": false - })) - .unwrap(); - assert_eq!(spec.target(10.0, None, 100.0, 500.0), 150.0); - } - - #[test] - fn disabled_interval_momentum_stays_within_one_interval() { - let spec = SnapSpec::from_props(&json!({ - "snapToInterval": 100.0, - "disableIntervalMomentum": true - })) - .unwrap(); - assert_eq!(spec.target(460.0, Some(100.0), 100.0, 1000.0), 200.0); - assert_eq!(spec.target(460.0, None, 100.0, 1000.0), 500.0); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroller_style.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroller_style.rs deleted file mode 100644 index 678afccbd1..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/scroller_style.rs +++ /dev/null @@ -1,91 +0,0 @@ -//! Whether scroll bars are drawn the way a mouse-driven desktop draws them: always -//! shown, with a track, instead of the overlay bars of a trackpad. -//! -//! macOS decides from the connected pointing devices, or from the user's choice in -//! System Settings, and tells apps when that changes. `RN_GPUI_SCROLLER_STYLE` -//! (`legacy` or `overlay`) overrides it on every platform, so a test does not -//! depend on the machine. - -use std::sync::atomic::{AtomicBool, Ordering}; - -static LEGACY: AtomicBool = AtomicBool::new(false); - -/// Whether scroll bars are drawn as legacy, always visible, scrollers. -pub(crate) fn legacy() -> bool { - LEGACY.load(Ordering::Relaxed) -} - -fn forced() -> Option { - match std::env::var("RN_GPUI_SCROLLER_STYLE").as_deref() { - Ok("legacy") => Some(true), - Ok("overlay") => Some(false), - _ => None, - } -} - -/// Tells JavaScript and the windows that the style changed. -pub(crate) fn announce(cx: &mut gpui::App) { - cx.refresh_windows(); - if let Some(store) = crate::store::store_from(cx) { - store.read(cx).host.emit_device_event_json( - "gpuiDesktop:scrollerStyle", - &serde_json::json!({ "legacy": legacy() }).to_string(), - ); - } -} - -/// Sets the style, as a change of the system setting does, for tests. -#[cfg(feature = "test-driver")] -pub(crate) fn set_for_test(value: bool, cx: &mut gpui::App) { - LEGACY.store(value, Ordering::Relaxed); - announce(cx); -} - -/// Reads the style, and on macOS calls `changed` whenever it changes. -pub(crate) fn install(changed: impl Fn() + Send + Sync + 'static) { - if let Some(forced) = forced() { - LEGACY.store(forced, Ordering::Relaxed); - return; - } - #[cfg(target_os = "macos")] - mac::install(changed); - #[cfg(not(target_os = "macos"))] - let _ = changed; -} - -#[cfg(target_os = "macos")] -mod mac { - use super::LEGACY; - use block::ConcreteBlock; - use cocoa::base::{id, nil}; - use cocoa::foundation::NSString; - use objc::{class, msg_send, sel, sel_impl}; - use std::sync::atomic::Ordering; - - const LEGACY_STYLE: isize = 0; - - fn read() -> bool { - // SAFETY: a class method of AppKit with no arguments. - let style: isize = unsafe { msg_send![class!(NSScroller), preferredScrollerStyle] }; - style == LEGACY_STYLE - } - - pub(super) fn install(changed: impl Fn() + Send + Sync + 'static) { - LEGACY.store(read(), Ordering::Relaxed); - // SAFETY: the observer block lives as long as the process and runs on the - // main queue, which is where AppKit posts the notification. - unsafe { - let center: id = msg_send![class!(NSNotificationCenter), defaultCenter]; - let name = - NSString::alloc(nil).init_str("NSPreferredScrollerStyleDidChangeNotification"); - let block = ConcreteBlock::new(move |_notification: id| { - LEGACY.store(read(), Ordering::Relaxed); - changed(); - }) - .copy(); - let queue: id = msg_send![class!(NSOperationQueue), mainQueue]; - let _: id = msg_send![center, addObserverForName: name object: nil queue: queue usingBlock: &*block]; - std::mem::forget(block); - } - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/store.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/store.rs deleted file mode 100644 index cd1616232d..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/store.rs +++ /dev/null @@ -1,3385 +0,0 @@ -use crate::frame::FrameHook; -use crate::host::Host; -use crate::node_view::{inherit, InheritInput, Inherited, RNNodeView}; -use gpui::deferred; -use gpui::{ - div, point, prelude::*, px, AnyWindowHandle, App, Context, Entity, Global, IntoElement, - MouseButton, NavigationDirection, Pixels, Point, Subscription, Window, -}; -use rn_gpui_sys::ffi::{MountBatch, MountKind, MountOp}; -use std::cell::{Cell, RefCell}; -use std::collections::{BTreeSet, HashMap, HashSet}; -use std::rc::Rc; -use std::sync::OnceLock; -use std::time::Instant; - -pub(crate) fn benchmark_mode() -> Option<&'static str> { - static MODE: OnceLock> = OnceLock::new(); - MODE.get_or_init(|| std::env::var("RN_GPUI_BENCH_MODE").ok()) - .as_deref() -} - -pub const APP_SURFACE_ID: i32 = 1; - -pub struct StoreGlobal(pub Entity); - -/// How often a surface is sent a new size during a live resize. -const RESIZE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50); -impl Global for StoreGlobal {} - -/// The queue every host component report goes into, and the store's one -/// delivery point for them. -pub(crate) type HostReportQueue = crate::host_component::HostReportQueue; - -/// How a surface's root is shown. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum SurfaceKind { - /// The root of a window: the menu bar, the overlay slot, the performance - /// monitor and the app key context belong to it. - Window, - /// Shown above a window's content through its overlay slot (LogBox). - Overlay, - /// Owned by a `ReactSurface`: GPUI places it inside any tree, and it carries - /// none of the window's chrome. - Embedded, -} - -/// Which layer dispatches `topLayout` for laid-out nodes. -/// -/// Fabric's `ShadowTree::emitLayoutEvents` already emits `topLayout` when -/// `BaseViewProps::onLayout` is set; Loom has no `ShadowTree`, so `ViewStore` -/// dispatches `topLayout` from mount ops. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum LayoutEventOwner { - ShadowTree, - Store, -} - -impl LayoutEventOwner { - pub fn from_loom_flag(loom_renderer: bool) -> Self { - if loom_renderer { - Self::Store - } else { - Self::ShadowTree - } - } -} - -pub struct ViewStore { - pub host: Host, - layout_event_owner: LayoutEventOwner, - pub frame_hook: FrameHook, - pub window: AnyWindowHandle, - pub windows: HashMap, - /// Fabric tags are unique across the surfaces of one React instance. - pub nodes: HashMap>, - pub(crate) accessibility_modal_tags: BTreeSet, - pub roots: HashMap>, - pub primary_surface_id: i32, - /// The size each surface's root was laid out at, as the last mount batch - /// reported it. A `FitContent` surface reads this to size its leaf. - pub surface_content_sizes: HashMap, - /// Embedded surfaces that report their content size, by surface id. - surface_size_observers: HashMap< - i32, - ( - crate::surface::SurfaceContentSize, - gpui::WeakEntity, - ), - >, - /// Where each embedded surface's box is in its window, shared with its nodes. - surface_origins: HashMap, - pub overlay_host: Entity, - /// Interior mutability on purpose: pointer movement must not update the store - /// entity, which nearly every node reads while rendering. - pub hovered: RefCell>, - pub pointer: Cell>, - /// Whether the pointer is over the window, as the last pointer event left it. - pub pointer_inside: Cell, - /// The mouse buttons held, as the DOM's `buttons` mask: 1 left, 2 right, 4 middle. - pub(crate) buttons_held: Cell, - /// Where a press of a button other than the left one started, which its - /// moves and its release follow. - pub(crate) button_target: RefCell>, - pub(crate) hover_retarget_pending: Rc>, - /// Nodes a transition was started on and has not been seen to finish, for - /// the test driver to keep drawing without scanning every node. - pub(crate) transitioning: RefCell>, - pub top_inset: f32, - /// Target fixed at primary-button down. RN keeps a touch's target stable - /// across drags, so responder moves/releases must still reach this node - /// after the pointer leaves its bounds. - pub active_touch_target: Option, - /// The screen whose Escape dismissal already announced its lifecycle - /// events. The following Fabric Remove should not announce it twice. - pub(crate) retained_subtrees: HashMap>, - /// What a `TreeView` reports about each mounted node, kept in step with - /// `nodes` as a batch is applied. - /// - /// Building this on demand copies every node in the tree, so doing it once - /// per insert and once per remove made a first mount of N nodes cost O(N²). - /// A batch now writes the entries it touches, and a hook borrows the map. - snapshots: HashMap, - log_mount_ops: bool, - /// A dropped `Subscription` unsubscribes, so the store owns it. - pub window_bounds_subscription: Option, - /// The main window's maximized / minimized / fullscreen observer. - pub window_state_subscription: Option, - pub window_appearance_subscription: Option, - pub navigation_keyboard_subscription: Option, - /// Every host component report waiting to be applied, in order. - pub(crate) host_reports: HostReportQueue, - /// When each surface was last sent a size. - resizes_in_flight: HashMap, - /// The latest size of each surface held back until then. - pending_resizes: HashMap, - /// The latest size each surface was given, in React's points. - sent_sizes: HashMap, -} - -impl ViewStore { - pub fn new( - host: Host, - window: impl Into, - frame_hook: FrameHook, - overlay_host: Entity, - layout_event_owner: LayoutEventOwner, - ) -> Self { - let window = window.into(); - note_surface_window(APP_SURFACE_ID, Some(window)); - Self { - host, - layout_event_owner, - frame_hook, - window, - windows: HashMap::from([(APP_SURFACE_ID, window)]), - nodes: HashMap::new(), - accessibility_modal_tags: BTreeSet::new(), - roots: HashMap::new(), - primary_surface_id: APP_SURFACE_ID, - surface_content_sizes: HashMap::new(), - surface_size_observers: HashMap::new(), - surface_origins: HashMap::new(), - overlay_host, - hovered: RefCell::new(Vec::new()), - pointer: Cell::new(point(px(0.), px(0.))), - pointer_inside: Cell::new(false), - buttons_held: Cell::new(0), - button_target: RefCell::new(None), - hover_retarget_pending: Rc::default(), - transitioning: RefCell::default(), - top_inset: 0.0, - active_touch_target: None, - retained_subtrees: HashMap::new(), - snapshots: HashMap::new(), - log_mount_ops: benchmark_mode().is_none(), - window_bounds_subscription: None, - window_state_subscription: None, - window_appearance_subscription: None, - navigation_keyboard_subscription: None, - host_reports: std::rc::Rc::new(crate::host_component::HostReports::default()), - resizes_in_flight: HashMap::new(), - pending_resizes: HashMap::new(), - sent_sizes: HashMap::new(), - } - } - - pub fn register_root(&mut self, surface_id: i32, root: Entity) { - self.roots.insert(surface_id, root); - } - - pub fn register_window(&mut self, surface_id: i32, window: AnyWindowHandle) { - self.windows.insert(surface_id, window); - note_surface_window(surface_id, Some(window)); - } - - pub fn unregister_window(&mut self, surface_id: i32) { - self.windows.remove(&surface_id); - note_surface_window(surface_id, None); - } - - pub fn window_for(&self, surface_id: i32) -> Option { - self.windows - .get(&surface_id) - .copied() - .or_else(|| (surface_id == APP_SURFACE_ID).then_some(self.window)) - } - - pub fn surfaces_in_window(&self, window: AnyWindowHandle) -> Vec { - self.windows - .iter() - .filter(|(_, handle)| **handle == window) - .map(|(surface, _)| *surface) - .collect() - } - - /// Fabric references the `RootView` as a parent that is never itself mounted, - /// so the root view is created the first time a node is spliced into it. - /// Lets `observer` be told when `surface_id`'s root changes size. - pub fn observe_surface_content_size( - &mut self, - surface_id: i32, - observer: crate::surface::SurfaceContentSize, - surface: gpui::WeakEntity, - ) { - if let Some(size) = self.surface_content_sizes.get(&surface_id) { - observer.set(*size); - } - self.surface_size_observers - .insert(surface_id, (observer, surface)); - } - - /// The root entity for `surface_id`, making one if needed. - pub fn ensure_root( - &mut self, - surface_id: i32, - cx: &mut Context, - ) -> Entity { - self.root_for(surface_id, cx) - } - - /// The root of an embedded surface: a surface GPUI places inside its own - /// tree. Unlike the root a mount batch creates for an unknown surface, it is - /// not shown through the overlay slot, and it carries no window chrome. - pub fn ensure_embedded_root( - &mut self, - surface_id: i32, - cx: &mut Context, - ) -> Entity { - if let Some(root) = self.roots.get(&surface_id) { - return root.clone(); - } - let root = cx.new(|_| SurfaceRootView::with_kind(surface_id, SurfaceKind::Embedded)); - self.roots.insert(surface_id, root.clone()); - root - } - - /// Uses `origin` as the box of `surface_id` in its window. Called before the - /// surface's first node mounts, so each node shares the cell. - pub fn use_surface_origin(&mut self, surface_id: i32, origin: crate::surface::SurfaceOrigin) { - self.surface_origins.insert(surface_id, origin); - } - - /// The origin cell nodes of `surface_id` share. A surface that was never - /// placed by GPUI (a window root) keeps the zero origin it starts with. - fn origin_for(&mut self, surface_id: i32) -> crate::surface::SurfaceOrigin { - self.surface_origins.entry(surface_id).or_default().clone() - } - - fn root_for(&mut self, surface_id: i32, cx: &mut Context) -> Entity { - if let Some(root) = self.roots.get(&surface_id) { - return root.clone(); - } - // A surface with no registered window belongs to the main window. That - // covers LogBox (surface 2), which C++ starts directly, and any surface - // that mounted before the window registry adopted it. - let window = self.window_for(surface_id).unwrap_or(self.window); - let overlay = surface_id != self.primary_surface_id && window == self.window; - let kind = if overlay { - SurfaceKind::Overlay - } else { - SurfaceKind::Window - }; - let root = cx.new(|_| SurfaceRootView::with_kind(surface_id, kind)); - self.roots.insert(surface_id, root.clone()); - if overlay { - log::info!("[store] surface {surface_id} registered as an overlay"); - self.overlay_host.update(cx, |host, cx| { - host.insert(surface_id, root.clone()); - cx.notify(); - }); - } - root - } - - /// Fabric emits no `Delete` mutations for a dying surface. On a reload every - /// node must go, or the new instance would reuse tags on top of the stale tree. - pub fn surface_stopped(&mut self, surface_id: i32, cx: &mut Context) { - if surface_id == rn_gpui_sys::ALL_SURFACES { - log::info!( - "[store] React instance going away: dropping {} nodes and every root child", - self.nodes.len() - ); - self.nodes.clear(); - self.snapshots.clear(); - self.accessibility_modal_tags.clear(); - self.hovered.borrow_mut().clear(); - self.active_touch_target = None; - crate::interaction::clear(); - let roots: Vec> = self.roots.values().cloned().collect(); - for root in roots { - root.update(cx, |root, cx| { - root.clear_children(); - cx.notify(); - }); - } - self.overlay_host.update(cx, |host, cx| { - host.clear(); - cx.notify(); - }); - cx.notify(); - return; - } - - let stale: Vec = self - .nodes - .iter() - .filter(|(_, node)| node.read(cx).surface_id == surface_id) - .map(|(tag, _)| *tag) - .collect(); - let dropped = stale.len(); - if self - .active_touch_target - .as_ref() - .is_some_and(|target| stale.contains(&target.tag)) - { - self.active_touch_target = None; - crate::interaction::clear(); - } - for tag in stale { - self.nodes.remove(&tag); - self.snapshots.remove(&tag); - self.accessibility_modal_tags.remove(&tag); - self.overlay_host.update(cx, |host, cx| { - host.remove_portal(tag); - cx.notify(); - }); - } - let live: HashSet = self.nodes.keys().copied().collect(); - self.hovered.borrow_mut().retain(|tag| live.contains(tag)); - if let Some(root) = self.roots.remove(&surface_id) { - self.overlay_host.update(cx, |host, cx| { - host.remove(surface_id); - cx.notify(); - }); - root.update(cx, |root, cx| { - root.clear_children(); - cx.notify(); - }); - } - self.windows.remove(&surface_id); - log::info!("[store] surface {surface_id} stopped: dropped {dropped} nodes"); - cx.notify(); - } - - /// Redraws the surfaces of a window whose layout changed outside React. - pub fn notify_window_roots(&mut self, window: AnyWindowHandle, cx: &mut Context) { - for surface_id in self.surfaces_in_window(window) { - let root = self.root_for(surface_id, cx); - root.update(cx, |_, cx| cx.notify()); - } - } - - /// Sizes each surface of `window`. A live resize reports a size every - /// frame, faster than React commits the layout of a large tree, and the - /// queued commits trip React's nested update limit; so a surface gets a - /// new size at most every [`RESIZE_INTERVAL`], and the latest one waits - /// for the end of it. - pub fn resize_window( - &mut self, - window: AnyWindowHandle, - width: f32, - height: f32, - scale: f32, - cx: &mut Context, - ) { - // Per surface, not per call: the menu bar can be hidden in one window and - // shown in another, so the inset has to follow the window the surface - // belongs to. - for surface_id in self.surfaces_in_window(window) { - let frame = crate::desktop::window_frame::insets_of(surface_id); - let zoom = crate::desktop::zoom::get(surface_id); - let width = ((width - frame.horizontal()) / zoom).max(1.0); - let height = ((height - - frame.vertical() - - crate::desktop::gpui_menu::menu_bar_inset_for_window_id(surface_id as u32)) - / zoom) - .max(1.0); - let scale = scale * zoom; - let busy = self - .resizes_in_flight - .get(&surface_id) - .is_some_and(|sent| sent.elapsed() < RESIZE_INTERVAL); - if busy { - let waiting = self - .pending_resizes - .insert(surface_id, (width, height, scale)) - .is_some(); - if !waiting { - self.flush_resize_later(surface_id, cx); - } - continue; - } - self.send_surface_size(surface_id, width, height, scale); - } - } - - /// Whether a surface still has a size held back from React: the resize - /// interval has not ended, so its layout has not been asked for yet. - pub fn has_pending_resize(&self) -> bool { - !self.pending_resizes.is_empty() - } - - /// Whether React has laid `window`'s surfaces out at the size they were - /// last given: none has a size held back, and the top views of each fill - /// it. A surface given no size since it started has nothing to wait for. - pub fn window_layout_matches_size(&self, window: AnyWindowHandle, cx: &gpui::App) -> bool { - self.surfaces_in_window(window) - .into_iter() - .all(|surface_id| { - if self.pending_resizes.contains_key(&surface_id) { - return false; - } - let (Some(&(width, height)), Some(root)) = ( - self.sent_sizes.get(&surface_id), - self.roots.get(&surface_id), - ) else { - return true; - }; - let children = &root.read(cx).children; - children.is_empty() - || children.iter().any(|(_, node)| { - let frame = node.read(cx).frame; - (frame.w - width).abs() <= 0.5 && (frame.h - height).abs() <= 0.5 - }) - }) - } - - fn send_surface_size(&mut self, surface_id: i32, width: f32, height: f32, scale: f32) { - log::info!( - "[store] surface {surface_id} resized to {width}x{height}@{scale}x (window-scoped)" - ); - self.pending_resizes.remove(&surface_id); - self.sent_sizes.insert(surface_id, (width, height)); - self.resizes_in_flight - .insert(surface_id, std::time::Instant::now()); - self.host.set_surface_size(surface_id, width, height, scale); - } - - /// Sends the size held back for `surface_id`, if any. - fn flush_resize(&mut self, surface_id: i32) { - self.resizes_in_flight.remove(&surface_id); - if let Some((width, height, scale)) = self.pending_resizes.remove(&surface_id) { - self.send_surface_size(surface_id, width, height, scale); - } - } - - /// Sends the size held back for `surface_id` once the interval is over. - fn flush_resize_later(&mut self, surface_id: i32, cx: &mut Context) { - cx.spawn(async move |store, cx| { - cx.background_executor().timer(RESIZE_INTERVAL).await; - let _ = store.update(cx, |store, cx| { - let expired = store - .resizes_in_flight - .get(&surface_id) - .is_none_or(|sent| sent.elapsed() >= RESIZE_INTERVAL); - if expired { - store.flush_resize(surface_id); - } else if store.pending_resizes.contains_key(&surface_id) { - store.flush_resize_later(surface_id, cx); - } - }); - }) - .detach(); - } - - /// Carries `native` more native surfaces and `effects` more nodes painted - /// as groups from `parent_tag` up to the surface root. - fn carry_native_surface_delta( - &mut self, - surface_id: i32, - parent_tag: Option, - native: i64, - effects: i64, - cx: &mut Context, - ) { - if native == 0 && effects == 0 { - return; - } - let mut parent = parent_tag; - while let Some(tag) = parent { - let Some(node) = self.nodes.get(&tag).cloned() else { - break; - }; - crate::counters::bump(crate::counters::Counter::NativeSurfaceWalkNodes); - let mut next = None; - node.update(cx, |node, cx| { - next = node.parent_tag_cached(); - let mut crossed = false; - if native > 0 { - crossed |= node.add_native_surface_descendants(native as u32); - } else if native < 0 { - crossed |= node.sub_native_surface_descendants((-native) as u32); - } - if effects > 0 { - crossed |= node.add_effect_group_descendants(effects as u32); - } else if effects < 0 { - crossed |= node.sub_effect_group_descendants((-effects) as u32); - } - if crossed { - cx.notify(); - } - }); - parent = next; - } - if native == 0 { - return; - } - if let Some(root) = self.roots.get(&surface_id).cloned() { - root.update(cx, |root, cx| { - let crossed = if native > 0 { - root.add_native_surfaces(native as u32) - } else { - root.sub_native_surfaces((-native) as u32) - }; - if crossed { - cx.notify(); - } - }); - } - } - - /// Claims what `tag`'s subtree owes, so it is counted exactly once: its - /// native surfaces and its nodes painted as groups. - fn claim_native_surface_contribution( - &mut self, - tag: i32, - cx: &mut Context, - ) -> (u32, u32) { - let Some(node) = self.nodes.get(&tag).cloned() else { - return (0, 0); - }; - let (counted, native, effects) = { - let node = node.read(cx); - ( - node.native_surface_counted, - node.native_surface_descendants, - node.effect_group_descendants, - ) - }; - if !counted { - return (0, 0); - } - node.update(cx, |node, _cx| { - node.take_native_surface_contribution(); - }); - (native, effects) - } - - /// Adds what `tag`'s subtree contributes to its ancestors. - fn add_native_surface_to_ancestors( - &mut self, - surface_id: i32, - tag: i32, - parent_tag: Option, - cx: &mut Context, - ) { - let Some(node) = self.nodes.get(&tag).cloned() else { - return; - }; - let (counted, native, effects) = { - let node = node.read(cx); - ( - node.native_surface_counted, - node.native_surface_descendants, - node.effect_group_descendants, - ) - }; - if counted { - return; - } - node.update(cx, |node, _cx| node.mark_native_surface_counted()); - self.carry_native_surface_delta( - surface_id, - parent_tag, - i64::from(native), - i64::from(effects), - cx, - ); - } - - /// Takes what `tag`'s subtree contributes back off its ancestors. - fn remove_native_surface_from_ancestors( - &mut self, - surface_id: i32, - tag: i32, - parent_tag: Option, - cx: &mut Context, - ) { - let (native, effects) = self.claim_native_surface_contribution(tag, cx); - self.carry_native_surface_delta( - surface_id, - parent_tag, - -i64::from(native), - -i64::from(effects), - cx, - ); - } - - /// Fabric emits `Create`/`Update` before the `Insert` that splices a node in, - /// so a parent always exists when its children arrive. - /// Works out what the pointer is over again once the tree it is over has - /// changed, the way a browser does after a layout: a view that mounts under - /// a still pointer is hovered without the pointer moving. - fn schedule_hover_retarget(&self, cx: &mut Context) { - if !self.pointer_inside.get() - || self.active_touch_target.is_some() - || self.hover_retarget_pending.replace(true) - { - return; - } - let window = self.window; - cx.defer(move |cx| { - let _ = cx.update_window(window, move |_, window, _| { - window.on_next_frame(move |window, cx| { - window.defer(cx, crate::events::flush_hover_retarget); - }); - }); - }); - } - - pub fn apply_batch(&mut self, batch: MountBatch, cx: &mut Context) { - self.install_report_waker(cx); - let surface_id = batch.surface_id; - if batch.has_content_size { - let size = (batch.content_width, batch.content_height); - log::debug!( - "[store] surface {surface_id} content size {}x{}", - size.0, - size.1 - ); - self.surface_content_sizes.insert(surface_id, size); - if let Some((observer, surface)) = self.surface_size_observers.get(&surface_id) { - if observer.set(size) { - let _ = surface.update(cx, |_, cx| cx.notify()); - } - } - } - log::debug!("[store] surface {}: {} ops", surface_id, batch.ops.len()); - let store = cx.entity().downgrade(); - let commands: std::sync::Arc>> = - Default::default(); - let handle = crate::extensions::StoreHandle::queued(store, commands.clone()); - let host_reports = self.host_reports.clone(); - let observers = crate::extensions::store_observers(); - if !observers.is_empty() { - let batch_view = crate::extensions::BatchView { - surface_id, - ops: batch - .ops - .iter() - .map(|op| crate::extensions::BatchOp { - kind: match op.kind { - MountKind::Create => crate::extensions::BatchOpKind::Create, - MountKind::Delete => crate::extensions::BatchOpKind::Delete, - MountKind::Insert => crate::extensions::BatchOpKind::Insert, - MountKind::Remove => crate::extensions::BatchOpKind::Remove, - MountKind::Update => crate::extensions::BatchOpKind::Update, - _ => crate::extensions::BatchOpKind::Update, - }, - tag: op.tag, - parent_tag: op.parent_tag, - index: op.index, - component: op.component.to_owned(), - props: std::sync::Arc::new(crate::extensions::parse_extension_props( - &op.extension_props_json, - )), - props_changed: op.props_changed, - }) - .collect(), - }; - for observer in &observers { - let tree = self.tree_view(cx); - observer.before_batch(&batch_view, &tree, &handle, cx); - self.apply_commands(&commands, cx); - } - let pending: Vec = - PENDING_RETAIN.with(|pending| pending.borrow_mut().drain().collect()); - for tag in pending { - self.retain_subtree(tag, cx); - } - } - let anchors = self.capture_scroll_anchors(cx); - for op in batch.ops.iter() { - match op.kind { - MountKind::Create | MountKind::Update => { - let is_visible_portal = crate::extensions::component_portal( - &op.component, - &crate::extensions::parse_extension_props(&op.extension_props_json), - ) - .is_some_and(|portal| portal.visible); - if op.view.accessibility_modal || is_visible_portal { - self.accessibility_modal_tags.insert(op.tag); - } else { - self.accessibility_modal_tags.remove(&op.tag); - } - } - MountKind::Delete | MountKind::Remove => { - self.accessibility_modal_tags.remove(&op.tag); - } - _ => {} - } - if self.log_mount_ops { - log_mount_op(op); - } - match op.kind { - MountKind::Create => { - let host_reports = host_reports.clone(); - let origin = self.origin_for(surface_id); - let node = cx.new(|cx| { - RNNodeView::from_op(op, surface_id, host_reports, Some(&mut **cx)) - .with_surface_origin(origin) - }); - self.nodes.insert(op.tag, node.clone()); - self.record_subtree_nodes(&[op.tag], cx); - let component_node = - (!observers.is_empty()).then(|| node.read(cx).component_node_shallow()); - for observer in &observers { - let component_node = component_node.as_ref().expect("observers"); - observer.on_mount(component_node, &handle, cx); - self.apply_commands(&commands, cx); - } - } - MountKind::Delete => { - if crate::extensions::component_portal( - &op.component, - &crate::extensions::parse_extension_props(&op.extension_props_json), - ) - .is_some() - { - self.overlay_host.update(cx, |host, cx| { - host.remove_portal(op.tag); - cx.notify(); - }); - } - if let Some(node) = self.nodes.get(&op.tag).cloned() { - let parent_tag = node.read(cx).parent_tag_cached(); - let (native, effects) = self.claim_native_surface_contribution(op.tag, cx); - self.carry_native_surface_delta( - surface_id, - parent_tag, - -i64::from(native), - -i64::from(effects), - cx, - ); - if native + effects > 0 { - if let Some(parent) = - parent_tag.and_then(|tag| self.nodes.get(&tag).cloned()) - { - parent.update(cx, |parent, cx| { - parent.remove_child(op.tag); - cx.notify(); - }); - } - } - } - self.nodes.remove(&op.tag); - self.drop_snapshot(op.tag); - for observer in &observers { - observer.on_remove(op.tag, &handle, cx); - self.apply_commands(&commands, cx); - } - } - MountKind::Insert => { - let Some(child) = self.nodes.get(&op.tag).cloned() else { - log::warn!("[store] insert of unknown tag {}", op.tag); - continue; - }; - if op.layout_changed || op.layout_patch != 0 { - child.update(cx, |child, _cx| child.apply_insert_layout(op)); - } - { - let node = child.read(cx); - let is_visible_portal = crate::extensions::component_portal( - &op.component, - &crate::extensions::parse_extension_props(&op.extension_props_json), - ) - .is_some_and(|portal| portal.visible); - if node.view.accessibility_modal || is_visible_portal { - self.accessibility_modal_tags.insert(op.tag); - } - } - if let Some(portal) = crate::extensions::component_portal( - &op.component, - &crate::extensions::parse_extension_props(&op.extension_props_json), - ) { - child.update(cx, |child, _cx| child.set_parent(None, None)); - if portal.visible { - self.overlay_host.update(cx, |host, cx| { - host.insert_portal(op.tag, child.clone()); - cx.notify(); - }); - } - continue; - } - let index = op.index.max(0) as usize; - if let Some(parent) = self.nodes.get(&op.parent_tag).cloned() { - self.add_native_surface_to_ancestors( - surface_id, - op.tag, - Some(op.parent_tag), - cx, - ); - let parent_ref = parent.downgrade(); - let previous_children = parent.read(cx).child_tags(); - parent.update(cx, |parent, cx| { - parent.insert_child(index, op.tag, child.clone()); - cx.notify(); - }); - child.update(cx, |child, _cx| { - child.set_parent(Some(parent_ref), Some(op.parent_tag)) - }); - // `on_insert` sees the tree with the splice applied, so - // both the parent and the child are re-recorded first. - self.record_subtree_nodes(&[op.parent_tag, op.tag], cx); - { - let inserted = child.read(cx).component_node_shallow(); - for observer in &observers { - let tree = self.tree_view(cx); - observer.on_insert( - &inserted, - op.parent_tag, - &previous_children, - &tree, - &handle, - cx, - ); - self.apply_commands(&commands, cx); - } - } - } else { - let root = self.root_for(surface_id, cx); - let (root_surface, before) = { - let root_ref = root.read(cx); - (root_ref.surface_id, root_ref.children.len()) - }; - log::info!( - "[store-debug] root child tag={} batch_surface={} root_surface={} children={}", - op.tag, - surface_id, - root_surface, - before - ); - root.update(cx, |root, cx| { - root.insert_child(index, op.tag, child.clone()); - cx.notify(); - }); - child.update(cx, |child, _cx| child.set_parent(None, None)); - self.add_native_surface_to_ancestors(surface_id, op.tag, None, cx); - } - } - MountKind::Remove => { - if crate::extensions::component_portal( - &op.component, - &crate::extensions::parse_extension_props(&op.extension_props_json), - ) - .is_some() - { - self.overlay_host.update(cx, |host, cx| { - host.remove_portal(op.tag); - cx.notify(); - }); - continue; - } - for observer in &observers { - let tree = self.tree_view(cx); - observer.on_remove_child( - op.tag, - op.parent_tag, - self.retained_subtrees.contains_key(&op.tag), - &tree, - &handle, - cx, - ); - self.apply_commands(&commands, cx); - } - if let Some(parent) = self.nodes.get(&op.parent_tag).cloned() { - self.remove_native_surface_from_ancestors( - surface_id, - op.tag, - Some(op.parent_tag), - cx, - ); - parent.update(cx, |parent, cx| { - parent.remove_child(op.tag); - cx.notify(); - }); - self.record_subtree_nodes(&[op.parent_tag], cx); - } else if let Some(root) = self.roots.get(&surface_id).cloned() { - self.remove_native_surface_from_ancestors(surface_id, op.tag, None, cx); - // The app's whole tree leaving its surface is what a blank - // window is: say so, with what is left, so a log answers - // "when did it go" without a debugger. - log::warn!( - "[store] surface {surface_id} root child tag={} ({}) removed; {} child(ren) were mounted", - op.tag, - op.component, - root.read(cx).children.len() - ); - root.update(cx, |root, cx| { - root.remove_child(op.tag); - cx.notify(); - }); - } - // The node itself stays mounted until Fabric deletes it, so - // its snapshot stays too: `is_live` and the parent's - // `children` kept answering this way when the tree was - // copied out on every call, and a retained card has to keep - // painting from its snapshot after the removal. - } - MountKind::Update => { - if let Some(node) = self.nodes.get(&op.tag).cloned() { - let previous_node = - (!observers.is_empty()).then(|| node.read(cx).component_node_shallow()); - let (counted, before, effects_before) = { - let node = node.read(cx); - ( - node.native_surface_counted, - node.native_surface_descendants, - node.effect_group_descendants, - ) - }; - let unchanged = { - let node = node.read(cx); - !op.props_changed - && !op.has_paragraph - && !op.layout_changed - && op.layout_patch == 0 - && op.host_changed == 0 - && op.host_changed_more.iter().all(|word| *word == 0) - && op.host_props_handle == 0 - && node.frame == op.frame - && node.has_extension_props_json(&op.extension_props_json) - }; - if !unchanged { - node.update(cx, |node, cx| { - node.update_from_op(op, Some(&mut **cx)); - node.sync_effect_group(); - cx.notify(); - node.notify_slot_owner(cx); - }); - } - let (after, effects_after) = { - let node = node.read(cx); - ( - node.native_surface_descendants, - node.effect_group_descendants, - ) - }; - if counted && (after != before || effects_after != effects_before) { - let parent_tag = node.read(cx).parent_tag_cached(); - self.carry_native_surface_delta( - surface_id, - parent_tag, - i64::from(after) - i64::from(before), - i64::from(effects_after) - i64::from(effects_before), - cx, - ); - } - let updated_node = previous_node - .as_ref() - .map(|_| node.read(cx).component_node_shallow()); - self.record_subtree_nodes(&[op.tag], cx); - if let (Some(updated_node), Some(previous_node)) = - (&updated_node, &previous_node) - { - for observer in &observers { - observer.on_update(updated_node, previous_node, &handle, cx); - self.apply_commands(&commands, cx); - } - } - if let Some(portal) = crate::extensions::component_portal( - &op.component, - &crate::extensions::parse_extension_props(&op.extension_props_json), - ) { - self.overlay_host.update(cx, |host, cx| { - if portal.visible { - host.insert_portal(op.tag, node.clone()); - } else { - host.remove_portal(op.tag); - } - cx.notify(); - }); - } - } - } - _ => log::warn!("[store] unknown mount kind {}", op.kind.repr), - } - // Fabric emits `topLayout` from `ShadowTree::emitLayoutEvents` using - // `BaseViewProps::onLayout`. Loom has no `ShadowTree`, so the store - // dispatches `topLayout` for any laid-out node that asked for `onLayout`. - if self.layout_event_owner == LayoutEventOwner::Store - && op.layout_changed - && !matches!(op.kind, MountKind::Delete | MountKind::Remove) - { - let wants_layout = self - .nodes - .get(&op.tag) - .is_some_and(|node| node.read(cx).view.on_layout); - if wants_layout { - self.host.dispatch_event( - op.tag, - "topLayout", - &serde_json::json!({ - "layout": { - "x": op.frame.x, - "y": op.frame.y, - "width": op.frame.w, - "height": op.frame.h - } - }), - ); - } - } - } - self.restore_scroll_anchors(anchors, cx); - for observer in &observers { - let tree = self.tree_view(cx); - observer.after_batch(&tree, &handle, cx); - self.apply_commands(&commands, cx); - } - self.refresh_inherited(surface_id, cx); - self.flush_host_reports(cx); - self.host.on_render(); - // A mount moves views against their scroll views; the store is borrowed - // here, so the modes are looked at once it is not. - cx.defer(crate::virtual_view::update); - let hook = self.frame_hook.clone(); - let target = self.window_for(surface_id).unwrap_or(self.window); - let _ = cx.update_window(target, |_root, window, _cx| { - hook.arm(window); - window.on_next_frame(crate::accessibility::sync_modal_focus); - }); - self.schedule_hover_retarget(cx); - crate::builtins::native_root::draw_settling_now(target, cx); - } - - /// The scroll views that keep their visible content in place, with the - /// item each is anchored to before a batch moves things. - fn capture_scroll_anchors(&self, cx: &Context) -> Vec { - self.nodes - .iter() - .filter_map(|(tag, node)| { - let node = node.read(cx); - let (min_index, threshold) = node.maintain_visible()?; - let (anchor, start) = node.visible_anchor(min_index, cx)?; - Some(ScrollAnchor { - scroll: *tag, - anchor, - start, - threshold, - }) - }) - .collect() - } - - fn restore_scroll_anchors(&mut self, anchors: Vec, cx: &mut Context) { - let host = self.host.clone(); - for anchor in anchors { - if let Some(node) = self.nodes.get(&anchor.scroll).cloned() { - node.update(cx, |node, cx| { - node.keep_anchor(anchor.anchor, anchor.start, anchor.threshold, &host, cx); - }); - } - } - } - - /// Applies every host component report queued so far, in order. - pub(crate) fn flush_host_reports(&mut self, cx: &mut Context) { - if !crate::host_component::any_host_components() { - return; - } - self.host_reports.release_flush(); - let reports = self.host_reports.take(); - let mut delivered = 0; - for report in reports { - // An event for a node that unmounted since it was sent has no one to - // receive it. - if let crate::host_component::HostReport::Event { tag, .. } = &report { - if !self.nodes.contains_key(tag) { - continue; - } - } - delivered += 1; - match report { - crate::host_component::HostReport::Size { tag, width, height } => { - crate::host_component::apply_size(tag, width, height); - if let Some(node) = self.nodes.get(&tag).cloned() { - node.update(cx, |node, _| node.set_intrinsic_size(width, height)); - } - } - crate::host_component::HostReport::Insets { - tag, - top, - right, - bottom, - left, - } => crate::host_component::apply_insets(tag, top, right, bottom, left), - crate::host_component::HostReport::Event { send, .. } => send(), - } - } - crate::counters::add(crate::counters::Counter::HostReportsDelivered, delivered); - } - - /// Lets an event sent outside a host call ask for its own delivery. - fn install_report_waker(&self, cx: &mut Context) { - let queue = std::rc::Rc::downgrade(&self.host_reports); - let app = cx.to_async(); - self.host_reports.install_waker(move || { - let (queue, app) = (queue.clone(), app.clone()); - app.foreground_executor() - .clone() - .spawn(async move { - app.update(|cx| { - let Some(queue) = queue.upgrade() else { return }; - queue.release_flush(); - if let Some(store) = store_from(cx) { - store.update(cx, |store, cx| { - store.flush_host_reports(cx); - // React Native buffers events until its next - // event beat; nothing else is about to tick it. - store.host.on_render(); - }); - } - }); - }) - .detach(); - }); - } - - fn apply_commands( - &mut self, - commands: &std::sync::Arc>>, - cx: &mut Context, - ) { - let queued: Vec = { - let mut queue = commands.lock().expect("command queue poisoned"); - queue.drain(..).collect() - }; - for command in queued { - match command { - crate::extensions::Command::Transition { tag, transition } => { - start_component_transition_here(self, tag, transition, cx); - } - crate::extensions::Command::ClearTransition { tag } => { - if let Some(node) = self.nodes.get(&tag).cloned() { - node.update(cx, |node, cx| { - node.transition = None; - cx.notify(); - }); - self.record_subtree_nodes(&[tag], cx); - } - } - crate::extensions::Command::Dispatch { tag, name, payload } => { - self.host.dispatch_event(tag, &name, &payload); - } - crate::extensions::Command::Wake => self.host.on_render(), - crate::extensions::Command::ReleaseRetained { tag } => { - release_retained_subtree_here(self, tag, cx); - } - crate::extensions::Command::After { duration, run } => { - cx.spawn(async move |_store, cx| { - cx.background_executor().timer(duration).await; - if let Some(run) = run.lock().ok().and_then(|mut slot| slot.take()) { - let _ = cx.update(|cx| run(cx)); - } - }) - .detach(); - } - } - } - } - - pub(crate) fn retain_subtree(&mut self, tag: i32, cx: &App) { - let mut descendants = Vec::new(); - let mut stack: Vec = self - .nodes - .get(&tag) - .map(|node| node.read(cx).child_tags()) - .unwrap_or_default(); - let mut seen = HashSet::new(); - while let Some(child) = stack.pop() { - if !seen.insert(child) { - continue; - } - descendants.push(child); - if let Some(node) = self.nodes.get(&child) { - stack.extend(node.read(cx).child_tags()); - } - } - self.retained_subtrees.insert(tag, descendants); - } - - pub(crate) fn tree_view<'a>(&'a self, cx: &App) -> crate::extensions::TreeView<'a> { - self.tree_view_at(None, cx) - } - - /// Re-records the tags a batch just changed, so the next `TreeView` reports - /// them without reading the entities. - /// - /// Every mutation a snapshot covers has to call this: the batch writes here - /// what it used to copy out of the whole tree on every operation. - fn record_subtree_nodes(&mut self, tags: &[i32], cx: &App) { - for tag in tags { - if let Some(entity) = self.nodes.get(tag) { - let snapshot = entity.read(cx).snapshot(); - self.snapshots.insert(*tag, snapshot); - } - } - } - - /// Forgets a node, and every tag below it that Fabric no longer reports. - fn drop_snapshot(&mut self, tag: i32) { - self.snapshots.remove(&tag); - } - - /// Re-reads every node, for the paths that mutate the tree outside a batch. - fn rebuild_snapshots(&mut self, cx: &App) { - self.snapshots.clear(); - for (tag, entity) in &self.nodes { - let snapshot = entity.read(cx).snapshot(); - self.snapshots.insert(*tag, snapshot); - } - } - - /// A view of the tree for a hook. - /// - /// The nodes are copied into `snapshots` as the batch applies them, before - /// any hook runs, because a hook is handed `&mut App` and a tree that kept - /// entity handles would let it read a node that the same call is updating. - pub(crate) fn tree_view_at<'a>( - &'a self, - current: Option<(i32, &'a RNNodeView)>, - cx: &App, - ) -> crate::extensions::TreeView<'a> { - let root_tags = self - .roots - .values() - .flat_map(|root| root.read(cx).children.iter().map(|(tag, _)| *tag)) - .collect(); - crate::extensions::TreeView { - nodes: std::borrow::Cow::Borrowed(&self.snapshots), - root_tags, - top_inset: self.top_inset, - animations_enabled: !cx.reduce_motion() - && !crate::animation_policy::animations_disabled(), - current: current.map(|(tag, node)| (tag, node.snapshot())), - retained: &self.retained_subtrees, - } - } - - pub(crate) fn animations_enabled(&self, cx: &App) -> bool { - !cx.reduce_motion() && !crate::animation_policy::animations_disabled() - } - - /// Writes a node only when its value changed, and notifies it only when a - /// value its own `render` reads changed. - pub(crate) fn refresh_inherited(&mut self, surface_id: i32, cx: &mut Context) { - let mut roots: Vec> = Vec::new(); - if let Some(root) = self.roots.get(&surface_id) { - roots.extend(root.read(cx).children.iter().map(|(_, node)| node.clone())); - } - for (_, portal) in self.overlay_host.read(cx).portals.iter() { - if portal.read(cx).surface_id == surface_id && portal.read(cx).parent.is_none() { - roots.push(portal.clone()); - } - } - // The pass runs while this entity is being updated, so `origin_frame` - // cannot read the store back out of the global; hand it the value. - let top_inset = self.top_inset; - let root_tags = self - .roots - .values() - .flat_map(|root| root.read(cx).children.iter().map(|(tag, _)| *tag)) - .collect(); - let animations_enabled = - !cx.reduce_motion() && !crate::animation_policy::animations_disabled(); - self.rebuild_snapshots(cx); - let tree = crate::extensions::TreeView { - nodes: std::borrow::Cow::Borrowed(&self.snapshots), - root_tags, - top_inset, - animations_enabled, - current: None, - retained: &self.retained_subtrees, - }; - for root in roots { - refresh_inherited_tree(root, top_inset, None, &tree, cx); - } - } -} - -/// One node's refreshed state, computed while the tree is alive and applied -/// after it is dropped. -struct InheritedUpdate { - node: Entity, - inherited: Inherited, - hides_self: bool, - renderer_frame: Option, - renderer_decoration: Option, - changed: bool, - render_affecting: bool, -} - -fn refresh_inherited_tree( - node: Entity, - top_inset: f32, - parent: Option<(Inherited, InheritInput)>, - tree: &crate::extensions::TreeView, - cx: &mut Context, -) { - let mut updates: Vec = Vec::new(); - let mut pending: Vec<(Entity, Option<(Inherited, InheritInput)>)> = - vec![(node, parent)]; - - while let Some((node, parent)) = pending.pop() { - let own = node.read(cx).inherit_input(tree); - let inherited = inherit(parent.as_ref().map(|(p, i)| (p, i)), &own); - let children: Vec> = node - .read(cx) - .children - .iter() - .map(|(_, child)| child.clone()) - .collect(); - let modal_children = children - .iter() - .filter(|child| child.read(cx).view.accessibility_modal) - .count(); - let (renderer_frame, renderer_decoration, changed, render_affecting) = { - let view = node.read(cx); - let frame = crate::extensions::component_renderer(&view.component) - .and_then(|r| r.layout_frame(&view.component_node_shallow(), tree)); - let decoration = crate::extensions::component_renderer(&view.component) - .map(|r| r.decorate(&view.component_node_shallow(), tree)); - ( - frame, - decoration, - !view.inherited.same(&inherited), - !view.inherited.same_render_affecting(&inherited), - ) - }; - for child in children { - let child_is_modal = child.read(cx).view.accessibility_modal; - let mut parent_input = own.clone(); - parent_input.other_modal_child = modal_children > usize::from(child_is_modal); - pending.push((child, Some((inherited.clone(), parent_input)))); - } - updates.push(InheritedUpdate { - node, - inherited, - hides_self: own.hides_subtree, - renderer_frame, - renderer_decoration, - changed, - render_affecting, - }); - } - - for update in updates { - update.node.update(cx, |view, cx| { - let renderer_changed = view.renderer_frame != update.renderer_frame - || view.renderer_decoration != update.renderer_decoration; - view.renderer_frame = update.renderer_frame; - view.renderer_decoration = update.renderer_decoration; - if update.changed { - view.inherited = update.inherited.clone(); - view.inherited.window_top_inset = top_inset; - view.inherited.hides_subtree_self = update.hides_self; - } - if update.render_affecting || renderer_changed { - cx.notify(); - } - }); - } -} - -pub(crate) fn start_component_transition( - store: &Entity, - tag: i32, - transition: crate::extensions::Transition, - cx: &mut App, -) { - store.update(cx, |store, cx| { - if let Some(node) = store.nodes.get(&tag).cloned() { - node.update(cx, |node, cx| { - let forward = transition.to.opacity >= transition.from.opacity; - node.transition = Some((transition, Instant::now())); - node.transition_forward = forward; - cx.notify(); - }); - store.transitioning.borrow_mut().insert(tag); - store.record_subtree_nodes(&[tag], cx); - } - }); -} - -fn start_component_transition_here( - store: &mut ViewStore, - tag: i32, - transition: crate::extensions::Transition, - cx: &mut Context, -) { - if let Some(node) = store.nodes.get(&tag).cloned() { - node.update(cx, |node, cx| { - node.transition = Some((transition, Instant::now())); - cx.notify(); - }); - store.transitioning.borrow_mut().insert(tag); - store.record_subtree_nodes(&[tag], cx); - } -} - -pub(crate) fn clear_node_transition(store: &Entity, tag: i32, cx: &mut App) { - store.update(cx, |store, cx| { - if let Some(node) = store.nodes.get(&tag).cloned() { - node.update(cx, |node, cx| { - node.transition = None; - cx.notify(); - }); - store.record_subtree_nodes(&[tag], cx); - } - }); -} - -pub(crate) fn request_retain_subtree(tag: i32) { - PENDING_RETAIN.with(|pending| pending.borrow_mut().insert(tag)); -} - -thread_local! { - static PENDING_RETAIN: std::cell::RefCell> = - std::cell::RefCell::new(std::collections::HashSet::new()); -} - -pub(crate) fn release_retained_subtree(store: &Entity, tag: i32, cx: &mut App) { - store.update(cx, |store, cx| { - release_retained_subtree_here(store, tag, cx) - }); -} - -fn release_retained_subtree_here(store: &mut ViewStore, tag: i32, cx: &mut Context) { - let Some(descendants) = store.retained_subtrees.remove(&tag) else { - return; - }; - let _ = descendants; - let parent_tag = store - .nodes - .get(&tag) - .and_then(|node| node.read(cx).parent_tag_cached()); - let surface_id = store - .nodes - .get(&tag) - .map(|node| node.read(cx).surface_id) - .unwrap_or(rn_gpui_sys::ALL_SURFACES); - store.remove_native_surface_from_ancestors(surface_id, tag, parent_tag, cx); - if let Some(parent) = store - .nodes - .get(&tag) - .and_then(|node| node.read(cx).parent.clone()) - .and_then(|parent| parent.upgrade()) - { - parent.update(cx, |parent, cx| { - parent.remove_child(tag); - cx.notify(); - }); - } - let surface_id = store - .nodes - .get(&tag) - .map(|node| node.read(cx).surface_id) - .unwrap_or(rn_gpui_sys::ALL_SURFACES); - log::info!("[extensions] retained subtree released tag={tag}"); - store.refresh_inherited(surface_id, cx); -} - -pub(crate) fn after_on_store( - store: Entity, - duration: std::time::Duration, - cx: &mut gpui::App, - f: impl FnOnce(&mut gpui::App) + 'static, -) { - let mut f = Some(f); - store.update(cx, |_: &mut ViewStore, cx: &mut Context| { - cx.spawn(async move |_store, cx| { - cx.background_executor().timer(duration).await; - if let Some(f) = f.take() { - let _ = cx.update(|cx| f(cx)); - } - }) - .detach(); - }); -} - -#[cfg(test)] -pub(crate) fn test_store_handle(cx: &mut gpui::TestAppContext) -> crate::extensions::StoreHandle { - let overlay_host = cx.new(|_| OverlayHost::new()); - let window = cx.open_window(gpui::size(gpui::px(120.0), gpui::px(100.0)), { - let overlay_host = overlay_host.clone(); - move |_, _| SurfaceRootView::new(1).with_overlay_host(overlay_host) - }); - let root = window.root(cx).unwrap(); - let any_window: gpui::AnyWindowHandle = window.into(); - let host = crate::host::Host::test_stub(); - let frame_hook = FrameHook::new(host.clone()); - let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host, LayoutEventOwner::ShadowTree)); - cx.update(|cx| cx.set_global(StoreGlobal(store.clone()))); - let _ = root; - crate::extensions::StoreHandle::new(store.downgrade()) -} - -#[cfg(test)] -mod test_app_context_tests { - use super::{ - LayoutEventOwner, OverlayHost, StoreGlobal, SurfaceKind, SurfaceRootView, ViewStore, - }; - use crate::{frame::FrameHook, host::Host}; - use gpui::{px, AppContext, TestAppContext}; - use rn_gpui_sys::ffi::{MountBatch, MountKind, MountOp, ParagraphFlat, RectF, ViewPropsFlat}; - - fn op(kind: MountKind) -> MountOp { - MountOp { - kind, - tag: 101, - parent_tag: -1, - index: 0, - component: "View".into(), - frame: RectF { - x: 10.0, - y: 12.0, - w: 40.0, - h: 30.0, - }, - props_changed: true, - view: ViewPropsFlat { - opacity: 1.0, - ..Default::default() - }, - extension_props_json: String::new(), - host_index: -1, - host_props_handle: 0, - host_emitter_handle: 0, - host_changed: 0, - host_changed_more: Vec::new(), - has_paragraph: false, - paragraph: ParagraphFlat::default(), - layout_changed: false, - layout_patch: 0, - } - } - - /// The registry index each native test component was declared at. - fn native_indices() -> &'static std::sync::Mutex> { - static INDICES: std::sync::OnceLock< - std::sync::Mutex>, - > = std::sync::OnceLock::new(); - INDICES.get_or_init(Default::default) - } - - /// Declares a host component whose content the OS composites, for the - /// counter tests below. Declared once per name at a fresh index; an op for it - /// carries that index, as a real one does. - fn register_native_component(name: &str) { - let mut indices = native_indices().lock().unwrap(); - if indices.contains_key(name) { - return; - } - let index = 1000 + indices.len() as u32; - crate::host_component::declare_host_component( - index, - name, - crate::host_component::HostComponentOptions { - native_surface: true, - ..Default::default() - }, - ); - indices.insert(name.to_string(), index as i32); - } - - /// Builds a store whose surface root is a real window root, and returns - /// both the store and that root. - fn store_with_layout_owner( - cx: &mut TestAppContext, - layout_event_owner: LayoutEventOwner, - ) -> (gpui::Entity, gpui::Entity) { - let overlay_host = cx.new(|_| OverlayHost::new()); - let window = cx.open_window(gpui::size(px(120.0), px(100.0)), { - let overlay_host = overlay_host.clone(); - move |_, _| SurfaceRootView::new(1).with_overlay_host(overlay_host) - }); - let root = window.root(cx).expect("surface root exists"); - let any_window: gpui::AnyWindowHandle = window.into(); - let host = Host::test_stub(); - let frame_hook = FrameHook::new(host.clone()); - let store = cx.new(|_| { - ViewStore::new( - host, - any_window, - frame_hook, - overlay_host, - layout_event_owner, - ) - }); - cx.update(|cx| cx.set_global(StoreGlobal(store.clone()))); - store.update(cx, |store, _| store.register_root(1, root.clone())); - (store, root) - } - - fn store_with_root( - cx: &mut TestAppContext, - ) -> (gpui::Entity, gpui::Entity) { - store_with_layout_owner(cx, LayoutEventOwner::ShadowTree) - } - - /// Applies a batch of `(kind, tag, parent)` triples. - fn apply(cx: &mut TestAppContext, store: &gpui::Entity, ops: Vec) { - store.update(cx, |store, cx| { - store.apply_batch( - MountBatch { - surface_id: 1, - ops, - ..Default::default() - }, - cx, - ); - }); - } - - fn create(tag: i32, component: &'static str) -> MountOp { - let mut create = op(MountKind::Create); - create.tag = tag; - create.component = component.into(); - if let Some(index) = native_indices().lock().unwrap().get(component) { - create.host_index = *index; - } - create - } - - fn insert(tag: i32, parent: i32) -> MountOp { - let mut insert = op(MountKind::Insert); - insert.tag = tag; - insert.parent_tag = parent; - insert - } - - fn remove(tag: i32, parent: i32) -> MountOp { - let mut remove = op(MountKind::Remove); - remove.tag = tag; - remove.parent_tag = parent; - remove - } - - fn delete(tag: i32) -> MountOp { - let mut delete = op(MountKind::Delete); - delete.tag = tag; - delete - } - - /// A counter read off one node, or `None` if it is not mounted. - fn count_of(cx: &mut TestAppContext, store: &gpui::Entity, tag: i32) -> Option { - cx.read_entity(store, |store, app| { - store - .nodes - .get(&tag) - .map(|node| node.read(app).native_surface_descendants) - }) - } - - /// An embedded surface's root belongs to the `ReactSurface` that placed it: - /// it must not also be shown through the window's overlay slot, where it - /// would cover the window it was meant to sit inside. - #[gpui::test] - fn an_embedded_root_is_not_an_overlay(cx: &mut TestAppContext) { - let (store, _root) = store_with_root(cx); - let (embedded, overlay_count) = store.update(cx, |store, cx| { - let root = store.ensure_embedded_root(5, cx); - (root, store.overlay_host.read(cx).overlay_count()) - }); - assert_eq!(overlay_count, 0, "an embedded surface is not an overlay"); - assert_eq!( - embedded.read_with(cx, |root, _| root.kind), - SurfaceKind::Embedded - ); - - let (logbox, overlay_count) = store.update(cx, |store, cx| { - let root = store.ensure_root(2, cx); - (root, store.overlay_host.read(cx).overlay_count()) - }); - assert_eq!(overlay_count, 1); - assert_eq!( - logbox.read_with(cx, |root, _| root.kind), - SurfaceKind::Overlay - ); - } - - /// The surface root's own count. - fn root_count(cx: &mut TestAppContext, root: &gpui::Entity) -> u32 { - root.read_with(cx, |root, _| root.native_surfaces) - } - - /// The effect-group count read off one node. - fn effect_count_of( - cx: &mut TestAppContext, - store: &gpui::Entity, - tag: i32, - ) -> Option { - cx.read_entity(store, |store, app| { - store - .nodes - .get(&tag) - .map(|node| node.read(app).effect_group_descendants) - }) - } - - fn translucent(mut create: MountOp) -> MountOp { - create.view.opacity = 0.5; - create - } - - #[gpui::test] - fn a_translucent_node_is_counted_up_the_parent_chain_and_off_again(cx: &mut TestAppContext) { - let (store, _root) = store_with_root(cx); - apply( - cx, - &store, - vec![ - create(1, "View"), - insert(1, -1), - create(2, "View"), - insert(2, 1), - translucent(create(3, "View")), - insert(3, 2), - ], - ); - assert_eq!(effect_count_of(cx, &store, 3), Some(1), "its own"); - assert_eq!(effect_count_of(cx, &store, 2), Some(1)); - assert_eq!(effect_count_of(cx, &store, 1), Some(1)); - - apply(cx, &store, vec![remove(3, 2)]); - assert_eq!(effect_count_of(cx, &store, 2), Some(0)); - assert_eq!(effect_count_of(cx, &store, 1), Some(0)); - } - - #[gpui::test] - fn a_node_that_becomes_opaque_gives_its_count_back(cx: &mut TestAppContext) { - let (store, _root) = store_with_root(cx); - apply( - cx, - &store, - vec![ - create(1, "View"), - insert(1, -1), - translucent(create(2, "View")), - insert(2, 1), - ], - ); - assert_eq!(effect_count_of(cx, &store, 1), Some(1)); - - let mut opaque = op(MountKind::Update); - opaque.tag = 2; - opaque.view.opacity = 1.0; - apply(cx, &store, vec![opaque]); - assert_eq!(effect_count_of(cx, &store, 2), Some(0)); - assert_eq!(effect_count_of(cx, &store, 1), Some(0)); - - let mut faded = op(MountKind::Update); - faded.tag = 2; - faded.view.opacity = 0.25; - apply(cx, &store, vec![faded]); - assert_eq!(effect_count_of(cx, &store, 1), Some(1)); - } - - #[gpui::test] - fn a_native_surface_is_counted_up_the_parent_chain(cx: &mut TestAppContext) { - register_native_component("CounterNative"); - let (store, root) = store_with_root(cx); - - apply( - cx, - &store, - vec![ - create(1, "View"), - insert(1, -1), - create(2, "View"), - insert(2, 1), - create(3, "View"), - insert(3, 2), - create(4, "Text"), - insert(4, 2), - create(5, "CounterNative"), - insert(5, 3), - ], - ); - - assert_eq!( - count_of(cx, &store, 5), - Some(1), - "the surface itself counts" - ); - assert_eq!( - count_of(cx, &store, 4), - Some(0), - "a GPUI-only node holds none" - ); - assert_eq!(count_of(cx, &store, 3), Some(1)); - assert_eq!(count_of(cx, &store, 2), Some(1)); - assert_eq!(count_of(cx, &store, 1), Some(1)); - assert_eq!(root_count(cx, &root), 1, "the root counts it too"); - } - - #[gpui::test] - fn two_native_surfaces_under_one_ancestor_both_count(cx: &mut TestAppContext) { - register_native_component("CounterNativeTwo"); - let (store, root) = store_with_root(cx); - - apply( - cx, - &store, - vec![ - create(1, "View"), - insert(1, -1), - create(2, "CounterNativeTwo"), - insert(2, 1), - create(3, "CounterNativeTwo"), - insert(3, 1), - ], - ); - - assert_eq!( - count_of(cx, &store, 1), - Some(2), - "the count is how many surfaces are below, not whether there is one" - ); - assert_eq!(root_count(cx, &root), 2); - } - - #[gpui::test] - fn the_counter_reports_a_crossing_only_at_zero(cx: &mut TestAppContext) { - register_native_component("CrossingNative"); - let (store, root) = store_with_root(cx); - apply( - cx, - &store, - vec![ - create(1, "View"), - create(2, "View"), - insert(1, -1), - insert(2, 1), - create(3, "CrossingNative"), - insert(3, 2), - ], - ); - let node = cx - .read_entity(&store, |store, _| store.nodes.get(&1).cloned()) - .unwrap(); - - let second = node.update(cx, |node, _cx| node.add_native_surface_descendants(1)); - assert!(!second, "1 -> 2 changes no reader's answer"); - - let back = node.update(cx, |node, _cx| node.sub_native_surface_descendants(1)); - assert!(!back, "2 -> 1 changes no reader's answer either"); - - let empty = node.update(cx, |node, _cx| node.sub_native_surface_descendants(1)); - assert!(empty, "1 -> 0 is the crossing a ScrollView must react to"); - - let first = node.update(cx, |node, _cx| node.add_native_surface_descendants(1)); - assert!(first, "0 -> 1 is the other crossing"); - let _ = (&store, &root); - } - - #[gpui::test] - fn removing_a_native_surface_takes_it_off_every_ancestor(cx: &mut TestAppContext) { - register_native_component("CounterNativeRemove"); - let (store, root) = store_with_root(cx); - - apply( - cx, - &store, - vec![ - create(1, "View"), - insert(1, -1), - create(2, "View"), - insert(2, 1), - create(3, "CounterNativeRemove"), - insert(3, 2), - ], - ); - assert_eq!(count_of(cx, &store, 1), Some(1)); - assert_eq!(root_count(cx, &root), 1); - - apply(cx, &store, vec![remove(3, 2)]); - - assert_eq!(count_of(cx, &store, 2), Some(0), "the parent drops it"); - assert_eq!(count_of(cx, &store, 1), Some(0), "so does the grandparent"); - assert_eq!(root_count(cx, &root), 0, "and the root"); - - apply(cx, &store, vec![delete(3)]); - assert_eq!( - count_of(cx, &store, 1), - Some(0), - "a delete after a remove takes nothing more off" - ); - } - - #[gpui::test] - fn deleting_without_a_remove_still_takes_the_surface_off(cx: &mut TestAppContext) { - register_native_component("CounterNativeDelete"); - let (store, root) = store_with_root(cx); - - apply( - cx, - &store, - vec![ - create(1, "View"), - insert(1, -1), - create(2, "CounterNativeDelete"), - insert(2, 1), - ], - ); - assert_eq!(root_count(cx, &root), 1); - - apply(cx, &store, vec![delete(2)]); - - assert_eq!( - count_of(cx, &store, 1), - Some(0), - "a delete with no remove still gives the count back" - ); - assert_eq!(root_count(cx, &root), 0); - } - - #[gpui::test] - fn reparenting_a_native_surface_does_not_double_count(cx: &mut TestAppContext) { - register_native_component("CounterNativeMove"); - let (store, root) = store_with_root(cx); - - apply( - cx, - &store, - vec![ - create(1, "View"), - insert(1, -1), - create(2, "View"), - insert(2, 1), - create(3, "View"), - insert(3, 1), - create(4, "CounterNativeMove"), - insert(4, 2), - ], - ); - assert_eq!(count_of(cx, &store, 2), Some(1)); - assert_eq!(count_of(cx, &store, 3), Some(0)); - assert_eq!(root_count(cx, &root), 1); - - apply(cx, &store, vec![remove(4, 2), insert(4, 3)]); - - assert_eq!(count_of(cx, &store, 2), Some(0), "the old parent lets go"); - assert_eq!( - count_of(cx, &store, 3), - Some(1), - "the new parent picks it up" - ); - assert_eq!( - count_of(cx, &store, 1), - Some(1), - "the shared ancestor is unchanged, not doubled" - ); - assert_eq!(root_count(cx, &root), 1); - } - - #[gpui::test] - fn an_event_sent_after_its_node_unmounted_is_dropped(cx: &mut TestAppContext) { - let (store, _root) = store_with_root(cx); - register_native_component("EventSenderProbe"); - apply(cx, &store, vec![create(1, "View"), insert(1, -1)]); - - let delivered = std::rc::Rc::new(std::cell::Cell::new(0)); - let (sender, queue) = store.read_with(cx, |store, _| { - let context = crate::host_component::HostContext::queued(1, store.host_reports.clone()); - (context.event_sender(), store.host_reports.clone()) - }); - for _ in 0..2 { - let delivered = delivered.clone(); - sender.send(move || delivered.set(delivered.get() + 1)); - } - store.update(cx, |store, cx| store.flush_host_reports(cx)); - assert_eq!(delivered.get(), 2, "the node is mounted"); - - apply(cx, &store, vec![remove(1, -1), delete(1)]); - let late = delivered.clone(); - sender.send(move || late.set(late.get() + 1)); - store.update(cx, |store, cx| store.flush_host_reports(cx)); - assert_eq!(delivered.get(), 2, "the node is gone"); - assert!(queue.is_empty()); - } - - #[gpui::test] - fn a_tree_with_no_native_surface_counts_nothing(cx: &mut TestAppContext) { - let (store, root) = store_with_root(cx); - - apply( - cx, - &store, - vec![ - create(1, "View"), - insert(1, -1), - create(2, "View"), - insert(2, 1), - create(3, "Text"), - insert(3, 2), - ], - ); - - for tag in [1, 2, 3] { - assert_eq!( - count_of(cx, &store, tag), - Some(0), - "tag {tag} must not report a surface it does not hold" - ); - } - assert_eq!(root_count(cx, &root), 0); - assert!( - !store.read_with(cx, |store, app| store - .nodes - .get(&1) - .expect("mounted") - .read(app) - .subtree_renders_native_surface()), - "a ScrollView over this tree stays on the scroll-layer path" - ); - } - - #[gpui::test] - #[gpui::test] - fn test_app_context_mounts_a_view_and_resolves_its_pointer_target(cx: &mut TestAppContext) { - let overlay_host = cx.new(|_| OverlayHost::new()); - let window = cx.open_window(gpui::size(px(120.0), px(100.0)), { - let overlay_host = overlay_host.clone(); - move |_, _| SurfaceRootView::new(1).with_overlay_host(overlay_host) - }); - let root = window.root(cx).unwrap(); - let any_window: gpui::AnyWindowHandle = window.into(); - let host = Host::test_stub(); - let frame_hook = FrameHook::new(host.clone()); - let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host, LayoutEventOwner::ShadowTree)); - cx.update(|cx| cx.set_global(StoreGlobal(store.clone()))); - store.update(cx, |store, _| store.register_root(1, root)); - - cx.update_entity(&store, |store, cx| { - store.apply_batch( - MountBatch { - surface_id: 1, - ops: vec![op(MountKind::Create), op(MountKind::Insert)], - ..Default::default() - }, - cx, - ); - }); - - cx.update_window(any_window, |_, window, app| { - let needs_clear = window.draw(app); - needs_clear.clear(app); - window.dispatch_event( - gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent { - position: gpui::point(px(20.0), px(20.0)), - pressed_button: None, - ..Default::default() - }), - app, - ); - }) - .unwrap(); - let hit = cx.read_entity(&store, |store, _| store.hovered.borrow().first().copied()); - assert_eq!(hit, Some(101)); - } - - /// A decoration that changes without any inherited value changing must - /// still be stored, and must notify. - /// - /// The pass used to write the renderer's answer only when the *inherited* - /// state changed, so a module whose decoration depends on transition - /// progress kept its answer from the start of the transition forever. - #[gpui::test] - fn refresh_stores_a_decoration_that_changed_alone(cx: &mut TestAppContext) { - use std::sync::atomic::{AtomicU32, Ordering}; - use std::sync::Arc; - - static COLOUR: AtomicU32 = AtomicU32::new(0); - - struct Probe; - impl crate::extensions::ComponentRenderer for Probe { - fn render( - &self, - _node: &crate::extensions::ComponentNode, - _window: &mut gpui::Window, - _cx: &mut gpui::App, - ) -> Option { - None - } - - fn decorate( - &self, - _node: &crate::extensions::ComponentNode, - _tree: &crate::extensions::TreeView, - ) -> crate::extensions::Decoration { - crate::extensions::Decoration { - background: Some(COLOUR.load(Ordering::SeqCst)), - ..Default::default() - } - } - } - - let overlay_host = cx.new(|_| OverlayHost::new()); - let window = cx.open_window(gpui::size(px(120.0), px(100.0)), { - let overlay_host = overlay_host.clone(); - move |_, _| SurfaceRootView::new(1).with_overlay_host(overlay_host) - }); - let root = window.root(cx).unwrap(); - let any_window: gpui::AnyWindowHandle = window.into(); - let host = Host::test_stub(); - let frame_hook = FrameHook::new(host.clone()); - let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host, LayoutEventOwner::ShadowTree)); - cx.update(|cx| cx.set_global(StoreGlobal(store.clone()))); - store.update(cx, |store, _| store.register_root(1, root)); - - crate::extensions::register_component_renderer("DecorationProbe", Arc::new(Probe)); - let mut create = op(MountKind::Create); - create.component = "DecorationProbe".into(); - cx.update_entity(&store, |store, cx| { - store.apply_batch( - MountBatch { - surface_id: 1, - ops: vec![create, op(MountKind::Insert)], - ..Default::default() - }, - cx, - ); - }); - - let read = |cx: &mut TestAppContext| { - cx.read_entity(&store, |store, _| { - store - .nodes - .get(&101) - .map(|node| node.read_with(cx, |n, _| n.renderer_decoration)) - .flatten() - }) - }; - assert_eq!(read(cx).and_then(|d| d.background), Some(0)); - - // Only the decoration changes; no inherited value moves. - COLOUR.store(0xff00ff00, Ordering::SeqCst); - cx.update_entity(&store, |store, cx| { - store.refresh_inherited(super::APP_SURFACE_ID, cx); - }); - assert_eq!( - read(cx).and_then(|d| d.background), - Some(0xff00ff00), - "a decoration that changed alone must be stored" - ); - } - - #[gpui::test] - fn test_driver_frames_follow_transforms_and_visibility_clips(cx: &mut TestAppContext) { - let overlay_host = cx.new(|_| OverlayHost::new()); - let window = cx.open_window(gpui::size(px(120.0), px(100.0)), { - let overlay_host = overlay_host.clone(); - move |_, _| SurfaceRootView::new(1).with_overlay_host(overlay_host) - }); - let root = window.root(cx).expect("surface root exists"); - let any_window: gpui::AnyWindowHandle = window.into(); - let host = Host::test_stub(); - let frame_hook = FrameHook::new(host.clone()); - let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host, LayoutEventOwner::ShadowTree)); - cx.update(|cx| cx.set_global(StoreGlobal(store.clone()))); - store.update(cx, |store, _| store.register_root(1, root)); - - let mut create = op(MountKind::Create); - create.view.has_transform = true; - create.view.transform = [ - 2.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 8.0, 6.0, 0.0, 1.0, - ]; - let mut insert = op(MountKind::Insert); - insert.view = create.view.clone(); - cx.update_entity(&store, |store, cx| { - store.apply_batch( - MountBatch { - surface_id: 1, - ops: vec![create, insert], - ..Default::default() - }, - cx, - ); - }); - - let transformed = cx.read_entity(&store, |store, app| { - crate::test_driver::node_frame(store, 101, app).expect("mounted frame") - }); - // Scaled about the centre of the 40 x 30 box at (10, 12), then moved by (8, 6). - assert_eq!((transformed.x, transformed.y), (-2.0, 25.5)); - assert_eq!((transformed.w, transformed.h), (80.0, 15.0)); - - let clipped = cx.read_entity(&store, |store, app| { - crate::test_driver::node_visible_frame( - store, - 101, - RectF { - x: 0.0, - y: 0.0, - w: 40.0, - h: 30.0, - }, - app, - ) - }); - let clipped = clipped.expect("transformed frame intersects viewport"); - assert_eq!((clipped.x, clipped.y), (0.0, 25.5)); - assert_eq!((clipped.w, clipped.h), (40.0, 4.5)); - - let outside = cx.read_entity(&store, |store, app| { - crate::test_driver::node_visible_frame( - store, - 101, - RectF { - x: 100.0, - y: 80.0, - w: 20.0, - h: 20.0, - }, - app, - ) - }); - assert!(outside.is_none(), "off-window view must be invisible"); - - let mut hidden = op(MountKind::Update); - hidden.view.display_none = true; - cx.update_entity(&store, |store, cx| { - store.apply_batch( - MountBatch { - surface_id: 1, - ops: vec![hidden], - ..Default::default() - }, - cx, - ); - }); - let hidden_frame = cx.read_entity(&store, |store, app| { - crate::test_driver::node_visible_frame( - store, - 101, - RectF { - x: 0.0, - y: 0.0, - w: 120.0, - h: 100.0, - }, - app, - ) - }); - assert!( - hidden_frame.is_none(), - "display:none view must be invisible" - ); - } - - /// Opening a view of the tree must not copy the tree. - /// - /// Core opens one for every observer on every insert and every remove, so - /// anything that copies every node per call makes a first mount of N nodes - /// cost O(N²). The view borrows the map the store keeps instead. - #[gpui::test] - fn opening_a_tree_view_copies_no_nodes(cx: &mut TestAppContext) { - let overlay_host = cx.new(|_| OverlayHost::new()); - let window = cx.open_window(gpui::size(px(120.0), px(100.0)), { - let overlay_host = overlay_host.clone(); - move |_, _| SurfaceRootView::new(1).with_overlay_host(overlay_host) - }); - let root = window.root(cx).unwrap(); - let any_window: gpui::AnyWindowHandle = window.into(); - let host = Host::test_stub(); - let frame_hook = FrameHook::new(host.clone()); - let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host, LayoutEventOwner::ShadowTree)); - cx.update(|cx| cx.set_global(StoreGlobal(store.clone()))); - store.update(cx, |store, _| store.register_root(1, root)); - - // Mount a tree big enough that a per-call copy would be obvious. - let mut ops = Vec::new(); - let mut parent = op(MountKind::Create); - parent.tag = 1; - ops.push(parent); - let mut parent_insert = op(MountKind::Insert); - parent_insert.tag = 1; - ops.push(parent_insert); - for row in 0..200i32 { - let tag = 1000 + row; - let mut create = op(MountKind::Create); - create.tag = tag; - create.component = "Text".into(); - create.parent_tag = 1; - ops.push(create); - let mut insert = op(MountKind::Insert); - insert.tag = tag; - insert.component = "Text".into(); - insert.parent_tag = 1; - insert.index = row; - ops.push(insert); - } - cx.update_entity(&store, |store, cx| { - store.apply_batch( - MountBatch { - surface_id: 1, - ops, - ..Default::default() - }, - cx, - ); - }); - - // Two hundred children, all in one view. - let copied = cx.read_entity(&store, |store, app| { - crate::node_view::reset_snapshot_count(); - let tree = store.tree_view(app); - let children = tree.children(1).len(); - assert_eq!(children, 200); - crate::node_view::snapshot_count() - }); - assert_eq!( - copied, 0, - "opening a tree view copied {copied} nodes; it must borrow the store's own map" - ); - - // A hook that needs one node's own fields still pays for one node, not - // for the tree. `tree_view_at` supplies the node core is holding. - let copied = cx.read_entity(&store, |store, app| { - let node = store.nodes.get(&1005).expect("row is mounted"); - let borrowed = node.read(app); - crate::node_view::reset_snapshot_count(); - let tree = store.tree_view_at(Some((1005, &borrowed)), app); - assert!(tree.node(1005).is_some()); - crate::node_view::snapshot_count() - }); - assert_eq!( - copied, 1, - "a tree built around one node copies that node and nothing else" - ); - } - - /// A hook must see the tree as it is, not as it was before the batch. - /// - /// The snapshots a `TreeView` borrows are now written per operation instead - /// of copied from every node per operation. A missed write shows up here as - /// a hook reading a stale parent, child list or frame, because the hooks all - /// run inside the batch, before the trailing rebuild. - #[gpui::test] - fn the_snapshot_map_follows_each_operation(cx: &mut TestAppContext) { - use crate::extensions::{ComponentNode, StoreHandle, StoreObserver, TreeView}; - use std::sync::{Arc, Mutex}; - - // The observer registry is process-wide, so no other test may install - // one while this runs. - let _exclusive = crate::extensions::exclusive_observers(); - - #[derive(Default)] - struct Seen { - /// What the tree said after each insert, in order. - inserts: Vec, - /// What the tree said at the end of every batch, in order. - batches: Vec, - /// What the tree said after the remove. - remove: Option, - /// What the tree said after the delete. - delete: Option, - } - - struct Probe(Arc>); - - fn describe(tree: &TreeView, tag: i32, parent: i32) -> String { - format!( - "parent={:?} children={:?} frame={}x{}", - tree.children(parent), - tree.children(tag), - tree.node(tag).map(|n| n.frame.w).unwrap_or(-1.0), - tree.node(tag).map(|n| n.frame.h).unwrap_or(-1.0) - ) - } - - impl StoreObserver for Probe { - fn on_mount(&self, _node: &ComponentNode, _h: &StoreHandle, _cx: &mut gpui::App) {} - fn on_update( - &self, - _node: &ComponentNode, - _previous: &ComponentNode, - _h: &StoreHandle, - _cx: &mut gpui::App, - ) { - } - fn after_batch(&self, tree: &TreeView, _h: &StoreHandle, _cx: &mut gpui::App) { - if tree.node(7202).is_none() && tree.node(7101).is_none() { - return; - } - self.0 - .lock() - .unwrap() - .batches - .push(describe(tree, 7202, 7101)); - } - fn on_remove(&self, tag: i32, _h: &StoreHandle, _cx: &mut gpui::App) { - if tag == 7202 { - self.0.lock().unwrap().delete = Some("deleted".into()); - } - } - fn on_insert( - &self, - child: &ComponentNode, - parent: i32, - _previous_children: &[i32], - tree: &TreeView, - _h: &StoreHandle, - _cx: &mut gpui::App, - ) { - // Other tests run their own batches against this process-wide - // registry, so only this test's own parent is recorded. - if parent != 7101 { - return; - } - self.0 - .lock() - .unwrap() - .inserts - .push(describe(tree, child.tag, parent)); - } - fn on_remove_child( - &self, - child: i32, - parent: i32, - _retained: bool, - tree: &TreeView, - _h: &StoreHandle, - _cx: &mut gpui::App, - ) { - if child == 7202 { - self.0.lock().unwrap().remove = Some(describe(tree, child, parent)); - } - } - } - - let seen = Arc::new(Mutex::new(Seen::default())); - crate::extensions::register_store_observer(Arc::new(Probe(seen.clone()))); - - let overlay_host = cx.new(|_| OverlayHost::new()); - let window = cx.open_window(gpui::size(px(120.0), px(100.0)), { - let overlay_host = overlay_host.clone(); - move |_, _| SurfaceRootView::new(1).with_overlay_host(overlay_host) - }); - let root = window.root(cx).unwrap(); - let any_window: gpui::AnyWindowHandle = window.into(); - let host = Host::test_stub(); - let frame_hook = FrameHook::new(host.clone()); - let store = cx.new(|_| ViewStore::new(host, any_window, frame_hook, overlay_host, LayoutEventOwner::ShadowTree)); - cx.update(|cx| cx.set_global(StoreGlobal(store.clone()))); - store.update(cx, |store, _| store.register_root(1, root)); - - let mut create_parent = op(MountKind::Create); - create_parent.tag = 7101; - let mut insert_parent = op(MountKind::Insert); - insert_parent.tag = 7101; - let mut create_child = op(MountKind::Create); - create_child.tag = 7202; - create_child.component = "Text".into(); - create_child.parent_tag = 7101; - create_child.frame = RectF { - x: 4.0, - y: 6.0, - w: 20.0, - h: 10.0, - }; - let mut insert_child = op(MountKind::Insert); - insert_child.tag = 7202; - insert_child.parent_tag = 7101; - insert_child.component = "Text".into(); - cx.update_entity(&store, |store, cx| { - store.apply_batch( - MountBatch { - surface_id: 1, - ops: vec![create_parent, insert_parent, create_child, insert_child], - ..Default::default() - }, - cx, - ); - }); - - let inserted = seen.lock().unwrap().inserts.clone(); - assert_eq!( - inserted.last().map(String::as_str), - Some("parent=[7202] children=[] frame=20x10"), - "on_insert must see the child spliced into its parent: {inserted:?}" - ); - - let mut move_child = op(MountKind::Update); - move_child.tag = 7202; - move_child.component = "Text".into(); - move_child.parent_tag = 7101; - move_child.frame = RectF { - x: 0.0, - y: 0.0, - w: 55.0, - h: 66.0, - }; - cx.update_entity(&store, |store, cx| { - store.apply_batch( - MountBatch { - surface_id: 1, - ops: vec![move_child], - ..Default::default() - }, - cx, - ); - }); - assert_eq!( - seen.lock().unwrap().batches.last().map(String::as_str), - Some("parent=[7202] children=[] frame=55x66"), - "the tree must report the frame an update gave the node" - ); - - let mut remove_child = op(MountKind::Remove); - remove_child.tag = 7202; - remove_child.component = "Text".into(); - remove_child.parent_tag = 7101; - cx.update_entity(&store, |store, cx| { - store.apply_batch( - MountBatch { - surface_id: 1, - ops: vec![remove_child], - ..Default::default() - }, - cx, - ); - }); - // The hook runs before the splice is undone, exactly as it did when the - // tree was read from the live nodes: the leaving card is still listed, - // which is what lets the module find it and keep it for its exit. - assert_eq!( - seen.lock().unwrap().remove.as_deref(), - Some("parent=[7202] children=[] frame=55x66"), - "a remove hook must still see the card it is being told about" - ); - - let mut delete_child = op(MountKind::Delete); - delete_child.tag = 7202; - delete_child.component = "Text".into(); - delete_child.parent_tag = -1; - cx.update_entity(&store, |store, cx| { - store.apply_batch( - MountBatch { - surface_id: 1, - ops: vec![delete_child], - ..Default::default() - }, - cx, - ); - }); - assert_eq!(seen.lock().unwrap().delete.as_deref(), Some("deleted")); - assert_eq!( - cx.read_entity(&store, |store, _| store.snapshots.contains_key(&7202)), - false, - "a deleted tag must not linger in the snapshot map" - ); - assert_eq!( - cx.read_entity(&store, |store, _| store.snapshots.contains_key(&7101)), - true, - "its parent must still be there" - ); - } - - #[gpui::test] - fn top_layout_dispatches_for_any_component_with_on_layout_and_skips_non_listeners( - cx: &mut TestAppContext, - ) { - let (store, _root) = store_with_layout_owner(cx, LayoutEventOwner::from_loom_flag(true)); - let with_on_layout = |tag: i32, component: &'static str, on_layout: bool| { - let mut node = create(tag, component); - node.layout_changed = true; - node.view.on_layout = on_layout; - node - }; - apply( - cx, - &store, - vec![ - with_on_layout(101, "View", true), - with_on_layout(102, "Paragraph", true), - with_on_layout(103, "TextInput", true), - with_on_layout(104, "Image", true), - with_on_layout(105, "ScrollView", true), - with_on_layout(106, "View", false), - with_on_layout(107, "Paragraph", false), - ], - ); - - let events = cx.read_entity(&store, |store, _| store.host.take_dispatched_events()); - let tags: Vec = events - .iter() - .filter(|(_, ty, _)| ty == "topLayout") - .map(|(tag, _, _)| *tag) - .collect(); - assert_eq!(tags, vec![101, 102, 103, 104, 105]); - assert_eq!( - events[1].2, - serde_json::json!({ - "layout": { - "x": 10.0, - "y": 12.0, - "width": 40.0, - "height": 30.0 - } - }) - ); - } - - #[gpui::test] - fn top_layout_tracks_on_layout_across_layout_only_updates_and_inserts( - cx: &mut TestAppContext, - ) { - let (store, _root) = store_with_layout_owner(cx, LayoutEventOwner::from_loom_flag(true)); - - let mut p_create = create(201, "Paragraph"); - p_create.layout_changed = true; - p_create.view.on_layout = true; - p_create.frame = RectF { - x: 0.0, - y: 0.0, - w: 50.0, - h: 20.0, - }; - apply(cx, &store, vec![p_create]); - assert_eq!( - cx.read_entity(&store, |store, _| store.host.take_dispatched_events()) - .len(), - 1 - ); - - // Layout-only update (props_changed = false, op.view default) keeps on_layout = true. - let mut p_layout_only = op(MountKind::Update); - p_layout_only.tag = 201; - p_layout_only.component = "Paragraph".into(); - p_layout_only.props_changed = false; - p_layout_only.layout_changed = true; - p_layout_only.frame = RectF { - x: 1.0, - y: 2.0, - w: 80.0, - h: 25.0, - }; - apply(cx, &store, vec![p_layout_only]); - let events = cx.read_entity(&store, |store, _| store.host.take_dispatched_events()); - assert_eq!(events.len(), 1); - assert_eq!( - events[0].2, - serde_json::json!({ - "layout": { - "x": 1.0, - "y": 2.0, - "width": 80.0, - "height": 25.0 - } - }) - ); - - // Removing onLayout stops subsequent layout events. - let mut p_remove_prop = op(MountKind::Update); - p_remove_prop.tag = 201; - p_remove_prop.component = "Paragraph".into(); - p_remove_prop.props_changed = true; - p_remove_prop.view.on_layout = false; - p_remove_prop.layout_changed = true; - p_remove_prop.frame = RectF { - x: 1.0, - y: 2.0, - w: 90.0, - h: 25.0, - }; - apply(cx, &store, vec![p_remove_prop]); - assert!( - cx.read_entity(&store, |store, _| store.host.take_dispatched_events()) - .is_empty() - ); - - // Insert carrying initial layout honors Create's on_layout flag. - let mut v_create = create(202, "Paragraph"); - v_create.layout_changed = false; - v_create.view.on_layout = true; - let mut v_insert = insert(202, -1); - v_insert.component = "Paragraph".into(); - v_insert.props_changed = false; - v_insert.layout_changed = true; - v_insert.frame = RectF { - x: 3.0, - y: 4.0, - w: 60.0, - h: 18.0, - }; - apply(cx, &store, vec![v_create, v_insert]); - let insert_events = cx.read_entity(&store, |store, _| store.host.take_dispatched_events()); - assert_eq!(insert_events.len(), 1); - assert_eq!(insert_events[0].0, 202); - } - - #[gpui::test] - fn top_layout_does_not_dispatch_when_shadow_tree_owns_layout_events(cx: &mut TestAppContext) { - let (store, _root) = store_with_layout_owner(cx, LayoutEventOwner::from_loom_flag(false)); - - let with_on_layout = |tag: i32, component: &'static str| { - let mut node = create(tag, component); - node.layout_changed = true; - node.view.on_layout = true; - node - }; - let mut insert_view = insert(306, -1); - insert_view.component = "View".into(); - insert_view.props_changed = false; - insert_view.layout_changed = true; - - let mut c306 = create(306, "View"); - c306.layout_changed = false; - c306.view.on_layout = true; - - apply( - cx, - &store, - vec![ - with_on_layout(301, "View"), - with_on_layout(302, "Paragraph"), - with_on_layout(303, "TextInput"), - with_on_layout(304, "Image"), - with_on_layout(305, "ScrollView"), - c306, - insert_view, - ], - ); - - let mut update = op(MountKind::Update); - update.tag = 301; - update.component = "View".into(); - update.props_changed = false; - update.layout_changed = true; - apply(cx, &store, vec![update]); - - assert!( - cx.read_entity(&store, |store, _| store.host.take_dispatched_events()) - .is_empty(), - "Fabric builds emit topLayout from ShadowTree and must not dispatch a second time from ViewStore" - ); - } -} - -fn log_mount_op(op: &MountOp) { - log::debug!( - "[store] {:<6} tag={} parent={} index={} {:<30} frame=({:.1},{:.1} {:.1}x{:.1}) props_changed={} props={}", - kind_name(op.kind), - op.tag, - op.parent_tag, - op.index, - op.component, - op.frame.x, - op.frame.y, - op.frame.w, - op.frame.h, - op.props_changed, - op.extension_props_json, - ); -} - -/// cxx models a shared enum as a struct with a `repr` field, so the match is -/// intentionally not exhaustive. -fn kind_name(kind: MountKind) -> &'static str { - match kind { - MountKind::Create => "Create", - MountKind::Delete => "Delete", - MountKind::Insert => "Insert", - MountKind::Remove => "Remove", - MountKind::Update => "Update", - _ => "Unknown", - } -} - -/// A separate entity because GPUI only re-runs `render` for entities the window -/// tracked while drawing, and the root view is not invalidated after its first -/// frame. Created before the window opens; it only toggles its own contents. -pub struct OverlayHost { - overlays: Vec<(i32, Entity)>, - portals: Vec<(i32, Entity)>, -} - -impl OverlayHost { - pub fn new() -> Self { - Self { - overlays: Vec::new(), - portals: Vec::new(), - } - } - - /// How many surfaces are shown through the slot, for tests. - #[cfg(test)] - pub(crate) fn overlay_count(&self) -> usize { - self.overlays.len() - } - - pub fn insert(&mut self, surface_id: i32, overlay: Entity) { - if !self.overlays.iter().any(|(id, _)| *id == surface_id) { - self.overlays.push((surface_id, overlay)); - } - } - - pub fn remove(&mut self, surface_id: i32) { - self.overlays.retain(|(id, _)| *id != surface_id); - } - - pub fn clear(&mut self) { - self.overlays.clear(); - self.portals.clear(); - } - - pub fn insert_portal(&mut self, tag: i32, portal: Entity) { - if !self.portals.iter().any(|(existing, _)| *existing == tag) { - self.portals.push((tag, portal)); - } - } - - pub fn remove_portal(&mut self, tag: i32) { - self.portals.retain(|(existing, _)| *existing != tag); - } -} - -impl Render for OverlayHost { - fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { - // Kept absolute so the empty host is exactly 0x0: a full-size empty div - // would swallow every hover and click meant for the app behind it. - let host = div().absolute().top_0().left_0(); - if self.overlays.is_empty() && self.portals.is_empty() { - host - } else { - // LogBox is painted last: it stays above the app's portals. - host.size_full() - .children(self.portals.iter().map(|(_, portal)| portal.clone())) - .children(self.overlays.iter().map(|(_, overlay)| overlay.clone())) - } - } -} - -pub struct SurfaceRootView { - surface_id: i32, - pub(crate) kind: SurfaceKind, - pub children: Vec<(i32, Entity)>, - /// How many of the nodes mounted under this surface render a native - /// surface. - native_surfaces: u32, - /// A GPUI-first app's content, painted where a React tree would be. - app_content: Option, - pub overlay_host: Option>, - pub perf_monitor: Option>, - pub menu_bar: Option>, - /// Kept alive for as long as the surface: dropping it would stop the - /// window-activation callback that dismisses an open menu on focus loss. - pub menu_bar_activation_subscription: Option, - #[cfg(all(target_os = "macos", feature = "visual-capture"))] - native_view_probe: Option>, -} - -impl SurfaceRootView { - pub fn new(surface_id: i32) -> Self { - Self::with_kind(surface_id, SurfaceKind::Window) - } - - pub fn with_kind(surface_id: i32, kind: SurfaceKind) -> Self { - Self { - surface_id, - kind, - children: Vec::new(), - native_surfaces: 0, - app_content: None, - overlay_host: None, - perf_monitor: None, - menu_bar: None, - menu_bar_activation_subscription: None, - #[cfg(all(target_os = "macos", feature = "visual-capture"))] - native_view_probe: None, - } - } - - /// Makes the root show a GPUI view instead of a React tree. The window chrome - /// — the menu bar, the overlay slot, the key context — stays the root's. - pub fn set_app_content(&mut self, view: gpui::AnyView) { - self.app_content = Some(view); - } - - pub fn with_overlay_host(mut self, overlay_host: Entity) -> Self { - self.overlay_host = Some(overlay_host); - self - } - - #[cfg(all(target_os = "macos", feature = "visual-capture"))] - pub fn with_native_view_probe( - mut self, - native_view_probe: Entity, - ) -> Self { - self.native_view_probe = Some(native_view_probe); - self - } - - pub fn insert_child(&mut self, index: usize, tag: i32, child: Entity) { - let index = index.min(self.children.len()); - self.children.insert(index, (tag, child)); - } - - pub fn remove_child(&mut self, tag: i32) { - self.children.retain(|(child_tag, _)| *child_tag != tag); - } - - /// Drops every child and the count that went with them. - pub fn clear_children(&mut self) { - self.children.clear(); - self.native_surfaces = 0; - } - - /// Adds to the number of native surfaces mounted under this surface. - pub(crate) fn add_native_surfaces(&mut self, delta: u32) -> bool { - let before = self.native_surfaces; - self.native_surfaces = before.saturating_add(delta); - before == 0 && self.native_surfaces != 0 - } - - pub(crate) fn sub_native_surfaces(&mut self, delta: u32) -> bool { - let before = self.native_surfaces; - self.native_surfaces = before.saturating_sub(delta); - before != 0 && self.native_surfaces == 0 - } - - /// Whether a native surface is mounted anywhere under this surface. - pub(crate) fn has_native_surface(&self) -> bool { - self.native_surfaces > 0 - } -} - -/// The invisible grab border of a window with client-side decorations. -/// -/// A frameless window has no native frame to drag, so the app supplies one. It -/// is drawn only where the compositor really did give client-side decorations: -/// an X11 window manager that ignores the request keeps its own frame, and a -/// second, invisible border inside it would take presses from the content with -/// no way to tell the user why. -#[cfg(target_os = "linux")] -fn resize_border(window: &mut Window) -> Option { - if !matches!( - window.window_decorations(), - gpui::Decorations::Client { .. } - ) { - return None; - } - if !window.is_resizable() { - return None; - } - let size = window.viewport_size(); - let (width, height) = (f32::from(size.width), f32::from(size.height)); - let mut border = div().absolute().inset_0().size_full(); - for edge in crate::desktop::client_frame::EDGES { - let bounds = crate::desktop::client_frame::border_bounds(edge, width, height); - border = border.child( - div() - .absolute() - .left(bounds.origin.x) - .top(bounds.origin.y) - .w(bounds.size.width) - .h(bounds.size.height) - // No background: the border only exists to catch the press, and - // painting it would put an eight-pixel band over the app's own - // edges. - .cursor(crate::desktop::client_frame::edge_cursor(edge)) - .on_mouse_down( - gpui::MouseButton::Left, - move |event: &gpui::MouseDownEvent, window, cx| { - if event.click_count > 1 { - return; - } - window.start_window_resize(edge); - cx.stop_propagation(); - }, - ), - ); - } - Some(border.into_any_element()) -} - -/// The window's content inside the frame a client-decorated window draws for -/// itself: a see-through margin that carries the shadow, then the content with -/// rounded corners and a hairline border. -/// -/// The margin shrinks to nothing on a side that touches the screen or another -/// window, and the corners there are square, which is how a maximized window -/// looks. -#[cfg(target_os = "linux")] -fn framed( - content: gpui::Div, - tiling: gpui::Tiling, - surface_id: i32, - window: &mut Window, -) -> gpui::AnyElement { - use crate::desktop::window_frame; - - let frame = window_frame::frame(); - let insets = window_frame::insets_of(surface_id); - let placement = window_frame::placement_of(surface_id); - // An overlay is maximized so it can cover the work area, but what it shows is - // a popover, which keeps its corners and its shadow. - let tiling = if placement.is_some() { - gpui::Tiling::default() - } else { - tiling - }; - let bare = placement.is_some_and(|placement| placement.bare); - let radius = px(if bare { 0.0 } else { frame.radius }); - let round = |element: gpui::Div| { - element - .when(!(tiling.top || tiling.left), |element| { - element.rounded_tl(radius) - }) - .when(!(tiling.top || tiling.right), |element| { - element.rounded_tr(radius) - }) - .when(!(tiling.bottom || tiling.left), |element| { - element.rounded_bl(radius) - }) - .when(!(tiling.bottom || tiling.right), |element| { - element.rounded_br(radius) - }) - }; - let mut body = round( - div() - .size_full() - .relative() - .overflow_hidden() - .overflow_clips_corners(), - ) - .when( - !bare && !tiling.is_tiled() && frame.shadow_alpha > 0.0, - |element| { - element.shadow(vec![gpui::BoxShadow::new( - px(0.0), - px(frame.shadow_dy), - gpui::hsla(0.0, 0.0, 0.0, frame.shadow_alpha), - ) - .blur_radius(px(frame.shadow_blur)) - .spread_radius(px(frame.shadow_spread))]) - }, - ) - .child(content); - if !bare && !tiling.is_tiled() { - body = body.child( - round(div().absolute().inset_0()) - .border_1() - .border_color(gpui::rgba(frame.border)), - ); - } - let mut shell = div() - .size_full() - .relative() - .pl(px(insets.left)) - .pt(px(insets.top)) - .pr(px(insets.right)) - .pb(px(insets.bottom)); - if let Some(placement) = placement { - // Only the popover takes input; a press anywhere else reaches the window - // under the overlay, and the popover closes when it loses focus. - window.set_input_region(Some(&[gpui::Bounds { - origin: gpui::point(px(insets.left), px(insets.top)), - size: gpui::size(px(placement.size.0), px(placement.size.1)), - }])); - } - shell = shell.child(body); - if let Some(border) = resize_border(window) { - shell = shell.child(border); - } - shell.into_any_element() -} - -impl SurfaceRootView { - /// The content under the window's zoom factor: laid out at the window's size - /// over the factor, and drawn scaled back up to it. - fn zoomed(root: gpui::Div, surface_id: i32, window: &Window) -> gpui::AnyElement { - let zoom = crate::desktop::zoom::get(surface_id); - if (zoom - 1.0).abs() < f32::EPSILON { - return root.into_any_element(); - } - let viewport = window.viewport_size(); - let frame = crate::desktop::window_frame::insets_of(surface_id); - let width = f32::from(viewport.width) - frame.horizontal(); - let height = f32::from(viewport.height) - - frame.vertical() - - crate::desktop::gpui_menu::menu_bar_inset_for_window_id(surface_id as u32); - let matrix = gpui::TransformationMatrix { - rotation_scale: [[zoom, 0.0], [0.0, zoom]], - translation: [0.0, 0.0], - }; - div() - .size_full() - .overflow_hidden() - .child(crate::transform::Transformed::new( - root.w(px((width / zoom).max(1.0))) - .h(px((height / zoom).max(1.0))) - .into_any_element(), - matrix, - )) - .into_any_element() - } -} - -impl Render for SurfaceRootView { - fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - if self.kind == SurfaceKind::Embedded { - return div() - .size_full() - .relative() - .capture_any_mouse_down(|_, _, _| crate::events::begin_press()) - .capture_any_mouse_up(|_, _, _| crate::events::begin_press_dispatch()) - .children(self.children.iter().map(|(_, child)| child.clone())) - .into_any_element(); - } - let has_fabric_native_view = self.has_native_surface(); - let mut root = div() - .size_full() - .relative() - // Ahead of every node's listener, so a press that a title bar handed - // to the window does not leave the next press marked as well. - .capture_any_mouse_down(|_, window, cx| { - crate::tooltip::dismiss(window, cx); - crate::events::begin_press() - }) - .capture_any_mouse_up(|_, _, _| crate::events::begin_press_dispatch()) - // The root stays hovered while any descendant is hit, so this only fires when - // the pointer left the window. - .on_mouse_exit(cx.listener(|_this, _event, window, cx| { - crate::events::leave_root(window, cx); - })) - .capture_key_down(|event, window, cx| { - if event.keystroke.key == "escape" && crate::drag_drop::cancel(window, cx) { - cx.stop_propagation(); - } - }) - // A press that started on a node follows the pointer wherever it - // goes: over a node, the node moves and ends it first; anywhere - // else it moves and ends here, so a drag that left every touchable - // still reaches React, which decides from it whether the press - // is kept. - .on_drag_move::(|event, _window, cx| { - crate::file_drop::moved(event.drag(cx).paths()); - }) - .on_drop::(|_, window, cx| crate::file_drop::dropped(window, cx)) - .on_file_drop_exit(|_, window, cx| crate::file_drop::exited(window, cx)) - .on_mouse_move(|event, window, cx| { - if crate::drag_drop::tracking() { - crate::drag_drop::moved( - window, - cx, - None, - event.position, - event.pressed_button.is_some(), - ); - return; - } - if crate::file_drop::active() { - crate::file_drop::left_unanswered(window, cx, event.position); - return; - } - if event.pressed_button.is_none() || crate::events::press_belongs_to_window() { - return; - } - crate::events::move_pressed( - window, - cx, - None, - event.position, - crate::node_view::modifier_state(event.modifiers), - ); - }) - .on_mouse_up(gpui::MouseButton::Left, |event, window, cx| { - if crate::drag_drop::tracking() { - if crate::drag_drop::released(window, cx, None, event.position) { - return; - } - } - if crate::events::press_belongs_to_window() { - return; - } - if let Some(target) = crate::events::active_touch_target(cx) { - crate::events::send( - window, - cx, - &target, - event.position, - crate::events::Phase::End, - Some(crate::events::Button::Left), - crate::node_view::modifier_state(event.modifiers), - ); - } - }) - .child(crate::events::outside_window_pointer()) - .children(self.app_content.clone()) - .children(self.children.iter().map(|(_, child)| child.clone())); - #[cfg(all(target_os = "macos", feature = "visual-capture"))] - if let Some(native_view_probe) = &self.native_view_probe { - root = root.child(native_view_probe.clone()); - } - if let Some(overlay_host) = &self.overlay_host { - let has_native_composition = has_fabric_native_view || { - #[cfg(all(target_os = "macos", feature = "visual-capture"))] - { - self.native_view_probe.is_some() - } - #[cfg(not(all(target_os = "macos", feature = "visual-capture")))] - { - false - } - }; - if has_native_composition { - root = root.child(deferred(overlay_host.clone()).priority(100)); - } else { - root = root.child(overlay_host.clone()); - } - } - if let Some(monitor) = self.perf_monitor.clone() { - root = root.child(monitor); - } - if _window.is_a11y_active() { - if let Some(announcement) = crate::accessibility::current_announcement() { - root = root.child(crate::accessibility::announcement_element(announcement)); - } - } - // The hardware navigation buttons belong to the window, not the - // surface: the handlers go on the outermost element so the in-window - // menu bar (Linux) cannot swallow a press aimed at the app. - // A press in the app body dismisses an open GPUI menu: clicking away - // from a menu is expected to close it. The handler is in the capture - // phase so the press is seen before any RN view consumes it, and it is - // on the content area *below* the menu bar — a press on a menu title - // still opens/replaces that menu, and the popup's own item clicks are in - // its separate window and never reach here. `dismiss` resolves the menu - // with `None`, the documented "dismissed" outcome for a context menu. - let content = div() - .id("surface-content") - .flex_1() - .min_h_0() - .capture_any_mouse_down(cx.listener(|_this, _event, _window, cx| { - let _ = crate::desktop::gpui_menu::MenuPopup::dismiss(cx); - })) - .child(Self::zoomed(root, self.surface_id, _window)); - // The root carries the app key context, so a shortcut with no scope can - // match with nothing focused: GPUI evaluates a context predicate against - // the focus path's contexts, and an empty stack matches nothing at all — - // including a negation. Since this is the shallowest context, every - // `ShortcutScope` inside it outranks it, which is the documented - // "innermost wins, window scope last" order. - let app_context = - gpui::KeyContext::parse(crate::desktop::keymap::APP_CONTEXT).unwrap_or_default(); - let window_id = self.surface_id as u32; - let menu_bar = self - .menu_bar - .clone() - .filter(|_| crate::desktop::gpui_menu::menu_bar_in_window(window_id)); - let mut window_root = div() - .size_full() - .flex() - .flex_col() - .relative() - .key_context(app_context); - if let Some(tooltip) = crate::tooltip::drawn_element(_window) { - window_root = window_root.child(tooltip); - } - window_root = match ( - menu_bar, - crate::desktop::gpui_menu::menu_bar_slot(window_id), - ) { - // The bar has its own row above everything else. - (Some(menu_bar), None) => window_root.child(menu_bar).child(content), - // The React tree reserved room for it, so it is drawn over that room. - (Some(menu_bar), Some(slot)) => window_root.child(content).child( - div() - .absolute() - .left(px(slot.x)) - .top(px(slot.y)) - .w(px(slot.width)) - .h(px(slot.height)) - .child(menu_bar), - ), - (None, _) => window_root.child(content), - }; - if self.surface_id == APP_SURFACE_ID { - for (button, event_name) in [ - ( - MouseButton::Navigate(NavigationDirection::Back), - "hardwareBackPress", - ), - ( - MouseButton::Navigate(NavigationDirection::Forward), - "hardwareForwardPress", - ), - ] { - window_root = window_root.on_mouse_down( - button, - cx.listener(move |_this, _event, window, cx| { - if let Some(store) = cx.try_global::() { - let store = store.0.read(cx); - store.host.emit_device_event(event_name); - store.frame_hook.arm(window); - log::info!("[navigation] emitted {event_name} from mouse button"); - } - cx.stop_propagation(); - }), - ); - } - } - // Last, so the border paints in front of the app: whichever edge the - // pointer is nearest is what a press there resizes. - #[cfg(target_os = "linux")] - if crate::desktop::window_frame::is_framed(self.surface_id) { - if let gpui::Decorations::Client { tiling } = _window.window_decorations() { - return framed(window_root, tiling, self.surface_id, _window); - } - } - #[cfg(target_os = "linux")] - if let Some(border) = resize_border(_window) { - window_root = window_root.child(border); - } - window_root.into_any_element() - } -} - -/// An item a scroll view keeps at the same place across a batch. -struct ScrollAnchor { - scroll: i32, - anchor: i32, - start: f32, - threshold: Option, -} - -thread_local! { - static SURFACE_WINDOWS: std::cell::RefCell> = - std::cell::RefCell::new(HashMap::new()); -} - -pub(crate) fn note_surface_window(surface_id: i32, window: Option) { - SURFACE_WINDOWS.with(|windows| { - let mut windows = windows.borrow_mut(); - match window { - Some(window) => windows.insert(surface_id, window), - None => windows.remove(&surface_id), - }; - }); -} - -/// The window a surface is shown in, read without the store, which a mount -/// batch has leased while it runs. -pub(crate) fn window_of_surface(surface_id: i32) -> Option { - SURFACE_WINDOWS.with(|windows| windows.borrow().get(&surface_id).copied()) -} - -pub fn store_from(cx: &App) -> Option> { - cx.try_global::() - .map(|global| global.0.clone()) -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/style.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/style.rs deleted file mode 100644 index 1a83093d88..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/style.rs +++ /dev/null @@ -1,434 +0,0 @@ -use crate::view_props::ViewProps; -use gpui::{ - point, px, rgba, BoxShadow, CursorStyle, Fill, Hsla, Overflow, SharedString, StyleRefinement, -}; -use serde_json::Value; - -/// RN colors are 0xAARRGGBB; GPUI's `rgba()` takes 0xRRGGBBAA. -pub fn color(argb: u32) -> Hsla { - let alpha = argb >> 24; - rgba((argb << 8) | alpha).into() -} - -/// `ViewPropsFlat::cursor` is the ordinal of RN's `Cursor` enum; the arms -/// below are in that order. -pub(crate) fn cursor_style(ordinal: u8) -> Option { - let style = match ordinal { - 0 => return None, // Auto - 1 => CursorStyle::DragLink, // Alias - 2 => CursorStyle::Arrow, // AllScroll - 3 => CursorStyle::Arrow, // Cell - 4 => CursorStyle::ResizeColumn, // ColResize - 5 => CursorStyle::ContextualMenu, // ContextMenu - 6 => CursorStyle::DragCopy, // Copy - 7 => CursorStyle::Crosshair, // Crosshair - 8 => CursorStyle::Arrow, // Default - 9 => CursorStyle::ResizeRight, // EResize - 10 => CursorStyle::ResizeLeftRight, // EWResize - 11 => CursorStyle::OpenHand, // Grab - 12 => CursorStyle::ClosedHand, // Grabbing - 13 => CursorStyle::Arrow, // Help - 14 => CursorStyle::Arrow, // Move - 15 => CursorStyle::ResizeUpRightDownLeft, // NEResize - 16 => CursorStyle::ResizeUpRightDownLeft, // NESWResize - 17 => CursorStyle::ResizeUp, // NResize - 18 => CursorStyle::ResizeUpDown, // NSResize - 19 => CursorStyle::ResizeUpLeftDownRight, // NWResize - 20 => CursorStyle::ResizeUpLeftDownRight, // NWSEResize - 21 => CursorStyle::OperationNotAllowed, // NoDrop - 22 => CursorStyle::Arrow, // None - 23 => CursorStyle::OperationNotAllowed, // NotAllowed - 24 => CursorStyle::PointingHand, // Pointer - 25 => CursorStyle::Arrow, // Progress - 26 => CursorStyle::ResizeRow, // RowResize - 27 => CursorStyle::ResizeDown, // SResize - 28 => CursorStyle::ResizeUpLeftDownRight, // SEResize - 29 => CursorStyle::ResizeUpRightDownLeft, // SWResize - 30 => CursorStyle::IBeam, // Text - 31 => CursorStyle::PointingHand, // Url - 32 => CursorStyle::ResizeLeft, // WResize - 33 => CursorStyle::Arrow, // Wait - 34 => CursorStyle::Arrow, // ZoomIn - 35 => CursorStyle::Arrow, // ZoomOut - unknown => { - log::warn!("[style] unknown cursor ordinal {unknown}; using the default"); - CursorStyle::Arrow - } - }; - Some(style) -} - -pub fn to_refinement(v: &ViewProps) -> StyleRefinement { - let mut s = StyleRefinement::default(); - if v.background_color != 0 { - s.background = Some(Fill::from(color(v.background_color))); - } - // RN borders are painted as four independent edge rules by `node_view`. - // GPUI border widths would add a second, default-colored edge on top. - s.corner_radii.top_left = Some(px(v.border_radii.tl).into()); - s.corner_radii.top_right = Some(px(v.border_radii.tr).into()); - s.corner_radii.bottom_right = Some(px(v.border_radii.br).into()); - s.corner_radii.bottom_left = Some(px(v.border_radii.bl).into()); - if v.overflow_hidden { - s.overflow.x = Some(Overflow::Hidden); - s.overflow.y = Some(Overflow::Hidden); - // React Native clips children to the rounded corners, not only the box. - s.overflow_clips_corners = Some(true); - } - if let Some(cursor) = cursor_style(v.cursor) { - log::debug!("[style] cursor ordinal {} -> {cursor:?}", v.cursor); - s.mouse_cursor = Some(cursor); - } - if v.opacity < 1.0 { - s.opacity = Some(v.opacity); - } - if !v.shadows.is_empty() { - s.box_shadow = Some( - v.shadows - .iter() - .map(|sh| BoxShadow { - color: color(sh.color), - offset: point(px(sh.dx), px(sh.dy)), - blur_radius: px(sh.blur / 2.0), - spread_radius: px(sh.spread), - inset: sh.inset, - }) - .collect(), - ); - } - s -} - -/// The properties a state style prop can change. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct StateStyle { - background_color: Option, - opacity: Option, - box_shadow: Option>, - /// Left, top, right, bottom: the order of `ViewPropsFlat::border_colors`. - border_colors: [Option; 4], - color: Option, - transform: Option<[f32; 16]>, - outline_color: Option, - outline_width: Option, - outline_offset: Option, -} - -#[derive(Clone, Debug, Default, PartialEq)] -struct ShadowSpec { - offset_x: f32, - offset_y: f32, - color: Option, - blur_radius: f32, - spread_distance: f32, - inset: bool, -} - -fn number(value: &Value, key: &str) -> Option { - value.get(key)?.as_f64().map(|n| n as f32) -} - -fn argb(value: &Value, key: &str) -> Option { - u32::try_from(value.get(key)?.as_u64()?).ok() -} - -impl ShadowSpec { - fn from_json(value: &Value) -> Self { - Self { - offset_x: number(value, "offsetX").unwrap_or(0.0), - offset_y: number(value, "offsetY").unwrap_or(0.0), - color: argb(value, "color"), - blur_radius: number(value, "blurRadius").unwrap_or(0.0), - spread_distance: number(value, "spreadDistance").unwrap_or(0.0), - inset: value.get("inset").and_then(Value::as_bool).unwrap_or(false), - } - } -} - -/// The properties a running animation owns, which a state style leaves alone. -#[derive(Clone, Copy, Debug, Default)] -pub struct Animating { - pub background: bool, - pub opacity: bool, -} - -impl StateStyle { - pub(crate) fn from_json(value: &Value) -> Self { - let all = argb(value, "borderColor"); - let side = |name: &str| argb(value, name).or(all); - Self { - background_color: argb(value, "backgroundColor"), - opacity: number(value, "opacity"), - box_shadow: value - .get("boxShadow") - .and_then(Value::as_array) - .map(|shadows| shadows.iter().map(ShadowSpec::from_json).collect()), - border_colors: [ - side("borderLeftColor"), - side("borderTopColor"), - side("borderRightColor"), - side("borderBottomColor"), - ], - color: argb(value, "color"), - outline_color: argb(value, "outlineColor"), - outline_width: number(value, "outlineWidth"), - outline_offset: number(value, "outlineOffset"), - transform: value - .get("transform") - .and_then(Value::as_array) - .and_then(|m| { - let matrix: Vec = m - .iter() - .filter_map(|n| n.as_f64()) - .map(|n| n as f32) - .collect(); - <[f32; 16]>::try_from(matrix).ok() - }), - } - } - - /// Lays `other` over this style: what it sets wins. - pub(crate) fn merge(&mut self, other: &StateStyle) { - self.background_color = other.background_color.or(self.background_color); - self.opacity = other.opacity.or(self.opacity); - if other.box_shadow.is_some() { - self.box_shadow.clone_from(&other.box_shadow); - } - for (mine, theirs) in self.border_colors.iter_mut().zip(other.border_colors) { - *mine = theirs.or(*mine); - } - self.color = other.color.or(self.color); - self.transform = other.transform.or(self.transform); - self.outline_color = other.outline_color.or(self.outline_color); - self.outline_width = other.outline_width.or(self.outline_width); - self.outline_offset = other.outline_offset.or(self.outline_offset); - } - - /// The border colors this style leaves to `base`, left, top, right, bottom. - pub(crate) fn border_colors(&self, base: [u32; 4]) -> [u32; 4] { - std::array::from_fn(|side| self.border_colors[side].unwrap_or(base[side])) - } - - /// The outline color, width and offset, with what this style leaves to `base`. - pub(crate) fn outline(&self, base: (u32, f32, f32)) -> (u32, f32, f32) { - ( - self.outline_color.unwrap_or(base.0), - self.outline_width.unwrap_or(base.1), - self.outline_offset.unwrap_or(base.2), - ) - } - - pub(crate) fn background(&self) -> Option { - self.background_color - } - - pub(crate) fn opacity(&self) -> Option { - self.opacity - } - - pub(crate) fn text_color(&self) -> Option { - self.color - } - - pub(crate) fn transform(&self) -> Option<[f32; 16]> { - self.transform - } - - /// The refinement gpui layers over the base style while the state holds. - /// `scale` is the node's accumulated transform scale, applied to shadows the - /// way the base style's are. - pub fn refinement(&self, scale: (f32, f32), animating: Animating) -> StyleRefinement { - let mut s = StyleRefinement::default(); - if let Some(argb) = self.background_color.filter(|_| !animating.background) { - s.background = Some(Fill::from(color(argb))); - } - if let Some(opacity) = self.opacity.filter(|_| !animating.opacity) { - s.opacity = Some(opacity.clamp(0.0, 1.0)); - } - if let Some(shadows) = &self.box_shadow { - let radius_scale = scale.0.min(scale.1); - s.box_shadow = Some( - shadows - .iter() - .map(|shadow| BoxShadow { - color: color(shadow.color.unwrap_or(0xFF00_0000)), - offset: point(px(shadow.offset_x * scale.0), px(shadow.offset_y * scale.1)), - blur_radius: px(shadow.blur_radius * radius_scale / 2.0), - spread_radius: px(shadow.spread_distance * radius_scale), - inset: shadow.inset, - }) - .collect(), - ); - } - s - } -} - -/// A style that applies while a named ancestor group is hovered or pressed. -#[derive(Clone, Debug, PartialEq)] -pub struct GroupStateStyle { - pub group: SharedString, - pub style: StateStyle, -} - -/// Everything a view declares through `group` and the `*Style` state props. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct StateStyles { - pub group: Option, - pub hover: Option, - pub active: Option, - pub focus: Option, - pub focus_visible: Option, - pub drag_over: Option, - pub group_hover: Option, - pub group_active: Option, -} - -fn parse_json(prop: &str, json: &str) -> Option { - if json.is_empty() { - return None; - } - match serde_json::from_str(json) { - Ok(parsed) => Some(parsed), - Err(error) => { - log::warn!("[style] ignoring invalid {prop}: {error}"); - None - } - } -} - -fn parse_state(prop: &str, json: &str) -> Option { - parse_json(prop, json).map(|value| StateStyle::from_json(&value)) -} - -fn parse_group(prop: &str, json: &str) -> Option { - let value = parse_json(prop, json)?; - let group = value - .get("group")? - .as_str() - .filter(|group| !group.is_empty())?; - Some(GroupStateStyle { - group: group.to_owned().into(), - style: StateStyle::from_json(value.get("style")?), - }) -} - -impl StateStyles { - /// Whether any state sets the text color. - pub fn sets_color(&self) -> bool { - [ - self.focus.as_ref(), - self.focus_visible.as_ref(), - self.drag_over.as_ref(), - self.hover.as_ref(), - self.active.as_ref(), - self.group_hover.as_ref().map(|grouped| &grouped.style), - self.group_active.as_ref().map(|grouped| &grouped.style), - ] - .into_iter() - .flatten() - .any(|style| style.text_color().is_some()) - } - - /// `None` when the view declares nothing, which is the case for almost every view. - pub fn from_flat(v: &ViewProps) -> Option> { - let styles = Self { - group: (!v.group.is_empty()).then(|| v.group.clone().into()), - hover: parse_state("hoverStyle", &v.hover_style), - active: parse_state("activeStyle", &v.active_style), - focus: parse_state("focusStyle", &v.focus_style), - focus_visible: parse_state("focusVisibleStyle", &v.focus_visible_style), - drag_over: parse_state("dragOverStyle", &v.drag_over_style), - group_hover: parse_group("groupHoverStyle", &v.group_hover_style), - group_active: parse_group("groupActiveStyle", &v.group_active_style), - }; - (styles != Self::default()).then(|| std::rc::Rc::new(styles)) - } -} - -#[cfg(test)] -mod state_style_tests { - use super::*; - use serde_json::json; - - fn state(value: Value) -> StateStyle { - StateStyle::from_json(&value) - } - - #[test] - fn a_side_color_overrides_border_color() { - let style = state(json!({"borderColor": 1, "borderBottomColor": 2})); - assert_eq!(style.border_colors([9; 4]), [1, 1, 1, 2]); - } - - #[test] - fn a_style_without_border_colors_keeps_the_base() { - assert_eq!(state(json!({})).border_colors([7, 8, 9, 10]), [7, 8, 9, 10]); - } - - #[test] - fn a_later_layer_wins_only_the_properties_it_sets() { - let mut base = state(json!({"backgroundColor": 1, "opacity": 0.5, "color": 3})); - base.merge(&state(json!({"backgroundColor": 2}))); - assert_eq!(base.background_color, Some(2)); - assert_eq!(base.opacity, Some(0.5)); - assert_eq!(base.text_color(), Some(3)); - } - - #[test] - fn an_outline_overrides_only_what_it_sets() { - let style = state(json!({"outlineColor": 5, "outlineWidth": 2.0})); - assert_eq!(style.outline((1, 9.0, 3.0)), (5, 2.0, 3.0)); - } - - #[test] - fn a_transform_needs_all_sixteen_numbers() { - assert!(state(json!({"transform": [1, 0]})).transform().is_none()); - let matrix: Vec = (0..16).map(f64::from).collect(); - assert_eq!( - state(json!({"transform": matrix})).transform().unwrap()[5], - 5.0 - ); - } - - #[test] - fn an_animated_property_is_left_out_of_the_refinement() { - let style = state(json!({"backgroundColor": 4278190080u32, "opacity": 0.2})); - let animating = Animating { - background: true, - opacity: false, - }; - let refinement = style.refinement((1.0, 1.0), animating); - assert!(refinement.background.is_none()); - assert_eq!(refinement.opacity, Some(0.2)); - } - - #[test] - fn a_view_with_no_state_props_has_no_state_styles() { - assert!(StateStyles::from_flat(&ViewProps::default()).is_none()); - } - - #[test] - fn a_group_style_needs_a_group_name() { - let mut view = ViewProps::default(); - view.group_hover_style = r#"{"group":"","style":{"opacity":1}}"#.to_string(); - assert!(StateStyles::from_flat(&view).is_none()); - view.group_hover_style = r#"{"group":"row","style":{"opacity":1}}"#.to_string(); - let styles = StateStyles::from_flat(&view).unwrap(); - assert_eq!(styles.group_hover.as_ref().unwrap().group.as_ref(), "row"); - } - - #[test] - fn invalid_json_is_ignored() { - let mut view = ViewProps::default(); - view.hover_style = "{".to_string(); - assert!(StateStyles::from_flat(&view).is_none()); - } - - #[test] - fn any_state_can_set_the_text_color() { - let mut view = ViewProps::default(); - view.active_style = r#"{"color":4294901760}"#.to_string(); - assert!(StateStyles::from_flat(&view).unwrap().sets_color()); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/surface.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/surface.rs deleted file mode 100644 index dab273d6da..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/surface.rs +++ /dev/null @@ -1,653 +0,0 @@ -//! A React surface placed inside a GPUI tree. -//! -//! A [`ReactSurface`] is an entity that owns one Fabric surface: it allocates a -//! surface id, starts the surface, renders the surface's `SurfaceRootView` as -//! its child, and stops the surface when it is dropped. It is what lets a -//! GPUI-first app — or another GPUI tree in this runtime — show React content in -//! a box that GPUI laid out: -//! -//! ```ignore -//! div().flex().child(sidebar).child( -//! cx.new(|cx| ReactSurface::new("SettingsPanel", cx) -//! .props(serde_json::json!({ "userId": 42 })) -//! .sizing(SurfaceSizing::Fill)) -//! ) -//! ``` -//! -//! # Layout -//! -//! One engine owns each subtree, and the boundary exchanges a constraint and a -//! measured size: -//! -//! * [`SurfaceSizing::Fill`] takes the bounds taffy gives the element. In -//! `prepaint`, when the bounds differ from the last size sent, -//! `set_surface_size` is called; React lays out one commit later. That is what -//! windows do today on resize. -//! * [`SurfaceSizing::FitContent`] is a measured leaf: the surface is started -//! with *constraints* instead of an exact size, and the size Fabric reports -//! back in each mount batch is the leaf's measured size. When that size -//! changes, the entity is notified and taffy measures it again. -//! -//! # Surface ids -//! -//! Surfaces use odd ids only; React tags are even. The allocator hands out odd -//! ids from a process-wide counter above the fixed ones (`1` window root, `2` -//! LogBox), so an embedded surface never collides with either. - -use crate::host::Host; -use crate::store::{store_from, SurfaceRootView, APP_SURFACE_ID}; -use gpui::{ - div, prelude::*, px, AnyElement, App, Bounds, Context, Entity, IntoElement, Pixels, Render, - Size, Window, -}; -use serde_json::Value; -use std::cell::Cell; - -/// The LogBox surface, started directly by C++. -const LOGBOX_SURFACE_ID: i32 = 2; - -/// How a surface sizes itself inside the GPUI tree that holds it. -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum SurfaceSizing { - /// Take the box taffy gives the element. The surface is told an exact size, - /// and React lays out to it. - Fill, - /// Ask for the size the React content wants. The surface is started with - /// constraints, the size comes back with the mount batches, and taffy lays - /// out around it. - FitContent { - /// The largest box the content may take. `None` leaves it unbounded on - /// that axis, which is what a scroll container around it wants. - max_width: Option, - max_height: Option, - /// The smallest box, which a component with chrome around it uses so it - /// does not collapse to zero before the first measurement. - min_width: f32, - min_height: f32, - }, -} - -impl SurfaceSizing { - /// `FitContent` with no bounds, the common case. - pub fn fit_content() -> Self { - Self::FitContent { - max_width: None, - max_height: None, - min_width: 0.0, - min_height: 0.0, - } - } - - fn is_fit_content(&self) -> bool { - matches!(self, Self::FitContent { .. }) - } -} - -impl Default for SurfaceSizing { - fn default() -> Self { - Self::Fill - } -} - -/// Allocates the next odd surface id. -fn next_surface_id() -> i32 { - use std::sync::atomic::{AtomicI32, Ordering}; - static NEXT: AtomicI32 = AtomicI32::new(3); - loop { - let candidate = NEXT.fetch_add(2, Ordering::Relaxed); - if candidate > APP_SURFACE_ID && candidate != LOGBOX_SURFACE_ID { - return candidate; - } - } -} - -/// The last size a surface reported, shared with the element that draws it. -#[derive(Clone, Default)] -pub struct SurfaceContentSize(std::rc::Rc>>); - -impl SurfaceContentSize { - pub(crate) fn set(&self, size: (f32, f32)) -> bool { - let changed = self.0.get() != Some(size); - if changed { - self.0.set(Some(size)); - } - changed - } - - pub fn get(&self) -> Option<(f32, f32)> { - self.0.get() - } -} - -/// Where a surface's box is in its window, shared with every node it mounts. -#[derive(Clone, Default)] -pub struct SurfaceOrigin(std::rc::Rc>>); - -impl SurfaceOrigin { - pub(crate) fn set(&self, origin: (f32, f32)) { - self.0.set(Some(origin)); - } - - pub fn get(&self) -> (f32, f32) { - self.0.get().unwrap_or_default() - } - - /// Whether GPUI placed the surface, which makes its nodes' frames window - /// coordinates already. - pub fn is_placed(&self) -> bool { - self.0.get().is_some() - } -} - -/// One React surface inside a GPUI tree. -pub struct ReactSurface { - surface_id: i32, - module: String, - props: Value, - sizing: SurfaceSizing, - /// The root entity, once the store has made it. A `ReactSurface` is created - /// before any mount batch, and the store is what creates and owns a root, so - /// this is filled on the first render. - root: Option>, - /// The scale the surface was last started or resized at. - scale: f32, - /// The exact size last sent, for `Fill`. - sent_size: Cell>, - /// The constraints last sent, for `FitContent`. - sent_constraints: Cell>, - /// What the React content last reported wanting. - pub(crate) content_size: SurfaceContentSize, - /// Where the surface's box is in its window. - pub(crate) origin: SurfaceOrigin, - /// Whether the surface has been started, so `Drop` knows whether to stop it. - started: bool, -} - -impl ReactSurface { - /// A surface showing `module`, sized by `Fill` until told otherwise. - pub fn new(module: impl Into, _cx: &mut App) -> Self { - Self { - surface_id: next_surface_id(), - module: module.into(), - props: Value::Object(Default::default()), - sizing: SurfaceSizing::Fill, - root: None, - scale: 1.0, - sent_size: Cell::new(None), - sent_constraints: Cell::new(None), - content_size: SurfaceContentSize::default(), - origin: SurfaceOrigin::default(), - started: false, - } - } - - /// The `initialProps` the surface's module receives. - #[must_use] - pub fn props(mut self, props: Value) -> Self { - self.props = if props.is_object() { - props - } else { - Value::Object(Default::default()) - }; - self - } - - /// How the surface sizes itself. - #[must_use] - pub fn sizing(mut self, sizing: SurfaceSizing) -> Self { - self.sizing = sizing; - self - } - - /// This surface's id. - pub fn surface_id(&self) -> i32 { - self.surface_id - } - - /// The size the React content last reported wanting, if it reports one. - pub fn content_size(&self) -> Option<(f32, f32)> { - self.content_size.get() - } - - /// Starts the surface at `bounds`, once. - fn start(&mut self, bounds: Bounds, scale: f32, cx: &mut Context) { - if self.started { - return; - } - let Some(store) = store_from(cx) else { - log::warn!( - "[surface] no store yet; surface {} will start on a later frame", - self.surface_id - ); - return; - }; - let host: Host = store.read(cx).host.clone(); - let width = f32::from(bounds.size.width).max(1.0); - let height = f32::from(bounds.size.height).max(1.0); - let props_json = self.props.to_string(); - match self.sizing { - SurfaceSizing::Fill => { - host.start_surface_with_props( - self.surface_id, - &self.module, - &props_json, - width, - height, - scale, - ); - self.sent_size.set(Some((width, height))); - } - SurfaceSizing::FitContent { - max_width, - max_height, - min_width, - min_height, - } => { - let max_width = max_width.unwrap_or(f32::INFINITY).max(min_width); - let max_height = max_height.unwrap_or(f32::INFINITY).max(min_height); - host.start_surface_with_constraints( - self.surface_id, - &self.module, - &props_json, - min_width, - min_height, - max_width, - max_height, - scale, - ); - self.sent_constraints - .set(Some((min_width, min_height, max_width, max_height))); - } - } - let content_size = self.content_size.clone(); - let origin = self.origin.clone(); - let notify = cx.entity().downgrade(); - let surface_id = self.surface_id; - self.root = Some(store.update(cx, |store, cx| { - store.use_surface_origin(surface_id, origin); - let root = store.ensure_embedded_root(surface_id, cx); - store.observe_surface_content_size(surface_id, content_size, notify); - root - })); - self.scale = scale; - self.started = true; - log::info!( - "[surface] started surface {} ({}) at {width}x{height} scale {scale}", - self.surface_id, - self.module - ); - } - - /// Keeps a `Fill` surface the same size as its box. - fn sync_fill_size(&mut self, bounds: Bounds, scale: f32, cx: &mut App) { - let width = f32::from(bounds.size.width).max(1.0); - let height = f32::from(bounds.size.height).max(1.0); - let size = (width, height); - if self.sent_size.get() == Some(size) && self.scale == scale { - return; - } - self.sent_size.set(Some(size)); - self.scale = scale; - if let Some(store) = store_from(cx) { - store - .read(cx) - .host - .set_surface_size(self.surface_id, width, height, scale); - log::debug!( - "[surface] surface {} resized to {width}x{height}", - self.surface_id - ); - } - } - - /// Keeps a `FitContent` surface's constraints in step with its box. - fn sync_fit_constraints(&mut self, scale: f32, cx: &mut App) { - let (min_width, min_height, max_width, max_height) = match self.sizing { - SurfaceSizing::FitContent { - max_width, - max_height, - min_width, - min_height, - } => ( - min_width, - min_height, - max_width.unwrap_or(f32::INFINITY).max(min_width), - max_height.unwrap_or(f32::INFINITY).max(min_height), - ), - SurfaceSizing::Fill => return, - }; - let constraints = (min_width, min_height, max_width, max_height); - if self.sent_constraints.get() == Some(constraints) && self.scale == scale { - return; - } - self.sent_constraints.set(Some(constraints)); - self.scale = scale; - if let Some(store) = store_from(cx) { - store.read(cx).host.set_surface_constraints( - self.surface_id, - min_width, - min_height, - max_width, - max_height, - scale, - ); - } - } -} - -impl Drop for ReactSurface { - fn drop(&mut self) { - if !self.started { - return; - } - crate::host::stop_surface_without_app(self.surface_id); - log::info!("[surface] stopped surface {}", self.surface_id); - } -} - -impl Render for ReactSurface { - fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let surface = cx.entity().downgrade(); - div().relative().size_full().child(SurfaceHost { - surface, - sizing: self.sizing, - content_size: self.content_size.clone(), - root: self.root.clone(), - }) - } -} - -/// The element that places a surface and tells it its box. -struct SurfaceHost { - surface: gpui::WeakEntity, - sizing: SurfaceSizing, - content_size: SurfaceContentSize, - /// The surface's root entity, rendered as the host's child once the store - /// has made one. A surface must show its React tree, or it is just a box. - root: Option>, -} - -impl IntoElement for SurfaceHost { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - -impl Element for SurfaceHost { - /// The surface's root, laid out once and painted in `paint`. - type RequestLayoutState = Option; - type PrepaintState = (); - - fn id(&self) -> Option { - None - } - - fn source_location(&self) -> Option<&'static core::panic::Location<'static>> { - None - } - - fn request_layout( - &mut self, - _id: Option<&gpui::GlobalElementId>, - _inspector_id: Option<&gpui::InspectorElementId>, - window: &mut Window, - cx: &mut App, - ) -> (gpui::LayoutId, Self::RequestLayoutState) { - let mut style = gpui::Style::default(); - let mut child = self.root.clone().map(|root| root.into_any_element()); - let child_layout: Option = child - .as_mut() - .map(|element| element.request_layout(window, cx)); - let children: Vec = child_layout.into_iter().collect(); - let layout = match self.sizing { - SurfaceSizing::Fill => { - style.size.width = gpui::relative(1.0).into(); - style.size.height = gpui::relative(1.0).into(); - window.request_layout(style, children, cx) - } - SurfaceSizing::FitContent { - max_width, - max_height, - min_width, - min_height, - } => { - let measured = SurfaceMeasure::new( - self.content_size.clone(), - Size { - width: max_width, - height: max_height, - }, - Size { - width: min_width, - height: min_height, - }, - ) - .measured(); - style.size.width = measured.width.into(); - style.size.height = measured.height.into(); - window.request_layout(style, children, cx) - } - }; - (layout, child) - } - - fn prepaint( - &mut self, - _id: Option<&gpui::GlobalElementId>, - _inspector_id: Option<&gpui::InspectorElementId>, - bounds: Bounds, - request_layout: &mut Self::RequestLayoutState, - window: &mut Window, - cx: &mut App, - ) -> Self::PrepaintState { - if let Some(child) = request_layout { - child.prepaint(window, cx); - } - let scale = window.scale_factor(); - let sizing = self.sizing; - let _ = self.surface.update(cx, |surface, cx| { - if !surface.started { - surface.start(bounds, scale, cx); - } - surface - .origin - .set((f32::from(bounds.origin.x), f32::from(bounds.origin.y))); - match sizing { - SurfaceSizing::Fill => surface.sync_fill_size(bounds, scale, cx), - SurfaceSizing::FitContent { .. } => surface.sync_fit_constraints(scale, cx), - } - }); - } - - fn paint( - &mut self, - _id: Option<&gpui::GlobalElementId>, - _inspector_id: Option<&gpui::InspectorElementId>, - _bounds: Bounds, - request_layout: &mut Self::RequestLayoutState, - _prepaint: &mut Self::PrepaintState, - window: &mut Window, - cx: &mut App, - ) { - if let Some(child) = request_layout { - child.paint(window, cx); - } - } -} - -/// Renders a surface at a fixed size, for an app that does not want taffy to -/// size it. Used by the tester and by [`ReactSurface`]'s own docs. -pub fn surface_element(surface: Entity) -> AnyElement { - div().flex_none().child(surface).into_any_element() -} - -/// A measured leaf whose size comes from a surface's reported content size. -pub struct SurfaceMeasure { - content: SurfaceContentSize, - max: Size>, - min: Size, -} - -impl SurfaceMeasure { - pub(crate) fn new(content: SurfaceContentSize, max: Size>, min: Size) -> Self { - Self { content, max, min } - } - - /// The size to lay the leaf out at, clamped to the constraints. - pub fn measured(&self) -> Size { - let (width, height) = self - .content - .get() - .unwrap_or((self.min.width, self.min.height)); - let width = self - .max - .width - .map_or(width, |max| width.min(max)) - .max(self.min.width); - let height = self - .max - .height - .map_or(height, |max| height.min(max)) - .max(self.min.height); - gpui::size(px(width), px(height)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn surface_ids_are_odd_and_avoid_the_fixed_ones() { - let ids: Vec = (0..8).map(|_| next_surface_id()).collect(); - for id in &ids { - assert_eq!(id % 2, 1, "surface ids are odd: {id}"); - assert_ne!(*id, APP_SURFACE_ID); - assert_ne!(*id, LOGBOX_SURFACE_ID); - } - let mut sorted = ids.clone(); - sorted.sort_unstable(); - sorted.dedup(); - assert_eq!(sorted.len(), ids.len(), "ids are unique: {ids:?}"); - assert!(ids.windows(2).all(|pair| pair[0] < pair[1]), "ids increase"); - } - - #[test] - fn a_surface_origin_is_shared_and_read_live() { - let origin = SurfaceOrigin::default(); - let node_side = origin.clone(); - assert_eq!(node_side.get(), (0.0, 0.0)); - origin.set((240.0, 32.0)); - assert_eq!(node_side.get(), (240.0, 32.0)); - } - - #[test] - fn an_unbounded_fit_axis_is_infinite_not_the_current_box() { - let measure = SurfaceMeasure::new( - SurfaceContentSize::default(), - Size { - width: None, - height: None, - }, - Size { - width: 0.0, - height: 0.0, - }, - ); - assert_eq!(measure.measured(), gpui::size(px(0.0), px(0.0))); - let content = SurfaceContentSize::default(); - content.set((180.0, 96.0)); - let measure = SurfaceMeasure::new( - content, - Size { - width: None, - height: None, - }, - Size { - width: 0.0, - height: 0.0, - }, - ); - assert_eq!(measure.measured(), gpui::size(px(180.0), px(96.0))); - } - - #[test] - fn fill_is_the_default_sizing() { - assert_eq!(SurfaceSizing::default(), SurfaceSizing::Fill); - assert!(!SurfaceSizing::Fill.is_fit_content()); - } - - #[test] - fn fit_content_without_bounds_is_unbounded_with_a_zero_minimum() { - match SurfaceSizing::fit_content() { - SurfaceSizing::FitContent { - max_width, - max_height, - min_width, - min_height, - } => { - assert_eq!(max_width, None); - assert_eq!(max_height, None); - assert_eq!(min_width, 0.0); - assert_eq!(min_height, 0.0); - } - other => panic!("expected FitContent, got {other:?}"), - } - } - - #[test] - fn a_measured_leaf_uses_the_reported_size_clamped_to_its_bounds() { - let content = SurfaceContentSize::default(); - let measure = SurfaceMeasure::new( - content.clone(), - Size { - width: Some(200.0), - height: Some(100.0), - }, - Size { - width: 10.0, - height: 10.0, - }, - ); - assert_eq!(measure.measured(), gpui::size(px(10.0), px(10.0))); - - assert!(content.set((50.0, 40.0))); - assert_eq!(measure.measured(), gpui::size(px(50.0), px(40.0))); - - assert!(content.set((500.0, 400.0))); - assert_eq!(measure.measured(), gpui::size(px(200.0), px(100.0))); - - assert!(content.set((1.0, 1.0))); - assert_eq!(measure.measured(), gpui::size(px(10.0), px(10.0))); - } - - #[test] - fn an_unbounded_measured_leaf_takes_the_reported_size() { - let content = SurfaceContentSize::default(); - let measure = SurfaceMeasure::new( - content.clone(), - Size { - width: None, - height: None, - }, - Size { - width: 0.0, - height: 0.0, - }, - ); - assert!(content.set((321.0, 123.0))); - assert_eq!(measure.measured(), gpui::size(px(321.0), px(123.0))); - } - - #[test] - fn a_content_size_only_reports_a_change_once() { - let content = SurfaceContentSize::default(); - assert_eq!(content.get(), None); - assert!(content.set((100.0, 50.0))); - assert!(!content.set((100.0, 50.0))); - assert_eq!(content.get(), Some((100.0, 50.0))); - assert!(content.set((120.0, 50.0))); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/test_driver.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/test_driver.rs deleted file mode 100644 index 64cb889869..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/test_driver.rs +++ /dev/null @@ -1,3116 +0,0 @@ -use crate::{node_view::RNNodeView, store::ViewStore}; -use async_channel::{Receiver, Sender}; -use base64::Engine; -use gpui::{point, px, AnyWindowHandle, App, AppContext, Entity}; -use rn_gpui_sys::ffi::RectF; -use serde_json::{json, Value}; -use std::{ - io::Write, - net::TcpListener, - sync::mpsc::{self, SyncSender}, - thread, - time::{Duration, Instant}, -}; -use tungstenite::{accept, Message}; - -const PROTOCOL_VERSION: u32 = 1; - -// SAFETY: the signatures match the definitions in the C++ host. -unsafe extern "C" { - fn rn_gpui_http_requests_not_ignored(patterns: *const std::ffi::c_char) -> u64; - fn rn_gpui_mount_batches_in_flight() -> u64; - fn rn_gpui_pending_timers_due_within(window_ms: u64) -> u64; - fn rn_gpui_pending_timers_dump(window_ms: u64, buffer: *mut u8, capacity: u64) -> u64; - fn rn_gpui_websocket_messages_in_flight() -> u64; - fn rn_gpui_pending_js_tasks() -> u64; - fn rn_gpui_pending_js_tasks_dump(buffer: *mut u8, capacity: u64) -> u64; - fn rn_gpui_native_animations_active() -> u64; - fn rn_gpui_frame_demand() -> u64; - fn rn_gpui_pending_work() -> u64; - fn rn_gpui_rust_promises_in_flight(younger_than_ms: u64) -> u64; - fn rn_gpui_request_reload(); - fn rn_gpui_reload_in_progress() -> bool; - /// Counts the React instances created so far. It changes when a reload - /// mounts a new one, which is how a caller waits for the replacement - /// instead of guessing from an empty tree. - fn rn_gpui_instance_generation() -> u64; -} - -struct Request { - value: Value, - reply: SyncSender, -} - -/// The generation of the React instance currently mounted, or 0 before the host -/// has created one. Reported by `hello`, `tree` and `reload` so a client can -/// wait for a *particular* instance after a reload. -#[cfg(target_os = "macos")] -fn dock_menu(command: &str, params: &Value) -> Value { - use cocoa::base::id; - use objc::{class, msg_send, sel, sel_impl}; - // SAFETY: AppKit is messaged on the main thread, where the driver runs; the - // menu is the delegate's own and outlives this call. - unsafe { - let app: id = msg_send![class!(NSApplication), sharedApplication]; - let delegate: id = msg_send![app, delegate]; - let menu: id = msg_send![delegate, applicationDockMenu: app]; - if menu.is_null() { - return json!({"titles": Vec::::new()}); - } - if command == "dockMenuPress" { - let index = params.get("index").and_then(Value::as_i64).unwrap_or(0); - let _: () = msg_send![menu, performActionForItemAtIndex: index as isize]; - return json!({"pressed": index}); - } - let count: isize = msg_send![menu, numberOfItems]; - let titles: Vec = (0..count) - .map(|index| { - let item: id = msg_send![menu, itemAtIndex: index]; - let title: id = msg_send![item, title]; - let bytes: *const std::os::raw::c_char = msg_send![title, UTF8String]; - std::ffi::CStr::from_ptr(bytes) - .to_string_lossy() - .into_owned() - }) - .collect(); - json!({"titles": titles}) - } -} - -#[cfg(not(target_os = "macos"))] -fn dock_menu(_command: &str, _params: &Value) -> Value { - json!({"error": "the Dock menu is only available on macOS"}) -} - -fn instance_generation() -> u64 { - // SAFETY: the C++ function takes no arguments and reads an atomic. - unsafe { rn_gpui_instance_generation() } -} - -pub(crate) fn start(app: &mut App, store: Entity, window: AnyWindowHandle) { - let token = std::env::var("RN_GPUI_TEST_DRIVER_TOKEN") - .expect("RN_GPUI_TEST_DRIVER=1 requires RN_GPUI_TEST_DRIVER_TOKEN"); - let listener = - TcpListener::bind("127.0.0.1:0").expect("could not bind the GPUI test driver to loopback"); - let port = listener - .local_addr() - .expect("driver listener has address") - .port(); - let (tx, rx) = async_channel::unbounded::(); - - app.spawn(async move |cx| serve_commands(rx, store, window, cx).await) - .detach(); - - thread::Builder::new() - .name("rn-gpui-test-driver".into()) - .spawn(move || serve_socket(listener, token, tx)) - .expect("could not start GPUI test driver thread"); - println!("RN_GPUI_TEST_DRIVER_PORT={port}"); - let _ = std::io::stdout().flush(); -} - -async fn serve_commands( - rx: Receiver, - store: Entity, - window: AnyWindowHandle, - cx: &mut gpui::AsyncApp, -) { - while let Ok(request) = rx.recv().await { - let id = request.value.get("id").cloned().unwrap_or(Value::Null); - let method = request - .value - .get("method") - .and_then(Value::as_str) - .unwrap_or(""); - let params = request.value.get("params").cloned().unwrap_or(json!({})); - - let result = match method { - "hello" => { - let (width, height, scale) = cx - .update_window(window, |_, window, _| { - let size = window.viewport_size(); - ( - f32::from(size.width), - f32::from(size.height), - window.scale_factor(), - ) - }) - .unwrap_or((0.0, 0.0, 1.0)); - json!({"protocol": PROTOCOL_VERSION, "platform": "desktop", "scale": scale, - // The React instance this tree belongs to. A client uses it - // to wait for the replacement after a reload; it is 0 only - // before the host has created any instance at all. - "generation": instance_generation(), - // Every backend that implements `Window::render_to_image` can - // answer `screenshot`: gpui_macos/metal, gpui_linux (X11 and - // Wayland) and gpui_windows/Direct3D all do. - "capture": cfg!(feature = "visual-capture") && cfg!(any(target_os = "macos", target_os = "linux", target_os = "windows")), - "animationsDisabled": crate::animation_policy::animations_disabled(), - "windowSize": {"width": width, "height": height}, "appName": std::env::var("RN_GPUI_APP_ID").unwrap_or_default()}) - } - "getWindowBounds" => cx.update_window(window, |_,window,_| { - let bounds = window.bounds(); - #[cfg(target_os = "macos")] - let hidden = !crate::native_view::test_window_visible(window); - // Offscreen test windows are created unmapped on Linux, so - // the X11 map state reports them as hidden; a real window - // session stays viewable. - #[cfg(target_os = "linux")] - let hidden = crate::desktop::platform_window::is_minimized(window); - // A window created with `show: false` (the offscreen test - // mode) is not `IsWindowVisible`; a real one is, even when - // another window covers it. - #[cfg(target_os = "windows")] - let hidden = crate::desktop::platform_window::is_hidden(window); - #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] - let hidden = false; - json!({"x":f32::from(bounds.origin.x),"y":f32::from(bounds.origin.y),"width":f32::from(bounds.size.width),"height":f32::from(bounds.size.height), "hidden":hidden}) - }).unwrap_or_else(|error|json!({"error":error.to_string()})), - #[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))] - "compositeCapture" => cx - .update_window(window, |_, window, _| { - match composite_png(window) { - Ok((png, width, height)) => json!({ - "png": base64::engine::general_purpose::STANDARD.encode(png), - "width": width, - "height": height, - "scale": window.scale_factor(), - "viewport": { - "width": f32::from(window.viewport_size().width), - "height": f32::from(window.viewport_size().height), - }, - }), - Err(error) => json!({"error": error}), - } - }) - .unwrap_or_else(|error| json!({"error": error.to_string()})), - "compositionLayers" => cx - .update_window(window, |_, window, _| { - json!({"count": window.composed_scene_layers().len()}) - }) - .unwrap_or_else(|error| json!({"error": error.to_string()})), - "nativeSurfaces" => { - let (scale, layers) = cx - .update_window(window, |_, window, _| { - (window.scale_factor(), window.composed_scene_layers()) - }) - .unwrap_or((1.0, Vec::new())); - let ops = |surface| { - layers - .iter() - .find(|layer| layer.surface == surface) - .map_or(0, |layer| layer.ranges.iter().map(|range| range.len()).sum()) - }; - let base_ops: usize = layers.first().map_or(0, |layer| { - layer.ranges.iter().map(|range| range.len()).sum() - }); - cx.update_entity(&store, |store, cx| { - let mut surfaces: Vec = store - .nodes - .iter() - .filter_map(|(tag, entity)| { - let node = entity.read(cx); - let surface = node.native_surface()?; - let mut state = surface.test_state(scale); - state["tag"] = json!(tag); - state["testID"] = json!(node.view.test_id); - state["aboveOps"] = json!(ops(surface.above())); - state["baseOps"] = json!(base_ops); - Some(state) - }) - .collect(); - surfaces.sort_by_key(|surface| surface["tag"].as_i64()); - json!({"surfaces": surfaces}) - }) - } - "hostCounters" => { - use crate::counters::{read, reset, Counter}; - let counters = json!({ - "hostRegistryLookups": read(Counter::HostRegistryLookups), - "hostEntryLookups": rn_gpui_sys::ffi::hostEntryLookups(), - "nativeSurfaceWalkNodes": read(Counter::NativeSurfaceWalkNodes), - "hostPropsBytesCopied": read(Counter::HostPropsBytesCopied), - "hostUpdateCalls": read(Counter::HostUpdateCalls), - "hostReportsDelivered": read(Counter::HostReportsDelivered), - "nativeOpsApplied": read(Counter::NativeOpsApplied), - "nativeApplyMicros": read(Counter::NativeApplyMicros), - "nativeRenderMicros": read(Counter::NativeRenderMicros), - "nativeInstancesCreated": read(Counter::NativeInstancesCreated), - "nativeInstancesRecycled": read(Counter::NativeInstancesRecycled), - "nativeRootHolds": read(Counter::NativeRootHolds), - "nativeRootHeldMs": read(Counter::NativeRootHeldMicros) as f64 / 1000.0, - "nativeRootHoldsSkipped": read(Counter::NativeRootHoldsSkipped), - }); - if params.get("reset").and_then(Value::as_bool).unwrap_or(false) { - reset(); - rn_gpui_sys::ffi::resetHostEntryLookups(); - } - counters - } - "displays" => cx.update(|cx| { - let primary = cx.primary_display().map(|display| display.id()); - let rect = |bounds: gpui::Bounds| { - json!({ - "x": f32::from(bounds.origin.x), - "y": f32::from(bounds.origin.y), - "width": f32::from(bounds.size.width), - "height": f32::from(bounds.size.height), - }) - }; - json!(cx - .displays() - .iter() - .map(|display| json!({ - "primary": Some(display.id()) == primary, - "bounds": rect(display.bounds()), - "visibleBounds": rect(display.visible_bounds()), - "scaleFactor": crate::desktop::background::display_scale( - display.id().into() - ), - })) - .collect::>()) - }), - "getWindowSize" => cx - .update_window(window, |_, window, _| { - let size = window.viewport_size(); - json!({"width": f32::from(size.width), "height":f32::from(size.height)}) - }) - .unwrap_or_else(|error| json!({"error":error.to_string()})), - "dockMenu" | "dockMenuPress" => dock_menu(method, ¶ms), - "layoutStats" => { - let reset = params.get("reset").and_then(Value::as_bool).unwrap_or(false); - cx.update_window(window, |_, window, cx| { - let views = crate::store::store_from(cx) - .map_or(0, |store| store.read(cx).nodes.len()); - let stats = window.layout_stats(); - let target_at = crate::wheel::target_at_stats(reset); - let scroll_deltas = crate::wheel::scroll_delta_stats(reset); - let ms = |duration: std::time::Duration| duration.as_secs_f64() * 1000.0; - let report = json!({ - "frames": stats.frames, - "nodesCreated": stats.nodes_created, - "nodesReused": stats.nodes_reused, - "nodesFreed": stats.nodes_freed, - "styleCompares": stats.style_compares, - "styleWrites": stats.style_writes, - "childrenWrites": stats.children_writes, - "measureRebinds": stats.measure_rebinds, - "measurementsKept": stats.measurements_kept, - "measurementsReplayed": stats.measurements_replayed, - "measureCalls": stats.measure_calls, - "measureMs": ms(stats.measure_time), - "computeLayoutCalls": stats.compute_layout_calls, - "buildMs": ms(stats.build_time), - "prepaintMs": ms(stats.prepaint_time), - "paintMs": ms(stats.paint_time), - "computeLayoutMs": ms(stats.compute_layout_time), - "linesShaped": stats.lines_shaped, - "shapeMs": ms(stats.shape_time), - "viewsBuilt": stats.views_built, - "viewsReused": stats.views_reused, - "layerFramesComposited": stats.layer_frames_composited, - "layerFramesRepainted": stats.layer_frames_repainted, - "tilesDirtied": stats.tiles_dirtied, - "layerRebuildsForInput": stats.layer_rebuilds_for_input, - "layersDemoted": stats.layers_demoted, - "layoutNodes": window.layout_node_count(), - "views": views, - "targetAtCalls": target_at.0, - "targetAtMs": target_at.1, - "scrollEvents": scroll_deltas.0, - "scrollEventsWholePixel": scroll_deltas.1, - }); - if reset { - window.reset_layout_stats(); - } - report - }) - .unwrap_or_else(|error| json!({"error": error.to_string()})) - } - "windowAlpha" => cx - .update_window(window, |_, window, _| { - json!({ - "alpha": crate::desktop::platform_window::window_alpha(window), - "revealedBy": crate::desktop::windows::last_reveal(), - }) - }) - .unwrap_or_else(|error| json!({"error": error.to_string()})), - "tooltip" => { - let active = crate::tooltip::active(); - #[cfg(target_os = "macos")] - let (owner_text, tracking_areas) = cx - .update_window(window, |_, window, _| { - crate::tooltip::native_probe(window, active.as_ref().map_or(0, |a| a.tag)) - }) - .unwrap_or((None, 0)); - #[cfg(not(target_os = "macos"))] - let (owner_text, tracking_areas): (Option, usize) = (None, 0); - let drawn = crate::tooltip::drawn(); - json!({ - "mode": crate::tooltip::mode(), - "tag": active.as_ref().map(|active| active.tag), - "text": active.as_ref().map(|active| active.text.clone()), - "rect": active.as_ref().map(|active| active.rect), - "drawn": drawn.map(|drawn| drawn.text), - "ownerText": owner_text, - "trackingAreas": tracking_areas, - }) - } - "focusWindow" => { - let offscreen = std::env::var("RN_GPUI_TEST_OFFSCREEN").as_deref() == Ok("1"); - if !offscreen && crate::desktop::background::enabled() { - // A background run is never the operating system's active - // application, so the window is made active logically. - cx.update(|cx| { - crate::desktop::windows::simulate_activation(cx, 1, true) - .map(|_| json!({"focused": true})) - .unwrap_or_else(|error| error.to_json_value()) - }) - } else { - let hwnd = cx.update_window(window, |_, window, _| { - if offscreen { - return None; - } - window.activate_window(); - #[cfg(target_os = "windows")] - return window_hwnd(window); - #[cfg(not(target_os = "windows"))] - None:: - }); - // The calls send activation messages that re-enter the window - // procedure, so they run after the window update has returned. - #[cfg(target_os = "windows")] - if let Ok(Some(hwnd)) = hwnd { - bring_to_front(hwnd); - } - match hwnd { - Ok(_) => json!({"focused":true}), - Err(error) => json!({"error":error.to_string()}), - } - } - } - "setScrollerStyle" => { - let legacy = params.get("legacy").and_then(Value::as_bool).unwrap_or(false); - cx.update(|cx| crate::scroller_style::set_for_test(legacy, cx)); - json!({"legacy": legacy}) - } - "setWindowActive" => { - let key = params.get("windowId").and_then(Value::as_u64).unwrap_or(1) as u32; - let active = params.get("active").and_then(Value::as_bool).unwrap_or(true); - cx.update(|cx| { - crate::desktop::windows::simulate_activation(cx, key, active) - .unwrap_or_else(|error| error.to_json_value()) - }) - } - "focusReadout" => { - let mirror = crate::desktop::window_mirror::get(1) - .and_then(|state| state.get("isFocused").cloned()) - .unwrap_or(Value::Null); - #[cfg(target_os = "windows")] - let mut readout = cx - .update_window(window, |_, window, _| window_hwnd(window)) - .ok() - .flatten() - .map(focus_readout) - .unwrap_or_else(|| json!({})); - #[cfg(not(target_os = "windows"))] - let mut readout = json!({}); - readout["mirrorIsFocused"] = mirror; - readout - } - "a11yTree" => { - let activated = cx - .update_window(window, |_, window, _| { - static ASKED: std::sync::atomic::AtomicBool = - std::sync::atomic::AtomicBool::new(false); - if window.is_a11y_active() - || ASKED.swap(true, std::sync::atomic::Ordering::Relaxed) - { - return false; - } - #[cfg(target_os = "macos")] - crate::native_view::activate_accessibility_probe(window); - #[cfg(target_os = "windows")] - activate_accessibility_probe(window); - window.refresh(); - true - }) - .unwrap_or(false); - if activated { - wait_for_frame(window, cx, Duration::from_millis(16)).await; - wait_for_frame(window, cx, Duration::from_millis(16)).await; - } - cx.update_window(window, |_, window, _| window.debug_a11y_tree_json()) - .map(|tree| { - tree.and_then(|tree| serde_json::from_str::(&tree).ok()) - .unwrap_or(Value::Null) - }) - .unwrap_or_else(|error| json!({"error":error.to_string()})) - } - "a11yNode" => { - #[cfg(target_os = "macos")] - { - let identifier = params - .get("identifier") - .and_then(Value::as_str) - .unwrap_or(""); - cx.update_window(window, |_, window, _| { - crate::native_view::test_accessibility_node(window, identifier) - }) - .ok() - .flatten() - .unwrap_or(Value::Null) - } - #[cfg(any(target_os = "linux", target_os = "windows"))] - { - // Resolve through GPUI's own AccessKit tree: the node whose - // author id (Element::accessibility_id, set from the React - // Native testID) matches. On Linux AccessKit's AT-SPI adapter - // publishes the same tree; on Windows it maps the author id - // to the UI Automation `AutomationId`, so no external client - // is needed to read it back here. - #[cfg(target_os = "windows")] - let _ = cx.update_window(window, |_, window, _| { - activate_accessibility_probe(window); - window.refresh(); - }); - let identifier = params - .get("identifier") - .and_then(Value::as_str) - .unwrap_or(""); - let tree = cx - .update_window(window, |_, window, _| window.debug_a11y_tree_json()) - .ok() - .flatten() - .and_then(|tree| serde_json::from_str::(&tree).ok()); - match tree { - None => { - json!({"error":"the native accessibility tree is unavailable"}) - } - Some(tree) => { - let node = tree - .get("nodes") - .and_then(Value::as_object) - .and_then(|nodes| { - nodes.values().find(|node| { - node.get("author_id").and_then(Value::as_str) - == Some(identifier) - && node - .get("aria") - .and_then(|aria| aria.get("hidden")) - .and_then(Value::as_bool) - != Some(true) - }) - }) - .cloned(); - match node { - Some(node) => { - let aria = - node.get("aria").cloned().unwrap_or(Value::Null); - let text = |key: &str| { - aria.get(key).and_then(Value::as_str).unwrap_or("") - }; - let label = text("label"); - let value = text("value"); - json!({ - "identifier": identifier, - "name": if label.is_empty() { value } else { label }, - "role": text("role"), - "hint": text("description"), - "enabled": aria.get("disabled").and_then(Value::as_bool) != Some(true), - }) - } - None => Value::Null, - } - } - } - } - #[cfg(not(any( - target_os = "macos", - target_os = "linux", - target_os = "windows" - )))] - { - json!({"error":"Native identifier lookup is pending platform testing; use a11yTree"}) - } - } - "reload" => { - // The generation *before* the request: the reload happens on - // another thread, so the reply carries the value the caller has - // to wait past, not the one it will end up at. - let generation = instance_generation(); - // SAFETY: the C++ function takes no arguments and queues a reload. - unsafe { - rn_gpui_request_reload(); - } - json!({"reloading":true, "generation": generation}) - } - "setAnimationsEnabled" => match params.get("enabled").and_then(Value::as_bool) { - Some(enabled) => { - crate::animation_policy::set_animations_disabled(!enabled); - json!({"enabled": enabled}) - } - None => { - json!({"error": "setAnimationsEnabled requires a boolean enabled value"}) - } - }, - "setWindowSize" => { - let width = params.get("width").and_then(Value::as_f64).unwrap_or(0.0) as f32; - let height = params.get("height").and_then(Value::as_f64).unwrap_or(0.0) as f32; - if !width.is_finite() || !height.is_finite() || width < 1.0 || height < 1.0 { - json!({"error": "setWindowSize requires positive finite width and height"}) - } else { - let requested = gpui::size(px(width), px(height)); - let resized = cx.update_window(window, move |_root, window, app| { - window.resize(requested); - window.bounds_changed(app); - }); - match resized { - Err(error) => json!({"error": error.to_string()}), - Ok(()) => { - // A window manager applies the resize asynchronously, - // so wait (bounded) until the new size takes effect. A - // never-mapped window has it immediately. - let deadline = - std::time::Instant::now() + std::time::Duration::from_secs(2); - let reply = loop { - let size = cx - .update_window(window, |_, window, app| { - window.bounds_changed(app); - window.viewport_size() - }) - .unwrap_or_default(); - if (f32::from(size.width), f32::from(size.height)) - == (width, height) - || std::time::Instant::now() >= deadline - { - break json!({ - "width": f32::from(size.width), - "height": f32::from(size.height), - }); - } - wait_for_frame(window, cx, std::time::Duration::from_millis(16)) - .await; - }; - // React lays the surface out at the new size later: a - // resize soon after another is held back for the - // store's resize interval, and the layout is a JS - // commit. Frames, hit tests and screenshots taken - // before it lands see the old layout, so wait - // (bounded) until the surface's top views fill it. - let deadline = - std::time::Instant::now() + std::time::Duration::from_secs(5); - let mut laid_out = false; - while std::time::Instant::now() < deadline { - laid_out = cx.update_entity(&store, |store, cx| { - store.window_layout_matches_size(window, cx) - }); - if laid_out { - break; - } - wait_for_frame(window, cx, std::time::Duration::from_millis(16)) - .await; - } - let mut reply = reply; - reply["laidOut"] = json!(laid_out); - reply - } - } - } - } - "query" | "tree" | "getProps" => { - let viewport = cx - .update_window(window, |_, window, _| { - let size = window.viewport_size(); - RectF { - x: 0.0, - y: 0.0, - w: f32::from(size.width) / crate::desktop::zoom::get(crate::store::APP_SURFACE_ID), - h: f32::from(size.height) / crate::desktop::zoom::get(crate::store::APP_SURFACE_ID), - } - }) - .unwrap_or_default(); - cx.update_entity(&store, |store, cx| match method { - "query" => query(store, ¶ms, viewport, cx), - "tree" => tree(store, cx), - _ => get_props(store, ¶ms, cx), - }) - } - "click" => { - // A screen transition paints its card away from the frame - // `node_visible_frame` reports, so a click dispatched now would - // land next to the node it names (`waitForIdle` waits for it, but - // a click that follows a push does not always reach that wait). - // `wait_for_frame` keeps drawing, which is what advances the - // transition. - let settle_until = Instant::now() + Duration::from_millis(1_000); - while Instant::now() < settle_until - && cx.update_entity(&store, |store, cx| { - store - .nodes - .values() - .any(|node| node.read(cx).transition_active(cx)) - }) - { - if !wait_for_frame(window, cx, Duration::from_millis(16)).await { - break; - } - } - let viewport = cx - .update_window(window, |_, window, _| { - let size = window.viewport_size(); - RectF { - x: 0.0, - y: 0.0, - w: f32::from(size.width) / crate::desktop::zoom::get(crate::store::APP_SURFACE_ID), - h: f32::from(size.height) / crate::desktop::zoom::get(crate::store::APP_SURFACE_ID), - } - }) - .ok(); - let target = viewport.and_then(|viewport| { - cx.update_entity(&store, |store, cx| { - let tag = params.get("tag").and_then(Value::as_i64)? as i32; - if let Some((position, root_tag)) = - crate::builtins::native_root::pointer_target(tag) - { - return Some(Ok((position, root_tag))); - } - let node = store.nodes.get(&tag)?; - if node.read(cx).view.accessibility_disabled { - return Some(Err("click target is disabled")); - } - let frame = node_visible_frame(store, tag, viewport, cx); - Some(frame.map_or(Err("click target is not visible"), |frame| { - Ok(( - frame_center(frame, window_offset(store, tag, cx)), - tag, - )) - })) - }) - }); - match target { - Some(Ok((position, tag))) => { - let button = match params.get("button").and_then(Value::as_str) { - Some("right") => gpui::MouseButton::Right, - Some("middle") => gpui::MouseButton::Middle, - Some("back") => gpui::MouseButton::Navigate(gpui::NavigationDirection::Back), - Some("forward") => gpui::MouseButton::Navigate(gpui::NavigationDirection::Forward), - _ => gpui::MouseButton::Left, - }; - let click_count = params - .get("clickCount") - .and_then(Value::as_u64) - .unwrap_or(1) - .clamp(1, 3) as usize; - let modifiers = params.get("modifiers").cloned().unwrap_or(Value::Null); - let modifiers = gpui::Modifiers { - control: modifiers - .get("control") - .and_then(Value::as_bool) - .unwrap_or(false), - alt: modifiers - .get("alt") - .and_then(Value::as_bool) - .unwrap_or(false), - shift: modifiers - .get("shift") - .and_then(Value::as_bool) - .unwrap_or(false), - platform: modifiers - .get("platform") - .and_then(Value::as_bool) - .unwrap_or(false), - function: modifiers - .get("function") - .and_then(Value::as_bool) - .unwrap_or(false), - }; - let moved = cx.update_window(window, move |_root, window, app| { - draw_frame(window, app); - window.dispatch_event( - gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent { - position, - pressed_button: None, - ..Default::default() - }), - app, - ); - }); - if let Err(error) = moved { - json!({"error": error.to_string()}) - } else { - let hit = cx.read_entity(&store, |store, _| { - let hit_chain = store.hovered.borrow().clone(); - (hit_chain.contains(&tag), hit_chain.first().copied()) - }); - if !hit.0 { - let cover = hit - .1 - .and_then(|cover_tag| { - cx.update_entity(&store, |store, cx| { - store.nodes.get(&cover_tag).map(|node| { - let node = node.read(cx); - format!("{} tag={cover_tag}", node.component) - }) - }) - }) - .unwrap_or_else(|| "no hit target".to_owned()); - json!({"error": format!("click target tag {tag} is covered by {cover}")}) - } else { - let dispatched = - cx.update_window(window, move |_root, window, app| { - draw_frame(window, app); - trace_input_dispatch("input"); - window.dispatch_event( - gpui::PlatformInput::MouseDown(gpui::MouseDownEvent { - button, - position, - click_count, - modifiers, - ..Default::default() - }), - app, - ); - window.dispatch_event( - gpui::PlatformInput::MouseUp(gpui::MouseUpEvent { - button, - position, - click_count, - modifiers, - ..Default::default() - }), - app, - ); - }); - match dispatched { - Ok(()) => json!({"clicked": true}), - Err(error) => json!({"error": error.to_string()}), - } - } - } - } - Some(Err(error)) => json!({"error": error}), - None => json!({"error": "click requires a mounted tag"}), - } - } - "hover" | "scroll" | "pinch" => { - let viewport = cx - .update_window(window, |_, window, _| { - let size = window.viewport_size(); - RectF { - x: 0.0, - y: 0.0, - w: f32::from(size.width) / crate::desktop::zoom::get(crate::store::APP_SURFACE_ID), - h: f32::from(size.height) / crate::desktop::zoom::get(crate::store::APP_SURFACE_ID), - } - }) - .ok(); - let target = viewport.and_then(|viewport| { - cx.read_entity(&store, |store, cx| { - let tag = params.get("tag").and_then(Value::as_i64)? as i32; - if let Some((position, root_tag)) = - crate::builtins::native_root::pointer_target(tag) - { - return Some(Ok((root_tag, position))); - } - let node = store.nodes.get(&tag)?; - if node.read(cx).view.accessibility_disabled { - return Some(Err("pointer target is disabled")); - } - Some(node_visible_frame(store, tag, viewport, cx).map_or( - Err("pointer target is not visible"), - |frame| { - Ok(( - tag, - frame_center(frame, window_offset(store, tag, cx)), - )) - }, - )) - }) - }); - match target { - Some(Ok((tag, position))) => { - let kind = method.to_owned(); - let dx = params.get("dx").and_then(Value::as_f64).unwrap_or(0.0) as f32; - let dy = params.get("dy").and_then(Value::as_f64).unwrap_or(0.0) as f32; - let phased = params.get("phase").is_some(); - let touch_phase = match params.get("phase").and_then(Value::as_str) { - Some("started") => gpui::TouchPhase::Started, - Some("ended") => gpui::TouchPhase::Ended, - _ => gpui::TouchPhase::Moved, - }; - let lines = params.get("lines").and_then(Value::as_bool).unwrap_or(false); - let held = |name: &str| { - params - .get("modifiers") - .and_then(|modifiers| modifiers.get(name)) - .and_then(Value::as_bool) - .unwrap_or(false) - }; - let modifiers = gpui::Modifiers { - shift: held("shift"), - control: held("control"), - alt: held("alt"), - platform: held("platform"), - ..Default::default() - }; - let pinch_delta = params.get("delta").and_then(Value::as_f64).unwrap_or(0.0) as f32; - let scroll_delta = if lines { - gpui::ScrollDelta::Lines(point(dx, dy)) - } else { - gpui::ScrollDelta::Pixels(point(px(dx), px(dy))) - }; - let preflight = cx.update_window(window, move |_root, window, app| { - draw_frame(window, app); - window.dispatch_event( - gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent { - position, - pressed_button: None, - ..Default::default() - }), - app, - ); - }); - let hit = if preflight.is_ok() { - Some(cx.read_entity(&store, |store, _| { - let chain = store.hovered.borrow().clone(); - (chain.contains(&tag), chain.first().copied()) - })) - } else { - None - }; - let mut draw_ms = 0.0f64; - let mut rendered = 0usize; - let mut rendered_total = 0usize; - let mut a11y_active = false; - let interval_ms = params - .get("intervalMs") - .and_then(Value::as_u64) - .unwrap_or(0) - .min(200); - let repeat = params - .get("repeat") - .and_then(Value::as_u64) - .unwrap_or(1) - .clamp(1, 1000); - let result: Result<(), String> = match hit { - Some((true, _)) if kind == "hover" => Ok(()), - Some((true, _)) if kind == "pinch" => cx - .update_window(window, |_root, window, app| { - draw_frame(window, app); - window.dispatch_event( - gpui::PlatformInput::Pinch(gpui::PinchEvent { - position, - delta: pinch_delta, - modifiers, - phase: touch_phase, - }), - app, - ); - draw_frame(window, app); - }) - .map_err(|error| error.to_string()), - Some((true, _)) => cx - .update_window(window, |_root, window, app| { - draw_frame(window, app); - if kind == "scroll" && !phased { - // A wheel tick within the latching window of the - // last one belongs to its sequence and stays with - // its container. Each driver scroll is a separate - // gesture, so a tick of the other delta kind that - // moves nothing ends that sequence first. - window.dispatch_event( - gpui::PlatformInput::Scroll(gpui::ScrollEvent { - position, - delta: if lines { - gpui::ScrollDelta::Pixels(point(px(0.0), px(0.0))) - } else { - gpui::ScrollDelta::Lines(point(0.0, 0.0)) - }, - modifiers, - touch_phase, - ..Default::default() - }), - app, - ); - } - window.dispatch_event( - gpui::PlatformInput::Scroll(gpui::ScrollEvent { - position, - delta: scroll_delta, - modifiers, - touch_phase, - ..Default::default() - }), - app, - ); - a11y_active = window.is_a11y_active(); - // Delta k goes out `k * interval_ms` after the - // first, whatever the frames in between cost, so - // a gesture's speed does not depend on how - // loaded the machine is. - let first_sent = std::time::Instant::now(); - for step in 0..repeat { - if step > 0 && interval_ms > 0 { - let due = first_sent - + std::time::Duration::from_millis( - interval_ms * step, - ); - let now = std::time::Instant::now(); - if due > now { - std::thread::sleep(due - now); - } - } - if step > 0 { - window.dispatch_event( - gpui::PlatformInput::Scroll( - gpui::ScrollEvent { - position, - delta: scroll_delta, - modifiers, - touch_phase, - ..Default::default() - }, - ), - app, - ); - } - let rendered_before = crate::node_view::RENDER_COUNT - .load(std::sync::atomic::Ordering::Relaxed); - let started = std::time::Instant::now(); - draw_frame(window, app); - draw_ms = started.elapsed().as_secs_f64() * 1000.0; - rendered = crate::node_view::RENDER_COUNT - .load(std::sync::atomic::Ordering::Relaxed) - - rendered_before; - rendered_total += rendered; - } - }) - .map_err(|error| error.to_string()), - Some((false, cover_tag)) => { - let cover = cover_tag - .and_then(|cover_tag| { - cx.update_entity(&store, |store, cx| { - store.nodes.get(&cover_tag).map(|node| { - let node = node.read(cx); - format!("{} tag={cover_tag}", node.component) - }) - }) - }) - .unwrap_or_else(|| "no hit target".to_owned()); - Err(format!("{method} target tag {tag} is covered by {cover}")) - } - None => Err(preflight.err().map_or_else( - || "pointer preflight failed".to_owned(), - |error| error.to_string(), - )), - }; - match result { - Ok(()) => json!({"dispatched": true, "drawMs": draw_ms, "renderedViews": rendered, "renderedViewsTotal": rendered_total, "a11yActive": a11y_active}), - Err(error) => json!({"error": error}), - } - } - Some(Err(error)) => json!({"error": error}), - None => json!({"error": format!("{method} requires a mounted tag")}), - } - } - "mouseDown" | "mouseUp" | "mouseMove" => { - let x = params.get("x").and_then(Value::as_f64); - let y = params.get("y").and_then(Value::as_f64); - if let (Some(x), Some(y)) = (x, y) { - if !x.is_finite() || !y.is_finite() { - json!({"error":"Pointer coordinates must be finite"}) - } else { - let position = point(px(x as f32), px(y as f32)); - let button = match params.get("button").and_then(Value::as_str) { - Some("right") => gpui::MouseButton::Right, - Some("middle") => gpui::MouseButton::Middle, - Some("back") => gpui::MouseButton::Navigate(gpui::NavigationDirection::Back), - Some("forward") => gpui::MouseButton::Navigate(gpui::NavigationDirection::Forward), - _ => gpui::MouseButton::Left, - }; - let modifiers = params.get("modifiers").cloned().unwrap_or(Value::Null); - let modifiers = gpui::Modifiers { - control: modifiers["control"].as_bool().unwrap_or(false), - alt: modifiers["alt"].as_bool().unwrap_or(false), - shift: modifiers["shift"].as_bool().unwrap_or(false), - platform: modifiers["platform"].as_bool().unwrap_or(false), - function: modifiers["function"].as_bool().unwrap_or(false), - }; - // A button pressed by this driver stays held until it is - // released, so a move in between is a drag, as with a mouse. - static HELD: std::sync::Mutex> = - std::sync::Mutex::new(None); - let held = { - let mut held = HELD.lock().unwrap_or_else(|e| e.into_inner()); - match method { - "mouseDown" => *held = Some(button), - "mouseUp" => *held = None, - _ => {} - } - *held - }; - let event = match method { - "mouseDown" => gpui::PlatformInput::MouseDown(gpui::MouseDownEvent { - position, - button, - modifiers, - click_count: params - .get("clickCount") - .and_then(Value::as_u64) - .unwrap_or(1) - .clamp(1, 3) as usize, - ..Default::default() - }), - "mouseUp" => gpui::PlatformInput::MouseUp(gpui::MouseUpEvent { - position, - button, - modifiers, - ..Default::default() - }), - _ => gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent { - position, - modifiers, - pressed_button: params - .get("button") - .and_then(Value::as_str) - .map(|_| button) - .or(held), - ..Default::default() - }), - }; - cx.update_window(window, move |_, window, app| { - let clear = window.draw(app); - clear.clear(app); - window.dispatch_event(event, app); - json!({"dispatched":true}) - }) - .unwrap_or_else(|error| json!({"error":error.to_string()})) - } - } else { - json!({"error":"Pointer command requires x and y"}) - } - } - "dragFiles" | "dropFiles" | "dragFilesExit" => { - let x = params.get("x").and_then(Value::as_f64).unwrap_or(0.0) as f32; - let y = params.get("y").and_then(Value::as_f64).unwrap_or(0.0) as f32; - let position = point(px(x), px(y)); - let paths: Vec = params - .get("paths") - .and_then(Value::as_array) - .map(|paths| { - paths - .iter() - .filter_map(Value::as_str) - .map(std::path::PathBuf::from) - .collect() - }) - .unwrap_or_default(); - let method = method.to_owned(); - cx.update_window(window, move |_, window, app| { - draw_frame(window, app); - let mut send = |event: gpui::FileDropEvent| { - window.dispatch_event(gpui::PlatformInput::FileDrop(event), app); - draw_frame(window, app); - }; - match method.as_str() { - "dragFiles" => { - if !paths.is_empty() { - send(gpui::FileDropEvent::Entered { - position, - paths: gpui::ExternalPaths(paths.into_iter().collect()), - }); - } - send(gpui::FileDropEvent::Pending { position }); - } - "dropFiles" => { - send(gpui::FileDropEvent::Submit { position }); - send(gpui::FileDropEvent::Ended); - } - _ => { - send(gpui::FileDropEvent::Exited); - send(gpui::FileDropEvent::Ended); - } - } - json!({"dispatched": true}) - }) - .unwrap_or_else(|error| json!({"error": error.to_string()})) - } - "focus" => { - let node = params - .get("tag") - .and_then(Value::as_i64) - .and_then(|tag| store.read_with(cx, |store, _| store.nodes.get(&(tag as i32)).cloned())); - cx.update_window(window, move |_, window, app| { - match node.and_then(|node| crate::node_view::RNNodeView::press_focus_handle(&node, window, app)) { - Some(handle) => { - window.focus(&handle, app); - draw_frame(window, app); - json!({"focused": true}) - } - None => json!({"error": "Target has no focusable ancestor"}), - } - }) - .unwrap_or_else(|error| json!({"error": error.to_string()})) - }, - "press" => { - let key = params.get("key").and_then(Value::as_str).unwrap_or(""); - let key = key.replace( - "mod-", - if cfg!(target_os = "macos") { - "cmd-" - } else { - "ctrl-" - }, - ); - // Modifiers first, the key last: `mod-ArrowDown`, `shift-PageUp`. - let key = match key.rsplit_once('-') { - Some((modifiers, name)) if !name.is_empty() => { - format!("{modifiers}-{}", crate::desktop::keymap::gpui_key_name(name)) - } - _ => crate::desktop::keymap::gpui_key_name(&key), - }; - match gpui::Keystroke::parse_with_os(&key, crate::desktop::keymap::host_os()) { - Ok(keystroke) => { - let dispatched = cx.update_window(window, move |_root, window, app| { - draw_frame(window, app); - window.dispatch_keystroke(keystroke.clone(), app); - window.dispatch_event( - gpui::PlatformInput::KeyUp(gpui::KeyUpEvent { keystroke }), - app, - ); - }); - match dispatched { - Ok(()) => json!({"dispatched": true}), - Err(error) => json!({"error": error.to_string()}), - } - } - Err(error) => json!({"error": format!("invalid keystroke {key:?}: {error}")}), - } - } - "ime" => { - let tag = params.get("tag").and_then(Value::as_i64).unwrap_or(0) as i32; - let steps = params - .get("steps") - .and_then(Value::as_array) - .cloned() - .unwrap_or_default(); - let target = cx.update_entity(&store, |store, cx| { - if let Some((position, _)) = crate::builtins::native_root::pointer_target(tag) { - return Some(position); - } - let node = store.nodes.get(&tag)?.read(cx); - if node.component != "TextInput" || !node.input().editable { - return None; - } - node_frame(store, tag, cx) - .map(|frame| frame_center(frame, window_offset(store, tag, cx))) - }); - match target { - None => json!({"error": "ime requires a mounted, editable text input"}), - Some(position) => { - let store = store.clone(); - let result = cx.update_window(window, move |_root, window, app| { - draw_frame(window, app); - let focused = store - .read(app) - .nodes - .get(&tag) - .and_then(|node| node.read(app).accessibility_focus_handle()) - .is_some_and(|handle| handle.is_focused(window)); - if !focused { - window.dispatch_event( - gpui::PlatformInput::MouseDown(gpui::MouseDownEvent { - button: gpui::MouseButton::Left, - position, - ..Default::default() - }), - app, - ); - window.dispatch_event( - gpui::PlatformInput::MouseUp(gpui::MouseUpEvent { - button: gpui::MouseButton::Left, - position, - ..Default::default() - }), - app, - ); - } - draw_frame(window, app); - let mut all = true; - for step in &steps { - if let Some(text) = step.get("mark").and_then(Value::as_str) { - all &= window.simulate_marked_text(text, app); - } else if let Some(text) = - step.get("commit").and_then(Value::as_str) - { - all &= window.simulate_committed_text(text, app); - } - draw_frame(window, app); - } - all - }); - match result { - Ok(true) => json!({"composed": true}), - Ok(false) => json!({"error": "focused view has no text input handler"}), - Err(error) => json!({"error": error.to_string()}), - } - } - } - } - "type" => { - let target = cx.update_entity(&store, |store, cx| { - let tag = params.get("tag").and_then(Value::as_i64)? as i32; - if let Some((position, _)) = crate::builtins::native_root::pointer_target(tag) { - return Some(position); - } - let entity = store.nodes.get(&tag)?; - let node = entity.read(cx); - if node.component != "TextInput" || !node.input().editable { - return None; - } - node_frame(store, tag, cx).map(|frame| { - frame_center(frame, window_offset(store, tag, cx)) - }) - }); - let text = params - .get("text") - .and_then(Value::as_str) - .unwrap_or("") - .to_owned(); - match target { - None => json!({"error": "type requires a mounted, editable TextInput"}), - Some(position) => { - let tag = params.get("tag").and_then(Value::as_i64).unwrap_or(0) as i32; - let store = store.clone(); - let dispatched = cx.update_window(window, move |_root, window, app| { - draw_frame(window, app); - let focused = store - .read(app) - .nodes - .get(&tag) - .and_then(|node| node.read(app).accessibility_focus_handle()) - .is_some_and(|handle| handle.is_focused(window)); - if !focused { - window.dispatch_event( - gpui::PlatformInput::MouseDown(gpui::MouseDownEvent { - button: gpui::MouseButton::Left, - position, - ..Default::default() - }), - app, - ); - window.dispatch_event( - gpui::PlatformInput::MouseUp(gpui::MouseUpEvent { - button: gpui::MouseButton::Left, - position, - ..Default::default() - }), - app, - ); - } - // Focusing can install a new InputHandler during - // paint. Native OS input arrives on a later turn; - // synthetic typing must complete that paint first. - draw_frame(window, app); - let keystroke = gpui::Keystroke { - modifiers: Default::default(), - key: "a".to_owned(), - key_char: Some(text), - }; - trace_input_dispatch("input"); - let handled = window.dispatch_keystroke(keystroke.clone(), app); - window.dispatch_event( - gpui::PlatformInput::KeyUp(gpui::KeyUpEvent { keystroke }), - app, - ); - handled - }); - match dispatched { - Ok(true) => json!({"typed": true}), - Ok(false) => json!({"error": "focused view has no text input handler"}), - Err(error) => json!({"error": error.to_string()}), - } - } - } - } - "drag" => { - let points = cx.update_entity(&store, |store, cx| { - let from_tag = params.get("fromTag").and_then(Value::as_i64)? as i32; - let to_tag = params.get("toTag").and_then(Value::as_i64)? as i32; - let from = node_frame(store, from_tag, cx)?; - let to = node_frame(store, to_tag, cx)?; - Some(( - frame_center(from, window_offset(store, from_tag, cx)), - frame_center(to, window_offset(store, to_tag, cx)), - )) - }); - match points { - None => json!({"error": "drag requires mounted source and destination tags"}), - Some((start, end)) => { - let from_tag = params - .get("fromTag") - .and_then(Value::as_i64) - .unwrap_or_default() as i32; - let preflight = cx.update_window(window, move |_root, window, app| { - draw_frame(window, app); - window.dispatch_event( - gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent { - position: start, - pressed_button: None, - ..Default::default() - }), - app, - ); - }); - if let Err(error) = preflight { - json!({"error": format!("drag pointer preflight failed: {error}")}) - } else { - let hit = cx.read_entity(&store, |store, _| { - let chain = store.hovered.borrow().clone(); - (chain.contains(&from_tag), chain.first().copied()) - }); - if !hit.0 { - let cover = hit - .1 - .and_then(|cover_tag| { - cx.update_entity(&store, |store, cx| { - store.nodes.get(&cover_tag).map(|node| { - let node = node.read(cx); - format!("{} tag={cover_tag}", node.component) - }) - }) - }) - .unwrap_or_else(|| "no hit target".to_owned()); - json!({"error": format!("drag source tag {from_tag} is covered by {cover}")}) - } else { - let steps = params - .get("steps") - .and_then(Value::as_u64) - .unwrap_or(8) - .clamp(1, 120) - as usize; - let duration_ms = if crate::animation_policy::animations_disabled() - { - 0 - } else { - params - .get("duration") - .and_then(Value::as_u64) - .unwrap_or(128) - .min(10_000) - }; - let down = cx.update_window(window, move |_root, window, app| { - draw_frame(window, app); - window.dispatch_event( - gpui::PlatformInput::MouseDown(gpui::MouseDownEvent { - button: gpui::MouseButton::Left, - position: start, - click_count: 1, - ..Default::default() - }), - app, - ); - }); - if let Err(error) = down { - json!({"error": error.to_string()}) - } else { - cx.read_entity(&store, |store, _| store.host.clone()) - .on_render(); - wait_for_frame(window, cx, Duration::from_millis(16)).await; - let mut failure = None; - for step in 1..=steps { - let progress = step as f32 / steps as f32; - let position = point( - px(f32::from(start.x) - + (f32::from(end.x) - f32::from(start.x)) - * progress), - px(f32::from(start.y) - + (f32::from(end.y) - f32::from(start.y)) - * progress), - ); - let moved = - cx.update_window(window, move |_root, window, app| { - draw_frame(window, app); - window.dispatch_event( - gpui::PlatformInput::MouseMove( - gpui::MouseMoveEvent { - position, - pressed_button: Some( - gpui::MouseButton::Left, - ), - ..Default::default() - }, - ), - app, - ); - window.refresh(); - }); - if let Err(error) = moved { - failure = Some(error.to_string()); - break; - } - cx.read_entity(&store, |store, _| store.host.clone()) - .on_render(); - cx.background_executor() - .timer(Duration::from_millis( - (duration_ms / steps as u64).max(16), - )) - .await; - } - let released = - cx.update_window(window, move |_root, window, app| { - window.dispatch_event( - gpui::PlatformInput::MouseUp(gpui::MouseUpEvent { - button: gpui::MouseButton::Left, - position: end, - ..Default::default() - }), - app, - ); - }); - match failure - .or_else(|| released.err().map(|error| error.to_string())) - { - Some(error) => json!({"error": error}), - None => json!({"dragged": true, "steps": steps}), - } - } - } - } - } - } - } - "idleStatus" => { - let ignore = ignore_sources(¶ms); - let ignore_urls = ignore_url_patterns(¶ms); - cx.update_entity(&store, |store, cx| { - idle_status(store, cx, &ignore, &ignore_urls, None) - }) - } - "waitForIdle" => { - let ignore = ignore_sources(¶ms); - let ignore_urls = ignore_url_patterns(¶ms); - let timeout_ms = params - .get("timeout") - .and_then(Value::as_u64) - .unwrap_or(5_000) - .clamp(100, 30_000); - let started = std::time::Instant::now(); - let mut stable_frames = 0u8; - let mut status = json!({"idle": false, "stableFrames": 0}); - loop { - let remaining = - Duration::from_millis(timeout_ms).saturating_sub(started.elapsed()); - if remaining.is_zero() { - break; - } - if !wait_for_frame(window, cx, remaining.min(Duration::from_millis(250))).await - { - continue; - } - let sources_idle = cx.update_entity(&store, |store, cx| { - idle_status(store, cx, &ignore, &ignore_urls, None)["idle"] == json!(true) - }); - stable_frames = if sources_idle { - stable_frames.saturating_add(1).min(2) - } else { - 0 - }; - status = cx.update_entity(&store, |store, cx| { - idle_status(store, cx, &ignore, &ignore_urls, Some(stable_frames)) - }); - if status.get("idle").and_then(Value::as_bool) == Some(true) { - break; - } - } - if status.get("idle").and_then(Value::as_bool) != Some(true) { - status = cx.update_entity(&store, |store, cx| { - idle_status(store, cx, &ignore, &ignore_urls, Some(stable_frames)) - }); - status["timeout"] = json!(true); - } - status - } - "screenshot" => { - let path = std::env::temp_dir().join(format!( - "rn-gpui-test-{}-{}.png", - std::process::id(), - id.as_u64().unwrap_or(0) - )); - let tag = params - .get("tag") - .and_then(Value::as_i64) - .map(|tag| tag as i32); - let (viewport, scale) = cx - .update_window(window, |_, window, _| { - let size = window.viewport_size(); - ( - RectF { - x: 0.0, - y: 0.0, - w: f32::from(size.width) / crate::desktop::zoom::get(crate::store::APP_SURFACE_ID), - h: f32::from(size.height) / crate::desktop::zoom::get(crate::store::APP_SURFACE_ID), - }, - window.scale_factor(), - ) - }) - .unwrap_or(( - RectF { - x: 0.0, - y: 0.0, - w: 0.0, - h: 0.0, - }, - 1.0, - )); - let frame = tag.and_then(|tag| { - cx.update_entity(&store, |store, cx| { - node_visible_frame(store, tag, viewport, cx) - .map(|frame| (frame, window_offset(store, tag, cx))) - }) - }); - let capture_started = Instant::now(); - // An element is drawn as its own device-pixel region of the - // frame, not as the whole frame cropped afterwards. - let captured = cx.update_window(window, |_root, window, app| { - draw_frame(window, app); - match frame { - Some((frame, offset)) => { - let size = window.viewport_size(); - let (width, height) = ( - (f32::from(size.width) * scale).round() as i32, - (f32::from(size.height) * scale).round() as i32, - ); - match device_region(frame, offset, scale, width, height) { - Some((x, y, w, h)) => window - .render_region_to_image(gpui::Bounds { - origin: point( - gpui::DevicePixels(x), - gpui::DevicePixels(y), - ), - size: gpui::size( - gpui::DevicePixels(w), - gpui::DevicePixels(h), - ), - }) - .map(Some), - None => Ok(None), - } - } - None => window.render_to_image().map(Some), - } - }); - if std::env::var_os("RN_GPUI_TEST_SCREENSHOT_TIMING").is_some() { - eprintln!( - "[rn-gpui-test] screenshot tag={:?} capture_ms={:.1}", - tag, - capture_started.elapsed().as_secs_f64() * 1000.0 - ); - } - match captured { - Ok(Ok(image)) => { - if tag.is_some() && frame.is_none() { - json!({"error": "screenshot target is not mounted or visible"}) - } else { - match image { - None => json!({"error": "screenshot target has no visible pixels"}), - Some(image) => match image.save(&path) { - Ok(()) => match std::fs::read(&path) { - Ok(bytes) => { - let _ = std::fs::remove_file(&path); - json!({"png": base64::engine::general_purpose::STANDARD.encode(bytes)}) - } - Err(error) => json!({"error": error.to_string()}), - }, - Err(error) => json!({"error": error.to_string()}), - }, - } - } - } - Ok(Err(error)) => json!({"error": error.to_string()}), - Err(error) => json!({"error": error.to_string()}), - } - } - "getAppMenu" => cx.update(|cx| crate::desktop::app_menu::menu_json(cx)), - "triggerMenuItem" => { - let id = params - .get("id") - .and_then(Value::as_str) - .unwrap_or("") - .to_string(); - cx.update(|cx| { - crate::desktop::app_menu::trigger_item(cx, &id); - json!({"triggered": id}) - }) - } - "showDevMenu" => cx.update(|cx| { - crate::desktop::dev_menu::show(cx); - json!({"shown": true}) - }), - "closeDevMenu" => cx.update(|cx| { - crate::desktop::dev_menu::hide(cx); - json!({"closed": true}) - }), - "devMenuState" => cx.update(|cx| { - let open = cx - .try_global::() - .is_some_and(|panel| panel.0.borrow().is_some()); - let model = crate::desktop::dev_menu::menu_model(cx); - json!({ - "installed": crate::desktop::dev_menu::is_installed(cx), - "open": open, - "items": crate::desktop::context_menu::nodes_json(&model.items), - }) - }), - "getDevMenu" => cx.update(|cx| { - let model = crate::desktop::dev_menu::menu_model(cx); - json!({"items": crate::desktop::context_menu::nodes_json(&model.items)}) - }), - "devMenuPerform" => { - let id = params - .get("id") - .and_then(Value::as_str) - .unwrap_or("") - .to_string(); - cx.update(|cx| { - crate::desktop::dev_menu::perform(cx, &id); - json!({"performed": id}) - }) - } - "getPerfMonitor" => cx.update(|cx| crate::desktop::perf_monitor::metrics(cx)), - "trayInstall" => cx.update(|cx| { - let mut config = crate::desktop::tray::TrayConfig::default(); - if let Some(id) = params.get("id").and_then(Value::as_str) { - config.id = id.to_string(); - } - if let Some(tooltip) = params.get("tooltip").and_then(Value::as_str) { - config.tooltip = Some(tooltip.to_string()); - } - if let Some(component) = params.get("component").and_then(Value::as_str) { - config.component = Some(component.to_string()); - } - if let Some(menu) = params.get("menu") { - match crate::desktop::menu_model::parse_menu(menu) { - Ok(menu) => config.menu = Some(menu), - Err(error) => return error.to_json_value(), - } - } - if let Some(quit) = params - .get("quitOnLastWindowClosed") - .and_then(Value::as_bool) - { - config.quit_on_last_window_closed = quit; - } - if let Some(hide) = params.get("hideWindowOnClose").and_then(Value::as_bool) { - config.hide_window_on_close = hide; - } - crate::desktop::tray::install(cx, config) - .unwrap_or_else(|error| error.to_json_value()) - }), - "trayState" => cx.update(|cx| crate::desktop::tray::state(cx)), - "trayClick" => { - let rect = crate::desktop::tray::TrayRect { - x: params.get("x").and_then(Value::as_f64).unwrap_or(0.0) as f32, - y: params.get("y").and_then(Value::as_f64).unwrap_or(0.0) as f32, - width: params.get("width").and_then(Value::as_f64).unwrap_or(24.0) as f32, - height: params.get("height").and_then(Value::as_f64).unwrap_or(24.0) as f32, - }; - let button = match params.get("button").and_then(Value::as_str) { - Some("right") => crate::desktop::tray::TrayButton::Right, - Some("middle") => crate::desktop::tray::TrayButton::Middle, - _ => crate::desktop::tray::TrayButton::Left, - }; - cx.update(|cx| { - crate::desktop::tray::handle_click(cx, rect, button); - crate::desktop::tray::state(cx) - }) - } - "trayHide" => cx.update(|cx| { - crate::desktop::tray::hide_popover(cx); - crate::desktop::tray::state(cx) - }), - "trayDestroy" => cx.update(|cx| { - crate::desktop::tray::destroy(cx) - .unwrap_or_else(|error| error.to_json_value()) - }), - "menuBarState" => cx.update(|cx| { - json!({ - "enabled": crate::desktop::gpui_menu::should_use_gpui_menu_bar(), - "inset": crate::desktop::gpui_menu::menu_bar_inset_for_window_id( - crate::desktop::windows::MAIN_WINDOW_KEY, - ), - "titles": crate::desktop::gpui_menu::menu_bar_entries(cx) - .into_iter() - .map(|(label, _)| label) - .collect::>(), - }) - }), - "openMenuBarMenu" => { - let title = params - .get("title") - .and_then(Value::as_str) - .unwrap_or("") - .to_string(); - cx.update(|cx| { - json!({"opened": crate::desktop::gpui_menu::open_menu_bar_menu(cx, &title)}) - }) - } - "clipboardText" => cx.update(|cx| { - json!({"text": cx.read_from_clipboard().and_then(|item| item.text())}) - }), - "setClipboardText" => { - let text = params - .get("text") - .and_then(Value::as_str) - .unwrap_or("") - .to_string(); - cx.update(|cx| { - cx.write_to_clipboard(gpui::ClipboardItem::new_string(text)); - json!({"set": true}) - }) - } - "contextMenuPresenter" => { - cx.update(|cx| json!({"presenter": crate::desktop::context_menu::presenter_name(cx)})) - } - "gpuiMenuState" => cx.update(|cx| match crate::desktop::gpui_menu::MenuPopup::pending(cx) { - Some((_window, items)) => json!({ - "open": true, - "items": crate::desktop::context_menu::nodes_json(&items), - }), - None => json!({"open": false}), - }), - "selectGpuiMenuItem" => { - let id = params - .get("id") - .and_then(Value::as_str) - .unwrap_or("") - .to_string(); - cx.update(|cx| json!({"selected": crate::desktop::gpui_menu::MenuPopup::select(cx, &id)})) - } - "dismissGpuiMenu" => cx.update(|cx| { - json!({"dismissed": crate::desktop::gpui_menu::MenuPopup::dismiss(cx)}) - }), - "getContextMenu" => cx.update(|cx| { - crate::desktop::context_menu::fake_model(cx).unwrap_or(Value::Null) - }), - "selectContextMenuItem" => { - let id = params - .get("id") - .and_then(Value::as_str) - .unwrap_or("") - .to_string(); - cx.update(|cx| { - json!({"selected": crate::desktop::context_menu::fake_select(cx, &id)}) - }) - } - "dismissContextMenu" => cx.update(|cx| { - json!({"dismissed": crate::desktop::context_menu::fake_dismiss(cx)}) - }), - "windowClose" => { - let key = params.get("windowId").and_then(Value::as_u64).unwrap_or(0) as u32; - let force = params.get("force").and_then(Value::as_bool).unwrap_or(false); - cx.update(|cx| { - crate::desktop::windows::close_window(cx, key, force) - .unwrap_or_else(|error| error.to_json_value()) - }) - } - // What the window's close button does first when a Modal is shown. - "modalCloseRequest" => cx - .update_window(window, |_, window, app| { - json!({"handled": crate::desktop::windows::request_modal_close(window, app)}) - }) - .unwrap_or_else(|error| json!({"error": error.to_string()})), - "osCloseWindow" => { - let key = params.get("windowId").and_then(Value::as_u64).unwrap_or(0) as u32; - cx.update(|cx| json!({"closed": crate::desktop::windows::os_close(cx, key)})) - } - "menuBarIcons" => json!({ - "titles": crate::desktop::app_menu::menu_bar_image_titles(), - }), - "appReopen" => cx.update(|cx| { - crate::desktop::windows::reopen(cx); - crate::desktop::windows::list_windows(cx).unwrap_or(Value::Null) - }), - // Stands in for the OS opening one of the app's URL schemes. - "openUrl" => { - let url = params - .get("url") - .and_then(Value::as_str) - .unwrap_or_default() - .to_string(); - crate::desktop::deep_link::handle_url(url); - json!({"delivered": true}) - } - #[cfg(target_os = "macos")] - "shareOpen" => json!({ - "open": crate::builtins::share::mac::is_open(), - "anchor": crate::builtins::share::mac::last_anchor() - .map(|(x, y, w, h, flipped)| json!({"x": x, "y": y, "width": w, "height": h, "flipped": flipped})), - }), - #[cfg(target_os = "macos")] - "shareChoose" => { - let name = params.get("service").and_then(Value::as_str); - json!({"sent": crate::builtins::share::mac::simulate_choice(name)}) - } - "alertState" => cx.update(|cx| { - crate::builtins::alert::dialog::describe(cx).unwrap_or_else(|| { - #[cfg(target_os = "macos")] - { - crate::builtins::alert::mac::describe().unwrap_or(Value::Null) - } - #[cfg(not(target_os = "macos"))] - { - Value::Null - } - }) - }), - "alertRespond" => { - let button = params.get("button").and_then(Value::as_u64).unwrap_or(0) as usize; - let texts: Vec = params - .get("texts") - .and_then(Value::as_array) - .map(|texts| { - texts - .iter() - .filter_map(|text| text.as_str().map(str::to_string)) - .collect() - }) - .unwrap_or_default(); - let responded = cx.update(|cx| { - if crate::builtins::alert::dialog::respond(cx, button, &texts) { - return true; - } - #[cfg(target_os = "macos")] - { - crate::builtins::alert::mac::respond(button, &texts) - } - #[cfg(not(target_os = "macos"))] - { - false - } - }); - json!({ "responded": responded }) - } - "alertEscape" => cx.update(|cx| { - if crate::builtins::alert::dialog::press_escape(cx) { - return json!({"sent": true}); - } - #[cfg(target_os = "macos")] - { - json!({"sent": crate::builtins::alert::mac::press_escape()}) - } - #[cfg(not(target_os = "macos"))] - { - json!({"sent": false}) - } - }), - "listWindows" => cx.update(|cx| { - crate::desktop::windows::list_windows(cx).unwrap_or(Value::Null) - }), - // One window's state, by the id `listWindows` gives it. The popover is - // not the main window, so `getWindowBounds` cannot answer for it. - "windowState" => { - let key = params.get("windowId").and_then(Value::as_u64).unwrap_or(0) as u32; - cx.update(|cx| { - let mut state = crate::desktop::windows::window_state(cx, key) - .unwrap_or_else(|error| error.to_json_value()); - if let Some(object) = state.as_object_mut() { - object.insert( - "nativeFrame".to_string(), - crate::desktop::windows::native_frame_json(cx, key), - ); - } - state - }) - } - _ => json!({"error": format!("unknown test-driver method: {method}")}), - }; - - if matches!( - method, - "click" - | "hover" - | "scroll" - | "press" - | "type" - | "mouseDown" - | "mouseUp" - | "mouseMove" - | "drag" - ) { - cx.read_entity(&store, |store, _| store.host.clone()) - .on_render(); - } - let _ = request - .reply - .send(json!({"jsonrpc":"2.0", "id": id, "result": result})); - } -} - -/// A forced draw does not run the compositor's frame callbacks, so this also -/// advances any host-driven screen transition. -fn draw_frame(window: &mut gpui::Window, app: &mut App) { - let needs_clear = window.draw(app); - needs_clear.clear(app); - crate::events::flush_hover_retarget(window, app); - let Some(store) = app.try_global::() else { - return; - }; - let store = store.0.clone(); - let transitioning: Vec> = { - let store = store.read(app); - let mut tracked = store.transitioning.borrow_mut(); - tracked.retain(|tag| { - store - .nodes - .get(tag) - .is_some_and(|node| node.read(app).transition_active(app)) - }); - tracked - .iter() - .filter_map(|tag| store.nodes.get(tag).cloned()) - .collect() - }; - for node in transitioning { - node.update(app, |_, cx| cx.notify()); - } -} - -/// A window the driver can draw. -/// -/// The handle the driver was started with is the main window's, and a test that -/// closes it leaves the handle dead: every draw then fails and a caller that -/// waits for frames spins until its timeout. The remaining windows are still -/// real, so fall back to one of them. -fn drawable_window(window: AnyWindowHandle, cx: &mut gpui::AsyncApp) -> Option { - if cx.update_window(window, |_, _, _| ()).is_ok() { - return Some(window); - } - let windows = cx.update(|cx| { - cx.try_global::() - .map(|windows| { - windows - .0 - .keys() - .into_iter() - .filter_map(|key| windows.0.get(key).map(|entry| entry.handle)) - .collect::>() - }) - })?; - windows - .into_iter() - .find(|candidate| cx.update_window(*candidate, |_, _, _| ()).is_ok()) -} - -async fn wait_for_frame( - window: AnyWindowHandle, - cx: &mut gpui::AsyncApp, - timeout: Duration, -) -> bool { - let drawn = drawable_window(window, cx).is_some_and(|window| { - cx.update_window(window, move |_root, window, app| { - draw_frame(window, app); - // A forced draw does not run the compositor's frame callbacks. - // Deliver Fabric's EventBeat too, so buffered native events reach JS. - let host = app - .try_global::() - .map(|store| store.0.read(app).host.clone()); - if let Some(host) = host { - host.on_render(); - } - }) - .is_ok() - }); - if !drawn { - // No window could be drawn: none is open yet, or it is in the middle of - // an update. Callers retry in a loop, and returning at once never - // yields the main thread, so the window could not open or finish its - // update until their timeout ran out. Give the app a frame first. - cx.background_executor() - .timer(timeout.min(Duration::from_millis(16))) - .await; - return false; - } - - // The pause after a forced draw lets JS answer the frame's events. A test - // does not need a display's 16 ms for that: 4 ms halves the cost of every - // idle wait. 1 ms was fast enough to let a scroll bar hover race ahead of - // the thumb under load, so `RN_GPUI_TEST_FRAME_MS` stays an override. - static FRAME_MS: std::sync::OnceLock = std::sync::OnceLock::new(); - let frame_ms = *FRAME_MS.get_or_init(|| { - std::env::var("RN_GPUI_TEST_FRAME_MS") - .ok() - .and_then(|value| value.parse().ok()) - .unwrap_or(4) - }); - let interval = timeout.min(Duration::from_millis(frame_ms)); - cx.background_executor().timer(interval).await; - true -} - -fn ignore_sources(params: &Value) -> Vec { - params - .get("ignore") - .and_then(Value::as_array) - .into_iter() - .flatten() - .filter_map(Value::as_str) - .map(str::to_owned) - .collect() -} - -fn ignore_url_patterns(params: &Value) -> Vec { - params - .get("ignoreUrls") - .and_then(Value::as_array) - .into_iter() - .flatten() - .filter_map(Value::as_str) - .map(str::to_owned) - .filter(|pattern| !pattern.contains('\n')) - .collect() -} - -fn idle_status( - store: &ViewStore, - cx: &gpui::App, - ignore: &[String], - ignore_urls: &[String], - stable_frames: Option, -) -> Value { - let mut busy = Vec::new(); - // SAFETY: these C++ probes take no pointers and only read counters. - let js_tasks = unsafe { rn_gpui_pending_js_tasks() }; - if (js_tasks > 0 || unsafe { rn_gpui_reload_in_progress() }) - && !ignore.iter().any(|item| item == "js") - { - let mut detail = format!("{js_tasks} queued or running JS task(s)"); - if std::env::var_os("RN_GPUI_DEBUG_JS_TASKS").is_some() { - let mut buffer = vec![0u8; 64 * 1024]; - // SAFETY: the buffer is valid for the capacity given, and the call - // writes at most that many bytes. - let length = - unsafe { rn_gpui_pending_js_tasks_dump(buffer.as_mut_ptr(), buffer.len() as u64) } - as usize; - buffer.truncate(length.min(buffer.len())); - detail.push_str(":\n"); - detail.push_str(&String::from_utf8_lossy(&buffer)); - } - busy.push(json!({"source":"js", "detail": detail})); - } - // SAFETY: these C++ probes take no pointers and only read counters. - let native_animations = unsafe { rn_gpui_native_animations_active() }; - let pending_work = unsafe { rn_gpui_pending_work() }; - let frame_demand = unsafe { rn_gpui_frame_demand() }; - if (native_animations > 0 || pending_work > 0) - && !ignore.iter().any(|item| item == "animations") - { - busy.push( - json!({"source": "animations", "detail": format!("{native_animations} native animation driver(s), {pending_work} pending module work item(s), frame demand {frame_demand}")}), - ); - } - // SAFETY: the C++ probe takes no pointers and only reads its table. - let promises = unsafe { rn_gpui_rust_promises_in_flight(1_000) }; - if promises > 0 && !ignore.iter().any(|item| item == "modules") { - busy.push(json!({"source": "modules", "detail": format!("{promises} Rust module promise call(s) made in the last second and not settled")})); - } - if crate::builtins::native_slot::layouts_pending() && !ignore.iter().any(|item| item == "slots") - { - busy.push(json!({"source": "slots", "detail": "a native slot is waiting for its content to get its width"})); - } - if store.has_pending_resize() && !ignore.iter().any(|item| item == "resize") { - busy.push( - json!({"source": "resize", "detail": "a surface has a window size React has not been given yet"}), - ); - } - if crate::wheel::pending() && !ignore.iter().any(|item| item == "wheel") { - busy.push( - json!({"source": "wheel", "detail": "a wheel event is waiting for its JS handlers"}), - ); - } - if store.frame_hook.gesture_is_active() && !ignore.iter().any(|item| item == "gestures") { - busy.push(json!({"source": "gestures", "detail": "native pointer gesture is active"})); - } - let patterns = std::ffi::CString::new(ignore_urls.join("\n")).unwrap_or_default(); - // SAFETY: `patterns` is a NUL-terminated string that outlives the call; the other probe reads a counter. - let http_requests = unsafe { rn_gpui_http_requests_not_ignored(patterns.as_ptr()) }; - let websocket_messages = unsafe { rn_gpui_websocket_messages_in_flight() }; - if (http_requests > 0 || websocket_messages > 0) && !ignore.iter().any(|item| item == "network") - { - busy.push(json!({"source": "network", "detail": format!("{http_requests} HTTP request(s), {websocket_messages} WebSocket message write(s) in flight after URL exclusions")})); - } - let image_loads = crate::image_loader::loads_in_flight(); - if image_loads > 0 && !ignore.iter().any(|item| item == "images") { - busy.push( - json!({"source": "images", "detail": format!("{image_loads} image load(s) in flight")}), - ); - } - // SAFETY: these C++ probes take no pointers and only read counters. - let mount_batches = unsafe { rn_gpui_mount_batches_in_flight() }; - if mount_batches > 0 && !ignore.iter().any(|item| item == "mount") { - busy.push(json!({"source": "mount", "detail": format!("{mount_batches} Fabric mount batch(es) queued for GPUI")})); - } - // SAFETY: these C++ probes take no pointers and only read counters. - let pending_timers = unsafe { rn_gpui_pending_timers_due_within(1_500) }; - if pending_timers > 0 && !ignore.iter().any(|item| item == "timers") { - let mut detail = format!("{pending_timers} one-shot timer(s) due within 1500 ms"); - let mut buffer = vec![0u8; 2048]; - // SAFETY: the buffer is valid for the capacity given, and the call - // writes at most that many bytes. - let length = - unsafe { rn_gpui_pending_timers_dump(1_500, buffer.as_mut_ptr(), buffer.len() as u64) } - as usize; - buffer.truncate(length.min(buffer.len())); - detail.push_str(":\n"); - detail.push_str(&String::from_utf8_lossy(&buffer)); - busy.push(json!({"source": "timers", "detail": detail})); - } - if !ignore.iter().any(|item| item == "animations") { - for (tag, entity) in &store.nodes { - let node = entity.read(cx); - if node.transition_active(cx) { - busy.push( - json!({"source": "animations", "detail": format!("transition on tag {tag}")}), - ); - } - } - } - let stable_count = stable_frames.unwrap_or(0); - let stable = stable_count >= 2 || ignore.iter().any(|item| item == "frames"); - if stable_frames.is_some() && !stable { - busy.push( - json!({"source": "frames", "detail": format!("{stable_count}/2 stable GPUI frames")}), - ); - } - json!({ - "idle": busy.is_empty(), - "stableFrames": stable_count, - "busySources": busy, - "trackedSources": ["frames", "animations", "gestures", "mount", "timers", "network", "images", "js", "slots", "resize"], - "untrackedSources": [] - }) -} - -fn serve_socket(listener: TcpListener, token: String, tx: Sender) { - for incoming in listener.incoming() { - let Ok(stream) = incoming else { break }; - let Ok(mut socket) = accept(stream) else { - continue; - }; - loop { - let message = match socket.read() { - Ok(Message::Text(text)) => text, - Ok(Message::Close(_)) | Err(_) => break, - Ok(Message::Ping(data)) => { - let _ = socket.send(Message::Pong(data)); - continue; - } - Ok(_) => continue, - }; - let value: Value = match serde_json::from_str(&message) { - Ok(value) => value, - Err(error) => { - let _ = socket.send(Message::Text( - json!({"error": error.to_string()}).to_string().into(), - )); - continue; - } - }; - let id = value.get("id").cloned().unwrap_or(Value::Null); - if value.pointer("/params/token").and_then(Value::as_str) != Some(&token) { - let _ = socket.send(Message::Text( - json!({"jsonrpc":"2.0", "id": id, - "error": {"code": -32001, "message": "invalid test-driver token"}}) - .to_string() - .into(), - )); - continue; - } - let (reply, response) = mpsc::sync_channel(1); - if tx.send_blocking(Request { value, reply }).is_err() { - break; - } - let Ok(response) = response.recv() else { break }; - if socket - .send(Message::Text(response.to_string().into())) - .is_err() - { - break; - } - } - } -} - -fn extension_props(node: &RNNodeView) -> Value { - match node.extension_props() { - Value::Null => Value::Object(serde_json::Map::new()), - props => props.clone(), - } -} - -fn paragraph_text(node: &RNNodeView) -> String { - if node.component == "TextInput" { - return node.input().text.clone(); - } - node.paragraph - .as_ref() - .map(|paragraph| { - paragraph - .fragments - .iter() - .map(|fragment| fragment.text.as_str()) - .collect() - }) - .unwrap_or_default() -} - -pub(crate) fn node_frame(store: &ViewStore, tag: i32, cx: &gpui::App) -> Option { - let entity = store.nodes.get(&tag)?; - let node = entity.read(cx); - let origin = node.absolute_origin(cx); - let (scale_x, scale_y) = node.cumulative_scale(cx); - let (x, y, w, h) = node.transformed_bounds( - cx, - ( - f32::from(origin.x), - f32::from(origin.y), - node.frame.w * scale_x, - node.frame.h * scale_y, - ), - ); - Some(RectF { x, y, w, h }) -} - -/// The GPUI menu bar is drawn inside the window (Linux by default), so the RN -/// surface starts below it: surface frames become window coordinates by adding -/// the inset. It is zero on platforms whose menu bar is native. -pub(crate) fn menu_bar_offset() -> f32 { - crate::desktop::gpui_menu::menu_bar_inset_for_window_id( - crate::desktop::windows::MAIN_WINDOW_KEY, - ) -} - -/// Asks GPUI to start publishing accessibility data on Windows. -/// -/// `gpui_windows` creates its AccessKit (UI Automation) adapter when the window -/// is built, but the adapter discards every tree update until a client requests -/// the tree: `a11y_tree_update` funnels through `Adapter::update_if_active`, and -/// activation happens in `handle_wm_getobject`, which only runs when Windows -/// sends the window `WM_GETOBJECT` on behalf of a UI Automation client. Without -/// that, `debug_a11y_tree_json()` has no tree and `a11yNode`/`a11yTree` report -/// "the native accessibility tree is unavailable". -/// -/// Sending `WM_GETOBJECT` with `OBJID_CLIENT` is exactly what such a client -/// does, and it is what the macOS probe does in spirit by asking AppKit for -/// `accessibilityChildren`. The call is synchronous and handled on this (the -/// GPUI) thread. -/// -/// Only compiled for the test driver: the message is otherwise a client's job. -/// -/// The reply is discarded deliberately, and it is safe to: `UiaReturnRawElementProvider` -/// returns an `LRESULT`, not an owned reference. AccessKit keeps the provider -/// alive inside its own `Context` (the adapter's `State::Active`) and answers -/// later WM_GETOBJECT messages from it; the reference Windows takes on the -/// caller's behalf is released by the client that asked, through the standard -/// WM_GETOBJECT contract. There is nothing here to free or release. -/// -/// It is sent once per window: `is_a11y_active()` is true forever after the -/// first successful activation, so resending it would only re-enter the window -/// procedure and make Windows hand out another provider reference for no gain. -#[cfg(all(target_os = "windows", feature = "test-driver"))] -fn activate_accessibility_probe(window: &gpui::Window) { - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - use windows_sys::Win32::UI::WindowsAndMessaging::{SendMessageW, WM_GETOBJECT}; - // OBJID_CLIENT: the window's own accessibility tree, which is what - // `AccessKit`'s `handle_wm_getobject` answers. - const OBJID_CLIENT: isize = 0xFFFF_FFFCu32 as i32 as isize; - if window.is_a11y_active() { - return; - } - let Ok(handle) = HasWindowHandle::window_handle(window) else { - return; - }; - let RawWindowHandle::Win32(win32) = handle.as_raw() else { - return; - }; - let hwnd = win32.hwnd.get() as *mut core::ffi::c_void; - // SAFETY: `hwnd` is the live window handle taken from the window's raw handle. - unsafe { - SendMessageW(hwnd, WM_GETOBJECT, 0, OBJID_CLIENT); - } -} - -/// The window-space center of a surface-space frame. Pointer events dispatched -/// with it land on the node the frame names, not `menu_bar_offset()` above it. -fn frame_center(frame: RectF, offset: f32) -> gpui::Point { - let zoom = crate::desktop::zoom::get(crate::store::APP_SURFACE_ID); - point( - px((frame.x + frame.w / 2.0) * zoom), - px((frame.y + frame.h / 2.0) * zoom + offset), - ) -} - -/// The inset to add to `tag`'s frame to get window coordinates: none for a -/// surface GPUI placed, whose frames are window coordinates already. -fn window_offset(store: &ViewStore, tag: i32, cx: &gpui::App) -> f32 { - match store.nodes.get(&tag) { - Some(node) if node.read(cx).surface_is_placed() => 0.0, - _ => menu_bar_offset(), - } -} - -pub(crate) fn node_visible_frame( - store: &ViewStore, - tag: i32, - viewport: RectF, - cx: &gpui::App, -) -> Option { - let mut visible = node_frame(store, tag, cx)?; - let node = store.nodes.get(&tag)?.read(cx); - if node.view.display_none || node.view.opacity <= 0.0 || node.inherited.hides_subtree_self { - return None; - } - visible = intersect(visible, viewport)?; - - let mut parent = node.parent.as_ref().and_then(|parent| parent.upgrade()); - while let Some(ancestor) = parent { - let ancestor = ancestor.read(cx); - if ancestor.view.display_none - || ancestor.view.opacity <= 0.0 - || ancestor.inherited.hides_subtree_self - { - return None; - } - if ancestor.view.overflow_hidden || ancestor.scroll.is_some() { - visible = intersect(visible, node_frame(store, ancestor.tag, cx)?)?; - } - parent = ancestor.parent.as_ref().and_then(|parent| parent.upgrade()); - } - Some(visible) -} - -fn intersect(frame: RectF, clip: RectF) -> Option { - let x = frame.x.max(clip.x); - let y = frame.y.max(clip.y); - let right = (frame.x + frame.w).min(clip.x + clip.w); - let bottom = (frame.y + frame.h).min(clip.y + clip.h); - (right > x && bottom > y).then_some(RectF { - x, - y, - w: right - x, - h: bottom - y, - }) -} - -fn query_label(store: &ViewStore, node: &RNNodeView, cx: &gpui::App) -> String { - if !node.view.accessibility_label.is_empty() { - return node.view.accessibility_label.clone(); - } - let text = paragraph_text(node); - if !text.is_empty() { - return text; - } - let mut parts = Vec::new(); - let mut pending: Vec = node.children.iter().map(|(tag, _)| *tag).collect(); - let mut visited = std::collections::HashSet::new(); - while let Some(tag) = pending.pop() { - if !visited.insert(tag) { - continue; - } - if let Some(entity) = store.nodes.get(&tag) { - let child = entity.read(cx); - let text = paragraph_text(child); - if !child.view.accessibility_label.is_empty() { - parts.push(child.view.accessibility_label.clone()); - } else if !text.is_empty() && child.component != "TextInput" { - parts.push(text); - } else { - pending.extend(child.children.iter().rev().map(|(tag, _)| *tag)); - } - } - } - parts.join(" ") -} - -fn query(store: &ViewStore, params: &Value, viewport: RectF, cx: &gpui::App) -> Value { - let by = params.get("by").and_then(Value::as_str).unwrap_or("testID"); - let value = params.get("value").and_then(Value::as_str).unwrap_or(""); - let exact = params - .get("exact") - .and_then(Value::as_bool) - .unwrap_or(false); - let name = params.get("name").and_then(Value::as_str).unwrap_or(""); - let items: Vec = store.nodes.iter().filter_map(|(tag, entity)| { - let node = entity.read(cx); - if let Some(root) = params.get("within").and_then(Value::as_i64) { - let mut parent = node.parent.as_ref().and_then(|parent| parent.upgrade()); - let mut found = false; - while let Some(entity) = parent { - let ancestor = entity.read(cx); - if ancestor.tag == root as i32 { found = true; break; } - parent = ancestor.parent.as_ref().and_then(|parent| parent.upgrade()); - } - if !found { return None; } - } - let text = paragraph_text(node); - let label = query_label(store, node, cx); - let actual = match by { - "testID" => node.view.test_id.as_str(), - "text" => text.as_str(), - "role" => node.view.accessibility_role.as_str(), - "label" => label.as_str(), - _ => return None, - }; - if actual.is_empty() - || !matches_query(actual, value, exact) - || (!name.is_empty() && !label.contains(name) && !text.contains(name)) - { - return None; - } - let frame = node_frame(store, *tag, cx).unwrap_or(node.frame); - Some(json!({"tag": tag, "component": node.component, "testID": node.view.test_id, - "text": text, "role": node.view.accessibility_role, "label": label, - "state": {"disabled": node.view.accessibility_disabled, "selected": node.view.accessibility_selected, "checked": match node.view.accessibility_checked { 1 => json!(false), 2 => json!(true), 3 => json!("mixed"), _ => Value::Null }}, - "frame": {"x": frame.x, "y": frame.y, "width": frame.w, "height": frame.h}, - "visible": node_visible_frame(store, *tag, viewport, cx).is_some(), - "enabled": !node.view.accessibility_disabled})) - }).collect(); - let mut items = items; - items.extend(native_query(by, value, exact, name)); - json!(items) -} - -fn matches_query(actual: &str, expected: &str, exact: bool) -> bool { - if exact { - actual == expected - } else { - actual.contains(expected) - } -} - -fn tree(store: &ViewStore, cx: &gpui::Context) -> Value { - let children = store - .roots - .get(&store.primary_surface_id) - .map(|root| { - root.read(cx) - .children - .iter() - .filter_map(|(tag, _)| store.nodes.get(tag)) - .map(|node| tree_node(node, store, cx)) - .collect::>() - }) - .unwrap_or_default(); - // `generation` says which React instance this tree came from, so a client - // that reloaded can tell "the old instance is gone" from "the new one has - // not mounted yet" without inferring it from an empty `children`. - json!({"surface": store.primary_surface_id, "generation": instance_generation(), "children": children}) -} - -/// The color of each border side as ARGB, `0` for none. -fn border_colors_json(node: &RNNodeView) -> Value { - let colors = node - .resolved_state() - .map_or(node.view.border_colors, |state| { - state.border_colors(node.view.border_colors) - }); - json!({"left": colors[0], "top": colors[1], "right": colors[2], "bottom": colors[3]}) -} - -/// The color of a node's text: the one a state style gives it, else its first -/// non-empty fragment's, as ARGB. -fn text_color(node: &RNNodeView) -> Value { - if let Some(color) = node.state_text_color() { - return json!(color); - } - node.paragraph - .as_ref() - .and_then(|paragraph| { - paragraph - .fragments - .iter() - .find(|fragment| !fragment.text.is_empty()) - }) - .map_or(Value::Null, |fragment| json!(fragment.color)) -} - -/// The background and opacity a node paints with, the state styles applied. -fn effective_background(node: &RNNodeView) -> u32 { - node.resolved_state() - .and_then(|state| state.background()) - .unwrap_or(node.view.background_color) -} - -fn effective_opacity(node: &RNNodeView) -> f32 { - node.resolved_state() - .and_then(|state| state.opacity()) - .unwrap_or(node.view.opacity) -} - -fn tree_node( - entity: &Entity, - store: &ViewStore, - cx: &gpui::Context, -) -> Value { - let node = entity.read(cx); - let mut children = node - .children - .iter() - .map(|(_, child)| tree_node(child, store, cx)) - .collect::>(); - if node.component == crate::builtins::native_root::COMPONENT { - let root = node - .extension_props - .get("rootId") - .and_then(Value::as_u64) - .unwrap_or(0) as u32; - children.extend(native_tree_json(root)); - } - json!({"tag": node.tag, "component": node.component, "testID": node.view.test_id, - "text": paragraph_text(node), "role": node.view.accessibility_role, - "label": node.view.accessibility_label, - "backgroundColor": effective_background(node), "opacity": effective_opacity(node), - "borderColors": border_colors_json(node), "textColor": text_color(node), - "frame": [node.frame.x, node.frame.y, node.frame.w, node.frame.h], - "contentSize": node.scroll.as_ref().map(|scroll| json!([scroll.content_size.0, scroll.content_size.1])).unwrap_or(Value::Null), - "scrollOffset": [node.scroll_offset().x, node.scroll_offset().y], - "scrollIndicatorShown": node.scroll_indicator_shown(cx), - "intrinsicSize": node.intrinsic_size().map(|(width, height)| json!([width, height])).unwrap_or(Value::Null), - "children": children}) -} - -/// The frame of an instance as the test driver reports frames: the window's -/// coordinates less the menu bar the surface starts below. -fn native_frame(bounds: Option>) -> [f32; 4] { - bounds.map_or([0.0; 4], |bounds| { - [ - f32::from(bounds.origin.x), - f32::from(bounds.origin.y) - menu_bar_offset(), - f32::from(bounds.size.width), - f32::from(bounds.size.height), - ] - }) -} - -fn native_text(props: &serde_json::Map, name: &str) -> String { - props - .get(name) - .and_then(Value::as_str) - .unwrap_or_default() - .to_string() -} - -/// The instances of a native tree, nested as the tree is. -fn native_tree_json(root: u32) -> Vec { - let infos = crate::builtins::native_root::instances(root); - let by_tag: std::collections::HashMap = infos - .iter() - .enumerate() - .map(|(index, info)| (info.tag, index)) - .collect(); - fn build( - infos: &[crate::builtins::native_root::InstanceInfo], - by_tag: &std::collections::HashMap, - index: usize, - ) -> Value { - let info = &infos[index]; - let children: Vec = info - .children - .iter() - .filter_map(|tag| by_tag.get(tag)) - .map(|child| build(infos, by_tag, *child)) - .collect(); - json!({ - "tag": info.tag, - "component": info.type_name, - "native": true, - "testID": native_text(&info.props, "testID"), - "text": native_text(&info.props, "text"), - "role": native_text(&info.props, "accessibilityRole"), - "label": native_text(&info.props, "accessibilityLabel"), - "frame": native_frame(info.bounds), - "children": children, - }) - } - infos - .first() - .map(|_| vec![build(&infos, &by_tag, 0)]) - .unwrap_or_default() -} - -fn native_query(by: &str, value: &str, exact: bool, name: &str) -> Vec { - let mut items = Vec::new(); - for root in crate::builtins::native_root::root_ids() { - for info in crate::builtins::native_root::instances(root) { - let text = native_text(&info.props, "text"); - let label = { - let label = native_text(&info.props, "accessibilityLabel"); - if label.is_empty() { - text.clone() - } else { - label - } - }; - let role = native_text(&info.props, "accessibilityRole"); - let test_id = native_text(&info.props, "testID"); - let actual = match by { - "testID" => test_id.as_str(), - "text" => text.as_str(), - "role" => role.as_str(), - "label" => label.as_str(), - _ => continue, - }; - if actual.is_empty() - || !matches_query(actual, value, exact) - || (!name.is_empty() && !label.contains(name) && !text.contains(name)) - { - continue; - } - let frame = native_frame(info.bounds); - items.push(json!({ - "tag": info.tag, "component": info.type_name, "testID": test_id, - "text": text, "role": role, "label": label, - "state": {"disabled": false, "selected": false, "checked": Value::Null}, - "frame": {"x": frame[0], "y": frame[1], "width": frame[2], "height": frame[3]}, - "visible": info.bounds.is_some(), "enabled": true, - })); - } - } - items -} - -fn get_props(store: &ViewStore, params: &Value, cx: &gpui::Context) -> Value { - let Some(tag) = params - .get("tag") - .and_then(Value::as_i64) - .map(|tag| tag as i32) - else { - return json!({"error": "getProps requires a tag"}); - }; - let Some(entity) = store.nodes.get(&tag) else { - return json!({"error": format!("tag {tag} is not mounted")}); - }; - let node = entity.read(cx); - let outline = node.resolved_state().map_or( - ( - node.view.outline_color, - node.view.outline_width, - node.view.outline_offset, - ), - |state| { - state.outline(( - node.view.outline_color, - node.view.outline_width, - node.view.outline_offset, - )) - }, - ); - let paragraph_fragments = node - .paragraph - .as_ref() - .map(|paragraph| { - paragraph - .fragments - .iter() - .map(|fragment| { - json!({ - "text": fragment.text, - "fontFamily": fragment.font_family, - "fontSize": fragment.font_size, - "fontWeight": fragment.font_weight, - "italic": fragment.italic, - "color": fragment.color, - "lineHeight": fragment.line_height, - "letterSpacing": fragment.letter_spacing, - "underline": fragment.underline, - "strikethrough": fragment.strikethrough, - "textTransform": fragment.text_transform, - }) - }) - .collect::>() - }) - .unwrap_or_default(); - json!({"tag": tag, "component": node.component, "testID": node.view.test_id, - "accessibilityLabel": node.view.accessibility_label, "accessibilityRole": node.view.accessibility_role, - "disabled": node.view.accessibility_disabled, "text": paragraph_text(node), - "paragraphFragments": paragraph_fragments, - "borderWidths": {"left": node.view.border_widths.left, "top": node.view.border_widths.top, - "right": node.view.border_widths.right, "bottom": node.view.border_widths.bottom}, - "borderStyles": node.view.border_styles, - "borderColors": border_colors_json(node), - "borderRadii": {"topLeft": node.view.border_radii.tl, "topRight": node.view.border_radii.tr, - "bottomRight": node.view.border_radii.br, "bottomLeft": node.view.border_radii.bl}, - "boxShadows": node.view.shadows.iter().map(|shadow| json!({ - "offsetX": shadow.dx, "offsetY": shadow.dy, "blurRadius": shadow.blur, - "spreadDistance": shadow.spread, "color": shadow.color, "inset": shadow.inset, - })).collect::>(), - "textColor": text_color(node), - "textAlign": node.paragraph.as_ref().map(|paragraph| paragraph.text_align), - "numberOfLines": node.paragraph.as_ref().map(|paragraph| paragraph.max_lines), - "outlineColor": outline.0, - "outlineOffset": outline.2, - "outlineWidth": outline.1, - "imageUri": extension_props(node).get("uri").cloned().unwrap_or(Value::Null), - "imageResizeMode": extension_props(node).get("resizeMode").cloned().unwrap_or(Value::Null), - "opacity":effective_opacity(node),"backgroundColor":effective_background(node),"baseBackgroundColor":node.view.background_color,"baseOpacity":node.view.opacity,"states":node.active_state_names(),"transform":node.view.transform,"renderCount":node.test_render_count(), - "scrollStrategy": node.scroll_strategy_name(), - "selection": if node.component == "TextInput" { json!({ - "start": node.input().text[..node.input().selection.start].encode_utf16().count(), - "end": node.input().text[..node.input().selection.end].encode_utf16().count() - }) } else { Value::Null }, - "inputScrollX": if node.component == "TextInput" { json!(node.input().scroll_x) } else { Value::Null }, - "frame": node_frame(store, tag, cx).map(|frame| json!({"x":frame.x,"y":frame.y,"width":frame.w,"height":frame.h}))}) -} - -/// The whole device pixels (x, y, width, height) an element's `frame`, shifted -/// down by `offset`, covers in a window of `width` x `height` device pixels, or -/// `None` when none are inside it. -fn device_region( - frame: RectF, - offset: f32, - scale: f32, - width: i32, - height: i32, -) -> Option<(i32, i32, i32, i32)> { - let (width, height) = (width.max(0) as u32, height.max(0) as u32); - let x = ((frame.x * scale).floor().max(0.0) as u32).min(width); - let y = (((frame.y + offset) * scale).floor().max(0.0) as u32).min(height); - let right = (((frame.x + frame.w) * scale).ceil().max(0.0) as u32).min(width); - let bottom = (((frame.y + offset + frame.h) * scale).ceil().max(0.0) as u32).min(height); - if x >= right || y >= bottom { - return None; - } - Some((x as i32, y as i32, (right - x) as i32, (bottom - y) as i32)) -} - -#[cfg(test)] -mod tests { - use super::{device_region, intersect, matches_query, RectF}; - - #[test] - fn device_region_scales_to_whole_device_pixels_and_clamps() { - let frame = RectF { - x: 10.25, - y: 4.0, - w: 20.0, - h: 10.5, - }; - // 2x: x 20.5 -> 20, right 60.5 -> 61; y (4 + 1) * 2 = 10, bottom 31 - assert_eq!( - device_region(frame, 1.0, 2.0, 200, 100), - Some((20, 10, 41, 21)) - ); - // Clamped to the window. - assert_eq!( - device_region(frame, 0.0, 2.0, 30, 100), - Some((20, 8, 10, 21)) - ); - // Outside it. - assert_eq!(device_region(frame, 0.0, 2.0, 10, 100), None); - } - - #[test] - fn query_matching_supports_exact_and_substring_modes() { - assert!(matches_query("Home title", "Home title", true)); - assert!(!matches_query("Home title", "Home", true)); - assert!(matches_query("Home title", "Home", false)); - assert!(!matches_query("Details", "Home", false)); - } - - #[test] - fn screenshot_frame_is_clipped_to_viewport() { - let frame = RectF { - x: -4.0, - y: 12.0, - w: 20.0, - h: 30.0, - }; - let viewport = RectF { - x: 0.0, - y: 0.0, - w: 10.0, - h: 20.0, - }; - - let clipped = intersect(frame, viewport).expect("frame intersects viewport"); - assert_eq!(clipped.x, 0.0); - assert_eq!(clipped.y, 12.0); - assert_eq!(clipped.w, 10.0); - assert_eq!(clipped.h, 8.0); - } - - #[test] - fn screenshot_frame_outside_clip_has_no_visible_pixels() { - let frame = RectF { - x: 20.0, - y: 20.0, - w: 5.0, - h: 5.0, - }; - let clip = RectF { - x: 0.0, - y: 0.0, - w: 10.0, - h: 10.0, - }; - - assert!(intersect(frame, clip).is_none()); - } -} - -/// The window as the compositor shows it, native views included, as PNG bytes -/// with its size in pixels. -#[cfg(target_os = "macos")] -fn composite_png(window: &gpui::Window) -> Result<(Vec, usize, usize), String> { - crate::native_view::test_composite_png(window) -} - -/// The window as the X server shows it: `XGetImage` includes the child windows -/// native views live in. Wayland offers no such read. -#[cfg(target_os = "linux")] -fn composite_png(window: &gpui::Window) -> Result<(Vec, usize, usize), String> { - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - use x11_dl::xlib; - - let id = match HasWindowHandle::window_handle(window) - .map_err(|error| error.to_string())? - .as_raw() - { - RawWindowHandle::Xcb(handle) => u64::from(handle.window.get()), - RawWindowHandle::Xlib(handle) => handle.window, - _ => return Err("the window cannot be captured outside X11".into()), - }; - let scale = window.scale_factor(); - let size = window.viewport_size(); - let (width, height) = ( - (f32::from(size.width) * scale).round() as u32, - (f32::from(size.height) * scale).round() as u32, - ); - let xlib = xlib::Xlib::open().map_err(|error| error.to_string())?; - // SAFETY: the display is opened and closed here, the image is destroyed once, and its pixels are read within its own `bytes_per_line` and height. - unsafe { - let display = (xlib.XOpenDisplay)(std::ptr::null()); - if display.is_null() { - return Err("could not open the X display".into()); - } - let image = (xlib.XGetImage)(display, id, 0, 0, width, height, !0, xlib::ZPixmap); - if image.is_null() { - (xlib.XCloseDisplay)(display); - return Err("XGetImage failed".into()); - } - let (red, green, blue) = ((*image).red_mask, (*image).green_mask, (*image).blue_mask); - let channel = - |mask: u64, pixel: u64| -> u8 { ((pixel & mask) >> mask.trailing_zeros()) as u8 }; - let mut rgba = image::RgbaImage::new(width, height); - for y in 0..height { - for x in 0..width { - let pixel = ((xlib.XGetPixel)(image, x as i32, y as i32)) as u64; - rgba.put_pixel( - x, - y, - image::Rgba([ - channel(red, pixel), - channel(green, pixel), - channel(blue, pixel), - 255, - ]), - ); - } - } - (xlib.XDestroyImage)(image); - (xlib.XCloseDisplay)(display); - let mut png = std::io::Cursor::new(Vec::new()); - rgba.write_to(&mut png, image::ImageFormat::Png) - .map_err(|error| error.to_string())?; - Ok((png.into_inner(), width as usize, height as usize)) - } -} - -/// The window as the desktop shows it, DirectComposition content included: the -/// screen is copied at the window's client rectangle, so the window must be on -/// screen and not covered. -#[cfg(target_os = "windows")] -fn composite_png(window: &gpui::Window) -> Result<(Vec, usize, usize), String> { - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - use windows_sys::Win32::Foundation::HWND; - - let RawWindowHandle::Win32(handle) = HasWindowHandle::window_handle(window) - .map_err(|error| error.to_string())? - .as_raw() - else { - return Err("the window is not a Win32 window".into()); - }; - capture_client(handle.hwnd.get() as HWND) -} - -#[cfg(target_os = "windows")] -fn window_hwnd(window: &gpui::Window) -> Option { - use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - - match HasWindowHandle::window_handle(window).ok()?.as_raw() { - RawWindowHandle::Win32(win32) => Some(win32.hwnd.get()), - _ => None, - } -} - -/// Which window holds the foreground, the active state and the keyboard focus, -/// next to this process's window. -#[cfg(target_os = "windows")] -fn focus_readout(hwnd: isize) -> Value { - use windows_sys::Win32::UI::{ - Input::KeyboardAndMouse::{GetActiveWindow, GetFocus}, - WindowsAndMessaging::GetForegroundWindow, - }; - // SAFETY: the calls only read the calling thread's input state. - let (foreground, active, focus) = unsafe { - ( - GetForegroundWindow() as isize, - GetActiveWindow() as isize, - GetFocus() as isize, - ) - }; - json!({ - "hwnd": hwnd, - "foreground": foreground, - "active": active, - "focus": focus, - "foregroundIsWindow": foreground == hwnd, - "activeIsWindow": active == hwnd, - "focusIsWindow": focus == hwnd, - }) -} - -/// Takes the foreground for the window. A new process is refused it by -/// default, so an Alt key press, which Windows counts as input from the -/// process, comes first; the window is then raised above the others. -#[cfg(target_os = "windows")] -fn bring_to_front(hwnd: isize) { - use windows_sys::Win32::UI::{ - Input::KeyboardAndMouse::{keybd_event, KEYEVENTF_KEYUP, VK_MENU}, - WindowsAndMessaging::{ - AllowSetForegroundWindow, SetForegroundWindow, SetWindowPos, ASFW_ANY, HWND_NOTOPMOST, - HWND_TOPMOST, SWP_NOMOVE, SWP_NOSIZE, - }, - }; - let hwnd = hwnd as windows_sys::Win32::Foundation::HWND; - // SAFETY: `hwnd` is the live handle of this process's window; the calls only - // change its z-order and foreground state. - unsafe { - AllowSetForegroundWindow(ASFW_ANY); - keybd_event(VK_MENU as u8, 0, 0, 0); - keybd_event(VK_MENU as u8, 0, KEYEVENTF_KEYUP, 0); - SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); - SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); - SetForegroundWindow(hwnd); - } -} - -#[cfg(target_os = "windows")] -fn capture_client( - hwnd: windows_sys::Win32::Foundation::HWND, -) -> Result<(Vec, usize, usize), String> { - use windows_sys::Win32::{ - Foundation::{POINT, RECT}, - Graphics::Dwm::DwmFlush, - Graphics::Gdi::{ - BitBlt, ClientToScreen, CreateCompatibleDC, CreateDIBSection, DeleteDC, DeleteObject, - GetDC, ReleaseDC, SelectObject, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, CAPTUREBLT, - DIB_RGB_COLORS, SRCCOPY, - }, - UI::WindowsAndMessaging::{ - GetClientRect, SetWindowPos, HWND_TOPMOST, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, - }, - }; - // SAFETY: every GDI object created here is released before returning; the pixel buffer is the section's own memory, read within its width and height. - unsafe { - let mut client = RECT { - left: 0, - top: 0, - right: 0, - bottom: 0, - }; - GetClientRect(hwnd, &mut client); - let (width, height) = (client.right - client.left, client.bottom - client.top); - if width <= 0 || height <= 0 { - return Err("the window has no client area".into()); - } - // The screen is copied, so a window in front of this one (a console - // another test left on the desktop) would be copied with it. Put this - // one on top and let the compositor present it. - SetWindowPos( - hwnd, - HWND_TOPMOST, - 0, - 0, - 0, - 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE, - ); - DwmFlush(); - let mut origin = POINT { x: 0, y: 0 }; - ClientToScreen(hwnd, &mut origin); - let screen = GetDC(std::ptr::null_mut()); - let memory = CreateCompatibleDC(screen); - let mut info: BITMAPINFO = std::mem::zeroed(); - info.bmiHeader = BITMAPINFOHEADER { - biSize: std::mem::size_of::() as u32, - biWidth: width, - biHeight: -height, - biPlanes: 1, - biBitCount: 32, - biCompression: BI_RGB, - ..std::mem::zeroed() - }; - let mut bits: *mut std::ffi::c_void = std::ptr::null_mut(); - let section = CreateDIBSection( - screen, - &info, - DIB_RGB_COLORS, - &mut bits, - std::ptr::null_mut(), - 0, - ); - let previous = SelectObject(memory, section); - let copied = BitBlt( - memory, - 0, - 0, - width, - height, - screen, - origin.x, - origin.y, - SRCCOPY | CAPTUREBLT, - ); - let result = if copied == 0 || bits.is_null() { - Err("the screen could not be copied".to_string()) - } else { - let bgra = std::slice::from_raw_parts(bits as *const u8, (width * height * 4) as usize); - let mut rgba = image::RgbaImage::new(width as u32, height as u32); - for (pixel, source) in rgba.pixels_mut().zip(bgra.chunks_exact(4)) { - *pixel = image::Rgba([source[2], source[1], source[0], 255]); - } - let mut png = std::io::Cursor::new(Vec::new()); - rgba.write_to(&mut png, image::ImageFormat::Png) - .map(|()| (png.into_inner(), width as usize, height as usize)) - .map_err(|error| error.to_string()) - }; - SelectObject(memory, previous); - DeleteObject(section); - DeleteDC(memory); - ReleaseDC(std::ptr::null_mut(), screen); - result - } -} - -/// Logs when an input event reaches the window, for latency measured from the -/// event rather than from the driver call that sent it (`RN_GPUI_MOUNT_TRACE`). -fn trace_input_dispatch(kind: &str) { - if crate::bootstrap::mount_trace_enabled() { - eprintln!( - "[mount-trace] {kind} epoch_ms={:.3}", - crate::bootstrap::epoch_ms() - ); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/text.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/text.rs deleted file mode 100644 index 9148ec5dbf..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/text.rs +++ /dev/null @@ -1,1475 +0,0 @@ -//! Paragraph shaping shared by Fabric measurement and GPUI painting. -//! -//! Fabric asks for text measurements from its JS/layout thread. The GPUI -//! `TextSystem` is an `Arc`-shared, synchronized service, so this module shapes -//! there and keeps the paintable result in a bounded cache for the UI thread. - -use gpui::{ - canvas, font, point, prelude::*, px, App, ContentMask, Font, FontStyle, FontWeight, - SharedString, StrikethroughStyle, TextAlign, TextRun, UnderlineStyle, WrappedLine, -}; -use rn_gpui_sys::ffi::{LineFlat, MeasureResult, ParagraphFlat, TextFragmentFlat}; -use std::{ - borrow::Cow, - collections::HashMap, - hash::Hash, - path::{Path, PathBuf}, - sync::{Arc, Mutex, OnceLock, RwLock}, -}; - -#[derive(Clone, Debug, Hash, PartialEq, Eq)] -struct FragmentKey { - text: String, - font_family: String, - font_size: u32, - font_weight: u16, - italic: bool, - color: u32, - line_height: u32, - letter_spacing: u32, - underline: bool, - strikethrough: bool, - text_transform: u8, - font_variant: u32, - background_color: u32, -} - -impl From<&TextFragmentFlat> for FragmentKey { - fn from(fragment: &TextFragmentFlat) -> Self { - Self { - text: fragment.text.clone(), - font_family: fragment.font_family.clone(), - font_size: fragment.font_size.to_bits(), - font_weight: fragment.font_weight, - italic: fragment.italic, - color: fragment.color, - line_height: fragment.line_height.to_bits(), - letter_spacing: fragment.letter_spacing.to_bits(), - underline: fragment.underline, - strikethrough: fragment.strikethrough, - text_transform: fragment.text_transform, - font_variant: fragment.font_variant, - background_color: fragment.background_color, - } - } -} - -#[derive(Clone, Debug, Hash, PartialEq, Eq)] -struct ParagraphKey { - fragments: Vec, - width: u32, - max_lines: i32, - text_align: u8, - ellipsize: u8, - fit: Option, - scale: u32, - empty_line: bool, -} - -impl ParagraphKey { - fn new(paragraph: &ParagraphFlat, width: f32) -> Self { - Self { - fragments: paragraph.fragments.iter().map(FragmentKey::from).collect(), - width: width.to_bits(), - max_lines: paragraph.max_lines, - text_align: resolve_alignment(paragraph.text_align), - ellipsize: paragraph.ellipsize, - fit: paragraph - .adjusts_to_fit - .then_some(paragraph.min_font_scale.to_bits()), - scale: device_scale().to_bits(), - empty_line: paragraph.measure_empty_line, - } - } -} - -struct ShapedParagraph { - lines: Vec, - line_heights: Vec, - /// Per line, the ascent and descent of the tallest font it uses, fallback - /// fonts included, unrounded. - line_metrics: Vec<(f32, f32)>, - width: f32, - height: f32, - visual_lines: usize, - text_align: TextAlign, -} - -struct TextService { - text_system: Arc, - cache: Mutex, -} - -const MAX_CACHED_PARAGRAPHS: usize = 12_288; -const MAX_CACHED_BYTES: usize = 48 << 20; - -struct CacheEntry { - shaped: Arc, - used: u64, - bytes: usize, -} - -/// Shaped paragraphs bounded by count and by approximate size. Past either -/// bound the least recently used quarter goes, so a screenful of text that was -/// shaped off the main thread is still there when it is painted. -#[derive(Default)] -struct ParagraphCache { - entries: HashMap, - bytes: usize, - clock: u64, -} - -impl ParagraphCache { - fn get(&mut self, key: &ParagraphKey) -> Option> { - self.clock += 1; - let clock = self.clock; - self.entries.get_mut(key).map(|entry| { - entry.used = clock; - entry.shaped.clone() - }) - } - - fn insert(&mut self, key: ParagraphKey, shaped: Arc) { - self.clock += 1; - let bytes = key - .fragments - .iter() - .map(|fragment| fragment.text.len()) - .sum::() - * 48 - + shaped.lines.len() * 256 - + 512; - if let Some(previous) = self.entries.insert( - key, - CacheEntry { - shaped, - used: self.clock, - bytes, - }, - ) { - self.bytes -= previous.bytes; - } - self.bytes += bytes; - if self.entries.len() > MAX_CACHED_PARAGRAPHS || self.bytes > MAX_CACHED_BYTES { - self.evict(); - } - } - - fn evict(&mut self) { - let mut stamps: Vec = self.entries.values().map(|entry| entry.used).collect(); - let cut = stamps.len() / 4; - let (_, threshold, _) = stamps.select_nth_unstable(cut); - let threshold = *threshold; - self.entries.retain(|_, entry| entry.used > threshold); - self.bytes = self.entries.values().map(|entry| entry.bytes).sum(); - } - - fn clear(&mut self) { - self.entries.clear(); - self.bytes = 0; - } -} - -/// A paragraph shaped off the main thread, kept with the node that paints it. -/// `width` is the content width it was shaped for. -#[derive(Clone)] -pub struct PreparedParagraph { - shaped: Arc, - width: f32, -} - -impl PreparedParagraph { - pub(crate) fn fits(&self, width: f32) -> bool { - (self.width - width).abs() <= 0.05 - } -} - -/// Takes the paragraph a handle from `rn_gpui_prepare_text` stands for. -pub(crate) fn take_prepared(handle: u64, width: f32) -> Option { - rn_gpui_sys::take_prepared(handle) - .and_then(|any| any.downcast::().ok()) - .map(|shaped| PreparedParagraph { shaped, width }) -} - -static TEXT_SERVICE: OnceLock> = OnceLock::new(); -static DEVICE_SCALE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0x3f80_0000); - -/// The pixel density line metrics are rounded at. A browser lays text out in -/// device pixels, so a line is a whole number of them. -pub(crate) fn set_device_scale(scale: f32) { - if scale.is_finite() && scale > 0.0 { - DEVICE_SCALE.store(scale.to_bits(), std::sync::atomic::Ordering::Relaxed); - } -} - -fn device_scale() -> f32 { - f32::from_bits(DEVICE_SCALE.load(std::sync::atomic::Ordering::Relaxed)) -} -static FONT_ALIASES: OnceLock>> = OnceLock::new(); -static FONT_DATA: OnceLock>>>> = OnceLock::new(); - -fn font_aliases() -> &'static RwLock> { - FONT_ALIASES.get_or_init(|| RwLock::new(HashMap::new())) -} - -fn font_data() -> &'static RwLock>>> { - FONT_DATA.get_or_init(|| RwLock::new(HashMap::new())) -} - -/// A font family as a lookup key. React Native for Windows names a font file's -/// family `/Assets/File.ttf#Family`, and icon libraries ask for it that way once -/// `Platform.OS` is `windows`: the family after the `#` is the name the font -/// is registered under. -fn normalized_font_name(name: &str) -> String { - let name = name.rsplit_once('#').map_or(name, |(_, family)| family); - name.chars() - .filter(|character| character.is_ascii_alphanumeric()) - .flat_map(char::to_lowercase) - .collect() -} - -fn remember_font(alias: &str, path: Option<&Path>, bytes: &[u8]) { - let mut keys = vec![normalized_font_name(alias)]; - if let Some(stem) = path - .and_then(Path::file_stem) - .and_then(|stem| stem.to_str()) - { - let stem = normalized_font_name(stem); - keys.push(stem.clone()); - for suffix in [ - "regular", - "semibold", - "bold", - "extrabold", - "light", - "medium", - ] { - if let Some(base) = stem.strip_suffix(suffix) { - keys.push(base.to_owned()); - } - } - } - let bytes = Arc::new(bytes.to_vec()); - let mut fonts = font_data() - .write() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - for key in keys.into_iter().filter(|key| !key.is_empty()) { - fonts.insert(key, bytes.clone()); - } -} - -fn supported_font_file(path: &Path) -> bool { - path.extension() - .and_then(|extension| extension.to_str()) - .is_some_and(|extension| matches!(extension.to_ascii_lowercase().as_str(), "ttf" | "otf")) -} - -fn collect_font_files(directory: &Path, files: &mut Vec) { - let Ok(entries) = std::fs::read_dir(directory) else { - return; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - collect_font_files(&path, files); - } else if supported_font_file(&path) { - files.push(path); - } - } -} - -pub(crate) fn install_fonts(cx: &mut App) { - let directory = crate::resources::default_assets_dir().map(|assets| assets.join("fonts")); - if let Some(directory) = directory { - let mut files = Vec::new(); - collect_font_files(&directory, &mut files); - files.sort(); - if files.is_empty() { - log::debug!("no desktop font assets found at {}", directory.display()); - } else { - let fonts = files - .iter() - .filter_map(|path| { - let bytes = std::fs::read(path).ok()?; - let alias = path.file_stem()?.to_str()?; - remember_font(alias, Some(path), &bytes); - Some(Cow::Owned(bytes)) - }) - .collect(); - match cx.text_system().add_fonts(fonts) { - Ok(()) => log::info!("registered {} bundled desktop font(s)", files.len()), - Err(error) => log::warn!("failed to register desktop font assets: {error:#}"), - } - } - } - let text_system = cx.text_system().clone(); - let _ = rn_gpui_sys::FONT_LOAD_HANDLER.set(Box::new(move |family, uri| { - let Some(bytes) = load_font_source(uri) else { - return false; - }; - install_custom_font(&text_system, family, &bytes) - })); - let _ = rn_gpui_sys::TEXT_IMAGE_HANDLER.set(Box::new(render_text_image)); -} - -fn load_font_source(uri: &str) -> Option> { - if uri.starts_with("https://") || uri.starts_with("http://") { - use futures::io::AsyncReadExt; - use http_client::HttpClient; - - let client = crate::http_client::RnHttpClient::new(); - let mut response = - futures::executor::block_on(client.get(uri, http_client::AsyncBody::empty(), true)) - .map_err(|error| log::warn!("failed to fetch font URI {uri}: {error:#}")) - .ok()?; - if !response.status().is_success() { - log::warn!("font URI {uri} returned HTTP {}", response.status()); - return None; - } - let mut bytes = Vec::new(); - futures::executor::block_on(response.body_mut().read_to_end(&mut bytes)) - .map_err(|error| log::warn!("failed to read font URI {uri}: {error}")) - .ok()?; - return Some(bytes); - } - - let path = crate::image_loader::file_uri_path(uri).unwrap_or_else(|| PathBuf::from(uri)); - match std::fs::read(&path) { - Ok(bytes) => Some(bytes), - Err(error) => { - log::warn!("failed to read font file {}: {error}", path.display()); - None - } - } -} - -fn install_custom_font(text_system: &gpui::TextSystem, alias: &str, bytes: &[u8]) -> bool { - if alias.trim().is_empty() || bytes.is_empty() { - return false; - } - let before = text_system.all_font_names(); - if let Err(error) = text_system.add_fonts(vec![Cow::Owned(bytes.to_vec())]) { - log::warn!("could not add runtime font {alias}: {error:#}"); - return false; - } - let names = text_system.all_font_names(); - let family = names - .iter() - .find(|name| name.eq_ignore_ascii_case(alias)) - .or_else(|| { - names.iter().find(|name| { - !before.iter().any(|previous| previous == *name) - && name - .to_ascii_lowercase() - .contains(&alias.to_ascii_lowercase()) - }) - }) - .cloned() - .unwrap_or_else(|| alias.to_owned()); - font_aliases() - .write() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .insert(alias.to_owned(), family); - remember_font(alias, None, bytes); - log::info!("registered runtime font {alias}"); - if let Some(service) = TEXT_SERVICE.get() { - service - .cache - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .clear(); - } - true -} - -fn render_text_image(family: &str, text: &str, font_size: f64, color: u32) -> String { - use base64::Engine; - use image::ImageEncoder; - - if !font_size.is_finite() || font_size <= 0.0 || font_size > 512.0 { - return String::new(); - } - let key = normalized_font_name(family); - let bytes = font_data() - .read() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .get(&key) - .cloned(); - let Some(bytes) = bytes else { - log::warn!("icon font {family} is not loaded"); - return String::new(); - }; - let Ok(font) = fontdue::Font::from_bytes(bytes.as_slice(), fontdue::FontSettings::default()) - else { - log::warn!("could not parse icon font {family}"); - return String::new(); - }; - let Some(glyph) = text.chars().next() else { - return String::new(); - }; - let (metrics, coverage) = font.rasterize(glyph, font_size as f32); - if metrics.width == 0 || metrics.height == 0 { - return String::new(); - } - let red = (color >> 16) as u8; - let green = (color >> 8) as u8; - let blue = color as u8; - let opacity = (color >> 24) as u8; - // Keep the complete glyph bitmap inside the source image with a small - // transparent edge. Some icon fonts have glyphs wider than their em size; - // returning the tight bitmap makes Image's default fill crop their sides. - let requested_size = (font_size.ceil() as usize).max(1); - let width = requested_size.max(metrics.width.saturating_add(4)); - let height = requested_size.max(metrics.height); - let left = (width - metrics.width) / 2; - let top = (height - metrics.height) / 2; - let mut rgba = vec![0; width * height * 4]; - for (index, alpha) in coverage.into_iter().enumerate() { - let source_x = index % metrics.width; - let source_y = index / metrics.width; - let target = ((top + source_y) * width + left + source_x) * 4; - rgba[target..target + 4].copy_from_slice(&[ - red, - green, - blue, - ((u16::from(alpha) * u16::from(opacity) + 127) / 255) as u8, - ]); - } - let mut png = std::io::Cursor::new(Vec::new()); - if image::codecs::png::PngEncoder::new(&mut png) - .write_image( - &rgba, - width as u32, - height as u32, - image::ExtendedColorType::Rgba8, - ) - .is_err() - { - return String::new(); - } - format!( - "data:image/png;base64,{}", - base64::engine::general_purpose::STANDARD.encode(png.into_inner()) - ) -} - -/// What the generic `monospace` family (React Native Android's name for it) -/// resolves to. -#[cfg(target_os = "macos")] -const MONOSPACE_FAMILY: &str = "Menlo"; -#[cfg(target_os = "windows")] -const MONOSPACE_FAMILY: &str = "Consolas"; -#[cfg(not(any(target_os = "macos", target_os = "windows")))] -const MONOSPACE_FAMILY: &str = "DejaVu Sans Mono"; - -fn font_size_of(size: f32) -> f32 { - if size.is_finite() && size > 0.0 { - size - } else { - 14.0 - } -} - -/// The OpenType features `fontVariant` asks for. -fn variant_features(variant: u32) -> Vec<(String, u32)> { - const TAGS: [(u32, &str); 5] = [ - (1 << 1, "smcp"), - (1 << 2, "onum"), - (1 << 3, "lnum"), - (1 << 4, "tnum"), - (1 << 5, "pnum"), - ]; - let mut features: Vec<(String, u32)> = TAGS - .iter() - .filter(|(bit, _)| variant & bit != 0) - .map(|(_, tag)| ((*tag).to_owned(), 1)) - .collect(); - // `stylistic-one` to `stylistic-twenty` are `ss01` to `ss20`. - for set in 1..=20u32 { - if variant & (1 << (5 + set)) != 0 { - features.push((format!("ss{set:02}"), 1)); - } - } - features -} - -/// The fragment's text with its `textTransform` applied. -pub(crate) fn fragment_text(fragment: &TextFragmentFlat) -> std::borrow::Cow<'_, str> { - use std::borrow::Cow; - match fragment.text_transform { - 1 => Cow::Owned(fragment.text.to_uppercase()), - 2 => Cow::Owned(fragment.text.to_lowercase()), - 3 => { - let mut out = String::with_capacity(fragment.text.len()); - let mut word_start = true; - for ch in fragment.text.chars() { - if word_start && ch.is_alphabetic() { - out.extend(ch.to_uppercase()); - } else { - out.push(ch); - } - word_start = ch.is_whitespace(); - } - Cow::Owned(out) - } - _ => Cow::Borrowed(fragment.text.as_str()), - } -} - -fn font_of(fragment: &TextFragmentFlat) -> Font { - let family = font_aliases() - .read() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .get(&fragment.font_family) - .cloned() - .unwrap_or_else(|| fragment.font_family.clone()); - let family = match family.as_str() { - "" => ".SystemUIFont", - "monospace" => MONOSPACE_FAMILY, - family => family, - }; - let mut font = font(family); - font.weight = FontWeight(f32::from(fragment.font_weight)); - if fragment.italic { - font.style = FontStyle::Italic; - } - if fragment.font_variant != 0 { - font.features = - gpui::FontFeatures(std::sync::Arc::new(variant_features(fragment.font_variant))); - } - font -} - -/// Measure the insertion point with the same font shaping GPUI uses to paint -/// the input text, so proportional fonts and Unicode land the caret correctly. -pub(crate) fn input_caret_x( - text_system: &gpui::WindowTextSystem, - paragraph: &ParagraphFlat, - line: &str, - byte_index: usize, -) -> f32 { - if line.is_empty() { - return 0.0; - } - let Some(fragment) = paragraph.fragments.first() else { - return 0.0; - }; - let font = font_of(fragment); - let text = SharedString::from(line.to_owned()); - let run = TextRun { - len: text.len(), - font, - color: crate::style::color(fragment.color), - background_color: None, - underline: None, - strikethrough: None, - }; - f32::from( - text_system - .shape_line(text, px(font_size_of(fragment.font_size)), &[run], None) - .x_for_index(byte_index.min(line.len())), - ) -} - -pub(crate) fn input_index_for_x( - text_system: &gpui::WindowTextSystem, - paragraph: &ParagraphFlat, - line: &str, - x: f32, -) -> usize { - if line.is_empty() { - return 0; - } - let Some(fragment) = paragraph.fragments.first() else { - return 0; - }; - let font = font_of(fragment); - let text = SharedString::from(line.to_owned()); - let run = TextRun { - len: text.len(), - font, - color: crate::style::color(fragment.color), - background_color: None, - underline: None, - strikethrough: None, - }; - text_system - .shape_line(text, px(font_size_of(fragment.font_size)), &[run], None) - .closest_index_for_x(px(x.max(0.0))) -} - -fn make_runs(paragraph: &ParagraphFlat) -> (String, Vec) { - let mut text = String::new(); - let mut runs = Vec::with_capacity(paragraph.fragments.len()); - for fragment in ¶graph.fragments { - if fragment.text.is_empty() { - continue; - } - let color = crate::style::color(if fragment.color == 0 { - 0xFF00_0000 - } else { - fragment.color - }); - let shown = fragment_text(fragment); - runs.push(TextRun { - len: shown.len(), - font: font_of(fragment), - color, - background_color: (fragment.background_color >> 24 != 0) - .then(|| crate::style::color(fragment.background_color)), - underline: fragment.underline.then_some(UnderlineStyle { - thickness: px(1.0), - color: None, - wavy: false, - }), - strikethrough: fragment.strikethrough.then_some(StrikethroughStyle { - thickness: px(1.0), - color: None, - }), - }); - text.push_str(&shown); - } - (text, runs) -} - -/// `natural` and `start` follow the trailing edge's mirror in a right-to-left -/// layout, `end` the leading one; `left` and `right` stay literal. -fn resolve_alignment(value: u8) -> u8 { - if !crate::builtins::i18n::rtl_active() { - return value; - } - match value { - 0 | 5 => 3, - 6 => 1, - other => other, - } -} - -fn text_align(value: u8) -> TextAlign { - match value { - 2 => TextAlign::Center, - 3 | 6 => TextAlign::Right, - _ => TextAlign::Left, - } -} - -/// `paragraph` with every font size and line height multiplied by `scale`. -fn scaled(paragraph: &ParagraphFlat, scale: f32) -> ParagraphFlat { - let mut next = paragraph.clone(); - for fragment in &mut next.fragments { - fragment.font_size = font_size_of(fragment.font_size) * scale; - fragment.line_height *= scale; - } - next -} - -impl TextService { - /// The largest scale, down to the paragraph's minimum, at which the text - /// fits in `max_lines`; the paragraph at that scale, without the fit flag. - fn fit_paragraph(&self, paragraph: &ParagraphFlat, width: f32) -> ParagraphFlat { - let floor = if paragraph.min_font_scale > 0.0 { - paragraph.min_font_scale.min(1.0) - } else { - 0.1 - }; - let mut probe = paragraph.clone(); - probe.adjusts_to_fit = false; - probe.max_lines = 0; - let mut scale = 1.0f32; - loop { - let shaped = self.shape(&scaled(&probe, scale), width); - if shaped.visual_lines <= paragraph.max_lines as usize || scale <= floor { - break; - } - scale = (scale * 0.95).max(floor); - } - let mut fitted = scaled(paragraph, scale); - fitted.adjusts_to_fit = false; - fitted - } - - fn shape(&self, paragraph: &ParagraphFlat, width: f32) -> Arc { - let width = if width.is_finite() && width > 0.0 { - width - } else { - f32::MAX - }; - let key = ParagraphKey::new(paragraph, width); - if let Some(shaped) = self - .cache - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .get(&key) - { - return shaped; - } - - if paragraph.adjusts_to_fit && paragraph.max_lines > 0 && width < f32::MAX { - let fitted = self.fit_paragraph(paragraph, width); - let shaped = self.shape(&fitted, width); - self.cache - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert(key, shaped.clone()); - return shaped; - } - - let (mut text, mut runs) = make_runs(paragraph); - let base_fragment = paragraph - .fragments - .iter() - .find(|fragment| !fragment.text.is_empty()) - .or_else(|| paragraph.fragments.first()); - let font_size = base_fragment - .map(|fragment| font_size_of(fragment.font_size)) - .unwrap_or(14.0); - let base_font = base_fragment.map(font_of).unwrap_or_default(); - - let window_text_system = gpui::WindowTextSystem::new(self.text_system.clone()); - // The box a text was measured into is rounded to the pixel grid, so it can - // be a hair narrower than the text it was measured for. Text that fits - // within that hair is not truncated, and keeps its line. - const ROUNDING_SLACK: f32 = 0.5; - let mut wrap_width = width; - let mut fits = false; - let mut was_truncated = false; - if paragraph.max_lines > 0 && !text.is_empty() && width < f32::MAX { - let probe = window_text_system - .shape_text( - SharedString::from(text.clone()), - px(font_size), - &runs, - Some(px(width + ROUNDING_SLACK)), - None, - ) - .unwrap_or_default(); - let lines: usize = probe - .iter() - .map(|line| line.wrap_boundaries.len() + 1) - .sum(); - fits = lines <= paragraph.max_lines as usize; - if fits { - wrap_width = width + ROUNDING_SLACK; - } - } - - if !fits && paragraph.max_lines > 0 && !text.is_empty() && width < f32::MAX { - let mut wrapper = self - .text_system - .line_wrapper(base_font.clone(), px(font_size)); - let truncation = match paragraph.ellipsize { - 1 => Some(gpui::TruncateFrom::Start), - 2 => Some(gpui::TruncateFrom::Middle), - 3 => Some(gpui::TruncateFrom::End), // clipped below to the same line limit - _ => Some(gpui::TruncateFrom::End), - }; - if let Some(direction) = truncation { - let affix = if paragraph.ellipsize == 3 { "" } else { "…" }; - let (truncated, truncated_runs) = wrapper.truncate_wrapped_line( - SharedString::from(text), - px(width), - paragraph.max_lines as usize, - affix, - &runs, - direction, - ); - text = truncated.to_string(); - runs = truncated_runs.into_owned(); - was_truncated = true; - } - } - - let shaped_lines = window_text_system - .shape_text( - SharedString::from(text), - px(font_size), - &runs, - (width < f32::MAX).then_some(px(wrap_width)), - (paragraph.max_lines > 0).then_some(paragraph.max_lines as usize), - ) - .unwrap_or_default(); - - let explicit_line_height = paragraph - .fragments - .iter() - .map(|fragment| fragment.line_height) - .find(|height| height.is_finite() && *height > 0.0); - let mut lines = Vec::with_capacity(shaped_lines.len()); - let mut line_heights = Vec::with_capacity(shaped_lines.len()); - let mut line_metrics = Vec::with_capacity(shaped_lines.len()); - let mut measured_width = 0.0f32; - let mut measured_height = 0.0f32; - for line in shaped_lines { - let (mut ascent, mut descent) = (f32::from(line.ascent()), f32::from(line.descent())); - for run in line.runs() { - if run.glyphs.iter().all(|glyph| glyph.is_emoji) { - continue; - } - let size = px(font_size); - ascent = ascent.max(f32::from(self.text_system.ascent(run.font_id, size))); - descent = descent.max(f32::from(self.text_system.descent(run.font_id, size)).abs()); - } - let line_height = explicit_line_height.unwrap_or_else(|| { - let scale = device_scale(); - (((ascent * scale).round() + (descent * scale).round()) / scale).max(1.0) - }); - line_metrics.push((ascent, descent)); - let visual_lines = line.wrap_boundaries.len() + 1; - measured_width = measured_width.max(f32::from(line.width())); - measured_height += line_height * visual_lines as f32; - lines.push(line); - line_heights.push(line_height); - } - - if paragraph.measure_empty_line { - let font_id = self.text_system.resolve_font(&base_font); - let size = px(font_size); - let ascent = f32::from(self.text_system.ascent(font_id, size)); - let descent = f32::from(self.text_system.descent(font_id, size)).abs(); - measured_height = explicit_line_height.unwrap_or_else(|| { - let scale = device_scale(); - (((ascent * scale).round() + (descent * scale).round()) / scale).max(1.0) - }); - } - - let visual_lines = lines - .iter() - .map(|line| line.wrap_boundaries.len() + 1) - .sum(); - let shaped = Arc::new(ShapedParagraph { - lines, - line_heights, - line_metrics, - width: if was_truncated { - width - } else { - measured_width.min(width) - }, - height: measured_height, - visual_lines, - text_align: text_align(resolve_alignment(paragraph.text_align)), - }); - let mut cache = self - .cache - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - cache.insert(key, shaped.clone()); - shaped - } -} - -pub fn install_measure_handler(cx: &mut App) { - let service = Arc::new(TextService { - text_system: cx.text_system().clone(), - cache: Mutex::new(ParagraphCache::default()), - }); - let _ = TEXT_SERVICE.set(service.clone()); - let lines_service = service.clone(); - let _ = rn_gpui_sys::LINES_HANDLER.set(Box::new(move |paragraph, width| { - measure_lines(&lines_service, paragraph, width) - })); - let prepare_service = service.clone(); - let _ = rn_gpui_sys::PREPARE_HANDLER.set(Box::new(move |paragraph, width| { - let shaped = prepare_service.shape(paragraph, width); - let scale = device_scale(); - ( - shaped.clone() as Arc, - MeasureResult { - width: shaped.width, - height: (shaped.height * scale).round() / scale, - }, - ) - })); - let _ = rn_gpui_sys::MEASURE_HANDLER.set(Box::new(move |paragraph, width, _height| { - let shaped = service.shape(paragraph, width); - let scale = device_scale(); - MeasureResult { - width: shaped.width, - height: (shaped.height * scale).round() / scale, - } - })); -} - -/// How a piece of text is set, for a host component that measures it. -#[derive(Clone, Debug, PartialEq)] -pub struct TextStyle { - /// The font family; empty for the system font. - pub family: String, - pub size: f32, - /// 100 to 900. - pub weight: u16, - pub italic: bool, - /// Zero for the font's own line height. - pub line_height: f32, - pub letter_spacing: f32, - /// Lines to show before cutting the text short, zero for all. - pub max_lines: u32, -} - -impl Default for TextStyle { - fn default() -> Self { - Self { - family: String::new(), - size: 14.0, - weight: 400, - italic: false, - line_height: 0.0, - letter_spacing: 0.0, - max_lines: 0, - } - } -} - -/// What a text takes once set. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct TextExtent { - pub width: f32, - pub height: f32, -} - -/// Sets `text` in `style`, wrapped to `max_width` when given, and returns the -/// room it takes, with the rounding Fabric's own text gets. Safe from the layout -/// thread. `None` before the text system exists, which is before the app starts. -pub fn measure_text(text: &str, style: &TextStyle, max_width: Option) -> Option { - let service = TEXT_SERVICE.get()?; - let paragraph = ParagraphFlat { - fragments: vec![TextFragmentFlat { - text: text.to_string(), - font_family: style.family.clone(), - font_size: style.size, - font_weight: style.weight, - italic: style.italic, - line_height: style.line_height, - letter_spacing: style.letter_spacing, - ..Default::default() - }], - max_lines: style.max_lines as i32, - ..Default::default() - }; - let shaped = service.shape(¶graph, max_width.unwrap_or(f32::MAX)); - let scale = device_scale(); - Some(TextExtent { - width: shaped.width, - height: (shaped.height * scale).round() / scale, - }) -} - -/// The height of the paragraph laid out on one line, or 0 when it is empty. -pub(crate) fn single_line_height(paragraph: &ParagraphFlat) -> f32 { - TEXT_SERVICE - .get() - .map_or(0.0, |service| service.shape(paragraph, f32::MAX).height) -} - -/// Every laid-out row of the paragraph, as `onTextLayout` reports them. -fn measure_lines(service: &TextService, paragraph: &ParagraphFlat, width: f32) -> Vec { - let shaped = service.shape(paragraph, width); - let mut rows = Vec::with_capacity(shaped.visual_lines); - let mut top = 0.0f32; - for (line, line_height) in shaped.lines.iter().zip(&shaped.line_heights) { - let lh = px(*line_height); - let count = line.wrap_boundaries.len() + 1; - let starts: Vec = (0..count) - .map(|row| { - if row == 0 { - return 0; - } - let probe = point(px(0.0), lh * row as f32 + lh * 0.5); - line.closest_index_for_position(probe, lh) - .unwrap_or_else(|nearest| nearest) - .min(line.len()) - }) - .collect(); - for (row, start) in starts.iter().enumerate() { - let end = starts.get(row + 1).copied().unwrap_or_else(|| line.len()); - let from = f32::from(line.position_for_index(*start, lh).unwrap_or_default().x); - let to = f32::from(line.position_for_index(end, lh).unwrap_or_default().x); - let ascent = f32::from(line.ascent()); - rows.push(LineFlat { - text: line.text.get(*start..end).unwrap_or_default().to_string(), - x: from, - y: top + row as f32 * line_height, - width: if row + 1 == count { - f32::from(line.width()) - from - } else { - (to - from).max(0.0) - }, - height: *line_height, - ascender: ascent, - descender: f32::from(line.descent()), - cap_height: ascent * 0.7, - x_height: ascent * 0.5, - }); - } - top += line_height * count as f32; - } - rows -} - -/// A paragraph shaped for a width, ready to paint into a box. -pub(crate) struct ParagraphPainter { - shaped: Arc, - shadow: Option>, - reach: f32, -} - -impl ParagraphPainter { - pub(crate) fn new( - paragraph: &ParagraphFlat, - width: f32, - height: f32, - prepared: Option<&PreparedParagraph>, - ) -> Self { - let shaped = prepared - .filter(|prepared| prepared.fits(width)) - .map(|prepared| prepared.shaped.clone()) - .or_else(|| { - TEXT_SERVICE - .get() - .map(|service| service.shape(paragraph, width)) - }) - .unwrap_or_else(|| { - Arc::new(ShapedParagraph { - lines: Vec::new(), - line_heights: Vec::new(), - line_metrics: Vec::new(), - visual_lines: 0, - width, - height, - text_align: text_align(resolve_alignment(paragraph.text_align)), - }) - }); - log::debug!( - "[text] cached shape: {:.1}x{:.1} at width {:.1}; mounted {:.1}x{:.1}; {} hard lines", - shaped.width, - shaped.height, - width, - width, - height, - shaped.lines.len() - ); - let shadow = (paragraph.shadow_color >> 24 != 0).then(|| shadow_layers(paragraph, width)); - let reach = paragraph.shadow_radius.max(0.0) - + paragraph.shadow_dx.abs().max(paragraph.shadow_dy.abs()); - Self { - shaped, - shadow, - reach, - } - } - - /// Paints the text and its shadow, clipped to `bounds` (the shadow to - /// `bounds` grown by its reach). - pub(crate) fn paint( - &self, - bounds: gpui::Bounds, - window: &mut gpui::Window, - cx: &mut App, - ) { - let reach = self.reach; - if let Some(layers) = self.shadow.as_ref() { - let wide = gpui::Bounds { - origin: bounds.origin - point(px(reach), px(reach)), - size: gpui::size( - bounds.size.width + px(reach * 2.0), - bounds.size.height + px(reach * 2.0), - ), - }; - window.with_content_mask(Some(ContentMask { bounds: wide }), |window| { - for layer in layers { - for (dx, dy) in &layer.offsets { - let origin = bounds.origin - + point(px(paragraph_dx(layer, *dx)), px(paragraph_dy(layer, *dy))); - paint_lines(&layer.shaped, origin, wide, window, cx); - } - } - }); - } - window.with_content_mask(Some(ContentMask { bounds }), |window| { - paint_lines(&self.shaped, bounds.origin, bounds, window, cx); - }); - } -} - -pub fn paragraph_element( - paragraph: &ParagraphFlat, - width: f32, - height: f32, - prepared: Option<&PreparedParagraph>, -) -> gpui::Canvas<()> { - let painter = ParagraphPainter::new(paragraph, width, height, prepared); - canvas( - |_, _, _| (), - move |bounds, (), window, cx| painter.paint(bounds, window, cx), - ) - .w(px(width.max(0.0))) - .h(px(height.max(0.0))) -} - -/// A painter with where its box sits in the node and how big it is. -pub(crate) type ParagraphOverlayParts = ( - ParagraphPainter, - gpui::Point, - gpui::Size, -); - -/// `child` with a paragraph painted over it at `offset` from its top-left -/// corner, the way a text child would be painted last, without a layout node. -pub(crate) struct ParagraphOverlay { - child: gpui::AnyElement, - painter: ParagraphPainter, - offset: gpui::Point, - size: gpui::Size, - /// Whether the text is clipped to the child's box, as the child's own - /// `overflow: hidden` would clip a text child. - clip: bool, -} - -impl ParagraphOverlay { - pub(crate) fn new( - child: impl IntoElement, - painter: ParagraphPainter, - offset: gpui::Point, - size: gpui::Size, - clip: bool, - ) -> Self { - Self { - child: child.into_any_element(), - painter, - offset, - size, - clip, - } - } -} - -impl IntoElement for ParagraphOverlay { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - -impl gpui::Element for ParagraphOverlay { - type RequestLayoutState = (); - type PrepaintState = (); - - fn id(&self) -> Option { - None - } - - fn source_location(&self) -> Option<&'static core::panic::Location<'static>> { - None - } - - fn request_layout( - &mut self, - _id: Option<&gpui::GlobalElementId>, - _inspector_id: Option<&gpui::InspectorElementId>, - window: &mut gpui::Window, - cx: &mut App, - ) -> (gpui::LayoutId, Self::RequestLayoutState) { - (self.child.request_layout(window, cx), ()) - } - - fn prepaint( - &mut self, - _id: Option<&gpui::GlobalElementId>, - _inspector_id: Option<&gpui::InspectorElementId>, - _bounds: gpui::Bounds, - _request_layout: &mut Self::RequestLayoutState, - window: &mut gpui::Window, - cx: &mut App, - ) -> Self::PrepaintState { - self.child.prepaint(window, cx); - } - - fn paint( - &mut self, - _id: Option<&gpui::GlobalElementId>, - _inspector_id: Option<&gpui::InspectorElementId>, - bounds: gpui::Bounds, - _request_layout: &mut Self::RequestLayoutState, - _prepaint: &mut Self::PrepaintState, - window: &mut gpui::Window, - cx: &mut App, - ) { - self.child.paint(window, cx); - let text = gpui::Bounds { - origin: bounds.origin + self.offset, - size: self.size, - }; - if self.clip { - window.with_content_mask(Some(ContentMask { bounds }), |window| { - self.painter.paint(text, window, cx) - }); - } else { - self.painter.paint(text, window, cx); - } - } -} - -/// The paragraph's text as the shaper sees it, fragments joined. -pub(crate) fn paragraph_text(paragraph: &ParagraphFlat) -> String { - paragraph.fragments.iter().map(fragment_text).collect() -} - -/// The byte offset in the paragraph's text closest to a point in its box. -pub(crate) fn text_index_at( - paragraph: &ParagraphFlat, - width: f32, - x: f32, - y: f32, -) -> Option { - let shaped = TEXT_SERVICE.get()?.shape(paragraph, width); - let mut top = 0.0f32; - let mut offset = 0usize; - let last = shaped.lines.len().checked_sub(1)?; - for (index, (line, line_height)) in shaped.lines.iter().zip(&shaped.line_heights).enumerate() { - let height = line_height * (line.wrap_boundaries.len() + 1) as f32; - if y < top + height || index == last { - let local = point(px(x), px((y - top).max(0.0))); - let within = line - .closest_index_for_position(local, px(*line_height)) - .unwrap_or_else(|nearest| nearest); - return Some(offset + within.min(line.len())); - } - top += height; - offset += line.len() + 1; - } - None -} - -/// The rectangles `(x, y, width, height)` a byte range covers, row by row. -pub(crate) fn text_range_rects( - paragraph: &ParagraphFlat, - width: f32, - range: std::ops::Range, -) -> Vec<(f32, f32, f32, f32)> { - let mut rects = Vec::new(); - let Some(shaped) = TEXT_SERVICE - .get() - .map(|service| service.shape(paragraph, width)) - else { - return rects; - }; - let mut top = 0.0f32; - let mut offset = 0usize; - for (line, line_height) in shaped.lines.iter().zip(&shaped.line_heights) { - let rows = line.wrap_boundaries.len() + 1; - let start = range.start.max(offset); - let end = range.end.min(offset + line.len()); - if start < end || (range.start <= offset + line.len() && range.end > offset + line.len()) { - let from = start.saturating_sub(offset).min(line.len()); - let to = end.saturating_sub(offset).min(line.len()); - let lh = px(*line_height); - let a = line.position_for_index(from, lh).unwrap_or_default(); - let b = line.position_for_index(to, lh).unwrap_or_default(); - let row_a = (f32::from(a.y) / line_height).floor() as usize; - let row_b = (f32::from(b.y) / line_height).floor() as usize; - // A selection that runs on past this line's end covers its newline. - let newline = range.end > offset + line.len(); - for row in row_a..=row_b.min(rows - 1) { - let x0 = if row == row_a { f32::from(a.x) } else { 0.0 }; - let x1 = if row == row_b && !newline { - f32::from(b.x) - } else if row == row_b { - f32::from(b.x).max(shaped.width) + 4.0 - } else { - shaped.width.max(f32::from(a.x)) - }; - if x1 > x0 { - rects.push((x0, top + row as f32 * line_height, x1 - x0, *line_height)); - } - } - } - top += line_height * rows as f32; - offset += line.len() + 1; - } - rects -} - -/// One alpha of a blurred shadow: the shaped text in that alpha and the offsets -/// it is painted at. -struct ShadowLayer { - shaped: Arc, - offsets: Vec<(f32, f32)>, - base: (f32, f32), -} - -fn paragraph_dx(layer: &ShadowLayer, offset: f32) -> f32 { - layer.base.0 + offset -} - -fn paragraph_dy(layer: &ShadowLayer, offset: f32) -> f32 { - layer.base.1 + offset -} - -/// A Gaussian-weighted blur of the text's shadow, drawn as the text repeated on -/// rings around the shadow's position. Each ring is painted in the alpha that, -/// composited over every sample, leaves the shadow's own alpha where all of -/// them overlap, so a thick glyph keeps its colour and a thin one fades out. -fn shadow_layers(paragraph: &ParagraphFlat, width: f32) -> Vec { - let Some(service) = TEXT_SERVICE.get() else { - return Vec::new(); - }; - let alpha = ((paragraph.shadow_color >> 24) as f32 / 255.0).min(0.999); - let rgb = paragraph.shadow_color & 0x00FF_FFFF; - let radius = paragraph.shadow_radius.max(0.0); - let base = (paragraph.shadow_dx, paragraph.shadow_dy); - // (distance from the centre, number of samples on that ring) - let mut rings: Vec<(f32, usize)> = vec![(0.0, 1)]; - if radius > 0.0 { - const RINGS: usize = 4; - for ring in 1..=RINGS { - rings.push((radius * ring as f32 / RINGS as f32, 6 * ring)); - } - } - let sigma = (radius / 2.0).max(0.001); - let weight = |distance: f32| (-(distance * distance) / (2.0 * sigma * sigma)).exp(); - let total: f32 = rings - .iter() - .map(|(distance, count)| weight(*distance) * *count as f32) - .sum(); - rings - .iter() - .enumerate() - .filter_map(|(index, (distance, count))| { - let ring_alpha = if radius > 0.0 { - 1.0 - (1.0 - alpha).powf(weight(*distance) / total) - } else { - alpha - }; - let color = (((ring_alpha * 255.0).round().max(1.0) as u32) << 24) | rgb; - let mut flat = paragraph.clone(); - for fragment in &mut flat.fragments { - fragment.color = color; - } - let offsets = (0..*count) - .map(|point_index| { - let angle = std::f32::consts::TAU * point_index as f32 / *count as f32 - + index as f32 * 0.5; - (distance * angle.cos(), distance * angle.sin()) - }) - .collect(); - Some(ShadowLayer { - shaped: service.shape(&flat, width), - offsets, - base, - }) - }) - .collect() -} - -/// How far to move a line so its baseline sits where a browser puts it: the -/// ascent and descent each rounded to whole device pixels and the half leading -/// rounded down to one, added above the ascent. gpui centres the unrounded -/// metrics instead. -fn baseline_correction( - line: &gpui::WrappedLine, - line_height: f32, - (ascent, descent): (f32, f32), -) -> f32 { - let scale = device_scale(); - let (rounded_ascent, rounded_descent) = ((ascent * scale).round(), (descent * scale).round()); - let browser = (rounded_ascent - + ((line_height * scale - rounded_ascent - rounded_descent) / 2.0).floor()) - / scale; - let (own_ascent, own_descent) = (f32::from(line.ascent()), f32::from(line.descent())); - let gpui = (line_height - own_ascent - own_descent) / 2.0 + own_ascent; - browser - gpui -} - -/// Where a highlight behind a run starts, relative to the top of its line: a -/// browser paints it over the font's content area, which the line's leading -/// centres in the line box. A line that wraps keeps GPUI's whole-line-tall -/// rectangle, which steps with the line height. -fn background_top( - line: &gpui::WrappedLine, - line_height: f32, - (ascent, descent): (f32, f32), -) -> f32 { - if !line.wrap_boundaries.is_empty() { - return 0.0; - } - let scale = device_scale(); - let content = (ascent * scale).round() + (descent * scale).round(); - ((line_height * scale - content) / 2.0).floor() / scale -} - -fn background_height( - line: &gpui::WrappedLine, - line_height: f32, - (ascent, descent): (f32, f32), -) -> f32 { - if !line.wrap_boundaries.is_empty() { - return line_height; - } - let scale = device_scale(); - ((ascent * scale).round() + (descent * scale).round()) / scale -} - -fn paint_lines( - shaped: &ShapedParagraph, - origin: gpui::Point, - bounds: gpui::Bounds, - window: &mut gpui::Window, - cx: &mut App, -) { - let mut y = origin.y; - for ((line, line_height), metrics) in shaped - .lines - .iter() - .zip(&shaped.line_heights) - .zip(&shaped.line_metrics) - { - let baseline = point( - origin.x, - y + px(baseline_correction(line, *line_height, *metrics)), - ); - let _ = line.paint_background( - point( - origin.x, - y + px(background_top(line, *line_height, *metrics)), - ), - px(background_height(line, *line_height, *metrics)), - shaped.text_align, - Some(bounds), - window, - cx, - ); - if line - .paint( - baseline, - px(*line_height), - shaped.text_align, - Some(bounds), - window, - cx, - ) - .is_err() - { - log::error!("failed to paint a shaped React Native text line"); - } - y += px(*line_height * (line.wrap_boundaries.len() + 1) as f32); - } -} - -#[cfg(test)] -mod font_name_tests { - use super::normalized_font_name; - - #[test] - fn a_windows_font_reference_names_the_family_after_the_hash() { - assert_eq!( - normalized_font_name("/Assets/MaterialIcons-Regular.ttf#Material Icons"), - normalized_font_name("Material Icons") - ); - } - - #[test] - fn a_plain_family_is_unchanged() { - assert_eq!(normalized_font_name("Material Icons"), "materialicons"); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/tooltip.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/tooltip.rs deleted file mode 100644 index 310c9ef2dc..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/tooltip.rs +++ /dev/null @@ -1,210 +0,0 @@ -//! `tooltip`: text shown after the pointer rests over a view. -//! -//! The view under the pointer, or its nearest ancestor with a `tooltip`, is -//! the one that counts. On macOS the text is handed to the system: one -//! `NSView` tooltip rectangle is kept over that view's frame, so the delay, -//! the look and the place are the operating system's and the tooltip can -//! leave the window. Elsewhere, and with `RN_GPUI_TOOLTIP=drawn`, the app -//! draws it after the same delay, in front of everything in the window. - -use crate::events::Target; -use crate::store::{store_from, StoreGlobal}; -use gpui::{point, px, App, AppContext as _, Pixels, Point, Window}; -use std::cell::{Cell, RefCell}; -use std::time::Duration; - -#[cfg(target_os = "macos")] -mod mac; - -const DRAWN_DELAY: Duration = Duration::from_millis(500); - -#[derive(Clone, Debug, PartialEq)] -pub(crate) struct Active { - pub tag: i32, - pub text: String, - /// The view's frame in the window: x, y, width, height. - pub rect: (f32, f32, f32, f32), -} - -#[derive(Clone, Debug, PartialEq)] -pub(crate) struct Drawn { - pub text: String, - pub x: f32, - pub y: f32, -} - -thread_local! { - static ACTIVE: RefCell> = const { RefCell::new(None) }; - static DRAWN: RefCell> = const { RefCell::new(None) }; - static GENERATION: Cell = const { Cell::new(0) }; -} - -fn native() -> bool { - cfg!(target_os = "macos") && std::env::var("RN_GPUI_TOOLTIP").as_deref() != Ok("drawn") -} - -#[cfg(target_os = "macos")] -pub(crate) fn native_probe(window: &Window, tag: i32) -> (Option, usize) { - mac::probe(window, tag) -} - -/// What the system tooltip would show, and for which view, if the pointer rests -/// at `position` in the window. -pub(crate) fn active() -> Option { - ACTIVE.with_borrow(Clone::clone) -} - -pub(crate) fn drawn() -> Option { - DRAWN.with_borrow(Clone::clone) -} - -pub(crate) fn mode() -> &'static str { - if native() { - "native" - } else { - "drawn" - } -} - -fn tooltip_view(cx: &App, chain: &[i32]) -> Option<(i32, String)> { - let store = cx.try_global::()?.0.read(cx); - chain.iter().find_map(|tag| { - let node = store.nodes.get(tag)?.read(cx); - let text = node.tooltip(); - (!text.is_empty()).then(|| (*tag, text.to_string())) - }) -} - -fn frame_in_window(cx: &App, tag: i32, target: &Target) -> Option<(f32, f32, f32, f32)> { - let store = cx.try_global::()?.0.read(cx); - let node = store.nodes.get(&tag)?.read(cx); - let origin = target.window_point(node.absolute_origin(cx)); - let (scale_x, scale_y) = node.cumulative_scale(cx); - let zoom = target.zoom(); - Some(( - f32::from(origin.x), - f32::from(origin.y), - node.frame.w * scale_x * zoom, - node.frame.h * scale_y * zoom, - )) -} - -/// The pointer is at `position` over `target` (the hover chain is current). -pub(crate) fn pointer_over( - window: &mut Window, - cx: &mut App, - target: Option<&Target>, - position: Point, -) { - let found = target.and_then(|target| { - let (tag, text) = tooltip_view(cx, &target.chain)?; - let rect = frame_in_window(cx, tag, target)?; - Some(Active { tag, text, rect }) - }); - let Some(next) = found else { - dismiss(window, cx); - return; - }; - let same = ACTIVE.with_borrow(|active| active.as_ref() == Some(&next)); - if same && native() { - return; - } - let same_view = ACTIVE.with_borrow(|active| { - active - .as_ref() - .is_some_and(|active| active.tag == next.tag && active.text == next.text) - }); - ACTIVE.with_borrow_mut(|active| *active = Some(next.clone())); - if native() { - #[cfg(target_os = "macos")] - mac::apply(window, Some(&next)); - return; - } - if same_view && DRAWN.with_borrow(Option::is_some) { - return; - } - hide_drawn(cx); - let generation = GENERATION.with(|generation| { - generation.set(generation.get() + 1); - generation.get() - }); - let Some(store) = store_from(cx) else { - return; - }; - let window_handle = store.read(cx).window; - let text = next.text; - let at = point(f32::from(position.x) + 12.0, f32::from(position.y) + 22.0); - cx.spawn(async move |cx| { - cx.background_executor().timer(DRAWN_DELAY).await; - let _ = cx.update(|cx| { - if GENERATION.with(Cell::get) != generation { - return; - } - DRAWN.with_borrow_mut(|drawn| { - *drawn = Some(Drawn { - text, - x: at.x, - y: at.y, - }) - }); - let _ = cx.update_window(window_handle, |_, window, _| window.refresh()); - }); - }) - .detach(); -} - -fn hide_drawn(cx: &mut App) { - let was = DRAWN.with_borrow_mut(Option::take).is_some(); - if was { - if let Some(store) = store_from(cx) { - let handle = store.read(cx).window; - let _ = cx.update_window(handle, |_, window, _| window.refresh()); - } - } -} - -/// The pointer left, pressed, scrolled, or the window lost focus. -pub(crate) fn dismiss(window: &mut Window, cx: &mut App) { - GENERATION.with(|generation| generation.set(generation.get() + 1)); - let had = ACTIVE.with_borrow_mut(Option::take).is_some(); - let drawn = DRAWN.with_borrow_mut(Option::take).is_some(); - if drawn { - window.refresh(); - } - #[cfg(target_os = "macos")] - if had && native() { - mac::apply(window, None); - } - let _ = (had, cx); -} - -/// The element that draws the tooltip, in window coordinates. -pub(crate) fn drawn_element(window: &Window) -> Option { - use gpui::{div, prelude::*, rgb, rgba}; - let drawn = drawn()?; - let size = window.viewport_size(); - let width = 260.0f32; - let x = drawn.x.min(f32::from(size.width) - width - 4.0).max(4.0); - let y = drawn.y.min(f32::from(size.height) - 28.0).max(4.0); - Some( - gpui::deferred( - div() - .id("tooltip") - .absolute() - .left(px(x)) - .top(px(y)) - .max_w(px(width)) - .px(px(6.0)) - .py(px(3.0)) - .rounded(px(4.0)) - .border_1() - .border_color(rgba(0x00000033)) - .bg(rgb(0xf5f5f5)) - .text_color(rgb(0x1a1a1a)) - .text_size(px(12.0)) - .child(drawn.text), - ) - .priority(1000) - .into_any_element(), - ) -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/tooltip/mac.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/tooltip/mac.rs deleted file mode 100644 index 9a4d4f89ef..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/tooltip/mac.rs +++ /dev/null @@ -1,122 +0,0 @@ -//! The system tooltip: a tooltip rectangle on the window's view. - -use super::Active; -use cocoa::base::{id, nil}; -use cocoa::foundation::{NSPoint, NSRect, NSSize, NSString}; -use objc::declare::ClassDecl; -use objc::runtime::{Class, Object, Sel}; -use objc::{class, msg_send, sel, sel_impl}; -use raw_window_handle::{HasWindowHandle, RawWindowHandle}; -use std::ffi::c_void; -use std::sync::Once; - -fn owner_class() -> &'static Class { - static REGISTER: Once = Once::new(); - REGISTER.call_once(|| { - let mut declaration = ClassDecl::new("RNGpuiToolTipOwner", class!(NSObject)) - .expect("the tooltip owner class is registered once"); - // SAFETY: the signature matches the `NSToolTipOwner` informal protocol. - unsafe { - declaration.add_method( - sel!(view:stringForToolTip:point:userData:), - string_for_tool_tip - as extern "C" fn(&Object, Sel, id, isize, NSPoint, *mut c_void) -> id, - ); - } - declaration.register(); - }); - Class::get("RNGpuiToolTipOwner").expect("the tooltip owner class exists") -} - -extern "C" fn string_for_tool_tip( - _this: &Object, - _selector: Sel, - _view: id, - _tag: isize, - _point: NSPoint, - data: *mut c_void, -) -> id { - let tag = data as isize as i32; - let Some(active) = super::active().filter(|active| active.tag == tag) else { - return nil; - }; - // SAFETY: the string is autoreleased, as AppKit expects of a returned object. - unsafe { - let string = NSString::alloc(nil).init_str(&active.text); - msg_send![string, autorelease] - } -} - -fn owner() -> id { - thread_local! { - static OWNER: std::cell::Cell = const { std::cell::Cell::new(0) }; - } - OWNER.with(|owner| { - if owner.get() == 0 { - // SAFETY: the owner is allocated once and kept for the process. - let object: id = unsafe { msg_send![owner_class(), new] }; - owner.set(object as usize); - } - owner.get() as id - }) -} - -fn ns_view(window: &gpui::Window) -> Option { - let handle = HasWindowHandle::window_handle(window).ok()?; - match handle.as_raw() { - RawWindowHandle::AppKit(appkit) => Some(appkit.ns_view.as_ptr() as id), - _ => None, - } -} - -/// The system tooltip text for a view, as AppKit's call to the owner gets it, and -/// how many tracking areas the window's view has. -pub(crate) fn probe(window: &gpui::Window, tag: i32) -> (Option, usize) { - let Some(view) = ns_view(window) else { - return (None, 0); - }; - // SAFETY: AppKit is messaged on the main thread with the window's view and - // the tooltip owner; the string is read before the autorelease pool drains. - unsafe { - let areas: id = msg_send![view, trackingAreas]; - let count: usize = msg_send![areas, count]; - let string: id = msg_send![owner(), view: view - stringForToolTip: 0isize - point: NSPoint::new(0.0, 0.0) - userData: tag as isize as *mut c_void]; - let text = if string.is_null() { - None - } else { - let bytes: *const std::os::raw::c_char = msg_send![string, UTF8String]; - Some( - std::ffi::CStr::from_ptr(bytes) - .to_string_lossy() - .into_owned(), - ) - }; - (text, count) - } -} - -/// Replaces the window's tooltip rectangle with the one for `active`, or none. -pub(super) fn apply(window: &mut gpui::Window, active: Option<&Active>) { - let Some(view) = ns_view(window) else { - return; - }; - // SAFETY: AppKit is messaged on the main thread, with the window's own view. - unsafe { - let _: () = msg_send![view, removeAllToolTips]; - let Some(active) = active else { - return; - }; - let bounds: NSRect = msg_send![view, bounds]; - let (x, y, width, height) = active.rect; - let rect = NSRect::new( - NSPoint::new(x as f64, bounds.size.height - (y + height) as f64), - NSSize::new(width as f64, height as f64), - ); - let _: isize = msg_send![view, addToolTipRect: rect - owner: owner() - userData: active.tag as isize as *mut c_void]; - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/transform.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/transform.rs deleted file mode 100644 index a0ab09fbef..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/transform.rs +++ /dev/null @@ -1,152 +0,0 @@ -//! Draws and hit-tests a node's subtree under the 2D matrix of its `transform`. - -use gpui::{ - AnyElement, App, Bounds, Element, ElementId, GlobalElementId, InspectorElementId, IntoElement, - LayoutId, Pixels, TransformationMatrix, Window, -}; - -/// The affine part of a Fabric transform, `None` when it is the identity. -/// -/// Fabric's matrix is column-vector-free: `x' = m0 x + m4 y + m12`, -/// `y' = m1 x + m5 y + m13`. Rows of depth and perspective are dropped. -pub(crate) fn affine(matrix: &[f32; 16]) -> Option { - if matrix.iter().any(|value| !value.is_finite()) { - return None; - } - let affine = TransformationMatrix { - rotation_scale: [[matrix[0], matrix[4]], [matrix[1], matrix[5]]], - translation: [matrix[12], matrix[13]], - }; - (affine != TransformationMatrix::unit()).then_some(affine) -} - -/// Whether the matrix reaches outside the plane (perspective, or a turn about -/// the x or y axis), which a 2D affine matrix cannot show. -pub(crate) fn is_three_dimensional(matrix: &[f32; 16]) -> bool { - [ - matrix[2], matrix[3], matrix[6], matrix[7], matrix[8], matrix[9], matrix[11], matrix[14], - ] - .into_iter() - .any(|value| value.abs() > 0.0001) - || (matrix[10] - 1.0).abs() > 0.0001 - || (matrix[15] - 1.0).abs() > 0.0001 -} - -/// Whether a node turned by `matrix` shows its back to the viewer: it is -/// turned out of the plane and the screen axes are mirrored. -pub(crate) fn faces_away(matrix: &[f32; 16]) -> bool { - is_three_dimensional(matrix) && matrix[0] * matrix[5] - matrix[4] * matrix[1] < 0.0 -} - -/// `child` drawn under `matrix`, turned about the child's own top-left corner. -pub(crate) struct Transformed { - child: AnyElement, - matrix: TransformationMatrix, -} - -impl Transformed { - pub(crate) fn new(child: AnyElement, matrix: TransformationMatrix) -> Self { - Self { child, matrix } - } -} - -impl IntoElement for Transformed { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - -impl Element for Transformed { - type RequestLayoutState = (); - type PrepaintState = (); - - fn id(&self) -> Option { - None - } - - fn source_location(&self) -> Option<&'static core::panic::Location<'static>> { - None - } - - fn request_layout( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&InspectorElementId>, - window: &mut Window, - cx: &mut App, - ) -> (LayoutId, Self::RequestLayoutState) { - (self.child.request_layout(window, cx), ()) - } - - fn prepaint( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&InspectorElementId>, - bounds: Bounds, - _request_layout: &mut Self::RequestLayoutState, - window: &mut Window, - cx: &mut App, - ) -> Self::PrepaintState { - let (matrix, child) = (self.matrix, &mut self.child); - window.with_transformation_about(bounds.origin, matrix, |window| { - child.prepaint(window, cx); - }); - } - - fn paint( - &mut self, - _id: Option<&GlobalElementId>, - _inspector_id: Option<&InspectorElementId>, - bounds: Bounds, - _request_layout: &mut Self::RequestLayoutState, - _prepaint: &mut Self::PrepaintState, - window: &mut Window, - cx: &mut App, - ) { - let (matrix, child) = (self.matrix, &mut self.child); - window.with_transformation_about(bounds.origin, matrix, |window| { - child.paint(window, cx); - }); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn identity() -> [f32; 16] { - let mut m = [0.0; 16]; - m[0] = 1.0; - m[5] = 1.0; - m[10] = 1.0; - m[15] = 1.0; - m - } - - #[test] - fn a_half_turn_about_y_faces_away() { - let mut m = identity(); - m[0] = -1.0; - m[10] = -1.0; - assert!(faces_away(&m)); - } - - #[test] - fn a_quarter_turn_about_y_still_faces_front() { - let mut m = identity(); - m[0] = 0.5; - m[8] = -0.87; - m[2] = 0.87; - m[10] = 0.5; - assert!(!faces_away(&m)); - } - - #[test] - fn a_flat_mirror_does_not_face_away() { - let mut m = identity(); - m[0] = -1.0; - assert!(!faces_away(&m)); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/view_props.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/view_props.rs deleted file mode 100644 index 32c9e118bc..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/view_props.rs +++ /dev/null @@ -1,310 +0,0 @@ -//! A node's view props, with the rarely set ones out of line. -//! -//! `ViewPropsFlat` holds two dozen strings and lists, a matrix, and the scalar -//! props. Most nodes set none of the strings and lists, so they live in a -//! [`ViewExtras`] allocated only for a node that sets one; every other node -//! reads them from one shared empty set. Fields are read as they are on -//! `ViewPropsFlat`, through `Deref`. - -use rn_gpui_sys::ffi::{AccessibilityActionFlat, CornersF, EdgesF, ShadowF, ViewPropsFlat}; - -const IDENTITY: [f32; 16] = [ - 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, -]; - -/// The scalar view props, and the rest behind [`ViewProps::extras`]. -#[derive(Clone, Debug)] -pub struct ViewProps { - pub opacity: f32, - pub background_color: u32, - pub border_widths: EdgesF, - pub content_insets: EdgesF, - pub border_colors: [u32; 4], - pub border_styles: [u8; 4], - pub border_radii: CornersF, - pub outline_color: u32, - pub outline_width: f32, - pub outline_offset: f32, - pub outline_style: u8, - pub overflow_hidden: bool, - pub display_none: bool, - pub pointer_events: u8, - pub cursor: u8, - pub mix_blend_mode: u8, - pub isolate: bool, - pub hit_slop: [f32; 4], - pub has_transform: bool, - pub backface_hidden: bool, - pub transform_origin_set: bool, - pub accessibility_traits: u32, - pub accessibility_value_min: i32, - pub accessibility_value_max: i32, - pub accessibility_value_now: i32, - pub accessibility_has_value_min: bool, - pub accessibility_has_value_max: bool, - pub accessibility_has_value_now: bool, - pub accessible: bool, - pub accessibility_disabled: bool, - pub accessibility_selected: bool, - pub accessibility_busy: bool, - pub accessibility_checked: u8, - pub accessibility_expanded: i8, - pub accessibility_important: u8, - pub accessibility_live_region: u8, - pub accessibility_hidden: bool, - pub accessibility_modal: bool, - pub accessibility_responds_to_interaction: bool, - pub accessibility_has_action_listener: bool, - pub accessibility_has_tap_listener: bool, - pub accessibility_has_escape_listener: bool, - pub desktop_drag_region: bool, - pub on_context_menu: bool, - pub on_wheel: bool, - pub on_layout: bool, - pub accepts_files: bool, - pub draggable: bool, - pub droppable: bool, - extras: Option>, -} - -/// The view props a node usually leaves unset. -#[derive(Clone, Debug)] -pub struct ViewExtras { - pub shadows: Vec, - pub background_json: String, - pub filter_json: String, - pub transform: [f32; 16], - pub test_id: String, - pub accessibility_label: String, - pub accessibility_hint: String, - pub accessibility_language: String, - pub accessibility_role: String, - pub accessibility_value_text: String, - pub accessibility_actions: Vec, - pub accessibility_labelled_by: Vec, - pub accessibility_order: Vec, - pub accessibility_native_id: String, - pub accessibility_large_content_title: String, - pub group: String, - pub hover_style: String, - pub active_style: String, - pub focus_style: String, - pub focus_visible_style: String, - pub group_hover_style: String, - pub group_active_style: String, - pub drag_over_style: String, - pub tooltip: String, -} - -static EMPTY: ViewExtras = ViewExtras { - shadows: Vec::new(), - background_json: String::new(), - filter_json: String::new(), - transform: IDENTITY, - test_id: String::new(), - accessibility_label: String::new(), - accessibility_hint: String::new(), - accessibility_language: String::new(), - accessibility_role: String::new(), - accessibility_value_text: String::new(), - accessibility_actions: Vec::new(), - accessibility_labelled_by: Vec::new(), - accessibility_order: Vec::new(), - accessibility_native_id: String::new(), - accessibility_large_content_title: String::new(), - group: String::new(), - hover_style: String::new(), - active_style: String::new(), - focus_style: String::new(), - focus_visible_style: String::new(), - group_hover_style: String::new(), - group_active_style: String::new(), - drag_over_style: String::new(), - tooltip: String::new(), -}; - -impl ViewExtras { - fn is_empty(&self) -> bool { - self.shadows.is_empty() - && self.background_json.is_empty() - && self.filter_json.is_empty() - && self.transform == IDENTITY - && self.test_id.is_empty() - && self.accessibility_label.is_empty() - && self.accessibility_hint.is_empty() - && self.accessibility_language.is_empty() - && self.accessibility_role.is_empty() - && self.accessibility_value_text.is_empty() - && self.accessibility_actions.is_empty() - && self.accessibility_labelled_by.is_empty() - && self.accessibility_order.is_empty() - && self.accessibility_native_id.is_empty() - && self.accessibility_large_content_title.is_empty() - && self.group.is_empty() - && self.hover_style.is_empty() - && self.active_style.is_empty() - && self.focus_style.is_empty() - && self.focus_visible_style.is_empty() - && self.group_hover_style.is_empty() - && self.group_active_style.is_empty() - && self.drag_over_style.is_empty() - && self.tooltip.is_empty() - } -} - -impl Default for ViewExtras { - fn default() -> Self { - EMPTY.clone() - } -} - -impl std::ops::Deref for ViewProps { - type Target = ViewExtras; - - fn deref(&self) -> &ViewExtras { - self.extras.as_deref().unwrap_or(&EMPTY) - } -} - -impl std::ops::DerefMut for ViewProps { - fn deref_mut(&mut self) -> &mut ViewExtras { - self.extras.get_or_insert_with(Default::default) - } -} - -impl Default for ViewProps { - fn default() -> Self { - Self::from(ViewPropsFlat::default()) - } -} - -impl From for ViewProps { - fn from(flat: ViewPropsFlat) -> Self { - let extras = ViewExtras { - shadows: flat.shadows, - background_json: flat.background_json, - filter_json: flat.filter_json, - transform: flat.transform, - test_id: flat.test_id, - accessibility_label: flat.accessibility_label, - accessibility_hint: flat.accessibility_hint, - accessibility_language: flat.accessibility_language, - accessibility_role: flat.accessibility_role, - accessibility_value_text: flat.accessibility_value_text, - accessibility_actions: flat.accessibility_actions, - accessibility_labelled_by: flat.accessibility_labelled_by, - accessibility_order: flat.accessibility_order, - accessibility_native_id: flat.accessibility_native_id, - accessibility_large_content_title: flat.accessibility_large_content_title, - group: flat.group, - hover_style: flat.hover_style, - active_style: flat.active_style, - focus_style: flat.focus_style, - focus_visible_style: flat.focus_visible_style, - group_hover_style: flat.group_hover_style, - group_active_style: flat.group_active_style, - drag_over_style: flat.drag_over_style, - tooltip: flat.tooltip, - }; - Self { - opacity: flat.opacity, - background_color: flat.background_color, - border_widths: flat.border_widths, - content_insets: flat.content_insets, - border_colors: flat.border_colors, - border_styles: flat.border_styles, - border_radii: flat.border_radii, - outline_color: flat.outline_color, - outline_width: flat.outline_width, - outline_offset: flat.outline_offset, - outline_style: flat.outline_style, - overflow_hidden: flat.overflow_hidden, - display_none: flat.display_none, - pointer_events: flat.pointer_events, - cursor: flat.cursor, - mix_blend_mode: flat.mix_blend_mode, - isolate: flat.isolate, - hit_slop: flat.hit_slop, - has_transform: flat.has_transform, - backface_hidden: flat.backface_hidden, - transform_origin_set: flat.transform_origin_set, - accessibility_traits: flat.accessibility_traits, - accessibility_value_min: flat.accessibility_value_min, - accessibility_value_max: flat.accessibility_value_max, - accessibility_value_now: flat.accessibility_value_now, - accessibility_has_value_min: flat.accessibility_has_value_min, - accessibility_has_value_max: flat.accessibility_has_value_max, - accessibility_has_value_now: flat.accessibility_has_value_now, - accessible: flat.accessible, - accessibility_disabled: flat.accessibility_disabled, - accessibility_selected: flat.accessibility_selected, - accessibility_busy: flat.accessibility_busy, - accessibility_checked: flat.accessibility_checked, - accessibility_expanded: flat.accessibility_expanded, - accessibility_important: flat.accessibility_important, - accessibility_live_region: flat.accessibility_live_region, - accessibility_hidden: flat.accessibility_hidden, - accessibility_modal: flat.accessibility_modal, - accessibility_responds_to_interaction: flat.accessibility_responds_to_interaction, - accessibility_has_action_listener: flat.accessibility_has_action_listener, - accessibility_has_tap_listener: flat.accessibility_has_tap_listener, - accessibility_has_escape_listener: flat.accessibility_has_escape_listener, - desktop_drag_region: flat.desktop_drag_region, - on_context_menu: flat.on_context_menu, - on_wheel: flat.on_wheel, - on_layout: flat.on_layout, - accepts_files: flat.accepts_files, - draggable: flat.draggable, - droppable: flat.droppable, - extras: (!extras.is_empty()).then(|| Box::new(extras)), - } - } -} - -impl From<&ViewPropsFlat> for ViewProps { - fn from(flat: &ViewPropsFlat) -> Self { - Self::from(flat.clone()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_view_without_strings_or_lists_has_no_extras() { - let props = ViewProps::from(ViewPropsFlat { - transform: IDENTITY, - opacity: 0.5, - ..Default::default() - }); - assert!(props.extras.is_none()); - assert_eq!(props.opacity, 0.5); - assert!(props.test_id.is_empty()); - assert_eq!(props.transform, IDENTITY); - } - - #[test] - fn a_set_string_or_matrix_is_kept() { - let mut flat = ViewPropsFlat { - transform: IDENTITY, - ..Default::default() - }; - flat.test_id = "cell".into(); - let props = ViewProps::from(flat); - assert_eq!(props.test_id, "cell"); - let mut moved = ViewPropsFlat::default(); - moved.transform[12] = 4.0; - assert_eq!(ViewProps::from(moved).transform[12], 4.0); - } - - #[test] - fn writing_an_extra_allocates_it() { - let mut props = ViewProps::from(ViewPropsFlat { - transform: IDENTITY, - ..Default::default() - }); - props.tooltip = "tip".into(); - assert_eq!(props.tooltip, "tip"); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/virtual_view.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/virtual_view.rs deleted file mode 100644 index 05428ba885..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/virtual_view.rs +++ /dev/null @@ -1,159 +0,0 @@ -//! `VirtualView`: which of three modes a view is in, by where it lies -//! against the viewport of the scroll view around it. -//! -//! Visible, in the viewport; prerender, in the viewport grown by -//! [`PRERENDER_RATIO`] viewports along the scroll axis, where the content is -//! worth having ready; hidden, anywhere else. React hears of every change -//! as `onModeChange` and decides what to keep mounted. - -use gpui::App; - -/// How many viewports past the visible one a view is still prerendered. -const PRERENDER_RATIO: f32 = 5.0; - -pub(crate) const VISIBLE: i32 = 0; -pub(crate) const PRERENDER: i32 = 1; -pub(crate) const HIDDEN: i32 = 2; - -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) struct Rect { - pub x: f32, - pub y: f32, - pub w: f32, - pub h: f32, -} - -impl Rect { - fn intersects(&self, other: &Rect) -> bool { - self.x < other.x + other.w - && other.x < self.x + self.w - && self.y < other.y + other.h - && other.y < self.y + self.h - } - - fn json(&self) -> serde_json::Value { - serde_json::json!({"x": self.x, "y": self.y, "width": self.w, "height": self.h}) - } -} - -/// The rect that counts as prerender: the viewport grown along the scroll -/// axis. A view that scrolls both ways is grown both ways. -pub(crate) fn prerender_rect(viewport: Rect, horizontal: bool) -> Rect { - let mut grown = viewport; - if horizontal { - grown.x -= viewport.w * PRERENDER_RATIO; - grown.w *= 1.0 + 2.0 * PRERENDER_RATIO; - } else { - grown.y -= viewport.h * PRERENDER_RATIO; - grown.h *= 1.0 + 2.0 * PRERENDER_RATIO; - } - grown -} - -/// The mode of a view at `target`, in the scroll view's content space. -pub(crate) fn mode(target: Rect, viewport: Rect, horizontal: bool) -> i32 { - if target.intersects(&viewport) { - VISIBLE - } else if target.intersects(&prerender_rect(viewport, horizontal)) { - PRERENDER - } else { - HIDDEN - } -} - -/// Reports the mode of every `VirtualView` that changed, after the content -/// of a scroll view moved or a batch mounted. -pub(crate) fn update(cx: &mut App) { - let Some(store) = crate::store::store_from(cx) else { - return; - }; - let (host, nodes): (_, Vec<_>) = { - let store = store.read(cx); - ( - store.host.clone(), - store - .nodes - .values() - .filter(|node| node.read(cx).component == "VirtualView") - .cloned() - .collect(), - ) - }; - for node in nodes { - let Some((target, viewport, horizontal)) = node.read(cx).virtual_view_geometry(cx) else { - continue; - }; - let now = mode(target, viewport, horizontal); - let tag = node.read(cx).tag; - if node.read(cx).virtual_view_mode.replace(Some(now)) == Some(now) { - continue; - } - host.dispatch_event( - tag, - "topModeChange", - &serde_json::json!({ - "mode": now, - "targetRect": target.json(), - "thresholdRect": match now { - VISIBLE => viewport, - _ => prerender_rect(viewport, horizontal), - }.json(), - }), - ); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - const VIEWPORT: Rect = Rect { - x: 0.0, - y: 1000.0, - w: 300.0, - h: 100.0, - }; - - fn at(y: f32) -> Rect { - Rect { - x: 0.0, - y, - w: 300.0, - h: 50.0, - } - } - - #[test] - fn a_view_in_the_viewport_is_visible_and_one_just_outside_is_not() { - assert_eq!(mode(at(1050.0), VIEWPORT, false), VISIBLE); - assert_eq!(mode(at(960.0), VIEWPORT, false), VISIBLE); - assert_eq!(mode(at(1100.0), VIEWPORT, false), PRERENDER); - } - - #[test] - fn a_view_within_five_viewports_is_prerendered_and_past_that_hidden() { - assert_eq!(mode(at(1500.0), VIEWPORT, false), PRERENDER); - assert_eq!(mode(at(1599.0), VIEWPORT, false), PRERENDER); - assert_eq!(mode(at(1700.0), VIEWPORT, false), HIDDEN); - assert_eq!(mode(at(460.0), VIEWPORT, false), PRERENDER); - assert_eq!(mode(at(300.0), VIEWPORT, false), HIDDEN); - } - - #[test] - fn a_horizontal_scroll_view_grows_the_viewport_sideways() { - let viewport = Rect { - x: 1000.0, - y: 0.0, - w: 100.0, - h: 300.0, - }; - let target = Rect { - x: 1400.0, - y: 0.0, - w: 50.0, - h: 300.0, - }; - assert_eq!(mode(target, viewport, true), PRERENDER); - assert_eq!(mode(target, viewport, false), HIDDEN); - } -} diff --git a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/wheel.rs b/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/wheel.rs deleted file mode 100644 index eaf987d9f0..0000000000 --- a/vendor/react-native-gpui/packages/core/ReactGpui/rn-gpui/src/wheel.rs +++ /dev/null @@ -1,465 +0,0 @@ -use crate::events::{self, ModifierState, Target}; -use crate::node_view::RNNodeView; -use crate::store::store_from; -use gpui::{ - px, AnyWindowHandle, App, AppContext as _, AsyncApp, DispatchPhase, Entity, PinchEvent, - PlatformInput, Point, ScrollDelta, ScrollEvent, TouchPhase, Window, -}; -use serde_json::{json, Value}; -use std::{ - cell::RefCell, - collections::VecDeque, - time::{Duration, SystemTime, UNIX_EPOCH}, -}; - -const REPLY_TIMEOUT: Duration = Duration::from_millis(250); -const PINCH_DELTA_SCALE: f32 = 100.0; - -#[derive(Clone)] -enum Wheel { - Scroll(ScrollEvent), - Pinch(PinchEvent), -} - -impl Wheel { - fn position(&self) -> Point { - match self { - Wheel::Scroll(event) => event.position, - Wheel::Pinch(event) => event.position, - } - } -} - -struct Queued { - wheel: Wheel, - momentum: bool, - received: f64, -} - -struct InFlight { - id: u64, - queued: Queued, -} - -#[derive(Default)] -struct State { - next_id: u64, - in_flight: Option, - queue: VecDeque, - replaying: bool, - after_lift: bool, - window: Option, -} - -thread_local! { - static STATE: RefCell = RefCell::new(State::default()); -} - -fn epoch_ms() -> f64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0.0, |elapsed| elapsed.as_secs_f64() * 1000.0) -} - -/// Whether an event is waiting for its handlers, which the test driver counts as work. -pub(crate) fn pending() -> bool { - STATE.with_borrow(|state| state.in_flight.is_some() || !state.queue.is_empty()) -} - -/// Listens, before the views below it scroll, for the wheel and the pinch. -static LAST_SCROLL_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - -/// Whether a scroll event arrived within `within`, so a window is being -/// scrolled, momentum included. -pub(crate) fn scrolled_within(within: Duration) -> bool { - let last = LAST_SCROLL_MS.load(std::sync::atomic::Ordering::Relaxed); - last != 0 && epoch_ms() - (last as f64) < within.as_secs_f64() * 1000.0 -} - -pub(crate) fn install(window: &mut Window) { - window.on_mouse_event(|event: &ScrollEvent, phase, window, cx| { - if phase == DispatchPhase::Capture { - LAST_SCROLL_MS.store(epoch_ms() as u64, std::sync::atomic::Ordering::Relaxed); - note_scroll_delta(event, window.scale_factor()); - } - if phase == DispatchPhase::Capture && intercept(Wheel::Scroll(event.clone()), window, cx) { - cx.stop_propagation(); - } - }); - window.on_mouse_event(|event: &PinchEvent, phase, window, cx| { - if phase == DispatchPhase::Capture && intercept(Wheel::Pinch(event.clone()), window, cx) { - cx.stop_propagation(); - } - }); -} - -fn intercept(wheel: Wheel, window: &mut Window, cx: &mut App) -> bool { - if STATE.with_borrow(|state| state.replaying) { - return false; - } - let busy = pending(); - if !busy && !any_handler(cx) { - return false; - } - let momentum = STATE.with_borrow_mut(|state| { - state.window = Some(window.window_handle()); - match &wheel { - Wheel::Scroll(event) if is_precise(event) => match event.touch_phase { - TouchPhase::Started => { - state.after_lift = false; - false - } - TouchPhase::Ended | TouchPhase::Cancelled => { - state.after_lift = true; - false - } - TouchPhase::Moved => state.after_lift, - }, - _ => false, - } - }); - let queued = Queued { - wheel, - momentum, - received: epoch_ms(), - }; - if busy { - STATE.with_borrow_mut(|state| state.queue.push_back(queued)); - return true; - } - match target_with_handler(window, cx, queued.wheel.position()) { - Some(target) => { - send(queued, target, window, cx); - true - } - None => false, - } -} - -fn is_precise(event: &ScrollEvent) -> bool { - matches!(event.delta, ScrollDelta::Pixels(_)) -} - -fn any_handler(cx: &App) -> bool { - let Some(store) = store_from(cx) else { - return false; - }; - let store = store.read(cx); - store.nodes.values().any(|node| node.read(cx).view.on_wheel) -} - -fn contains(node: &RNNodeView, page: Point, cx: &App) -> bool { - let origin = node.absolute_origin(cx); - let (scale_x, scale_y) = node.cumulative_scale(cx); - page.x >= origin.x - && page.y >= origin.y - && page.x < origin.x + px(node.frame.w * scale_x) - && page.y < origin.y + px(node.frame.h * scale_y) -} - -fn clipped_out(node: &Entity, page: Point, cx: &App) -> bool { - let mut parent = node.read(cx).parent.clone(); - while let Some(next) = parent.and_then(|weak| weak.upgrade()) { - let ancestor = next.read(cx); - if (ancestor.view.overflow_hidden || ancestor.scroll.is_some()) - && !contains(ancestor, page, cx) - { - return true; - } - parent = ancestor.parent.clone(); - } - false -} - -/// Where a node sits in paint order: its index among its siblings at each level, -/// from the root. A later sibling paints over an earlier one, and a node over its -/// ancestors, which is how the vectors compare. -fn paint_path(node: &Entity, cx: &App) -> Vec { - let mut path = Vec::new(); - let mut current = node.clone(); - loop { - let parent = current - .read(cx) - .parent - .clone() - .and_then(|weak| weak.upgrade()); - let Some(parent) = parent else { - break; - }; - let tag = current.read(cx).tag; - let index = parent - .read(cx) - .children - .iter() - .position(|(child, _)| *child == tag) - .unwrap_or(0); - path.push(index); - current = parent; - } - path.reverse(); - path -} - -static SCROLL_EVENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -static SCROLL_EVENTS_WHOLE_PIXEL: std::sync::atomic::AtomicU64 = - std::sync::atomic::AtomicU64::new(0); - -fn note_scroll_delta(event: &ScrollEvent, scale: f32) { - use std::sync::atomic::Ordering::Relaxed; - let ScrollDelta::Pixels(delta) = event.delta else { - return; - }; - SCROLL_EVENTS.fetch_add(1, Relaxed); - let whole = |value: f32| ((value * scale) - (value * scale).round()).abs() < 0.001; - if whole(f32::from(delta.x)) && whole(f32::from(delta.y)) { - SCROLL_EVENTS_WHOLE_PIXEL.fetch_add(1, Relaxed); - } -} - -/// The precise scroll events seen since the last reset, and how many moved by a -/// whole number of device pixels on both axes. -pub(crate) fn scroll_delta_stats(reset: bool) -> (u64, u64) { - use std::sync::atomic::Ordering::Relaxed; - if reset { - ( - SCROLL_EVENTS.swap(0, Relaxed), - SCROLL_EVENTS_WHOLE_PIXEL.swap(0, Relaxed), - ) - } else { - ( - SCROLL_EVENTS.load(Relaxed), - SCROLL_EVENTS_WHOLE_PIXEL.load(Relaxed), - ) - } -} - -static TARGET_AT_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -static TARGET_AT_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - -/// The calls to `target_at` and the time they took, in milliseconds, since the -/// last reset. -pub(crate) fn target_at_stats(reset: bool) -> (u64, f64) { - use std::sync::atomic::Ordering::Relaxed; - let (calls, nanos) = if reset { - ( - TARGET_AT_CALLS.swap(0, Relaxed), - TARGET_AT_NANOS.swap(0, Relaxed), - ) - } else { - (TARGET_AT_CALLS.load(Relaxed), TARGET_AT_NANOS.load(Relaxed)) - }; - (calls, nanos as f64 / 1_000_000.0) -} - -/// The target under a window position, found from the nodes' frames, their -/// scroll offsets and the clips of their ancestors. -pub(crate) fn target_at(cx: &App, position: Point) -> Option { - use std::sync::atomic::Ordering::Relaxed; - let started = std::time::Instant::now(); - let target = find_target(cx, position); - TARGET_AT_CALLS.fetch_add(1, Relaxed); - TARGET_AT_NANOS.fetch_add(started.elapsed().as_nanos() as u64, Relaxed); - target -} - -fn find_target(cx: &App, position: Point) -> Option { - let store = store_from(cx)?; - let store = store.read(cx); - let conversion = store - .nodes - .values() - .find_map(|node| events::target(cx, node.read(cx)))?; - let page = conversion.page(position); - let mut hit: Option<(Vec, Entity)> = None; - for entity in store.nodes.values() { - let node = entity.read(cx); - if node.view.display_none { - continue; - } - if !contains(node, page, cx) || clipped_out(entity, page, cx) { - continue; - } - let path = paint_path(entity, cx); - if hit.as_ref().map_or(true, |(best, _)| path > *best) { - hit = Some((path, entity.clone())); - } - } - let (_, entity) = hit?; - events::target(cx, entity.read(cx)) -} - -fn target_with_handler( - _window: &Window, - cx: &App, - position: Point, -) -> Option { - let store = store_from(cx)?; - let store = store.read(cx); - let target = target_at(cx, position)?; - let wants = target.chain.iter().any(|tag| { - store - .nodes - .get(tag) - .is_some_and(|node| node.read(cx).view.on_wheel) - }); - wants.then_some(target) -} - -fn payload(queued: &Queued, target: &Target) -> Value { - let position = target.page(queued.wheel.position()); - let location = target.local_position(position); - let (x, y) = (f32::from(position.x), f32::from(position.y)); - let (modifiers, delta_x, delta_y, mode, trackpad, phase, momentum, pinch) = match &queued.wheel - { - Wheel::Scroll(event) => { - let modifiers = ModifierState::from_gpui(&event.modifiers); - let (mut delta_x, mut delta_y, mode, trackpad) = match event.delta { - ScrollDelta::Pixels(delta) => (-f32::from(delta.x), -f32::from(delta.y), 0, true), - ScrollDelta::Lines(delta) => (-delta.x, -delta.y, 1, false), - }; - if !trackpad && modifiers.shift && delta_x == 0.0 { - delta_x = delta_y; - delta_y = 0.0; - } - let phase = if !trackpad { - "none" - } else if queued.momentum { - "changed" - } else { - match event.touch_phase { - TouchPhase::Started => "began", - TouchPhase::Moved => "changed", - TouchPhase::Ended => "ended", - TouchPhase::Cancelled => "cancelled", - } - }; - ( - modifiers, - delta_x, - delta_y, - mode, - trackpad, - phase, - queued.momentum, - false, - ) - } - Wheel::Pinch(event) => { - let mut modifiers = ModifierState::from_gpui(&event.modifiers); - modifiers.ctrl = true; - let phase = match event.phase { - TouchPhase::Started => "began", - TouchPhase::Moved => "changed", - TouchPhase::Ended => "ended", - TouchPhase::Cancelled => "cancelled", - }; - ( - modifiers, - 0.0, - -event.delta * PINCH_DELTA_SCALE, - 0, - true, - phase, - false, - true, - ) - } - }; - json!({ - "target": target.tag, - "deltaX": delta_x, - "deltaY": delta_y, - "deltaZ": 0.0, - "deltaMode": mode, - "isTrackpad": trackpad, - "phase": phase, - "momentum": momentum, - "isPinch": pinch, - "ctrlKey": modifiers.ctrl, - "shiftKey": modifiers.shift, - "altKey": modifiers.alt, - "metaKey": modifiers.meta, - "clientX": x, - "clientY": y, - "x": x, - "y": y, - "pageX": x, - "pageY": y, - "screenX": x, - "screenY": y, - "offsetX": f32::from(location.x), - "offsetY": f32::from(location.y), - "timestamp": queued.received, - }) -} - -fn send(queued: Queued, target: Target, window: &mut Window, cx: &mut App) { - let Some(store) = store_from(cx) else { - replay(queued, window, cx); - return; - }; - let host = store.read(cx).host.clone(); - let body = payload(&queued, &target); - let id = STATE.with_borrow_mut(|state| { - state.next_id += 1; - let id = state.next_id; - state.in_flight = Some(InFlight { id, queued }); - id - }); - host.dispatch_wheel(target.tag, id, &body); - let handle = window.window_handle(); - cx.spawn(async move |cx| { - cx.background_executor().timer(REPLY_TIMEOUT).await; - let _ = cx.update_window(handle, |_, window, cx| finish(id, false, window, cx)); - }) - .detach(); -} - -/// The handlers of the wheel event `id` have run. -pub(crate) fn done(id: u64, prevented: bool, cx: &mut AsyncApp) { - let Some(handle) = STATE.with_borrow(|state| state.window) else { - return; - }; - let _ = cx.update_window(handle, |_, window, cx| finish(id, prevented, window, cx)); -} - -fn finish(id: u64, prevented: bool, window: &mut Window, cx: &mut App) { - let current = STATE.with_borrow_mut(|state| { - if state - .in_flight - .as_ref() - .is_some_and(|flight| flight.id == id) - { - state.in_flight.take() - } else { - None - } - }); - let Some(flight) = current else { - return; - }; - if !prevented { - replay(flight.queued, window, cx); - } - loop { - let Some(next) = STATE.with_borrow_mut(|state| state.queue.pop_front()) else { - break; - }; - match target_with_handler(window, cx, next.wheel.position()) { - Some(target) => { - send(next, target, window, cx); - break; - } - None => replay(next, window, cx), - } - } -} - -fn replay(queued: Queued, window: &mut Window, cx: &mut App) { - let Wheel::Scroll(event) = queued.wheel else { - return; - }; - STATE.with_borrow_mut(|state| state.replaying = true); - window.dispatch_event(PlatformInput::Scroll(event), cx); - STATE.with_borrow_mut(|state| state.replaying = false); -} diff --git a/vendor/react-native-gpui/packages/core/babel-plugin-node-addons.js b/vendor/react-native-gpui/packages/core/babel-plugin-node-addons.js deleted file mode 100644 index b49bf1df1d..0000000000 --- a/vendor/react-native-gpui/packages/core/babel-plugin-node-addons.js +++ /dev/null @@ -1,1223 +0,0 @@ -// Babel plugin: turn `require('….node')` / `import … from '….node'` into -// `_requireNodeLibrary(key, path)` for the GPUI desktop runtime. -// -// On a phone an app may only load code that was embedded and signed at build -// time, so addons are discovered ahead of time and loaded through a shim. A -// desktop app has none of those restrictions: it can `dlopen` any file, so the -// stock `.node` binary a package publishes to npm loads unchanged. All this -// plugin does is tell the runtime which file to open and give it a stable name -// for that file. -// -// It is a no-op unless Babel's caller reports `platform === 'desktop'`, so one -// `babel.config.js` works for iOS, Android and desktop. -'use strict'; - -const crypto = require('node:crypto'); -const fs = require('node:fs'); -const path = require('node:path'); - -// ELF magic and e_machine values, enough to tell a Linux addon for the host -// architecture from one built for another platform or CPU. -const ELF_MAGIC = Buffer.from([0x7f, 0x45, 0x4c, 0x46]); - -// Mach-O magics as the byte order they appear in the file: -// CF FA ED FE / CE FA ED FE 64- and 32-bit thin, little-endian fields -// FE ED FA CF / FE ED FA CE the same, big-endian fields -// CA FE BA BE universal, big-endian table -// BE BA FE CA universal, little-endian table -const MACHO_THIN_LE = Buffer.from([0xcf, 0xfa, 0xed, 0xfe]); -const MACHO_THIN_LE_32 = Buffer.from([0xce, 0xfa, 0xed, 0xfe]); -const MACHO_THIN_BE = Buffer.from([0xfe, 0xed, 0xfa, 0xcf]); -const MACHO_THIN_BE_32 = Buffer.from([0xfe, 0xed, 0xfa, 0xce]); -const MACHO_FAT_BE = Buffer.from([0xca, 0xfe, 0xba, 0xbe]); -const MACHO_FAT_LE = Buffer.from([0xbe, 0xba, 0xfe, 0xca]); - -// cputype values that mean "the host CPU" for each arch name. -const CPU_TYPES = { - arm64: 0x0100000c, - x64: 0x01000007, - ia32: 0x00000007, -}; - -const ELF_MACHINE = { - arm64: 0xb7, - x64: 0x3e, - ia32: 0x03, -}; - -/** - * Platform markers that appear in a prebuild directory or file name, and the - * host platform each one belongs to. A segment naming a *different* platform - * is foreign; one naming the host's is not. - */ -const PLATFORM_MARKERS = { - darwin: 'darwin', - macos: 'darwin', - osx: 'darwin', - win32: 'win32', - windows: 'win32', - linux: 'linux', - linuxmusl: 'linux', - android: 'android', - freebsd: 'freebsd', - openharmony: 'openharmony', -}; - -/** - * Whether a segment names a libc other than the host's. `musl` on a glibc host - * cannot load (and the reverse), and neither can an `eabi`/`gnueabihf` ARM - * variant on a soft-float host. - */ -function namesForeignLibc(segment) { - return /\bmusl\b|musleabihf|musl-/u.test(segment); -} - -/** - * Whether a segment names a platform or CPU other than the host's. Architecture - * tokens are compared after normalizing the common spellings, so `x86_64` and - * `amd64` both become `x64` before the `x86` token could match and a plain - * `linux-x64` segment is not mistaken for 32-bit. - */ -function namesForeignTarget(segment, hostPlatform, hostArch) { - const lower = segment.toLowerCase(); - // A platform marker is only foreign when it is not the host's. `darwin` and - // `linux` both appear in the paths the plugin is *supposed* to accept on - // their own platform. - for (const [marker, platform] of Object.entries(PLATFORM_MARKERS)) { - if (!lower.includes(marker)) continue; - if (platform !== hostPlatform) return true; - // The host platform matched; a foreign libc in the same segment still - // disqualifies it. - if (namesForeignLibc(lower)) return true; - } - const tokens = lower - .replace(/x86[_-]?64|amd64/gu, 'x64') - .replace(/aarch64/gu, 'arm64') - .split(/[^a-z0-9]+/u) - .filter(Boolean); - // `ios` as a whole token: it would otherwise match unrelated names such as - // `studios`. - if (tokens.includes('ios') && hostPlatform !== 'ios') return true; - const hostToken = hostArch === 'arm64' ? 'arm64' : 'x64'; - const archTokens = tokens.filter(token => - ['x64', 'arm64', 'arm', 'ia32', 'x86'].includes(token), - ); - // A segment naming several architectures is a multi-arch artifact (a - // `darwin-x64+arm64` prebuild directory, or one universal Mach-O file), so it - // is foreign only when *none* of the architectures it names is the host's. - // A segment naming exactly one is foreign when that one is not the host's. - // The byte-level header check still has the final say for a thin binary. - return archTokens.length > 0 && !archTokens.includes(hostToken); -} - -function isElfForArch(header, arch) { - if (!header.subarray(0, 4).equals(ELF_MAGIC)) return null; - const machine = ELF_MACHINE[arch]; - if (machine === undefined) return false; - return header.readUInt16LE(18) === machine; -} - -// PE/COFF. A Windows binary starts with `MZ`; the 4-byte little-endian value at -// offset 0x3C is the file offset of the `PE\0\0` signature, and the 2-byte -// machine field follows it. Only the first 64 bytes of the file are read, so -// the signature is checked to be within that window before reading the machine. -const DOS_MAGIC = Buffer.from([0x4d, 0x5a]); // "MZ" -const PE_SIGNATURE = Buffer.from([0x50, 0x45, 0x00, 0x00]); // "PE\0\0" - -const PE_MACHINE = { - x64: 0x8664, - arm64: 0xaa64, - ia32: 0x014c, -}; - -/** - * Whether a PE file is built for `arch`. Returns null when the bytes are not a - * PE file at all, and true for an unrecognized machine value (an unusual-but - * valid binary is never rejected, matching the Mach-O helper). - * - * The `PE\0\0` signature lives at the offset named by the 4-byte field at 0x3C, - * which a normal linker places right after the 64-byte DOS header but is not - * required to; `header` therefore only has to cover the offset named, and a - * caller reading a short prefix reports "not a PE" rather than "wrong arch". - */ -function isPeForArch(header, arch) { - if (header.length < 2 || !header.subarray(0, 2).equals(DOS_MAGIC)) { - return null; - } - if (header.length < 0x40) return false; - const peOffset = header.readUInt32LE(0x3c); - if (peOffset + 6 > header.length) return false; - if (!header.subarray(peOffset, peOffset + 4).equals(PE_SIGNATURE)) { - return false; - } - const machine = header.readUInt16LE(peOffset + 4); - const expected = PE_MACHINE[arch]; - if (expected === undefined) return true; - if (machine === expected) return true; - // 0x0 is IMAGE_FILE_MACHINE_UNKNOWN, which some linkers write; treat it as - // acceptable rather than rejecting a working binary. - return machine === 0x0000; -} - -/** - * Whether a Mach-O file contains a slice for `arch`. A thin file has one - * cputype at offset 4; a universal file has a table of them after the 8-byte - * header, each `fat_arch` starting with its own cputype. Anything we cannot - * parse is accepted, so an unusual-but-valid binary is never rejected. - */ -function machoHasArch(header, arch) { - const expected = CPU_TYPES[arch]; - if (expected === undefined) return false; - const magic = header.subarray(0, 4); - const isFat = magic.equals(MACHO_FAT_BE) || magic.equals(MACHO_FAT_LE); - const read = - magic.equals(MACHO_FAT_LE) || - magic.equals(MACHO_THIN_LE) || - magic.equals(MACHO_THIN_LE_32) - ? offset => header.readUInt32LE(offset) - : offset => header.readUInt32BE(offset); - if (isFat) { - if (header.length < 8) return true; - const count = read(4); - if (count === 0 || count > 64) return true; - const fatEntrySize = 20; - if (header.length < 8 + count * fatEntrySize) return true; - for (let index = 0; index < count; index += 1) { - if (read(8 + index * fatEntrySize) === expected) return true; - } - return false; - } - if (header.length < 8) return true; - return read(4) === expected; -} - -/** - * Whether `filePath` is a shared library for the host. A file built for another - * platform or CPU is treated as missing, so a package's per-platform binary - * list does not make the bundle try to load one that cannot work. - */ -function isHostPrebuiltNodeAddon(filePath, hostPlatform, hostArch) { - const segments = filePath.split(path.sep); - if ( - segments.some(segment => - namesForeignTarget(segment, hostPlatform, hostArch), - ) - ) { - return false; - } - let handle; - try { - handle = fs.openSync(filePath, 'r'); - // One window covers every header this function reads: ELF's and Mach-O's - // first bytes, a universal Mach-O table, and a PE image whose `PE\0\0` - // signature sits past the 64-byte DOS header plus a stub (MSVC places it - // around 0xE8). Reading past the end of a short file is not an error. - const header = Buffer.alloc(1024); - const read = fs.readSync(handle, header, 0, header.length, 0); - if (read < 20) return false; - const headerBytes = header.subarray(0, read); - if (hostPlatform === 'linux') { - return isElfForArch(headerBytes, hostArch) === true; - } - if (hostPlatform === 'darwin') { - const magic = headerBytes.subarray(0, 4); - const known = - magic.equals(MACHO_THIN_LE) || - magic.equals(MACHO_THIN_LE_32) || - magic.equals(MACHO_THIN_BE) || - magic.equals(MACHO_THIN_BE_32) || - magic.equals(MACHO_FAT_BE) || - magic.equals(MACHO_FAT_LE); - if (!known) return false; - return machoHasArch(headerBytes, hostArch); - } - if (hostPlatform === 'win32') { - // `true` only, like the two branches above: `isPeForArch` returns null for - // "not a PE file at all", and `null !== false` is true, so accepting - // anything but an explicit rejection let a Linux `.node` or a macOS - // Mach-O through on a Windows host. - return isPeForArch(headerBytes, hostArch) === true; - } - // Platforms with no header check accept every file, which is the same as no - // guard. - return true; - } catch { - return false; - } finally { - if (handle !== undefined) fs.closeSync(handle); - } -} - -/** - * The stable, relative key for an addon (section 3.3 of the plan): - * - * - if the real path has a `node_modules` segment, everything from the first - * `node_modules/` onward, with `/` separators; - * - otherwise `local//`. - * - * The key is how a packaged app finds the addon after `node_modules` is gone, - * so it must be portable: always `/`, never `..`, never a leading slash. - */ -function addonKey(absolutePath) { - const normalized = absolutePath.split(path.sep).join('/'); - const marker = '/node_modules/'; - const index = normalized.indexOf(marker); - const key = - index === -1 - ? `local/${crypto - .createHash('sha1') - .update(normalized) - .digest('hex') - .slice(0, 8)}/${path.posix.basename(normalized)}` - : normalized.slice(index + 1); - if ( - key.startsWith('/') || - key.includes('\\') || - key.split('/').includes('..') - ) { - throw new Error(`invalid node addon key '${key}' for ${absolutePath}`); - } - return key; -} - -/** Files Metro would resolve before an extensionless `.node` file. */ -const RESOLVABLE_EXTENSIONS = ['.js', '.cjs', '.mjs', '.json', '.ts', '.tsx']; - -/** - * Resolves a `require(`${...}.node`)` whose interpolated - * segment is a platform/arch tag (R7). Packages such as `farmhash` build the - * file name from `process.platform` and `process.arch` in a template literal, - * which no run-time platform data can turn into a path here. - * - * The static prefix locates the directory; every `.node` file matching the - * static suffix is a candidate, and the one usable on the host wins. That is - * safe precisely because the tag is the only thing that varies: the candidate - * set is exactly the set of platform builds the package ships. - */ -function resolveInterpolatedAddon(prefix, suffix, options) { - const { hostPlatform, hostArch } = options; - const directory = path.dirname(prefix); - const basePrefix = path.basename(prefix); - let entries; - try { - entries = fs.readdirSync(directory); - } catch { - return null; - } - const candidates = entries - .filter( - entry => - entry.startsWith(basePrefix) && - entry.endsWith(suffix) && - entry.length > basePrefix.length + suffix.length, - ) - .sort(); - for (const entry of candidates) { - // The path segment named by the interpolated part must not name a foreign - // target, and the bytes must be the host's. - const middle = entry.slice(basePrefix.length, entry.length - suffix.length); - if (namesForeignTarget(middle, hostPlatform, hostArch)) continue; - const candidate = path.join(directory, entry); - if (isHostPrebuiltNodeAddon(candidate, hostPlatform, hostArch)) { - return candidate; - } - } - return null; -} - -/** - * Classifies a specifier written in `fromDirectory`: - * - * { kind: 'addon', path } a host `.node` file to load; - * { kind: 'missing' } an explicit `.node` specifier with no usable file - * (`missingModuleExpression` must stand in for it); - * null not an addon reference at all, so the require or - * import is left exactly as written. - * - * The `missing` case exists because packages list a binary per platform and - * wrap each in `try`/`catch`: the ones that are not installed must fail at run - * time, not at bundle time. - */ -function resolveAddon(specifier, fromDirectory, options) { - const { hostPlatform, hostArch } = options; - const usable = filePath => - isHostPrebuiltNodeAddon(filePath, hostPlatform, hostArch) ? filePath : null; - - const tryFile = candidate => { - if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) { - const resolved = usable(candidate); - return resolved === null - ? { kind: 'missing' } - : { kind: 'addon', path: resolved }; - } - return { kind: 'missing' }; - }; - - const isRelative = specifier.startsWith('./') || specifier.startsWith('../'); - const isAbsolute = path.isAbsolute(specifier); - - // R1: an explicit `.node` specifier. - if (specifier.endsWith('.node')) { - if (isRelative || isAbsolute) { - return tryFile( - isAbsolute ? specifier : path.resolve(fromDirectory, specifier), - ); - } - // A bare specifier, either `pkg/x.node` or an addon a package lists in its - // own manifest. `require.resolve` follows the package's own entry points. - try { - const resolved = require.resolve(specifier, { paths: [fromDirectory] }); - if (fs.statSync(resolved).isFile()) { - const addonPath = usable(resolved); - return addonPath === null - ? { kind: 'missing' } - : { kind: 'addon', path: addonPath }; - } - } catch {} - return { kind: 'missing' }; - } - - // R2: a relative specifier with no extension, where `.node` exists and - // nothing Metro would resolve first does. - if (isRelative || isAbsolute) { - const candidate = path.resolve(fromDirectory, specifier); - if ( - RESOLVABLE_EXTENSIONS.some(extension => - fs.existsSync(candidate + extension), - ) - ) { - return null; - } - // A package.json or index file is a real module too. - if (fs.existsSync(path.join(candidate, 'package.json'))) return null; - for (const index of ['index.js', 'index.ts', 'index.tsx', 'index.json']) { - if (fs.existsSync(path.join(candidate, index))) return null; - } - if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) { - return null; - } - if (!fs.existsSync(`${candidate}.node`)) return null; - return tryFile(`${candidate}.node`); - } - - // R3: a bare package whose installed `main` (or `exports` entry) is an addon. - try { - const entry = require.resolve(specifier, { paths: [fromDirectory] }); - if (!entry.endsWith('.node')) return null; - const addonPath = usable(entry); - return addonPath === null - ? { kind: 'missing' } - : { kind: 'addon', path: addonPath }; - } catch { - // Not installed here. A package a platform-specific branch would have - // loaded is not our business; leave the require to Metro, which reports it - // the same way it would for any missing module. - return null; - } -} - -// --- R4–R6: packages that pick their binary at run time --------------------- -// -// Most packages do not write `require('./x.node')` themselves. They use a small -// loader that chooses the binary with `fs`, `path` and `process.platform` — none -// of which exist in Hermes. On desktop the build machine *is* the target, so the -// plugin can run that selection at build time instead, using the package's own -// data. - -/** `node-gyp-build`'s own prebuild layout, plus the directories it probes. */ -const NODE_GYP_BUILD_DIRECTORIES = [ - '.', - 'build', - 'build/Debug', - 'build/Release', - 'build/RelWithDebInfo', - 'build/MinSizeRel', - 'out', -]; - -/** - * `prebuilds/-+` directory tags, as `node-gyp-build` - * parses them. The arch list may be a `+`-joined union, which is how a package - * ships one universal binary for two architectures. - */ -function parsePrebuildTuple(name) { - const parts = name.split('-'); - if (parts.length !== 2) return null; - const architectures = parts[1].split('+'); - if ( - !parts[0] || - architectures.length === 0 || - !architectures.every(Boolean) - ) { - return null; - } - return { name, platform: parts[0], architectures }; -} - -/** - * The tags `node-gyp-build` reads out of a file name (`bcrypt.glibc.node`, - * `node.napi.node`, `node.abi115.node`, `node.napi.armv8.node`). - */ -function parsePrebuildTags(file) { - const parts = file.split('.'); - const extension = parts.pop(); - if (extension !== 'node') return null; - const tags = { file, specificity: 0 }; - for (const tag of parts) { - if (tag === 'node' || tag === 'electron' || tag === 'node-webkit') { - tags.runtime = tag; - } else if (tag === 'napi') { - tags.napi = true; - } else if (tag.startsWith('abi')) { - tags.abi = tag.slice(3); - } else if (tag.startsWith('uv')) { - tags.uv = tag.slice(2); - } else if (tag.startsWith('armv')) { - tags.armv = tag.slice(4); - } else if (tag === 'glibc' || tag === 'musl') { - tags.libc = tag; - } else { - // An unknown tag carries no meaning to node-gyp-build. - continue; - } - tags.specificity += 1; - } - return tags; -} - -/** - * Whether a parsed file matches this host. `node` + `napi` is - * runtime-agnostic, so a `node.napi.node` loads in any N-API host; a plain - * `abi` tag is tied to the Node ABI and does not match us. - */ -function prebuildTagsMatchHost(tags, hostPlatform, hostArch) { - if (tags === null) return false; - // We are an N-API host with no Node ABI, so only `napi` (or no runtime/ABI - // tag at all) qualifies. A `uv` tag means the addon needs a libuv - // version, which this runtime does not provide. - if (tags.uv) return false; - if (tags.abi && !tags.napi) return false; - if (tags.armv) { - const armv = hostArch === 'arm64' ? '8' : null; - if (armv === null || tags.armv !== armv) return false; - } - if (tags.libc) { - const hostLibc = hostPlatform === 'linux' ? linuxLibc() : null; - if (hostLibc === null || tags.libc !== hostLibc) return false; - } - if (tags.runtime && tags.runtime !== 'node') return false; - return true; -} - -/** - * Which libc this *build machine* uses, for the `glibc` / `musl` file tags. - * Matches `node-gyp-build`'s own check (it looks for Alpine): the bundler runs - * on the machine the app is built for, which is the whole premise of resolving - * this at build time. - */ -function linuxLibc() { - return fs.existsSync('/etc/alpine-release') ? 'musl' : 'glibc'; -} - -/** - * Resolves `require('node-gyp-build')()` at build time (R4). - * - * The plan asks for `node-gyp-build`'s own resolver rather than a copy of it, - * and that is what runs first: its `path()` export is called with - * `process.platform` / `process.arch` temporarily set to the host the bundle is - * being built for. Both properties are configurable, so this always restores - * them. - * - * It is only called when the requested host is the build host: `path()` also - * reads the ABI and libuv versions of the *running* Node, which have no meaning - * for a foreign target. For a cross-build, or when the package is not - * installed, the resolver below reproduces the same algorithm against the - * requested host. It is also the fallback when `path()` throws. - */ -function resolveNodeGypBuild(directory, options) { - const { hostPlatform, hostArch } = options; - if (hostPlatform === process.platform && hostArch === process.arch) { - const viaNodeGypBuild = resolveWithNodeGypBuild(directory); - if (viaNodeGypBuild !== null) return viaNodeGypBuild; - } - return resolvePrebuilds(directory, options); -} - -/** - * Runs the installed `node-gyp-build`'s `path()` for `directory`, with the - * process's platform and architecture forced to the host. Returns null when the - * package is not installed, when its resolver throws (its error message is the - * only report it gives), or when it finds nothing usable. - */ -function resolveWithNodeGypBuild(directory) { - const platformDescriptor = Object.getOwnPropertyDescriptor( - process, - 'platform', - ); - const archDescriptor = Object.getOwnPropertyDescriptor(process, 'arch'); - let resolved = null; - try { - Object.defineProperty(process, 'platform', { - value: process.platform, - configurable: true, - }); - Object.defineProperty(process, 'arch', { - value: process.arch, - configurable: true, - }); - const nodeGypBuild = require( - require.resolve('node-gyp-build', { paths: [directory, __dirname] }), - ); - const candidate = nodeGypBuild.path(directory); - if ( - typeof candidate === 'string' && - fs.existsSync(candidate) && - isHostPrebuiltNodeAddon(candidate, process.platform, process.arch) && - // `node-gyp-build`'s own resolver consults the *running* Node's - // `process.versions`, and under recent Node versions it can settle on an - // `electron.napi.node` build (it treats the absent - // `process.versions.electron` as a match). An Electron ABI is not this - // runtime's, so a file tagged with a runtime other than `node` is - // rejected here and the ported resolver below picks the right one. - !prefersForeignRuntime(candidate) - ) { - resolved = candidate; - } - } catch { - resolved = null; - } finally { - // Restore whatever the properties were, descriptor and all. - if (platformDescriptor) { - Object.defineProperty(process, 'platform', platformDescriptor); - } else { - delete process.platform; - } - if (archDescriptor) { - Object.defineProperty(process, 'arch', archDescriptor); - } else { - delete process.arch; - } - } - return resolved; -} - -/** - * Whether a file name is tagged for a runtime this platform is not. Our runtime - * is Hermes with Node-API; an Electron or NW.js build links a different ABI. - */ -function prefersForeignRuntime(file) { - const tags = parsePrebuildTags(path.basename(file)); - return tags !== null && tags.runtime !== undefined && tags.runtime !== 'node'; -} - -/** - * A faithful re-implementation of `node-gyp-build`'s selection, for a host that - * is not the running process (or when its resolver cannot be reached). - * - * The order is its own: an in-tree `build/Release` or `build/Debug` binary - * first, then a `prebuilds/` directory whose `-` tuple - * matches the host (single-arch preferred over a `+`-joined union), then the - * most specific matching file tag. - */ -function resolvePrebuilds(directory, options) { - const { hostPlatform, hostArch } = options; - // node-gyp-build checks these before the prebuilds directory. - for (const subdirectory of ['build/Release', 'build/Debug']) { - const base = path.join(directory, subdirectory); - let entries; - try { - entries = fs.readdirSync(base, { withFileTypes: true }); - } catch { - continue; - } - for (const entry of entries) { - if (!entry.isFile() || !entry.name.endsWith('.node')) continue; - const filePath = path.join(base, entry.name); - if (isHostPrebuiltNodeAddon(filePath, hostPlatform, hostArch)) { - return filePath; - } - } - } - - const prebuildsRoot = path.join(directory, 'prebuilds'); - let tuples = []; - try { - tuples = fs - .readdirSync(prebuildsRoot) - .map(parsePrebuildTuple) - .filter(Boolean) - .filter( - tuple => - tuple.platform === hostPlatform && - tuple.architectures.includes(hostArch), - ) - // Fewer architectures means more specific; a `darwin-arm64` directory - // beats a `darwin-x64+arm64` one. - .sort((a, b) => a.architectures.length - b.architectures.length); - } catch { - tuples = []; - } - for (const tuple of tuples) { - const prebuilds = path.join(prebuildsRoot, tuple.name); - let parsed = []; - try { - parsed = fs.readdirSync(prebuilds).map(parsePrebuildTags); - } catch { - continue; - } - const winner = parsed - .filter(tags => prebuildTagsMatchHost(tags, hostPlatform, hostArch)) - .sort((a, b) => { - // An ABI-specific build is preferred over a plain napi one; with no - // ABI of our own, that only ever picks `node.napi` last. - if (Boolean(a.abi) !== Boolean(b.abi)) return a.abi ? -1 : 1; - return b.specificity - a.specificity; - })[0]; - if (!winner) continue; - const candidate = path.join(prebuilds, winner.file); - if (isHostPrebuiltNodeAddon(candidate, hostPlatform, hostArch)) { - return candidate; - } - } - - // The in-tree builds and the plain `build/Release` layout. - for (const subdirectory of NODE_GYP_BUILD_DIRECTORIES) { - const base = path.join(directory, subdirectory); - let entries; - try { - entries = fs.readdirSync(base, { withFileTypes: true }); - } catch { - continue; - } - for (const entry of entries) { - if (!entry.isFile() || !entry.name.endsWith('.node')) continue; - const filePath = path.join(base, entry.name); - if (isHostPrebuiltNodeAddon(filePath, hostPlatform, hostArch)) { - return filePath; - } - } - } - return null; -} - -/** - * The directories `bindings` searches, in its own order (R5). Read from its - * source: it walks up from the calling module's directory looking for a - * `package.json`, then tries these relative to each ancestor. - */ -const BINDINGS_DIRECTORIES = [ - 'build/Release', - 'build/Debug', - 'build/RelWithDebInfo', - 'build/MinSizeRel', - 'out/Release', - 'out/Debug', - 'Release', - 'Debug', - 'Release/node-v', - 'Debug/node-v', - 'build', - 'out', - 'compiled', - 'addon-build/release/install-root', - 'addon-build/debug/install-root', - 'addon-build/default/install-root', -]; - -/** - * Resolves `require('bindings')('')` at build time (R5). `bindings` - * searches upward from the package root for `package.json` and then tries each - * candidate directory; this walks the same ancestors of `fromDirectory`. - */ -function resolveBindings(name, fromDirectory, options) { - const { hostPlatform, hostArch } = options; - let directory = fromDirectory; - for (;;) { - const candidates = [directory]; - const parent = path.dirname(directory); - if (parent !== directory) candidates.push(parent); - for (const base of candidates) { - for (const subdirectory of BINDINGS_DIRECTORIES) { - const target = path.join(base, subdirectory, name); - for (const candidate of [target, `${target}.node`]) { - try { - if (!fs.statSync(candidate).isFile()) continue; - } catch { - continue; - } - if (isHostPrebuiltNodeAddon(candidate, hostPlatform, hostArch)) { - return candidate; - } - } - } - } - // `bindings` stops at the directory holding `package.json`, so a nested - // call inside a package resolves against that package only. - if (fs.existsSync(path.join(directory, 'package.json'))) break; - if (parent === directory) break; - directory = parent; - } - return null; -} - -/** - * `process.platform` / `process.arch` as a napi-rs loader spells them in the - * file name (`linux-x64-gnu`, `win32-arm64-msvc`). The host's own triple, from - * most to least preferred: glibc beats musl on Linux, msvc beats gnu on - * Windows. - */ -function napiRsTriples(hostPlatform, hostArch) { - const platform = hostPlatform; - if (platform === 'linux') { - return [`linux-${hostArch}-gnu`, `linux-${hostArch}-musl`]; - } - if (platform === 'win32') { - return [`win32-${hostArch}-msvc`, `win32-${hostArch}-gnu`]; - } - if (platform === 'darwin') { - return [`darwin-${hostArch}`, 'darwin-universal']; - } - return [`${platform}-${hostArch}`]; -} - -/** - * Detects a napi-rs generated loader and returns the binary it would pick (R6). - * - * The generated file is one big `if (process.platform === …)` chain whose - * branches `require` either a local `..node` or a per-platform - * package `-`. Detection is a heuristic, per the plan: a module - * with several `.node` requires for *different* platforms is one of these. When - * a file matches but no host binary exists it is left untouched. - */ -function resolveNapiRsLoader(source, filename, options) { - const { hostPlatform, hostArch } = options; - const triples = napiRsTriples(hostPlatform, hostArch); - // Every triple named in the file, so a non-loader that happens to require a - // couple of binaries is not misread. - const mentioned = new Set(); - const triplePattern = - /\b(?:darwin|linux|win32|android|freebsd|openharmony)-(?:x64|arm64|arm|ia32|loong64|riscv64|ppc64|s390x)(?:-(?:gnu|musl|msvc|eabi|gnueabihf|musleabihf))?\b/gu; - for (const match of source.matchAll(triplePattern)) { - mentioned.add(match[0]); - } - // A napi-rs loader names at least three platforms; a hand-written file that - // happens to name two is left alone. - const platforms = new Set([...mentioned].map(triple => triple.split('-')[0])); - if (platforms.size < 3) return null; - - const directory = path.dirname(filename); - // The local copy first, exactly as the loader tries it. - for (const triple of triples) { - const local = path.join(directory, `${triple}.node`); - if (fs.existsSync(local)) { - if (isHostPrebuiltNodeAddon(local, hostPlatform, hostArch)) return local; - } - // `..node` for any prefix the file uses. - let entries = []; - try { - entries = fs.readdirSync(directory); - } catch { - entries = []; - } - for (const entry of entries) { - if (!entry.endsWith(`.${triple}.node`)) continue; - const filePath = path.join(directory, entry); - if (isHostPrebuiltNodeAddon(filePath, hostPlatform, hostArch)) { - return filePath; - } - } - } - - // Then the per-platform packages, whose own entry is the `.node` file itself. - const scoped = /require\((['"])(@[^'"]+|[^'"./][^'"]*)\1\)/gu; - const packageNames = new Set(); - for (const match of source.matchAll(scoped)) { - packageNames.add(match[2]); - } - for (const triple of triples) { - for (const packageName of packageNames) { - if (!packageName.endsWith(triple)) continue; - try { - const entry = require.resolve(packageName, { paths: [directory] }); - if ( - entry.endsWith('.node') && - isHostPrebuiltNodeAddon(entry, hostPlatform, hostArch) - ) { - return entry; - } - } catch {} - } - } - return null; -} - -module.exports = function babelPluginNodeAddons(api, options = {}) { - const t = api.types; - const hostPlatform = options.hostPlatform ?? process.platform; - const hostArch = options.hostArch ?? process.arch; - const embedPaths = options.embedPaths !== false; - const pluginOptions = { hostPlatform, hostArch }; - // Resolving a bare specifier costs a `require.resolve`, and the visitor sees - // every literal `require` in the bundle, so the answer is memoised per file - // directory and specifier. - const resolutionCache = new Map(); - // One warning per (file, reason), so a loader in a widely-imported module - // does not fill the bundler's output. - const warned = new Set(); - const warnOnce = (state, message) => { - const key = `${state.file.opts.filename}\u0000${message}`; - if (warned.has(key)) return; - warned.add(key); - state.file.metadata.rnGpuiNodeAddonWarnings ??= []; - state.file.metadata.rnGpuiNodeAddonWarnings.push(message); - // `console` is all a Babel plugin has; Metro shows it with the file name. - console.warn(`[react-native-gpui/babel-plugin-node-addons] ${message}`); - }; - // Read once, at config time: `api.caller` caches the answer and refuses a - // callback once traversal has started. - const isGpuiPlatform = api.caller(caller => caller?.platform) === 'desktop'; - - const missingModuleExpression = specifier => { - const error = t.callExpression(t.identifier('Error'), [ - t.stringLiteral(`Cannot find module '${specifier}'`), - ]); - // (() => { const error = new Error(...); error.code = 'MODULE_NOT_FOUND'; - // throw error; })() - return t.callExpression( - t.arrowFunctionExpression( - [], - t.blockStatement([ - t.variableDeclaration('const', [ - t.variableDeclarator(t.identifier('error'), error), - ]), - t.expressionStatement( - t.assignmentExpression( - '=', - t.memberExpression(t.identifier('error'), t.identifier('code')), - t.stringLiteral('MODULE_NOT_FOUND'), - ), - ), - t.throwStatement(t.identifier('error')), - ]), - ), - [], - ); - }; - - const requireNodeLibraryCall = resolvedPath => { - const key = addonKey(fs.realpathSync(resolvedPath)); - const args = [t.stringLiteral(key)]; - if (embedPaths) args.push(t.stringLiteral(resolvedPath)); - return t.callExpression(t.identifier('_requireNodeLibrary'), args); - }; - - /** - * The expression an addon reference becomes. `null` means the specifier is - * not an addon reference after all and must be left alone. - */ - const addonExpression = (specifier, fromDirectory) => { - const cacheKey = `${fromDirectory}\u0000${specifier}`; - let resolution = resolutionCache.get(cacheKey); - if (resolution === undefined) { - resolution = resolveAddon(specifier, fromDirectory, pluginOptions); - resolutionCache.set(cacheKey, resolution); - } - if (resolution === null) return null; - if (resolution.kind === 'missing') - return missingModuleExpression(specifier); - return requireNodeLibraryCall(resolution.path); - }; - - /** The directory argument of a `node-gyp-build`-style call, if static. */ - const staticDirectoryArgument = (argument, fromDirectory) => { - if (argument === undefined) return null; - // `__dirname` - if (argument.type === 'Identifier' && argument.name === '__dirname') { - return fromDirectory; - } - // `path.join(__dirname, 'literal', ...)` or `path.resolve(...)`, either - // reached bare or through the module: `require('path').join(...)`. - if (argument.type === 'CallExpression') { - const callee = argument.callee; - if ( - callee.type !== 'MemberExpression' || - callee.property.type !== 'Identifier' || - (callee.property.name !== 'join' && callee.property.name !== 'resolve') - ) { - return null; - } - const isPathModule = object => - (object.type === 'Identifier' && object.name === 'path') || - (object.type === 'CallExpression' && - object.callee.type === 'Identifier' && - object.callee.name === 'require' && - object.arguments.length === 1 && - object.arguments[0].type === 'StringLiteral' && - object.arguments[0].value === 'path'); - if (!isPathModule(callee.object)) return null; - const parts = []; - let base = null; - for (const part of argument.arguments) { - if (part.type === 'StringLiteral') { - parts.push(part.value); - } else if (part.type === 'Identifier' && part.name === '__dirname') { - base = fromDirectory; - } else { - return null; - } - } - if (base === null) return null; - return path.resolve(base, ...parts); - } - return null; - }; - - /** The string argument of a `bindings('')` call, if static. */ - const staticBindingsName = argument => { - if (argument === undefined) return null; - if (argument.type === 'StringLiteral') return argument.value; - // `{ bindings: '' }` - if (argument.type === 'ObjectExpression') { - for (const property of argument.properties) { - if ( - property.type === 'ObjectProperty' && - !property.computed && - property.key.type === 'Identifier' && - property.key.name === 'bindings' && - property.value.type === 'StringLiteral' - ) { - return property.value.value; - } - } - } - return null; - }; - - /** - * R4/R5: recognises `require('node-gyp-build')()` and - * `require('bindings')()` and returns the expression that replaces the - * whole call, or `null` when resolution failed (a throwing expression is - * emitted and one warning printed), or `undefined` when the node is not one - * of these calls at all. - */ - const loaderCallExpression = (node, fromDirectory, state) => { - // The outer call is `require('x')(...)`: its callee is the inner `require`. - if (node.callee.type !== 'CallExpression') return undefined; - const inner = node.callee; - if ( - inner.callee.type !== 'Identifier' || - inner.callee.name !== 'require' || - inner.arguments.length !== 1 || - inner.arguments[0].type !== 'StringLiteral' - ) { - return undefined; - } - const loaderName = inner.arguments[0].value; - if (loaderName === 'node-gyp-build') { - const directory = staticDirectoryArgument( - node.arguments[0], - fromDirectory, - ); - if (directory === null) return undefined; - const resolved = resolveNodeGypBuild(directory, pluginOptions); - if (resolved !== null) return requireNodeLibraryCall(resolved); - warnOnce( - state, - `node-gyp-build: no ${pluginOptions.hostPlatform}-${pluginOptions.hostArch} binary under ${directory}`, - ); - return missingModuleExpression('node-gyp-build'); - } - if (loaderName === 'bindings') { - const name = staticBindingsName(node.arguments[0]); - if (name === null) return undefined; - const resolved = resolveBindings(name, fromDirectory, pluginOptions); - if (resolved !== null) return requireNodeLibraryCall(resolved); - warnOnce( - state, - `bindings: no ${pluginOptions.hostPlatform}-${pluginOptions.hostArch} binary named '${name}' from ${fromDirectory}`, - ); - return missingModuleExpression('bindings'); - } - return undefined; - }; - - return { - name: 'react-native-gpui-node-addons', - visitor: { - CallExpression(nodePath, state) { - if (!isGpuiPlatform) return; - const { node } = nodePath; - const filename = state.file.opts.filename; - if (typeof filename !== 'string' || filename === 'unknown') return; - const fromDirectory = path.dirname(filename); - - // R4/R5: the whole loader call is replaced, so it is matched before the - // `require` inside it — `require('node-gyp-build')(__dirname)` would - // otherwise be visited on the way down and left as it is anyway, since - // neither specifier ends in `.node`. - const loader = loaderCallExpression(node, fromDirectory, state); - if (loader !== undefined) { - if (loader === null) return; - nodePath.replaceWith(loader); - return; - } - - if ( - node.callee.type !== 'Identifier' || - node.callee.name !== 'require' || - node.arguments.length !== 1 - ) { - return; - } - - // R7: `require(`./build/thing-${platform}.node`)`, where the - // interpolated segments are platform/arch tags. The static prefix and - // suffix locate the candidates; the tags themselves cannot be - // evaluated. Any number of interpolations is allowed as long as the - // suffix still ends in `.node` — the glob between prefix and suffix - // absorbs them all. - if (node.arguments[0].type === 'TemplateLiteral') { - if (nodePath.parentPath.isCallExpression({ callee: node })) return; - const { quasis } = node.arguments[0]; - if (node.arguments[0].expressions.length === 0) return; - const prefix = quasis[0].value.cooked ?? quasis[0].value.raw; - const suffix = - quasis[quasis.length - 1].value.cooked ?? - quasis[quasis.length - 1].value.raw; - if (!suffix.endsWith('.node') || !prefix.startsWith('.')) return; - const resolved = resolveInterpolatedAddon( - path.resolve(fromDirectory, prefix), - suffix, - pluginOptions, - ); - if (resolved === null) { - warnOnce( - state, - `no ${pluginOptions.hostPlatform}-${pluginOptions.hostArch} file matches ${prefix}…${suffix}`, - ); - nodePath.replaceWith( - missingModuleExpression(`${prefix}…${suffix}`), - ); - return; - } - nodePath.replaceWith(requireNodeLibraryCall(resolved)); - return; - } - - if (node.arguments[0].type !== 'StringLiteral') return; - const specifier = node.arguments[0].value; - // A dynamic `import()` is a different node type entirely, and the - // `require` a bundler synthesises from it is not what this rewrites. - if (nodePath.parentPath.isCallExpression({ callee: node })) return; - const expression = addonExpression(specifier, path.dirname(filename)); - // `addonExpression` returns null when the specifier turned out not to - // name an addon, so every other require is left for Metro. - if (expression === null) return; - nodePath.replaceWith(expression); - }, - - // R6: a napi-rs generated loader is replaced as a whole module, since - // every branch of its `process.platform` chain is dead here. - Program(nodePath, state) { - if (!isGpuiPlatform) return; - const filename = state.file.opts.filename; - if (typeof filename !== 'string' || filename === 'unknown') return; - // Babel hands the original source here even when the transform was - // given a string rather than a file, which is how the unit tests drive - // it; the on-disk file name is still what relative requires resolve - // against. - const source = state.file.code; - if (typeof source !== 'string') return; - // Cheap gate before the full check: a napi-rs loader always branches - // on the platform. - if (!/(?:process\.platform|process\.config)/u.test(source)) return; - const resolved = resolveNapiRsLoader(source, filename, pluginOptions); - if (resolved === null) return; - for (const statement of nodePath.get('body')) { - statement.remove(); - } - nodePath.pushContainer( - 'body', - t.expressionStatement( - t.assignmentExpression( - '=', - t.memberExpression( - t.identifier('module'), - t.identifier('exports'), - ), - requireNodeLibraryCall(resolved), - ), - ), - ); - }, - - ImportDeclaration(nodePath, state) { - if (!isGpuiPlatform) return; - const { node } = nodePath; - if ( - typeof node.source.value !== 'string' || - !/\.node$/u.test(node.source.value) - ) { - return; - } - const filename = state.file.opts.filename; - if (typeof filename !== 'string' || filename === 'unknown') return; - const specifier = node.source.value; - const expression = addonExpression(specifier, path.dirname(filename)); - if (expression === null) return; - - // Every form binds the same exports object: a default import is the - // object itself, a namespace import is the object itself, and named - // imports are destructured from it. - const statements = []; - const shared = t.identifier('_nodeAddonExports'); - const named = node.specifiers.filter( - item => item.type === 'ImportSpecifier' && item.imported, - ); - const bound = node.specifiers.filter( - item => - item.type === 'ImportDefaultSpecifier' || - item.type === 'ImportNamespaceSpecifier', - ); - const needsShared = bound.length > 0 || named.length > 0; - if (needsShared) { - statements.push( - t.variableDeclaration('const', [ - t.variableDeclarator(shared, expression), - ]), - ); - } - for (const item of bound) { - statements.push( - t.variableDeclaration('const', [ - t.variableDeclarator(item.local, shared), - ]), - ); - } - if (named.length > 0) { - statements.push( - t.variableDeclaration('const', [ - t.variableDeclarator( - t.objectPattern( - named.map(item => - t.objectProperty(item.imported, item.local), - ), - ), - shared, - ), - ]), - ); - } - if (statements.length === 0) { - // A bare `import 'x.node'` still has to load the addon. - statements.push(t.expressionStatement(expression)); - } - nodePath.replaceWithMultiple(statements); - }, - }, - }; -}; - -module.exports.addonKey = addonKey; -module.exports.isHostPrebuiltNodeAddon = isHostPrebuiltNodeAddon; -module.exports.resolveAddon = resolveAddon; diff --git a/vendor/react-native-gpui/packages/core/babel-plugin-node-addons.test.js b/vendor/react-native-gpui/packages/core/babel-plugin-node-addons.test.js deleted file mode 100644 index 098f0c3d8e..0000000000 --- a/vendor/react-native-gpui/packages/core/babel-plugin-node-addons.test.js +++ /dev/null @@ -1,1091 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import vm from 'node:vm'; -import { transformSync } from '@babel/core'; -import { afterAll, expect, test } from 'vitest'; -import plugin, { - addonKey, - isHostPrebuiltNodeAddon, - resolveAddon, -} from './babel-plugin-node-addons.js'; - -const packageRoot = path.dirname(fileURLToPath(import.meta.url)); -const temporaryRoots = []; - -afterAll(() => { - for (const root of temporaryRoots) { - fs.rmSync(root, { recursive: true, force: true }); - } -}); - -/** A scratch directory whose real path is stable for the test's duration. */ -function scratch() { - const root = fs.mkdtempSync(path.join(packageRoot, '.node-addons-test-')); - temporaryRoots.push(root); - // `mkdtempSync` under /var on macOS is a symlink farm; resolve it once so - // expectations about the key match what the plugin sees. - return fs.realpathSync(root); -} - -function write(filePath, contents = '') { - fs.mkdirSync(path.dirname(filePath), { recursive: true }); - fs.writeFileSync(filePath, contents); -} - -function transform(source, { filename, platform = 'desktop', ...options }) { - return transformSync(source, { - filename, - caller: { name: 'metro', bundler: 'metro', platform }, - configFile: false, - babelrc: false, - plugins: [[plugin, options]], - compact: false, - }).code; -} - -/** - * A file that passes the host guard on the host the test runs on. The guard - * reads real bytes, so a valid header has to be written rather than a text - * placeholder. - */ -function hostAddonHeader() { - if (process.platform === 'linux') { - const header = Buffer.alloc(20); - Buffer.from([0x7f, 0x45, 0x4c, 0x46]).copy(header, 0); - header.writeUInt16LE(process.arch === 'arm64' ? 0xb7 : 0x3e, 18); - return header; - } - if (process.platform === 'darwin') { - // 64-bit thin little-endian Mach-O for the host CPU. - const header = Buffer.alloc(32); - Buffer.from([0xcf, 0xfa, 0xed, 0xfe]).copy(header, 0); - header.writeUInt32LE(process.arch === 'arm64' ? 0x0100000c : 0x01000007, 4); - return header; - } - if (process.platform === 'win32') { - // A PE image for the host machine: `MZ`, the `PE\0\0` signature at the - // offset named at 0x3C, and the machine field right after it. - return peHeader(process.arch === 'arm64' ? 0xaa64 : 0x8664); - } - return Buffer.from('not a real binary'); -} - -/** A PE image header for one machine value. */ -function peHeader(machine) { - const header = Buffer.alloc(64); - Buffer.from([0x4d, 0x5a]).copy(header, 0); - header.writeUInt32LE(0x40, 0x3c); - // The signature sits at 0x40, which is past the 64 bytes read here, so the - // smallest valid file the plugin can accept is 0x46 bytes; write enough. - const full = Buffer.alloc(0x48); - header.copy(full, 0); - Buffer.from([0x50, 0x45, 0x00, 0x00]).copy(full, 0x40); - full.writeUInt16LE(machine, 0x44); - return full; -} - -/** A file the host guard rejects: an ELF for the other architecture. */ -function foreignAddonHeader() { - if (process.platform === 'darwin') { - const header = Buffer.alloc(32); - Buffer.from([0xcf, 0xfa, 0xed, 0xfe]).copy(header, 0); - header.writeUInt32LE(process.arch === 'arm64' ? 0x01000007 : 0x0100000c, 4); - return header; - } - if (process.platform === 'win32') { - // The other Windows machine: a PE for the CPU the host is not. - return peHeader(process.arch === 'arm64' ? 0x8664 : 0xaa64); - } - const header = Buffer.alloc(20); - Buffer.from([0x7f, 0x45, 0x4c, 0x46]).copy(header, 0); - header.writeUInt16LE(process.arch === 'arm64' ? 0x3e : 0xb7, 18); - return header; -} - -function writeAddon(filePath, header = hostAddonHeader()) { - write(filePath, header); -} - -/** An ELF header for one Linux e_machine value. */ -function elfHeader(machine) { - const header = Buffer.alloc(20); - Buffer.from([0x7f, 0x45, 0x4c, 0x46]).copy(header, 0); - header.writeUInt16LE(machine, 18); - return header; -} - -/** A 64-bit thin little-endian Mach-O header for one cputype value. */ -function machoHeader(cputype) { - const header = Buffer.alloc(32); - Buffer.from([0xcf, 0xfa, 0xed, 0xfe]).copy(header, 0); - header.writeUInt32LE(cputype, 4); - return header; -} - -/** - * Writes a binary for one named target, so a test can hand the plugin a host - * other than the one it runs on and still get bytes that match. - */ -/** `writeAddonFor` under a shorter name for the R4 tag tests. */ -function writeAddonAt(filePath, hostPlatform, hostArch) { - writeAddonFor(filePath, hostPlatform, hostArch); -} - -function writeAddonFor(filePath, hostPlatform, hostArch) { - if (hostPlatform === 'linux') { - writeAddon(filePath, elfHeader(hostArch === 'arm64' ? 0xb7 : 0x3e)); - return; - } - if (hostPlatform === 'darwin') { - writeAddon( - filePath, - machoHeader(hostArch === 'arm64' ? 0x0100000c : 0x01000007), - ); - return; - } - if (hostPlatform === 'win32') { - writeAddon(filePath, peHeader(hostArch === 'arm64' ? 0xaa64 : 0x8664)); - return; - } - // Other platforms' binaries are not header-checked. - writeAddon(filePath); -} - -/** - * The `_requireNodeLibrary(...)` arguments in transformed code. The plugin emits - * paths through `t.stringLiteral`, so on Windows every backslash is escaped - * (`"C:\\dir\\addon.node"`); each captured literal is decoded back to the real - * string before it is compared. - */ -function callsIn(code) { - const calls = []; - const pattern = - /_requireNodeLibrary\(\s*"((?:[^"\\]|\\.)*)"(?:\s*,\s*"((?:[^"\\]|\\.)*)")?\s*\)/gu; - const decode = value => - value === undefined ? undefined : JSON.parse(`"${value}"`); - for (const match of code.matchAll(pattern)) { - calls.push({ key: decode(match[1]), path: decode(match[2]) }); - } - return calls; -} - -test('rewrites a relative .node require on gpui', () => { - const root = scratch(); - const addon = path.join(root, 'build/Release/addon.node'); - writeAddon(addon); - const code = transform( - "const addon = require('./build/Release/addon.node');", - { - filename: path.join(root, 'index.js'), - }, - ); - expect(code).toContain('_requireNodeLibrary'); - expect(code).not.toContain('require('); - const [call] = callsIn(code); - expect(call.key).toBe(`local/${addonKey(addon).split('/')[1]}/addon.node`); - expect(call.path).toBe(addon); -}); - -test('leaves the require untouched on ios and android', () => { - const root = scratch(); - writeAddon(path.join(root, 'addon.node')); - const source = "const addon = require('./addon.node');"; - for (const platform of ['ios', 'android', 'web']) { - const code = transform(source, { - filename: path.join(root, 'index.js'), - platform, - }); - expect(code).toContain("require('./addon.node')"); - expect(code).not.toContain('_requireNodeLibrary'); - } -}); - -test('rewrites every import form', () => { - const root = scratch(); - writeAddon(path.join(root, 'thing.node')); - const filename = path.join(root, 'index.js'); - const cases = [ - [ - "import binding from './thing.node';", - /const _nodeAddonExports = _requireNodeLibrary\(/u, - ], - [ - "import * as binding from './thing.node';", - /const binding = _nodeAddonExports/u, - ], - [ - "import { add, sub as minus } from './thing.node';", - /const \{\s+add: add,\s+sub: minus\s+\} = _nodeAddonExports/u, - ], - ["import './thing.node';", /^_requireNodeLibrary\(/mu], - ]; - for (const [source, pattern] of cases) { - const code = transform(source, { filename }); - expect(code, source).toMatch(pattern); - expect(code, source).toContain('_requireNodeLibrary('); - } -}); - -test('a bare .node specifier resolves through node resolution', () => { - const root = scratch(); - const addon = path.join( - root, - 'node_modules/some-package/prebuilds/thing.node', - ); - write(filePathIn(root, 'node_modules/some-package/package.json'), '{}'); - writeAddon(addon); - const code = transform("require('some-package/prebuilds/thing.node');", { - filename: path.join(root, 'index.js'), - }); - const [call] = callsIn(code); - expect(call.path).toBe(addon); - expect(call.key).toBe('node_modules/some-package/prebuilds/thing.node'); -}); - -test('a missing .node file becomes a throwing expression with a code', () => { - const root = scratch(); - const code = transform("require('./missing.node');", { - filename: path.join(root, 'index.js'), - }); - expect(code).toContain("Cannot find module './missing.node'"); - expect(code).toContain('MODULE_NOT_FOUND'); - expect(code).not.toContain('_requireNodeLibrary'); -}); - -test('a surrounding try/catch catches the throwing expression', () => { - const root = scratch(); - const code = transform( - "let value; try { value = require('./missing.node'); } catch (error) { value = error.code; }", - { filename: path.join(root, 'index.js') }, - ); - // Evaluated in a bare VM context so the assertion is about the emitted - // expression, not about this test file's scope. - const result = vm.runInNewContext(`${code}\nvalue;`, {}); - expect(result).toBe('MODULE_NOT_FOUND'); -}); - -test('R2 fires only when nothing else would resolve', () => { - const root = scratch(); - const filename = path.join(root, 'index.js'); - writeAddon(path.join(root, 'only.node')); - expect(transform("require('./only');", { filename })).toContain( - '_requireNodeLibrary', - ); - - // With a real .js sibling the require must be left alone. - write(path.join(root, 'both.js'), 'module.exports = {};'); - writeAddon(path.join(root, 'both.node')); - expect(transform("require('./both');", { filename })).toContain( - "require('./both')", - ); - - // With a directory of that name, likewise. - write(path.join(root, 'dir/index.js'), 'module.exports = {};'); - writeAddon(path.join(root, 'dir.node')); - expect(transform("require('./dir');", { filename })).toContain( - "require('./dir')", - ); - - // With a package.json in the directory, likewise. - write(path.join(root, 'pkg/package.json'), '{"main":"x.js"}'); - writeAddon(path.join(root, 'pkg.node')); - expect(transform("require('./pkg');", { filename })).toContain( - "require('./pkg')", - ); -}); - -test('R3 rewrites a bare package whose main is an addon', () => { - const root = scratch(); - const addon = path.join(root, 'node_modules/native-thing/index.node'); - write( - path.join(root, 'node_modules/native-thing/package.json'), - JSON.stringify({ name: 'native-thing', main: 'index.node' }), - ); - writeAddon(addon); - const code = transform("require('native-thing');", { - filename: path.join(root, 'index.js'), - }); - const [call] = callsIn(code); - expect(call.key).toBe('node_modules/native-thing/index.node'); - expect(call.path).toBe(addon); -}); - -test('a bare package whose main is JavaScript is left alone', () => { - const root = scratch(); - write( - path.join(root, 'node_modules/plain-thing/package.json'), - JSON.stringify({ name: 'plain-thing', main: 'index.js' }), - ); - write(path.join(root, 'node_modules/plain-thing/index.js'), ''); - expect( - transform("require('plain-thing');", { - filename: path.join(root, 'index.js'), - }), - ).toContain("require('plain-thing')"); -}); - -test('key: everything from the first node_modules segment', () => { - const root = scratch(); - const addon = path.join( - root, - 'node_modules/a/node_modules/b/prebuilds/x.node', - ); - writeAddon(addon); - expect(addonKey(addon)).toBe( - 'node_modules/a/node_modules/b/prebuilds/x.node', - ); -}); - -test('key: the local form for a path outside node_modules', () => { - const root = scratch(); - const addon = path.join(root, 'build/Release/addon.node'); - writeAddon(addon); - const key = addonKey(addon); - expect(key).toMatch(/^local\/[0-9a-f]{8}\/addon\.node$/u); - expect(key).not.toContain('..'); - expect(key.startsWith('/')).toBe(false); -}); - -test('key: a symlinked package directory uses the real path', () => { - const root = scratch(); - const real = path.join(root, 'real-package/prebuilds/x.node'); - write(filePathIn(root, 'real-package/package.json'), '{}'); - writeAddon(real); - const link = path.join(root, 'node_modules/linked-package'); - fs.mkdirSync(path.dirname(link), { recursive: true }); - // A symbolic link needs an elevated process or Developer Mode on Windows; a - // directory junction needs neither and `fs.realpath` resolves it to the same - // target, which is the behaviour under test. - fs.symlinkSync( - path.dirname(path.dirname(real)), - link, - process.platform === 'win32' ? 'junction' : 'dir', - ); - const code = transform("require('linked-package/prebuilds/x.node');", { - filename: path.join(root, 'index.js'), - }); - const [call] = callsIn(code); - // The key comes from the real path (section 3.3), and a symlinked workspace - // package resolves outside node_modules, so it takes the `local/` form — - // the same key the real path produces when required directly, which is the - // invariant that matters: one file, one key, whichever way it is reached. - expect(call.key).toBe(addonKey(real)); - expect(call.key).toMatch(/^local\/[0-9a-f]{8}\/x\.node$/u); -}); - -test('embedPaths: false omits the second argument', () => { - const root = scratch(); - writeAddon(path.join(root, 'addon.node')); - const code = transform("require('./addon.node');", { - filename: path.join(root, 'index.js'), - embedPaths: false, - }); - expect(code).toMatch(/_requireNodeLibrary\("[^"]+"\)/u); - expect(callsIn(code)[0].path).toBeUndefined(); -}); - -test('a binary for another platform is treated as missing', () => { - const root = scratch(); - const addon = path.join(root, 'foreign.node'); - write(addon, foreignAddonHeader()); - expect(isHostPrebuiltNodeAddon(addon, process.platform, process.arch)).toBe( - false, - ); - const code = transform("require('./foreign.node');", { - filename: path.join(root, 'index.js'), - }); - expect(code).toContain('MODULE_NOT_FOUND'); - expect(code).not.toContain('_requireNodeLibrary'); -}); - -test('a path segment naming another platform is rejected without reading', () => { - const root = scratch(); - // A segment naming a platform that is not the host's, so the guard rejects it - // before it ever opens the file (the bytes written are the host's, which is - // what makes this a test of the segment check rather than the header check). - const foreign = process.platform === 'win32' ? 'linux' : 'win32'; - const foreignArch = process.arch === 'arm64' ? 'arm64' : 'x64'; - const addon = path.join( - root, - `prebuilds/${foreign}-${foreignArch}/thing.node`, - ); - writeAddon(addon); - expect(isHostPrebuiltNodeAddon(addon, process.platform, process.arch)).toBe( - false, - ); -}); - -test('the host platform and arch are options, so tests run anywhere', () => { - const root = scratch(); - const linuxX64 = Buffer.alloc(20); - Buffer.from([0x7f, 0x45, 0x4c, 0x46]).copy(linuxX64, 0); - linuxX64.writeUInt16LE(0x3e, 18); - const addon = path.join(root, 'linux.node'); - write(addon, linuxX64); - - expect(isHostPrebuiltNodeAddon(addon, 'linux', 'x64')).toBe(true); - expect(isHostPrebuiltNodeAddon(addon, 'linux', 'arm64')).toBe(false); - - const code = transform("require('./linux.node');", { - filename: path.join(root, 'index.js'), - hostPlatform: 'linux', - hostArch: 'x64', - }); - expect(code).toContain('_requireNodeLibrary'); - - const foreign = transform("require('./linux.node');", { - filename: path.join(root, 'index.js'), - hostPlatform: 'linux', - hostArch: 'arm64', - }); - expect(foreign).toContain('MODULE_NOT_FOUND'); -}); - -test('a universal Mach-O with a host slice is accepted', () => { - const root = scratch(); - const fat = Buffer.alloc(8 + 2 * 20); - Buffer.from([0xca, 0xfe, 0xba, 0xbe]).copy(fat, 0); - fat.writeUInt32BE(2, 4); - fat.writeUInt32BE(0x01000007, 8); // x86_64 - fat.writeUInt32BE(0x0100000c, 8 + 20); // arm64 - const addon = path.join(root, 'universal.node'); - write(addon, fat); - expect(isHostPrebuiltNodeAddon(addon, 'darwin', 'arm64')).toBe(true); - expect(isHostPrebuiltNodeAddon(addon, 'darwin', 'x64')).toBe(true); -}); - -test('a universal Mach-O without a host slice is rejected', () => { - const root = scratch(); - const fat = Buffer.alloc(8 + 20); - Buffer.from([0xca, 0xfe, 0xba, 0xbe]).copy(fat, 0); - fat.writeUInt32BE(1, 4); - fat.writeUInt32BE(0x01000007, 8); // x86_64 only - const addon = path.join(root, 'intel-only.node'); - write(addon, fat); - expect(isHostPrebuiltNodeAddon(addon, 'darwin', 'arm64')).toBe(false); - expect(isHostPrebuiltNodeAddon(addon, 'darwin', 'x64')).toBe(true); -}); - -test('resolveAddon reports a non-addon specifier as null', () => { - const root = scratch(); - write(path.join(root, 'plain.js'), ''); - expect( - resolveAddon('./plain', root, { - hostPlatform: process.platform, - hostArch: process.arch, - }), - ).toBeNull(); - expect( - resolveAddon('react', root, { - hostPlatform: process.platform, - hostArch: process.arch, - }), - ).toBeNull(); -}); - -test('a dynamic import and a computed require are left alone', () => { - const root = scratch(); - writeAddon(path.join(root, 'addon.node')); - const filename = path.join(root, 'index.js'); - expect(transform("import('./addon.node');", { filename })).toContain( - "import('./addon.node')", - ); - expect(transform('require(name);', { filename })).toContain('require(name)'); - expect(transform('require(`./addon.node`);', { filename })).toContain( - 'require(`./addon.node`)', - ); -}); - -test('the key never contains a backslash or a parent segment', () => { - const root = scratch(); - const addon = path.join(root, 'build/Release/addon.node'); - writeAddon(addon); - const key = addonKey(addon); - expect(key).not.toContain('\\'); - expect(key.split('/')).not.toContain('..'); -}); - -function filePathIn(root, relative) { - return path.join(root, relative); -} - -// --- R4/R5/R6: packages that pick their binary at run time ------------------ - -/** - * Writes a `prebuilds//.node` tree plus a package.json, the layout - * `node-gyp-build` uses. - */ -function writeNodeGypBuildPackage(root, tags) { - for (const tag of tags) { - writeAddon(path.join(root, 'prebuilds', tag, 'thing.node')); - } - write( - path.join(root, 'package.json'), - JSON.stringify({ name: 'gyp-thing', version: '1.0.0', main: 'index.js' }), - ); -} - -/** The host's `node-gyp-build` tag, matching the plugin's own choice. */ -function hostPrebuildTag() { - return `${process.platform}-${process.arch}`; -} - -test('R4 resolves require("node-gyp-build")(__dirname)', () => { - const root = scratch(); - writeNodeGypBuildPackage(root, [hostPrebuildTag()]); - const code = transform( - "module.exports = require('node-gyp-build')(__dirname);", - { filename: path.join(root, 'index.js') }, - ); - const [call] = callsIn(code); - expect(call.path).toBe( - path.join(root, 'prebuilds', hostPrebuildTag(), 'thing.node'), - ); - expect(code).not.toContain('node-gyp-build'); -}); - -test('R4 resolves path.join(__dirname, "sub")', () => { - const root = scratch(); - const fixture = path.join(root, 'native'); - writeNodeGypBuildPackage(fixture, [hostPrebuildTag()]); - const code = transform( - "module.exports = require('node-gyp-build')(require('path').join(__dirname, 'native'));", - { filename: path.join(root, 'index.js') }, - ); - expect(callsIn(code)[0].path).toBe( - path.join(fixture, 'prebuilds', hostPrebuildTag(), 'thing.node'), - ); -}); - -test('R4 prefers the host tag over node.napi', () => { - const root = scratch(); - writeNodeGypBuildPackage(root, [hostPrebuildTag(), 'node.napi']); - const code = transform("require('node-gyp-build')(__dirname);", { - filename: path.join(root, 'index.js'), - }); - expect(callsIn(code)[0].path).toBe( - path.join(root, 'prebuilds', hostPrebuildTag(), 'thing.node'), - ); -}); - -test('R4 falls back to an in-tree build/Release binary', () => { - const root = scratch(); - writeAddon(path.join(root, 'build/Release/built.node')); - write( - path.join(root, 'package.json'), - JSON.stringify({ name: 'gyp-built', version: '1.0.0' }), - ); - const code = transform("require('node-gyp-build')(__dirname);", { - filename: path.join(root, 'index.js'), - }); - expect(callsIn(code)[0].path).toBe( - path.join(root, 'build/Release/built.node'), - ); -}); - -test('R4 emits a throwing expression and warns when nothing resolves', () => { - const root = scratch(); - write( - path.join(root, 'package.json'), - JSON.stringify({ name: 'gyp-empty', version: '1.0.0' }), - ); - const code = transform("require('node-gyp-build')(__dirname);", { - filename: path.join(root, 'index.js'), - }); - expect(code).toContain('MODULE_NOT_FOUND'); - expect(code).not.toContain('_requireNodeLibrary'); -}); - -test('R4 ignores a dynamic directory argument', () => { - const root = scratch(); - const code = transform("require('node-gyp-build')(someDir);", { - filename: path.join(root, 'index.js'), - }); - expect(code).toContain("require('node-gyp-build')(someDir)"); -}); - -test('R5 resolves require("bindings")("thing")', () => { - const root = scratch(); - const addon = path.join(root, 'build/Release/thing.node'); - writeAddon(addon); - write( - path.join(root, 'package.json'), - JSON.stringify({ name: 'binding-thing', version: '1.0.0' }), - ); - const code = transform("module.exports = require('bindings')('thing');", { - filename: path.join(root, 'index.js'), - }); - expect(callsIn(code)[0].path).toBe(addon); - expect(code).not.toContain("require('bindings')"); -}); - -test('R5 accepts the { bindings: name } form', () => { - const root = scratch(); - const addon = path.join(root, 'build/Release/thing.node'); - writeAddon(addon); - const code = transform( - "module.exports = require('bindings')({ bindings: 'thing' });", - { filename: path.join(root, 'lib/index.js') }, - ); - expect(callsIn(code)[0].path).toBe(addon); -}); - -test('R5 searches upward for the package root, like bindings does', () => { - const root = scratch(); - const addon = path.join(root, 'build/Release/thing.node'); - writeAddon(addon); - write( - path.join(root, 'package.json'), - JSON.stringify({ name: 'binding-thing', version: '1.0.0' }), - ); - const code = transform("require('bindings')('thing');", { - filename: path.join(root, 'lib/deep/index.js'), - }); - expect(callsIn(code)[0].path).toBe(addon); -}); - -test('R5 emits a throwing expression when nothing resolves', () => { - const root = scratch(); - write( - path.join(root, 'package.json'), - JSON.stringify({ name: 'binding-empty', version: '1.0.0' }), - ); - const code = transform("require('bindings')('missing');", { - filename: path.join(root, 'index.js'), - }); - expect(code).toContain('MODULE_NOT_FOUND'); -}); - -/** The napi-rs triple the plugin should choose for the host. */ -function hostNapiRsTriple() { - if (process.platform === 'linux') return `linux-${process.arch}-gnu`; - if (process.platform === 'win32') return `win32-${process.arch}-msvc`; - return `${process.platform}-${process.arch}`; -} - -test('R6 replaces a napi-rs generated loader with one require', () => { - const root = scratch(); - const triple = hostNapiRsTriple(); - // Three distinct platforms, none of which is the host's, so only the host - // branch can resolve. The names must be ones the napi-rs triple scanner - // recognises, otherwise this reads as a hand-written two-platform file and R6 - // never fires. - const otherTriple = 'freebsd-x64'; - const thirdTriple = 'android-x64'; - writeAddon(path.join(root, `thing.${triple}.node`)); - writeAddon(path.join(root, `thing.${otherTriple}.node`)); - writeAddon(path.join(root, `thing.${thirdTriple}.node`)); - const loader = ` -if (process.platform === '${process.platform}') { - module.exports = require('./thing.${triple}.node'); -} else if (process.platform === 'freebsd') { - module.exports = require('./thing.${otherTriple}.node'); -} else if (process.platform === 'android') { - module.exports = require('./thing.${thirdTriple}.node'); -} else { - throw new Error('unsupported'); -} -`; - const code = transform(loader, { filename: path.join(root, 'index.js') }); - expect(callsIn(code)).toHaveLength(1); - expect(callsIn(code)[0].path).toBe(path.join(root, `thing.${triple}.node`)); - expect(code).toContain('module.exports'); - expect(code).not.toContain('process.platform'); -}); - -test('R6 resolves the per-platform package form', () => { - const root = scratch(); - // A Linux host named explicitly, so the package that has to exist is the - // one the loader names for Linux regardless of where this test runs. - const triple = 'linux-x64-gnu'; - const packageName = `@scope/thing-${triple}`; - const addon = path.join( - root, - 'node_modules/@scope', - `thing-${triple}`, - 'thing.node', - ); - // The host is named as linux/x64 below, so the bytes must be an ELF for x64 - // even when this test runs on macOS. - writeAddonFor(addon, 'linux', 'x64'); - write( - path.join(root, `node_modules/@scope/thing-${triple}/package.json`), - JSON.stringify({ name: packageName, version: '1.0.0', main: 'thing.node' }), - ); - const loader = ` -if (process.platform === 'linux') { - module.exports = require('@scope/thing-linux-x64-gnu'); -} else if (process.platform === 'darwin') { - module.exports = require('@scope/thing-darwin-arm64'); -} else if (process.platform === 'win32') { - module.exports = require('@scope/thing-win32-x64-msvc'); -} -`; - const code = transform(loader, { - filename: path.join(root, 'index.js'), - hostPlatform: 'linux', - hostArch: 'x64', - }); - expect(callsIn(code)).toHaveLength(1); - expect(callsIn(code)[0].path).toBe(addon); -}); - -test('R6 leaves a file that names fewer than three platforms to R1', () => { - const root = scratch(); - // Two platforms only, so this is not a napi-rs loader and R1 alone rewrites - // it. The host's own triple is one of them, so the rewrite really resolves. - const hostTriple = hostNapiRsTriple(); - const foreignTriple = 'darwin-arm64'; - writeAddon(path.join(root, `thing.${hostTriple}.node`)); - writeAddonFor( - path.join(root, `thing.${foreignTriple}.node`), - 'darwin', - 'arm64', - ); - const source = ` -if (process.platform === '${process.platform}') { - module.exports = require('./thing.${hostTriple}.node'); -} else { - module.exports = require('./thing.${foreignTriple}.node'); -} -`; - const code = transform(source, { filename: path.join(root, 'index.js') }); - // Not a napi-rs loader, so the module body is untouched: the `process` - // reference only means something where a platform branch survives, and R1 - // rewrote the requires it could resolve. - expect(code).toContain(`process.platform === '${process.platform}'`); - expect(code).toMatch(/module\.exports = _requireNodeLibrary\(/u); -}); - -test('R6 leaves a matching file alone when no host binary exists', () => { - const root = scratch(); - const source = ` -if (process.platform === 'freebsd') { - module.exports = require('./thing.freebsd-x64.node'); -} else if (process.platform === 'android') { - module.exports = require('./thing.android-arm64.node'); -} else if (process.platform === 'openharmony') { - module.exports = require('./thing.openharmony-arm64.node'); -} -`; - const code = transform(source, { filename: path.join(root, 'index.js') }); - expect(code).not.toContain('_requireNodeLibrary'); -}); - -test('R4/R5/R6 are no-ops off gpui', () => { - const root = scratch(); - writeNodeGypBuildPackage(root, [hostPrebuildTag()]); - const source = [ - "require('node-gyp-build')(__dirname);", - "require('bindings')('thing');", - ].join('\n'); - const code = transform(source, { - filename: path.join(root, 'index.js'), - platform: 'ios', - }); - expect(code).toContain("require('node-gyp-build')(__dirname)"); - expect(code).toContain("require('bindings')('thing')"); - expect(code).not.toContain('_requireNodeLibrary'); -}); - -test('R4/R6 use the hostPlatform/hostArch options', () => { - const root = scratch(); - // `node-gyp-build` spells the Linux tag `linux-x64`; the napi-rs spelling - // `linux-x64-gnu` is a different directory and must not be picked. - const directory = path.join(root, 'linux-only'); - writeAddonFor( - path.join(directory, 'prebuilds/linux-x64-gnu/thing.node'), - 'linux', - 'x64', - ); - write( - path.join(directory, 'package.json'), - JSON.stringify({ name: 'linux-only', version: '1.0.0' }), - ); - const missing = transform("require('node-gyp-build')(__dirname);", { - filename: path.join(directory, 'index.js'), - hostPlatform: 'linux', - hostArch: 'x64', - }); - expect(missing).toContain('MODULE_NOT_FOUND'); - - writeAddonFor( - path.join(directory, 'prebuilds/linux-x64/thing.node'), - 'linux', - 'x64', - ); - const resolved = transform("require('node-gyp-build')(__dirname);", { - filename: path.join(directory, 'index.js'), - hostPlatform: 'linux', - hostArch: 'x64', - }); - expect(callsIn(resolved)[0].path).toBe( - path.join(directory, 'prebuilds/linux-x64/thing.node'), - ); -}); - -test('R4 handles path.resolve(__dirname), as bcrypt writes it', () => { - const root = scratch(); - const tag = hostPrebuildTag(); - // bcrypt ships `prebuilds/-/.node`, with a `glibc` - // tag on Linux builds. - const fileName = - process.platform === 'linux' ? 'thing.glibc.node' : 'thing.node'; - if (process.platform === 'linux') { - writeAddon(path.join(root, 'prebuilds', tag, fileName)); - } else { - writeAddon(path.join(root, 'prebuilds', tag, fileName)); - } - const code = transform( - "const path = require('path');\nmodule.exports = require('node-gyp-build')(path.resolve(__dirname));", - { filename: path.join(root, 'index.js') }, - ); - expect(callsIn(code)).toHaveLength(1); - expect(callsIn(code)[0].path).toBe( - path.join(root, 'prebuilds', tag, fileName), - ); -}); - -test('R4 resolves path.resolve(__dirname, "sub")', () => { - const root = scratch(); - const fixture = path.join(root, 'native'); - writeNodeGypBuildPackage(fixture, [hostPrebuildTag()]); - const code = transform( - "module.exports = require('node-gyp-build')(require('path').resolve(__dirname, 'native'));", - { filename: path.join(root, 'index.js') }, - ); - expect(callsIn(code)[0].path).toBe( - path.join(fixture, 'prebuilds', hostPrebuildTag(), 'thing.node'), - ); -}); - -test('R4 accepts a host arch inside a + joined directory', () => { - const root = scratch(); - const platform = process.platform; - const arch = process.arch; - const other = arch === 'arm64' ? 'x64' : 'arm64'; - // The layout microtime ships: one universal binary for a two-arch directory. - // The host arch is one of the two, so this is a valid host artifact. - writeAddonFor( - path.join( - root, - 'prebuilds', - `${platform}-${other}+${arch}`, - 'node.napi.node', - ), - platform, - arch, - ); - const code = transform("require('node-gyp-build')(__dirname);", { - filename: path.join(root, 'index.js'), - }); - expect(callsIn(code)).toHaveLength(1); - expect(callsIn(code)[0].path).toContain('node.napi.node'); -}); - -test('R4 rejects a + joined directory that excludes the host arch', () => { - const root = scratch(); - const platform = process.platform; - const arch = process.arch; - const other = arch === 'arm64' ? 'x64' : 'arm64'; - // Two architectures, neither of them the host's. - writeAddon( - path.join( - root, - 'prebuilds', - `${platform}-${other}+${other === 'x64' ? 'ia32' : 'x86'}`, - 'node.napi.node', - ), - ); - const code = transform("require('node-gyp-build')(__dirname);", { - filename: path.join(root, 'index.js'), - }); - expect(code).toContain('MODULE_NOT_FOUND'); -}); - -test('R4 prefers a single-arch directory over a + joined one', () => { - const root = scratch(); - const platform = process.platform; - const arch = process.arch; - // Both directories match the host; the one naming just this arch wins, - // exactly as node-gyp-build compares tuples. - writeAddon(path.join(root, 'prebuilds', `${platform}-${arch}`, 'thing.node')); - writeAddon( - path.join(root, 'prebuilds', `${platform}-other+${arch}`, 'thing.node'), - ); - const code = transform("require('node-gyp-build')(__dirname);", { - filename: path.join(root, 'index.js'), - }); - expect(callsIn(code)[0].path).toBe( - path.join(root, 'prebuilds', `${platform}-${arch}`, 'thing.node'), - ); -}); - -test('R4 accepts a bare node.napi.node, which is runtime-agnostic', () => { - const root = scratch(); - // A multi-arch directory holding only an ABI-agnostic N-API build, which is - // what a package that targets Node, Electron and other hosts ships. - writeAddon( - path.join( - root, - 'prebuilds', - `${process.platform}-${process.arch}`, - 'node.napi.node', - ), - ); - const code = transform("require('node-gyp-build')(__dirname);", { - filename: path.join(root, 'index.js'), - }); - expect(callsIn(code)).toHaveLength(1); - expect(callsIn(code)[0].path).toContain('node.napi.node'); -}); - -test('R4 rejects an abi-tagged build, which is not an N-API host', () => { - const root = scratch(); - const directory = path.join( - root, - 'prebuilds', - `${process.platform}-${process.arch}`, - ); - // `node.abi115.node` is bound to Node's ABI, not to N-API, so it must not be - // picked even though it is a valid binary for this CPU. - writeAddon(path.join(directory, 'node.abi115.node')); - const code = transform("require('node-gyp-build')(__dirname);", { - filename: path.join(root, 'index.js'), - }); - expect(code).toContain('MODULE_NOT_FOUND'); -}); - -test('R4 honours the glibc/musl file tag on Linux', () => { - const root = scratch(); - const directory = path.join(root, 'prebuilds', 'linux-x64'); - writeAddonAt(path.join(directory, 'thing.glibc.node'), 'linux', 'x64'); - writeAddonAt(path.join(directory, 'thing.musl.node'), 'linux', 'x64'); - const code = transform("require('node-gyp-build')(__dirname);", { - filename: path.join(root, 'index.js'), - hostPlatform: 'linux', - hostArch: 'x64', - }); - // The test host is not Alpine, so the glibc build is the one node-gyp-build - // would load there. - expect(callsIn(code)[0].path).toBe(path.join(directory, 'thing.glibc.node')); -}); - -test('R7 resolves a require whose path is a template literal', () => { - const root = scratch(); - const platform = process.platform; - const arch = process.arch; - const tag = - platform === 'linux' ? `${platform}-${arch}` : `${platform}-${arch}`; - // The farmhash layout: one binary per `-` under `build/`. - writeAddonFor(path.join(root, 'build', `thing-${tag}.node`), platform, arch); - writeAddon( - path.join(root, 'build', 'thing-otheros-x64.node'), - Buffer.alloc(0), - ); - const code = transform( - 'module.exports = require(`./build/thing-${platform}-${arch}.node`);', - { filename: path.join(root, 'index.js') }, - ); - expect(callsIn(code)).toHaveLength(1); - expect(callsIn(code)[0].path).toBe( - path.join(root, 'build', `thing-${tag}.node`), - ); -}); - -test('R7 skips a candidate naming a foreign target', () => { - const root = scratch(); - // Only foreign builds exist, so R7 must not pick one. - writeAddon(path.join(root, 'build', 'thing-win32-x64.node')); - writeAddon(path.join(root, 'build', 'thing-linux-arm64.node')); - const code = transform( - 'module.exports = require(`./build/thing-${platform}-${arch}.node`);', - { - filename: path.join(root, 'index.js'), - hostPlatform: 'darwin', - hostArch: 'arm64', - }, - ); - expect(code).toContain('MODULE_NOT_FOUND'); -}); - -test('R7 emits a throwing expression when no candidate exists', () => { - const root = scratch(); - const code = transform( - 'module.exports = require(`./build/thing-${platform}.node`);', - { filename: path.join(root, 'index.js') }, - ); - expect(code).toContain('MODULE_NOT_FOUND'); - expect(code).not.toContain('_requireNodeLibrary'); -}); - -test('R7 leaves a template literal that is not a .node path alone', () => { - const root = scratch(); - const code = transform('const x = `./data/${name}.json`;', { - filename: path.join(root, 'index.js'), - }); - expect(code).toContain('const x = `./data/${name}.json`'); -}); - -// --- Part H: the host-binary check accepts only a host binary ----------------- -// -// `isPeForArch` answers `null` for "not a PE file at all", `false` for "a PE for -// another machine" and `true` for a match. The caller used `!== false`, so a -// `null` — a Linux ELF or a macOS Mach-O — was accepted on a Windows host. The -// ELF and Mach-O branches already required `=== true`; these tests pin the same -// rule for Windows, and pin it on every host by naming the platform. - -/** A file whose first bytes are not any known executable format. */ -function notAnExecutable() { - return Buffer.from('this is not a native addon, it is text', 'utf8'); -} - -test('on win32 an ELF file is rejected', () => { - const root = scratch(); - const addon = path.join(root, 'linux.node'); - write(addon, elfHeader(0x3e)); - expect(isHostPrebuiltNodeAddon(addon, 'win32', 'x64')).toBe(false); -}); - -test('on win32 a Mach-O file is rejected', () => { - const root = scratch(); - const addon = path.join(root, 'darwin.node'); - write(addon, machoHeader(0x01000007)); - expect(isHostPrebuiltNodeAddon(addon, 'win32', 'x64')).toBe(false); -}); - -test('on win32 a file that is not an executable at all is rejected', () => { - const root = scratch(); - const addon = path.join(root, 'text.node'); - write(addon, notAnExecutable()); - // The case the bug let through: not a PE, so `isPeForArch` answers null. - expect(isHostPrebuiltNodeAddon(addon, 'win32', 'x64')).toBe(false); -}); - -test('on win32 a PE for the other architecture is rejected', () => { - const root = scratch(); - const addon = path.join(root, 'other-arch.node'); - write(addon, peHeader(0xaa64)); - expect(isHostPrebuiltNodeAddon(addon, 'win32', 'x64')).toBe(false); -}); - -test('on win32 a PE for the host architecture is accepted', () => { - const root = scratch(); - const addon = path.join(root, 'host.node'); - write(addon, peHeader(0x8664)); - expect(isHostPrebuiltNodeAddon(addon, 'win32', 'x64')).toBe(true); -}); - -test('a rejected foreign binary becomes a MODULE_NOT_FOUND require', () => { - const root = scratch(); - const addon = path.join(root, 'linux.node'); - write(addon, elfHeader(0x3e)); - const code = transform("require('./linux.node');", { - filename: path.join(root, 'index.js'), - hostPlatform: 'win32', - hostArch: 'x64', - }); - expect(code).toContain('MODULE_NOT_FOUND'); - expect(code).not.toContain('_requireNodeLibrary'); -}); diff --git a/vendor/react-native-gpui/packages/core/contextMenu.test.js b/vendor/react-native-gpui/packages/core/contextMenu.test.js deleted file mode 100644 index 872302107f..0000000000 --- a/vendor/react-native-gpui/packages/core/contextMenu.test.js +++ /dev/null @@ -1,1012 +0,0 @@ -/** - * Unit tests for the custom context menu's pure modules. - * - * The repo's vitest include list only picks up `*.test.js` under `packages/core`, - * so this file lives at the package root rather than next to the sources. The - * sources it imports are TypeScript, and the GPUI vitest preset resolves those - * with the `.desktop`/`.native` extension order and the same `react-native` - * alias the rest of `packages/core`'s tests use, so importing the modules - * directly works without a build step. - * - * @format - */ - -import { describe, expect, test } from 'vitest'; -import { - DEFAULT_MENU_MARGIN, - measurableSize, - placeRootMenu, - placeSubmenu, -} from './src-gpui/src/private/desktop/contextMenu/placement'; -import { - placeLevels, - rowRect as rowRectOf, -} from './src-gpui/src/private/desktop/contextMenu/levels'; -import { - EMPTY_NAVIGATION, - TYPEAHEAD_TIMEOUT_MS, - firstEnabledIndex, - lastEnabledIndex, - navigate, - nextEnabledIndex, - typeaheadIndex, -} from './src-gpui/src/private/desktop/contextMenu/navigation'; -import { - dark, - light, - mergeTheme, - themeForScheme, -} from './src-gpui/src/private/desktop/contextMenu/theme'; -import { formatAccelerator } from './src-gpui/src/private/desktop/contextMenu/accelerator'; -import { - isInSafeTriangle, - safeTriangleFor, -} from './src-gpui/src/private/desktop/contextMenu/safeTriangle'; -import { - contextMenuConfig, - setContextMenuConfig, - setContextMenuRenderers, - contextMenuRenderers, - contextMenuTheme, - setContextMenuPresentation, - contextMenuPresentation, - setContextMenuTheme, - subscribeContextMenuConfig, -} from './src-gpui/src/private/desktop/contextMenu/config'; -import { - contextMenuHostFor, - contextMenuWindowIds, - hasContextMenuHost, - registerContextMenuHost, - unregisterContextMenuHost, -} from './src-gpui/src/private/desktop/contextMenu/registry'; -import { - entryId, - entryLabel, - entryTestId, - isChecked, - isEnabled, - isSubmenu, - humanizeRole, -} from './src-gpui/src/private/desktop/contextMenu/types'; - -const windowSize = { width: 1000, height: 800 }; - -describe('placeRootMenu', () => { - test('places the menu at the anchor when it fits', () => { - expect( - placeRootMenu({ - anchor: { x: 100, y: 120 }, - menuSize: { width: 200, height: 150 }, - windowSize, - }), - ).toEqual({ x: 100, y: 120 }); - }); - - test('flips left at the right edge and stays inside', () => { - // 900 + 200 > 996 (the window width less the margin), so it opens leftwards. - const point = placeRootMenu({ - anchor: { x: 900, y: 100 }, - menuSize: { width: 200, height: 150 }, - windowSize, - }); - expect(point.x).toBe(700); - expect(point.x + 200).toBeLessThanOrEqual(windowSize.width); - }); - - test('flips up at the bottom edge and stays inside', () => { - const point = placeRootMenu({ - anchor: { x: 100, y: 700 }, - menuSize: { width: 200, height: 150 }, - windowSize, - }); - expect(point.y).toBe(550); - expect(point.y + 150).toBeLessThanOrEqual(windowSize.height); - }); - - test('flips in both directions in the bottom-right corner', () => { - expect( - placeRootMenu({ - anchor: { x: 980, y: 780 }, - menuSize: { width: 200, height: 150 }, - windowSize, - }), - ).toEqual({ x: 780, y: 630 }); - }); - - test('clamps to the margin when the anchor is outside the window', () => { - expect( - placeRootMenu({ - anchor: { x: -50, y: -80 }, - menuSize: { width: 200, height: 150 }, - windowSize, - }), - ).toEqual({ x: DEFAULT_MENU_MARGIN, y: DEFAULT_MENU_MARGIN }); - }); - - test('clamps past the far edge rather than overflowing', () => { - const point = placeRootMenu({ - anchor: { x: 5000, y: 5000 }, - menuSize: { width: 200, height: 150 }, - windowSize, - }); - expect(point).toEqual({ - x: windowSize.width - DEFAULT_MENU_MARGIN - 200, - y: windowSize.height - DEFAULT_MENU_MARGIN - 150, - }); - }); - - test('keeps a menu bigger than the window against the near margin', () => { - const point = placeRootMenu({ - anchor: { x: 400, y: 400 }, - menuSize: { width: 1400, height: 1200 }, - windowSize, - }); - expect(point).toEqual({ x: DEFAULT_MENU_MARGIN, y: DEFAULT_MENU_MARGIN }); - expect(point.x).toBeGreaterThanOrEqual(0); - expect(point.y).toBeGreaterThanOrEqual(0); - }); - - test('honours a wider margin', () => { - expect( - placeRootMenu({ - anchor: { x: 0, y: 0 }, - menuSize: { width: 100, height: 100 }, - windowSize, - margin: 20, - }), - ).toEqual({ x: 20, y: 20 }); - }); - - test('treats a negative margin as no margin and a non-finite one as the default', () => { - expect( - placeRootMenu({ - anchor: { x: 0, y: 0 }, - menuSize: { width: 100, height: 100 }, - windowSize, - margin: -10, - }), - ).toEqual({ x: 0, y: 0 }); - for (const margin of [Number.NaN, Number.POSITIVE_INFINITY]) { - expect( - placeRootMenu({ - anchor: { x: 0, y: 0 }, - menuSize: { width: 100, height: 100 }, - windowSize, - margin, - }), - ).toEqual({ x: DEFAULT_MENU_MARGIN, y: DEFAULT_MENU_MARGIN }); - } - }); - - test('is deterministic', () => { - const input = { - anchor: { x: 950, y: 780 }, - menuSize: { width: 240, height: 180 }, - windowSize, - }; - expect(placeRootMenu(input)).toEqual(placeRootMenu(input)); - }); -}); - -describe('placeSubmenu', () => { - const rowRect = { x: 200, y: 300, width: 180, height: 26 }; - - test('opens to the right of the row when there is room', () => { - const placed = placeSubmenu({ - rowRect, - menuSize: { width: 200, height: 100 }, - windowSize, - }); - expect(placed).toEqual({ x: 380, y: 300, side: 'right' }); - }); - - test('opens to the left when the right edge is too close', () => { - const placed = placeSubmenu({ - rowRect: { x: 800, y: 300, width: 180, height: 26 }, - menuSize: { width: 200, height: 100 }, - windowSize, - }); - expect(placed.side).toBe('left'); - expect(placed.x).toBe(600); - }); - - test('aligns vertically with the row and clamps near the bottom', () => { - const placed = placeSubmenu({ - rowRect: { x: 200, y: 760, width: 180, height: 26 }, - menuSize: { width: 200, height: 100 }, - windowSize, - }); - expect(placed.y).toBe(windowSize.height - DEFAULT_MENU_MARGIN - 100); - expect(placed.y + 100).toBeLessThanOrEqual(windowSize.height); - }); - - test('clamps a submenu wider than the window to the near margin', () => { - const placed = placeSubmenu({ - rowRect, - menuSize: { width: 1200, height: 100 }, - windowSize, - }); - expect(placed.x).toBe(DEFAULT_MENU_MARGIN); - expect(placed.side).toBe('left'); - }); - - test('still reports a side when clamped on both axes', () => { - const placed = placeSubmenu({ - rowRect: { x: 990, y: 790, width: 10, height: 10 }, - menuSize: { width: 900, height: 900 }, - windowSize, - }); - expect(placed.side).toBe('left'); - expect(placed.x).toBeGreaterThanOrEqual(0); - expect(placed.y).toBeGreaterThanOrEqual(0); - }); -}); - -describe('measurableSize', () => { - test('accepts a measured window', () => { - expect(measurableSize({ width: 800, height: 600 })).toEqual({ - width: 800, - height: 600, - }); - }); - - test('rejects a zero or non-finite layout', () => { - expect(measurableSize({ width: 0, height: 600 })).toBeNull(); - expect(measurableSize({ width: 800, height: 0 })).toBeNull(); - expect(measurableSize({ width: Number.NaN, height: 600 })).toBeNull(); - }); -}); - -const items = [ - { id: 'new', label: 'New' }, - { type: 'separator' }, - { id: 'open', label: 'Open' }, - { id: 'save', label: 'Save', enabled: false }, - { type: 'submenu', id: 'export', label: 'Export', items: [] }, - { id: 'edit', label: 'Edit' }, -]; - -describe('nextEnabledIndex', () => { - test('skips separators and disabled rows', () => { - expect(nextEnabledIndex(items, -1, 1)).toBe(0); - expect(nextEnabledIndex(items, 0, 1)).toBe(2); - expect(nextEnabledIndex(items, 2, 1)).toBe(4); - }); - - test('wraps at both ends', () => { - expect(nextEnabledIndex(items, 5, 1)).toBe(0); - expect(nextEnabledIndex(items, 0, -1)).toBe(5); - expect(nextEnabledIndex(items, -1, -1)).toBe(5); - }); - - test('returns -1 for a level with nothing selectable', () => { - expect( - nextEnabledIndex([{ type: 'separator' }, { type: 'separator' }], -1, 1), - ).toBe(-1); - }); - - test('first and last go to a selectable row', () => { - expect(firstEnabledIndex(items)).toBe(0); - expect(lastEnabledIndex(items)).toBe(5); - }); -}); - -describe('typeaheadIndex', () => { - test('finds a row by its label prefix', () => { - expect(typeaheadIndex(items, 'op', -1, false)).toBe(2); - expect(typeaheadIndex(items, 'ex', -1, false)).toBe(4); - }); - - test('is case insensitive', () => { - expect(typeaheadIndex(items, 'NEW', -1, false)).toBe(0); - }); - - test('skips a disabled match', () => { - // "Save" is disabled and is the only S row, so nothing matches. - expect(typeaheadIndex(items, 's', -1, false)).toBe(-1); - }); - - test('keeps the current row while the buffer grows', () => { - expect(typeaheadIndex(items, 'ed', 5, true)).toBe(5); - }); - - test('cycles to the next match when the buffer restarts', () => { - const rows = [ - { id: 'a', label: 'Edit' }, - { id: 'b', label: 'Export' }, - { id: 'c', label: 'Extend' }, - ]; - expect(typeaheadIndex(rows, 'e', -1, false)).toBe(0); - expect(typeaheadIndex(rows, 'e', 0, false)).toBe(1); - expect(typeaheadIndex(rows, 'e', 1, false)).toBe(2); - expect(typeaheadIndex(rows, 'e', 2, false)).toBe(0); - }); - - test('returns the current index when nothing matches', () => { - expect(typeaheadIndex(items, 'zz', 2, false)).toBe(2); - }); -}); - -describe('navigate', () => { - const state = index => ({ index, typed: '', typedAt: 0 }); - - test('Down moves to the next selectable row and wraps', () => { - expect(navigate({ items, key: 'down', state: state(-1) })).toEqual({ - state: state(0), - action: 'none', - }); - expect(navigate({ items, key: 'down', state: state(5) }).state.index).toBe( - 0, - ); - }); - - test('Up moves backwards and wraps', () => { - expect(navigate({ items, key: 'up', state: state(0) }).state.index).toBe(5); - expect(navigate({ items, key: 'up', state: state(-1) }).state.index).toBe( - 5, - ); - }); - - test('Home and End go to the first and last selectable rows', () => { - expect(navigate({ items, key: 'home', state: state(4) }).state.index).toBe( - 0, - ); - expect(navigate({ items, key: 'end', state: state(0) }).state.index).toBe( - 5, - ); - }); - - test('Right opens a submenu only on a submenu row', () => { - expect(navigate({ items, key: 'right', state: state(4) }).action).toBe( - 'openSubmenu', - ); - expect(navigate({ items, key: 'right', state: state(2) }).action).toBe( - 'none', - ); - expect(navigate({ items, key: 'right', state: state(-1) }).action).toBe( - 'none', - ); - }); - - test('Left and Escape close a level', () => { - expect(navigate({ items, key: 'left', state: state(2) }).action).toBe( - 'closeLevel', - ); - expect(navigate({ items, key: 'escape', state: state(2) }).action).toBe( - 'closeLevel', - ); - expect(navigate({ items, key: 'Esc', state: state(2) }).action).toBe( - 'closeLevel', - ); - }); - - test('Enter activates a row and opens a submenu', () => { - expect(navigate({ items, key: 'enter', state: state(2) }).action).toBe( - 'activate', - ); - expect(navigate({ items, key: 'enter', state: state(4) }).action).toBe( - 'openSubmenu', - ); - expect(navigate({ items, key: 'enter', state: state(-1) }).action).toBe( - 'none', - ); - expect(navigate({ items, key: 'enter', state: state(3) }).action).toBe( - 'none', - ); - }); - - test('Space activates like Enter', () => { - expect(navigate({ items, key: ' ', state: state(2) }).action).toBe( - 'activate', - ); - }); - - test('type-to-select moves the highlight and accumulates', () => { - const first = navigate({ - items, - key: 'o', - state: state(-1), - now: 1000, - }); - expect(first.state.index).toBe(2); - expect(first.state.typed).toBe('o'); - const second = navigate({ - items, - key: 'p', - state: first.state, - now: 1100, - }); - expect(second.state.typed).toBe('op'); - expect(second.state.index).toBe(2); - }); - - test('the buffer expires after the timeout', () => { - const first = navigate({ items, key: 'e', state: state(-1), now: 1000 }); - expect(first.state.typed).toBe('e'); - const later = navigate({ - items, - key: 'n', - state: first.state, - now: 1000 + TYPEAHEAD_TIMEOUT_MS + 1, - }); - // The old buffer is gone, so the new key starts one of its own. - expect(later.state.typed).toBe('n'); - expect(later.state.index).toBe(0); - }); - - test('a modifier turns a character into a shortcut, not type-ahead', () => { - const result = navigate({ - items, - key: 'k', - state: EMPTY_NAVIGATION, - now: 1000, - modifiers: { meta: true }, - }); - expect(result.state).toEqual(EMPTY_NAVIGATION); - expect(result.action).toBe('none'); - }); - - test('unknown keys leave the state alone', () => { - const before = state(2); - expect(navigate({ items, key: 'f13', state: before })).toEqual({ - state: before, - action: 'none', - }); - }); -}); - -describe('theme', () => { - test('the built-in themes have every token', () => { - for (const theme of [light, dark]) { - for (const token of [ - 'background', - 'foreground', - 'mutedForeground', - 'separator', - 'border', - 'highlightBackground', - 'highlightForeground', - 'disabledForeground', - 'shadow', - 'fontSize', - 'rowHeight', - 'paddingX', - 'paddingY', - 'radius', - 'minWidth', - 'maxWidth', - ]) { - expect(theme[token]).toBeDefined(); - } - expect(theme.minWidth).toBeLessThan(theme.maxWidth); - } - expect(light.background).not.toBe(dark.background); - }); - - test('merging applies the override', () => { - const merged = mergeTheme(light, { - background: '#000000', - fontSize: 16, - }); - expect(merged.background).toBe('#000000'); - expect(merged.fontSize).toBe(16); - expect(merged.foreground).toBe(light.foreground); - }); - - test('an undefined field does not erase the base value', () => { - const merged = mergeTheme(light, { - background: undefined, - fontFamily: undefined, - }); - expect(merged.background).toBe(light.background); - expect(merged.fontFamily).toBe(light.fontFamily); - }); - - test('merging does not mutate the base theme', () => { - const before = { ...light }; - mergeTheme(light, { fontSize: 20 }); - expect(light).toEqual(before); - }); - - test('a missing override returns a copy', () => { - const copy = mergeTheme(light); - expect(copy).toEqual(light); - expect(copy).not.toBe(light); - }); - - test('a scheme picks the matching built-in theme', () => { - expect(themeForScheme('dark').background).toBe(dark.background); - expect(themeForScheme('light').background).toBe(light.background); - // An unknown scheme (RN reports null before the platform answers) uses light. - expect(themeForScheme(null).background).toBe(light.background); - expect(themeForScheme(undefined).background).toBe(light.background); - }); - - test('overrides only apply to their own scheme', () => { - const overrides = { dark: { background: '#101010' } }; - expect(themeForScheme('dark', overrides).background).toBe('#101010'); - expect(themeForScheme('light', overrides).background).toBe( - light.background, - ); - }); -}); - -describe('formatAccelerator', () => { - test('spells a shortcut with the macOS symbols', () => { - expect(formatAccelerator('CmdOrCtrl+Shift+K', 'macos')).toBe( - '\u2318\u21e7K', - ); - }); - - test('spells the same shortcut in words elsewhere', () => { - expect(formatAccelerator('CmdOrCtrl+Shift+K', 'windows')).toBe( - 'Ctrl+Shift+K', - ); - expect(formatAccelerator('CmdOrCtrl+Shift+K', 'linux')).toBe( - 'Ctrl+Shift+K', - ); - }); - - test('keeps a single character key as written', () => { - expect(formatAccelerator('Cmd+Z', 'macos')).toBe('\u2318Z'); - expect(formatAccelerator('Ctrl+z', 'linux')).toBe('Ctrl+z'); - }); - - test('names special keys', () => { - expect(formatAccelerator('Cmd+Enter', 'macos')).toBe('\u2318\u21a9'); - expect(formatAccelerator('Ctrl+Enter', 'windows')).toBe('Ctrl+Enter'); - }); - - test('returns an empty string for a missing or empty spec', () => { - expect(formatAccelerator(undefined, 'macos')).toBe(''); - expect(formatAccelerator(' ', 'macos')).toBe(''); - }); -}); - -describe('safe triangle', () => { - const submenuRect = { x: 400, y: 200, width: 200, height: 160 }; - - test('a right-opening submenu uses its left edge', () => { - const triangle = safeTriangleFor({ x: 200, y: 260 }, submenuRect, 'right'); - expect(triangle.nearTop).toEqual({ x: 400, y: 200 }); - expect(triangle.nearBottom).toEqual({ x: 400, y: 360 }); - }); - - test('a left-opening submenu uses its right edge', () => { - const triangle = safeTriangleFor({ x: 800, y: 260 }, submenuRect, 'left'); - expect(triangle.nearTop).toEqual({ x: 600, y: 200 }); - expect(triangle.nearBottom).toEqual({ x: 600, y: 360 }); - }); - - test('a diagonal move towards the submenu stays inside', () => { - const triangle = safeTriangleFor({ x: 200, y: 210 }, submenuRect, 'right'); - expect(isInSafeTriangle({ x: 300, y: 240 }, triangle)).toBe(true); - }); - - test('a move far above the triangle is outside', () => { - const triangle = safeTriangleFor({ x: 200, y: 260 }, submenuRect, 'right'); - expect(isInSafeTriangle({ x: 380, y: 100 }, triangle)).toBe(false); - }); - - test('a move below the origin is outside', () => { - const triangle = safeTriangleFor({ x: 200, y: 260 }, submenuRect, 'right'); - expect(isInSafeTriangle({ x: 300, y: 500 }, triangle)).toBe(false); - }); - - test('the near edge counts as inside', () => { - const triangle = safeTriangleFor({ x: 200, y: 260 }, submenuRect, 'right'); - expect(isInSafeTriangle({ x: 400, y: 280 }, triangle)).toBe(true); - expect(isInSafeTriangle({ x: 400, y: 200 }, triangle)).toBe(true); - expect(isInSafeTriangle({ x: 400, y: 360 }, triangle)).toBe(true); - }); -}); - -describe('entry helpers', () => { - test('a separator is never enabled', () => { - expect(isEnabled({ type: 'separator' })).toBe(false); - expect(isEnabled({ id: 'a', label: 'A' })).toBe(true); - expect(isEnabled({ id: 'a', label: 'A', enabled: false })).toBe(false); - }); - - test('checked only means something for a plain item', () => { - expect(isChecked({ id: 'a', label: 'A', checked: true })).toBe(true); - expect(isChecked({ id: 'a', label: 'A' })).toBe(false); - expect(isChecked({ type: 'submenu', label: 'S', items: [] })).toBe(false); - }); - - test('a submenu is recognised', () => { - expect(isSubmenu({ type: 'submenu', label: 'S', items: [] })).toBe(true); - expect(isSubmenu({ id: 'a', label: 'A' })).toBe(false); - }); - - test('a role item resolves with its role and gets a label', () => { - expect(entryId({ type: 'role', role: 'selectAll' })).toBe('selectAll'); - expect(entryLabel({ type: 'role', role: 'selectAll' })).toBe('Select All'); - expect(entryLabel({ type: 'role', role: 'copy', label: 'Copy text' })).toBe( - 'Copy text', - ); - expect(humanizeRole('hideOthers')).toBe('Hide Others'); - }); - - test('test ids use the id, or a slug of the label', () => { - expect(entryTestId({ id: 'open', label: 'Open' })).toBe('open'); - expect(entryTestId({ type: 'role', role: 'selectAll' })).toBe('selectAll'); - expect( - entryTestId({ type: 'submenu', label: 'More Options', items: [] }), - ).toBe('more-options'); - }); -}); - -describe('config store', () => { - test('notifies subscribers and can be reset', () => { - let calls = 0; - const unsubscribe = subscribeContextMenuConfig(() => { - calls += 1; - }); - setContextMenuTheme({ dark: { background: '#000000' } }); - expect(calls).toBe(1); - expect(contextMenuConfig().theme.dark.background).toBe('#000000'); - unsubscribe(); - setContextMenuConfig({}); - expect(calls).toBe(1); - expect(contextMenuConfig().theme).toBeUndefined(); - }); -}); - -describe('renderers store', () => { - const Row = () => null; - const Surface = () => null; - - test('replacing one slot keeps the others and the theme', () => { - setContextMenuConfig({ theme: { dark: { background: '#000000' } } }); - setContextMenuRenderers({ Row }); - expect(contextMenuRenderers().Row).toBe(Row); - // Setting renderers must not drop unrelated config: the two setters share a - // store, and a replacement that silently reset the theme would be a mystery. - expect(contextMenuTheme().dark.background).toBe('#000000'); - - setContextMenuRenderers({ Row, Surface }); - expect(contextMenuRenderers().Row).toBe(Row); - expect(contextMenuRenderers().Surface).toBe(Surface); - - setContextMenuRenderers(undefined); - expect(contextMenuRenderers()).toBeUndefined(); - expect(contextMenuTheme().dark.background).toBe('#000000'); - setContextMenuConfig({}); - }); - - test('an explicit undefined slot means the built-in', () => { - setContextMenuRenderers({ Row, Surface: undefined }); - expect(contextMenuRenderers().Row).toBe(Row); - // `undefined` is the documented way back to the built-in for one slot, so the - // host's `?? MenuSurface` fallback has to see it rather than an empty object. - expect(contextMenuRenderers().Surface).toBeUndefined(); - setContextMenuConfig({}); - }); -}); - -describe('presentation resolution', () => { - test('the app default applies only to default, never to an explicit choice', () => { - setContextMenuPresentation('custom'); - expect(contextMenuPresentation()).toBe('custom'); - // An explicit 'native' must win over the app default, otherwise an app that - // set a custom default could never ask for the platform's menu. - setContextMenuPresentation('native'); - expect(contextMenuPresentation()).toBe('native'); - }); - - test('unset means default, which the platform decides', () => { - setContextMenuPresentation(undefined); - expect(contextMenuPresentation()).toBe('default'); - }); -}); - -describe('registry', () => { - const handle = { open: () => Promise.resolve(null), close: () => {} }; - - test('registers, looks up and unregisters by window id', () => { - const remove = registerContextMenuHost(7, handle); - expect(hasContextMenuHost(7)).toBe(true); - expect(contextMenuHostFor(7)).toBe(handle); - expect(contextMenuWindowIds()).toContain(7); - remove(); - expect(contextMenuHostFor(7)).toBeNull(); - }); - - test('a second registration for one window wins', () => { - const first = { open: () => Promise.resolve(null), close: () => {} }; - const second = { open: () => Promise.resolve(null), close: () => {} }; - const removeFirst = registerContextMenuHost(8, first); - registerContextMenuHost(8, second); - expect(contextMenuHostFor(8)).toBe(second); - // The stale unmount must not remove the replacement. - removeFirst(); - expect(contextMenuHostFor(8)).toBe(second); - unregisterContextMenuHost(8); - expect(contextMenuHostFor(8)).toBeNull(); - }); - - test('unregistering a specific host leaves another one alone', () => { - const other = { open: () => Promise.resolve(null), close: () => {} }; - registerContextMenuHost(9, handle); - unregisterContextMenuHost(9, other); - expect(contextMenuHostFor(9)).toBe(handle); - unregisterContextMenuHost(9, handle); - expect(contextMenuHostFor(9)).toBeNull(); - }); - - test('an unknown window has no host', () => { - expect(contextMenuHostFor(12345)).toBeNull(); - expect(hasContextMenuHost(12345)).toBe(false); - }); -}); - -/** - * A level with one 26px row per entry, starting at `y` inside the panel. The - * rows are what the host learns from each row's `onLayout`; the size is what the - * panel reports about itself. - */ -function level({ size, parentIndex = 0, rows, openedAt = null }) { - return { - items: [], - highlightedIndex: -1, - size, - rows, - parentIndex, - openedAt, - }; -} - -/** Rows laid out top to bottom with the given height, plus the panel's padding. */ -function rowsOf(count, height = 26, paddingTop = 4) { - const rows = {}; - for (let index = 0; index < count; index += 1) { - rows[index] = { y: paddingTop + index * height, height }; - } - return rows; -} - -describe('placeLevels chaining', () => { - const bigWindow = { width: 1000, height: 800 }; - - test('a three-level chain attaches each level to its own parent row', () => { - // Root at (100, 100), 200x150, rows 26px tall from y=4. - // Row 1 of the root is therefore at window y = 100 + 4 + 26 = 130. - const root = level({ - size: { width: 200, height: 150 }, - rows: rowsOf(5), - }); - // The submenu opens beside the root's row 1 at x = 300, y = 130; its own - // row 2 is at y = 130 + 4 + 2*26 = 190. - const submenu = level({ - size: { width: 180, height: 120 }, - parentIndex: 1, - rows: rowsOf(4), - }); - // The third level must use the submenu's row 2, not the root's row 1. - const subSubmenu = level({ - size: { width: 160, height: 90 }, - parentIndex: 2, - rows: rowsOf(3), - }); - - const placed = placeLevels( - [root, submenu, subSubmenu], - { x: 100, y: 100 }, - bigWindow, - ); - - expect(placed[0]).toEqual({ point: { x: 100, y: 100 }, side: null }); - expect(placed[1]).toEqual({ point: { x: 300, y: 130 }, side: 'right' }); - // x = 300 + 180 = 480; y = 130 + (4 + 2*26) = 186, i.e. the submenu's own - // row 2. Using the root's placement instead would give y = 130, which is the - // chaining bug this asserts against. - expect(placed[2]).toEqual({ point: { x: 480, y: 186 }, side: 'right' }); - }); - - test('a third level follows its parent, not the root, on every axis', () => { - // Put the root's referenced row and the submenu's referenced row at - // different y values, then check the third level matches the submenu. - const root = level({ - size: { width: 200, height: 40 }, - rows: rowsOf(3), - }); - const submenu = level({ - size: { width: 200, height: 200 }, - parentIndex: 2, - rows: rowsOf(6), - }); - const subSubmenu = level({ - size: { width: 100, height: 100 }, - parentIndex: 5, - rows: rowsOf(2), - }); - const placed = placeLevels( - [root, submenu, subSubmenu], - { x: 50, y: 50 }, - bigWindow, - ); - const rootRowY = 50 + 4 + 2 * 26; - const submenuRowY = rootRowY + 4 + 5 * 26; - expect(placed[1].point).toEqual({ x: 250, y: rootRowY }); - expect(placed[2].point).toEqual({ x: 450, y: submenuRowY }); - expect(placed[2].point.y).not.toBe(rootRowY); - }); - - test('an unmeasured parent yields null and propagates it downwards', () => { - const root = level({ size: { width: 200, height: 150 }, rows: rowsOf(5) }); - const unmeasured = level({ - size: null, - parentIndex: 0, - rows: {}, - }); - const below = level({ - size: { width: 100, height: 100 }, - parentIndex: 0, - rows: rowsOf(2), - }); - let placed; - expect(() => { - placed = placeLevels( - [root, unmeasured, below], - { x: 10, y: 10 }, - bigWindow, - ); - }).not.toThrow(); - expect(placed[0]).toEqual({ point: { x: 10, y: 10 }, side: null }); - expect(placed[1]).toBeNull(); - // Its parent has no position, so it cannot be placed either; it must not - // silently fall back to the root. - expect(placed[2]).toBeNull(); - }); - - test('a level whose parent row has not been measured yet yields null', () => { - const root = level({ size: { width: 200, height: 150 }, rows: {} }); - const child = level({ - size: { width: 100, height: 100 }, - parentIndex: 0, - rows: rowsOf(2), - }); - const placed = placeLevels([root, child], { x: 10, y: 10 }, bigWindow); - expect(placed[0]).not.toBeNull(); - expect(placed[1]).toBeNull(); - }); - - test('a missing anchor or window size places nothing', () => { - const root = level({ size: { width: 200, height: 150 }, rows: rowsOf(5) }); - expect(placeLevels([root], null, bigWindow)).toEqual([null]); - expect(placeLevels([root], { x: 1, y: 1 }, null)).toEqual([null]); - expect(placeLevels([root], undefined, bigWindow)).toEqual([null]); - expect(placeLevels([root], { x: 1, y: 1 }, undefined)).toEqual([null]); - }); - - test('a chain running off the bottom is clamped level by level', () => { - const window = { width: 600, height: 300 }; - const root = level({ - size: { width: 150, height: 200 }, - rows: rowsOf(8), - }); - const child = level({ - size: { width: 150, height: 180 }, - parentIndex: 7, - rows: rowsOf(6), - }); - const grandchild = level({ - size: { width: 150, height: 160 }, - parentIndex: 5, - rows: rowsOf(5), - }); - // Anchor near the bottom so the root itself has to flip up. - const placed = placeLevels( - [root, child, grandchild], - { x: 20, y: 280 }, - window, - ); - for (const entry of placed) { - expect(entry).not.toBeNull(); - expect(entry.point.y).toBeGreaterThanOrEqual(0); - expect(entry.point.x).toBeGreaterThanOrEqual(0); - expect(entry.point.y).toBeLessThanOrEqual(window.height); - expect(entry.point.x).toBeLessThanOrEqual(window.width); - } - // Each level's own size still fits inside the window. - expect(placed[1].point.y + 180).toBeLessThanOrEqual(window.height); - expect(placed[2].point.y + 160).toBeLessThanOrEqual(window.height); - }); - - test('a submenu on the last row flips up while the root stays put', () => { - const window = { width: 800, height: 800 }; - // The root fits comfortably at the anchor, so it must not move. - const root = level({ - size: { width: 200, height: 240 }, - rows: rowsOf(9), - }); - // The child opens beside the last row, which is near the bottom, and is - // taller than the space left below it, so it has to be clamped upwards. - const child = level({ - size: { width: 200, height: 200 }, - parentIndex: 8, - rows: rowsOf(7), - }); - const placed = placeLevels([root, child], { x: 100, y: 300 }, window); - expect(placed[0]).toEqual({ point: { x: 100, y: 300 }, side: null }); - // The last row is at 300 + 4 + 8*26 = 512; a 200px menu would end at 712, - // which still fits in 800, so clamping only starts past the margin. - expect(placed[1].point.y).toBe(512); - expect(placed[1].point.y + 200).toBeLessThanOrEqual(window.height); - }); - - test('a submenu near the bottom is pulled up without moving the root', () => { - const window = { width: 800, height: 600 }; - const root = level({ - size: { width: 200, height: 240 }, - rows: rowsOf(9), - }); - const child = level({ - size: { width: 200, height: 200 }, - parentIndex: 8, - rows: rowsOf(7), - }); - // Last root row at 400 + 4 + 8*26 = 612, past the bottom, so the root flips. - const placed = placeLevels([root, child], { x: 100, y: 400 }, window); - expect(placed[0].point).toEqual({ x: 100, y: 400 - 240 }); - expect(placed[1].point.y + 200).toBeLessThanOrEqual(window.height); - expect(placed[1].point.y).toBeGreaterThanOrEqual(DEFAULT_MENU_MARGIN); - }); - - test('is deterministic and leaves its input untouched', () => { - const root = level({ size: { width: 200, height: 150 }, rows: rowsOf(5) }); - const child = level({ - size: { width: 180, height: 120 }, - parentIndex: 1, - rows: rowsOf(4), - }); - const levels = [root, child]; - const snapshot = JSON.parse(JSON.stringify(levels)); - const first = placeLevels(levels, { x: 100, y: 100 }, bigWindow); - const second = placeLevels(levels, { x: 100, y: 100 }, bigWindow); - expect(second).toEqual(first); - expect(levels).toEqual(snapshot); - expect(levels[0]).toBe(root); - expect(levels[0].rows).toBe(root.rows); - }); - - test('one level places on its own like placeRootMenu', () => { - const root = level({ size: { width: 200, height: 150 }, rows: rowsOf(5) }); - const placed = placeLevels([root], { x: 950, y: 780 }, bigWindow); - expect(placed[0].point).toEqual( - placeRootMenu({ - anchor: { x: 950, y: 780 }, - menuSize: { width: 200, height: 150 }, - windowSize: bigWindow, - }), - ); - }); - - test('an empty chain is an empty array', () => { - expect(placeLevels([], { x: 0, y: 0 }, bigWindow)).toEqual([]); - }); -}); - -describe('rowRect', () => { - test('adds the panel position to a row measured relative to it', () => { - const root = level({ - size: { width: 200, height: 150 }, - rows: rowsOf(5), - }); - expect(rowRectOf(root, { x: 100, y: 100 }, 1)).toEqual({ - x: 100, - y: 100 + 4 + 26, - width: 200, - height: 26, - }); - }); - - test('returns null without a measurement', () => { - const root = level({ size: null, rows: rowsOf(2) }); - expect(rowRectOf(root, { x: 0, y: 0 }, 0)).toBeNull(); - const noRows = level({ size: { width: 10, height: 10 }, rows: {} }); - expect(rowRectOf(noRows, { x: 0, y: 0 }, 3)).toBeNull(); - }); -}); diff --git a/vendor/react-native-gpui/packages/core/desktop.ts b/vendor/react-native-gpui/packages/core/desktop.ts deleted file mode 100644 index 29c3ea0685..0000000000 --- a/vendor/react-native-gpui/packages/core/desktop.ts +++ /dev/null @@ -1,177 +0,0 @@ -/** - * `react-native-gpui/desktop` — the desktop-shell public API. - * - * ```ts - * import {Desktop} from '@react-native-gpui/core/desktop'; - * ``` - * - * `Menu`, `ContextMenu`, `Tray`, `DesktopWindow` and `PerfMonitor` are added by - * the feature steps; `Desktop` covers app info and capability checks. Each of - * them calls a method of the `GpuiDesktop` TurboModule, whose spec lists every - * command the shell accepts. - * - * @format - */ - -export { - capabilities, - DesktopError, - desktopModule, - isDesktopAvailable, - platform, - request, - useClientDecorations, -} from './src-gpui/src/private/desktop'; - -export type { - DesktopCapabilities, - DesktopErrorCode, -} from './src-gpui/src/private/desktop'; - -export { - DesktopWindow, - useDesktopWindow, - useWindowFocus, - useWindowState, -} from './src-gpui/src/private/desktop/windows'; - -export type { - OpenWindowOptions, - Subscription, - WindowBounds, - WindowEvent, - WindowEventName, - WindowState, -} from './src-gpui/src/private/desktop/windows'; - -export { - installDesktopWindowContext, - MAIN_WINDOW_ID, - useDesktopWindowId, -} from './src-gpui/src/private/desktop/windowContext'; - -export { default as ScrollBar } from './src-gpui/src/private/specs/DesktopScrollBarNativeComponent'; -export { TitleBar } from './src-gpui/src/private/desktop/TitleBar'; -export { WindowControl } from './src-gpui/src/private/desktop/WindowControl'; - -export type { - NativeProps as ScrollBarProps, - ScrollBarEvent, -} from './src-gpui/src/private/specs/DesktopScrollBarNativeComponent'; -export type { TitleBarProps } from './src-gpui/src/private/desktop/TitleBar'; -export type { - WindowControlAction, - WindowControlProps, - WindowControlState, -} from './src-gpui/src/private/desktop/WindowControl'; - -export { ApplicationMenu, Menu } from './src-gpui/src/private/desktop/menu'; - -export { - ContextMenu, - ContextMenuView, -} from './src-gpui/src/private/desktop/contextMenu'; - -export { PerfMonitor } from './src-gpui/src/private/desktop/perfMonitor'; -export { Network } from './src-gpui/src/private/desktop/network'; - -export { - shortcutId, - Shortcut, - Shortcuts, -} from './src-gpui/src/private/desktop/shortcuts'; - -export { NativeRoot } from './src-gpui/src/private/desktop/nativeRoot/NativeRoot'; -export type { NativeRootProps } from './src-gpui/src/private/desktop/nativeRoot/NativeRoot'; -export { NativeVirtualList } from './src-gpui/src/private/desktop/nativeRoot/NativeVirtualList'; -export type { - NativeVirtualListHandle, - NativeVirtualListProps, - ScrollAlign, -} from './src-gpui/src/private/desktop/nativeRoot/NativeVirtualList'; -export { NativeSlot } from './src-gpui/src/private/desktop/nativeRoot/NativeSlot'; -export type { NativeSlotProps } from './src-gpui/src/private/desktop/nativeRoot/NativeSlot'; - -export { - ShortcutScope, - useShortcut, - useShortcutScope, -} from './src-gpui/src/private/desktop/useShortcut'; - -export type { - InstalledShortcut, - ShortcutDefinition, - ShortcutEvent, - ShortcutFailure, - ShortcutHandler, - ShortcutResolution, -} from './src-gpui/src/private/desktop/shortcuts'; - -export type { - ShortcutOptions, - ShortcutScopeProps, -} from './src-gpui/src/private/desktop/useShortcut'; - -export { - DragDrop, - DragPreview, - useDragAutoScroll, - useDragState, - useIsDragging, -} from './src-gpui/src/private/desktop/dragDrop'; -export type { - DragAutoScrollOptions, - DragPreviewProps, - DragState, -} from './src-gpui/src/private/desktop/dragDrop'; -export { App } from './src-gpui/src/private/desktop/app'; -export { Tray } from './src-gpui/src/private/desktop/tray'; - -export type { - TrayOptions, - TrayState, -} from './src-gpui/src/private/desktop/tray'; - -export type { PerfMetrics } from './src-gpui/src/private/desktop/perfMonitor'; -export type { - NetworkSettings, - ProxyConfig, -} from './src-gpui/src/private/desktop/network'; - -export type { - DesktopContextMenuEvent, - DesktopContextMenuEventData, - DesktopWheelEvent, - DesktopWheelEventData, -} from './types'; -export type { - ContextMenuOpenEvent, - ContextMenuOptions, - ContextMenuPresentation, - ContextMenuViewProps, -} from './src-gpui/src/private/desktop/contextMenu'; - -export type { - ApplicationMenuProps, - DesktopIcon, - MenuDescription, - MenuItemPatch, - MenuItemSpec, - MenuPressEvent, - MenuRole, -} from './src-gpui/src/private/desktop/menu'; - -// The augmentation lives in the published `types.d.ts`, which an app's -// `react-native-gpui-env.d.ts` references. Importing it here as well means an app -// that imports this desktop entry needs nothing further. -import type {} from './types'; - -import { capabilities, request } from './src-gpui/src/private/desktop'; -import type { DesktopAppInfo } from './src-gpui/src/private/specs/NativeGpuiDesktop'; - -export type { DesktopAppInfo }; - -export const Desktop = { - getInfo: () => request(native => native.appInfo()), - capabilities, -}; diff --git a/vendor/react-native-gpui/packages/core/diagnostics.ts b/vendor/react-native-gpui/packages/core/diagnostics.ts deleted file mode 100644 index 043d60c454..0000000000 --- a/vendor/react-native-gpui/packages/core/diagnostics.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { AppState } from 'react-native'; - -type ErrorHandler = (error: unknown, isFatal?: boolean) => void; -type ErrorUtilsLike = { - getGlobalHandler?: () => ErrorHandler | undefined; - setGlobalHandler?: (handler: ErrorHandler) => void; -}; - -let enabled = false; - -/** - * Writes uncaught JS errors and AppState changes to the console with a - * timestamp, to trace a window that goes blank after a long time in the - * background. Off unless an app calls it: an uncaught error is otherwise - * reported twice, and every focus change adds a console line. - */ -export function enableDiagnostics(): void { - if (enabled || __DEV__ === false) { - return; - } - enabled = true; - const stamp = () => new Date().toISOString(); - const utils = (globalThis as { ErrorUtils?: ErrorUtilsLike }).ErrorUtils; - if (utils && typeof utils.setGlobalHandler === 'function') { - const previous = utils.getGlobalHandler && utils.getGlobalHandler(); - utils.setGlobalHandler((error, isFatal) => { - const detail = error as { stack?: string; message?: string } | null; - console.error( - `[rn-gpui] ${stamp()} ${isFatal ? 'fatal' : 'non-fatal'} JS error: ${ - (detail && (detail.stack || detail.message)) || String(error) - }`, - ); - if (previous) { - previous(error, isFatal); - } - }); - } - AppState.addEventListener('change', state => - console.log(`[rn-gpui] ${stamp()} app state -> ${state}`), - ); -} diff --git a/vendor/react-native-gpui/packages/core/index.desktop.js b/vendor/react-native-gpui/packages/core/index.desktop.js deleted file mode 100644 index d8780966a7..0000000000 --- a/vendor/react-native-gpui/packages/core/index.desktop.js +++ /dev/null @@ -1,14 +0,0 @@ -// Keep the GPUI entry aligned with React Native's public JavaScript surface. -// -// The desktop-shell wrapper component is installed here: the host -// passes each window's surface `windowId` as `initialProps`, and the wrapper -// turns it into the `DesktopWindowContext` that `DesktopWindow.current()` reads. -// Doing it on the platform entry guarantees it happens before the app's own -// `AppRegistry.registerComponent` runs. -const { - installDesktopWindowContext, -} = require('./src-gpui/src/private/desktop/windowContext'); - -installDesktopWindowContext(); - -module.exports = require('react-native'); diff --git a/vendor/react-native-gpui/packages/core/js-engine.js b/vendor/react-native-gpui/packages/core/js-engine.js deleted file mode 100644 index 8028828754..0000000000 --- a/vendor/react-native-gpui/packages/core/js-engine.js +++ /dev/null @@ -1,52 +0,0 @@ -const fs = require('node:fs'); -const path = require('node:path'); - -const MANIFEST_PATH = ['desktop', 'autolink', 'autolink.json']; - -function installedJsEngines(projectRoot) { - const manifestPath = path.join(projectRoot, ...MANIFEST_PATH); - if (!fs.existsSync(manifestPath)) return []; - try { - const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); - return Array.isArray(manifest.jsEngines) ? manifest.jsEngines : []; - } catch { - return []; - } -} - -/** - * The engine this run uses, mirroring the runtime's selection: the - * `RN_GPUI_JS_ENGINE` override, otherwise the only installed engine. Returns - * null when the choice is ambiguous or nothing is installed, in which case the - * runtime reports it. - */ -function activeJsEngine(projectRoot) { - const engines = installedJsEngines(projectRoot); - const requested = process.env.RN_GPUI_JS_ENGINE; - if (requested) { - return engines.find(engine => engine.name === requested) ?? null; - } - return engines.length === 1 ? engines[0] : null; -} - -function activeJsEngineBundle(projectRoot) { - const engine = activeJsEngine(projectRoot); - if (!engine || !engine.bundle) return null; - // Absolute path: the manifest records where the package actually lives, which - // may be a hoisted or linked install rather than the app's own node_modules. - return require(engine.bundle); -} - -function activeJsEngineBundleExtension(projectRoot) { - const bundle = activeJsEngineBundle(projectRoot); - return typeof bundle?.bundleExtension === 'string' - ? bundle.bundleExtension - : '.js'; -} - -module.exports = { - installedJsEngines, - activeJsEngine, - activeJsEngineBundle, - activeJsEngineBundleExtension, -}; diff --git a/vendor/react-native-gpui/packages/core/metro-babel-transformer.js b/vendor/react-native-gpui/packages/core/metro-babel-transformer.js deleted file mode 100644 index 22344ebf39..0000000000 --- a/vendor/react-native-gpui/packages/core/metro-babel-transformer.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * React Native's Babel transformer with Flow enums turned into runtime objects - * before the preset's own plugins run. - * - * `@react-native/babel-preset` lists `babel-plugin-transform-flow-enums` after - * `@babel/plugin-transform-flow-strip-types`, and the strip plugin removes an - * `export enum` first, so a module such as `VirtualView` loses its enums and - * fails at run time with a ReferenceError. App-level plugins run ahead of the - * preset's. - */ -const path = require('path'); -const upstream = require('@react-native/metro-babel-transformer'); - -const presetDir = path.dirname( - require.resolve('@react-native/babel-preset/package.json'), -); -const flowEnums = require( - require.resolve('babel-plugin-transform-flow-enums', { paths: [presetDir] }), -); - -module.exports = { - ...upstream, - transform: args => - upstream.transform({ - ...args, - plugins: [...(args.plugins ?? []), flowEnums], - }), - getCacheKey: () => - `${upstream.getCacheKey?.() ?? ''}$${require('crypto') - .createHash('sha1') - .update( - require('fs').readFileSync( - path.join(__dirname, 'metro-babel-transformer.js'), - ), - ) - .digest('hex')}`, -}; diff --git a/vendor/react-native-gpui/packages/core/metro-transform-worker.js b/vendor/react-native-gpui/packages/core/metro-transform-worker.js deleted file mode 100644 index 12d85baba5..0000000000 --- a/vendor/react-native-gpui/packages/core/metro-transform-worker.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Metro's own transform worker, except that `Platform.OS` is left alone. - * - * Metro always inlines `Platform.OS` and `Platform.select` as the platform it is - * building for, which is `desktop`. The desktop shell runs on macOS, Windows and - * Linux from the same bundle, so the operating system is only known at runtime: - * `Platform.desktop.js` reads it from the shell, and `Platform.OS` has to be that - * value rather than a constant folded in at build time. - */ -const path = require('path'); -const crypto = require('crypto'); -const fs = require('fs'); - -const metroDir = path.dirname(require.resolve('metro/package.json')); -const worker = require( - require.resolve('metro-transform-worker', { paths: [metroDir] }), -); - -const selfKey = crypto - .createHash('sha1') - .update(fs.readFileSync(path.join(__dirname, 'metro-transform-worker.js'))) - .digest('hex'); - -module.exports = { - transform: (config, projectRoot, filename, data, options) => - worker.transform(config, projectRoot, filename, data, { - ...options, - inlinePlatform: false, - }), - getCacheKey: (config, opts) => - `${worker.getCacheKey(config, opts)}$${selfKey}`, -}; diff --git a/vendor/react-native-gpui/packages/core/metro-transform-worker.test.js b/vendor/react-native-gpui/packages/core/metro-transform-worker.test.js deleted file mode 100644 index f9e1197797..0000000000 --- a/vendor/react-native-gpui/packages/core/metro-transform-worker.test.js +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; -import { createRequire } from 'node:module'; - -const require = createRequire(import.meta.url); -const metroDir = require('node:path').dirname( - require.resolve('metro/package.json'), -); -const workerPath = require.resolve('metro-transform-worker', { - paths: [metroDir], -}); - -describe('metro-transform-worker', () => { - it('turns off the build-time Platform.OS inlining and nothing else', async () => { - const worker = require(workerPath); - const transform = vi.spyOn(worker, 'transform').mockResolvedValue('out'); - const ours = require('./metro-transform-worker.js'); - const options = { dev: true, platform: 'desktop', inlinePlatform: true }; - await expect( - ours.transform({}, '/root', 'a.js', '', options), - ).resolves.toBe('out'); - expect(transform).toHaveBeenCalledWith({}, '/root', 'a.js', '', { - dev: true, - platform: 'desktop', - inlinePlatform: false, - }); - expect(options.inlinePlatform).toBe(true); - transform.mockRestore(); - }); -}); diff --git a/vendor/react-native-gpui/packages/core/metro.config.js b/vendor/react-native-gpui/packages/core/metro.config.js deleted file mode 100644 index c8c845e3a4..0000000000 --- a/vendor/react-native-gpui/packages/core/metro.config.js +++ /dev/null @@ -1,336 +0,0 @@ -const fs = require('fs'); -const path = require('path'); -const { createRequire } = require('module'); -const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); -const { activeJsEngineBundle } = require('./js-engine'); -const { resolveRenderer } = require('./renderer'); - -const PACKAGE_NAME = '@react-native-gpui/core'; -const PACKAGE_DIR = __dirname; -const ENTRY = path.join(PACKAGE_DIR, 'index.desktop.js'); -const SETUP_ENV = path.join(PACKAGE_DIR, 'setup-env.js'); -const SRC_DIR = path.join(PACKAGE_DIR, 'src-gpui'); -const DESKTOP_SUFFIX = /\.desktop\.(?:js|ts|tsx)$/; -// Some React Native modules ship only `.ios.js`/`.android.js`; desktop uses iOS's. -const FALLBACK_PLATFORM = 'ios'; - -const isInside = (file, dir) => file.startsWith(dir + path.sep); - -// The first usable target of a package.json `exports` entry. -function exportsTarget(value) { - if (typeof value === 'string') return value; - if (Array.isArray(value)) { - for (const entry of value) { - const target = exportsTarget(entry); - if (target) return target; - } - return null; - } - if (value && typeof value === 'object') { - if (typeof value.default === 'string') return value.default; - for (const entry of Object.values(value)) { - const target = exportsTarget(entry); - if (target) return target; - } - } - return null; -} - -// `react-native/` inside another React Native tree: entries such as -// `./asset-registry` only resolve through the `exports` map. -function subpathIn(treeDir, subpath) { - let exportsMap; - try { - exportsMap = JSON.parse( - fs.readFileSync(path.join(treeDir, 'package.json'), 'utf8'), - ).exports; - } catch { - return `${treeDir}/${subpath}`; - } - const target = exportsTarget(exportsMap?.[`./${subpath}`]); - return path.join( - treeDir, - target?.startsWith('./') ? target.slice(2) : subpath, - ); -} -const withFilePath = (resolution, filePath) => ({ ...resolution, filePath }); - -// "/" for a file under node_modules, so an override -// applies to every installed copy of the package. -function packageKey(filePath) { - const parts = filePath.split(path.sep); - const index = parts.lastIndexOf('node_modules'); - return index === -1 ? null : parts.slice(index + 1).join('/'); -} - -// The nearest repository or workspace root above `directory`, or null. -function findTreeRoot(directory) { - for (let current = directory; ; current = path.dirname(current)) { - if (fs.existsSync(path.join(current, '.git'))) return current; - try { - const manifest = path.join(current, 'package.json'); - if (JSON.parse(fs.readFileSync(manifest, 'utf8')).workspaces) { - return current; - } - } catch {} - if (path.dirname(current) === current) return null; - } -} - -// Every node_modules from `directory` up to its tree root (only its own when -// there is no root), never above it. -function nodeModulesUpToTreeRoot(directory) { - const stop = findTreeRoot(directory) ?? directory; - const found = []; - for (let current = directory; ; current = path.dirname(current)) { - const modules = path.join(current, 'node_modules'); - if (fs.existsSync(modules)) found.push(modules); - if (current === stop || path.dirname(current) === current) return found; - } -} - -// `src-gpui/.desktop.js` replaces React Native's `.js` (and its -// platform variants). -function reactNativeOverrides(reactNativeDir) { - const overrides = new Map(); - const walk = directory => { - for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { - const file = path.join(directory, entry.name); - if (entry.isDirectory()) walk(file); - if (!DESKTOP_SUFFIX.test(entry.name)) continue; - const base = path - .relative(SRC_DIR, file) - .replace(DESKTOP_SUFFIX, '') - .split(path.sep) - .join('/'); - for (const variant of ['.js', '.native.js', '.ios.js', '.android.js']) { - if (fs.existsSync(path.join(reactNativeDir, base + variant))) { - overrides.set(`react-native/${base}${variant}`, file); - } - } - } - }; - walk(SRC_DIR); - return overrides; -} - -// A library package declares its replacements in react-native.config.js as -// `platforms.desktop.sourceOverrides: { '/': './' }`. -function libraryOverrides(packageDirs) { - const overrides = new Map(); - for (const packageDir of packageDirs) { - const configFile = path.join(packageDir, 'react-native.config.js'); - if (!fs.existsSync(configFile)) continue; - const declared = - require(configFile).dependency?.platforms?.desktop?.sourceOverrides ?? {}; - for (const [key, target] of Object.entries(declared)) { - overrides.set(key, path.resolve(packageDir, target)); - } - } - return overrides; -} - -// React Native's `Foo.js` deep-import shims re-export `./Foo` and expect a -// platform variant to win, which never happens for gpui. -const SHIM = - /^(?:import ([\w$]+) from '\.\/\1'; ?export default \1;?|export \* from '\.\/[\w$]+';?)$/; -const shims = new Map(); -function isReExportShim(filePath) { - if (!shims.has(filePath)) { - const code = fs - .readFileSync(filePath, 'utf8') - .replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '') - .replace(/\s+/g, ' ') - .trim(); - shims.set(filePath, SHIM.test(code)); - } - return shims.get(filePath); -} - -function makeMetroConfig({ projectRoot = process.cwd() } = {}) { - const appRequire = createRequire(path.join(projectRoot, 'package.json')); - // Loom's tree replaces the installed package everywhere React Native's - // JavaScript is read; Fabric keeps the installed one. - const selection = resolveRenderer(projectRoot); - const loomDir = - selection.renderer === 'loom' ? selection.reactNativeDir : null; - const reactNativeDir = selection.reactNativeDir; - const reactNativeEntry = loomDir - ? path.join(loomDir, 'index.js') - : appRequire.resolve('react-native'); - // `react-native/` as the selected tree names it. - const inReactNative = moduleName => - loomDir && moduleName.startsWith('react-native/') - ? subpathIn(loomDir, moduleName.slice('react-native/'.length)) - : moduleName; - // "react-native/" for a file of the selected tree, else the - // file's package key. - const fileKey = filePath => - loomDir && isInside(filePath, loomDir) - ? `react-native/${path.relative(loomDir, filePath).split(path.sep).join('/')}` - : packageKey(filePath); - const appPackage = JSON.parse( - fs.readFileSync(path.join(projectRoot, 'package.json'), 'utf8'), - ); - - const nodeModulesPaths = nodeModulesUpToTreeRoot(projectRoot); - const dependencyDirs = Object.keys({ - ...appPackage.dependencies, - ...appPackage.devDependencies, - }).flatMap(name => { - const modules = nodeModulesPaths.find(dir => - fs.existsSync(path.join(dir, name)), - ); - return modules ? [fs.realpathSync(path.join(modules, name))] : []; - }); - // Linked packages (`file:`, workspaces) resolve their imports from the tree - // they live in, so Metro has to watch that tree's node_modules too. - const linkedDirs = dependencyDirs.filter( - dir => - !isInside(dir, projectRoot) && - !nodeModulesPaths.some(modules => isInside(dir, modules)), - ); - const watchFolders = [ - ...new Set([ - PACKAGE_DIR, - reactNativeDir, - ...nodeModulesPaths, - ...linkedDirs.flatMap(dir => [dir, ...nodeModulesUpToTreeRoot(dir)]), - ]), - ].filter((folder, _, all) => !all.some(other => isInside(folder, other))); - - const rnOverrides = reactNativeOverrides(reactNativeDir); - const rnOverrideFiles = new Set(rnOverrides.values()); - const overrides = new Map([ - ...rnOverrides, - ...libraryOverrides(dependencyDirs), - ]); - - const resolveWithFallback = (context, moduleName, platform) => { - try { - return context.resolveRequest(context, moduleName, platform); - } catch (error) { - try { - return context.resolveRequest(context, moduleName, FALLBACK_PLATFORM); - } catch { - throw error; - } - } - }; - - const resolveModule = (context, moduleName, platform) => { - const origin = context.originModulePath ?? ''; - // Every route to RN's setup-env goes through ours first (it adds `window`). - if ( - moduleName === 'react-native/setup-env' || - (moduleName === '../../src/setup-env' && - /[\\/]Libraries[\\/]Core[\\/]InitializeCore\.js$/.test(origin)) - ) { - const target = - origin === SETUP_ENV - ? path.join(reactNativeDir, 'src/setup-env.js') - : SETUP_ENV; - return resolveWithFallback(context, target, platform); - } - // An override keeps the relative imports of the file it replaces. - if (moduleName.startsWith('.') && rnOverrideFiles.has(origin)) { - const upstream = path - .relative(SRC_DIR, origin) - .replace(DESKTOP_SUFFIX, '.js'); - context = { - ...context, - originModulePath: path.join(reactNativeDir, upstream), - }; - } - // `react-native` means this package, except inside this package. - if (moduleName === 'react-native' || moduleName === PACKAGE_NAME) { - const target = isInside(origin, PACKAGE_DIR) ? reactNativeEntry : ENTRY; - return resolveWithFallback(context, target, platform); - } - // `@react-native-gpui/core/` is this package's file, else RN's. - if (moduleName.startsWith(`${PACKAGE_NAME}/`)) { - const subpath = moduleName.slice(PACKAGE_NAME.length + 1); - try { - return context.resolveRequest( - context, - path.join(PACKAGE_DIR, subpath), - platform, - ); - } catch { - return resolveWithFallback( - context, - inReactNative(`react-native/${subpath}`), - platform, - ); - } - } - return resolveWithFallback(context, inReactNative(moduleName), platform); - }; - - const resolveRequest = (context, moduleName, platform) => { - let resolution = resolveModule(context, moduleName, platform); - // An adapter in src-gpui can import an explicit upstream variant. - if ( - isInside(context.originModulePath ?? '', SRC_DIR) && - /\.(?:ios|android)(?:\.js)?$/.test(moduleName) - ) { - return resolution; - } - let key = resolution?.filePath && fileKey(resolution.filePath); - if (key?.startsWith('react-native/') && key.endsWith('.js')) { - const variant = resolution.filePath.replace( - /\.js$/, - `.${FALLBACK_PLATFORM}.js`, - ); - if (fs.existsSync(variant) && isReExportShim(resolution.filePath)) { - resolution = withFilePath(resolution, variant); - key = fileKey(variant); - } - } - const override = key && overrides.get(key); - // An override that imports the module it replaces gets the upstream one. - if (override === context.originModulePath) return resolution; - return override ? withFilePath(resolution, override) : resolution; - }; - - const config = mergeConfig(getDefaultConfig(projectRoot), { - watchFolders, - // Leaves `Platform.OS` to the runtime: Metro would fold it to `desktop`. - transformerPath: path.join(PACKAGE_DIR, 'metro-transform-worker.js'), - transformer: { - babelTransformerPath: path.join( - PACKAGE_DIR, - 'metro-babel-transformer.js', - ), - }, - serializer: { - // Ours, not RN's: the default names the RN beside @react-native/metro-config, - // which is not in the app's graph when this package is linked. - getModulesRunBeforeMainModule: () => [SETUP_ENV], - }, - resolver: { - platforms: ['desktop', 'native'], - nodeModulesPaths, - // Resolve only from `nodeModulesPaths`, not by walking up from each - // importing file. When this package is linked (`file:`, `npm link`, a - // workspace), its own sources import `react`/`react-native`, and that walk - // finds the *linked tree's* copies — a second React in the app's bundle, - // which React rejects with "Invalid hook call" as soon as a component runs. - // `nodeModulesPaths` already lists every `node_modules` from the app up to - // its tree root, so nothing legitimate is lost; the tester has set this at - // its own config for the same reason. - disableHierarchicalLookup: true, - // `main` over `browser`: a desktop app wants native bindings, not WASM. - resolverMainFields: ['react-native', 'main'], - resolveRequest, - }, - }); - - // The active JS engine can adjust the config (e.g. its bytecode transform). - const engineBundle = activeJsEngineBundle(projectRoot); - return typeof engineBundle?.metroConfig === 'function' - ? mergeConfig(config, engineBundle.metroConfig(config) ?? {}) - : config; -} - -module.exports = { makeMetroConfig, findTreeRoot, nodeModulesUpToTreeRoot }; diff --git a/vendor/react-native-gpui/packages/core/metro.config.test.js b/vendor/react-native-gpui/packages/core/metro.config.test.js deleted file mode 100644 index 6f1f67fd68..0000000000 --- a/vendor/react-native-gpui/packages/core/metro.config.test.js +++ /dev/null @@ -1,145 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, describe, expect, test } from 'vitest'; - -const { - findTreeRoot, - makeMetroConfig, - nodeModulesUpToTreeRoot, -} = require('./metro.config.js'); - -const roots = []; -afterEach(() => { - while (roots.length) fs.rmSync(roots.pop(), { recursive: true, force: true }); -}); - -function scratch() { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'metro-watch-')); - roots.push(root); - return root; -} - -function mkdir(...parts) { - const directory = path.join(...parts); - fs.mkdirSync(directory, { recursive: true }); - return directory; -} - -function workspace(root) { - fs.writeFileSync( - path.join(root, 'package.json'), - JSON.stringify({ workspaces: ['packages/*'] }), - ); -} - -describe('findTreeRoot', () => { - test('finds the nearest directory holding .git', () => { - const root = scratch(); - mkdir(root, '.git'); - expect(findTreeRoot(mkdir(root, 'packages/app/src'))).toBe(root); - }); - - test('finds a package.json that declares workspaces', () => { - const root = scratch(); - workspace(root); - expect(findTreeRoot(mkdir(root, 'packages/app'))).toBe(root); - }); - - test('ignores a package.json without workspaces', () => { - const root = scratch(); - mkdir(root, '.git'); - const app = mkdir(root, 'packages/app'); - fs.writeFileSync(path.join(app, 'package.json'), '{"name":"app"}'); - expect(findTreeRoot(app)).toBe(root); - }); - - test('returns the nearest root, not the outermost', () => { - const outer = scratch(); - mkdir(outer, '.git'); - const inner = mkdir(outer, 'vendor/repo'); - mkdir(inner, '.git'); - expect(findTreeRoot(mkdir(inner, 'packages/app'))).toBe(inner); - }); - - test('returns null when there is no repository or workspace above', () => { - expect(findTreeRoot(mkdir(scratch(), 'standalone'))).toBeNull(); - }); -}); - -describe('nodeModulesUpToTreeRoot', () => { - test('collects every node_modules up to a repository root', () => { - const root = scratch(); - mkdir(root, '.git'); - const expected = [ - mkdir(root, 'node_modules'), - mkdir(root, 'packages/app/node_modules'), - ]; - const found = nodeModulesUpToTreeRoot(path.join(root, 'packages/app')); - expect(found.sort()).toEqual(expected.sort()); - }); - - test('stops at a workspace root', () => { - const root = scratch(); - workspace(root); - const expected = [ - mkdir(root, 'node_modules'), - mkdir(root, 'packages/app/node_modules'), - ]; - const found = nodeModulesUpToTreeRoot(path.join(root, 'packages/app')); - expect(found.sort()).toEqual(expected.sort()); - }); - - test('never includes a node_modules above the tree root', () => { - const outer = scratch(); - const decoy = mkdir(outer, 'node_modules'); - const repo = mkdir(outer, 'repo'); - mkdir(repo, '.git'); - mkdir(repo, 'node_modules'); - const found = nodeModulesUpToTreeRoot(mkdir(repo, 'packages/app')); - expect(found).not.toContain(decoy); - expect(found.every(folder => folder.startsWith(repo + path.sep))).toBe( - true, - ); - }); - - test('returns only its own node_modules without a tree root', () => { - const root = scratch(); - const stray = mkdir(root, 'node_modules'); - const own = mkdir(root, 'standalone/node_modules'); - const found = nodeModulesUpToTreeRoot(path.dirname(own)); - expect(found).toEqual([own]); - expect(found).not.toContain(stray); - }); -}); - -describe('makeMetroConfig', () => { - const tester = path.resolve(__dirname, '../rn-gpui-tester'); - const config = makeMetroConfig({ projectRoot: tester }); - - // When this package is linked, the default names a React Native copy that is - // not in the app's graph, and RN's setup never runs. - test('runs this package’s setup-env before the app entry', () => { - expect(config.serializer.getModulesRunBeforeMainModule()).toEqual([ - path.join(__dirname, 'setup-env.js'), - ]); - }); - - test('watches nothing outside the repository', () => { - const repo = findTreeRoot(tester); - expect( - config.watchFolders.every( - folder => folder === repo || folder.startsWith(repo + path.sep), - ), - ).toBe(true); - }); - - // When this package is linked, its own sources import `react`/`react-native`, - // and a hierarchical lookup walks up from them into the linked tree's - // `node_modules` — a second React in the app's bundle, which React rejects - // with "Invalid hook call" as soon as a component runs. Resolution has to - // come from `nodeModulesPaths` alone. - test('does not walk up from an importer for its dependencies', () => { - expect(config.resolver.disableHierarchicalLookup).toBe(true); - }); -}); diff --git a/vendor/react-native-gpui/packages/core/nativeRoot.test.ts b/vendor/react-native-gpui/packages/core/nativeRoot.test.ts deleted file mode 100644 index b376165863..0000000000 --- a/vendor/react-native-gpui/packages/core/nativeRoot.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -import * as React from 'react'; -import { describe, expect, test } from 'vitest'; -import { createNativeRoot } from './src-gpui/src/private/desktop/nativeRoot/reconciler'; - -const h = React.createElement; - -function start() { - const batches: unknown[][] = []; - const errors: unknown[] = []; - const root = createNativeRoot( - 7, - error => errors.push(error), - (_id, payload) => { - if (payload !== 'destroy') { - batches.push(JSON.parse(payload)); - } - }, - ); - return { root, batches, errors }; -} - -describe('the native root reconciler', () => { - test('the first commit is one batch that creates the container, the tree and its links', () => { - const { root, batches } = start(); - root.render( - h( - 'Panel', - { title: 'a' }, - h('Label', { text: 'x' }), - h('Label', { text: 'y' }), - ), - ); - expect(batches).toHaveLength(1); - const ops = batches[0] as unknown[][]; - expect(ops[0]).toEqual(['create', 1, 'NativeRootContainer', {}]); - const kinds = ops.map(op => op[0]); - expect(kinds.filter(kind => kind === 'create')).toHaveLength(4); - expect(kinds.filter(kind => kind === 'append')).toHaveLength(3); - expect( - ops.find(op => op[0] === 'create' && op[2] === 'Panel')?.[3], - ).toEqual({ - title: 'a', - }); - }); - - test('an update sends only the props that changed, and nothing when none did', () => { - const { root, batches } = start(); - root.render(h('Label', { text: 'x', size: 3 })); - root.render(h('Label', { text: 'y', size: 3 })); - expect(batches[1]).toEqual([ - ['update', expect.any(Number), { text: 'y' }, []], - ]); - root.render(h('Label', { text: 'y', size: 3 })); - expect(batches).toHaveLength(2); - root.render(h('Label', { text: 'y' })); - expect(batches[2]).toEqual([['update', expect.any(Number), {}, ['size']]]); - }); - - test('a keyed reorder moves existing instances and a removal removes one, by the same ids', () => { - const { root, batches } = start(); - const list = (keys: string[]) => - h('Panel', null, ...keys.map(key => h('Label', { key, text: key }))); - const children = new Map(); - const names = new Map(); - const apply = (ops: unknown[][]) => { - for (const op of ops) { - const [kind, a, b, c] = op as [ - string, - number, - number | string, - unknown, - ]; - if (kind === 'create') { - names.set(a, (c as { text?: string }).text ?? String(b)); - } else if (kind === 'append' || kind === 'insert') { - for (const list of children.values()) { - const at = list.indexOf(b as number); - if (at >= 0) list.splice(at, 1); - } - const list = children.get(a) ?? []; - const before = kind === 'insert' ? list.indexOf(c as number) : -1; - list.splice(before < 0 ? list.length : before, 0, b as number); - children.set(a, list); - } else if (kind === 'remove') { - children.set( - a, - (children.get(a) ?? []).filter(id => id !== b), - ); - } - } - }; - const order = () => { - const panel = [...names.entries()].find( - ([, name]) => name === 'Panel', - )?.[0]; - return (children.get(panel!) ?? []).map(id => names.get(id)); - }; - root.render(list(['a', 'b', 'c'])); - apply(batches[0] as unknown[][]); - expect(order()).toEqual(['a', 'b', 'c']); - const created = (batches[0] as unknown[][]).filter( - op => op[0] === 'create', - ); - root.render(list(['c', 'a', 'b'])); - apply(batches[1] as unknown[][]); - expect(order()).toEqual(['c', 'a', 'b']); - expect((batches[1] as unknown[][]).every(op => op[0] !== 'create')).toBe( - true, - ); - root.render(list(['c', 'b'])); - apply(batches[2] as unknown[][]); - expect(order()).toEqual(['c', 'b']); - expect(batches[2]).toEqual([ - [ - 'remove', - expect.any(Number), - created.find(op => (op[3] as { text?: string }).text === 'a')?.[1], - ], - ]); - }); - - test('a handler stays here: the runtime gets true, and the event calls the latest one', () => { - const { root, batches } = start(); - const calls: string[] = []; - root.render(h('Button', { onPress: () => calls.push('first') })); - const create = (batches[0] as unknown[][]).find(op => op[2] === 'Button')!; - expect(create[3]).toEqual({ onPress: true }); - root.render( - h('Button', { - onPress: (payload: unknown) => calls.push(`second ${payload}`), - }), - ); - expect(batches).toHaveLength(1); - root.dispatch({ id: create[1] as number, name: 'onPress', payload: 5 }); - expect(calls).toEqual(['second 5']); - root.dispatch({ id: 999, name: 'onPress' }); - }); - - test('a state update inside the tree sends its own batch', async () => { - const { root, batches } = start(); - let bump: () => void = () => {}; - function Counter() { - const [count, setCount] = React.useState(0); - bump = () => setCount(value => value + 1); - return h('Label', { text: `n${count}` }); - } - root.render(h(Counter)); - expect(batches).toHaveLength(1); - bump(); - await new Promise(resolve => setTimeout(resolve, 20)); - expect(batches).toHaveLength(2); - expect(batches[1]).toEqual([ - ['update', expect.any(Number), { text: 'n1' }, []], - ]); - }); - - test('a component that throws while rendering reports it', async () => { - const { root, errors } = start(); - function Broken(): never { - throw new Error('boom'); - } - try { - root.render(h(Broken)); - } catch { - // the error is also reported through onError - } - await new Promise(resolve => setTimeout(resolve, 0)); - expect(errors.length).toBeGreaterThan(0); - }); - - test('text directly in the tree is refused with a message that says why', async () => { - const { root, errors } = start(); - try { - root.render(h('Panel', null, 'loose text')); - } catch { - // reported through onError as well - } - await new Promise(resolve => setTimeout(resolve, 0)); - expect(String(errors[0])).toContain( - 'Text is not allowed directly inside a NativeRoot', - ); - }); -}); - -describe('image props of a native tree', () => { - test('are left as they are where React Native is not available to resolve them', async () => { - const { resolveImageProps } = - await import('./src-gpui/src/private/desktop/nativeRoot/imageProps'); - const props = { icon: { uri: 'file:///x.png' }, title: 't' }; - expect(resolveImageProps('Anything', props)).toBe(props); - }); -}); diff --git a/vendor/react-native-gpui/packages/core/navigation.ts b/vendor/react-native-gpui/packages/core/navigation.ts deleted file mode 100644 index 70cb556a7d..0000000000 --- a/vendor/react-native-gpui/packages/core/navigation.ts +++ /dev/null @@ -1 +0,0 @@ -export { useDesktopForwardNavigation } from './src-gpui/navigation/useDesktopForwardNavigation'; diff --git a/vendor/react-native-gpui/packages/core/overrides.json b/vendor/react-native-gpui/packages/core/overrides.json deleted file mode 100644 index 403bb100a6..0000000000 --- a/vendor/react-native-gpui/packages/core/overrides.json +++ /dev/null @@ -1,315 +0,0 @@ -{ - "includePatterns": [ - "ReactCxxPlatform/**", - "ReactCommonOverrides/**", - "ReactCommonOverrides.loom/**", - "index.desktop.js", - "src-gpui/**" - ], - "baseVersion": "0.87.1", - "overrides": [ - { - "type": "derived", - "file": "index.desktop.js", - "baseFile": "packages/react-native/index.js", - "baseHash": "5aa61d7bd7be95533271f158851e8398cdec478a", - "issue": 0 - }, - { - "type": "derived", - "file": "src-gpui/Libraries/Components/ScrollView/ScrollViewNativeComponent.desktop.js", - "baseFile": "packages/react-native/Libraries/Components/ScrollView/ScrollViewNativeComponent.js", - "baseHash": "eeee1a603e7211afa2441c4eb10d9f25a8c3bb48", - "issue": 0 - }, - { - "type": "platform", - "file": "src-gpui/Libraries/Utilities/Platform.desktop.js" - }, - { - "type": "platform", - "file": "src-gpui/Libraries/Modal/Modal.desktop.js" - }, - { - "type": "platform", - "file": "src-gpui/Libraries/Settings/Settings.desktop.js" - }, - { - "type": "platform", - "file": "src-gpui/Libraries/Components/RefreshControl/RefreshControl.desktop.js" - }, - { - "type": "platform", - "file": "src-gpui/Libraries/Components/StatusBar/StatusBar.desktop.js" - }, - { - "type": "derived", - "file": "src-gpui/Libraries/Components/ScrollView/ScrollView.desktop.js", - "baseFile": "packages/react-native/Libraries/Components/ScrollView/ScrollView.js", - "baseHash": "8f218c6e51209bbe56bba4d3fbb9b6320c718c29", - "issue": 0 - }, - { - "type": "platform", - "file": "src-gpui/Libraries/StyleSheet/PlatformColorValueTypes.desktop.js" - }, - { - "type": "platform", - "file": "src-gpui/Libraries/StyleSheet/PlatformColorValueTypesIOS.desktop.js" - }, - { - "type": "derived", - "file": "src-gpui/Libraries/Components/TextInput/TextInputState.desktop.js", - "baseFile": "packages/react-native/Libraries/Components/TextInput/TextInputState.js", - "baseHash": "9ef598defeeaf109527f39b48f77564eba80129a", - "issue": 0 - }, - { - "type": "platform", - "file": "src-gpui/Libraries/Utilities/useWindowDimensions.desktop.js" - }, - { - "type": "platform", - "file": "src-gpui/Libraries/Share/Share.desktop.js" - }, - { - "type": "patch", - "file": "ReactCommonOverrides/react/devsupport/DevServerHelper.cpp", - "baseFile": "packages/react-native/ReactCxxPlatform/react/devsupport/DevServerHelper.cpp", - "baseHash": "f5af9cc2a109d29a6c479782f7753e5410effe3a", - "issue": 0 - }, - { - "type": "patch", - "file": "ReactCommonOverrides/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.cpp", - "baseFile": "packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.cpp", - "baseHash": "f52700da0048f7dce129267d9edbe8e9f724f955", - "issue": 0 - }, - { - "type": "patch", - "file": "ReactCommonOverrides/react/renderer/textlayoutmanager/TextLayoutManager.h", - "baseFile": "packages/react-native/ReactCommon/react/renderer/textlayoutmanager/platform/cxx/react/renderer/textlayoutmanager/TextLayoutManager.h", - "baseHash": "63f2c1afcbc99cde197f9b306bc56384fd6f2e6c", - "issue": 0 - }, - { - "type": "patch", - "file": "ReactCommonOverrides/yoga/algorithm/CalculateLayout.cpp", - "baseFile": "packages/react-native/ReactCommon/yoga/yoga/yoga/algorithm/CalculateLayout.cpp", - "baseHash": "e9d62492daae89288c04d4ff11756257ae3e43a0", - "issue": 0 - }, - { - "type": "patch", - "file": "ReactCommonOverrides/yoga/YGEnums.h", - "baseFile": "packages/react-native/ReactCommon/yoga/yoga/yoga/YGEnums.h", - "baseHash": "f96abdf2f58c960d3e82d0343733c18e9370c27c", - "issue": 0 - }, - { - "type": "patch", - "file": "ReactCommonOverrides/yoga/YGEnums.cpp", - "baseFile": "packages/react-native/ReactCommon/yoga/yoga/yoga/YGEnums.cpp", - "baseHash": "1e823138684a1381fcd0a042a0b286d8413da589", - "issue": 0 - }, - { - "type": "patch", - "file": "ReactCommonOverrides/yoga/enums/Errata.h", - "baseFile": "packages/react-native/ReactCommon/yoga/yoga/yoga/enums/Errata.h", - "baseHash": "5f59ab16a4b39d4e4452263ce78b1bf6a8a6d93a", - "issue": 0 - }, - { - "type": "patch", - "file": "ReactCommonOverrides/react/renderer/components/view/HostPlatformViewProps.h", - "baseFile": "packages/react-native/ReactCommon/react/renderer/components/view/platform/cxx/react/renderer/components/view/HostPlatformViewProps.h", - "baseHash": "9c378b43b42022f3769b9fa788a353bf387ab391", - "issue": 0 - }, - { - "type": "patch", - "file": "ReactCommonOverrides/react/renderer/components/view/HostPlatformViewTraitsInitializer.h", - "baseFile": "packages/react-native/ReactCommon/react/renderer/components/view/platform/cxx/react/renderer/components/view/HostPlatformViewTraitsInitializer.h", - "baseHash": "6176ff1061b41ade659d2e7f83fa48eb273ae60e", - "issue": 0 - }, - { - "type": "copy", - "directory": "ReactCxxPlatform", - "baseDirectory": "packages/react-native/ReactCxxPlatform", - "baseHash": "1ccfa0a8780ab2c866948891dbdf0f1261d2f05a", - "issue": 0 - }, - { - "type": "patch", - "file": "src-gpui/Libraries/LogBox/UI/LogBoxButton.desktop.js", - "baseFile": "packages/react-native/Libraries/LogBox/UI/LogBoxButton.js", - "baseHash": "ec31459f5c444aa4fb155a8140297df7a7f816db", - "issue": 0 - }, - { - "type": "patch", - "file": "src-gpui/Libraries/LogBox/UI/LogBoxNotification.desktop.js", - "baseFile": "packages/react-native/Libraries/LogBox/UI/LogBoxNotification.js", - "baseHash": "70ae5dd0c89f708a88b7d359d04d3a368a76981b", - "issue": 0 - }, - { - "type": "patch", - "file": "src-gpui/Libraries/LogBox/UI/LogBoxInspectorCodeFrame.desktop.js", - "baseFile": "packages/react-native/Libraries/LogBox/UI/LogBoxInspectorCodeFrame.js", - "baseHash": "3f1f73cd47e82adc1953c6693ca202c7efbc02fd", - "issue": 0 - }, - { - "type": "patch", - "file": "src-gpui/Libraries/LogBox/UI/LogBoxInspectorHeader.desktop.js", - "baseFile": "packages/react-native/Libraries/LogBox/UI/LogBoxInspectorHeader.js", - "baseHash": "ffb9ae6a81577f35df0a7dda0546d00d7799c95e", - "issue": 0 - }, - { - "type": "platform", - "file": "src-gpui/Libraries/Alert/Alert.desktop.js" - }, - { - "type": "platform", - "file": "src-gpui/Libraries/Components/TextInput/TextInput.desktop.js" - }, - { - "type": "platform", - "file": "src-gpui/Libraries/Components/Button.desktop.js" - }, - { - "type": "platform", - "file": "src-gpui/Libraries/Utilities/Appearance.desktop.js" - }, - { - "type": "platform", - "file": "src-gpui/Libraries/Utilities/BackHandler.desktop.js" - }, - { - "type": "patch", - "file": "ReactCommonOverrides/react/nativemodule/dom/NativeDOM.h", - "baseFile": "packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.h", - "baseHash": "d6acbe5683b2cc276509305f9cafc721ad92a88c", - "issue": 0 - }, - { - "type": "patch", - "file": "ReactCommonOverrides/react/nativemodule/dom/NativeDOM.cpp", - "baseFile": "packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.cpp", - "baseHash": "190c251544809795faf1be36043d2684d49d8627", - "issue": 0 - }, - { - "type": "patch", - "file": "ReactCommonOverrides/react/renderer/components/textinput/BaseTextInputShadowNode.h", - "baseFile": "packages/react-native/ReactCommon/react/renderer/components/textinput/BaseTextInputShadowNode.h", - "baseHash": "a94e72f4836e257f6cd1fe9cb21ede410169e267", - "issue": 0 - }, - { - "type": "patch", - "file": "ReactCommonOverrides.loom/react/nativemodule/dom/NativeDOM.cpp", - "baseFile": "packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.cpp", - "baseHash": "190c251544809795faf1be36043d2684d49d8627", - "loomBaseFile": "ReactCommon/react/nativemodule/dom/NativeDOM.cpp", - "loomBaseHash": "c5d01a411c1e006f42ae68366a4b718825637fafb45fcc6d203a15d8dc2bac07", - "issue": 0 - }, - { - "type": "platform", - "file": "ReactCommonOverrides.loom/unistd.h" - }, - { - "type": "patch", - "file": "ReactCommonOverrides.loom/react/nativemodule/dom/NativeDOM.h", - "baseFile": "packages/react-native/ReactCommon/react/nativemodule/dom/NativeDOM.h", - "baseHash": "d6acbe5683b2cc276509305f9cafc721ad92a88c", - "loomBaseFile": "ReactCommon/react/nativemodule/dom/NativeDOM.h", - "loomBaseHash": "a96b02643dbb508ffaba7e0a01e4490009c846e3ee156be2b1cab809465e7935", - "issue": 0 - }, - { - "type": "platform", - "file": "src-gpui/src/private/specs/NativeGpuiDesktop.ts" - }, - { - "type": "platform", - "file": "src-gpui/src/private/desktop/index.ts" - }, - { - "type": "platform", - "file": "src-gpui/src/private/desktop/windowContext.ts" - }, - { - "type": "platform", - "file": "src-gpui/src/private/desktop/windows.ts" - }, - { - "type": "platform", - "file": "src-gpui/src/private/desktop/TitleBar.tsx" - }, - { - "type": "platform", - "file": "src-gpui/src/private/desktop/types.ts" - }, - { - "type": "platform", - "file": "src-gpui/src/private/desktop/menu.ts" - }, - { - "type": "platform", - "file": "src-gpui/src/private/desktop/contextMenu.tsx" - }, - { - "type": "platform", - "file": "src-gpui/src/private/desktop/perfMonitor.ts" - }, - { - "type": "platform", - "file": "src-gpui/src/private/desktop/scrollerStyle.ts" - }, - { - "type": "platform", - "file": "src-gpui/src/private/desktop/network.ts" - }, - { - "type": "platform", - "file": "src-gpui/Libraries/NativeComponent/BaseViewConfig.desktop.ts" - }, - { - "type": "platform", - "file": "src-gpui/Libraries/Network/RCTNetworking.desktop.js" - }, - { - "type": "platform", - "file": "src-gpui/Libraries/Renderer/shims/ReactNativeViewConfigRegistry.desktop.js" - }, - { - "type": "platform", - "file": "src-gpui/navigation/useDesktopForwardNavigation.ts" - }, - { - "type": "platform", - "file": "src-gpui/src/private/desktop/tray.ts" - }, - { - "type": "patch", - "file": "ReactCommonOverrides/react/renderer/imagemanager/platform/cxx/react/renderer/imagemanager/ImageManager.cpp", - "baseFile": "packages/react-native/ReactCommon/react/renderer/imagemanager/platform/cxx/react/renderer/imagemanager/ImageManager.cpp", - "baseHash": "604eb031600c654f84bd021091e764fa107ddd86", - "issue": 0 - }, - { - "type": "derived", - "file": "src-gpui/Libraries/ReactNative/RendererProxy.desktop.js", - "baseFile": "packages/react-native/Libraries/ReactNative/RendererProxy.js", - "baseHash": "83c98fa706b08494398f4e47b06c83b6ae8c7f7e", - "issue": 0 - } - ] -} diff --git a/vendor/react-native-gpui/packages/core/package.json b/vendor/react-native-gpui/packages/core/package.json deleted file mode 100644 index 6ae14244d8..0000000000 --- a/vendor/react-native-gpui/packages/core/package.json +++ /dev/null @@ -1,96 +0,0 @@ -{ - "name": "@react-native-gpui/core", - "version": "0.87.0-alpha.5", - "description": "React Native platform powered by GPUI. Desktop React Native for macOS, Windows and Linux with one GPU-accelerated renderer.", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/streetwriters/react-native-gpui.git", - "directory": "packages/core" - }, - "homepage": "https://streetwriters.github.io/react-native-gpui/", - "bugs": { - "url": "https://github.com/streetwriters/react-native-gpui/issues" - }, - "main": "index.desktop.js", - "files": [ - "index.desktop.js", - "js-engine.js", - "renderer.js", - "navigation.ts", - "desktop.ts", - "diagnostics.ts", - "types.d.ts", - "babel-plugin-node-addons.js", - "polyfills", - "metro.config.js", - "metro-babel-transformer.js", - "metro-transform-worker.js", - "setup-env.js", - "src-gpui", - "bin", - "ReactCommonOverrides", - "ReactCommonOverrides.loom", - "ReactCxxPlatform", - "ReactGpui/Cargo.lock", - "ReactGpui/Cargo.toml", - "ReactGpui/GPUI_PIN.md", - "ReactGpui/loom-pin.json", - "ReactGpui/LOOM_PIN.md", - "ReactGpui/rn-gpui/Cargo.toml", - "ReactGpui/rn-gpui/build.rs", - "ReactGpui/rn-gpui/src", - "ReactGpui/rn-gpui-sys/Cargo.toml", - "ReactGpui/rn-gpui-sys/build.rs", - "ReactGpui/rn-gpui-sys/src", - "ReactGpui/rn-gpui-sys/cpp", - "ReactGpui/rn-gpui-sys/scripts", - "react-native.config.js", - "overrides.json", - "prebuilt-binaries.json", - "scripts/prebuilt-binaries.mjs", - "scripts/prebuilt-inputs.mjs", - "scripts/repo-root.mjs", - "scripts/build-prebuilt.mjs", - "scripts/generate-prebuilt-inputs.mjs", - "scripts/check-standalone-cmake.mjs", - "scripts/check-prebuilt-pin.mjs", - "scripts/prebuilt-renderers.mjs", - "scripts/check-loom-overrides.mjs", - "ReactGpui/rn-gpui-module/Cargo.toml", - "ReactGpui/rn-gpui-module/src", - "ReactGpui/rn-gpui-module/tests", - "ReactGpui/rn-gpui-module-build/Cargo.toml", - "ReactGpui/rn-gpui-module-build/src", - "CHANGELOG.md", - "!**/*.test.js", - "!**/*.test.mjs", - "!**/*.test.ts", - "!**/*.test.cjs" - ], - "scripts": { - "prepublishOnly": "node scripts/check-prebuilt-pin.mjs", - "check:loom-overrides": "node scripts/check-loom-overrides.mjs" - }, - "peerDependencies": { - "react": "19.2.3", - "react-native": "0.87.x" - }, - "dependencies": { - "@react-native-gpui/codegen": "0.87.0-alpha.2", - "its-fine": "2.1.1", - "react-reconciler": "0.33.0" - }, - "keywords": [ - "react-native", - "gpui", - "desktop", - "macos", - "windows", - "linux" - ], - "publishConfig": { - "access": "public", - "tag": "latest" - } -} diff --git a/vendor/react-native-gpui/packages/core/polyfills/menu.tsx b/vendor/react-native-gpui/packages/core/polyfills/menu.tsx deleted file mode 100644 index a887c5b9e1..0000000000 --- a/vendor/react-native-gpui/packages/core/polyfills/menu.tsx +++ /dev/null @@ -1,132 +0,0 @@ -/** - * `@react-native-menu/menu` polyfill. - * - * Existing apps (and Zeego, which builds on this package) can keep importing - * `@react-native-menu/menu` if their Metro config maps the package name here: - * - * ```js - * // metro.config.js - * resolver: { - * extraNodeModules: { - * '@react-native-menu/menu': require.resolve('@react-native-gpui/core/polyfills/menu'), - * }, - * } - * ``` - * - * Supported: `actions` (`subactions`, `state: 'on' | 'off' | 'mixed'`, - * `attributes.disabled`, `attributes.hidden`, `attributes.destructive`), - * `onPressAction`, `shouldOpenOnLongPress` (false opens on a primary press), - * `title`. Ignored: `themeVariant`, `hitSlop` beyond what `View` takes, and - * icon-based attributes (see the README). - * - * @format - */ - -import React from 'react'; -import { Pressable, View } from 'react-native'; -import type { ViewProps } from 'react-native'; -import { ContextMenu } from '../src-gpui/src/private/desktop/contextMenu'; -import type { MenuItemSpec } from '../src-gpui/src/private/desktop/menu'; - -export interface MenuAction { - id: string; - title: string; - attributes?: { - disabled?: boolean; - hidden?: boolean; - destructive?: boolean; - }; - state?: 'on' | 'off' | 'mixed'; - subactions?: MenuAction[]; - image?: string; - imageColor?: string; -} - -export interface MenuViewProps extends ViewProps { - actions: MenuAction[]; - onPressAction?: (event: { nativeEvent: { event: string } }) => void; - shouldOpenOnLongPress?: boolean; - title?: string; - children?: React.ReactNode; -} - -export function toMenuItems(actions: MenuAction[]): MenuItemSpec[] { - const items: MenuItemSpec[] = []; - for (const action of actions) { - if (action.attributes?.hidden) { - continue; - } - const enabled = !action.attributes?.disabled; - if (action.subactions != null && action.subactions.length > 0) { - items.push({ - type: 'submenu', - id: action.id, - label: action.title, - enabled, - items: toMenuItems(action.subactions), - }); - continue; - } - items.push({ - id: action.id, - label: action.title, - enabled, - checked: action.state === 'on', - }); - } - return items; -} - -export function MenuView({ - actions, - onPressAction, - shouldOpenOnLongPress = true, - // `title` is part of the upstream API but the desktop model has no menu - // title; it is ignored rather than rejected. - title: _title, - children, - ...viewProps -}: MenuViewProps) { - const open = React.useCallback( - (x: number, y: number, windowId?: number) => { - ContextMenu.show(toMenuItems(actions), { x, y, windowId }) - .then(id => { - if (id != null) { - onPressAction?.({ nativeEvent: { event: id } }); - } - }) - .catch(() => {}); - }, - [actions, onPressAction], - ); - - if (shouldOpenOnLongPress) { - return ( - - open( - event.nativeEvent.x, - event.nativeEvent.y, - event.nativeEvent.windowId, - ) - } - > - {children} - - ); - } - - return ( - - open(event.nativeEvent.pageX ?? 0, event.nativeEvent.pageY ?? 0) - } - > - {children} - - ); -} - -export default { MenuView }; diff --git a/vendor/react-native-gpui/packages/core/prebuilt-binaries.json b/vendor/react-native-gpui/packages/core/prebuilt-binaries.json deleted file mode 100644 index a16ef1c239..0000000000 --- a/vendor/react-native-gpui/packages/core/prebuilt-binaries.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "version": "0.0.15", - "reactNative": "0.87.1", - "inputHash": "b8a2aade17907c26908b3c6fb3ae833e25f9ea9a6d9a969d07cbacb45cabb544", - "repo": "streetwriters/react-native-gpui", - "tag": "@react-native-gpui/prebuilt-binaries@0.0.15", - "assets": { - "darwin-arm64": { - "file": "prebuilt-binaries-darwin-arm64.tar.gz", - "sha256": "2a17ffad6d3e5462c75a2c5c8938285eeca41c2a3d24cd8a9a652c37df82c45c", - "size": 45723173 - }, - "darwin-x64": { - "file": "prebuilt-binaries-darwin-x64.tar.gz", - "sha256": "78fedec1cfd5e0362d0586db0dc9928cdd9a117d64a7c2311dbe24160f39400a", - "size": 47100029 - }, - "linux-arm64": { - "file": "prebuilt-binaries-linux-arm64.tar.gz", - "sha256": "b1a33025f94a51a3a7d84a0d9758fbfc71b03189e40b22fbbadfdb55fb5bdba7", - "size": 69977456 - }, - "linux-x64": { - "file": "prebuilt-binaries-linux-x64.tar.gz", - "sha256": "45bc82379ec12d68a8bcb139f9e304f5fd5d8d0c7bdda91e9d1e58b4f558b623", - "size": 71933235 - }, - "win32-arm64": { - "file": "prebuilt-binaries-win32-arm64.tar.gz", - "sha256": "865617b84309f7338c7701fd0f6898387fa4ac471ae50ccfed7c45343c0d5176", - "size": 183358970 - }, - "win32-x64": { - "file": "prebuilt-binaries-win32-x64.tar.gz", - "sha256": "36eb3f172ee7d379b66b983654842c2c25d056f81541492647234949bf677e4d", - "size": 100094437 - } - } -} diff --git a/vendor/react-native-gpui/packages/core/react-native.config.js b/vendor/react-native-gpui/packages/core/react-native.config.js deleted file mode 100644 index 72c86db0e1..0000000000 --- a/vendor/react-native-gpui/packages/core/react-native.config.js +++ /dev/null @@ -1,12 +0,0 @@ -module.exports = { - platforms: { - desktop: { - npmPackageName: '@react-native-gpui/core', - // The Rust crate builds the platform; there is no Gradle/Xcode project to - // configure or to autolink dependencies against. `project.desktop` only - // carries build options, which autolink validates. - projectConfig: (_root, project) => project ?? {}, - dependencyConfig: (_root, dependencyConfig) => dependencyConfig ?? null, - }, - }, -}; diff --git a/vendor/react-native-gpui/packages/core/renderer.js b/vendor/react-native-gpui/packages/core/renderer.js deleted file mode 100644 index e337d76d26..0000000000 --- a/vendor/react-native-gpui/packages/core/renderer.js +++ /dev/null @@ -1,344 +0,0 @@ -// Which renderer an app runs and which React Native tree everything builds -// against. `renderer` and `jsThread` come from `desktop/desktop.json` -// (`desktop..json` on top), overridden by `RN_GPUI_RENDERER` and -// `RN_GPUI_JS_THREAD`. Fabric builds against the installed `react-native`; -// Loom builds against that package with Loom's overrides applied, produced by -// Loom's own `materialize` from a pinned source archive. -// -// Metro, autolink and the Rust build all go through `resolveRenderer`, so one -// answer selects the JavaScript, the C++ headers and the C++ sources. -const crypto = require('node:crypto'); -const fs = require('node:fs'); -const https = require('node:https'); -const os = require('node:os'); -const path = require('node:path'); -const { execFileSync } = require('node:child_process'); - -const RENDERERS = ['fabric', 'loom']; -const JS_THREADS = ['background', 'main']; -const PIN_PATH = path.join(__dirname, 'ReactGpui', 'loom-pin.json'); - -const CONFIG_FILES = { - darwin: 'macos', - win32: 'windows', -}; - -/** - * The tar that extracts an archive. On Windows it is the one that ships with - * the OS: a bash session puts Git's GNU tar first on PATH, and GNU tar reads a - * `C:\...` argument as a remote host ("Cannot connect to C: resolve failed"). - */ -function tarCommand() { - if (process.platform !== 'win32') return 'tar'; - const systemTar = path.join( - process.env.SystemRoot ?? 'C:\\Windows', - 'System32', - 'tar.exe', - ); - return fs.existsSync(systemTar) ? systemTar : 'tar'; -} - -function readJson(file) { - try { - return JSON.parse(fs.readFileSync(file, 'utf8')); - } catch (error) { - if (error.code === 'ENOENT') return undefined; - throw new Error(`${file} is not valid JSON: ${error.message}`); - } -} - -/** `{ renderer, jsThread }` for an app, validated. */ -function rendererConfig( - projectRoot, - { env = process.env, platform = process.platform } = {}, -) { - const desktopDir = path.join(projectRoot, 'desktop'); - const os_ = CONFIG_FILES[platform] ?? platform; - const files = [ - readJson(path.join(desktopDir, 'desktop.json')), - readJson(path.join(desktopDir, `desktop.${os_}.json`)), - ]; - let renderer; - let jsThread; - for (const file of files) { - if (file && file.renderer !== undefined) renderer = file.renderer; - if (file && file.jsThread !== undefined) jsThread = file.jsThread; - } - const overridden = Boolean(env.RN_GPUI_RENDERER); - renderer = env.RN_GPUI_RENDERER || renderer || 'fabric'; - jsThread = env.RN_GPUI_JS_THREAD || jsThread; - if (!RENDERERS.includes(renderer)) { - throw new Error( - `renderer must be one of ${RENDERERS.map(name => `"${name}"`).join(', ')}, got ${JSON.stringify(renderer)}`, - ); - } - if (jsThread !== undefined && !JS_THREADS.includes(jsThread)) { - throw new Error( - `jsThread must be one of ${JS_THREADS.map(name => `"${name}"`).join(', ')}, got ${JSON.stringify(jsThread)}`, - ); - } - if (renderer !== 'loom' && jsThread !== undefined) { - // A file's jsThread belongs to the renderer it was written for, so - // switching to Fabric for one run needs no edit to the file. - if (!overridden || env.RN_GPUI_JS_THREAD) { - throw new Error('jsThread is only available with "renderer": "loom"'); - } - } - return { - renderer, - jsThread: renderer === 'loom' ? (jsThread ?? 'background') : undefined, - }; -} - -/** The shared per-user cache the native dependency downloads also use. */ -function cacheRoot(env = process.env) { - const set = name => (env[name] ? env[name] : undefined); - if (set('RN_GPUI_NATIVE_DEPS_CACHE')) { - return path.resolve(set('RN_GPUI_NATIVE_DEPS_CACHE')); - } - if (set('RN_GPUI_PREBUILT_CACHE')) { - return path.join( - path.resolve(set('RN_GPUI_PREBUILT_CACHE')), - 'native-deps', - ); - } - const home = os.homedir(); - let base; - if (process.platform === 'darwin') { - base = path.join(home, 'Library', 'Caches'); - } else if (process.platform === 'win32') { - base = set('LOCALAPPDATA') ?? path.join(home, 'AppData', 'Local'); - } else { - const xdg = set('XDG_CACHE_HOME'); - base = xdg && path.isAbsolute(xdg) ? xdg : path.join(home, '.cache'); - } - return path.join(base, 'react-native-gpui', 'native-deps'); -} - -function loomPin() { - return JSON.parse(fs.readFileSync(PIN_PATH, 'utf8')); -} - -const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); - -/** Runs `body` holding an exclusive directory lock; a dead owner's lock is taken over. */ -async function withLock(lockDir, body) { - fs.mkdirSync(path.dirname(lockDir), { recursive: true }); - const started = Date.now(); - for (;;) { - try { - fs.mkdirSync(lockDir); - fs.writeFileSync(path.join(lockDir, 'owner'), String(process.pid)); - break; - } catch (error) { - if (error.code !== 'EEXIST') throw error; - let owner = NaN; - try { - owner = Number(fs.readFileSync(path.join(lockDir, 'owner'), 'utf8')); - } catch {} - if (Number.isInteger(owner) && owner > 0) { - let alive = true; - try { - process.kill(owner, 0); - } catch (killError) { - alive = killError.code === 'EPERM'; - } - if (!alive) { - fs.rmSync(lockDir, { recursive: true, force: true }); - continue; - } - } - if (Date.now() - started > 10 * 60 * 1000) { - throw new Error(`${lockDir} is held; remove it if no build is running`); - } - await delay(200); - } - } - try { - return await body(); - } finally { - fs.rmSync(lockDir, { recursive: true, force: true }); - } -} - -function download(url, file, redirects = 5) { - return new Promise((resolve, reject) => { - https - .get(url, response => { - const status = response.statusCode ?? 0; - if (status >= 300 && status < 400 && response.headers.location) { - response.resume(); - if (redirects === 0) - return reject(new Error(`too many redirects: ${url}`)); - resolve( - download( - new URL(response.headers.location, url).toString(), - file, - redirects - 1, - ), - ); - return; - } - if (status !== 200) { - response.resume(); - return reject(new Error(`GET ${url} returned ${status}`)); - } - const out = fs.createWriteStream(file); - response.pipe(out); - out.on('finish', () => out.close(resolve)); - out.on('error', reject); - response.on('error', reject); - }) - .on('error', reject); - }); -} - -const sha256 = file => - crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex'); - -/** - * The `react-native-loom` package directory: `RN_GPUI_LOOM_DIR` when set, - * otherwise the pinned commit's archive, downloaded once into the cache and - * checked against the pinned digest. - */ -async function loomPackageDir(env = process.env) { - if (env.RN_GPUI_LOOM_DIR) { - const dir = path.resolve(env.RN_GPUI_LOOM_DIR); - if (!fs.existsSync(path.join(dir, 'bin', 'loom.js'))) { - throw new Error( - `RN_GPUI_LOOM_DIR must name a react-native-loom package (no bin/loom.js in ${dir})`, - ); - } - return dir; - } - const pin = loomPin(); - const id = pin.commit.slice(0, 12); - const root = path.join(cacheRoot(env), 'loom'); - const finalDir = path.join(root, `loom-${id}`); - const packageDir = path.join(finalDir, pin.packagePath); - if (fs.existsSync(path.join(packageDir, 'bin', 'loom.js'))) return packageDir; - - const archive = path.join(root, `loom-${id}.tar.gz`); - await withLock(path.join(root, `loom-${id}.lock`), async () => { - if (fs.existsSync(path.join(packageDir, 'bin', 'loom.js'))) return; - if (!fs.existsSync(archive) || sha256(archive) !== pin.sha256) { - const part = `${archive}.part`; - await download(pin.archiveUrl, part); - const actual = sha256(part); - if (actual !== pin.sha256) { - fs.rmSync(part, { force: true }); - throw new Error( - `${pin.archiveUrl} has sha256 ${actual}, expected ${pin.sha256}`, - ); - } - fs.renameSync(part, archive); - } - const scratch = `${finalDir}.tmp`; - fs.rmSync(scratch, { recursive: true, force: true }); - fs.mkdirSync(scratch, { recursive: true }); - execFileSync(tarCommand(), [ - '-xzf', - archive, - '-C', - scratch, - '--strip-components=1', - ]); - fs.rmSync(finalDir, { recursive: true, force: true }); - fs.renameSync(scratch, finalDir); - }); - return packageDir; -} - -function installedReactNative(projectRoot) { - const manifest = require.resolve('react-native/package.json', { - paths: [projectRoot], - }); - const dir = path.dirname(fs.realpathSync(manifest)); - return { - dir, - version: JSON.parse(fs.readFileSync(manifest, 'utf8')).version, - }; -} - -/** Runs `loom materialize` for the app's `react-native` into the cache. */ -async function materializedTree(projectRoot, env = process.env) { - const pristine = installedReactNative(projectRoot); - const packageDir = await loomPackageDir(env); - const loomVersion = JSON.parse( - fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8'), - ).version; - const key = crypto - .createHash('sha256') - .update(`${packageDir}\0${pristine.dir}`) - .digest('hex') - .slice(0, 12); - const out = path.join( - cacheRoot(env), - 'loom', - 'trees', - `${pristine.version}-${key}`, - 'react-native', - ); - fs.mkdirSync(path.dirname(out), { recursive: true }); - try { - execFileSync( - process.execPath, - [path.join(packageDir, 'bin', 'loom.js'), 'materialize', '--out', out], - { cwd: projectRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }, - ); - } catch (error) { - throw new Error( - `loom materialize failed:\n${error.stderr || error.stdout || error.message}`, - ); - } - return { - reactNativeDir: out, - pristineReactNativeDir: pristine.dir, - loomPackageDir: packageDir, - loomVersion, - }; -} - -/** - * Where an app's React Native comes from. Spawns itself for the Loom case, - * because a download cannot finish inside a synchronous Metro config. - */ -function resolveRenderer(projectRoot, options = {}) { - const config = rendererConfig(projectRoot, options); - if (config.renderer === 'fabric') { - const { dir } = installedReactNative(projectRoot); - return { ...config, reactNativeDir: dir, pristineReactNativeDir: dir }; - } - const output = execFileSync( - process.execPath, - [path.join(__dirname, 'renderer.js'), 'tree', projectRoot], - { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] }, - ); - return { ...config, ...JSON.parse(output.trim().split('\n').pop()) }; -} - -module.exports = { - RENDERERS, - JS_THREADS, - rendererConfig, - resolveRenderer, - materializedTree, - loomPackageDir, - cacheRoot, - loomPin, -}; - -if (require.main === module) { - const [command, projectRoot] = process.argv.slice(2); - if (command !== 'tree' || !projectRoot) { - console.error('usage: renderer.js tree '); - process.exit(2); - } - materializedTree(path.resolve(projectRoot)).then( - tree => console.log(JSON.stringify(tree)), - error => { - console.error(error.message); - process.exit(1); - }, - ); -} diff --git a/vendor/react-native-gpui/packages/core/renderer.test.js b/vendor/react-native-gpui/packages/core/renderer.test.js deleted file mode 100644 index 662ca69dc7..0000000000 --- a/vendor/react-native-gpui/packages/core/renderer.test.js +++ /dev/null @@ -1,74 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, describe, expect, test } from 'vitest'; - -const { rendererConfig } = require('./renderer.js'); - -const roots = []; -afterEach(() => { - while (roots.length) fs.rmSync(roots.pop(), { recursive: true, force: true }); -}); - -function project(files = {}) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'renderer-')); - roots.push(root); - fs.mkdirSync(path.join(root, 'desktop')); - for (const [name, contents] of Object.entries(files)) { - fs.writeFileSync( - path.join(root, 'desktop', name), - JSON.stringify(contents), - ); - } - return root; -} - -describe('rendererConfig', () => { - test('is fabric without a choice', () => { - expect(rendererConfig(project(), { env: {} })).toEqual({ - renderer: 'fabric', - jsThread: undefined, - }); - }); - - test('reads desktop.json and lets the OS file and the environment win', () => { - const root = project({ - 'desktop.json': { renderer: 'loom', jsThread: 'main' }, - 'desktop.linux.json': { jsThread: 'background' }, - }); - expect(rendererConfig(root, { env: {}, platform: 'darwin' })).toEqual({ - renderer: 'loom', - jsThread: 'main', - }); - expect(rendererConfig(root, { env: {}, platform: 'linux' }).jsThread).toBe( - 'background', - ); - expect( - rendererConfig(root, { - env: { RN_GPUI_RENDERER: 'fabric', RN_GPUI_JS_THREAD: '' }, - platform: 'darwin', - }).renderer, - ).toBe('fabric'); - }); - - test('loom defaults to a background JS thread', () => { - const root = project({ 'desktop.json': { renderer: 'loom' } }); - expect(rendererConfig(root, { env: {} }).jsThread).toBe('background'); - }); - - test('refuses a JS thread without loom and unknown values', () => { - expect(() => - rendererConfig(project({ 'desktop.json': { jsThread: 'main' } }), { - env: {}, - }), - ).toThrow(/only available with "renderer": "loom"/); - expect(() => - rendererConfig(project(), { env: { RN_GPUI_RENDERER: 'skia' } }), - ).toThrow(/renderer must be one of "fabric", "loom"/); - expect(() => - rendererConfig(project({ 'desktop.json': { renderer: 'loom' } }), { - env: { RN_GPUI_JS_THREAD: 'worker' }, - }), - ).toThrow(/jsThread must be one of "background", "main"/); - }); -}); diff --git a/vendor/react-native-gpui/packages/core/scripts/build-prebuilt.mjs b/vendor/react-native-gpui/packages/core/scripts/build-prebuilt.mjs deleted file mode 100644 index ea7fca36fc..0000000000 --- a/vendor/react-native-gpui/packages/core/scripts/build-prebuilt.mjs +++ /dev/null @@ -1,567 +0,0 @@ -#!/usr/bin/env node -// Builds the prebuilt C++ runtime for this host and packs it as -// prebuilt-binaries-.tar.gz with a manifest.json. -// -// Usage: -// node scripts/build-prebuilt.mjs --version --out \ -// [--bridge --rncore ] \ -// [--build-dir ] [--native-deps ] [--skip-build] [--jobs ] \ -// [--renderer fabric|loom --react-native-dir ] -// -// --renderer loom builds the runtime against the Loom React Native tree that -// `renderer.js tree ` materializes (--react-native-dir) and names its -// archive prebuilt-binaries-loom-.tar.gz. -// -// --bridge and --rncore are optional. When omitted, the cxxbridge headers and -// FBReactNativeSpec sources are generated (scripts/generate-prebuilt-inputs.mjs), -// so no tester build is needed. When given, they must be the generated -// directories of a `cargo build -p rn-gpui-sys` (files under -// `/rn-gpui-cmake///generated/`: -// `cxxbridge-include` and `fbreactnativespec`). --native-deps reuses -// downloaded native dependencies between runs. -// -// Output (under --out): -// / the cmake --install prefix (lib/, include/, cmake/) -// prebuilt-binaries-.tar.gz -// prebuilt-binaries-.tar.gz.sha256 -// prebuilt-binaries--pdb.tar.gz Windows only -// prebuilt-binaries--pdb.tar.gz.sha256 Windows only - -import { spawnSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; -import { - cpSync, - existsSync, - mkdirSync, - readFileSync, - readdirSync, - rmSync, - statSync, - symlinkSync, - writeFileSync, -} from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { inputHash, overridesSha256 } from './prebuilt-inputs.mjs'; -import { findNodeModule, repoRoot as findRepoRoot } from './repo-root.mjs'; - -const scriptDir = path.dirname(fileURLToPath(import.meta.url)); -const packageDir = path.resolve(scriptDir, '..'); -const repoRoot = findRepoRoot(scriptDir); -const cppDir = path.join(packageDir, 'ReactGpui', 'rn-gpui-sys', 'cpp'); -const reactNativeRoot = - findNodeModule(packageDir, 'react-native') ?? - path.join(repoRoot, 'node_modules', 'react-native'); -const reactCxxPlatformDir = path.join(packageDir, 'ReactCxxPlatform'); -const overridesDir = path.join(packageDir, 'ReactCommonOverrides'); -const reactNativePkg = path.join(reactNativeRoot, 'package.json'); -const cargoLock = path.join(packageDir, 'ReactGpui', 'Cargo.lock'); - -const args = parseArgs(process.argv.slice(2)); -const renderer = args.renderer ?? 'fabric'; -if (!['fabric', 'loom'].includes(renderer)) - fail(`unknown renderer ${renderer}`); -const loom = renderer === 'loom'; -const loomTreeDir = loom - ? path.resolve( - args['react-native-dir'] ?? - fail('--react-native-dir is required with loom'), - ) - : null; -const reactCommonDir = path.join(loomTreeDir ?? reactNativeRoot, 'ReactCommon'); -const version = args.version; -const outDir = path.resolve(args.out ?? fail('--out is required')); -// Without --bridge/--rncore the generated inputs are produced into the build -// dir (scripts/generate-prebuilt-inputs.mjs), so no tester build is needed. -const generatedDir = path.resolve( - args['build-dir'] ?? path.join(os.tmpdir(), 'rn-gpui-prebuilt-build'), - '..', - 'generated-inputs', -); -let bridgeDir = args.bridge ? path.resolve(args.bridge) : null; -let rncoreDir = args.rncore ? path.resolve(args.rncore) : null; -const buildDir = path.resolve( - args['build-dir'] ?? path.join(os.tmpdir(), 'rn-gpui-prebuilt-build'), -); -// Source of the native-deps cache (OpenSSL, curl, folly sources). A fresh build -// dir cannot build OpenSSL apps/ on macOS, so the cache is linked in. -const nativeDepsSource = args['native-deps'] - ? path.resolve(args['native-deps']) - : null; -const jobs = - args.jobs ?? String(os.availableParallelism?.() ?? os.cpus().length); -if (!version) fail('--version is required'); - -const platform = hostPlatform(); -const platformName = loom ? `loom-${platform}` : platform; -const platformDir = path.join(outDir, platformName); -const archiveName = `prebuilt-binaries-${platformName}.tar.gz`; -const started = Date.now(); - -function parseArgs(argv) { - const out = {}; - for (let i = 0; i < argv.length; i++) { - const key = argv[i]; - if (!key.startsWith('--')) fail(`unexpected argument ${key}`); - const name = key.slice(2); - if (name === 'skip-build') { - out[name] = true; - } else { - out[name] = argv[++i]; - } - } - return out; -} - -function fail(message) { - console.error(`build-prebuilt: ${message}`); - process.exit(2); -} - -function hostPlatform() { - const archMap = { arm64: 'arm64', x64: 'x64' }; - const arch = archMap[process.arch] ?? process.arch; - if (process.platform === 'darwin') return `darwin-${arch}`; - if (process.platform === 'linux') return `linux-${arch}`; - if (process.platform === 'win32') return `win32-${arch}`; - return `${process.platform}-${arch}`; -} - -function run(cmd, cmdArgs, options = {}) { - console.log(`$ ${cmd} ${cmdArgs.join(' ')}`); - const result = spawnSync(cmd, cmdArgs, { stdio: 'inherit', ...options }); - if (result.status !== 0) { - throw new Error(`${cmd} exited with ${result.status ?? result.signal}`); - } -} - -/** - * A path as a CMake `-D` value. - * - * CMake parses a `-D` value as source text, so a Windows backslash starts an - * escape and `-DFOO=C:\dir\gen` dies with "Invalid character escape '\g'". - * Forward slashes are valid separators on Windows, so pass those. - */ -function cmakePath(value) { - return path.resolve(value).split(path.sep).join('/'); -} - -/** - * The `tar` to archive with. - * - * On Windows `tar` resolves to whatever is first on `PATH`, and Git for Windows - * ships a GNU `tar` that reads `C:\...` as a remote host (`tar: Cannot connect - * to C: resolve failed`), so archiving only works with the bsdtar in System32. - * Prefer that by full path and fall back to the name for macOS and Linux, where - * the first `tar` on `PATH` is the right one. - */ -function tarCommand() { - if (process.platform === 'win32') { - const system32 = path.join( - process.env.SystemRoot ?? 'C:\\Windows', - 'System32', - 'tar.exe', - ); - if (existsSync(system32)) return system32; - } - return 'tar'; -} - -/** - * Links `target` at `linkPath`, or copies it when the platform will not make a - * link. - * - * A directory symlink on Windows needs an elevated process or Developer Mode - * (`EPERM: operation not permitted, symlink`), so a directory junction is used - * instead, which any user may create. Both are transparent to the build: CMake - * only reads the path. If neither works, copy, which always does. - */ -function linkDirectory(target, linkPath) { - try { - symlinkSync( - target, - linkPath, - process.platform === 'win32' ? 'junction' : 'dir', - ); - return; - } catch (error) { - if (process.platform !== 'win32') throw error; - console.log( - `note: could not link ${linkPath} (${error.code}); copying instead`, - ); - } - cpSync(target, linkPath, { recursive: true }); -} - -function sha256File(file) { - return createHash('sha256').update(readFileSync(file)).digest('hex'); -} - -function listFiles(dir, root = dir, out = []) { - for (const entry of readdirSync(dir)) { - const full = path.join(dir, entry); - if (statSync(full).isDirectory()) listFiles(full, root, out); - else out.push(path.relative(root, full).split(path.sep).join('/')); - } - return out.sort(); -} - -/// Absolute paths of every file under `dir` that `matches` accepts. -function findFiles(dir, matches) { - const out = []; - const walk = current => { - for (const entry of readdirSync(current, { withFileTypes: true })) { - const full = path.join(current, entry.name); - if (entry.isDirectory()) walk(full); - else if (matches(full)) out.push(full); - } - }; - if (existsSync(dir)) walk(dir); - return out.sort(); -} - -/** - * Whether a PDB is CMake's link-time-optimisation probe rather than a target's - * debug information. - * - * `_CMakeLTOTest-*` directories hold throwaway binaries CMake compiles to decide - * whether the toolchain supports LTO. Their PDBs are named after the probe - * sources (`boo.pdb`, `foo.pdb`, `vc143.pdb`), so several unrelated targets - * collide on one name, and none of them describes a library in the archive. - * CMake spells the directory with a leading underscore (`_CMakeLTOTest-CXX`). - */ -function isCmakeLtoTestArtifact(root, file) { - return path - .relative(root, file) - .split(path.sep) - .some(segment => /^_?CMakeLTOTest-/u.test(segment)); -} - -function sizeOfDir(dir) { - let total = 0; - for (const rel of listFiles(dir)) total += statSync(path.join(dir, rel)).size; - return total; -} - -function pkgVersion(file, key) { - return JSON.parse(readFileSync(file, 'utf8'))[key]; -} - -function cargoLockVersion(name) { - const text = readFileSync(cargoLock, 'utf8'); - const block = text - .split('[[package]]') - .find(b => b.includes(`name = "${name}"`)); - return block ? /version = "([^"]+)"/.exec(block)?.[1] : undefined; -} - -/** - * The compiler that built the archive, for the manifest. - * - * `c++ --version` is the Unix spelling; MSVC has no `c++` and spells the flag - * `/Bv`, so asking for `--version` there leaves `stdout` undefined. Report - * whatever the toolchain actually says, and fall back to a plain description - * rather than crashing the whole archive build over a metadata string. - */ -function compilerVersion() { - const [command, cmdArgs] = - process.platform === 'win32' - ? ['cl', ['/Bv']] - : [process.env.CXX ?? 'c++', ['--version']]; - const result = spawnSync(command, cmdArgs, { encoding: 'utf8' }); - const output = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim(); - const first = output - .split('\n') - .map(line => line.trim()) - .filter(Boolean)[0]; - return first ?? (process.platform === 'win32' ? 'cl' : 'unknown'); -} - -function libraryFiles(dir) { - const libDir = path.join(dir, 'lib'); - if (!existsSync(libDir)) return []; - return readdirSync(libDir) - .filter(f => /\.(a|lib|so|dylib|dll)$|\.lib$/.test(f)) - .sort(); -} - -const configuration = 'Release'; - -// Release with light debug info so stacks symbolize without the ~1.8 GB of -// full debug libs. The consumer (build.rs) must match the runtime ABI: -// - MSVC: /MD (MultiThreadedDLL) and _ITERATOR_DEBUG_LEVEL=0; PDBs ship -// separately (prebuilt-binaries-win32-x64-pdb.tar.gz). -// - clang/gcc: NDEBUG from Release, line tables only. -// These are recorded in the manifest `flags` field. -function buildFlags() { - const isMsvc = process.platform === 'win32'; - const isGcc = !isMsvc && process.platform === 'linux'; - const debugCxx = isMsvc ? '/Zi' : isGcc ? '-g1' : '-gline-tables-only'; - // One section per function and per datum, so the linker can drop what an - // executable never reaches. `cc` (which a source build goes through) adds - // these itself; a prebuilt that omitted them behaved differently from a - // source build in exactly one visible way: an unused C++ module's call into - // the Rust module installers stayed live, and the `rn-gpui-sys` test binary - // then failed to link `rn_gpui_fixture_badge_frame` on Linux. Rust links with - // `--gc-sections` and reports only the undefined symbols that survive it, so - // without per-function sections a single live function keeps a whole object. - // MSVC has no equivalent flag; it dead-strips per function already. - const sections = isMsvc ? [] : ['-ffunction-sections', '-fdata-sections']; - const common = ['-w', ...sections]; - return { - cxx: [...common, debugCxx], - c: [...common, debugCxx], - msvcRuntimeLibrary: isMsvc ? 'MultiThreadedDLL' : null, - msvcIteratorDebugLevel: isMsvc ? '0' : null, - debugInfo: isMsvc ? 'pdb-separate' : 'embedded-line-tables', - }; -} -const flags = buildFlags(); -// MSVC needs the iterator-debug level as a compile definition; other toolchains -// get only the warning and debug flags. -const cxxFlags = [ - ...flags.cxx, - ...(flags.msvcIteratorDebugLevel !== null - ? [`/D_ITERATOR_DEBUG_LEVEL=${flags.msvcIteratorDebugLevel}`] - : []), -].join(' '); -const cFlags = [ - ...flags.c, - ...(flags.msvcIteratorDebugLevel !== null - ? [`/D_ITERATOR_DEBUG_LEVEL=${flags.msvcIteratorDebugLevel}`] - : []), -].join(' '); - -if (!bridgeDir || !rncoreDir) { - const generated = spawnSync( - process.execPath, - [path.join(scriptDir, 'generate-prebuilt-inputs.mjs'), generatedDir], - { - stdio: ['ignore', 'pipe', 'inherit'], - encoding: 'utf8', - env: { - ...process.env, - ...(loom ? { RN_GPUI_REACT_NATIVE_DIR: loomTreeDir } : {}), - }, - }, - ); - if (generated.status !== 0) - fail('generating cxxbridge/FBReactNativeSpec failed'); - const [bridgeOut, rncoreOut] = generated.stdout.trim().split('\n'); - bridgeDir ??= bridgeOut; - rncoreDir ??= rncoreOut; -} -if (!existsSync(path.join(bridgeDir, 'rust', 'cxx.h'))) - fail(`missing ${path.join(bridgeDir, 'rust', 'cxx.h')}`); -if (!existsSync(path.join(rncoreDir, 'jni'))) - fail(`missing ${path.join(rncoreDir, 'jni')}`); - -if (!args['skip-build']) { - mkdirSync(buildDir, { recursive: true }); - const linkedDeps = path.join(buildDir, 'native-deps'); - if ( - nativeDepsSource && - !existsSync(linkedDeps) && - existsSync(nativeDepsSource) - ) { - linkDirectory(nativeDepsSource, linkedDeps); - } - run('cmake', [ - '-S', - cppDir, - '-B', - buildDir, - `-DCMAKE_BUILD_TYPE=${configuration}`, - // Cargo's cmake crate builds with -w (warnings suppressed); the prebuilt - // matches it, since boost headers emit -Werror warnings under clang. - `-DCMAKE_CXX_FLAGS=${cxxFlags}`, - `-DCMAKE_C_FLAGS=${cFlags}`, - ...(flags.msvcRuntimeLibrary - ? [ - `-DCMAKE_MSVC_RUNTIME_LIBRARY=${flags.msvcRuntimeLibrary}`, - '-DCMAKE_POLICY_DEFAULT_CMP0091=NEW', - ] - : []), - // curl's docs/man-page install rules need generated pages the source build - // never makes. The prebuilt installs curl's headers and library itself. - '-DCURL_DISABLE_INSTALL=ON', - // Forward slashes: a `-D` value is parsed as a CMake string, where a - // backslash starts an escape, so `-D...=C:\rn-gpui\...` fails at configure - // time with "Invalid character escape '\g'". CMake accepts '/' on Windows - // and `build.rs` normalises the same paths the same way. - `-DRN_GPUI_PROJECT_ROOT=${cmakePath(repoRoot)}`, - `-DREACT_COMMON_DIR=${cmakePath(reactCommonDir)}`, - `-DREACT_CXX_PLATFORM_DIR=${cmakePath(reactCxxPlatformDir)}`, - `-DRN_GPUI_OVERRIDES_DIR=${cmakePath(overridesDir)}`, - `-DRN_GPUI_CXXBRIDGE_INCLUDE_DIR=${cmakePath(bridgeDir)}`, - `-DRN_GPUI_GENERATED_RNCORE_DIR=${cmakePath(rncoreDir)}`, - ...(loom - ? [ - `-DLOOM_RENDERER=1`, - `-DRN_GPUI_REACT_NATIVE_DIR=${cmakePath(loomTreeDir)}`, - ] - : []), - ]); - run('cmake', [ - '--build', - buildDir, - '--target', - 'rn_gpui_core', - '--parallel', - jobs, - '--config', - configuration, - ]); -} - -rmSync(platformDir, { recursive: true, force: true }); -mkdirSync(platformDir, { recursive: true }); -run('cmake', [ - '--install', - buildDir, - '--config', - configuration, - '--prefix', - platformDir, -]); - -// Native-deps archives the build downloaded (DownloadNativeDeps.cmake), with -// their sha256, so consumers and CI can see exactly which sources a build used. -// The downloads live in a cache shared with other builds, so the list comes from -// the `name sha256` lines CMake writes for the archives it pinned and verified. -function nativeDepsArchives(dir) { - const list = path.join(dir, 'native-deps', 'archives.txt'); - if (!existsSync(list)) return []; - return readFileSync(list, 'utf8') - .split('\n') - .filter(line => line.trim()) - .map(line => { - const [name, sha256] = line.trim().split(' '); - return { name, sha256 }; - }); -} - -const inputs = inputHash(renderer); -const files = {}; -for (const rel of listFiles(platformDir)) { - if (rel === 'manifest.json') continue; - files[rel] = sha256File(path.join(platformDir, rel)); -} -const manifest = { - formatVersion: 1, - version, - renderer, - ...(loom - ? { - loom: JSON.parse( - readFileSync( - path.join(packageDir, 'ReactGpui', 'loom-pin.json'), - 'utf8', - ), - ).commit, - } - : {}), - inputHash: inputs.hash, - sourceCommit: spawnSync('git', ['rev-parse', 'HEAD'], { - cwd: repoRoot, - encoding: 'utf8', - }).stdout.trim(), - reactNative: pkgVersion(reactNativePkg, 'version'), - triple: platform, - cxxStdlib: - process.platform === 'darwin' - ? 'libc++' - : process.platform === 'linux' - ? 'libstdc++' - : 'msvc', - compiler: compilerVersion(), - cxxStandard: 20, - msvcRuntime: process.platform === 'win32' ? '/MD' : null, - cxxCrate: cargoLockVersion('cxx'), - cxxBridgeHeaderSha256: sha256File( - path.join(bridgeDir, 'rn-gpui-sys', 'src', 'lib.rs.h'), - ), - overridesSha256: overridesSha256(renderer), - // Read by the consumer: the archive is Release, so its ReactCommon headers - // select the production ABI. No engine define belongs here; the engine glue - // is compiled by the app instead (see RN_GPUI_JS_ENGINE_* in cpp/CMakeLists.txt). - defines: { REACT_NATIVE_DEBUG: 0 }, - flags, - minOs: process.platform === 'darwin' ? 'macos 11.0' : null, - glibc: process.platform === 'linux' ? '2.36' : null, - libraries: libraryFiles(platformDir), - // Headers are not shipped: consumers take them from node_modules/react-native, - // this package, their own build.rs output, any installed engine package and - // the native-deps downloads listed here. OpenSSL's generated headers are the only - // exception (include/openssl-generated). - nativeDeps: nativeDepsArchives(buildDir), - files, -}; -writeFileSync( - path.join(platformDir, 'manifest.json'), - `${JSON.stringify(manifest, null, 2)}\n`, -); - -const archivePath = path.join(outDir, archiveName); -rmSync(archivePath, { force: true }); -run(tarCommand(), ['-czf', archivePath, '-C', outDir, platformName]); -writeFileSync( - `${archivePath}.sha256`, - `${sha256File(archivePath)} ${archiveName}\n`, -); - -// Static libraries carry their debug information in PDB files that live next to -// the objects, not inside the archive, so the symbols are useless to a consumer -// unless they are published too. This is what the workflow's "Collect Windows -// PDBs" step does; doing it here means a local build produces the same two -// archives the release does. Collection is flat (one directory), as the -// workflow's is, because a debugger is given the PDB search path rather than a -// mirrored tree. -if (process.platform === 'win32') { - const pdbDir = path.join(outDir, 'pdb'); - rmSync(pdbDir, { recursive: true, force: true }); - mkdirSync(pdbDir, { recursive: true }); - // A flat directory cannot hold two files with one name, so record what each - // name already staged with; identical content is a harmless duplicate and - // differing content is refused rather than silently dropped. - const staged = new Map(); - let pdbCount = 0; - for (const pdb of findFiles( - buildDir, - file => - path.extname(file) === '.pdb' && !isCmakeLtoTestArtifact(buildDir, file), - )) { - const name = path.basename(pdb); - const previous = staged.get(name); - if (previous !== undefined) { - if (sha256File(previous) === sha256File(pdb)) continue; - fail( - `two different PDBs are both named ${name}:\n` + - ` ${path.relative(buildDir, previous)}\n ${path.relative(buildDir, pdb)}\n` + - 'The PDB archive is flat, so one would be lost.', - ); - } - staged.set(name, pdb); - cpSync(pdb, path.join(pdbDir, name)); - pdbCount += 1; - } - if (pdbCount === 0) { - fail(`no PDB files were produced under ${buildDir}`); - } - const pdbArchiveName = `prebuilt-binaries-${platformName}-pdb.tar.gz`; - const pdbArchivePath = path.join(outDir, pdbArchiveName); - rmSync(pdbArchivePath, { force: true }); - run(tarCommand(), ['-czf', pdbArchivePath, '-C', pdbDir, '.']); - writeFileSync( - `${pdbArchivePath}.sha256`, - `${sha256File(pdbArchivePath)} ${pdbArchiveName}\n`, - ); - console.log(`pdb archive ${pdbArchivePath} (${pdbCount} files)`); -} - -const seconds = Math.round((Date.now() - started) / 1000); -console.log(`archive ${archivePath} (${statSync(archivePath).size} bytes)`); -console.log(`installed tree ${platformDir} (${sizeOfDir(platformDir)} bytes)`); -console.log(`inputHash ${inputs.hash}`); -console.log(`build-prebuilt done in ${seconds}s`); diff --git a/vendor/react-native-gpui/packages/core/scripts/check-loom-overrides.mjs b/vendor/react-native-gpui/packages/core/scripts/check-loom-overrides.mjs deleted file mode 100644 index 9084b54973..0000000000 --- a/vendor/react-native-gpui/packages/core/scripts/check-loom-overrides.mjs +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env node -// Fails when a file Loom changes, and that a Loom variant in -// ReactCommonOverrides.loom was copied from, is not the one the pinned Loom -// ships any more. Run it after moving the pin. -import { createHash } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { createRequire } from 'node:module'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const packageDir = path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - '..', -); -const require = createRequire(import.meta.url); -const { materializedTree } = require('../renderer.js'); -const overrides = JSON.parse( - readFileSync(path.join(packageDir, 'overrides.json'), 'utf8'), -); - -const tree = await materializedTree(packageDir); -const stale = []; -let checked = 0; -for (const override of overrides.overrides) { - if (!override.loomBaseFile) continue; - checked += 1; - const actual = createHash('sha256') - .update(readFileSync(path.join(tree.reactNativeDir, override.loomBaseFile))) - .digest('hex'); - if (actual !== override.loomBaseHash) { - stale.push(`${override.file}: ${override.loomBaseFile} is now ${actual}`); - } -} -if (stale.length > 0) { - console.error( - `Loom ${tree.loomVersion} changed files a Loom variant was copied from:\n ${stale.join('\n ')}\nCarry the change over to the variant and update loomBaseHash.`, - ); - process.exit(1); -} -console.log(`${checked} Loom variants match Loom ${tree.loomVersion}`); diff --git a/vendor/react-native-gpui/packages/core/scripts/check-prebuilt-pin.mjs b/vendor/react-native-gpui/packages/core/scripts/check-prebuilt-pin.mjs deleted file mode 100644 index 875ddad716..0000000000 --- a/vendor/react-native-gpui/packages/core/scripts/check-prebuilt-pin.mjs +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/env node - -import { spawnSync } from 'node:child_process'; -import { readFileSync } from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { PREBUILT_RENDERERS } from './prebuilt-renderers.mjs'; - -const scriptDir = path.dirname(fileURLToPath(import.meta.url)); -const packageDir = path.resolve(scriptDir, '..'); - -if (process.env.RN_GPUI_SKIP_PREBUILT_PIN_CHECK === '1') { - console.warn( - 'check-prebuilt-pin: RN_GPUI_SKIP_PREBUILT_PIN_CHECK=1; skipping the pin check.', - ); - process.exit(0); -} - -const pin = JSON.parse( - readFileSync(path.join(packageDir, 'prebuilt-binaries.json'), 'utf8'), -); - -const hashRun = spawnSync( - process.execPath, - [path.join(scriptDir, 'prebuilt-inputs.mjs')], - { encoding: 'utf8' }, -); -if (hashRun.status !== 0) { - console.error( - `check-prebuilt-pin: cannot compute the input hash\n${hashRun.stderr}`, - ); - process.exit(1); -} -const current = hashRun.stdout.trim(); - -const loomPrebuilt = PREBUILT_RENDERERS.includes('loom'); -let currentLoom = ''; -if (loomPrebuilt) { - const loomRun = spawnSync( - process.execPath, - [path.join(scriptDir, 'prebuilt-inputs.mjs'), '--renderer', 'loom'], - { encoding: 'utf8' }, - ); - if (loomRun.status !== 0) { - console.error( - `check-prebuilt-pin: cannot compute the Loom input hash\n${loomRun.stderr}`, - ); - process.exit(1); - } - currentLoom = loomRun.stdout.trim(); -} - -const problems = []; -if (pin.inputHash !== current) { - problems.push( - `pin inputHash ${pin.inputHash || '(empty)'} does not match the current C++ inputs ${current}`, - ); -} -if (!pin.assets || Object.keys(pin.assets).length === 0) { - problems.push('pin lists no prebuilt assets'); -} -if (loomPrebuilt && pin.loom?.inputHash !== currentLoom) { - problems.push( - `pin loom.inputHash ${pin.loom?.inputHash || '(empty)'} does not match the current Loom C++ inputs ${currentLoom}`, - ); -} -if ( - loomPrebuilt && - (!pin.loom?.assets || Object.keys(pin.loom.assets).length === 0) -) { - problems.push('pin lists no Loom prebuilt assets'); -} - -if (problems.length > 0) { - console.error( - 'react-native-gpui will not publish with a stale prebuilt pin:', - ); - for (const p of problems) console.error(` - ${p}`); - console.error( - 'Run the prebuilt-binaries workflow (or force it) so the pin is updated, then publish.', - ); - process.exit(1); -} -console.log( - `check-prebuilt-pin: pin ${pin.version} matches inputHash ${current}`, -); diff --git a/vendor/react-native-gpui/packages/core/scripts/check-standalone-cmake.mjs b/vendor/react-native-gpui/packages/core/scripts/check-standalone-cmake.mjs deleted file mode 100644 index c4f33b1679..0000000000 --- a/vendor/react-native-gpui/packages/core/scripts/check-standalone-cmake.mjs +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env node - -import { spawnSync } from 'node:child_process'; -import { existsSync, mkdirSync } from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { findNodeModule, repoRoot as findRepoRoot } from './repo-root.mjs'; - -const scriptDir = path.dirname(fileURLToPath(import.meta.url)); -const packageDir = path.resolve(scriptDir, '..'); -const repoRoot = findRepoRoot(scriptDir); -const cppDir = path.join(packageDir, 'ReactGpui', 'rn-gpui-sys', 'cpp'); -const reactNativeRoot = - findNodeModule(packageDir, 'react-native') ?? - path.join(repoRoot, 'node_modules', 'react-native'); -const reactCommonDir = path.join(reactNativeRoot, 'ReactCommon'); -const reactCxxPlatformDir = path.join(packageDir, 'ReactCxxPlatform'); -const overridesDir = path.join(packageDir, 'ReactCommonOverrides'); - -const [, , bridgeArg, rncoreArg, buildArg] = process.argv; -if (!bridgeArg || !rncoreArg) { - console.error( - 'usage: check-standalone-cmake.mjs [build-dir]', - ); - process.exit(2); -} -const bridgeDir = path.resolve(bridgeArg); -const rncoreDir = path.resolve(rncoreArg); -if (!existsSync(path.join(bridgeDir, 'rust', 'cxx.h'))) { - console.error(`missing ${path.join(bridgeDir, 'rust', 'cxx.h')}`); - process.exit(2); -} -const buildDir = path.resolve( - buildArg ?? path.join(os.tmpdir(), 'rn-gpui-standalone-cmake'), -); -mkdirSync(buildDir, { recursive: true }); - -const cmake = args => { - const result = spawnSync('cmake', args, { stdio: 'inherit' }); - if (result.status !== 0) { - process.exit(result.status ?? 1); - } -}; - -cmake([ - '-S', - cppDir, - '-B', - buildDir, - '-DCMAKE_BUILD_TYPE=Debug', - `-DRN_GPUI_PROJECT_ROOT=${repoRoot}`, - `-DREACT_COMMON_DIR=${reactCommonDir}`, - `-DREACT_CXX_PLATFORM_DIR=${reactCxxPlatformDir}`, - `-DRN_GPUI_OVERRIDES_DIR=${overridesDir}`, - `-DRN_GPUI_CXXBRIDGE_INCLUDE_DIR=${bridgeDir}`, - `-DRN_GPUI_GENERATED_RNCORE_DIR=${rncoreDir}`, -]); -cmake(['--build', buildDir, '--target', 'rn_gpui_core', '--parallel']); -console.log(`rn_gpui_core built in ${buildDir}`); diff --git a/vendor/react-native-gpui/packages/core/scripts/generate-prebuilt-inputs.mjs b/vendor/react-native-gpui/packages/core/scripts/generate-prebuilt-inputs.mjs deleted file mode 100644 index e044fc9f75..0000000000 --- a/vendor/react-native-gpui/packages/core/scripts/generate-prebuilt-inputs.mjs +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env node - -import { spawnSync } from 'node:child_process'; -import { - existsSync, - mkdirSync, - readFileSync, - rmSync, - writeFileSync, -} from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { findNodeModule, repoRoot as findRepoRoot } from './repo-root.mjs'; - -const scriptDir = path.dirname(fileURLToPath(import.meta.url)); -const packageDir = path.resolve(scriptDir, '..'); -const repoRoot = findRepoRoot(scriptDir); -// The Loom runtime generates from its own React Native tree. -const reactNativeDir = - process.env.RN_GPUI_REACT_NATIVE_DIR ?? - findNodeModule(packageDir, 'react-native') ?? - path.join(repoRoot, 'node_modules', 'react-native'); -const rnGpuiSysDir = path.join(packageDir, 'ReactGpui', 'rn-gpui-sys'); -const fbSpecCodegen = path.join( - rnGpuiSysDir, - 'scripts', - 'generate-fbreactnativespec.cjs', -); - -// Keep this in sync with the cxx entry in ReactGpui/Cargo.lock. -const CXX_VERSION = '1.0.202'; - -function fail(message) { - console.error(`generate-prebuilt-inputs: ${message}`); - process.exit(2); -} - -function run(cmd, args, options = {}) { - const result = spawnSync(cmd, args, { - stdio: ['ignore', 'pipe', 'inherit'], - encoding: 'utf8', - maxBuffer: 64 * 1024 * 1024, - ...options, - }); - if (result.status !== 0) { - fail( - `${cmd} ${args.join(' ')} exited with ${result.status ?? result.signal}`, - ); - } - return result.stdout; -} - -function lockedCxxVersion() { - const lock = readFileSync( - path.join(packageDir, 'ReactGpui', 'Cargo.lock'), - 'utf8', - ); - const match = lock.match(/name = "cxx"\r?\nversion = "([^"]+)"/u); - if (!match) fail('cxx is not in ReactGpui/Cargo.lock'); - if (match[1] !== CXX_VERSION) { - fail(`Cargo.lock pins cxx ${match[1]}; update CXX_VERSION to match`); - } - return match[1]; -} - -function ensureCxxbridge(toolRoot) { - const bin = path.join( - toolRoot, - 'bin', - process.platform === 'win32' ? 'cxxbridge.exe' : 'cxxbridge', - ); - if (existsSync(bin)) return bin; - mkdirSync(toolRoot, { recursive: true }); - console.error( - `generate-prebuilt-inputs: installing cxxbridge-cmd ${CXX_VERSION}`, - ); - run( - 'cargo', - [ - 'install', - '--locked', - '--version', - CXX_VERSION, - 'cxxbridge-cmd', - '--root', - toolRoot, - ], - { stdio: 'inherit' }, - ); - if (!existsSync(bin)) fail(`cargo install did not produce ${bin}`); - return bin; -} - -const outDir = path.resolve(process.argv[2] ?? fail('usage: ')); -lockedCxxVersion(); - -const toolRoot = path.join(os.tmpdir(), `rn-gpui-cxxbridge-${CXX_VERSION}`); -const cxxbridge = ensureCxxbridge(toolRoot); - -const bridgeInclude = path.join(outDir, 'cxxbridge-include'); -rmSync(bridgeInclude, { recursive: true, force: true }); -mkdirSync(path.join(bridgeInclude, 'rust'), { recursive: true }); -mkdirSync(path.join(bridgeInclude, 'rn-gpui-sys', 'src'), { recursive: true }); -const cxxH = run(cxxbridge, ['--header']); -writeFile(path.join(bridgeInclude, 'rust', 'cxx.h'), cxxH); -const libRsH = run(cxxbridge, [ - path.join(rnGpuiSysDir, 'src', 'lib.rs'), - '--header', -]); -writeFile(path.join(bridgeInclude, 'rn-gpui-sys', 'src', 'lib.rs.h'), libRsH); - -const rncoreDir = path.join(outDir, 'fbreactnativespec'); -rmSync(rncoreDir, { recursive: true, force: true }); -run(process.execPath, [fbSpecCodegen, reactNativeDir, rncoreDir], { - stdio: 'inherit', -}); -if (!existsSync(path.join(rncoreDir, 'jni'))) { - fail(`codegen produced no jni/ under ${rncoreDir}`); -} - -console.error(`generate-prebuilt-inputs: bridge ${bridgeInclude}`); -console.error(`generate-prebuilt-inputs: rncore ${rncoreDir}`); -process.stdout.write(`${bridgeInclude}\n${rncoreDir}\n`); - -function writeFile(file, content) { - writeFileSync(file, content); -} diff --git a/vendor/react-native-gpui/packages/core/scripts/prebuilt-binaries.mjs b/vendor/react-native-gpui/packages/core/scripts/prebuilt-binaries.mjs deleted file mode 100644 index 83830b2598..0000000000 --- a/vendor/react-native-gpui/packages/core/scripts/prebuilt-binaries.mjs +++ /dev/null @@ -1,548 +0,0 @@ -#!/usr/bin/env node -// Fetches, verifies and caches the prebuilt C++ runtime for react-native-gpui. -// -// Usage: -// node scripts/prebuilt-binaries.mjs ensure [--triple ] [--renderer fabric|loom] -// Print the cached runtime dir, downloading it first when needed. -// --renderer loom takes the runtime built against Loom's React Native -// tree (pin file `loom` section); fabric is the default. -// Exit 2 when the pin file has no asset for the platform. -// node scripts/prebuilt-binaries.mjs fetch [--triple ] -// Same as ensure (the host triple by default). -// node scripts/prebuilt-binaries.mjs path [--triple ] -// Print the cache dir for the platform (does not download). -// node scripts/prebuilt-binaries.mjs verify -// Check every files[].sha256 in /manifest.json. -// node scripts/prebuilt-binaries.mjs clean -// Remove the cache for this package version. -// node scripts/prebuilt-binaries.mjs pin --version --input-hash --tag -// --repo --sums --out -// [--loom-input-hash ] -// Write the pin file from a release's SHA256SUMS.txt (used by CI). -// -// stdout carries only the result dir (or the verify result); diagnostics go to -// stderr. Environment: -// RN_GPUI_PREBUILT_CACHE cache root (default: the OS cache dir) -// RN_GPUI_PREBUILT_OFFLINE=1 or CARGO_NET_OFFLINE=true: cache only, no network -// GITHUB_TOKEN / GH_TOKEN optional, sent with release downloads -// -// The pin file (packages/core/prebuilt-binaries.json) names the -// release and per-platform assets: { version, inputHash, repo, tag, assets: -// { "": { file, sha256, size } }, loom: { inputHash, loom, assets } }. -// `loom` describes the same release's Loom archives, named -// prebuilt-binaries-loom-.tar.gz. An empty assets map means no -// prebuilt is published yet. - -import { execFileSync, spawnSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; -import { - closeSync, - createReadStream, - createWriteStream, - existsSync, - mkdirSync, - openSync, - readFileSync, - renameSync, - rmSync, - statSync, - unlinkSync, - writeFileSync, -} from 'node:fs'; -import { request as httpsRequest } from 'node:https'; -import { request as httpRequest } from 'node:http'; -import os from 'node:os'; -import path from 'node:path'; -import { fileURLToPath, URL } from 'node:url'; -import { copyFile as copyFileCb } from 'node:fs'; - -function copyFile(src, dest) { - return new Promise((resolve, reject) => - copyFileCb(src, dest, err => (err ? reject(err) : resolve())), - ); -} - -/** - * The tar to extract an archive with. On Windows, use the bsdtar that ships - * with the OS: a bash step puts Git-for-Windows' GNU tar first on PATH, and GNU - * tar reads a `D:\...` argument as a remote host spec, failing with - * "Cannot connect to D: resolve failed". Same reason `fetch-binaries.mjs` - * prefers it for the Hermes zips. - */ -function tarCommand() { - if (process.platform !== 'win32') return 'tar'; - const systemTar = path.join( - process.env.SystemRoot ?? 'C:\\Windows', - 'System32', - 'tar.exe', - ); - return existsSync(systemTar) ? systemTar : 'tar'; -} - -const scriptDir = path.dirname(fileURLToPath(import.meta.url)); -const packageDir = path.resolve(scriptDir, '..'); -const pinPath = path.join(packageDir, 'prebuilt-binaries.json'); - -const TRIPLE_PLATFORMS = { - 'aarch64-apple-darwin': 'darwin-arm64', - 'x86_64-apple-darwin': 'darwin-x64', - 'x86_64-unknown-linux-gnu': 'linux-x64', - 'aarch64-unknown-linux-gnu': 'linux-arm64', - 'x86_64-pc-windows-msvc': 'win32-x64', - 'aarch64-pc-windows-msvc': 'win32-arm64', -}; -const MAX_REDIRECTS = 8; - -function die(message, status = 1) { - process.stderr.write(`prebuilt-binaries: ${message}\n`); - process.exit(status); -} - -function log(message) { - process.stderr.write(`prebuilt-binaries: ${message}\n`); -} - -function readPin() { - return JSON.parse(readFileSync(pinPath, 'utf8')); -} - -function hostTriple() { - const arch = process.arch === 'arm64' ? 'aarch64' : 'x86_64'; - if (process.platform === 'darwin') return `${arch}-apple-darwin`; - if (process.platform === 'win32') return `${arch}-pc-windows-msvc`; - if (process.platform === 'linux') return `${arch}-unknown-linux-gnu`; - die(`unsupported host ${process.platform}-${process.arch}`); -} - -function platformFor(triple) { - const platform = TRIPLE_PLATFORMS[triple]; - if (!platform) die(`no prebuilt platform for triple ${triple}`); - return platform; -} - -function parseArgs(argv) { - const args = { _: [] }; - for (let i = 0; i < argv.length; i += 1) { - const arg = argv[i]; - if (arg === '--triple') args.triple = argv[++i]; - else if (arg.startsWith('--triple=')) args.triple = arg.slice(9); - else if (arg.startsWith('--')) { - const key = arg.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase()); - args[key] = argv[++i]; - } else args._.push(arg); - } - return args; -} - -function cacheRoot() { - if (process.env.RN_GPUI_PREBUILT_CACHE) { - return path.resolve(process.env.RN_GPUI_PREBUILT_CACHE); - } - if (process.platform === 'darwin') { - return path.join(os.homedir(), 'Library', 'Caches'); - } - if (process.platform === 'win32') { - return path.join( - process.env.LOCALAPPDATA ?? path.join(os.homedir(), 'AppData', 'Local'), - ); - } - return process.env.XDG_CACHE_HOME ?? path.join(os.homedir(), '.cache'); -} - -function cacheDir(version, platform) { - if (process.env.RN_GPUI_PREBUILT_CACHE) { - return path.join(cacheRoot(), version, platform); - } - return path.join( - cacheRoot(), - 'react-native-gpui', - 'prebuilt', - version, - platform, - ); -} - -function offline() { - return ( - process.env.RN_GPUI_PREBUILT_OFFLINE === '1' || - process.env.CARGO_NET_OFFLINE === 'true' - ); -} - -function sha256File(file) { - return new Promise((resolve, reject) => { - const hash = createHash('sha256'); - createReadStream(file) - .on('data', chunk => hash.update(chunk)) - .on('error', reject) - .on('end', () => resolve(hash.digest('hex'))); - }); -} - -function isComplete(dir) { - return existsSync(path.join(dir, 'manifest.json')); -} - -// Follows redirects, sends the token only to GitHub hosts, and streams the body -// to dest while counting bytes. -function download(url, dest, redirects = 0, headers = {}) { - if (url.startsWith('file:')) { - return copyFile(fileURLToPath(url), dest); - } - return new Promise((resolve, reject) => { - if (redirects > MAX_REDIRECTS) - return reject(new Error('too many redirects')); - const parsed = new URL(url); - const send = parsed.protocol === 'http:' ? httpRequest : httpsRequest; - const reqHeaders = { - 'user-agent': 'react-native-gpui-prebuilt', - ...headers, - }; - const req = send(parsed, { headers: reqHeaders }, res => { - if ( - res.statusCode >= 300 && - res.statusCode < 400 && - res.headers.location - ) { - res.resume(); - const next = new URL(res.headers.location, parsed).toString(); - // Drop the auth header when leaving GitHub, as curl does. - const keep = - new URL(next).hostname.endsWith('github.com') || - new URL(next).hostname.endsWith('githubusercontent.com'); - const nextHeaders = keep ? headers : {}; - return resolve(download(next, dest, redirects + 1, nextHeaders)); - } - if (res.statusCode !== 200) { - res.resume(); - return reject(new Error(`HTTP ${res.statusCode} for ${url}`)); - } - const total = Number(res.headers['content-length']); - let received = 0; - let reported = 0; - if (total > 0) { - res.on('data', chunk => { - received += chunk.length; - const percent = Math.floor((received / total) * 10) * 10; - if (percent > reported) { - reported = percent; - log(`downloaded ${percent}%`); - } - }); - } - const out = createWriteStream(dest); - res.pipe(out); - out.on('finish', () => resolve()); - out.on('error', reject); - res.on('error', reject); - }); - req.on('error', reject); - req.end(); - }); -} - -function releaseAuthHeaders() { - const token = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN; - const headers = { accept: 'application/octet-stream' }; - if (token) headers.authorization = `Bearer ${token}`; - return headers; -} - -// RN_GPUI_PREBUILT_BASE_URL replaces the GitHub release base (file:// or -// http:// mirrors, used for testing and offline mirrors). -function assetUrl(pin, asset) { - const base = process.env.RN_GPUI_PREBUILT_BASE_URL; - if (base) return `${base.replace(/\/$/, '')}/${asset.file}`; - return `https://github.com/${pin.repo}/releases/download/${encodeURIComponent( - pin.tag, - )}/${asset.file}`; -} - -function acquireLock(lockPath) { - for (let attempt = 0; attempt < 600; attempt += 1) { - try { - const fd = openSync(lockPath, 'wx'); - writeFileSync(fd, String(process.pid)); - closeSync(fd); - return; - } catch (error) { - if (error.code !== 'EEXIST') throw error; - if (attempt === 0) log(`waiting for another download (${lockPath})`); - Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 500); - // A lock left by a dead process is removed after 10 minutes. - try { - if (Date.now() - statSync(lockPath).mtimeMs > 600_000) - unlinkSync(lockPath); - } catch {} - } - } - throw new Error(`timed out waiting for lock ${lockPath}`); -} - -async function ensureDir( - triple, - { allowNetwork = true, renderer = 'fabric' } = {}, -) { - const pin = readPin(); - const platform = platformFor(triple); - const loom = renderer === 'loom'; - const asset = (loom ? pin.loom : pin)?.assets?.[platform]; - if (!asset) { - die( - `no ${renderer} prebuilt asset for ${platform} in ${path.relative(packageDir, pinPath)} (version ${pin.version}); build from source or publish one`, - 2, - ); - } - const dir = cacheDir(pin.version, loom ? `loom-${platform}` : platform); - if (isComplete(dir)) { - return dir; - } - if (!allowNetwork || offline()) { - die( - `prebuilt ${platform} is not cached at ${dir} and offline mode is on`, - 3, - ); - } - - const parent = path.dirname(dir); - mkdirSync(parent, { recursive: true }); - const lockPath = `${dir}.lock`; - acquireLock(lockPath); - let temp; - try { - // Another process may have finished while we waited for the lock. - if (isComplete(dir)) return dir; - - temp = path.join( - parent, - `.${platform}-${process.pid}-${Date.now()}.tar.gz`, - ); - const url = assetUrl(pin, asset); - log(`downloading ${asset.file} (${asset.size} bytes)`); - await download(url, temp, 0, releaseAuthHeaders()); - - const size = statSync(temp).size; - if (size !== asset.size) { - throw new Error( - `size mismatch for ${asset.file}: expected ${asset.size}, got ${size}`, - ); - } - const digest = await sha256File(temp); - if (digest !== asset.sha256) { - throw new Error( - `sha256 mismatch for ${asset.file}: expected ${asset.sha256}, got ${digest}`, - ); - } - - const stage = path.join(parent, `.${platform}-${process.pid}-stage`); - rmSync(stage, { recursive: true, force: true }); - mkdirSync(stage, { recursive: true }); - const tar = spawnSync( - tarCommand(), - ['-xzf', temp, '-C', stage, '--strip-components=1'], - { - stdio: ['ignore', 'ignore', 'pipe'], - }, - ); - if (tar.status !== 0) { - throw new Error( - `tar failed: ${tar.stderr?.toString().trim() ?? tar.error}`, - ); - } - if (!isComplete(stage)) { - throw new Error('archive has no manifest.json at its top level'); - } - rmSync(dir, { recursive: true, force: true }); - renameSync(stage, dir); - log(`installed ${platform} runtime in ${dir}`); - return dir; - } finally { - if (temp) rmSync(temp, { force: true }); - rmSync(lockPath, { force: true }); - } -} - -async function verifyDir(dir) { - const manifestPath = path.join(dir, 'manifest.json'); - if (!existsSync(manifestPath)) { - throw new Error(`no manifest.json in ${dir}`); - } - const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')); - const failures = []; - for (const [rel, expected] of Object.entries(manifest.files ?? {})) { - const file = path.join(dir, rel); - if (!existsSync(file)) { - failures.push(`missing ${rel}`); - continue; - } - const digest = await sha256File(file); - if (digest !== expected) failures.push(`sha256 mismatch ${rel}`); - } - return { - ok: failures.length === 0, - failures, - count: Object.keys(manifest.files ?? {}).length, - }; -} - -async function main() { - const [command, ...rest] = process.argv.slice(2); - const args = parseArgs(rest); - const triple = args.triple ?? hostTriple(); - - switch (command) { - case 'ensure': - case 'fetch': { - const dir = await ensureDir(triple, { - renderer: args.renderer ?? 'fabric', - }); - process.stdout.write(`${dir}\n`); - return; - } - case 'path': { - const pin = readPin(); - const platform = platformFor(triple); - process.stdout.write( - `${cacheDir(pin.version, args.renderer === 'loom' ? `loom-${platform}` : platform)}\n`, - ); - return; - } - case 'verify': { - const dir = args._[0]; - if (!dir) die('verify needs a ', 1); - const result = await verifyDir(path.resolve(dir)); - if (!result.ok) { - for (const failure of result.failures) log(failure); - die(`verification failed (${result.failures.length} problem(s))`, 1); - } - process.stdout.write(`${path.resolve(dir)}\n`); - log(`verified ${result.count} files`); - return; - } - case 'clean': { - const pin = readPin(); - const root = process.env.RN_GPUI_PREBUILT_CACHE - ? path.join(cacheRoot(), pin.version) - : path.join(cacheRoot(), 'react-native-gpui', 'prebuilt', pin.version); - rmSync(root, { recursive: true, force: true }); - log(`removed ${root}`); - return; - } - case 'pin': { - // `--sums` and `--assets` are the same file: the CI workflow calls it - // `--assets` while the usage line above says `--sums`. Accept both so the - // published pin can be written by the command the workflow runs. - const sums = args.sums ?? args.assets; - const { version, inputHash, tag, repo, out } = args; - for (const [k, v] of Object.entries({ - version, - inputHash, - tag, - repo, - sums, - out, - })) { - if (!v) - die( - `pin needs --${k.replace(/[A-Z]/g, c => '-' + c.toLowerCase())}`, - 2, - ); - } - const sumsDir = path.dirname(path.resolve(sums)); - const loomInputHash = args.loomInputHash; - const assets = {}; - const loomAssets = {}; - let loomCommit = null; - let reactNative = null; - for (const rawLine of readFileSync(sums, 'utf8').split('\n')) { - // A sums file written on Windows (PowerShell's `Set-Content`, or a - // checkout with `core.autocrlf`) has CRLF endings, and the stray - // carriage return stops the `$`-anchored pattern below from matching. - const line = rawLine.trim(); - if (!line) continue; - // The sums file also lists `prebuilt-binaries--pdb.tar.gz`. - // The alternation and the anchoring keep that from being read as a - // platform named `win32-x64-pdb`. - const match = line.match( - /^([0-9a-f]{64})\s+\*?prebuilt-binaries-(loom-)?([a-z0-9]+-[a-z0-9_]+)\.tar\.gz$/u, - ); - if (!match) continue; - const [, sha256, loomPrefix, platform] = match; - const loom = loomPrefix !== undefined; - if (loom && !loomInputHash) continue; - const dirName = loom ? `loom-${platform}` : platform; - const file = `prebuilt-binaries-${dirName}.tar.gz`; - // Only platforms this package knows are published. - const knownPlatform = Object.keys(TRIPLE_PLATFORMS).some( - t => TRIPLE_PLATFORMS[t] === platform, - ); - if (!knownPlatform) continue; - const archive = path.join(sumsDir, file); - // The archive has one top-level / dir; read its manifest.json - // directly so the same call works with GNU and BSD tar. - const manifest = JSON.parse( - execFileSync( - tarCommand(), - ['-xzOf', archive, `${dirName}/manifest.json`], - { - encoding: 'utf8', - // The manifest lists every file (about 18k entries), above the default buffer. - maxBuffer: 256 * 1024 * 1024, - }, - ), - ); - const expectedHash = loom ? loomInputHash : inputHash; - if (manifest.inputHash !== expectedHash) { - die( - `${file} was built from input hash ${manifest.inputHash}, not ${expectedHash}`, - 1, - ); - } - reactNative ??= manifest.reactNative; - if (loom) loomCommit ??= manifest.loom; - // Keyed by platform ("win32-x64"), not triple ("x86_64-pc-windows-msvc"): - // that is the documented shape at the top of this file and what - // `ensureDir` looks up (`pin.assets?.[platform]`). Keying by triple here - // meant a written pin could never be read back. - (loom ? loomAssets : assets)[platform] = { - file, - sha256, - size: statSync(archive).size, - }; - } - if (Object.keys(assets).length === 0) - die('no prebuilt archives in SHA256SUMS', 1); - const pin = { - version, - reactNative, - inputHash, - repo, - tag, - assets, - ...(Object.keys(loomAssets).length > 0 - ? { - loom: { - inputHash: loomInputHash, - loom: loomCommit, - assets: loomAssets, - }, - } - : {}), - }; - writeFileSync(path.resolve(out), `${JSON.stringify(pin, null, 2)}\n`); - log( - `wrote ${out} with ${Object.keys(assets).length} asset(s) and ${Object.keys(loomAssets).length} Loom asset(s)`, - ); - return; - } - default: - die( - 'usage: prebuilt-binaries.mjs [--triple ] [dir]', - 1, - ); - } -} - -main().catch(error => { - die(error?.message ?? String(error), 1); -}); diff --git a/vendor/react-native-gpui/packages/core/scripts/prebuilt-inputs.mjs b/vendor/react-native-gpui/packages/core/scripts/prebuilt-inputs.mjs deleted file mode 100644 index 634888d850..0000000000 --- a/vendor/react-native-gpui/packages/core/scripts/prebuilt-inputs.mjs +++ /dev/null @@ -1,203 +0,0 @@ -#!/usr/bin/env node - -import { createHash } from 'node:crypto'; -import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { findNodeModule, repoRoot } from './repo-root.mjs'; - -const scriptDir = path.dirname(fileURLToPath(import.meta.url)); -const packageDir = path.resolve(scriptDir, '..'); - -// Every path here is relative to this package, never to the repository root. -// A folder move must not invalidate the prebuilt runtime, so the hash has to -// describe the C++ inputs and nothing about where they are checked out. The -// same rule applies to react-native, which is hashed under its own name. -const TREE_INPUTS = [ - 'ReactGpui/rn-gpui-sys/cpp', - 'ReactCxxPlatform', - 'ReactCommonOverrides', -]; -const FILE_INPUTS = [ - 'ReactGpui/Cargo.lock', - 'scripts/build-prebuilt.mjs', - 'scripts/prebuilt-inputs.mjs', - 'ReactGpui/rn-gpui-sys/src/lib.rs', -]; -// The Loom runtime also depends on Loom's header variants and on the pinned -// Loom the React Native tree is built from. The Fabric hash does not include -// them, so Loom changes do not invalidate the Fabric runtime. -const LOOM_TREE_INPUTS = ['ReactCommonOverrides.loom']; -const LOOM_FILE_INPUTS = ['ReactGpui/loom-pin.json', 'overrides.json']; -const REACT_NATIVE_INPUT = 'react-native/package.json'; - -export const RENDERERS = ['fabric', 'loom']; - -const SKIP_DIRS = new Set(['build', 'node_modules', '.git', 'native-deps']); - -function walk(dir, out) { - for (const entry of readdirSync(dir)) { - if (SKIP_DIRS.has(entry)) continue; - const full = path.join(dir, entry); - const st = statSync(full); - if (st.isDirectory()) walk(full, out); - else if (st.isFile()) out.push(full); - } - return out; -} - -function reactNativePackageJson() { - const installed = findNodeModule(packageDir, 'react-native'); - if (installed) return path.join(installed, 'package.json'); - return path.join( - repoRoot(scriptDir), - 'node_modules', - 'react-native', - 'package.json', - ); -} - -/** - * The C++ inputs keyed by a path that does not depend on the checkout: package - * relative for this package's files, and `react-native/package.json` for the - * React Native pin. - */ -export function collectInputs(renderer = 'fabric') { - const loom = renderer === 'loom'; - const files = new Map(); - for (const rel of loom - ? [...TREE_INPUTS, ...LOOM_TREE_INPUTS] - : TREE_INPUTS) { - const dir = path.join(packageDir, rel); - if (!existsSync(dir)) continue; - for (const full of walk(dir, [])) { - files.set( - path.relative(packageDir, full).split(path.sep).join('/'), - full, - ); - } - } - for (const rel of loom - ? [...FILE_INPUTS, ...LOOM_FILE_INPUTS] - : FILE_INPUTS) { - const full = path.join(packageDir, rel); - if (existsSync(full)) files.set(rel, full); - } - const reactNative = reactNativePackageJson(); - if (existsSync(reactNative)) files.set(REACT_NATIVE_INPUT, reactNative); - return [...files.entries()] - .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) - .map(([rel, full]) => ({ path: rel, file: full })); -} - -// Hash with CRLF folded to LF so a Windows checkout with core.autocrlf -// produces the same hashes as macOS and Linux. -function contentSha256(file) { - const text = readFileSync(file).toString('latin1').replace(/\r\n/gu, '\n'); - return createHash('sha256').update(text, 'latin1').digest('hex'); -} - -export function inputHash(renderer = 'fabric') { - const hash = createHash('sha256'); - const perFile = []; - for (const { path: rel, file } of collectInputs(renderer)) { - const digest = contentSha256(file); - perFile.push({ path: rel, sha256: digest }); - hash.update(`${rel}\0${digest}\n`); - } - return { hash: hash.digest('hex'), files: perFile }; -} - -/** - * Whether a build should link the pinned prebuilt runtime or compile the C++ - * from source. - * - * A changed C++ input is not an error: the pinned archive was built from - * different sources, so linking it would run code the checkout does not - * contain. The build falls back to source and verifies the change. `build.rs` - * makes the same decision in Rust; this is the one place that names the rule - * for tooling and CI. - * - * `pin` is the parsed `prebuilt-binaries.json`; omit it to read the file. - */ -export function runtimeChoice(pin, renderer = 'fabric') { - const whole = pin ?? readPinFile(); - const pinned = - renderer === 'loom' - ? { version: whole.version, inputHash: whole.loom?.inputHash } - : whole; - const local = inputHash(renderer).hash; - if (local === pinned.inputHash) { - return { - kind: 'prebuilt', - version: pinned.version, - localHash: local, - pinnedHash: pinned.inputHash, - }; - } - return { - kind: 'source', - version: pinned.version, - localHash: local, - pinnedHash: pinned.inputHash, - reason: `local C++ inputs hash to ${local}, the pinned prebuilt was built from ${pinned.inputHash}`, - }; -} - -function readPinFile() { - return JSON.parse( - readFileSync(path.join(packageDir, 'prebuilt-binaries.json'), 'utf8'), - ); -} - -// Run as a CLI only when this file is the entry point. The guard matters -// because importers (build-prebuilt.mjs, build.rs via node -e) must not print. -const isEntry = - process.argv[1] !== undefined && - fileURLToPath(import.meta.url) === path.resolve(process.argv[1]); -if (isEntry) { - const rendererIndex = process.argv.indexOf('--renderer'); - const renderer = - rendererIndex === -1 ? 'fabric' : process.argv[rendererIndex + 1]; - if (!RENDERERS.includes(renderer)) { - console.error(`unknown renderer ${renderer}`); - process.exit(2); - } - if (process.argv.includes('--overrides-sha256')) { - console.log(overridesSha256(renderer)); - process.exit(0); - } - if (process.argv.includes('--runtime')) { - console.log(runtimeChoice(undefined, renderer).kind); - process.exit(0); - } - const { hash, files } = inputHash(renderer); - if (process.argv.includes('--list')) { - for (const f of files) console.log(`${f.sha256} ${f.path}`); - console.log(`${hash} `); - } else { - console.log(hash); - } -} - -// sha256 over the sorted "file\0sha256" lines of ReactCommonOverrides, joined -// by "\n". build-prebuilt.mjs writes this into the manifest; the CMake prebuilt -// branch receives it from build.rs and compares. -export function overridesSha256(renderer = 'fabric') { - const lines = []; - for (const [name, prefix] of [ - ['ReactCommonOverrides', ''], - ...(renderer === 'loom' ? [['ReactCommonOverrides.loom', 'loom/']] : []), - ]) { - const dir = path.join(packageDir, name); - const files = []; - walk(dir, files); - lines.push( - ...files - .map(f => path.relative(dir, f).split(path.sep).join('/')) - .sort() - .map(rel => `${prefix}${rel}\0${contentSha256(path.join(dir, rel))}`), - ); - } - return createHash('sha256').update(lines.join('\n')).digest('hex'); -} diff --git a/vendor/react-native-gpui/packages/core/scripts/prebuilt-inputs.test.mjs b/vendor/react-native-gpui/packages/core/scripts/prebuilt-inputs.test.mjs deleted file mode 100644 index c79c5656ae..0000000000 --- a/vendor/react-native-gpui/packages/core/scripts/prebuilt-inputs.test.mjs +++ /dev/null @@ -1,135 +0,0 @@ -import { createRequire } from 'node:module'; -import { readFileSync } from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { describe, expect, test } from 'vitest'; -import { - collectInputs, - inputHash, - overridesSha256, - runtimeChoice, -} from './prebuilt-inputs.mjs'; - -const scriptDir = path.dirname(fileURLToPath(import.meta.url)); -const packageDir = path.resolve(scriptDir, '..'); -const require = createRequire(import.meta.url); - -function packageFiles() { - return JSON.parse(readFileSync(path.join(packageDir, 'package.json'), 'utf8')) - .files; -} - -// `react-native/package.json` is the React Native pin: it lives in the -// consumer's install, not in this package, so it is deliberately not in -// `files`. -const EXTERNAL_PREFIX = 'react-native/'; - -/// Does an `npm pack` of this package include `relPath`? npm treats a `files` -/// entry as covering the file itself and everything under it. -export function coveredByFiles(relPath, files) { - return files.some( - entry => relPath === entry || relPath.startsWith(`${entry}/`), - ); -} - -describe('collectInputs', () => { - test('uses the pinned prebuilt while the inputs match the pin', () => { - const pin = JSON.parse( - readFileSync(path.join(packageDir, 'prebuilt-binaries.json'), 'utf8'), - ); - const choice = runtimeChoice({ ...pin, inputHash: inputHash().hash }); - expect(choice.kind).toBe('prebuilt'); - expect(choice.version).toBe(pin.version); - }); - - test('falls back to source, with a reason, when the inputs changed', () => { - const pin = JSON.parse( - readFileSync(path.join(packageDir, 'prebuilt-binaries.json'), 'utf8'), - ); - const choice = runtimeChoice({ ...pin, inputHash: 'not-the-local-hash' }); - expect(choice.kind).toBe('source'); - expect(choice.reason).toContain(inputHash().hash); - expect(choice.reason).toContain('not-the-local-hash'); - }); - - test("hashes Loom's own inputs for the Loom runtime only", () => { - const fabric = collectInputs('fabric').map(entry => entry.path); - const loom = collectInputs('loom').map(entry => entry.path); - expect(fabric).not.toContain('ReactGpui/loom-pin.json'); - expect(loom).toContain('ReactGpui/loom-pin.json'); - expect(loom.some(rel => rel.startsWith('ReactCommonOverrides.loom/'))).toBe( - true, - ); - expect(inputHash('loom').hash).not.toBe(inputHash('fabric').hash); - expect(overridesSha256('loom')).not.toBe(overridesSha256('fabric')); - }); - - test('uses the Loom pin section for the Loom runtime', () => { - const pin = { version: '1.0.0', inputHash: 'x', loom: { inputHash: 'y' } }; - expect(runtimeChoice(pin, 'loom').pinnedHash).toBe('y'); - expect(runtimeChoice({ ...pin, loom: undefined }, 'loom').kind).toBe( - 'source', - ); - }); - - test('keys every path without the checkout location', () => { - for (const { path: rel } of collectInputs()) { - expect(path.isAbsolute(rel)).toBe(false); - expect(rel).not.toContain('..'); - // Always POSIX separators, so a Windows checkout hashes identically. - expect(rel).not.toContain('\\'); - } - }); - - test('hashes the files and folders the archive is built from', () => { - const paths = collectInputs().map(entry => entry.path); - for (const expected of [ - 'ReactGpui/Cargo.lock', - 'ReactGpui/rn-gpui-sys/src/lib.rs', - 'ReactGpui/rn-gpui-sys/cpp/GpuiHost.cpp', - 'scripts/build-prebuilt.mjs', - 'scripts/prebuilt-inputs.mjs', - 'react-native/package.json', - ]) { - expect(paths).toContain(expected); - } - }); -}); - -describe('core package.json files', () => { - // If a hashed path is not published, an installed package hashes fewer files - // than the pin was built from and can never match, so every consumer falls - // back to building React Native from source. - test('covers every path collectInputs() returns', () => { - const files = packageFiles(); - const uncovered = ['fabric', 'loom'] - .flatMap(renderer => collectInputs(renderer)) - .map(entry => entry.path) - .filter(rel => !rel.startsWith(EXTERNAL_PREFIX)) - .filter(rel => !coveredByFiles(rel, files)); - expect(uncovered).toEqual([]); - }); - - test('covers every inputHash entry, including on a packed install', () => { - const files = packageFiles(); - const uncovered = inputHash() - .files.map(entry => entry.path) - .filter(rel => !rel.startsWith(EXTERNAL_PREFIX)) - .filter(rel => !coveredByFiles(rel, files)); - expect(uncovered).toEqual([]); - }); - - test('coveredByFiles treats a folder entry as covering its contents', () => { - expect(coveredByFiles('a/b/c.cpp', ['a/b'])).toBe(true); - expect(coveredByFiles('a/b', ['a/b'])).toBe(true); - expect(coveredByFiles('a/bc', ['a/b'])).toBe(false); - expect(coveredByFiles('a/b/c.cpp', ['a'])).toBe(true); - }); - - test('the published package.json is the one the test read', () => { - // Guards against the test passing because it read a different manifest. - expect(require(path.join(packageDir, 'package.json')).name).toBe( - '@react-native-gpui/core', - ); - }); -}); diff --git a/vendor/react-native-gpui/packages/core/scripts/prebuilt-renderers.mjs b/vendor/react-native-gpui/packages/core/scripts/prebuilt-renderers.mjs deleted file mode 100644 index a1d8453b20..0000000000 --- a/vendor/react-native-gpui/packages/core/scripts/prebuilt-renderers.mjs +++ /dev/null @@ -1,3 +0,0 @@ -// The renderers the prebuilt runtime workflow builds and the pin file lists. -// An app that selects a renderer outside this list builds it from source. -export const PREBUILT_RENDERERS = ['fabric']; diff --git a/vendor/react-native-gpui/packages/core/scripts/repo-root.mjs b/vendor/react-native-gpui/packages/core/scripts/repo-root.mjs deleted file mode 100644 index 4b1761929b..0000000000 --- a/vendor/react-native-gpui/packages/core/scripts/repo-root.mjs +++ /dev/null @@ -1,50 +0,0 @@ -// The repository root, found by lookup rather than by counting parent -// directories: this file lives at a different depth before and after a folder -// move, but the root is always the nearest ancestor whose package.json declares -// `workspaces`. -// -// A published package has no repository root above it, so callers that only -// run inside this checkout use this; anything that must also work from an -// installed copy resolves its dependencies from node_modules instead. - -import { existsSync, readFileSync } from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; - -function hasWorkspaces(dir) { - const manifest = path.join(dir, 'package.json'); - if (!existsSync(manifest)) return false; - try { - return Boolean(JSON.parse(readFileSync(manifest, 'utf8')).workspaces); - } catch { - return false; - } -} - -export function repoRoot(from = path.dirname(fileURLToPath(import.meta.url))) { - let current = path.resolve(from); - while (true) { - if (hasWorkspaces(current)) return current; - const parent = path.dirname(current); - if (parent === current) { - throw new Error( - `no repository root with a workspaces manifest above ${from}`, - ); - } - current = parent; - } -} - -// The installed `` package, found by walking up from `start` for a -// `node_modules` directory that holds it. Mirrors `find_node_module` in -// `rn-gpui-sys/build.rs` and `rn_gpui_find_node_module` in CMake. -export function findNodeModule(start, name) { - let current = path.resolve(start); - while (true) { - const candidate = path.join(current, 'node_modules', name); - if (existsSync(path.join(candidate, 'package.json'))) return candidate; - const parent = path.dirname(current); - if (parent === current) return null; - current = parent; - } -} diff --git a/vendor/react-native-gpui/packages/core/setup-env.js b/vendor/react-native-gpui/packages/core/setup-env.js deleted file mode 100644 index d7442a17bd..0000000000 --- a/vendor/react-native-gpui/packages/core/setup-env.js +++ /dev/null @@ -1,9 +0,0 @@ -// RN 0.87's development setup expects the browser `window` global. A JS engine -// on the desktop only has `globalThis`, so provide the alias before the stock -// RN setup. -// This file is loaded by the CLI before the app entry module. -if (typeof globalThis.window === 'undefined') { - globalThis.window = globalThis; -} - -module.exports = require('react-native/setup-env'); diff --git a/vendor/react-native-gpui/packages/core/shortcuts.test.js b/vendor/react-native-gpui/packages/core/shortcuts.test.js deleted file mode 100644 index 068f11b1ae..0000000000 --- a/vendor/react-native-gpui/packages/core/shortcuts.test.js +++ /dev/null @@ -1,391 +0,0 @@ -/** - * Unit tests for the shortcut registry. - * - * The repo's vitest include list only picks up `*.test.js` under `packages/core`, - * so this file lives at the package root rather than next to the source. The - * preset resolves the TypeScript sources (and the `.desktop` extension order) - * without a build step, the same way `contextMenu.test.js` imports its modules. - * - * The precedence itself is native — GPUI's keymap resolves it — so these tests - * cover what JS owns: which shortcuts exist, which handlers run, what a user - * keymap does, and how a scope is named. The two Rust tests that prove the - * ordering are `desktop::keymap::tests::an_inner_scope_outranks_an_outer_one` - * and `a_text_input_disables_a_shortcut_that_opts_out`. - * - * @format - */ - -import { beforeEach, describe, expect, test, vi } from 'vitest'; - -// The registry installs through the TurboModule, which a unit test has no -// runtime for. A stub that records calls is enough: `install` is the only thing -// that would cross the boundary. -vi.mock('./src-gpui/src/private/specs/NativeGpuiShortcuts', () => { - const installs = []; - return { - default: { - shortcutInstall: async shortcuts => { - installs.push(shortcuts); - return { installed: shortcuts.length }; - }, - shortcutGet: async () => installs[installs.length - 1] ?? [], - }, - __installs: installs, - }; -}); - -import { - __resetForTests, - addHandler, - clear, - count, - describe as describeShortcuts, - fire, - getUserBindings, - install, - keysFor, - list, - normaliseKeys, - register, - reset, - resolve, - setUserBindings, - shortcutId, - unregister, -} from './src-gpui/src/private/desktop/shortcuts'; - -beforeEach(() => { - __resetForTests(); -}); - -describe('registration', () => { - test('a shortcut is listed with its defaults filled in', () => { - register([{ id: 'file.save', keys: 'mod+s' }]); - expect(count()).toBe(1); - expect(list()).toEqual([ - { - id: 'file.save', - keys: 'mod+s', - scope: undefined, - enabled: true, - allowInTextInput: false, - global: false, - }, - ]); - }); - - test('a global shortcut cannot also be scoped or allowed in a text input', () => { - register([{ id: 'palette', keys: 'alt+space', global: true }]); - expect(list()[0].global).toBe(true); - expect(() => - register([{ id: 'a', keys: 'alt+a', global: true, when: 'editor' }]), - ).toThrow(/global/u); - expect(() => - register([ - { id: 'b', keys: 'alt+b', global: true, allowInTextInput: true }, - ]), - ).toThrow(/global/u); - }); - - test('an id keeps one shortcut however many components register it', () => { - register([{ id: 'file.save', keys: 'mod+s' }]); - register([{ id: 'file.save', keys: 'mod+s' }]); - expect(count()).toBe(1); - }); - - test('re-registering replaces the keys rather than adding a second binding', () => { - register([{ id: 'file.save', keys: 'mod+s' }]); - register([{ id: 'file.save', keys: 'mod+shift+s' }]); - expect(count()).toBe(1); - expect(keysFor('file.save')).toBe('mod+shift+s'); - }); - - test('two shortcuts with the same keys in different scopes coexist', () => { - // This is what makes an override possible: they are two bindings, and a - // deeper context wins. - register([ - { id: 'save.outside', keys: 'mod+s', when: 'files' }, - { id: 'save.inside', keys: 'mod+s', when: 'editor' }, - ]); - expect(count()).toBe(2); - expect(list().map(shortcut => shortcut.scope)).toEqual(['files', 'editor']); - }); - - test('a shortcut with no keys is rejected', () => { - expect(() => register([{ id: 'broken', keys: ' ' }])).toThrow(/no keys/u); - }); - - test('a shortcut with no id is rejected', () => { - expect(() => register([{ id: '', keys: 'mod+s' }])).toThrow( - /requires an id/u, - ); - }); - - test('unregister removes the shortcut but leaves handlers to their owner', () => { - // A handler is owned by the function `addHandler` returned, not by the - // definition. Removing the definition must not silently drop a handler that - // is still mounted: a component that re-registers would otherwise install a - // shortcut with nothing listening to it. - const handler = vi.fn(); - const remove = addHandler('file.save', handler); - register([{ id: 'file.save', keys: 'mod+s' }]); - unregister('file.save'); - expect(count()).toBe(0); - // The handler is still there, so it still runs when something fires the id. - fire('file.save'); - expect(handler).toHaveBeenCalledOnce(); - remove(); - fire('file.save'); - expect(handler).toHaveBeenCalledOnce(); - }); - - test('a re-register does not clobber a handler from a sibling effect', () => { - // This is the bug the toggle test in the e2e caught: `useShortcut` has one - // effect for the handler and another for the definition, so a definition - // change (toggling `allowInTextInput`) must leave the handler alone. - const handler = vi.fn(); - register([{ id: 'file.save', keys: 'mod+s', allowInTextInput: false }]); - addHandler('file.save', handler); - unregister('file.save'); - register([{ id: 'file.save', keys: 'mod+s', allowInTextInput: true }]); - fire('file.save'); - expect(handler).toHaveBeenCalledOnce(); - }); - - test('an id is only removed when its last owner lets go', () => { - // Two components can register the same id; one unmounting must not take the - // shortcut away from the other. - register([{ id: 'file.save', keys: 'mod+s' }]); - register([{ id: 'file.save', keys: 'mod+s' }]); - unregister('file.save'); - expect(count()).toBe(1); - unregister('file.save'); - expect(count()).toBe(0); - }); - - test('clear removes everything', () => { - register([ - { id: 'a', keys: 'mod+a' }, - { id: 'b', keys: 'mod+b' }, - ]); - clear(); - expect(count()).toBe(0); - expect(list()).toEqual([]); - }); - - test('describe reports the declared fields with the effective keys', () => { - register([ - { - id: 'file.save', - keys: 'mod+s', - when: 'editor', - description: 'Save the file', - allowInTextInput: true, - }, - ]); - expect(describeShortcuts()).toEqual([ - { - id: 'file.save', - keys: 'mod+s', - when: 'editor', - enabled: true, - allowInTextInput: true, - global: false, - description: 'Save the file', - }, - ]); - }); -}); - -describe('handlers', () => { - test('every handler for an id runs, in the order they were added', () => { - register([{ id: 'file.save', keys: 'mod+s' }]); - const order = []; - addHandler('file.save', () => order.push('first')); - addHandler('file.save', () => order.push('second')); - fire('file.save'); - expect(order).toEqual(['first', 'second']); - }); - - test('a handler receives the shortcut, its keys and its scope', () => { - register([{ id: 'file.save', keys: 'mod+s', when: 'editor' }]); - const handler = vi.fn(); - addHandler('file.save', handler); - fire('file.save'); - expect(handler).toHaveBeenCalledWith({ - id: 'file.save', - keys: 'mod+s', - scope: 'editor', - }); - }); - - test('the handler sees a remapped key, not the declared one', () => { - register([{ id: 'file.save', keys: 'mod+s' }]); - setUserBindings({ 'file.save': 'mod+shift+s' }); - const handler = vi.fn(); - addHandler('file.save', handler); - fire('file.save'); - expect(handler.mock.calls[0][0].keys).toBe('mod+shift+s'); - }); - - test('the returned function removes only that handler', () => { - register([{ id: 'file.save', keys: 'mod+s' }]); - const first = vi.fn(); - const second = vi.fn(); - const remove = addHandler('file.save', first); - addHandler('file.save', second); - remove(); - fire('file.save'); - expect(first).not.toHaveBeenCalled(); - expect(second).toHaveBeenCalledOnce(); - }); - - test('a handler that removes itself does not disturb the loop', () => { - register([{ id: 'file.save', keys: 'mod+s' }]); - const second = vi.fn(); - const remove = addHandler('file.save', () => remove()); - addHandler('file.save', second); - fire('file.save'); - expect(second).toHaveBeenCalledOnce(); - }); - - test('firing an unregistered shortcut does nothing', () => { - expect(() => fire('nobody.listens')).not.toThrow(); - }); -}); - -describe('user bindings', () => { - test('a binding replaces the declared keys', () => { - register([{ id: 'file.save', keys: 'mod+s' }]); - setUserBindings({ 'file.save': 'mod+shift+s' }); - expect(keysFor('file.save')).toBe('mod+shift+s'); - expect(getUserBindings()).toEqual({ 'file.save': 'mod+shift+s' }); - }); - - test('a null binding unbinds the shortcut', () => { - register([ - { id: 'file.save', keys: 'mod+s' }, - { id: 'file.open', keys: 'mod+o' }, - ]); - setUserBindings({ 'file.save': null }); - // Left out of the installed list entirely: an absent binding cannot shadow - // another one. - expect(list().map(shortcut => shortcut.id)).toEqual(['file.open']); - }); - - test('reset restores what the app declared', () => { - register([{ id: 'file.save', keys: 'mod+s' }]); - setUserBindings({ 'file.save': 'f5' }); - reset(); - expect(keysFor('file.save')).toBe('mod+s'); - expect(getUserBindings()).toEqual({}); - }); - - test('a binding for an id that is not installed is kept', () => { - // The user bound something this screen does not have; it applies if the - // screen appears. - setUserBindings({ 'file.save': 'mod+shift+s' }); - expect(getUserBindings()).toEqual({ 'file.save': 'mod+shift+s' }); - register([{ id: 'file.save', keys: 'mod+s' }]); - expect(keysFor('file.save')).toBe('mod+shift+s'); - }); - - test('the keymap is a copy, so a caller cannot mutate the registry', () => { - setUserBindings({ 'file.save': 'mod+shift+s' }); - const bindings = getUserBindings(); - bindings['file.save'] = 'f1'; - expect(getUserBindings()['file.save']).toBe('mod+shift+s'); - }); -}); - -describe('resolution', () => { - test('the keys resolve to the shortcut that owns them', () => { - register([{ id: 'file.save', keys: 'mod+s' }]); - expect(resolve('mod+s')).toEqual({ - id: 'file.save', - keys: 'mod+s', - scope: undefined, - }); - }); - - test('two spellings of one binding resolve the same way', () => { - register([{ id: 'file.save', keys: 'Mod+S' }]); - expect(resolve('mod+s')?.id).toBe('file.save'); - expect(normaliseKeys('Mod + S')).toBe('mod+s'); - }); - - test('the last declaration wins, as a later keymap binding does', () => { - register([ - { id: 'first', keys: 'mod+s' }, - { id: 'second', keys: 'mod+s' }, - ]); - expect(resolve('mod+s')?.id).toBe('second'); - }); - - test('a disabled shortcut does not resolve', () => { - register([{ id: 'file.save', keys: 'mod+s', enabled: false }]); - expect(resolve('mod+s')).toBeNull(); - }); - - test('an unbound key resolves to nothing', () => { - register([{ id: 'file.save', keys: 'mod+s' }]); - expect(resolve('mod+q')).toBeNull(); - }); - - test('a remap changes what resolves', () => { - register([{ id: 'file.save', keys: 'mod+s' }]); - setUserBindings({ 'file.save': 'mod+shift+s' }); - expect(resolve('mod+s')).toBeNull(); - expect(resolve('mod+shift+s')?.id).toBe('file.save'); - }); - - test('a chord is one binding, not two', () => { - register([{ id: 'chord.save', keys: 'mod+k mod+s' }]); - expect(resolve('mod+k mod+s')?.id).toBe('chord.save'); - expect(resolve('mod+k')).toBeNull(); - }); -}); - -describe('installing', () => { - test('the same list installs once', async () => { - const { __installs } = - await import('./src-gpui/src/private/specs/NativeGpuiShortcuts'); - __installs.length = 0; - - register([{ id: 'file.save', keys: 'mod+s' }]); - await install(); - await install(); - // The signature is unchanged, so the second call never reaches native. - expect(__installs.length).toBe(1); - expect(__installs[0]).toHaveLength(1); - - register([{ id: 'file.save', keys: 'mod+shift+s' }]); - await install(); - expect(__installs.length).toBe(2); - }); - - test('a null binding is not installed', async () => { - const { __installs } = - await import('./src-gpui/src/private/specs/NativeGpuiShortcuts'); - __installs.length = 0; - register([{ id: 'file.save', keys: 'mod+s' }]); - await install(); - setUserBindings({ 'file.save': null }); - await install(); - expect(__installs[__installs.length - 1]).toEqual([]); - }); -}); - -describe('scope names', () => { - test('a hook id includes its scope, so two scopes do not collide', () => { - expect(shortcutId('mod+s', 'editor')).toBe('shortcut:editor/mod+s'); - expect(shortcutId('mod+s', 'files')).toBe('shortcut:files/mod+s'); - expect(shortcutId('mod+s', undefined)).toBe('shortcut:mod+s'); - }); - - test('whitespace in the keys does not change the id', () => { - expect(shortcutId('mod+k mod+s', 'editor')).toBe( - 'shortcut:editor/mod+k mod+s', - ); - }); -}); diff --git a/vendor/react-native-gpui/packages/core/src-gpui/Libraries/Alert/Alert.desktop.js b/vendor/react-native-gpui/packages/core/src-gpui/Libraries/Alert/Alert.desktop.js deleted file mode 100644 index 0733ee9a4d..0000000000 --- a/vendor/react-native-gpui/packages/core/src-gpui/Libraries/Alert/Alert.desktop.js +++ /dev/null @@ -1,243 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - * @format - */ - -import type { DialogOptions } from '../NativeModules/specs/NativeDialogManagerAndroid'; - -import Platform from '../Utilities/Platform'; -import { alertWithArgs } from './RCTAlertManager'; - -/** - * @platform ios - */ -export type AlertType = - 'default' | 'plain-text' | 'secure-text' | 'login-password'; - -/** - * @platform ios - */ -export type AlertButtonStyle = 'default' | 'cancel' | 'destructive'; - -export type AlertButton = { - text?: string, - onPress?: ?((value?: string) => any) | ?Function, - isPreferred?: boolean, - style?: AlertButtonStyle, - ... -}; - -export type AlertButtons = Array; - -export type AlertOptions = { - /** @platform android */ - cancelable?: ?boolean, - userInterfaceStyle?: 'unspecified' | 'light' | 'dark', - /** @platform android */ - onDismiss?: ?() => void, - ... -}; - -/** - * Launches an alert dialog with the specified title and message. - * - * Optionally provide a list of buttons. Tapping any button will fire the - * respective onPress callback and dismiss the alert. By default, the only - * button will be an 'OK' button. - * - * This is an API that works both on iOS and Android and can show static - * alerts. On iOS, you can show an alert that prompts the user to enter - * some information. - * - * ## iOS - * - * On iOS you can specify any number of buttons. Each button can optionally - * specify a style, which is one of 'default', 'cancel' or 'destructive'. - * - * ## Android - * - * On Android at most three buttons can be specified. Android has a concept - * of a neutral, negative and a positive button: - * - * - If you specify one button, it will be the 'positive' one (such as 'OK') - * - Two buttons mean 'negative', 'positive' (such as 'Cancel', 'OK') - * - Three buttons mean 'neutral', 'negative', 'positive' (such as 'Later', 'Cancel', 'OK') - * - * Example: - * - * ```tsx - * // Works on both iOS and Android - * Alert.alert( - * 'Alert Title', - * 'My Alert Msg', - * [ - * {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')}, - * {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'}, - * {text: 'OK', onPress: () => console.log('OK Pressed')}, - * ] - * ) - * ``` - * - * @see https://reactnative.dev/docs/alert - */ -class Alert { - /** - * Display an alert dialog with the specified title, message, and buttons. - * On Android, at most three buttons can be specified. On iOS, any number of - * buttons can be used. - */ - static alert( - title: ?string, - message?: ?string, - buttons?: AlertButtons, - options?: AlertOptions, - ): void { - if (Platform.OS !== 'android') { - Alert.prompt( - title, - message, - buttons, - 'default', - undefined, - undefined, - options, - ); - } else if (Platform.OS === 'android') { - const NativeDialogManagerAndroid = - require('../NativeModules/specs/NativeDialogManagerAndroid').default; - if (!NativeDialogManagerAndroid) { - return; - } - const constants = NativeDialogManagerAndroid.getConstants(); - - const config: DialogOptions = { - title: title || '', - message: message || '', - cancelable: false, - }; - - if (options && options.cancelable) { - config.cancelable = options.cancelable; - } - // At most three buttons (neutral, negative, positive). Ignore rest. - // The text 'OK' should be probably localized. iOS Alert does that in native. - const defaultPositiveText = 'OK'; - const validButtons: AlertButtons = buttons - ? buttons.slice(0, 3) - : [{ text: defaultPositiveText }]; - const buttonPositive = validButtons.pop(); - const buttonNegative = validButtons.pop(); - const buttonNeutral = validButtons.pop(); - - if (buttonNeutral) { - config.buttonNeutral = buttonNeutral.text || ''; - } - if (buttonNegative) { - config.buttonNegative = buttonNegative.text || ''; - } - if (buttonPositive) { - config.buttonPositive = buttonPositive.text || defaultPositiveText; - } - - /* $FlowFixMe[missing-local-annot] The type annotation(s) required by - * Flow's LTI update could not be added via codemod */ - const onAction = (action, buttonKey) => { - if (action === constants.buttonClicked) { - if (buttonKey === constants.buttonNeutral) { - // $FlowFixMe[incompatible-type] - // $FlowFixMe[incompatible-use] - buttonNeutral.onPress && buttonNeutral.onPress(); - } else if (buttonKey === constants.buttonNegative) { - // $FlowFixMe[incompatible-type] - // $FlowFixMe[incompatible-use] - buttonNegative.onPress && buttonNegative.onPress(); - } else if (buttonKey === constants.buttonPositive) { - // $FlowFixMe[incompatible-type] - // $FlowFixMe[incompatible-use] - buttonPositive.onPress && buttonPositive.onPress(); - } - } else if (action === constants.dismissed) { - options && options.onDismiss && options.onDismiss(); - } - }; - const onError = (errorMessage: string) => console.warn(errorMessage); - NativeDialogManagerAndroid.showAlert(config, onError, onAction); - } - } - - /** - * Create and display a prompt to enter text. Accepts a title, message, - * callback or buttons, input type, default value, keyboard type, and options. - * - * @platform ios - */ - static prompt( - title: ?string, - message?: ?string, - callbackOrButtons?: ?(((text: string) => void) | AlertButtons), - type?: ?AlertType = 'plain-text', - defaultValue?: string, - keyboardType?: string, - options?: AlertOptions, - ): void { - if (Platform.OS !== 'android') { - let callbacks: Array = []; - const buttons = []; - let cancelButtonKey; - let destructiveButtonKey; - let preferredButtonKey; - if (typeof callbackOrButtons === 'function') { - callbacks = [callbackOrButtons]; - } else if (Array.isArray(callbackOrButtons)) { - callbackOrButtons.forEach((btn, index) => { - callbacks[index] = btn.onPress; - if (btn.style === 'cancel') { - cancelButtonKey = String(index); - } else if (btn.style === 'destructive') { - destructiveButtonKey = String(index); - } - if (btn.isPreferred) { - preferredButtonKey = String(index); - } - if (btn.text || index < (callbackOrButtons || []).length - 1) { - const btnDef: { [number]: string } = {}; - btnDef[index] = btn.text || ''; - buttons.push(btnDef); - } - }); - } - - alertWithArgs( - { - title: title || '', - message: message || undefined, - buttons, - type: type || undefined, - defaultValue, - cancelButtonKey, - destructiveButtonKey, - preferredButtonKey, - keyboardType, - userInterfaceStyle: options?.userInterfaceStyle || undefined, - cancelable: options?.cancelable || undefined, - }, - (id, value) => { - if (id < 0) { - options?.onDismiss?.(); - return; - } - const cb = callbacks[id]; - cb && - cb(type === 'login-password' ? JSON.parse(value || '{}') : value); - }, - ); - } - } -} - -export default Alert; diff --git a/vendor/react-native-gpui/packages/core/src-gpui/Libraries/Components/Button.desktop.js b/vendor/react-native-gpui/packages/core/src-gpui/Libraries/Components/Button.desktop.js deleted file mode 100644 index c10300fd59..0000000000 --- a/vendor/react-native-gpui/packages/core/src-gpui/Libraries/Components/Button.desktop.js +++ /dev/null @@ -1,401 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow - * @format - */ - -'use strict'; - -import type { TextStyleProp, ViewStyleProp } from '../StyleSheet/StyleSheet'; -import type { GestureResponderEvent } from '../Types/CoreEventTypes'; -import type { - AccessibilityActionEvent, - AccessibilityActionInfo, - AccessibilityState, -} from './View/ViewAccessibility'; - -import StyleSheet, { type ColorValue } from '../StyleSheet/StyleSheet'; -import Text from '../Text/Text'; -import Platform from '../Utilities/Platform'; -import TouchableNativeFeedback from './Touchable/TouchableNativeFeedback'; -import TouchableOpacity from './Touchable/TouchableOpacity'; -import View from './View/View'; -import invariant from 'invariant'; -import * as React from 'react'; - -/** - * Label colour for a filled button, derived from the background's luminance so - * a light `color` prop does not end up with white text on it. Non-hex colours - * (dynamic or platform colours) return null and keep the platform default. - */ -function readableLabelColor(background: ?ColorValue): ?string { - if (typeof background !== 'string' || !/^#[0-9a-f]{3,8}$/i.test(background)) { - return null; - } - let hex = background.slice(1); - if (hex.length === 3) { - hex = hex.replace(/./g, character => character + character); - } - if (hex.length !== 6) { - return null; - } - const red = parseInt(hex.slice(0, 2), 16); - const green = parseInt(hex.slice(2, 4), 16); - const blue = parseInt(hex.slice(4, 6), 16); - const luma = (red * 299 + green * 587 + blue * 114) / 1000; - return luma > 150 ? '#18212f' : '#ffffff'; -} - -/** @build-types emit-as-interface Uniwind compatibility */ -export type ButtonProps = Readonly<{ - /** - * Text to display inside the button. On Android the given title will be - * converted to the uppercased form. - */ - title: string, - - /** - * Handler called when the user taps the button. - */ - onPress?: (event?: GestureResponderEvent) => unknown, - - /** - * If `true`, doesn't play system sound on touch. - * - * @platform android - * - * @default `false` - */ - touchSoundDisabled?: ?boolean, - - /** - * Color of the text (iOS), or background color of the button (Android). - * - * @default {@platform android} `'#2196F3'` - * @default {@platform ios} `'#007AFF'` - */ - color?: ?ColorValue, - - /** - * TV preferred focus. - * - * @platform tv - * - * @default `false` - * @deprecated Use `focusable` instead - */ - hasTVPreferredFocus?: ?boolean, - - /** - * Designates the next view to receive focus when the user navigates down. See - * the [Android documentation][android:nextFocusDown]. - * - * [android:nextFocusDown]: - * https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusDown - * - * @platform android, tv - */ - nextFocusDown?: ?number, - - /** - * Designates the next view to receive focus when the user navigates forward. - * See the [Android documentation][android:nextFocusForward]. - * - * [android:nextFocusForward]: - * https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusForward - * - * @platform android, tv - */ - nextFocusForward?: ?number, - - /** - * Designates the next view to receive focus when the user navigates left. See - * the [Android documentation][android:nextFocusLeft]. - * - * [android:nextFocusLeft]: - * https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusLeft - * - * @platform android, tv - */ - nextFocusLeft?: ?number, - - /** - * Designates the next view to receive focus when the user navigates right. See - * the [Android documentation][android:nextFocusRight]. - * - * [android:nextFocusRight]: - * https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusRight - * - * @platform android, tv - */ - nextFocusRight?: ?number, - - /** - * Designates the next view to receive focus when the user navigates up. See - * the [Android documentation][android:nextFocusUp]. - * - * [android:nextFocusUp]: - * https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusUp - * - * @platform android, tv - */ - nextFocusUp?: ?number, - - /** - * Text to display for blindness accessibility features. - */ - accessibilityLabel?: ?string, - - /** - * Alias for `accessibilityLabel`. - */ - 'aria-label'?: ?string, - - /** - * If `true`, disable all interactions for this component. - * - * @default `false` - */ - disabled?: ?boolean, - - testID?: ?string, - - accessible?: ?boolean, - accessibilityActions?: ?ReadonlyArray, - onAccessibilityAction?: ?(event: AccessibilityActionEvent) => unknown, - accessibilityState?: ?AccessibilityState, - - /** - * Alias for `accessibilityState`. - */ - 'aria-busy'?: ?boolean, - 'aria-checked'?: ?boolean | 'mixed', - 'aria-disabled'?: ?boolean, - 'aria-expanded'?: ?boolean, - 'aria-selected'?: ?boolean, - - importantForAccessibility?: ?('auto' | 'yes' | 'no' | 'no-hide-descendants'), - accessibilityHint?: ?string, - - /** - * A BCP 47 language tag for the screen reader to use when reading text - * content. - * - * @platform ios - */ - accessibilityLanguage?: ?Stringish, -}>; - -const NativeTouchable: - typeof TouchableNativeFeedback | typeof TouchableOpacity = - Platform.OS === 'android' ? TouchableNativeFeedback : TouchableOpacity; - -export type ButtonInstance = React.ElementRef; - -/** - * A basic button component that should render nicely on any platform. Supports a - * minimal level of customization. - * - * If this button doesn't look right for your app, you can build your own button - * using `Pressable`. - * - * Example: - * - * ```tsx - *