|
| 1 | +# Fix Torch State Retention on Camera Switch in camera_android_camerax |
| 2 | + |
| 3 | +## Goal Description |
| 4 | + |
| 5 | +The `camera_android_camerax` package fails to retain the torch state when switching between cameras. Specifically, if the torch is turned on while using the rear camera, and the user switches to the front camera (which typically does not support torch) and then back to the rear camera, the torch does not turn back on automatically. Furthermore, attempting to turn it on again after switching back fails because the internal state (`torchEnabled`) still thinks it is on, causing an early return. |
| 6 | + |
| 7 | +This plan proposes to fix this by tracking torch state per camera and restoring it when a camera becomes active, after verifying that the camera supports flash. |
| 8 | + |
| 9 | +## User Review Required |
| 10 | + |
| 11 | +> [!IMPORTANT] |
| 12 | +> **Multi-Camera Support**: To prevent out-of-sync issues in complex camera switching cases (e.g., devices with more than 2 cameras), I propose changing `torchEnabled` from a single boolean to a map `_torchEnabledPerCamera = <String, bool>{}` keyed by the camera name (from `CameraDescription.name`). This ensures torch state is isolated per camera. |
| 13 | +> |
| 14 | +> **New Mapping**: Instead of tracking a single active camera, I will maintain a map `_cameraIdToCameraName = <int, String>{}` to map `cameraId` (texture ID) to the camera name. This is required because some methods (like `initializeCamera`) only receive a `cameraId` and need to know which camera name it corresponds to in order to use it as a key in `_torchEnabledPerCamera`. This approach is more robust than relying on a "current" camera state. |
| 15 | +
|
| 16 | +> [!NOTE] |
| 17 | +> **CameraX Expectations**: CameraX expects developers to check `CameraInfo.hasFlashUnit()` before calling `CameraControl.enableTorch()`. |
| 18 | +> I will incorporate this by: |
| 19 | +> 1. Exposing `hasFlashUnit()` via Pigeon in `CameraInfo`. |
| 20 | +> 2. Checking it in Dart before attempting to restore torch state, and giving a helpful error if the user tries to turn on torch on a camera without flash. |
| 21 | +
|
| 22 | +## Prerequisites |
| 23 | + |
| 24 | +Before making any code changes, run the following command to ensure dependencies are up to date: |
| 25 | +```bash |
| 26 | +dart run ../../../script/tool/bin/flutter_plugin_tools.dart fetch-deps --packages=camera_android_camerax |
| 27 | +``` |
| 28 | + |
| 29 | +## Test-Driven Development Workflow |
| 30 | + |
| 31 | +We will strictly follow Test-Driven Development (TDD) for this implementation as described in the TDD skill. |
| 32 | +1. **RED**: Write a minimal failing test in `test/android_camera_camerax_test.dart` or relevant Java test file. |
| 33 | +2. **Verify RED**: Run the test and verify it fails with the expected message. |
| 34 | +3. **GREEN**: Write the minimal production code to make the test pass. |
| 35 | +4. **Verify GREEN**: Run the test and verify it passes. |
| 36 | +5. **REFACTOR**: Clean up the code while keeping the tests green. |
| 37 | + |
| 38 | +*The Iron Law: No production code without a failing test first.* |
| 39 | + |
| 40 | +## Proposed Changes |
| 41 | + |
| 42 | +### camera_android_camerax |
| 43 | + |
| 44 | +Summary of changes to retain and restore torch state across camera switches. Following TDD, we will implement these by first writing tests in `test/android_camera_camerax_test.dart` and relevant Java test files to reproduce the missing behavior or test the new functionality, and then writing the minimal code to pass the tests. |
| 45 | + |
| 46 | +--- |
| 47 | + |
| 48 | +#### [MODIFY] [pigeons/camerax_library.dart](pigeons/camerax_library.dart) |
| 49 | + |
| 50 | +- Add `bool hasFlashUnit();` to `abstract class CameraInfo`. |
| 51 | +- Run the Pigeon generator to update generated files. |
| 52 | +- The version of pigeon should not change. |
| 53 | + |
| 54 | +#### [MODIFY] [android/src/main/java/io/flutter/plugins/camerax/CameraInfoProxyApi.java](android/src/main/java/io/flutter/plugins/camerax/CameraInfoProxyApi.java) |
| 55 | + |
| 56 | +- Implement `hasFlashUnit(CameraInfo pigeonInstance)` to return `pigeonInstance.hasFlashUnit()`. |
| 57 | +- New methods in `CameraInfoProxyApi` need to include a `CameraInfoProxyTest` for the new method. |
| 58 | + |
| 59 | +#### [MODIFY] [lib/src/android_camera_camerax.dart](lib/src/android_camera_camerax.dart) |
| 60 | + |
| 61 | +- Add `Map<int, String> _cameraIdToCameraName = {};` to map `cameraId` (texture ID) to camera name. |
| 62 | +- Update `_cameraIdToCameraName` in `createCameraWithSettings` with the created camera's ID and name. |
| 63 | +- Replace `torchEnabled` boolean with `Map<String, bool> _torchEnabledPerCamera = {};`. |
| 64 | +- Update `setFlashMode` to use `_torchEnabledPerCamera` keyed by the camera name retrieved from `_cameraIdToCameraName[cameraId]`. If mode is `FlashMode.torch`, check `await cameraInfo!.hasFlashUnit()` first and throw a `CameraException` with error code `torchNotSupported` if false. Also ensure native errors from `CameraControl.enableTorch()` are surfaced. |
| 65 | +- Create a `_restoreTorchState` method that takes `cameraId`, retrieves the camera name from `_cameraIdToCameraName[cameraId]`, checks if `_torchEnabledPerCamera[cameraName]` is true and `await cameraInfo!.hasFlashUnit()` is true, and if so, calls `_enableTorchMode(true)`. |
| 66 | +- Call `_restoreTorchState` in `initializeCamera` (after `cameraControl` is initialized) and `setDescriptionWhileRecording` as appropriate. |
| 67 | + |
| 68 | +## Verification Plan |
| 69 | + |
| 70 | +To make commands easier to read, you can use an alias: |
| 71 | +```bash |
| 72 | +alias tool="dart run ../../../script/tool/bin/flutter_plugin_tools.dart" |
| 73 | +``` |
| 74 | + |
| 75 | +### Automated Tests |
| 76 | + |
| 77 | +I will add unit tests in `android_camera_camerax_test.dart` to verify: |
| 78 | +1. `setFlashMode` with `FlashMode.torch` sets torch state for that camera. |
| 79 | +2. `_restoreTorchState` attempts to restore torch state to ON if enabled for that camera and flash is available. |
| 80 | +3. `_restoreTorchState` does not attempt to turn on torch if not enabled for that camera. |
| 81 | +4. `setDescriptionWhileRecording` restores torch state as expected when switching cameras. |
| 82 | + |
| 83 | + |
| 84 | +Run tests using: |
| 85 | +```bash |
| 86 | +tool dart-test --package=camera_android_camerax |
| 87 | +``` |
| 88 | + |
| 89 | +## Grill Session Answers |
| 90 | + |
| 91 | +**Question 1:** The plan proposes using a map `_torchEnabledPerCamera` to track torch state per camera. Why is this approach preferred over simply resetting the state on switch or querying CameraX? |
| 92 | +**Answer:** It allows retaining the desired torch state for each camera independently, enabling automatic restoration when switching back to a camera that supported it, which matches user expectations. |
| 93 | + |
| 94 | +**Question 2:** The plan proposes adding `_currentCameraDescription` to track the active camera because some methods only receive a `cameraId`. Would it be better to maintain a map from `cameraId` (texture ID) to camera name instead, or do you prefer tracking the full `CameraDescription`? |
| 95 | +**Answer:** I prefer maintaining a map from `cameraId` to camera name to be more robust and avoid relying on a "current" camera state. |
| 96 | + |
| 97 | +**Question 3:** The plan proposes throwing a specific `CameraException` if the user tries to turn on torch on a camera without flash. What specific error code and message should we use, and should we also handle failures from `CameraControl.enableTorch()` itself? |
| 98 | +**Answer:** Use a specific error code like `torchNotSupported` when `hasFlashUnit()` is false, and also handle failures from `enableTorch` by surfacing the native error. |
| 99 | + |
| 100 | +**Question 4:** The plan proposes calling `_restoreTorchState` in `createCameraWithSettings`. However, `cameraControl` is not initialized until `initializeCamera`. Should we call `_restoreTorchState` in `initializeCamera` instead? |
| 101 | +**Answer:** Yes, call `_restoreTorchState` in `initializeCamera` after `cameraControl` is initialized, to ensure we don't get null pointer or uninitialized variable errors. |
| 102 | + |
| 103 | +### Manual Verification |
| 104 | + |
| 105 | +1. **Example App**: Build and run the example app to check behavior visually. **Explicitly test switching between all 3 cameras** (Main, Ultrawide, and Front) to ensure torch state is handled correctly. |
| 106 | +2. **Integration Tests**: Run `flutter test` in `example/integration_test` to ensure nothing broke. |
| 107 | +3. **Emulator Testing**: |
| 108 | + - Start emulator: `../../Library/Android/sdk/emulator/emulator -avd Pixel_9_API_36` (or `Pixel_9` or other available AVD). *Note: This path assumes execution from the repository root.* |
| 109 | + - Run example app: `flutter run example` |
| 110 | + - Check torch state via adb: `adb shell dumpsys media.camera | grep -i "torch"` |
| 111 | + - Ensure emulator has camera flash enabled in settings if testing actual toggle. |
| 112 | + |
| 113 | + |
| 114 | +### Required Checks for Completion |
| 115 | + |
| 116 | +- Versions of dependencies should not change unless a feature from a newer version is required. |
| 117 | +- Run `tool format --packages=camera_android_camerax` and `tool analyze --packages=camera_android_camerax` after every code edit. |
| 118 | +- Run `tool fix --packages=camera_android_camerax` if errors are found in analyze before attempting any other mitigations. |
| 119 | +- Run tests after each test case added and after finishing a unit of code work using `tool dart-test --packages=camera_android_camerax`. |
| 120 | +- Run `tool gradle-check --packages=camera_android_camerax` after touching `build.gradle` files. |
| 121 | +- Run `tool license-check --packages=camera_android_camerax` after getting new files to their final state. |
| 122 | +- When completely done, run: |
| 123 | + - `tool readme-check --packages=camera_android_camerax` |
| 124 | + - `tool version-check --packages=camera_android_camerax` |
| 125 | + - `tool pubspec-check --packages=camera_android_camerax --allow-dependencies=../../../script/configs/allowed_unpinned_deps.yaml` |
| 126 | +- After completing all the above checks and considering the work done, run the `/comprehensive-code-review` skill on the changes. Review the generated feedback, address any items that are agreed to be valid improvements, and then re-run the list of required checks to ensure no new issues were introduced. |
| 127 | +- Finally, run `tool publish-check --packages=camera_android_camerax`. |
| 128 | + |
| 129 | +> [!IMPORTANT] |
| 130 | +> If any of the above commands fail, the task is NOT complete. You must fix any errors found and re-run the checks until they all pass. |
0 commit comments