diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..c1711f02 --- /dev/null +++ b/.clang-format @@ -0,0 +1,28 @@ +# Checked by .github/workflows/lint-cpp.yml; run `bun lint-cpp` to apply. +# Written for the clang-format version pinned in scripts/clang-format.sh. +# +# Tuned to the code as it was written rather than a stock style, so adopting it +# moved few lines. ColumnLimit 0 keeps the author's line breaks: wrapping is a +# review call here, not a formatter's. +BasedOnStyle: Google +Standard: c++20 +ColumnLimit: 0 + +# Pointer and reference alignment +DerivePointerAlignment: false +PointerAlignment: Left + +# Short blocks +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: true +AllowShortEnumsOnASingleLine: true + +# Includes and comments are ordered and worded by hand +IncludeBlocks: Preserve +SortIncludes: Never +ReflowComments: false +SpacesBeforeTrailingComments: 2 + +AccessModifierOffset: -1 diff --git a/.claude/skills/rn-tgfx/references/vision-camera.md b/.claude/skills/rn-tgfx/references/vision-camera.md index 4cf092c9..05099533 100644 --- a/.claude/skills/rn-tgfx/references/vision-camera.md +++ b/.claude/skills/rn-tgfx/references/vision-camera.md @@ -138,9 +138,9 @@ behind it. and a `try`/`finally` releases the buffer and disposes the frame on every path including a throw. Your callback runs inside that same `try`. -## Face blur — the reference app +## Face blur -`apps/example/src/TgfxFaceBlur.tsx`. The scene compiles once, so allocate a +The scene compiles once, so allocate a **fixed** number of slots; an unused slot has zero size and draws nothing. ```tsx diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index cff72dc5..00000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,255 +0,0 @@ -name: CI - -on: - push: - branches: [main] - pull_request: - workflow_dispatch: - -# No pipelines here today; `shell: bash` is the alias carrying -o pipefail, so -# one added later cannot silently report success. review.yml is where it bites. -defaults: - run: - shell: bash - -jobs: - package: - name: Package (typecheck, tests, codegen) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: oven-sh/setup-bun@v2 - with: - bun-version: latest - - run: bun install --frozen-lockfile - # Every workspace package, not a hardcoded one: the second package that - # was added went untested for exactly as long as this line named the - # first. `shell: bash` carries -e, so a failure inside the loop aborts it. - - name: Typecheck - run: for p in packages/*/; do (cd "$p" && bun run typecheck); done - - name: Unit tests - run: for p in packages/*/; do (cd "$p" && bun run test); done - # `lint`/`format` themselves rewrite files, so CI runs the checking pair. - - name: Lint - run: for p in packages/*/; do (cd "$p" && bun run lint:check); done - - name: Formatting - run: for p in packages/*/; do (cd "$p" && bun run format:check); done - - name: Benchmark acceptance gate tests - run: bun test benchmarks/renderer-benchmark/scripts - - name: Nitrogen output is committed and in sync - run: | - for p in packages/*/; do (cd "$p" && bunx nitrogen); done - if ! git diff --quiet -- 'packages/*/nitrogen/*'; then - echo "::error::nitrogen output is stale — run 'bunx nitrogen' in the package and commit the result" - git diff --stat -- 'packages/*/nitrogen/*' - exit 1 - fi - - name: Tarball carries the entrypoints and the legal files - working-directory: packages/react-native-tgfx - run: | - rm -rf lib - npm pack --silent - # Herestring, not a pipe: `grep -q` would SIGPIPE tar and trip pipefail. - entries=$(tar -tzf react-native-tgfx-*.tgz) - for f in package/lib/index.js package/lib/index.d.ts package/LICENSE package/NOTICE; do - if ! grep -qx "$f" <<<"$entries"; then - echo "::error::$f is missing from the packed tarball" - exit 1 - fi - done - rm -f react-native-tgfx-*.tgz - - # #165: the published tarball shipped none of tgfx's vendored dependencies for - # two releases, because every local and CI build reads them out of the - # submodule and nothing ever installed the packed artifact. - installable: - name: Packed tarball installs and carries a buildable tgfx - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - submodules: recursive - token: ${{ secrets.PERSONAL_ACCESS_TOKEN }} - - name: Verify the tgfx submodule is populated - run: | - if [ ! -f packages/react-native-tgfx/cpp/third_party/tgfx/CMakeLists.txt ]; then - echo "::error::tgfx submodule is empty — PERSONAL_ACCESS_TOKEN needs read access to riteshshukla04/tgfx-private" - exit 1 - fi - - uses: oven-sh/setup-bun@v2 - with: - bun-version: latest - - uses: actions/setup-node@v4 - with: - node-version: 22 - - run: bun install --frozen-lockfile - - name: Pack - working-directory: packages/react-native-tgfx - run: | - rm -rf lib - npm pack --silent --pack-destination "$RUNNER_TEMP" - # Deliberately not --ignore-scripts: the postinstall that fetches the - # vendored dependencies is the thing under test. - - name: Install the tarball into a scratch app - working-directory: ${{ runner.temp }} - run: | - mkdir -p scratch && cd scratch - echo '{"name":"scratch","private":true,"version":"1.0.0"}' > package.json - npm install --no-audit --no-fund ../react-native-tgfx-*.tgz - - name: The installed package has everything the Android configure step reads - working-directory: ${{ runner.temp }}/scratch/node_modules/react-native-tgfx - run: | - for f in cpp/third_party/tgfx/CMakeLists.txt \ - cpp/third_party/tgfx/src/gpu/Texture.cpp \ - cpp/third_party/tgfx/third_party/vendor_tools/vendor.cmake \ - cpp/third_party/tgfx/third_party/vendor_tools/ios.toolchain.cmake; do - if [ ! -f "$f" ]; then - echo "::error::$f missing after a clean install — a fresh app cannot build" - exit 1 - fi - done - - native-changes: - name: Native paths changed - runs-on: ubuntu-latest - outputs: - changed: ${{ steps.check.outputs.changed }} - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - id: check - env: - BASE: ${{ github.event.pull_request.base.sha }} - run: | - if [ -z "$BASE" ]; then - echo "changed=false" >> "$GITHUB_OUTPUT" - exit 0 - fi - # Herestring, not a pipe: `grep -q` would SIGPIPE git and trip pipefail. - files=$(git diff --name-only "$BASE" HEAD) - if grep -qE '^packages/[^/]+/(android|ios|cpp)/' <<<"$files"; then - echo "changed=true" >> "$GITHUB_OUTPUT" - else - echo "changed=false" >> "$GITHUB_OUTPUT" - fi - - ios: - name: iOS Simulator build - # 20-30 min each: dispatched every fifth merged PR, and on any PR that - # touches android/ios/cpp — a Kotlin, Swift or C++ regression would - # otherwise merge without ever being compiled. - needs: native-changes - if: github.event_name == 'workflow_dispatch' || needs.native-changes.outputs.changed == 'true' - runs-on: macos-15 - steps: - - uses: actions/checkout@v4 - with: - submodules: recursive - - uses: oven-sh/setup-bun@v2 - with: - bun-version: latest - - run: bun install --frozen-lockfile - - name: Fetch tgfx third-party dependencies - working-directory: packages/react-native-tgfx/cpp/third_party/tgfx - run: ./install_tools.sh && ./sync_deps.sh - - name: Build the tgfx static library - run: bash packages/react-native-tgfx/scripts/build-tgfx-ios.sh - # Built, not run: they need a Metal device. `bun test` only exercises the - # header-only harness programs, so this is the one place SceneTest — where - # the scene reader's bounds behaviour is asserted — is compiled at all. - # macOS because cpp/tests/CMakeLists.txt forces TGFX_USE_METAL. - - name: Build the C++ tests - working-directory: packages/react-native-tgfx/cpp/tests - run: | - cmake -S . -B build -DCMAKE_BUILD_TYPE=Release - cmake --build build -j3 - - name: Install pods - working-directory: benchmarks/renderer-benchmark - run: | - npm ci - cd ios && pod install - # Compile only: this is the step that would have caught the unwrapped - # baseAddress, and the only one that compiles the Swift and Obj-C++ at all. - - name: Build - working-directory: benchmarks/renderer-benchmark/ios - run: | - xcodebuild -workspace RendererBenchmark.xcworkspace \ - -scheme RendererBenchmark -configuration Release \ - -sdk iphonesimulator -destination 'generic/platform=iOS Simulator' \ - ARCHS=arm64 ONLY_ACTIVE_ARCH=YES build - - leak: - name: Memory-leak soak (emulator) - # Dispatch-only: it costs an emulator hour. The soak churns every - # allocation path; GPU-side growth still needs a real device, because the - # hosted emulator's software renderer draws image scenes blank. - if: github.event_name == 'workflow_dispatch' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - submodules: recursive - token: ${{ secrets.PERSONAL_ACCESS_TOKEN }} - - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '17' - - uses: oven-sh/setup-bun@v2 - with: - bun-version: latest - - uses: actions/setup-node@v4 - with: - node-version: 22 - - run: bun install --frozen-lockfile - - name: Fetch tgfx third-party dependencies - working-directory: packages/react-native-tgfx/cpp/third_party/tgfx - run: ./install_tools.sh && ./sync_deps.sh - - name: Enable KVM - run: | - echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' \ - | sudo tee /etc/udev/rules.d/99-kvm4all.rules - sudo udevadm control --reload-rules - sudo udevadm trigger --name-match=kvm - - name: Build the example debug APK - working-directory: apps/example/android - run: ./gradlew assembleDebug -x lint -PTgfxVulkan=OFF -PreactNativeArchitectures=x86_64 - - name: Soak on the emulator - uses: reactivecircus/android-emulator-runner@v2 - with: - api-level: 34 - arch: x86_64 - avd-name: ci-avd - emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim - script: | - adb install -r apps/example/android/app/build/outputs/apk/debug/app-debug.apk - HARNESS_APP_PATH=apps/example/android/app/build/outputs/apk/debug/app-debug.apk \ - node scripts/leak-check.mjs --runner ci-emu - - android: - name: Android release build - # 20-30 min each: dispatched every fifth merged PR, and on any PR that - # touches android/ios/cpp. - needs: native-changes - if: github.event_name == 'workflow_dispatch' || needs.native-changes.outputs.changed == 'true' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - submodules: recursive - - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '17' - - uses: oven-sh/setup-bun@v2 - with: - bun-version: latest - - run: bun install --frozen-lockfile - - name: Fetch tgfx third-party dependencies - working-directory: packages/react-native-tgfx/cpp/third_party/tgfx - run: ./install_tools.sh && ./sync_deps.sh - - name: Assemble - working-directory: benchmarks/renderer-benchmark - run: | - npm ci - cd android && ./gradlew assembleRelease -x lint diff --git a/.github/workflows/harness-android.yml b/.github/workflows/harness-android.yml new file mode 100644 index 00000000..d6a164ad --- /dev/null +++ b/.github/workflows/harness-android.yml @@ -0,0 +1,142 @@ +name: Harness Android + +concurrency: + group: harness-android-${{ github.ref }} + cancel-in-progress: ${{ github.ref_name != 'main' }} + +on: + push: + branches: [main] + paths: + - '.github/workflows/harness-android.yml' + - 'packages/**' + - 'apps/example/**' + - 'patches/**' + - 'scripts/tgfx-prebuilt.sh' + - 'package.json' + - 'bun.lock' + pull_request: + paths: + - '.github/workflows/harness-android.yml' + - 'packages/**' + - 'apps/example/**' + - 'patches/**' + - 'scripts/tgfx-prebuilt.sh' + - 'package.json' + - 'bun.lock' + workflow_dispatch: + inputs: + api_level: + description: 'Android API level of the emulator' + required: false + default: '35' + type: string + +permissions: + contents: read + +defaults: + run: + shell: bash + +env: + # Read by apps/example/rn-harness.config.mjs (the ci-emu runner). + HARNESS_AVD_NAME: ci-avd + HARNESS_AVD_API_LEVEL: ${{ inputs.api_level || '35' }} + HARNESS_AVD_PROFILE: pixel_7 + +jobs: + harness: + name: Harness Android + runs-on: ubuntu-latest + timeout-minutes: 90 + steps: + - uses: actions/checkout@v7 + + - name: Reclaim disk space + uses: AdityaGarg8/remove-unwanted-software@v5 + with: + remove-dotnet: true + remove-haskell: true + remove-codeql: true + remove-docker-images: true + + - uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + + - name: Install npm dependencies (bun) + run: bun install --frozen-lockfile + + # Keyed by the submodule's pinned commit, so a PR that bumps tgfx misses + # and builds it from source below. + - name: Fetch prebuilt tgfx + id: prebuilt + continue-on-error: true + run: bash scripts/tgfx-prebuilt.sh + + - name: Build tgfx from source (no prebuilt for this submodule commit) + if: steps.prebuilt.outcome == 'failure' + env: + # The fork has no LFS objects; Tencent/tgfx serves the same OIDs. + GIT_LFS_SKIP_SMUDGE: 1 + run: | + git submodule update --init --recursive packages/react-native-tgfx/cpp/third_party/tgfx + (cd packages/react-native-tgfx/cpp/third_party/tgfx && + git config lfs.url https://github.com/Tencent/tgfx.git/info/lfs && + ./install_tools.sh && ./sync_deps.sh) + # NDK 29's clang rejects tgfx's vendored highway, so pin RN's NDK. + (yes || true) | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" "ndk;27.1.12297006" > /dev/null + TGFX_BACKENDS=vulkan VULKAN_ABIS=x86_64 bash packages/react-native-tgfx/scripts/build-tgfx-android.sh + + - name: Setup JDK 17 + uses: actions/setup-java@v6 + with: + distribution: zulu + java-version: 17 + + - name: Restore Gradle/CMake cache + uses: actions/cache@v6 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + apps/example/android/.gradle + apps/example/android/app/.cxx + key: ${{ runner.os }}-gradle-x86_64-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', '**/CMakeLists.txt', '**/*.cmake', 'bun.lock') }} + restore-keys: | + ${{ runner.os }}-gradle-x86_64- + + - name: Build the example debug APK + working-directory: apps/example/android + run: ./gradlew :app:assembleDebug -x lint --no-daemon --build-cache -PreactNativeArchitectures=x86_64 + + - name: Run Harness E2E tests + uses: callstackincubator/react-native-harness@v1.4.0 + with: + runner: ci-emu + projectRoot: apps/example + app: android/app/build/outputs/apk/debug/app-debug.apk + packageManager: bun + + # Written fresh on every run (see the ci-emu runner), so this is the only + # place to see what the emulator drew. + - name: Upload emulator snapshots + if: always() + uses: actions/upload-artifact@v4 + with: + name: harness-android-snapshots + path: apps/example/src/__image_snapshots__/ci-emu + if-no-files-found: ignore + retention-days: 7 + + - name: Print native crash reports + if: failure() + working-directory: apps/example + run: | + [ -d .harness/crash-reports ] || exit 0 + find .harness/crash-reports -type f | sort | while read -r report; do + echo "::group::$report" + cat "$report" + echo "::endgroup::" + done diff --git a/.github/workflows/harness-ios.yml b/.github/workflows/harness-ios.yml new file mode 100644 index 00000000..d1074503 --- /dev/null +++ b/.github/workflows/harness-ios.yml @@ -0,0 +1,175 @@ +name: Harness iOS + +concurrency: + group: harness-ios-${{ github.ref }} + cancel-in-progress: ${{ github.ref_name != 'main' }} + +on: + push: + branches: [main] + paths: + - '.github/workflows/harness-ios.yml' + - 'packages/**' + - 'apps/example/**' + - 'patches/**' + - 'scripts/tgfx-prebuilt.sh' + - 'package.json' + - 'bun.lock' + pull_request: + paths: + - '.github/workflows/harness-ios.yml' + - 'packages/**' + - 'apps/example/**' + - 'patches/**' + - 'scripts/tgfx-prebuilt.sh' + - 'package.json' + - 'bun.lock' + workflow_dispatch: + inputs: + device_model: + description: 'iOS Simulator device model' + required: false + default: 'iPhone 17 Pro' + type: string + ios_version: + description: 'iOS version' + required: false + default: '26.5' + type: string + xcode_version: + description: 'Xcode version' + required: false + default: '26.5' + type: string + +permissions: + contents: read + +defaults: + run: + shell: bash + +env: + XCODE_VERSION: ${{ inputs.xcode_version || '26.5' }} + DEVELOPER_DIR: /Applications/Xcode_${{ inputs.xcode_version || '26.5' }}.app/Contents/Developer + # Read by apps/example/rn-harness.config.mjs (the ios-sim runner). + HARNESS_SIM_DEVICE: ${{ inputs.device_model || 'iPhone 17 Pro' }} + HARNESS_SIM_OS: ${{ inputs.ios_version || '26.5' }} + +jobs: + harness: + name: Harness iOS + runs-on: macos-26 + timeout-minutes: 90 + steps: + - uses: actions/checkout@v7 + + - uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + + - name: Install npm dependencies (bun) + run: bun install --frozen-lockfile + + # Keyed by the submodule's pinned commit; a PR that bumps tgfx misses and + # builds the xcframework from source. + - name: Fetch prebuilt tgfx + id: prebuilt + continue-on-error: true + run: bash scripts/tgfx-prebuilt.sh + + - name: Build tgfx from source (no prebuilt for this submodule commit) + if: steps.prebuilt.outcome == 'failure' + env: + # The fork has no LFS objects; Tencent/tgfx serves the same OIDs. + GIT_LFS_SKIP_SMUDGE: 1 + run: | + git submodule update --init --recursive packages/react-native-tgfx/cpp/third_party/tgfx + (cd packages/react-native-tgfx/cpp/third_party/tgfx && + git config lfs.url https://github.com/Tencent/tgfx.git/info/lfs && + ./install_tools.sh && ./sync_deps.sh) + bash packages/react-native-tgfx/scripts/build-tgfx-ios.sh + + - name: Setup Ruby (bundle) + uses: ruby/setup-ruby@v1 + with: + ruby-version: '3.3' + bundler-cache: true + working-directory: apps/example + + - name: Restore Pods cache + uses: actions/cache@v6 + with: + path: apps/example/ios/Pods + key: ${{ runner.os }}-pods-${{ hashFiles('bun.lock', 'apps/example/Gemfile.lock', 'apps/example/ios/Podfile.lock') }} + restore-keys: | + ${{ runner.os }}-pods- + + - name: Install Pods + working-directory: apps/example/ios + run: bundle exec pod install + + - name: Restore DerivedData cache + uses: actions/cache@v6 + with: + path: apps/example/ios/build + key: ${{ runner.os }}-xcode${{ env.XCODE_VERSION }}-dd-${{ hashFiles('bun.lock', 'apps/example/Gemfile.lock', 'apps/example/ios/Podfile.lock') }} + restore-keys: | + ${{ runner.os }}-xcode${{ env.XCODE_VERSION }}-dd- + + # arm64 only: the runner is Apple Silicon, so the simulator runs natively + # and a second slice would only double the build. + - name: Build the example app for the simulator + working-directory: apps/example/ios + run: | + xcodebuild \ + -derivedDataPath build \ + -workspace TgfxExample.xcworkspace \ + -scheme TgfxExample \ + -sdk iphonesimulator \ + -configuration Debug \ + -destination 'generic/platform=iOS Simulator' \ + ARCHS=arm64 \ + CODE_SIGNING_ALLOWED=NO \ + build | xcbeautify --renderer github-actions + + - name: Install Watchman + run: brew install watchman + + - name: Run Harness E2E tests + uses: callstackincubator/react-native-harness@v1.4.0 + env: + # Metro runs in the harness process and keeps a graph per test file, + # past Node's ~2 GB default on this 7 GB runner (Ubuntu's 16 GB gets ~4 GB). + NODE_OPTIONS: --max-old-space-size=5120 + with: + runner: ios-sim + projectRoot: apps/example + app: ios/build/Build/Products/Debug-iphonesimulator/TgfxExample.app + packageManager: bun + + # Written fresh on every run (see the ios-sim runner), so this is the only + # place to see what the simulator drew. + - name: Upload simulator snapshots + if: always() + uses: actions/upload-artifact@v4 + with: + name: harness-ios-snapshots + path: apps/example/src/__image_snapshots__/ios-sim + if-no-files-found: ignore + retention-days: 7 + + - name: Print native crash reports + if: failure() + working-directory: apps/example + run: | + # Harness only extracts crash logs it classifies as native crashes, + # so also print the simulator's own crash reports. + { + [ -d .harness/crash-reports ] && find .harness/crash-reports -type f + find ~/Library/Logs/DiagnosticReports -name 'TgfxExample*.ips' 2>/dev/null + } | sort | while read -r report; do + echo "::group::$report" + cat "$report" + echo "::endgroup::" + done diff --git a/.github/workflows/lint-cpp.yml b/.github/workflows/lint-cpp.yml new file mode 100644 index 00000000..1de03a2d --- /dev/null +++ b/.github/workflows/lint-cpp.yml @@ -0,0 +1,56 @@ +name: Lint C++ + +on: + push: + branches: [main] + paths: + - '.github/workflows/lint-cpp.yml' + - '.clang-format' + - 'scripts/clang-format.sh' + - '**/*.h' + - '**/*.hpp' + - '**/*.c' + - '**/*.cpp' + - '**/*.m' + - '**/*.mm' + pull_request: + paths: + - '.github/workflows/lint-cpp.yml' + - '.clang-format' + - 'scripts/clang-format.sh' + - '**/*.h' + - '**/*.hpp' + - '**/*.c' + - '**/*.cpp' + - '**/*.m' + - '**/*.mm' + +permissions: + contents: read + +defaults: + run: + shell: bash + +jobs: + lint: + name: Format C++ + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + # The version scripts/clang-format.sh pins; the runner's own is another major. + - name: Install clang-format + run: | + version=$(sed -n 's/^CLANG_FORMAT_VERSION=//p' scripts/clang-format.sh) + pipx install "clang-format==$version" + + - name: Run clang-format + run: bash scripts/clang-format.sh + + - name: Verify no files have changed after format + run: | + if ! git diff --exit-code; then + echo "::error::C++ is not formatted, run 'bun lint-cpp' and commit the result" + exit 1 + fi diff --git a/.github/workflows/lint-typescript.yml b/.github/workflows/lint-typescript.yml new file mode 100644 index 00000000..f4a81f0b --- /dev/null +++ b/.github/workflows/lint-typescript.yml @@ -0,0 +1,85 @@ +name: Lint TypeScript + +on: + push: + branches: [main] + paths: + - '.github/workflows/lint-typescript.yml' + - '**/*.ts' + - '**/*.tsx' + - '**/*.js' + - '**/*.jsx' + - '**/*.mjs' + - '**/*.cjs' + - '**/*.json' + - '**/.eslintrc.js' + - '**/.prettierrc*' + - 'bun.lock' + pull_request: + paths: + - '.github/workflows/lint-typescript.yml' + - '**/*.ts' + - '**/*.tsx' + - '**/*.js' + - '**/*.jsx' + - '**/*.mjs' + - '**/*.cjs' + - '**/*.json' + - '**/.eslintrc.js' + - '**/.prettierrc*' + - 'bun.lock' + +permissions: + contents: read + +# `shell: bash` is the alias carrying -e and -o pipefail, so a failure inside a +# loop below aborts the step instead of being masked by the next package. +defaults: + run: + shell: bash + +jobs: + tsc: + name: Compile TypeScript (tsc) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + + - name: Install npm dependencies (bun) + run: bun install --frozen-lockfile + + # Every workspace package, not a hardcoded one: a package this loop does + # not know about is a package with no gate. + - name: Run TypeScript (tsc) + run: for p in packages/*/; do (cd "$p" && bun run typecheck); done + + lint: + name: Lint TypeScript (eslint, prettier) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + + - name: Install npm dependencies (bun) + run: bun install --frozen-lockfile + + # `lint`/`format` rewrite files, so the packages run their checking pair. + - name: Run ESLint in packages + run: for p in packages/*/; do (cd "$p" && bun run lint:check); done + + - name: Run Prettier in packages + run: for p in packages/*/; do (cd "$p" && bun run format:check); done + + # The apps' `lint` is a plain `eslint .`; errors fail, warnings do not. + - name: Run ESLint in example + working-directory: apps/example + run: bun run lint + + - name: Run ESLint in benchmark + working-directory: apps/benchmark + run: bun run lint diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e3fdf04e..853c82d5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,6 +13,10 @@ on: - major - alpha default: alpha + reuse-build-run-id: + description: 'Skip the tgfx builds and reuse the artifacts of this earlier run id (kept 3 days)' + type: string + default: '' defaults: run: @@ -21,6 +25,7 @@ defaults: jobs: build-tgfx: name: Build tgfx (${{ matrix.platform }}) + if: inputs.reuse-build-run-id == '' runs-on: macos-15 permissions: contents: read @@ -87,10 +92,12 @@ jobs: release: name: Publish to npm (OIDC) and create GitHub release needs: build-tgfx + if: ${{ !cancelled() && (needs.build-tgfx.result == 'success' || needs.build-tgfx.result == 'skipped') }} runs-on: ubuntu-latest permissions: contents: write id-token: write + actions: read steps: # Full history for the changelog; GITHUB_TOKEN stays persisted for release-it's push. - uses: actions/checkout@v6 @@ -98,15 +105,18 @@ jobs: fetch-depth: 0 submodules: recursive - - uses: actions/download-artifact@v4 with: name: tgfx-ios + run-id: ${{ inputs.reuse-build-run-id || github.run_id }} + github-token: ${{ github.token }} path: packages/react-native-tgfx/ios/libs - uses: actions/download-artifact@v4 with: name: tgfx-android + run-id: ${{ inputs.reuse-build-run-id || github.run_id }} + github-token: ${{ github.token }} path: packages/react-native-tgfx/android - name: Verify the prebuilt tgfx libraries @@ -156,7 +166,8 @@ jobs: VERSION=$(./node_modules/.bin/release-it --release-version --ci $ARGS | tail -n1) echo "Releasing $VERSION" echo "version=$VERSION" >> "$GITHUB_OUTPUT" - echo "args=$ARGS" >> "$GITHUB_OUTPUT" + # The increment is already baked into VERSION; only the pre-release flag (npm dist-tag) carries over. + [[ "$RELEASE_TYPE" == "alpha" ]] && echo "args=$ARGS" >> "$GITHUB_OUTPUT" || true - name: Release ${{ steps.version.outputs.version }} env: diff --git a/.github/workflows/review.yml b/.github/workflows/review.yml deleted file mode 100644 index e6ea6267..00000000 --- a/.github/workflows/review.yml +++ /dev/null @@ -1,116 +0,0 @@ -name: Review - -# Automated review pass on every pull request. Separate from ci.yml on purpose: -# CI answers "does it build and pass", this answers "is the change acceptable" -# and leaves its findings on the PR as a comment. -on: - pull_request: - types: [opened, synchronize, reopened] - -# tee in a `run:` returns tee's status, so a failing step reports success. -# `shell: bash` is the alias that carries -o pipefail. -defaults: - run: - shell: bash - -permissions: - contents: read - pull-requests: write - -jobs: - review: - name: Static review - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - uses: oven-sh/setup-bun@v2 - with: - bun-version: latest - - run: bun install --frozen-lockfile - - # Looped over every workspace package rather than naming one: a package - # this gate does not know about is a package with no gate. - - name: Lint - id: lint - continue-on-error: true - run: | - for p in packages/*/; do - (cd "$p" && bunx eslint "**/*.{js,ts,tsx}" --max-warnings 0) - done 2>&1 | tee /tmp/lint.txt - - - name: Formatting - id: format - continue-on-error: true - # bun run resolves node_modules/.bin locally, so the prettier major - # cannot depend on the cwd. The root hoists a different one. - run: | - for p in packages/*/; do (cd "$p" && bun run format:check); done 2>&1 | tee /tmp/format.txt - - # The generated bindings must match the spec, or the native side silently - # drifts from the TypeScript API. - - name: Nitrogen output is in sync - id: codegen - continue-on-error: true - run: | - # nitrogen's own failure has to reach the file too, or -e aborts - # before the tee and the PR comment renders an empty block. - for p in packages/*/; do (cd "$p" && bunx nitrogen); done 2>&1 | tee /tmp/codegen.txt - git diff --exit-code -- 'packages/*/nitrogen/*' 2>&1 | tee -a /tmp/codegen.txt - - # A change to the draw-program format is only safe if both ends move - # together, so flag it for a human rather than trying to judge it here. - - name: Wire-format change needs both ends - id: wire - continue-on-error: true - run: | - BASE=$(git merge-base origin/${{ github.base_ref }} HEAD) - JS=$(git diff --name-only "$BASE" HEAD -- packages/react-native-tgfx/src/compiler/writer.ts | wc -l) - NATIVE=$(git diff --name-only "$BASE" HEAD -- packages/react-native-tgfx/cpp/TgfxScene.cpp | wc -l) - if [ "$JS" -ne "$NATIVE" ]; then - echo "writer.ts and TgfxScene.cpp changed independently — the binary draw program is written by one and read by the other, so check they still agree." | tee /tmp/wire.txt - exit 1 - fi - # Advisory: see the blocking flag in the Comment findings step below. - - - name: Comment findings - uses: actions/github-script@v7 - with: - script: | - const fs = require('fs') - const read = (f) => { try { return fs.readFileSync(f, 'utf8').trim() } catch { return '' } } - // blocking: a machine can be sure it is wrong. The wire check is a - // heuristic — it fires whenever one end of the draw program changes - // without the other, which is usually a cache or rename edit, not a - // format change. It reports; it does not gate. - const checks = [ - ['Lint', '${{ steps.lint.outcome }}', read('/tmp/lint.txt'), true], - ['Formatting', '${{ steps.format.outcome }}', read('/tmp/format.txt'), true], - ['Nitrogen in sync', '${{ steps.codegen.outcome }}', read('/tmp/codegen.txt'), true], - ['Wire format', '${{ steps.wire.outcome }}', read('/tmp/wire.txt'), false], - ] - const hit = checks.filter(([, outcome]) => outcome === 'failure') - const failed = hit.filter(([, , , blocking]) => blocking) - const advisory = hit.filter(([, , , blocking]) => !blocking) - const section = ([name, , out]) => - `**${name}**\n\n\`\`\`\n${out.slice(0, 3000)}\n\`\`\`` - const body = hit.length === 0 - ? '### Review: no findings\n\nLint, formatting, codegen sync and wire-format checks all passed.' - : [ - failed.length - ? '### Review found ' + failed.length + ' issue(s)' - : '### Review: nothing blocking', - '', - ...failed.map(section), - ...(advisory.length - ? ['### Worth a look (not blocking)', '', ...advisory.map(section)] - : []), - ].join('\n') - await github.rest.issues.createComment({ - issue_number: context.issue.number, - owner: context.repo.owner, - repo: context.repo.repo, - body, - }) - if (failed.length > 0) core.setFailed(failed.length + ' review check(s) failed') diff --git a/.wrangler/cache/wrangler-account.json b/.wrangler/cache/wrangler-account.json deleted file mode 100644 index 14358565..00000000 --- a/.wrangler/cache/wrangler-account.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "account": { - "id": "473454749667feb097783cbf918593dc", - "name": "Riteshshukla2381@gmail.com's Account" - } -} \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 15b0f9e7..0d08984b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -34,10 +34,10 @@ bundle install && (cd ios && bundle exec pod install) && bun run ios "Unicode Normalization not appropriate for ASCII-8BIT". Prefix it with `LANG=en_US.UTF-8` if your shell does not set one. -The app has three screens behind the tab bar: the feature gallery, face blur, -and the camera effects. The two camera screens ask for the camera permission -the first time they are opened, and fall back to a message when the device has -no camera — an emulator without a webcam included. +The tab bar switches between the feature gallery, the camera effects and the +other demos. The camera screen asks for the camera permission the first time it +is opened, and falls back to a message when the device has no camera - an +emulator without a webcam included. ## Running the tests @@ -93,6 +93,22 @@ Run the image suites on a real phone. On the `Pixel_8_API_35` AVD's software renderer every image-backed scene comes back blank, so those tests fail there by design rather than writing an empty baseline. +## CI + +Each workflow runs on the pull requests whose paths it covers, and on `main`. + +- `lint-cpp.yml` - clang-format over the C++ and Objective-C++ in `packages/`. + Fix with `bun lint-cpp`, using the version `scripts/clang-format.sh` pins + (`pipx install clang-format==23.1.3`). +- `lint-typescript.yml` - `tsc`, eslint and prettier in each package, eslint in + `apps/example` and `apps/benchmark`. +- `harness-android.yml` - every harness suite on a hosted emulator (`ci-emu`). +- `harness-ios.yml` - every harness suite on a simulator (`ios-sim`), x86_64 + build since ML Kit has no arm64 simulator slice. + +The CI runners write their baselines fresh on each run and upload them as an +artifact. Committed baselines are for the `android` phone only. + ## The memory-leak gate `scripts/leak-check.mjs` drives `apps/example/src/leakSoak.harness.tsx` — ~100s @@ -111,12 +127,9 @@ node scripts/leak-check.mjs # device from rn-harness.config.mjs, debug bu The soak is excluded from the default `bun run harness` run (`testPathIgnorePatterns` in `jest.harness.config.mjs`); the script re-enables -it. In CI, the `leak` job in `ci.yml` runs the same script on a hosted -emulator via `--runner ci-emu` — dispatch-only, -because it costs an emulator hour. It catches allocation-path leaks (the -registries, the scene, the JSI boundary); GPU-side growth needs the real -device, since the hosted emulator's software renderer draws image scenes -blank. +it. It does not run in CI. `--runner ci-emu` runs it on the CI emulator +instead of the phone, which catches allocation-path leaks (the registries, the +scene, the JSI boundary) but not GPU-side growth. ## Imperative APIs first diff --git a/apps/benchmark/App.tsx b/apps/benchmark/App.tsx index a6483a16..8098464b 100644 --- a/apps/benchmark/App.tsx +++ b/apps/benchmark/App.tsx @@ -129,22 +129,6 @@ const PATHS_900 = makePaths(900, 30); function pathsFor(scene: string) { return scene === 'paths100' ? PATHS_100 : scene === 'paths300' ? PATHS_300 : PATHS_900; } -const UNUSED_PATHS = Array.from({ length: 0 }, (_, i) => { - const col = i % 30; - const row = Math.floor(i / 30); - const x = col * (W / 30); - const y = row * (H / 30); - const w = W / 30 - 1; - const h = H / 30 - 1; - return { - d: - `M${x} ${y + h / 2}` + - `C${x + w / 4} ${y}, ${x + w / 2} ${y + h}, ${x + w} ${y + h / 2}` + - `C${x + w * 0.75} ${y + h}, ${x + w / 2} ${y}, ${x} ${y + h / 2}Z`, - color: PALETTE[i % PALETTE.length], - stroked: i % 2 === 0, - }; -}); const TEXTS = Array.from({ length: 6000 }, (_, i) => ({ x: (i % 25) * (W / 25), diff --git a/apps/example/.gitignore b/apps/example/.gitignore index cbabea3c..9a3d05ee 100644 --- a/apps/example/.gitignore +++ b/apps/example/.gitignore @@ -76,3 +76,7 @@ yarn-error.log # React Native Harness generated manifest .harness/ + +# Baselines the CI runners write on every run (harness-*.yml); never committed +src/__image_snapshots__/ci-emu/ +src/__image_snapshots__/ios-sim/ diff --git a/apps/example/App.tsx b/apps/example/App.tsx index d9081c0f..75c1d0bf 100644 --- a/apps/example/App.tsx +++ b/apps/example/App.tsx @@ -61,7 +61,6 @@ import { SdCirclePanel, } from './src/shaderExamples'; import { TgfxCameraEffects } from './src/TgfxCameraEffects'; -import { TgfxFaceBlur } from './src/TgfxFaceBlur'; import { LittlePrinceScreen } from './src/littlePrince'; import { ScrollableShapesScreen } from './src/scrollableShapes'; import { PhysicsScreen } from './src/physics'; @@ -391,7 +390,6 @@ const SCREENS = [ 'gallery', 'logo', 'pan', - 'faceblur', 'effects', 'prince', 'shapes', @@ -435,11 +433,6 @@ function Screens() { ) : null} - {screen === 'faceblur' ? ( - - - - ) : null} {screen === 'effects' ? ( diff --git a/apps/example/ios/Podfile b/apps/example/ios/Podfile index 6277bb65..cbc22846 100644 --- a/apps/example/ios/Podfile +++ b/apps/example/ios/Podfile @@ -5,8 +5,7 @@ require Pod::Executable.execute_command('node', ['-p', {paths: [process.argv[1]]}, )', __dir__]).strip -# 15.5 is the floor for GoogleMLKit/FaceDetection pulled in by VisionCameraFaceDetector -platform :ios, [min_ios_version_supported, '15.5'].max +platform :ios, min_ios_version_supported prepare_react_native_project! linkage = ENV['USE_FRAMEWORKS'] diff --git a/apps/example/ios/Podfile.lock b/apps/example/ios/Podfile.lock index a56e61fa..1b753cb3 100644 --- a/apps/example/ios/Podfile.lock +++ b/apps/example/ios/Podfile.lock @@ -1,28 +1,5 @@ PODS: - FBLazyVector (0.85.3) - - GoogleDataTransport (10.1.1): - - nanopb (~> 3.30910.0) - - PromisesObjC (~> 2.4) - - GoogleMLKit/FaceDetection (9.0.0): - - GoogleMLKit/MLKitCore - - MLKitFaceDetection (~> 8.0.0) - - GoogleMLKit/MLKitCore (9.0.0): - - MLKitCommon (~> 14.0.0) - - GoogleToolboxForMac/Defines (4.2.1) - - GoogleToolboxForMac/Logger (4.2.1): - - GoogleToolboxForMac/Defines (= 4.2.1) - - "GoogleToolboxForMac/NSData+zlib (4.2.1)": - - GoogleToolboxForMac/Defines (= 4.2.1) - - GoogleUtilities/Environment (8.1.2): - - GoogleUtilities/Privacy - - GoogleUtilities/Logger (8.1.2): - - GoogleUtilities/Environment - - GoogleUtilities/Privacy - - GoogleUtilities/Privacy (8.1.2) - - GoogleUtilities/UserDefaults (8.1.2): - - GoogleUtilities/Logger - - GoogleUtilities/Privacy - - GTMSessionFetcher/Core (3.5.0) - HarnessUI (1.3.0): - hermes-engine - RCTRequired @@ -48,28 +25,6 @@ PODS: - hermes-engine (250829098.0.10): - hermes-engine/Pre-built (= 250829098.0.10) - hermes-engine/Pre-built (250829098.0.10) - - MLImage (1.0.0-beta8) - - MLKitCommon (14.0.0): - - GoogleDataTransport (~> 10.0) - - GoogleToolboxForMac/Logger (< 5.0, >= 4.2.1) - - "GoogleToolboxForMac/NSData+zlib (< 5.0, >= 4.2.1)" - - GoogleUtilities/Logger (~> 8.0) - - GoogleUtilities/UserDefaults (~> 8.0) - - GTMSessionFetcher/Core (< 4.0, >= 3.3.2) - - MLKitFaceDetection (8.0.0): - - MLKitCommon (~> 14.0) - - MLKitVision (~> 10.0) - - MLKitVision (10.0.0): - - GoogleToolboxForMac/Logger (< 5.0, >= 4.2.1) - - "GoogleToolboxForMac/NSData+zlib (< 5.0, >= 4.2.1)" - - GTMSessionFetcher/Core (< 4.0, >= 3.3.2) - - MLImage (= 1.0.0-beta8) - - MLKitCommon (~> 14.0) - - nanopb (3.30910.0): - - nanopb/decode (= 3.30910.0) - - nanopb/encode (= 3.30910.0) - - nanopb/decode (3.30910.0) - - nanopb/encode (3.30910.0) - NitroImage (0.15.1): - hermes-engine - NitroModules @@ -117,7 +72,7 @@ PODS: - ReactCommon/turbomodule/core - ReactNativeDependencies - Yoga - - NitroTgfx (0.0.2-alpha.10): + - NitroTgfx (0.1.0): - hermes-engine - NitroModules - RCTRequired @@ -141,7 +96,7 @@ PODS: - ReactCommon/turbomodule/core - ReactNativeDependencies - Yoga - - NitroTgfxCamera (0.0.1-alpha.4): + - NitroTgfxCamera (0.1.0): - hermes-engine - NitroModules - NitroTgfx @@ -167,7 +122,6 @@ PODS: - ReactNativeDependencies - VisionCamera - Yoga - - PromisesObjC (2.4.1) - RCTDeprecation (0.85.3) - RCTRequired (0.85.3) - RCTSwiftUI (0.85.3) @@ -2238,32 +2192,6 @@ PODS: - ReactCommon/turbomodule/core - ReactNativeDependencies - Yoga - - VisionCameraFaceDetector (2.0.6): - - GoogleMLKit/FaceDetection (= 9.0.0) - - hermes-engine - - NitroModules - - RCTRequired - - RCTTypeSafety - - React-callinvoker - - React-Core - - React-Core-prebuilt - - React-debug - - React-Fabric - - React-featureflags - - React-graphics - - React-ImageManager - - React-jsi - - React-NativeModulesApple - - React-RCTFabric - - React-renderercss - - React-rendererdebug - - React-utils - - ReactCodegen - - ReactCommon/turbomodule/bridging - - ReactCommon/turbomodule/core - - ReactNativeDependencies - - VisionCamera - - Yoga - VisionCameraWorklets (5.2.0): - hermes-engine - NitroModules @@ -2377,24 +2305,9 @@ DEPENDENCIES: - RNReanimated (from `../../../node_modules/react-native-reanimated`) - RNWorklets (from `../../../node_modules/react-native-worklets`) - VisionCamera (from `../../../node_modules/react-native-vision-camera`) - - VisionCameraFaceDetector (from `../../../node_modules/react-native-vision-camera-face-detector`) - VisionCameraWorklets (from `../../../node_modules/react-native-vision-camera-worklets`) - Yoga (from `../../../node_modules/react-native/ReactCommon/yoga`) -SPEC REPOS: - trunk: - - GoogleDataTransport - - GoogleMLKit - - GoogleToolboxForMac - - GoogleUtilities - - GTMSessionFetcher - - MLImage - - MLKitCommon - - MLKitFaceDetection - - MLKitVision - - nanopb - - PromisesObjC - EXTERNAL SOURCES: FBLazyVector: :path: "../../../node_modules/react-native/Libraries/FBLazyVector" @@ -2563,8 +2476,6 @@ EXTERNAL SOURCES: :path: "../../../node_modules/react-native-worklets" VisionCamera: :path: "../../../node_modules/react-native-vision-camera" - VisionCameraFaceDetector: - :path: "../../../node_modules/react-native-vision-camera-face-detector" VisionCameraWorklets: :path: "../../../node_modules/react-native-vision-camera-worklets" Yoga: @@ -2572,23 +2483,12 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: FBLazyVector: 24e62c765683b8d89006a88a2c8f5cf019f0074d - GoogleDataTransport: a24e58982ab3ba2f64d79613e027fe7f57e88539 - GoogleMLKit: b1eee21a41c57704fe72483b15c85cb2c0cd7444 - GoogleToolboxForMac: d1a2cbf009c453f4d6ded37c105e2f67a32206d8 - GoogleUtilities: 766ace00c6b10d8148408f329d10c4f051931850 - GTMSessionFetcher: 5aea5ba6bd522a239e236100971f10cb71b96ab6 HarnessUI: f439596aec93ff76765451f834c93f966d54e53e - hermes-engine: d9f77c582ef8af5579a4bce269900b09b739735d - MLImage: 0de5c6c2bf9e93b80ef752e2797f0836f03b58c0 - MLKitCommon: 47d47b50a031d00db62f1b0efe5a1d8b09a3b2e6 - MLKitFaceDetection: 32549f1e70e6e7731261bf9cea2b74095e2531cb - MLKitVision: 39a5a812db83c4a0794445088e567f3631c11961 - nanopb: fad817b59e0457d11a5dfbde799381cd727c1275 + hermes-engine: 58f4822764f3a9815044f59cfb5686c16a84754d NitroImage: 2f592086cbdecbbaa1c10dd97e0cdd43b1bb0817 NitroModules: 452230d9b63c6c3f59dd97eeaa27ec3449271d4a - NitroTgfx: 80ee71ec84987ceafac599cd081aca0937e79b17 - NitroTgfxCamera: d376202c7b83edb3a14bf786f41d5f48301becff - PromisesObjC: 752c3227f599e3467650e47ea36f433eeb10c273 + NitroTgfx: c75630aa991b4a7b16fceb0720c65da640960fd9 + NitroTgfxCamera: 4829584fec253c1f7c23fdd2b13219ea47870b77 RCTDeprecation: a4c521821fab57cbb125b36effe84d897d0dfa12 RCTRequired: 9f3a7e5645d4bc3f551593de7550bb66ab6e42bc RCTSwiftUI: 239ed2eb9e73de5a6f518810630f0c95e01c8702 @@ -2597,7 +2497,7 @@ SPEC CHECKSUMS: React: e2dc35338068bbd299c66f043ae0d7f25de8499e React-callinvoker: 28b25d21b124c26cebaea713ba7d801b9351dc48 React-Core: 02ed7d2ffb70437bdf2aba074a13078a7b0b9ff0 - React-Core-prebuilt: 2825901e5c1cd6b1e2a782b512315ed4f1f839d3 + React-Core-prebuilt: 25b2ed0b2a1b5c83d11b223a023cc09b4b565806 React-CoreModules: b3a5a42dadcde3b5d47b325bd912eb2ced89e146 React-cxxreact: fe8f88dda044e5905e99a00f41b7a874c3908716 React-debug: 92944dc4d89f56d640e75498266cbde557a48189 @@ -2660,15 +2560,14 @@ SPEC CHECKSUMS: ReactAppDependencyProvider: 25c9c516839be2c5e3d3344f95dc7da5f7e63fc2 ReactCodegen: dfe41c3f92bdf782bcf9b2c9d7c12cb9cfd82cb7 ReactCommon: 7dfc3250793bf36cf221096ff59e1179e13eef7f - ReactNativeDependencies: 51b835cb1683792f4e1ddda290ff014f204cc1e1 + ReactNativeDependencies: c28f59fffc0eb0b5916f8ce57fb9c91ae67ba018 RNGestureHandler: ea542e5ad254ac2d234024168a8b87d723cf9463 RNReanimated: 7094afd106a35ecb18602b098a2d862e5d358610 RNWorklets: 569850c3a49a5fc56fce17aafb19be4316a60e58 VisionCamera: fee2d5cfbc39eae6cd7c1ecf2165873a544e7ecd - VisionCameraFaceDetector: 8c4ba53663f9137d4329d55d8ad2019be78c5037 VisionCameraWorklets: d7658e2935db2dbb6c25a6929b13a93414697aef Yoga: 77dfa8673de2874e1855002ae59c68b8be9b007b -PODFILE CHECKSUM: e48e639020fe727755b1eb78129c50e72b433a63 +PODFILE CHECKSUM: eab69dfd2daa1cf741d10f4aba50ad95d22d8a5b COCOAPODS: 1.15.2 diff --git a/apps/example/ios/TgfxExample/AppDelegate.swift b/apps/example/ios/TgfxExample/AppDelegate.swift index a9127137..2f0a4f44 100644 --- a/apps/example/ios/TgfxExample/AppDelegate.swift +++ b/apps/example/ios/TgfxExample/AppDelegate.swift @@ -5,8 +5,6 @@ import ReactAppDependencyProvider @main class AppDelegate: UIResponder, UIApplicationDelegate { - var window: UIWindow? - var reactNativeDelegate: ReactNativeDelegate? var reactNativeFactory: RCTReactNativeFactory? @@ -21,15 +19,31 @@ class AppDelegate: UIResponder, UIApplicationDelegate { reactNativeDelegate = delegate reactNativeFactory = factory - window = UIWindow(frame: UIScreen.main.bounds) + return true + } +} + +// The iOS 27 SDK traps at launch in an app that does not adopt the scene lifecycle. +class SceneDelegate: UIResponder, UIWindowSceneDelegate { + var window: UIWindow? + + func scene( + _ scene: UIScene, + willConnectTo session: UISceneSession, + options connectionOptions: UIScene.ConnectionOptions + ) { + guard let windowScene = scene as? UIWindowScene, + let factory = (UIApplication.shared.delegate as? AppDelegate)?.reactNativeFactory else { + return + } + + window = UIWindow(windowScene: windowScene) factory.startReactNative( withModuleName: "TgfxExample", in: window, - launchOptions: launchOptions + launchOptions: nil ) - - return true } } diff --git a/apps/example/ios/TgfxExample/Info.plist b/apps/example/ios/TgfxExample/Info.plist index baaf8f40..dac97a6f 100644 --- a/apps/example/ios/TgfxExample/Info.plist +++ b/apps/example/ios/TgfxExample/Info.plist @@ -39,6 +39,23 @@ RCTNewArchEnabled + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationName + Default Configuration + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + + + + UILaunchStoryboardName LaunchScreen UIRequiredDeviceCapabilities diff --git a/apps/example/jest.harness.config.mjs b/apps/example/jest.harness.config.mjs index 3a74261e..70b3316c 100644 --- a/apps/example/jest.harness.config.mjs +++ b/apps/example/jest.harness.config.mjs @@ -1,11 +1,13 @@ export default { preset: 'react-native-harness', testMatch: ['/src/**/*.harness.[jt]s?(x)'], - // The ~90s memory soak is scripts/leak-check.mjs's business, not the default - // suite's; the script re-enables it with --testPathIgnorePatterns='$^'. - testPathIgnorePatterns: ['leakSoak'], - // The ~35s adb-watched purge scenario is scripts/cache-purge-check.mjs's - // business, not the default suite's; the script re-enables it with - // --testPathIgnorePatterns='$^'. - testPathIgnorePatterns: ['cachePurgeAdb'], + testPathIgnorePatterns: [ + // The ~90s memory soak is scripts/leak-check.mjs's business, not the + // default suite's; the script re-enables it with --testPathIgnorePatterns='$^'. + 'leakSoak', + // The ~35s adb-watched purge scenario is scripts/cache-purge-check.mjs's + // business, not the default suite's; the script re-enables it with + // --testPathIgnorePatterns='$^'. + 'cachePurgeAdb', + ], }; diff --git a/apps/example/package.json b/apps/example/package.json index 52709b88..c0629146 100644 --- a/apps/example/package.json +++ b/apps/example/package.json @@ -22,7 +22,6 @@ "react-native-tgfx": "workspace:*", "react-native-tgfx-vision-camera": "workspace:*", "react-native-vision-camera": "^5.2.0", - "react-native-vision-camera-face-detector": "^2.0.6", "react-native-vision-camera-worklets": "^5.2.0", "react-native-worklets": "0.11.3" }, diff --git a/apps/example/rn-harness.config.mjs b/apps/example/rn-harness.config.mjs index aa7d479d..ef249abf 100644 --- a/apps/example/rn-harness.config.mjs +++ b/apps/example/rn-harness.config.mjs @@ -8,6 +8,8 @@ import { appleSimulator, } from '@react-native-harness/platform-apple'; +const CI = process.env.CI === 'true'; + export default { entryPoint: './index.js', appRegistryComponentName: 'TgfxExample', @@ -19,6 +21,9 @@ export default { // shorter than the ~90s leak soak (leakSoak.harness.tsx), which would be // reported as "the device did not respond". bridgeTimeout: 180000, + // A cold hosted emulator or simulator boots and bundles far slower than a device. + platformReadyTimeout: CI ? 420000 : 300000, + bundleStartTimeout: CI ? 120000 : 60000, runners: [ // The default runner, so the one baseline directory: __image_snapshots__/android. @@ -29,17 +34,30 @@ export default { device: physicalAndroidDevice('samsung', 'SM-E146B'), bundleId: 'com.tgfxexample', }), - // CI's emulator, selected with --harnessRunner=ci-emu. Only the leak soak - // runs there (ci.yml `leak` job), and it snapshots nothing. + // CI's emulator (harness-android.yml), selected with --harnessRunner=ci-emu. + // Harness creates the AVD when it is missing. Its baselines are written on + // every run and never committed: a hosted emulator's software renderer is + // not the reference device, so on CI the frame-comparison and drew-something + // assertions gate, and the snapshots are uploaded for a look. androidPlatform({ name: 'ci-emu', - device: androidEmulator('ci-avd'), + device: androidEmulator(process.env.HARNESS_AVD_NAME ?? 'ci-avd', { + apiLevel: Number(process.env.HARNESS_AVD_API_LEVEL ?? 35), + profile: process.env.HARNESS_AVD_PROFILE ?? 'pixel_7', + diskSize: '4G', + heapSize: '1G', + snapshot: { enabled: CI }, + }), bundleId: 'com.tgfxexample', }), - // An iOS simulator, selected with --harnessRunner=ios-sim. + // An iOS simulator (harness-ios.yml), selected with --harnessRunner=ios-sim. + // Same baseline rule as ci-emu. applePlatform({ name: 'ios-sim', - device: appleSimulator('iPhone 17 Pro', '26.5'), + device: appleSimulator( + process.env.HARNESS_SIM_DEVICE ?? 'iPhone 17 Pro', + process.env.HARNESS_SIM_OS ?? '26.5', + ), bundleId: 'com.pikachu.ritesh.dev', }), ], diff --git a/apps/example/src/TgfxCameraEffects.tsx b/apps/example/src/TgfxCameraEffects.tsx index 6c421ba1..dce45209 100644 --- a/apps/example/src/TgfxCameraEffects.tsx +++ b/apps/example/src/TgfxCameraEffects.tsx @@ -2,7 +2,6 @@ import { useEffect, useState } from 'react' import { Pressable, StyleSheet, Text as RNText, View } from 'react-native' import type { CameraDevice } from 'react-native-vision-camera' import { - NativePreviewView, useCamera, useCameraDevice, useCameraPermission, diff --git a/apps/example/src/TgfxFaceBlur.tsx b/apps/example/src/TgfxFaceBlur.tsx deleted file mode 100644 index 2029f241..00000000 --- a/apps/example/src/TgfxFaceBlur.tsx +++ /dev/null @@ -1,157 +0,0 @@ -import { useCallback, useMemo } from 'react' -import { StyleSheet, Text, View } from 'react-native' -import type { CameraDevice, Frame } from 'react-native-vision-camera' -import { - useCamera, - useCameraDevice, - useCameraPermission, - useFrameOutput, -} from 'react-native-vision-camera' -import { useFaceDetector } from 'react-native-vision-camera-face-detector' -import { - Blur, - Canvas, - CameraFrame, - ImageShader, - Oval, - Paint, - useCameraFrame, - useNode, - type NodeHandle, -} from 'react-native-tgfx' - -const BLUR_RADIUS = 25 -const SLOTS = [0, 1, 2, 3, 4, 5, 6, 7] -// Module const: a fresh options object re-creates the ML Kit client every render. -const DETECTOR_OPTIONS = { - performanceMode: 'fast', - runContours: false, - runLandmarks: false, - runClassifications: false, -} as const - -/** - * The gate is its own component: the frame and face-detector hooks below reach - * for a camera as soon as they run, so on a device without one they must never - * run at all — and a hook cannot be called conditionally. - */ -export function TgfxFaceBlur() { - const { hasPermission, requestPermission } = useCameraPermission() - const device = useCameraDevice('front') - - if (!hasPermission) { - return ( - - { - requestPermission() - }} - > - Tap to grant camera permission. - - - ) - } - if (device == null) { - return ( - - - No camera available. - - - ) - } - return -} - -function FaceBlurCamera({ device }: { device: CameraDevice }) { - const slot0 = useNode() - const slot1 = useNode() - const slot2 = useNode() - const slot3 = useNode() - const slot4 = useNode() - const slot5 = useNode() - const slot6 = useNode() - const slot7 = useNode() - // Stable array identity: rebuilt every render it would re-create the worklet each frame. - const ovals: NodeHandle[] = useMemo( - () => [slot0, slot1, slot2, slot3, slot4, slot5, slot6, slot7], - [slot0, slot1, slot2, slot3, slot4, slot5, slot6, slot7] - ) - - const faceDetector = useFaceDetector(DETECTOR_OPTIONS) - - const detect = useCallback( - (frame: Frame) => { - 'worklet' - // Already in frame pixels, the space 's children draw in, so unscaled. - const faces = faceDetector.detectFaces(frame) - for (let i = 0; i < SLOTS.length; i++) { - const bounds = i < faces.length ? faces[i]!.bounds : null - if (bounds == null) { - ovals[i]!.set({ width: 0, height: 0 }) - continue - } - ovals[i]!.set({ - x: bounds.x, - y: bounds.y, - width: bounds.width, - height: bounds.height, - }) - } - }, - [faceDetector, ovals] - ) - - const { image, posture, onFrame } = useCameraFrame(detect) - - const frameOutput = useFrameOutput({ - // 'yuv', not 'rgb': tgfx imports the planes straight to a texture and converts in the shader. - pixelFormat: 'yuv', - dropFramesWhileBusy: true, - // The pipeline rotates the buffers, so `orientation` arrives 'up' and `isMirrored` false. - enablePhysicalBufferRotation: true, - // Headless: this output is the only one, so deferring it behind a preview starts it late. - allowDeferredStart: false, - onFrame, - }) - useCamera({ - isActive: true, - device: device, - outputs: [frameOutput], - }) - - return ( - - - - {SLOTS.map(slot => ( - - - {/* The same frame, sampled 1:1 in this space, so the blurred - pixels are the pixels underneath. Tile modes are left at - 'clamp': a YUV image sampled with any other one comes back - transparent at the pinned tgfx. */} - - - - - ))} - - - - ) -} - -const styles = StyleSheet.create({ - fill: { flex: 1, backgroundColor: '#000' }, - center: { - flex: 1, - alignItems: 'center', - justifyContent: 'center', - backgroundColor: '#000', - }, - text: { color: '#fff', fontSize: 16 }, -}) diff --git a/apps/example/src/__image_snapshots__/android/image-fit-modes.png b/apps/example/src/__image_snapshots__/android/image-fit-modes.png index 51d0e354..920168e2 100644 Binary files a/apps/example/src/__image_snapshots__/android/image-fit-modes.png and b/apps/example/src/__image_snapshots__/android/image-fit-modes.png differ diff --git a/apps/example/src/__image_snapshots__/android/imperative-shader-uniform-patched.png b/apps/example/src/__image_snapshots__/android/imperative-shader-uniform-patched.png index 9e3e07cb..da83cdef 100644 Binary files a/apps/example/src/__image_snapshots__/android/imperative-shader-uniform-patched.png and b/apps/example/src/__image_snapshots__/android/imperative-shader-uniform-patched.png differ diff --git a/apps/example/src/__image_snapshots__/android/pixels-from-pixels.png b/apps/example/src/__image_snapshots__/android/pixels-from-pixels.png index 47cbf3d7..5814543b 100644 Binary files a/apps/example/src/__image_snapshots__/android/pixels-from-pixels.png and b/apps/example/src/__image_snapshots__/android/pixels-from-pixels.png differ diff --git a/apps/example/src/__image_snapshots__/android/shader-procedural-rings-dense.png b/apps/example/src/__image_snapshots__/android/shader-procedural-rings-dense.png index 11cf4a05..7364a672 100644 Binary files a/apps/example/src/__image_snapshots__/android/shader-procedural-rings-dense.png and b/apps/example/src/__image_snapshots__/android/shader-procedural-rings-dense.png differ diff --git a/apps/example/src/app.harness.tsx b/apps/example/src/app.harness.tsx index 675b5fb7..a197e5e1 100644 --- a/apps/example/src/app.harness.tsx +++ b/apps/example/src/app.harness.tsx @@ -1,10 +1,10 @@ -// UI test of the shell the three screens live in: tabs, switching, and what each screen mounts. +// UI test of the shell the screens live in: tabs, switching, and what each screen mounts. import React from 'react'; import { describe, expect, render, test, waitFor } from 'react-native-harness'; import { screen, userEvent } from '@react-native-harness/ui'; import App from '../App'; -const TABS = ['gallery', 'faceblur', 'effects'] as const; +const TABS = ['gallery', 'effects'] as const; type Tab = (typeof TABS)[number]; // waitFor defaults to 1s; a camera screen's first mount on real hardware — @@ -32,12 +32,12 @@ describe('example app shell', () => { await render(); expect(await screen.findByTestId('screen-gallery')).toBeTruthy(); - await userEvent.press(await screen.findByTestId('tab-faceblur')); + await userEvent.press(await screen.findByTestId('tab-effects')); await waitFor(() => { expect(screen.queryByTestId('screen-gallery')).toBeFalsy(); }, MOUNT); - // Deliberately not asserting that `screen-faceblur` mounts. VisionCamera + // Deliberately not asserting that `screen-effects` mounts. VisionCamera // does not come up inside a Harness overlay render — on an emulator or on // a device — so the camera screens are covered by running the app, not // from here. What this does protect is the gallery being torn down, which diff --git a/apps/example/src/image.harness.tsx b/apps/example/src/image.harness.tsx index 370655a0..e01a7890 100644 --- a/apps/example/src/image.harness.tsx +++ b/apps/example/src/image.harness.tsx @@ -26,7 +26,6 @@ import { Stage, drawnSnapshot, sameFrame, - snapshot, stageBytes, } from './testSupport'; @@ -200,6 +199,37 @@ describe('tgfx image rendering', () => { ); }); + /** The settled frame of the 128x128 sample drawn into one box with `fit`. */ + async function fitFrame(fit: Fit, width: number, height: number) { + await render( + + + + , + ); + return stageBytes(); + } + + test('scaleDown shrinks an image larger than its box like contain', async () => { + const scaleDown = await fitFrame('scaleDown', 62, 44); + expect(sameFrame(scaleDown, await fitFrame('contain', 62, 44))).toBe(true); + // Also proves the image drew: two blank frames would match too. + expect(sameFrame(scaleDown, await fitFrame('fill', 62, 44))).toBe(false); + }); + + test('scaleDown leaves an image smaller than its box at its own size', async () => { + const scaleDown = await fitFrame('scaleDown', 160, 150); + expect(sameFrame(scaleDown, await fitFrame('none', 160, 150))).toBe(true); + expect(sameFrame(scaleDown, await fitFrame('fill', 160, 150))).toBe(false); + }); + test('draws every sampling mode', async () => { const modes = ['nearest', 'linear', 'mipmap'] as const; await drawnSnapshot( diff --git a/apps/example/src/offscreen.harness.tsx b/apps/example/src/offscreen.harness.tsx index 20124155..86546e84 100644 --- a/apps/example/src/offscreen.harness.tsx +++ b/apps/example/src/offscreen.harness.tsx @@ -4,18 +4,20 @@ import React from 'react'; import { Platform } from 'react-native'; import { describe, expect, render, test } from 'react-native-harness'; import { - Canvas, Circle, Fill, Group, Rect, RoundedRect, Scene, + blur, circle, createHandle, createOffscreenSurface, fill, group, + image, + imageFromPixels, rect, renderToImage, rrect, @@ -169,4 +171,60 @@ describe('tgfx offscreen surface', () => { } expect(failed).toBe(true); }); + + // Pixel assertions verify the workload; memory is measured outside the app. + test('offscreen leak soak: repeatedly renders and releases snapshots on one retained surface', async () => { + const size = 512; + const surface = createOffscreenSurface({ width: size, height: size }); + const pixels = new Uint32Array(size * size); + const scene = Scene.create(); + try { + scene.attach(surface); + for (let frame = 0; frame < 450; frame += 1) { + const x = frame % 2 === 0 ? 0 : size - 32; + const blue = frame % 256; + const top = 0xff000000 + blue * 0x10000; + pixels.fill(top); + pixels.fill(top + 0xffff, pixels.length / 2); // sharp horizontal boundary + const input = imageFromPixels(pixels.buffer, size, size); + try { + // Literal scenes isolate the worker from UI-runtime slot scheduling. + scene.replaceChildren([ + fill({ color: '#000' }), + image({ x: 0, y: 0, width: size, height: size, image: input }, [ + blur({ blur: 4 }), + ]), + rect({ x, y: 0, width: 32, height: 32, color: '#ff0000' }), + ]); + scene.flush(); + // Wait for a real worker render; flush coalescing cannot skip frames. + const snapshot = await surface.toImage(); + try { + if (frame < 2 || frame === 449) { + const bytes = new Uint8Array(await snapshot.encode('raw')); + expect(bytes.length).toBe(size * size * 4); + expect(bytes[(x + 16 * size) * 4]).toBe(255); + expect(bytes[(x + 16 * size) * 4 + 1]).toBe(0); + const background = (size / 2 + (size / 4) * size) * 4; + expect(bytes[background]).toBe(0); + expect(bytes[background + 2]).toBe(blue); + const boundary = (size / 2 + (size / 2) * size) * 4; + // Without blur this first pixel in the bottom half is 255. + expect(bytes[boundary]).toBeGreaterThan(32); + expect(bytes[boundary]).toBeLessThan(223); + } + } finally { + snapshot.dispose(); + } + } finally { + input.dispose(); + } + await sleep(150); + } + } finally { + scene.dispose(); + surface.dispose(); + } + await sleep(500); + }); }); diff --git a/apps/example/src/transform3d.harness.tsx b/apps/example/src/transform3d.harness.tsx index ef00d050..e3b4c075 100644 --- a/apps/example/src/transform3d.harness.tsx +++ b/apps/example/src/transform3d.harness.tsx @@ -38,7 +38,9 @@ async function readBack(scene: React.ReactNode) { width: shot.width, height: shot.height, at(x: number, y: number) { - const i = (y * shot.width + x) * 4; + // Floored: an odd-sized frame puts width / 2 on a half pixel, and a + // fractional index lands on another row's left edge instead. + const i = (Math.floor(y) * shot.width + Math.floor(x)) * 4; return [px[i]!, px[i + 1]!, px[i + 2]!]; }, }; diff --git a/bun.lock b/bun.lock index ef64f5f4..2040d1fb 100644 --- a/bun.lock +++ b/bun.lock @@ -63,7 +63,6 @@ "react-native-tgfx": "workspace:*", "react-native-tgfx-vision-camera": "workspace:*", "react-native-vision-camera": "^5.2.0", - "react-native-vision-camera-face-detector": "^2.0.6", "react-native-vision-camera-worklets": "^5.2.0", "react-native-worklets": "0.11.3", }, @@ -124,7 +123,7 @@ }, "packages/react-native-tgfx": { "name": "react-native-tgfx", - "version": "0.0.2-alpha.12", + "version": "0.1.0", "dependencies": { "react-reconciler": "0.33.0", }, @@ -159,7 +158,7 @@ }, "packages/react-native-tgfx-vision-camera": { "name": "react-native-tgfx-vision-camera", - "version": "0.0.1-alpha.4", + "version": "0.1.0", "devDependencies": { "@eslint/js": "^9.39.4", "@typescript-eslint/eslint-plugin": "^8.48.2", @@ -2467,8 +2466,6 @@ "react-native-vision-camera": ["react-native-vision-camera@5.2.0", "", { "peerDependencies": { "react": "*", "react-native": "*", "react-native-nitro-image": "*", "react-native-nitro-modules": "*" } }, "sha512-0qvR62KLj15YO0L0MeZFqiepGunDD3Ld1i6tWNtFFxZgU5jIyuTFHBI2hsFM6v1N+GaVez/qe1Jkta9rSe7BFg=="], - "react-native-vision-camera-face-detector": ["react-native-vision-camera-face-detector@2.0.6", "", { "peerDependencies": { "react": ">= 18", "react-native": ">= 0.74", "react-native-nitro-modules": ">= 0.35", "react-native-vision-camera": ">= 5.0" } }, "sha512-UWB+lPTaPy4bDRWcVCbmYBZdZ8u4p9FxPVeCNY6hmR4e+cnqQLRW+MgiYM2hremFlPUPoPJh8rH7702SBYuB7g=="], - "react-native-vision-camera-worklets": ["react-native-vision-camera-worklets@5.2.0", "", { "peerDependencies": { "react": "*", "react-native": "*", "react-native-nitro-modules": "*", "react-native-vision-camera": "*", "react-native-worklets": "*" } }, "sha512-LqaHDYt+ahzDahLIlgfwpb3lhI6Y/WSVKj+BNjJOiigDmCMuM9UrCESxYIWW5gPMkye14wdDhbCqQRYVoV31OA=="], "react-native-webgpu-dawn": ["react-native-webgpu-dawn@157.0.0", "", {}, "sha512-HRquN2/995ZvcxiKDTiCwk3CduOYg9g3AK4yyoPrfMt5qUBbS6SefCpXE5mksvY4YaFrj2PqrtUuY2K1NkXsmQ=="], diff --git a/package.json b/package.json index 47ffa5eb..5f0ee397 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "specs": "bun --cwd packages/react-native-tgfx run specs", "typecheck": "bun --cwd packages/react-native-tgfx run typecheck", "example": "bun --cwd apps/example", + "lint-cpp": "bash scripts/clang-format.sh", "release": "bash scripts/release.sh", "bootstrap": "bash scripts/tgfx-prebuilt.sh" }, @@ -23,7 +24,7 @@ "react-native-vision-camera@5.2.0": "patches/react-native-vision-camera@5.2.0.patch", "@react-native-harness/runtime@1.3.0": "patches/@react-native-harness%2Fruntime@1.3.0.patch" }, - "version": "0.0.2-alpha.12", + "version": "0.1.0", "release-it": { "npm": { "publish": false diff --git a/packages/react-native-tgfx-vision-camera/package.json b/packages/react-native-tgfx-vision-camera/package.json index 7c95c354..0dced2ca 100644 --- a/packages/react-native-tgfx-vision-camera/package.json +++ b/packages/react-native-tgfx-vision-camera/package.json @@ -1,6 +1,6 @@ { "name": "react-native-tgfx-vision-camera", - "version": "0.0.1-alpha.4", + "version": "0.1.0", "description": "A native VisionCamera frame-processor plugin that hands camera frames to react-native-tgfx without JS on the per-frame path.", "main": "lib/index", "module": "lib/index", diff --git a/packages/react-native-tgfx/android/src/main/cpp/TgfxAndroid.cpp b/packages/react-native-tgfx/android/src/main/cpp/TgfxAndroid.cpp index 8c8a3b7b..3effef5d 100644 --- a/packages/react-native-tgfx/android/src/main/cpp/TgfxAndroid.cpp +++ b/packages/react-native-tgfx/android/src/main/cpp/TgfxAndroid.cpp @@ -360,7 +360,7 @@ Java_com_margelo_nitro_tgfx_TgfxNative_hitTest(JNIEnv* env, jobject, jlong ptr, JNIEXPORT jboolean JNICALL Java_com_margelo_nitro_tgfx_TgfxNative_setViewport(JNIEnv*, jobject, jlong ptr, - jfloat zoom, jfloat x, jfloat y) { + jfloat zoom, jfloat x, jfloat y) { auto* view = asView(ptr); if (view == nullptr) { return JNI_FALSE; @@ -370,7 +370,7 @@ Java_com_margelo_nitro_tgfx_TgfxNative_setViewport(JNIEnv*, jobject, jlong ptr, JNIEXPORT void JNICALL Java_com_margelo_nitro_tgfx_TgfxNative_setColorSpace(JNIEnv*, jobject, jlong ptr, - jboolean displayP3) { + jboolean displayP3) { auto* view = asView(ptr); if (view != nullptr) { view->renderer.setColorSpace(displayP3 == JNI_TRUE); @@ -401,8 +401,9 @@ Java_com_margelo_nitro_tgfx_TgfxNative_setWakeTarget(JNIEnv* env, jobject, jlong if (view->requestRender == nullptr) { // A pending NoSuchMethodError would abort the next JNI call instead. env->ExceptionClear(); - TGFXRN_LOGW("TgfxRenderTarget.requestRender() not found; a swapped hardware " - "buffer will not schedule a draw"); + TGFXRN_LOGW( + "TgfxRenderTarget.requestRender() not found; a swapped hardware " + "buffer will not schedule a draw"); return; } view->renderer.setWakeCallback([view] { diff --git a/packages/react-native-tgfx/android/src/main/cpp/TgfxVideoStream.cpp b/packages/react-native-tgfx/android/src/main/cpp/TgfxVideoStream.cpp index 42fb42a5..ec410642 100644 --- a/packages/react-native-tgfx/android/src/main/cpp/TgfxVideoStream.cpp +++ b/packages/react-native-tgfx/android/src/main/cpp/TgfxVideoStream.cpp @@ -500,7 +500,7 @@ JNIEXPORT void JNICALL Java_com_margelo_nitro_tgfx_TgfxNative_videoStreamNotify( } JNIEXPORT jint JNICALL Java_com_margelo_nitro_tgfx_TgfxNative_videoStreamUpdate(JNIEnv*, jobject, - jlong ptr) { + jlong ptr) { auto stream = asStream(ptr); if (stream == nullptr) { return 0; @@ -529,7 +529,7 @@ JNIEXPORT jint JNICALL Java_com_margelo_nitro_tgfx_TgfxNative_videoStreamUpdate( * deep inside tgfx. Nothing is drawn until videoStreamRebuild() lands. */ JNIEXPORT void JNICALL Java_com_margelo_nitro_tgfx_TgfxNative_videoStreamRelease(JNIEnv*, jobject, - jlong ptr) { + jlong ptr) { auto stream = asStream(ptr); if (stream == nullptr) { return; @@ -566,7 +566,7 @@ JNIEXPORT jobject JNICALL Java_com_margelo_nitro_tgfx_TgfxNative_videoStreamRebu } JNIEXPORT void JNICALL Java_com_margelo_nitro_tgfx_TgfxNative_videoStreamDestroy(JNIEnv*, jobject, - jlong ptr) { + jlong ptr) { auto* holder = asHolder(ptr); if (holder == nullptr) { return; diff --git a/packages/react-native-tgfx/cpp/Core/Log.hpp b/packages/react-native-tgfx/cpp/Core/Log.hpp index 884c4a76..c4658fa3 100644 --- a/packages/react-native-tgfx/cpp/Core/Log.hpp +++ b/packages/react-native-tgfx/cpp/Core/Log.hpp @@ -8,11 +8,11 @@ __android_log_print(ANDROID_LOG_INFO, "react-native-tgfx", __VA_ARGS__) #else #include -#define TGFXRN_LOGW(...) \ - do { \ +#define TGFXRN_LOGW(...) \ + do { \ std::fprintf(stderr, "[react-native-tgfx] "); \ - std::fprintf(stderr, __VA_ARGS__); \ - std::fprintf(stderr, "\n"); \ + std::fprintf(stderr, __VA_ARGS__); \ + std::fprintf(stderr, "\n"); \ } while (0) #define TGFXRN_LOGI(...) TGFXRN_LOGW(__VA_ARGS__) #endif diff --git a/packages/react-native-tgfx/cpp/Image/HybridTgfxImageFactory.cpp b/packages/react-native-tgfx/cpp/Image/HybridTgfxImageFactory.cpp index d77d34e8..7bd2b28a 100644 --- a/packages/react-native-tgfx/cpp/Image/HybridTgfxImageFactory.cpp +++ b/packages/react-native-tgfx/cpp/Image/HybridTgfxImageFactory.cpp @@ -493,7 +493,7 @@ tgfxrn::SnapshotRequest encodeRequest(const std::optional& format, } std::shared_ptr<::tgfx::Data> encodeRegisteredImage(int32_t handle, - const tgfxrn::SnapshotRequest& request) { + const tgfxrn::SnapshotRequest& request) { auto raster = tgfxrn::rasterizeRegisteredImage(handle); std::shared_ptr<::tgfx::Data> out; std::string error; diff --git a/packages/react-native-tgfx/cpp/Image/ImageRegistry.cpp b/packages/react-native-tgfx/cpp/Image/ImageRegistry.cpp index d7f5d20f..17b907a9 100644 --- a/packages/react-native-tgfx/cpp/Image/ImageRegistry.cpp +++ b/packages/react-native-tgfx/cpp/Image/ImageRegistry.cpp @@ -70,7 +70,7 @@ ImageHandle ImageRegistry::add(std::shared_ptr codec) { } ImageHandle ImageRegistry::addExternal(std::shared_ptr image, size_t ownedBytes, - bool live) { + bool live) { if (image == nullptr) { return {}; } @@ -169,7 +169,7 @@ std::shared_ptr ImageRegistry::acquire(int32_t handle, bool* extern return entry.decoded; } if (entry.decoded == nullptr) { - // Only after the budget dropped these pixels. The caller is the render thread, so the worker re-decodes. + // Only after the budget dropped these pixels. The caller is the render thread, so the worker re-decodes. scheduleDecodeLocked(handle); return nullptr; } diff --git a/packages/react-native-tgfx/cpp/Offscreen/OffscreenRender.hpp b/packages/react-native-tgfx/cpp/Offscreen/OffscreenRender.hpp index deb37059..901096f2 100644 --- a/packages/react-native-tgfx/cpp/Offscreen/OffscreenRender.hpp +++ b/packages/react-native-tgfx/cpp/Offscreen/OffscreenRender.hpp @@ -15,10 +15,32 @@ class Context; class Data; class Device; class Image; -} +} // namespace tgfx namespace tgfxrn { +/** + * Drains what Metal autoreleases inside its scope: offscreen GPU work runs on + * long-lived C++ threads (the surface worker, Nitro's promise pool) that never + * drain a pool of their own. A no-op off Apple. + */ +class AutoreleasePool { + public: +#if defined(__APPLE__) + AutoreleasePool(); + ~AutoreleasePool(); +#else + AutoreleasePool() = default; +#endif + AutoreleasePool(const AutoreleasePool&) = delete; + AutoreleasePool& operator=(const AutoreleasePool&) = delete; + + private: +#if defined(__APPLE__) + void* pool_; +#endif +}; + /** * Holds the shared windowless GPU context for as long as it lives, replacing a * device that lost its context for good. Throws if there is no usable GPU. @@ -35,6 +57,7 @@ class OffscreenContext { } private: + AutoreleasePool pool_; std::shared_ptr device_; tgfx::Context* context_ = nullptr; }; diff --git a/packages/react-native-tgfx/cpp/Offscreen/OffscreenSurface.cpp b/packages/react-native-tgfx/cpp/Offscreen/OffscreenSurface.cpp index 31492f5b..38bbf1bd 100644 --- a/packages/react-native-tgfx/cpp/Offscreen/OffscreenSurface.cpp +++ b/packages/react-native-tgfx/cpp/Offscreen/OffscreenSurface.cpp @@ -458,5 +458,4 @@ void OffscreenSurface::renderNow() { } } - } // namespace tgfxrn diff --git a/packages/react-native-tgfx/cpp/Path/PathOps.cpp b/packages/react-native-tgfx/cpp/Path/PathOps.cpp index 24b8ad04..2d5edcd9 100644 --- a/packages/react-native-tgfx/cpp/Path/PathOps.cpp +++ b/packages/react-native-tgfx/cpp/Path/PathOps.cpp @@ -143,10 +143,22 @@ void appendReversed(tgfx::Path& out, const std::vector& seg for (const auto& segment : segments) { switch (segment.verb) { case tgfx::PathVerb::Move: ends.push_back(segment.points[0]); break; - case tgfx::PathVerb::Line: ends.push_back(segment.points[1]); curves.push_back(segment); break; - case tgfx::PathVerb::Quad: ends.push_back(segment.points[2]); curves.push_back(segment); break; - case tgfx::PathVerb::Conic: ends.push_back(segment.points[2]); curves.push_back(segment); break; - case tgfx::PathVerb::Cubic: ends.push_back(segment.points[3]); curves.push_back(segment); break; + case tgfx::PathVerb::Line: + ends.push_back(segment.points[1]); + curves.push_back(segment); + break; + case tgfx::PathVerb::Quad: + ends.push_back(segment.points[2]); + curves.push_back(segment); + break; + case tgfx::PathVerb::Conic: + ends.push_back(segment.points[2]); + curves.push_back(segment); + break; + case tgfx::PathVerb::Cubic: + ends.push_back(segment.points[3]); + curves.push_back(segment); + break; default: break; } } diff --git a/packages/react-native-tgfx/cpp/Path/SvgPath.cpp b/packages/react-native-tgfx/cpp/Path/SvgPath.cpp index 79db44e9..e4f05ff1 100644 --- a/packages/react-native-tgfx/cpp/Path/SvgPath.cpp +++ b/packages/react-native-tgfx/cpp/Path/SvgPath.cpp @@ -133,9 +133,12 @@ tgfx::Path parseSvgPath(const std::string& data) { float x2 = cur.number(), y2 = cur.number(); float x = cur.number(), y = cur.number(); if (relative) { - x1 += curX; y1 += curY; - x2 += curX; y2 += curY; - x += curX; y += curY; + x1 += curX; + y1 += curY; + x2 += curX; + y2 += curY; + x += curX; + y += curY; } path.cubicTo(x1, y1, x2, y2, x, y); ctrlX = x2; @@ -148,8 +151,10 @@ tgfx::Path parseSvgPath(const std::string& data) { float x2 = cur.number(), y2 = cur.number(); float x = cur.number(), y = cur.number(); if (relative) { - x2 += curX; y2 += curY; - x += curX; y += curY; + x2 += curX; + y2 += curY; + x += curX; + y += curY; } float x1 = curX, y1 = curY; char up = static_cast(std::toupper(static_cast(prevCmd))); @@ -168,8 +173,10 @@ tgfx::Path parseSvgPath(const std::string& data) { float x1 = cur.number(), y1 = cur.number(); float x = cur.number(), y = cur.number(); if (relative) { - x1 += curX; y1 += curY; - x += curX; y += curY; + x1 += curX; + y1 += curY; + x += curX; + y += curY; } path.quadTo(x1, y1, x, y); ctrlX = x1; @@ -181,7 +188,8 @@ tgfx::Path parseSvgPath(const std::string& data) { case 'T': { float x = cur.number(), y = cur.number(); if (relative) { - x += curX; y += curY; + x += curX; + y += curY; } float x1 = curX, y1 = curY; char up = static_cast(std::toupper(static_cast(prevCmd))); @@ -205,7 +213,8 @@ tgfx::Path parseSvgPath(const std::string& data) { break; } if (relative) { - x += curX; y += curY; + x += curX; + y += curY; } if (path.isEmpty()) { path.moveTo(curX, curY); diff --git a/packages/react-native-tgfx/cpp/Render/IdleGate.hpp b/packages/react-native-tgfx/cpp/Render/IdleGate.hpp index 445119bd..5137c6e6 100644 --- a/packages/react-native-tgfx/cpp/Render/IdleGate.hpp +++ b/packages/react-native-tgfx/cpp/Render/IdleGate.hpp @@ -8,7 +8,9 @@ namespace tgfxrn { // Per-tick decision for a display link that pauses itself once nothing animates. class IdleGate { public: - enum class Tick { Draw, Skip, Pause }; + enum class Tick { Draw, + Skip, + Pause }; void wake() { wakeGeneration_.fetch_add(1, std::memory_order_release); diff --git a/packages/react-native-tgfx/cpp/Scene/TgfxScene.cpp b/packages/react-native-tgfx/cpp/Scene/TgfxScene.cpp index 614e95fe..b97217cd 100644 --- a/packages/react-native-tgfx/cpp/Scene/TgfxScene.cpp +++ b/packages/react-native-tgfx/cpp/Scene/TgfxScene.cpp @@ -152,8 +152,24 @@ std::atomic gFilterBuilds{0}; /// Node kinds, mirrored from src/compiler/writer.ts. enum Kind { - KGroup = 0, KRect, KRRect, KOval, KCircle, KLine, KPath, KImage, KText, KFill, - KTextPath, KCameraFrame, KGlyphs, KGroupLayer, KMask, KAtlas, KVertices, KBackdrop + KGroup = 0, + KRect, + KRRect, + KOval, + KCircle, + KLine, + KPath, + KImage, + KText, + KFill, + KTextPath, + KCameraFrame, + KGlyphs, + KGroupLayer, + KMask, + KAtlas, + KVertices, + KBackdrop }; /// Sampling codes, mirrored from src/compiler/writer.ts. @@ -243,13 +259,15 @@ FitRects fitRects(Fit fit, const tgfx::Rect& source, const tgfx::Rect& dest) { sh = dh = std::min(ih, oh); break; case Fit::ScaleDown: - if (dh > ih) { - dw = ih * (iw / ih); - dh = ih; + dw = iw; + dh = ih; + if (dh > oh) { + dw = oh * (iw / ih); + dh = oh; } - if (dw > iw) { - dh = iw / (iw / ih); - dw = iw; + if (dw > ow) { + dh = ow / (iw / ih); + dw = ow; } break; } @@ -744,8 +762,8 @@ const TextLayout& TextCmd::resolve(float size, } layoutSize = size; layout = !glyphs.empty() ? layoutGlyphs(glyphs, spec, size) - : onPath ? layoutTextOnPath(runs, spec, size, path) - : layoutText(runs, spec, size); + : onPath ? layoutTextOnPath(runs, spec, size, path) + : layoutText(runs, spec, size); return layout; } @@ -1545,8 +1563,9 @@ bool SceneRenderer::readNodeFields(SceneReader& r, DrawCmd& cmd, int depth) { cmd.children.push_back(std::move(child)); } if (cmd.cachePicture && r.dynamic != dynamicBefore) { - TGFXRN_LOGW(" holds something that resolves per frame, so it is drawn " - "directly; a recording would freeze it"); + TGFXRN_LOGW( + " holds something that resolves per frame, so it is drawn " + "directly; a recording would freeze it"); cmd.cachePicture = false; } if (r.ok) { @@ -1577,8 +1596,9 @@ bool SceneRenderer::readNodeFields(SceneReader& r, DrawCmd& cmd, int depth) { cmd.children.push_back(std::move(child)); } if (cmd.cachePicture && r.dynamic != dynamicBefore) { - TGFXRN_LOGW(" holds something that resolves per frame, so it is drawn " - "directly; a recording would freeze it"); + TGFXRN_LOGW( + " holds something that resolves per frame, so it is drawn " + "directly; a recording would freeze it"); cmd.cachePicture = false; } return r.ok; @@ -1608,8 +1628,9 @@ bool SceneRenderer::readNodeFields(SceneReader& r, DrawCmd& cmd, int depth) { cmd.children.push_back(std::move(child)); } if (cmd.cachePicture && r.dynamic != dynamicBefore) { - TGFXRN_LOGW(" holds something that resolves per frame, so it is drawn " - "directly; a recording would freeze it"); + TGFXRN_LOGW( + " holds something that resolves per frame, so it is drawn " + "directly; a recording would freeze it"); cmd.cachePicture = false; } return r.ok; @@ -2049,7 +2070,6 @@ void SceneRenderer::setScene(std::span words, usesBackdrop_ = backdrop; } - namespace { /** @@ -3097,8 +3117,7 @@ void SceneRenderer::addLayerContent(tgfx::Layer* layer, const DrawCmd& owner, si bool fills = false; if (body != nullptr) { still = body->layerAlpha.slot < 0 && body->grain == nullptr && - std::none_of(body->children.begin(), body->children.end(), - [](const DrawCmd& child) { return child.dynamic; }); + std::none_of(body->children.begin(), body->children.end(), [](const DrawCmd& child) { return child.dynamic; }); fills = body->fills; } else { for (const auto* cmd : run) { diff --git a/packages/react-native-tgfx/cpp/Scene/TgfxScene.hpp b/packages/react-native-tgfx/cpp/Scene/TgfxScene.hpp index 6dc13440..c749af99 100644 --- a/packages/react-native-tgfx/cpp/Scene/TgfxScene.hpp +++ b/packages/react-native-tgfx/cpp/Scene/TgfxScene.hpp @@ -40,7 +40,13 @@ namespace tgfxrn { inline constexpr double kSceneVersion = 31; /// How an image is scaled into its destination rect; see fitRects() in TgfxScene.cpp. -enum class Fit { Fill = 0, Contain, Cover, FitWidth, FitHeight, None, ScaleDown }; +enum class Fit { Fill = 0, + Contain, + Cover, + FitWidth, + FitHeight, + None, + ScaleDown }; struct SceneReader; @@ -342,8 +348,21 @@ struct LayerContent { struct DrawCmd { enum Kind { - Group, Rect, RRect, Oval, Circle, Line, Path, Image, Text, Fill, CameraFrame, Mask, Atlas, - Vertices, Backdrop + Group, + Rect, + RRect, + Oval, + Circle, + Line, + Path, + Image, + Text, + Fill, + CameraFrame, + Mask, + Atlas, + Vertices, + Backdrop }; /// Backdrop only: the panel's shape and the style's parameters. @@ -360,7 +379,6 @@ struct DrawCmd { AnimF lightAngle; AnimF lightIntensity; - /// Mask only: the subtree whose alpha or luminance cuts `children` down. std::vector maskChildren; bool maskLuminance = false; diff --git a/packages/react-native-tgfx/cpp/TextLayout/FontRegistry.cpp b/packages/react-native-tgfx/cpp/TextLayout/FontRegistry.cpp index 24744d63..b3c399f8 100644 --- a/packages/react-native-tgfx/cpp/TextLayout/FontRegistry.cpp +++ b/packages/react-native-tgfx/cpp/TextLayout/FontRegistry.cpp @@ -51,8 +51,12 @@ uint16_t beU16(const uint8_t* bytes) { /// Where a font file can live. Android first, then the desktop hosts. No file names by design. constexpr std::array kFontDirs = { - "/system/fonts", "/product/fonts", "/system/font", - "/data/fonts", "/System/Library/Fonts", "/Library/Fonts", + "/system/fonts", + "/product/fonts", + "/system/font", + "/data/fonts", + "/System/Library/Fonts", + "/Library/Fonts", }; bool isFontFile(const std::string& name) { diff --git a/packages/react-native-tgfx/cpp/TextLayout/TextLayout.cpp b/packages/react-native-tgfx/cpp/TextLayout/TextLayout.cpp index 7dc8fa39..a0f7f66f 100644 --- a/packages/react-native-tgfx/cpp/TextLayout/TextLayout.cpp +++ b/packages/react-native-tgfx/cpp/TextLayout/TextLayout.cpp @@ -436,7 +436,7 @@ Placement place(const std::vector& runs, const TextSpec& spec, if (i > 0) { baseline += step; } - float x = spec.align == TextAlign::Center ? (box - line.width) / 2 + float x = spec.align == TextAlign::Center ? (box - line.width) / 2 : spec.align == TextAlign::Right ? box - line.width : 0; LineMetrics metrics; diff --git a/packages/react-native-tgfx/cpp/TextLayout/TextLayout.hpp b/packages/react-native-tgfx/cpp/TextLayout/TextLayout.hpp index a952f2c5..b377b0a7 100644 --- a/packages/react-native-tgfx/cpp/TextLayout/TextLayout.hpp +++ b/packages/react-native-tgfx/cpp/TextLayout/TextLayout.hpp @@ -15,7 +15,9 @@ class TextBlob; namespace tgfxrn { -enum class TextAlign { Left = 0, Center = 1, Right = 2 }; +enum class TextAlign { Left = 0, + Center = 1, + Right = 2 }; struct TextRun { std::string text; diff --git a/packages/react-native-tgfx/cpp/TextLayout/TextShaping.cpp b/packages/react-native-tgfx/cpp/TextLayout/TextShaping.cpp index bdf5be37..46d0e3a2 100644 --- a/packages/react-native-tgfx/cpp/TextLayout/TextShaping.cpp +++ b/packages/react-native-tgfx/cpp/TextLayout/TextShaping.cpp @@ -17,7 +17,20 @@ namespace { /// The bidi classes the resolver needs. UAX#9 has more; the ones left out are /// the explicit embedding, override and isolate controls, which are treated as /// BN — see the note on shapeText(). -enum class Bidi : uint8_t { L, R, AL, EN, AN, ES, ET, CS, NSM, BN, B, S, WS, ON }; +enum class Bidi : uint8_t { L, + R, + AL, + EN, + AN, + ES, + ET, + CS, + NSM, + BN, + B, + S, + WS, + ON }; bool isStrong(Bidi c) { return c == Bidi::L || c == Bidi::R || c == Bidi::AL; @@ -324,7 +337,7 @@ void resolveLevels(std::vector& chars, uint8_t paragraphLevel) { // and numbers two; inside a right-to-left run everything else goes up one. for (auto& c : chars) { if (paragraphLevel == 0) { - c.level = c.resolved == Bidi::R ? 1 + c.level = c.resolved == Bidi::R ? 1 : (c.resolved == Bidi::EN || c.resolved == Bidi::AN) ? 2 : 0; } else { @@ -346,7 +359,6 @@ void resolveLevels(std::vector& chars, uint8_t paragraphLevel) { // --- HarfBuzz faces ------------------------------------------------------ - hb_blob_t* tableOf(hb_face_t*, hb_tag_t tag, void* user) { // The user data is the shared_ptr the face holds, not the typeface itself: // the face reads tables lazily and has to keep it alive to do so. @@ -438,9 +450,10 @@ void warnMissingGlyph(int32_t code) { void checkVersionOnce() { static const bool once = [] { if (std::string(hb_version_string()) != HB_VERSION_STRING) { - TGFXRN_LOGW("HarfBuzz headers say %s but the linked library is %s. Refresh " - "cpp/third_party/harfbuzz — see its README.", - HB_VERSION_STRING, hb_version_string()); + TGFXRN_LOGW( + "HarfBuzz headers say %s but the linked library is %s. Refresh " + "cpp/third_party/harfbuzz — see its README.", + HB_VERSION_STRING, hb_version_string()); } return true; }(); diff --git a/packages/react-native-tgfx/cpp/tests/AllocBench.cpp b/packages/react-native-tgfx/cpp/tests/AllocBench.cpp index 8ab177c3..cc8d142b 100644 --- a/packages/react-native-tgfx/cpp/tests/AllocBench.cpp +++ b/packages/react-native-tgfx/cpp/tests/AllocBench.cpp @@ -41,11 +41,16 @@ void* operator new(size_t size) { gAllocs.fetch_add(1, std::memory_order_relaxed); } void* p = std::malloc(size ? size : 1); - if (p == nullptr) throw std::bad_alloc(); + if (p == nullptr) + throw std::bad_alloc(); return p; } -void operator delete(void* p) noexcept { std::free(p); } -void operator delete(void* p, size_t) noexcept { std::free(p); } +void operator delete(void* p) noexcept { + std::free(p); +} +void operator delete(void* p, size_t) noexcept { + std::free(p); +} namespace { @@ -67,7 +72,8 @@ struct Writer { std::vector finish() { auto patchStart = words.size(); words.push_back(static_cast(patches.size() / 2)); - for (double p : patches) words.push_back(p); + for (double p : patches) + words.push_back(p); words.push_back(0); // empty string-patch table words[0] = tgfxrn::kSceneVersion; words[1] = static_cast(words.size()); @@ -95,8 +101,9 @@ std::vector scene(bool filters) { w.push(24); // multiply w.push(0); // colour matrix const double m[20] = {0.2, 0.7, 0.1, 0, 0, 0.2, 0.7, 0.1, 0, 0, - 0.2, 0.7, 0.1, 0, 0, 0, 0, 0, 1, 0}; - for (double v : m) w.push(v); + 0.2, 0.7, 0.1, 0, 0, 0, 0, 0, 1, 0}; + for (double v : m) + w.push(v); w.push(-1); // no image filter } w.push(-1); // no shader @@ -179,11 +186,11 @@ std::vector childShaderScene(int32_t childHandle, bool animatedUniform, continue; } w.push(6); // runtime shader - w.push(0); // body - w.push(1); // empty preamble - w.push(0); // no functions - w.push(1); // one uniform - w.push(2); // "uLevel" + w.push(0); // body + w.push(1); // empty preamble + w.push(0); // no functions + w.push(1); // one uniform + w.push(2); // "uLevel" w.push(1); w.pushAnim(0.5, animatedUniform ? 0 : -1); if (childHandle == 0) { @@ -307,24 +314,24 @@ std::vector textScene() { w.pushAnim(2); w.pushAnim(12 + (i % 4) * 12); w.pushAnim(kBaseSize, 0); - w.push(1); // "Helvetica" + w.push(1); // "Helvetica" w.push(400); - w.push(0); // style bits - w.push(0); // letterSpacing - w.push(1); // one run - w.push(0); // "Benchmark" - w.push(2); // run family ("") - w.push(0); // run weight (inherit) - w.push(0); // run italic (inherit) - w.push(0); // run letterSpacing - w.push(0); // run size (inherit) - w.push(0); // run hasColor - w.push(0); // run color - w.push(0); // no wrap - w.push(0); // align left - w.push(0); // natural line height - w.push(0); // no maxLines - w.push(2); // empty ellipsis + w.push(0); // style bits + w.push(0); // letterSpacing + w.push(1); // one run + w.push(0); // "Benchmark" + w.push(2); // run family ("") + w.push(0); // run weight (inherit) + w.push(0); // run italic (inherit) + w.push(0); // run letterSpacing + w.push(0); // run size (inherit) + w.push(0); // run hasColor + w.push(0); // run color + w.push(0); // no wrap + w.push(0); // align left + w.push(0); // natural line height + w.push(0); // no maxLines + w.push(2); // empty ellipsis w.push(0xff000000); w.push(2); w.pushAnim(1); @@ -517,8 +524,7 @@ bool reportCamera() { std::printf(" opaque pixels drawn %zu\n", drawn); std::printf(" decodes on the frame path %zu\n", decodes); std::printf(" GPU bytes before / after %zu / %zu (delta %+lld)\n", memoryBefore, - memoryAfter, static_cast(memoryAfter) - - static_cast(memoryBefore)); + memoryAfter, static_cast(memoryAfter) - static_cast(memoryBefore)); std::printf(" allocations per render() mean %zu, worst %zu (%d nodes)\n", total / kCameraFrames, worst, kOverlays + 1); std::printf("\n"); @@ -683,8 +689,9 @@ bool reportHardwareFrame() { return false; } if (lightFullRange == light) { - std::printf("FAIL: full-range and limited-range imports of the same luma read " - "identically — the format argument is not reaching the import\n"); + std::printf( + "FAIL: full-range and limited-range imports of the same luma read " + "identically — the format argument is not reaching the import\n"); return false; } if (decodes != 0) { @@ -692,9 +699,10 @@ bool reportHardwareFrame() { return false; } if (memoryAfter > memoryBefore) { - std::printf("FAIL: GPU memory grew by %zu bytes over %d frames — a per-frame " - "texture, i.e. a YUV->RGB pre-pass or a re-upload\n", - memoryAfter - memoryBefore, kHardwareFrames); + std::printf( + "FAIL: GPU memory grew by %zu bytes over %d frames — a per-frame " + "texture, i.e. a YUV->RGB pre-pass or a re-upload\n", + memoryAfter - memoryBefore, kHardwareFrames); return false; } return true; diff --git a/packages/react-native-tgfx/cpp/tests/CMakeLists.txt b/packages/react-native-tgfx/cpp/tests/CMakeLists.txt index 2d9090a6..252ef15a 100644 --- a/packages/react-native-tgfx/cpp/tests/CMakeLists.txt +++ b/packages/react-native-tgfx/cpp/tests/CMakeLists.txt @@ -14,6 +14,12 @@ add_subdirectory(${TGFX_DIR} ${CMAKE_BINARY_DIR}/tgfx) add_executable(SceneTest SceneTest.cpp ../Scene/TgfxScene.cpp ../Path/SvgPath.cpp ../Image/SvgImage.cpp ../Image/ImageRegistry.cpp ../Offscreen/OffscreenRender.cpp ../Offscreen/OffscreenSurface.cpp ../Export/PdfExport.cpp ../Export/SvgExport.cpp ../TextLayout/FontRegistry.cpp ../TextLayout/TextLayout.cpp ../TextLayout/TextShaping.cpp ../Path/PathOps.cpp ../Buffers/BufferRegistry.cpp) +if(APPLE) + enable_language(OBJCXX) + set_property(TARGET SceneTest PROPERTY OBJCXX_STANDARD 20) + target_sources(SceneTest PRIVATE ../../ios/TgfxAutoreleasePool.mm) + target_link_libraries(SceneTest "-framework Foundation") +endif() # tgfx's src too: the EXIF test names JpegCodec rather than going through # ImageCodec::MakeFrom, which would fall through to the platform decoder and # prove nothing about the embedded one. diff --git a/packages/react-native-tgfx/cpp/tests/SceneTest.cpp b/packages/react-native-tgfx/cpp/tests/SceneTest.cpp index 8f8a8b8c..b1be5d3b 100644 --- a/packages/react-native-tgfx/cpp/tests/SceneTest.cpp +++ b/packages/react-native-tgfx/cpp/tests/SceneTest.cpp @@ -49,12 +49,12 @@ namespace { int failures = 0; -#define CHECK(cond) \ - do { \ - if (!(cond)) { \ - std::printf(" FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ - failures++; \ - } \ +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::printf(" FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ } while (0) tgfxrn::TextRun run(std::string text) { @@ -686,7 +686,7 @@ void writeTextNode(Writer& w, double fontSize, int fontSizeSlot, int textIndex = w.push(1); // font family string index w.push(weight); w.push(style); // 1 italic, 2 faux bold, 4 faux italic - w.push(0); // letterSpacing + w.push(0); // letterSpacing writeRun(w, textIndex, 2, 0, runItalic); w.push(wrapWidth); w.push(align); @@ -846,9 +846,9 @@ void aChildShaderSamplesWhereItIsAsked() { // repeat/repeat, nearest: the same child both paths draw. const std::vector child = {7, static_cast(image.handle), 1, 1, 0, 0}; const std::vector strings = { - "return TGFX_CHILD_0(fragCoord);", // 0 - "", // 1: no preamble - "return TGFX_CHILD_0(fragCoord + vec2(1.0, 0.0));", // 2: shifted a texel + "return TGFX_CHILD_0(fragCoord);", // 0 + "", // 1: no preamble + "return TGFX_CHILD_0(fragCoord + vec2(1.0, 0.0));", // 2: shifted a texel }; auto draw = [&](int body) { @@ -1057,8 +1057,8 @@ void aGroupClipConfinesItsSubtree() { }; auto clipped = scene(1, false); - CHECK(opaqueAt(clipped, 16, 16)); // inside the clip - CHECK(!opaqueAt(clipped, 2, 2)); // outside it + CHECK(opaqueAt(clipped, 16, 16)); // inside the clip + CHECK(!opaqueAt(clipped, 2, 2)); // outside it CHECK(!opaqueAt(clipped, 40, 40)); auto inverted = scene(1, true); @@ -1085,7 +1085,7 @@ void aLayerCompositesTheSubtreeOnce() { w.push(layer ? 13 : 0); w.push(0); if (layer) { - w.push(4); // layer, no clip + w.push(4); // layer, no clip w.pushAnim(0.5); } w.push(2); @@ -1188,9 +1188,9 @@ void pathEffectsReshapeTheGeometry() { return render(w.finish(), {"M4 4 L60 4 L60 60 L4 60 Z M20 20 L44 20 L44 44 L20 44 Z"}, {}); }; - CHECK(!opaqueAt(donut(8, {}), 32, 32)); // the hole is open - CHECK(opaqueAt(donut(0, {}), 32, 32)); // winding fills it - CHECK(!opaqueAt(donut(8 | 4, {6}), 32, 32)); // still open through a corner effect + CHECK(!opaqueAt(donut(8, {}), 32, 32)); // the hole is open + CHECK(opaqueAt(donut(0, {}), 32, 32)); // winding fills it + CHECK(!opaqueAt(donut(8 | 4, {6}), 32, 32)); // still open through a corner effect CHECK(!opaqueAt(donut(8 | 2, {2, 6, 6, 0}), 32, 32)); // and through a dash // An animated trim re-applies per frame: the same program, two different values. @@ -1239,8 +1239,8 @@ void pathEffectsReshapeTheGeometry() { auto atZero = drawFrame(marching, {0.0}); auto atFour = drawFrame(marching, {4.0}); CHECK(anyPixelSet(atZero)); - CHECK(atZero != atFour); // the phase still moves - CHECK(!opaqueAt(atZero, 55, 32)); // and the baked trim still bites + CHECK(atZero != atFour); // the phase still moves + CHECK(!opaqueAt(atZero, 55, 32)); // and the baked trim still bites } /// Luma and the inner shadow: the filter kinds #179 was missing. @@ -1299,8 +1299,8 @@ void aThresholdCutsAlphaAndAColorFilterCanFollowAnImageFilter() { // A half-transparent fill: below the threshold it disappears, above it goes solid. const uint32_t half = 0x80336699; auto plain = shape({-1}, {-1}, half); - auto cut = shape({3, 0.9}, {-1}, half); // 0.5 alpha < 0.9 => transparent - auto kept = shape({3, 0.25}, {-1}, half); // 0.5 alpha >= 0.25 => opaque + auto cut = shape({3, 0.9}, {-1}, half); // 0.5 alpha < 0.9 => transparent + auto kept = shape({3, 0.25}, {-1}, half); // 0.5 alpha >= 0.25 => opaque CHECK(!opaqueAt(cut, 32, 32)); CHECK(kept != plain); // The colour, not just "something is there". This filter shipped once before @@ -1324,11 +1324,11 @@ void aThresholdCutsAlphaAndAColorFilterCanFollowAnImageFilter() { live.push(0); live.push(0); live.pushAnim(1); - live.push(3); // blend srcOver - live.push(3); // colour filter kind: alphaThreshold + live.push(3); // blend srcOver + live.push(3); // colour filter kind: alphaThreshold live.pushAnim(0.9, 0); // threshold, slot 0 - live.push(-1); // no image filter - live.push(-1); // no shader + live.push(-1); // no image filter + live.push(-1); // no shader auto program = live.finish(); CHECK(!opaqueAt(render(program, {}, {0.9}), 32, 32)); CHECK(opaqueAt(render(program, {}, {0.25}), 32, 32)); @@ -1548,14 +1548,14 @@ void aMaskCutsItsContentDown() { w.push(1); w.push(14); // Mask w.push(luminance); - w.push(1); // one mask node: a rect over the left half + w.push(1); // one mask node: a rect over the left half w.push(1); w.pushAnim(0); w.pushAnim(0); w.pushAnim(32); w.pushAnim(64); w.pushPaint(maskColor, false); - w.push(1); // one content node: a rect over the whole canvas + w.push(1); // one content node: a rect over the whole canvas w.push(1); w.pushAnim(0); w.pushAnim(0); @@ -1566,8 +1566,8 @@ void aMaskCutsItsContentDown() { }; auto alpha = scene(0, 0xffffffff); - CHECK(opaqueAt(alpha, 16, 32)); // under the mask, the content survives - CHECK(!opaqueAt(alpha, 48, 32)); // outside it, nothing is left + CHECK(opaqueAt(alpha, 16, 32)); // under the mask, the content survives + CHECK(!opaqueAt(alpha, 48, 32)); // outside it, nothing is left // A transparent mask keeps nothing, whatever its colour. CHECK(!anyPixelSet(scene(0, 0x00ffffff))); @@ -1762,7 +1762,6 @@ void aLiveHandleRefusesToBeDerivedFrom() { CHECK(registry.sourceImage(frame.handle) == nullptr); } - void fitModesLetterboxAndCrop() { auto image = registerSolid(cellColor(7), 4, 2); auto draw = [&](int fit) { @@ -1773,14 +1772,14 @@ void fitModesLetterboxAndCrop() { }; auto contain = draw(1); - CHECK(opaqueAt(contain, 16, 16)); // the letterboxed band - CHECK(!opaqueAt(contain, 16, 2)); // above it, untouched + CHECK(opaqueAt(contain, 16, 16)); // the letterboxed band + CHECK(!opaqueAt(contain, 16, 2)); // above it, untouched CHECK(!opaqueAt(contain, 16, 30)); auto cover = draw(2); - CHECK(opaqueAt(cover, 16, 2)); // fills the box + CHECK(opaqueAt(cover, 16, 2)); // fills the box CHECK(opaqueAt(cover, 16, 30)); - CHECK(!opaqueAt(cover, 40, 16)); // but never past it + CHECK(!opaqueAt(cover, 40, 16)); // but never past it auto fill = draw(0); CHECK(opaqueAt(fill, 1, 1) && opaqueAt(fill, 30, 30)); @@ -2207,7 +2206,7 @@ void aBlendModeSurvivesAnImageFilter() { blur = {0, sigma, sigma, 3}; } w.pushFilteredPaint(0xffff00ff, {24, {-1}, blur}); // BlendMode::Multiply - w.push(1); // Rect: an ordinary green one, drawn after the layered node + w.push(1); // Rect: an ordinary green one, drawn after the layered node w.pushAnim(44); w.pushAnim(44); w.pushAnim(16); @@ -2376,7 +2375,6 @@ void filtersAreBuiltOnceAndNeverOnTheDrawPath() { CHECK(tgfxrn::filterBuildCount() == afterCompile); } - /// Composition made a chain rebuildable as a unit; only the parts with a slot /// should actually be rebuilt. Counted, not reasoned about. void onlyTheAnimatedPartOfAFilterChainIsRebuilt() { @@ -2402,10 +2400,10 @@ void onlyTheAnimatedPartOfAFilterChainIsRebuilt() { w.push(0); // blur w.pushAnim(4, 0); w.pushAnim(4, 0); - w.push(3); // decal - w.push(3); // colorFilter in the image chain - w.push(2); // luma - w.push(-1); // no shader + w.push(3); // decal + w.push(3); // colorFilter in the image chain + w.push(2); // luma + w.push(-1); // no shader auto words = w.finish(); tgfxrn::SceneRenderer renderer; @@ -3193,8 +3191,8 @@ std::shared_ptr exifRotatedJpeg(int width, int height) { // APP1: length, "Exif\0\0", then a little-endian TIFF whose one entry is Orientation = 6. const std::array app1 = { 0xFF, 0xE1, 0x00, 0x22, // marker, length (34) - 'E', 'x', 'i', 'f', 0x00, 0x00, // Exif\0\0 - 'I', 'I', 0x2A, 0x00, 0x08, 0x00, 0x00, 0x00, // II, 42, IFD0 at 8 + 'E', 'x', 'i', 'f', 0x00, 0x00, // Exif\0\0 + 'I', 'I', 0x2A, 0x00, 0x08, 0x00, 0x00, 0x00, // II, 42, IFD0 at 8 0x01, 0x00, // one entry 0x12, 0x01, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, // Orientation, SHORT, 1 0x06, 0x00, 0x00, 0x00, // = 6 @@ -4270,8 +4268,8 @@ void hitTestReportsWhatIsUnderThePoint() { // 23,3 sits in the circle's bounding box but outside the disc, and inside the rect. auto boxed = renderer.hitTest(23, 3, false, {}); auto exact = renderer.hitTest(23, 3, true, {}); - CHECK(boxed.size() == 5); // the circle, then the rect - CHECK(exact.size() == 2); // only the rect + CHECK(boxed.size() == 5); // the circle, then the rect + CHECK(exact.size() == 2); // only the rect CHECK(exact[0] == 1 && exact[1] == 0); } @@ -4418,7 +4416,7 @@ void aBackdropFrostsWhatIsBeneathIt() { w.pushAnim(8); w.pushAnim(48); w.pushAnim(48); - w.push(0); // corner radius + w.push(0); // corner radius w.pushAnim(10); // blur w.pushAnim(refraction); // 0 is a plain blur, above 0 is glass w.pushAnim(20); @@ -4531,9 +4529,9 @@ void filmGrainDustsOnlyWhatTheGroupDrew() { CHECK(render(program(0, 0, 4, 0), {}, {}) == plain); // Every remaining word has to reach NoiseStyle, or it is decoration. - CHECK(render(program(0, 0.5, 16, 0), {}, {}) != mono); // coarser grain - CHECK(render(program(0, 0.5, 4, 7), {}, {}) != mono); // a different pattern - CHECK(render(program(0, 0.9, 4, 0), {}, {}) != mono); // denser + CHECK(render(program(0, 0.5, 16, 0), {}, {}) != mono); // coarser grain + CHECK(render(program(0, 0.5, 4, 7), {}, {}) != mono); // a different pattern + CHECK(render(program(0, 0.9, 4, 0), {}, {}) != mono); // denser // Duo fills the complementary half too, and multi keeps the noise's own RGB. auto duo = render(program(1, 0.5, 4, 0), {}, {}); auto multi = render(program(2, 0.5, 4, 0), {}, {}); @@ -4601,8 +4599,8 @@ void filmGrainAnswersToItsBlendModeAndLiveColour() { w.pushAnim(0, 1); // green w.pushAnim(0, 2); // blue w.pushAnim(1, 3); // alpha - w.push(1); // one child - w.push(1); // Rect + w.push(1); // one child + w.push(1); // Rect w.pushAnim(8); w.pushAnim(8); w.pushAnim(40); @@ -4640,7 +4638,7 @@ void filmGrainResolvesFromValueSlots() { w.push(13); w.push(0); w.push(16); - w.push(0); // mono + w.push(0); // mono w.pushAnim(4); w.pushAnim(0, 0); // density w.pushAnim(0, 1); // seed @@ -4684,7 +4682,7 @@ void glassTakesItsLightFromTheScene() { w.pushAnim(8); w.pushAnim(48); w.pushAnim(48); - w.push(12); // corner radius, so there is a curved edge to refract along + w.push(12); // corner radius, so there is a curved edge to refract along w.pushAnim(10); // blur, ignored on the glass path w.pushAnim(60); // refraction: above 0 is glass w.pushAnim(30); // depth @@ -4747,15 +4745,15 @@ void theGlassMaterialResolvesFromValueSlots() { w.pushAnim(8); w.pushAnim(48); w.pushAnim(48); - w.push(12); // corner radius, static - w.pushAnim(10); // blur - w.pushAnim(60); // refraction - w.pushAnim(30); // depth - w.pushAnim(20); // frost - w.pushAnim(0); // dispersion - w.pushAnim(0); // splay - w.pushAnim(45, 0); // light angle, slot 0 - w.pushAnim(50, 1); // light intensity, slot 1 + w.push(12); // corner radius, static + w.pushAnim(10); // blur + w.pushAnim(60); // refraction + w.pushAnim(30); // depth + w.pushAnim(20); // frost + w.pushAnim(0); // dispersion + w.pushAnim(0); // splay + w.pushAnim(45, 0); // light angle, slot 0 + w.pushAnim(50, 1); // light intensity, slot 1 w.pushPaint(0xffffffff, false); auto program = w.finish(); @@ -4794,7 +4792,7 @@ void aBackdropOnACanvasTheSizeOfARealOne() { w.pushAnim(24); w.pushAnim(150); w.pushAnim(72); - w.push(18); // corner radius + w.push(18); // corner radius w.pushAnim(14); // blur w.pushAnim(0); // refraction: a plain frosted panel w.pushAnim(20); @@ -4891,7 +4889,7 @@ void aBackdropAtAPixelRatioLeavesTheRestOfTheSceneAlone() { w.pushAnim(8); w.pushAnim(16); w.pushAnim(16); - w.push(3); // corner radius + w.push(3); // corner radius w.pushAnim(6); // blur w.pushAnim(refraction); // 0 is a plain blur, above 0 is glass w.pushAnim(20); @@ -5055,20 +5053,20 @@ void liveTextReshapesOnAStringPush() { w.push(400); w.push(0); w.push(0); - w.push(1); // one run - w.pushStringAnim(0, 0); // run text follows string slot 0 - w.push(2); // run family ("") - w.push(0); // run weight - w.push(0); // run italic - w.push(0); // run letterSpacing - w.push(0); // run size - w.push(0); // run hasColor - w.push(0); // run color - w.push(0); // wrapWidth - w.push(0); // align - w.push(0); // lineHeight - w.push(0); // maxLines - w.push(2); // ellipsis ("") + w.push(1); // one run + w.pushStringAnim(0, 0); // run text follows string slot 0 + w.push(2); // run family ("") + w.push(0); // run weight + w.push(0); // run italic + w.push(0); // run letterSpacing + w.push(0); // run size + w.push(0); // run hasColor + w.push(0); // run color + w.push(0); // wrapWidth + w.push(0); // align + w.push(0); // lineHeight + w.push(0); // maxLines + w.push(2); // ellipsis ("") w.pushPaint(0xff000000, false); tgfxrn::SceneRenderer renderer; renderer.setScene(w.finish(), strings); @@ -5208,13 +5206,13 @@ void animatedBlurRadiusChangesThePixels() { w.pushAnim(0); w.pushAnim(0); w.pushAnim(1); - w.pushAnim(3); // blend srcOver - w.push(-1); // no colour filter - w.push(0); // blur image filter + w.pushAnim(3); // blend srcOver + w.push(-1); // no colour filter + w.push(0); // blur image filter w.pushAnim(0, /*slot=*/0); w.pushAnim(0, /*slot=*/0); - w.push(3); // decal - w.push(-1); // no shader + w.push(3); // decal + w.push(-1); // no shader tgfxrn::SceneRenderer renderer; renderer.setScene(w.finish(), {}); auto sharp = drawFrame(renderer, {0.01}); @@ -5233,7 +5231,7 @@ void animatedStyleWordFlipsFillToStroke() { w.pushAnim(32); w.pushAnim(32); w.push(0xffff0000); - w.push(2 | 32); // antiAlias + animated style/aa words + w.push(2 | 32); // antiAlias + animated style/aa words w.pushAnim(0, /*slot=*/0); // style word w.pushAnim(1); // antiAlias word w.pushAnim(2); // strokeWidth @@ -5335,11 +5333,10 @@ void srcRectSlotStepsSprites() { CHECK(pixelAt(blueFrame, 32, 32)[2] == 255); } - void aSparseStringPushNeverBlanksANeighbour() { // Two live-path nodes on slots 0 and 1; pushing only slot 1 must leave 0 drawn. const std::vector strings{"M8 8 L28 8 L28 28 L8 28 Z", - "M36 8 L56 8 L56 28 L36 28 Z"}; + "M36 8 L56 8 L56 28 L36 28 Z"}; Writer w; w.push(2); w.push(6); @@ -5420,8 +5417,8 @@ void anImageShaderSlotSeededZeroStillGoesLive() { w.pushAnim(0); w.pushAnim(0); w.pushAnim(1); - w.push(7); // image shader - w.pushAnim(0, 0); // handle slot seeded 0: nothing loaded at commit time + w.push(7); // image shader + w.pushAnim(0, 0); // handle slot seeded 0: nothing loaded at commit time w.push(1); w.push(1); w.push(1); @@ -5437,7 +5434,6 @@ void anImageShaderSlotSeededZeroStillGoesLive() { CHECK(pixelAt(lit, 32, 32)[1] == 0); } - /// encode/save's rasterize path: any registry entry becomes CPU pixels finishSnapshot can eat. void aRegisteredImageRasterizesForEncoding() { auto& registry = tgfxrn::ImageRegistry::instance(); @@ -5472,7 +5468,6 @@ void aRegisteredImageRasterizesForEncoding() { CHECK(threw); } - namespace { /// Bounded spin for the offscreen worker's callback; SceneTest has no runloop. bool waitFor(const std::atomic& flag) { @@ -5520,22 +5515,22 @@ void anOffscreenSurfaceRendersSlotsAndViewport() { auto first = surfaceRaw(surface); CHECK(first.size() == 8u * 8u * 4u); - CHECK(first[0] == 255 && first[1] == 45 && first[2] == 85); // (0,0) inside the rect + CHECK(first[0] == 255 && first[1] == 45 && first[2] == 85); // (0,0) inside the rect size_t right = (0 * 8 + 6) * 4; - CHECK(first[right + 0] == 0 && first[right + 1] == 0); // (6,0) is background + CHECK(first[right + 0] == 0 && first[right + 1] == 0); // (6,0) is background // A slot write moves the rect with no re-encode; the retained program re-renders. surface->setValues({4}); auto moved = surfaceRaw(surface); - CHECK(moved[0] == 0); // left edge vacated - CHECK(moved[right + 0] == 255 && moved[right + 2] == 85); // landed at x=4..8 + CHECK(moved[0] == 0); // left edge vacated + CHECK(moved[right + 0] == 255 && moved[right + 2] == 85); // landed at x=4..8 // The viewport rides above the program, exactly as on a view. surface->setValues({0}); surface->setViewport(2.0f, 0.0f, 0.0f); auto zoomed = surfaceRaw(surface); size_t past = (0 * 8 + 7) * 4; - CHECK(zoomed[past + 0] == 255); // 4pt rect fills 8px at zoom 2 + CHECK(zoomed[past + 0] == 255); // 4pt rect fills 8px at zoom 2 // Headless hit test answers from the staged scene in canvas points. surface->setViewport(1.0f, 0.0f, 0.0f); @@ -5557,7 +5552,6 @@ void anOffscreenSurfaceRendersSlotsAndViewport() { CHECK(waitFor(rejected)); } - /// The unpremultiply in the encode tail, at an alpha where it is not a no-op, /// and the two rejection branches encode must take. void encodingUnpremultipliesAndRejectsLiveFrames() { diff --git a/packages/react-native-tgfx/cpp/tests/SnapshotTest.cpp b/packages/react-native-tgfx/cpp/tests/SnapshotTest.cpp index 66c2c7e2..69db1fa3 100644 --- a/packages/react-native-tgfx/cpp/tests/SnapshotTest.cpp +++ b/packages/react-native-tgfx/cpp/tests/SnapshotTest.cpp @@ -44,7 +44,7 @@ tgfx::Device* device() { } std::shared_ptr drawFrame(tgfx::Context* context, - std::shared_ptr space = nullptr) { + std::shared_ptr space = nullptr) { auto surface = space == nullptr ? tgfx::Surface::Make(context, kWidth, kHeight) : tgfx::Surface::Make(context, kWidth, kHeight, false, 1, false, 0, diff --git a/packages/react-native-tgfx/cpp/third_party/tgfx b/packages/react-native-tgfx/cpp/third_party/tgfx index fba0154d..1b2a429d 160000 --- a/packages/react-native-tgfx/cpp/third_party/tgfx +++ b/packages/react-native-tgfx/cpp/third_party/tgfx @@ -1 +1 @@ -Subproject commit fba0154dbf55a4a15c98f54cb058eb30da15135a +Subproject commit 1b2a429d1a375b0ecc754159ef182720d75dc3b2 diff --git a/packages/react-native-tgfx/ios/TgfxAutoreleasePool.mm b/packages/react-native-tgfx/ios/TgfxAutoreleasePool.mm new file mode 100644 index 00000000..c6616b0a --- /dev/null +++ b/packages/react-native-tgfx/ios/TgfxAutoreleasePool.mm @@ -0,0 +1,16 @@ +#include "OffscreenRender.hpp" + +// What @autoreleasepool compiles to (Clang's ARC spec, "Runtime support"), +// called directly so the pool can span a C++ scope. +extern "C" void* objc_autoreleasePoolPush(void); +extern "C" void objc_autoreleasePoolPop(void* pool); + +namespace tgfxrn { + +AutoreleasePool::AutoreleasePool() : pool_(objc_autoreleasePoolPush()) {} + +AutoreleasePool::~AutoreleasePool() { + objc_autoreleasePoolPop(pool_); +} + +} // namespace tgfxrn diff --git a/packages/react-native-tgfx/ios/TgfxMetalView.mm b/packages/react-native-tgfx/ios/TgfxMetalView.mm index 7b14356d..eacb8f2d 100644 --- a/packages/react-native-tgfx/ios/TgfxMetalView.mm +++ b/packages/react-native-tgfx/ios/TgfxMetalView.mm @@ -18,6 +18,13 @@ #include "tgfx/core/ColorSpace.h" #include "tgfx/gpu/metal/MetalWindow.h" +#if TARGET_OS_SIMULATOR +// The simulator's CAMetalLayer throws on the XR formats; 8-bit still carries P3, with less precision. +static const MTLPixelFormat kWidePixelFormat = MTLPixelFormatBGRA8Unorm; +#else +static const MTLPixelFormat kWidePixelFormat = MTLPixelFormatBGRA10_XR_sRGB; +#endif + // The `token` is the encoded buffer's owning reference, so ArrayBuffer.wrap needs no copy. void TgfxSnapshotRelease(void* token) { delete static_cast*>(token); @@ -32,6 +39,8 @@ @implementation TgfxMetalView { std::atomic _drawPending; tgfxrn::IdleGate _idleGate; std::atomic _windowBound; + // The space the bound window was built in. Render queue only. + bool _boundP3; // Set once the display link is gone, so a snapshot staged after that is rejected, not hung. std::atomic _released; std::atomic _drawableWidth; @@ -71,6 +80,7 @@ - (void)commonInit { __weak __typeof(self) weakSelf = self; _renderer->setWakeCallback([weakSelf] { [weakSelf wakeUp]; }); _windowBound = false; + _boundP3 = false; _released = false; _drawPending = false; _drawableWidth = 0; @@ -116,14 +126,22 @@ - (void)layoutSubviews { } - (void)bindWindowIfNeeded { - if (_windowBound || _renderer == nullptr) { + if (_renderer == nullptr) { return; } + bool wantsP3 = _renderer->wantsDisplayP3(); + if (_windowBound) { + if (_boundP3 == wantsP3) { + return; + } + // Recycled from a canvas in the other space: a window keeps its space, so build another. + _renderer->setWindow(nullptr); + _windowBound = false; + } if (_drawableWidth <= 0 || _drawableHeight <= 0) { return; } // The layer's own space too, or the surface is P3 while the layer still presents sRGB. - bool wantsP3 = _renderer->wantsDisplayP3(); if (_layerWantsP3.load() != wantsP3) { if (!_layerConfigPending.exchange(true)) { dispatch_async(dispatch_get_main_queue(), ^{ @@ -133,7 +151,7 @@ - (void)bindWindowIfNeeded { self->_layer.colorspace = cgSpace; CGColorSpaceRelease(cgSpace); self->_layer.pixelFormat = - wantsP3 ? MTLPixelFormatBGRA10_XR_sRGB : MTLPixelFormatBGRA8Unorm; + wantsP3 ? kWidePixelFormat : MTLPixelFormatBGRA8Unorm; self->_layerWantsP3 = wantsP3; self->_layerConfigPending = false; [self wakeUp]; @@ -145,6 +163,7 @@ - (void)bindWindowIfNeeded { auto window = tgfx::MetalWindow::MakeFrom(_layer, nullptr, space); if (window != nullptr) { _renderer->setWindow(window); + _boundP3 = wantsP3; _windowBound = true; } } diff --git a/packages/react-native-tgfx/package.json b/packages/react-native-tgfx/package.json index 36c2b6ef..e20cd95a 100644 --- a/packages/react-native-tgfx/package.json +++ b/packages/react-native-tgfx/package.json @@ -1,6 +1,6 @@ { "name": "react-native-tgfx", - "version": "0.0.2-alpha.12", + "version": "0.1.0", "description": "A declarative, Skia-style GPU 2D canvas for React Native, backed by Tencent's tgfx and built with Nitro Modules.", "main": "lib/index", "module": "lib/index", diff --git a/packages/react-native-tgfx/src/__tests__/Canvas.test.tsx b/packages/react-native-tgfx/src/__tests__/Canvas.test.tsx index b9980b81..db420e81 100644 --- a/packages/react-native-tgfx/src/__tests__/Canvas.test.tsx +++ b/packages/react-native-tgfx/src/__tests__/Canvas.test.tsx @@ -235,16 +235,36 @@ test('a background does not recompile the scene on every render', async () => { expect(scenes.length).toBe(0) }) -test('unmounting still tears the root down', async () => { - const tree = await render(SCENE) +// Fabric can recycle the view into the next canvas before this one's teardown +// runs, so the teardown stays off the view or it blanks that canvas. +test('unmounting tears the root down without writing to the view', async () => { + let cleaned = 0 + function Child(): React.ReactElement { + useEffect( + () => () => { + cleaned++ + }, + [] + ) + return + } + const direct = await render(SCENE) + const reconciled = await render( + + + + ) expect(scenes.at(-1)![3]).toBe(1) + scenes = [] await act(async () => { - tree.unmount() + direct.unmount() + reconciled.unmount() await new Promise((resolve) => setTimeout(resolve, 20)) }) - expect(scenes.at(-1)![3]).toBe(0) + expect(cleaned).toBe(1) + expect(scenes).toEqual([]) }) // A single starts at word 4: [kind, x, y, width, height, ...paint]. diff --git a/packages/react-native-tgfx/src/__tests__/mirror.test.ts b/packages/react-native-tgfx/src/__tests__/mirror.test.ts index 65a9048e..9d3f500c 100644 --- a/packages/react-native-tgfx/src/__tests__/mirror.test.ts +++ b/packages/react-native-tgfx/src/__tests__/mirror.test.ts @@ -6,7 +6,10 @@ import { NodeType, type Node } from '../reconciler/types' import type { FlagBlock } from '../reanimated/slotFlags' /** A SharedValue whose `.value` read is a cross-runtime hop on Reanimated 4: count them. */ -function shared(value: number): { sv: { value: number; _isReanimatedSharedValue: true }; reads: () => number } { +function shared(value: number): { + sv: { value: number; _isReanimatedSharedValue: true } + reads: () => number +} { let reads = 0 const sv = { _isReanimatedSharedValue: true as const, @@ -35,7 +38,11 @@ test('a commit snapshots an animating slot from the mirror, not from .value', () words.push(new Float64Array(buffer)) }) const roots = [ - { type: NodeType.Circle, props: { cx: x.sv, cy: y.sv, r: 1, color: '#fff' }, children: [] }, + { + type: NodeType.Circle, + props: { cx: x.sv, cy: y.sv, r: 1, color: '#fff' }, + children: [], + }, ] as Node[] container.setRootDirect(roots) // First commit: nothing mirrored yet, so the literals come from .value. @@ -54,7 +61,11 @@ test('a commit snapshots an animating slot from the mirror, not from .value', () // A value this container has never seen is read once. const z = shared(9) container.setRootDirect([ - { type: NodeType.Circle, props: { cx: x.sv, cy: z.sv, r: 1, color: '#fff' }, children: [] }, + { + type: NodeType.Circle, + props: { cx: x.sv, cy: z.sv, r: 1, color: '#fff' }, + children: [], + }, ] as Node[]) expect(Array.from(words[3]!.subarray(5, 7))).toEqual([50, 9]) expect(x.reads()).toBe(1) @@ -67,7 +78,11 @@ test('a JS-thread push takes mirrored values the same way', () => { const container = new TgfxContainer(() => {}) container.onValues = (values) => pushed.push(values.slice()) container.setRootDirect([ - { type: NodeType.Rect, props: { x: x.sv, y: 0, width: 1, height: 1 }, children: [] }, + { + type: NodeType.Rect, + props: { x: x.sv, y: 0, width: 1, height: 1 }, + children: [], + }, ] as Node[]) container.mirror = { values: [x.sv], block: block([7], true) } const before = x.reads() @@ -86,7 +101,11 @@ test('with a driver to follow, an unseen mutable is deferred and the program fla const pushed: number[][] = [] container.onValues = (values) => pushed.push(values.slice()) container.setRootDirect([ - { type: NodeType.Rect, props: { x: x.sv, y: 0, width: 1, height: 1 }, children: [] }, + { + type: NodeType.Rect, + props: { x: x.sv, y: 0, width: 1, height: 1 }, + children: [], + }, ] as Node[]) expect(x.reads()).toBe(0) expect(container.unresolved).toBe(true) diff --git a/packages/react-native-tgfx/src/__tests__/useImage.test.tsx b/packages/react-native-tgfx/src/__tests__/useImage.test.tsx index 7039379f..556faba3 100644 --- a/packages/react-native-tgfx/src/__tests__/useImage.test.tsx +++ b/packages/react-native-tgfx/src/__tests__/useImage.test.tsx @@ -117,13 +117,24 @@ test('a bundled asset resolving to a bare path is opened as a file', async () => expect(made[0]!.arg).toBe('/var/app/assets/pic.png') }) -// A JPEG payload starts "/9j/", so a leading slash cannot mean "path" here. +test('an absolute path, as save() writes, is opened as a file', async () => { + await mount('/data/user/0/app/cache/pic.png') + expect(made[0]!.via).toBe('fromFile') + expect(made[0]!.arg).toBe('/data/user/0/app/cache/pic.png') +}) + +// A JPEG payload starts "/9j/", so a leading slash alone cannot mean "path". test('a raw base64 source goes to the base64 path even when it starts with /', async () => { await mount('/9j/4AAQSkZJRg==') expect(made[0]!.via).toBe('fromBase64') expect(made[0]!.arg).toBe('/9j/4AAQSkZJRg==') }) +test('line-wrapped base64 that starts with / is still base64', async () => { + await mount('/9j/4AAQ\nSkZJRg==') + expect(made[0]!.via).toBe('fromBase64') +}) + test('a data: URI is decoded from its payload, not its whole URI', async () => { await mount('data:image/png;base64,aGk=') expect(made[0]!.via).toBe('fromBase64') diff --git a/packages/react-native-tgfx/src/hooks/source.ts b/packages/react-native-tgfx/src/hooks/source.ts index 24fa5b13..b46c2945 100644 --- a/packages/react-native-tgfx/src/hooks/source.ts +++ b/packages/react-native-tgfx/src/hooks/source.ts @@ -29,6 +29,15 @@ export function looksLikeSvgMarkup(source: string): boolean { return false } +/** + * True for an absolute path such as `save()` writes to. Base64 can open with + * "/" too (a JPEG payload starts "/9j/"), but never holds a character outside + * its alphabet, and a real path's name or extension nearly always does. + */ +function looksLikeAbsolutePath(source: string): boolean { + return source.startsWith('/') && /[^A-Za-z0-9+/=\s]/.test(source) +} + function dataPayload(uri: string): string | null { if (!uri.startsWith('data:')) { return null @@ -75,7 +84,11 @@ export async function loadSource( // A release Android build compiles a bundled asset into a drawable/raw // resource, so this is a bare resource name - no scheme, no path. Native // reads it by name; base64 would only see the name's own characters. - if (uri.startsWith('file:') || (bareIsPath && !/^[a-z][a-z\d+.-]*:/i.test(uri))) { + if ( + uri.startsWith('file:') || + (bareIsPath && !/^[a-z][a-z\d+.-]*:/i.test(uri)) || + looksLikeAbsolutePath(uri) + ) { return api.fromFile(uri) } if (/^(https?|content|asset):/.test(uri)) { diff --git a/packages/react-native-tgfx/src/imperative.ts b/packages/react-native-tgfx/src/imperative.ts index f830d3ab..9f6a9c5b 100644 --- a/packages/react-native-tgfx/src/imperative.ts +++ b/packages/react-native-tgfx/src/imperative.ts @@ -335,7 +335,9 @@ export function createHandle(): NodeHandle { const boxedFlags = flagBlock?.boxed ?? null const flagBytes = flagBlock?.bytes ?? null const live = (at: number, initial: number): LiveValue => - flagBlock != null ? liveFromBlock(flagBlock, at, initial) : makeLive(initial) + flagBlock != null + ? liveFromBlock(flagBlock, at, initial) + : makeLive(initial) const liveString = (at: number, initial: string): LiveString => flagBlock != null ? liveStringFromBlock(flagBlock, at, initial) diff --git a/packages/react-native-tgfx/src/reanimated/liveValue.ts b/packages/react-native-tgfx/src/reanimated/liveValue.ts index e804757e..02a61ccc 100644 --- a/packages/react-native-tgfx/src/reanimated/liveValue.ts +++ b/packages/react-native-tgfx/src/reanimated/liveValue.ts @@ -1,11 +1,6 @@ import type { MaybeSharedValue } from '../compiler/values' import { reanimated, type Reanimated } from './peer' -import { - slotsOf, - valuesOf, - type BoxedSlots, - type FlagBlock, -} from './slotFlags' +import { slotsOf, valuesOf, type BoxedSlots, type FlagBlock } from './slotFlags' /** A value slot this package created, rather than one the caller animates. */ export type LiveValue = MaybeSharedValue @@ -40,38 +35,66 @@ interface BlockStringSlot extends MaybeSharedValue { __tgfxStrAt: number } -export function liveFromBlock(block: FlagBlock, at: number, initial: number): LiveValue { +/** + * A slot object whose keys cannot be redefined. In dev, react-native-worklets + * redefines every configurable key of an object a worklet captures - on the + * original, not only the clone - as a getter frozen at capture time and a + * setter that only warns. A captured block slot then dropped every JS-thread + * write. Non-configurable keys are skipped, and stay enumerable so the clone + * still carries `__tgfxBoxed` and the slot index. + */ +function pinnedSlot(keys: PropertyDescriptorMap): T { + const slot = {} + for (const key in keys) { + Object.defineProperty(slot, key, { + ...keys[key], + enumerable: true, + configurable: false, + }) + } + return slot as T +} + +export function liveFromBlock( + block: FlagBlock, + at: number, + initial: number +): LiveValue { block.values[at] = initial - const slot: BlockSlot = { - _isReanimatedSharedValue: true, - __tgfxBoxed: block.boxed, - __tgfxAt: at, - get value(): number { - return block.values[at]! + const slot = pinnedSlot({ + _isReanimatedSharedValue: { value: true }, + __tgfxBoxed: { value: block.boxed }, + __tgfxAt: { value: at }, + value: { + get: (): number => block.values[at]!, + set: (v: number) => { + block.values[at] = v + }, }, - set value(v: number) { - block.values[at] = v - }, - } + }) LIVE.add(slot) return slot } -export function liveStringFromBlock(block: FlagBlock, at: number, initial: string): LiveString { +export function liveStringFromBlock( + block: FlagBlock, + at: number, + initial: string +): LiveString { if (initial !== '') { block.slots.setString(at, initial) } - const slot: BlockStringSlot = { - _isReanimatedSharedValue: true, - __tgfxBoxed: block.boxed, - __tgfxStrAt: at, - get value(): string { - return block.slots.getString(at) + const slot = pinnedSlot({ + _isReanimatedSharedValue: { value: true }, + __tgfxBoxed: { value: block.boxed }, + __tgfxStrAt: { value: at }, + value: { + get: (): string => block.slots.getString(at), + set: (v: string) => { + block.slots.setString(at, v) + }, }, - set value(v: string) { - block.slots.setString(at, v) - }, - } + }) LIVE.add(slot) return slot } diff --git a/packages/react-native-tgfx/src/reconciler/Container.ts b/packages/react-native-tgfx/src/reconciler/Container.ts index eb0481c7..54007464 100644 --- a/packages/react-native-tgfx/src/reconciler/Container.ts +++ b/packages/react-native-tgfx/src/reconciler/Container.ts @@ -65,7 +65,8 @@ export class TgfxContainer implements NodeOwner { * byte 0 marks the mirror written. Block slots are never taken from it: a * JS-thread write to one fires no driver, so the mirror can trail it. */ - mirror: { values: MaybeSharedValue[]; block: FlagBlock } | null = null + mirror: { values: MaybeSharedValue[]; block: FlagBlock } | null = + null /// What the last program wrote per SharedValue: exactly what native draws /// until the driver's first push, so a commit before that push reuses it. private lastLiterals: Map | null = null diff --git a/packages/react-native-tgfx/src/reconciler/Reconciler.ts b/packages/react-native-tgfx/src/reconciler/Reconciler.ts index dd18cbd0..5b6cf62b 100644 --- a/packages/react-native-tgfx/src/reconciler/Reconciler.ts +++ b/packages/react-native-tgfx/src/reconciler/Reconciler.ts @@ -209,9 +209,17 @@ export class TgfxRoot { } unmount(): void { - reconciler.updateContainer(null, this.root, null, null) - if (this.container.root.length > 0) { - this.container.setRootDirect([]) + // Flushed muted, as in setDirect: by now Fabric may have recycled the view + // into the next canvas, and this teardown's empty scene would blank it. + this.container.muted = true + try { + reconciler.updateContainerSync(null, this.root, null, null) + reconciler.flushSyncWork() + if (this.container.root.length > 0) { + this.container.setRootDirect([]) + } + } finally { + this.container.muted = false } } } diff --git a/packages/react-native-tgfx/src/scene.ts b/packages/react-native-tgfx/src/scene.ts index 6c4c8f38..42c6118c 100644 --- a/packages/react-native-tgfx/src/scene.ts +++ b/packages/react-native-tgfx/src/scene.ts @@ -403,44 +403,41 @@ export class Scene { if (listenable.length === 0) { return } - this.mapperId = startMapper( - () => { - 'worklet' - const mirrored = mirror != null ? valuesOf(mirror) : null - for (let i = 0; i < values.length; i++) { - const v = readLiveNumber(values[i]!) - slots[i] = v - if (mirrored != null) { - mirrored[i] = v - } - } - if (mirror != null) { - flagsOf(mirror)[0] = 1 - } - for (const view of views) { - view.setValues(slots) + this.mapperId = startMapper(() => { + 'worklet' + const mirrored = mirror != null ? valuesOf(mirror) : null + for (let i = 0; i < values.length; i++) { + const v = readLiveNumber(values[i]!) + slots[i] = v + if (mirrored != null) { + mirrored[i] = v } - if (stringValues.length > 0) { - let indices: number[] | null = null - let out: string[] | null = null - for (let i = 0; i < stringValues.length; i++) { - const now = readLiveString(stringValues[i]!) - if (now === sent[i]) { - continue - } - sent[i] = now - ;(indices ??= []).push(i) - ;(out ??= []).push(now) + } + if (mirror != null) { + flagsOf(mirror)[0] = 1 + } + for (const view of views) { + view.setValues(slots) + } + if (stringValues.length > 0) { + let indices: number[] | null = null + let out: string[] | null = null + for (let i = 0; i < stringValues.length; i++) { + const now = readLiveString(stringValues[i]!) + if (now === sent[i]) { + continue } - if (indices != null && out != null) { - for (const view of views) { - view.setStringValues?.(indices, out) - } + sent[i] = now + ;(indices ??= []).push(i) + ;(out ??= []).push(now) + } + if (indices != null && out != null) { + for (const view of views) { + view.setStringValues?.(indices, out) } } - }, - listenable - ) + } + }, listenable) } private markDirty(): void { diff --git a/packages/react-native-tgfx/src/specs/TgfxOffscreenSurface.nitro.ts b/packages/react-native-tgfx/src/specs/TgfxOffscreenSurface.nitro.ts index 1b266a7d..c31b37ad 100644 --- a/packages/react-native-tgfx/src/specs/TgfxOffscreenSurface.nitro.ts +++ b/packages/react-native-tgfx/src/specs/TgfxOffscreenSurface.nitro.ts @@ -20,11 +20,10 @@ import type { TgfxImage } from './TgfxImage.nitro' * The colour space is a `createOffscreenSurface` option rather than a method: * a surface's space is fixed at creation, exactly like a view's. */ -export interface TgfxOffscreenSurface - extends HybridObject<{ - ios: 'c++' - android: 'c++' - }> { +export interface TgfxOffscreenSurface extends HybridObject<{ + ios: 'c++' + android: 'c++' +}> { /** Logical points, as given at creation. */ readonly width: number readonly height: number @@ -82,11 +81,10 @@ export interface TgfxOffscreenSurface * Creates {@link TgfxOffscreenSurface}s. Use the exported * `createOffscreenSurface` wrapper, which validates and applies defaults. */ -export interface TgfxOffscreenSurfaceFactory - extends HybridObject<{ - ios: 'c++' - android: 'c++' - }> { +export interface TgfxOffscreenSurfaceFactory extends HybridObject<{ + ios: 'c++' + android: 'c++' +}> { create( width: number, height: number, diff --git a/packages/react-native-tgfx/src/specs/TgfxVideo.nitro.ts b/packages/react-native-tgfx/src/specs/TgfxVideo.nitro.ts index ac80097e..da4f526f 100644 --- a/packages/react-native-tgfx/src/specs/TgfxVideo.nitro.ts +++ b/packages/react-native-tgfx/src/specs/TgfxVideo.nitro.ts @@ -8,11 +8,10 @@ import type { HybridObject } from 'react-native-nitro-modules' * A frame never reaches JS at all, as pixels or as a pointer: the decoder writes * into a registry entry natively and JS only ever sees its id. */ -export interface TgfxVideo - extends HybridObject<{ - ios: 'swift' - android: 'kotlin' - }> { +export interface TgfxVideo extends HybridObject<{ + ios: 'swift' + android: 'kotlin' +}> { /** Total length in milliseconds, 0 when the source does not report one. */ readonly duration: number readonly framerate: number @@ -49,11 +48,10 @@ export interface TgfxVideo release(): void } -export interface TgfxVideoFactory - extends HybridObject<{ - ios: 'swift' - android: 'kotlin' - }> { +export interface TgfxVideoFactory extends HybridObject<{ + ios: 'swift' + android: 'kotlin' +}> { /** A `file://`, `http(s)://`, `content://` or `asset://` URI, or a bare path. */ load(uri: string): Promise } diff --git a/scripts/clang-format.sh b/scripts/clang-format.sh new file mode 100755 index 00000000..1caec920 --- /dev/null +++ b/scripts/clang-format.sh @@ -0,0 +1,44 @@ +#!/bin/bash +# Formats the hand-written C++, Objective-C++ and C in place with the repo's +# .clang-format. CI runs this, then fails on any diff it leaves. +# +# bun lint-cpp +# +# Generated code (nitrogen/) and the vendored tgfx submodule are not ours to format. +set -euo pipefail + +# CI installs exactly this version; another major version formats differently. +CLANG_FORMAT_VERSION=23.1.3 + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" + +CPP_DIRS=( + packages/react-native-tgfx/cpp + packages/react-native-tgfx/ios + packages/react-native-tgfx/android/src/main/cpp + packages/react-native-tgfx-vision-camera/cpp + packages/react-native-tgfx-vision-camera/android/src/main/cpp +) + +if ! command -v clang-format >/dev/null; then + echo "error: clang-format not installed. Install the version CI uses with" >&2 + echo " pipx install clang-format==$CLANG_FORMAT_VERSION" >&2 + exit 1 +fi + +installed="$(clang-format --version | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)" +if [ "${installed%%.*}" != "${CLANG_FORMAT_VERSION%%.*}" ]; then + # On CI a stray runner clang-format would pass or fail the check by accident. + if [ -n "${CI:-}" ]; then + echo "error: clang-format $installed on PATH, expected $CLANG_FORMAT_VERSION" >&2 + exit 1 + fi + echo "warning: clang-format $installed, CI uses $CLANG_FORMAT_VERSION, so the result may differ from CI's" >&2 +fi + +find "${CPP_DIRS[@]}" -path '*/third_party' -prune -o -type f \ + \( -name '*.h' -o -name '*.hpp' -o -name '*.c' -o -name '*.cpp' -o -name '*.m' -o -name '*.mm' \) \ + -print0 | xargs -0 clang-format -style=file -i + +echo "C++ format done!" diff --git a/scripts/release.sh b/scripts/release.sh index 86fab45c..68ef2d4f 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -32,6 +32,10 @@ ensure_github_token for pkg in packages/*; do [ -d "$pkg" ] || continue + if [ -n "$(npm view "$(basename "$pkg")@$1" version 2>/dev/null)" ]; then + echo "Skipping '$(basename "$pkg")': $1 is already on NPM" + continue + fi echo "Publishing '$(basename "$pkg")' to NPM" (cd "$pkg" && bun run release "$@") done