text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
33e4d21f7c13e02a7c92c7272309afbff792a864
| plugins/.ci/flutter_master.version/0 | {
"file_path": "plugins/.ci/flutter_master.version",
"repo_id": "plugins",
"token_count": 26
} | 1,186 |
gcp_credentials: ENCRYPTED[!3a93d98d7c95a41f5033834ef30e50928fc5d81239dc632b153c2628200a8187f3811cb01ce338b1ab3b6505a7a65c37!]
# Run on PRs and main branch post submit only. Don't run tests when tagging.
only_if: $CIRRUS_TAG == '' && ($CIRRUS_PR != '' || $CIRRUS_BRANCH == 'main')
env:
CHANNEL: "master" # Default to master when not explicitly set by a task.
PLUGIN_TOOL_COMMAND: "dart pub global run flutter_plugin_tools"
install_chrome_linux_template: &INSTALL_CHROME_LINUX
env:
CHROME_NO_SANDBOX: true
CHROME_DOWNLOAD_DIR: /tmp/chromium
CHROME_EXECUTABLE: $CHROME_DOWNLOAD_DIR/chrome-linux/chrome
CHROMEDRIVER_EXECUTABLE: $CHROME_DOWNLOAD_DIR/chromedriver/chromedriver
PATH: $PATH:$CHROME_DOWNLOAD_DIR/chrome-linux
install_chromium_script:
# Install a pinned version of Chromium and its corresponding ChromeDriver.
# Setting CHROME_EXECUTABLE above causes this version to be used for tests.
- ./script/install_chromium.sh
tool_setup_template: &TOOL_SETUP_TEMPLATE
tool_setup_script:
- .ci/scripts/prepare_tool.sh
flutter_upgrade_template: &FLUTTER_UPGRADE_TEMPLATE
upgrade_flutter_script:
# Channels that are part of our normal test matrix use a pinned,
# auto-rolled version to prevent out-of-band CI failures due to changes in
# Flutter.
- TARGET_TREEISH=$CHANNEL
- if [[ "$CHANNEL" == "master" || "$CHANNEL" == "stable" ]]; then
- TARGET_TREEISH=$(< .ci/flutter_$CHANNEL.version)
- fi
# Ensure that the repository has all the branches.
- cd $FLUTTER_HOME
- git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
- git fetch origin
# Switch to the requested channel.
- git checkout $TARGET_TREEISH
# When using a branch rather than a hash or version tag, reset to the
# upstream branch rather than using pull, since the base image can sometimes
# be in a state where it has diverged from upstream (!).
- if [[ "$TARGET_TREEISH" == "$CHANNEL" ]] && [[ "$CHANNEL" != *"."* ]]; then
- git reset --hard @{u}
- fi
# Run doctor to allow auditing of what version of Flutter the run is using.
- flutter doctor -v
<< : *TOOL_SETUP_TEMPLATE
# Ensures that the latest versions of all of the 1P packages can be used
# together. See script/configs/exclude_all_packages_app.yaml for exceptions.
build_all_packages_app_template: &BUILD_ALL_PACKAGES_APP_TEMPLATE
create_all_packages_app_script:
- $PLUGIN_TOOL_COMMAND create-all-packages-app --output-dir=. --exclude script/configs/exclude_all_packages_app.yaml
build_all_packages_debug_script:
- cd all_packages
- if [[ "$BUILD_ALL_ARGS" == "web" ]]; then
- echo "Skipping; web does not support debug builds"
- else
- flutter build $BUILD_ALL_ARGS --debug
- fi
build_all_packages_release_script:
- cd all_packages
- flutter build $BUILD_ALL_ARGS --release
# Light-workload Linux tasks.
# These use default machines, with fewer CPUs, to reduce pressure on the
# concurrency limits.
task:
<< : *FLUTTER_UPGRADE_TEMPLATE
gke_container:
dockerfile: .ci/Dockerfile
builder_image_name: docker-builder-linux # gce vm image
builder_image_project: flutter-cirrus
cluster_name: test-cluster
zone: us-central1-a
namespace: default
matrix:
### Platform-agnostic tasks ###
# Repository rules and best-practice enforcement.
# Only channel-agnostic tests should go here since it is only run once
# (on Flutter master).
- name: repo_checks
always:
format_script: ./script/tool_runner.sh format --fail-on-change
license_script: $PLUGIN_TOOL_COMMAND license-check
# The major and minor versions here should match the lowest version
# analyzed in legacy_version_analyze.
pubspec_script: ./script/tool_runner.sh pubspec-check --min-min-flutter-version=3.0.0 --min-min-dart-version=2.17.0
readme_script:
- ./script/tool_runner.sh readme-check
# Re-run with --require-excerpts, skipping packages that still need
# to be converted. Once https://github.com/flutter/flutter/issues/102679
# has been fixed, this can be removed and there can just be a single
# run with --require-excerpts and no exclusions.
- ./script/tool_runner.sh readme-check --require-excerpts --exclude=script/configs/temp_exclude_excerpt.yaml
dependabot_script: $PLUGIN_TOOL_COMMAND dependabot-check
version_script:
# For pre-submit, pass the PR labels to the script to allow for
# check overrides.
# For post-submit, ignore platform version breaking version changes
# and missing version/CHANGELOG detection since the labels aren't
# available outside of the context of the PR.
- if [[ $CIRRUS_PR == "" ]]; then
- ./script/tool_runner.sh version-check --ignore-platform-interface-breaks
- else
- ./script/tool_runner.sh version-check --check-for-missing-changes --pr-labels="$CIRRUS_PR_LABELS"
- fi
publishable_script: ./script/tool_runner.sh publish-check --allow-pre-release
federated_safety_script:
# This check is only meaningful for PRs, as it validates changes
# rather than state.
- if [[ $CIRRUS_PR == "" ]]; then
- ./script/tool_runner.sh federation-safety-check
- else
- echo "Only run in presubmit"
- fi
- name: analyze
env:
matrix:
CHANNEL: "master"
CHANNEL: "stable"
analyze_script:
# DO NOT change the custom-analysis argument here without changing the Dart repo.
# See the comment in script/configs/custom_analysis.yaml for details.
- ./script/tool_runner.sh analyze --custom-analysis=script/configs/custom_analysis.yaml
pathified_analyze_script:
# Re-run analysis with path-based dependencies to ensure that publishing
# the changes won't break analysis of other packages in the respository
# that depend on it.
- ./script/tool_runner.sh make-deps-path-based --target-dependencies-with-non-breaking-updates
# This uses --run-on-dirty-packages rather than --packages-for-branch
# since only the packages changed by 'make-deps-path-based' need to be
# checked.
- $PLUGIN_TOOL_COMMAND analyze --run-on-dirty-packages --log-timing --custom-analysis=script/configs/custom_analysis.yaml
# Restore the tree to a clean state, to avoid accidental issues if
# other script steps are added to this task.
- git checkout .
# Does a sanity check that packages at least pass analysis on the N-1 and N-2
# versions of Flutter stable if the package claims to support that version.
# This is to minimize accidentally making changes that break old versions
# (which we don't commit to supporting, but don't want to actively break)
# without updating the constraints.
# Note: The versions below should be manually updated after a new stable
# version comes out.
- name: legacy_version_analyze
depends_on: analyze
matrix:
# Change the arguments to pubspec-check when changing these values.
env:
CHANNEL: "3.0.5"
DART_VERSION: "2.17.6"
env:
CHANNEL: "3.3.10"
DART_VERSION: "2.18.6"
package_prep_script:
# Allow analyzing packages that use a dev dependency with a higher
# minimum Flutter/Dart version than the package itself.
- ./script/tool_runner.sh remove-dev-dependencies
analyze_script:
# Only analyze lib/; non-client code doesn't need to work on
# all supported legacy version.
- ./script/tool_runner.sh analyze --lib-only --skip-if-not-supporting-flutter-version="$CHANNEL" --skip-if-not-supporting-dart-version="$DART_VERSION" --custom-analysis=script/configs/custom_analysis.yaml
# Does a sanity check that packages pass analysis with the lowest possible
# versions of all dependencies. This is to catch cases where we add use of
# new APIs but forget to update minimum versions of dependencies to where
# those APIs are introduced.
- name: downgraded_analyze
depends_on: analyze
analyze_script:
- ./script/tool_runner.sh analyze --downgrade --custom-analysis=script/configs/custom_analysis.yaml
- name: readme_excerpts
env:
CIRRUS_CLONE_SUBMODULES: true
script: ./script/tool_runner.sh update-excerpts --fail-on-change
### Web tasks ###
- name: web-build_all_packages
env:
BUILD_ALL_ARGS: "web"
matrix:
CHANNEL: "master"
CHANNEL: "stable"
<< : *BUILD_ALL_PACKAGES_APP_TEMPLATE
### Linux desktop tasks ###
- name: linux-build_all_packages
env:
BUILD_ALL_ARGS: "linux"
matrix:
CHANNEL: "master"
CHANNEL: "stable"
<< : *BUILD_ALL_PACKAGES_APP_TEMPLATE
- name: linux-platform_tests
# Don't run full platform tests on both channels in pre-submit.
skip: $CIRRUS_PR != '' && $CHANNEL == 'stable'
env:
matrix:
CHANNEL: "master"
CHANNEL: "stable"
build_script:
- ./script/tool_runner.sh build-examples --linux
native_test_script:
- xvfb-run ./script/tool_runner.sh native-test --linux --no-integration
drive_script:
- xvfb-run ./script/tool_runner.sh drive-examples --linux --exclude=script/configs/exclude_integration_linux.yaml
# Heavy-workload Linux tasks.
# These use machines with more CPUs and memory, so will reduce parallelization
# for non-credit runs.
task:
<< : *FLUTTER_UPGRADE_TEMPLATE
gke_container:
dockerfile: .ci/Dockerfile
builder_image_name: docker-builder-linux # gce vm image
builder_image_project: flutter-cirrus
cluster_name: test-cluster
zone: us-central1-a
namespace: default
cpu: 4
memory: 16G
matrix:
### Platform-agnostic tasks ###
- name: dart_unit_tests
env:
matrix:
CHANNEL: "master"
CHANNEL: "stable"
unit_test_script:
- ./script/tool_runner.sh test
### Android tasks ###
- name: android-platform_tests
# Don't run full platform tests on both channels in pre-submit.
skip: $CIRRUS_PR != '' && $CHANNEL == 'stable'
env:
matrix:
PACKAGE_SHARDING: "--shardIndex 0 --shardCount 5"
PACKAGE_SHARDING: "--shardIndex 1 --shardCount 5"
PACKAGE_SHARDING: "--shardIndex 2 --shardCount 5"
PACKAGE_SHARDING: "--shardIndex 3 --shardCount 5"
PACKAGE_SHARDING: "--shardIndex 4 --shardCount 5"
matrix:
CHANNEL: "master"
CHANNEL: "stable"
MAPS_API_KEY: ENCRYPTED[596a9f6bca436694625ac50851dc5da6b4d34cba8025f7db5bc9465142e8cd44e15f69e3507787753accebfc4910d550]
GCLOUD_FIREBASE_TESTLAB_KEY: ENCRYPTED[df5cf97036c09184e386edbf4ab1e741189e0ac5ca7e4c73673c4bf02d8709c9ac733597e8f5b6511b51eafb52e4027f]
build_script:
- ./script/tool_runner.sh build-examples --apk
lint_script:
- ./script/tool_runner.sh lint-android # must come after build-examples
native_unit_test_script:
# Native integration tests are handled by Firebase Test Lab below, so
# only run unit tests.
# Must come after build-examples.
- ./script/tool_runner.sh native-test --android --no-integration --exclude script/configs/exclude_native_unit_android.yaml
firebase_test_lab_script:
- if [[ -n "$GCLOUD_FIREBASE_TESTLAB_KEY" ]]; then
- echo $GCLOUD_FIREBASE_TESTLAB_KEY > ${HOME}/gcloud-service-key.json
- ./script/tool_runner.sh firebase-test-lab --device model=redfin,version=30 --device model=starqlteue,version=26 --exclude=script/configs/exclude_integration_android.yaml
- else
- echo "This user does not have permission to run Firebase Test Lab tests."
- fi
# Upload the full lint results to Cirrus to display in the results UI.
always:
android-lint_artifacts:
path: "**/reports/lint-results-debug.xml"
type: text/xml
format: android-lint
- name: android-build_all_packages
env:
BUILD_ALL_ARGS: "apk"
matrix:
CHANNEL: "master"
CHANNEL: "stable"
<< : *BUILD_ALL_PACKAGES_APP_TEMPLATE
### Web tasks ###
- name: web-platform_tests
env:
matrix:
PACKAGE_SHARDING: "--shardIndex 0 --shardCount 2"
PACKAGE_SHARDING: "--shardIndex 1 --shardCount 2"
matrix:
CHANNEL: "master"
CHANNEL: "stable"
<< : *INSTALL_CHROME_LINUX
chromedriver_background_script:
- $CHROMEDRIVER_EXECUTABLE --port=4444
build_script:
- ./script/tool_runner.sh build-examples --web
drive_script:
- ./script/tool_runner.sh drive-examples --web --exclude=script/configs/exclude_integration_web.yaml
| plugins/.cirrus.yml/0 | {
"file_path": "plugins/.cirrus.yml",
"repo_id": "plugins",
"token_count": 5309
} | 1,187 |
<?xml version="1.0" encoding="UTF-8"?>
<issues format="5" by="lint 3.5.0" client="gradle" variant="debug" version="3.5.0">
<issue
id="Assert"
message="Assertions are unreliable in Dalvik and unimplemented in ART. Use `BuildConfig.DEBUG` conditional checks instead."
errorLine1=" assert (boundaries.getWidth() > 0 && boundaries.getHeight() > 0);"
errorLine2=" ~~~~~~">
<location
file="src/main/java/io/flutter/plugins/camera/CameraRegionUtils.java"
line="73"
column="5"/>
</issue>
<issue
id="Assert"
message="Assertions are unreliable in Dalvik and unimplemented in ART. Use `BuildConfig.DEBUG` conditional checks instead."
errorLine1=" assert (x >= 0 && x <= 1);"
errorLine2=" ~~~~~~">
<location
file="src/main/java/io/flutter/plugins/camera/CameraRegionUtils.java"
line="74"
column="5"/>
</issue>
<issue
id="Assert"
message="Assertions are unreliable in Dalvik and unimplemented in ART. Use `BuildConfig.DEBUG` conditional checks instead."
errorLine1=" assert (y >= 0 && y <= 1);"
errorLine2=" ~~~~~~">
<location
file="src/main/java/io/flutter/plugins/camera/CameraRegionUtils.java"
line="75"
column="5"/>
</issue>
<issue
id="Assert"
message="Assertions are unreliable in Dalvik and unimplemented in ART. Use `BuildConfig.DEBUG` conditional checks instead."
errorLine1=" assert (maxBoundaries == null || maxBoundaries.getWidth() > 0);"
errorLine2=" ~~~~~~">
<location
file="src/main/java/io/flutter/plugins/camera/CameraRegions.java"
line="16"
column="5"/>
</issue>
<issue
id="Assert"
message="Assertions are unreliable in Dalvik and unimplemented in ART. Use `BuildConfig.DEBUG` conditional checks instead."
errorLine1=" assert (maxBoundaries == null || maxBoundaries.getHeight() > 0);"
errorLine2=" ~~~~~~">
<location
file="src/main/java/io/flutter/plugins/camera/CameraRegions.java"
line="17"
column="5"/>
</issue>
<issue
id="Assert"
message="Assertions are unreliable in Dalvik and unimplemented in ART. Use `BuildConfig.DEBUG` conditional checks instead."
errorLine1=" assert (x >= 0 && x <= 1);"
errorLine2=" ~~~~~~">
<location
file="src/main/java/io/flutter/plugins/camera/CameraRegions.java"
line="50"
column="5"/>
</issue>
<issue
id="Assert"
message="Assertions are unreliable in Dalvik and unimplemented in ART. Use `BuildConfig.DEBUG` conditional checks instead."
errorLine1=" assert (y >= 0 && y <= 1);"
errorLine2=" ~~~~~~">
<location
file="src/main/java/io/flutter/plugins/camera/CameraRegions.java"
line="51"
column="5"/>
</issue>
<issue
id="SwitchIntDef"
message="Switch statement on an `int` with known associated constant missing case `Configuration.ORIENTATION_SQUARE`, `Configuration.ORIENTATION_UNDEFINED`"
errorLine1=" switch (orientation) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/io/flutter/plugins/camera/DeviceOrientationManager.java"
line="143"
column="5"/>
</issue>
<issue
id="SwitchIntDef"
message="Switch statement on an `int` with known associated constant missing case `Configuration.ORIENTATION_SQUARE`, `Configuration.ORIENTATION_UNDEFINED`"
errorLine1=" switch (orientation) {"
errorLine2=" ~~~~~~">
<location
file="src/main/java/io/flutter/plugins/camera/features/sensororientation/DeviceOrientationManager.java"
line="264"
column="5"/>
</issue>
<issue
id="ObsoleteSdkInt"
message="Unnecessary; SDK_INT is never < 21"
errorLine1=" if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/io/flutter/plugins/camera/CameraPlugin.java"
line="102"
column="9"/>
</issue>
</issues>
| plugins/packages/camera/camera_android/android/lint-baseline.xml/0 | {
"file_path": "plugins/packages/camera/camera_android/android/lint-baseline.xml",
"repo_id": "plugins",
"token_count": 1996
} | 1,188 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features;
import android.app.Activity;
import androidx.annotation.NonNull;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.DartMessenger;
import io.flutter.plugins.camera.features.autofocus.AutoFocusFeature;
import io.flutter.plugins.camera.features.exposurelock.ExposureLockFeature;
import io.flutter.plugins.camera.features.exposureoffset.ExposureOffsetFeature;
import io.flutter.plugins.camera.features.exposurepoint.ExposurePointFeature;
import io.flutter.plugins.camera.features.flash.FlashFeature;
import io.flutter.plugins.camera.features.focuspoint.FocusPointFeature;
import io.flutter.plugins.camera.features.fpsrange.FpsRangeFeature;
import io.flutter.plugins.camera.features.noisereduction.NoiseReductionFeature;
import io.flutter.plugins.camera.features.resolution.ResolutionFeature;
import io.flutter.plugins.camera.features.resolution.ResolutionPreset;
import io.flutter.plugins.camera.features.sensororientation.SensorOrientationFeature;
import io.flutter.plugins.camera.features.zoomlevel.ZoomLevelFeature;
/**
* Implementation of the {@link CameraFeatureFactory} interface creating the supported feature
* implementation controlling different aspects of the {@link
* android.hardware.camera2.CaptureRequest}.
*/
public class CameraFeatureFactoryImpl implements CameraFeatureFactory {
@Override
public AutoFocusFeature createAutoFocusFeature(
@NonNull CameraProperties cameraProperties, boolean recordingVideo) {
return new AutoFocusFeature(cameraProperties, recordingVideo);
}
@Override
public ExposureLockFeature createExposureLockFeature(@NonNull CameraProperties cameraProperties) {
return new ExposureLockFeature(cameraProperties);
}
@Override
public ExposureOffsetFeature createExposureOffsetFeature(
@NonNull CameraProperties cameraProperties) {
return new ExposureOffsetFeature(cameraProperties);
}
@Override
public FlashFeature createFlashFeature(@NonNull CameraProperties cameraProperties) {
return new FlashFeature(cameraProperties);
}
@Override
public ResolutionFeature createResolutionFeature(
@NonNull CameraProperties cameraProperties,
ResolutionPreset initialSetting,
String cameraName) {
return new ResolutionFeature(cameraProperties, initialSetting, cameraName);
}
@Override
public FocusPointFeature createFocusPointFeature(
@NonNull CameraProperties cameraProperties,
@NonNull SensorOrientationFeature sensorOrientationFeature) {
return new FocusPointFeature(cameraProperties, sensorOrientationFeature);
}
@Override
public FpsRangeFeature createFpsRangeFeature(@NonNull CameraProperties cameraProperties) {
return new FpsRangeFeature(cameraProperties);
}
@Override
public SensorOrientationFeature createSensorOrientationFeature(
@NonNull CameraProperties cameraProperties,
@NonNull Activity activity,
@NonNull DartMessenger dartMessenger) {
return new SensorOrientationFeature(cameraProperties, activity, dartMessenger);
}
@Override
public ZoomLevelFeature createZoomLevelFeature(@NonNull CameraProperties cameraProperties) {
return new ZoomLevelFeature(cameraProperties);
}
@Override
public ExposurePointFeature createExposurePointFeature(
@NonNull CameraProperties cameraProperties,
@NonNull SensorOrientationFeature sensorOrientationFeature) {
return new ExposurePointFeature(cameraProperties, sensorOrientationFeature);
}
@Override
public NoiseReductionFeature createNoiseReductionFeature(
@NonNull CameraProperties cameraProperties) {
return new NoiseReductionFeature(cameraProperties);
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/CameraFeatureFactoryImpl.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/CameraFeatureFactoryImpl.java",
"repo_id": "plugins",
"token_count": 1069
} | 1,189 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.resolution;
// Mirrors camera.dart
public enum ResolutionPreset {
low,
medium,
high,
veryHigh,
ultraHigh,
max,
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/resolution/ResolutionPreset.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/resolution/ResolutionPreset.java",
"repo_id": "plugins",
"token_count": 101
} | 1,190 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.graphics.Rect;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.util.Range;
import android.util.Rational;
import android.util.Size;
import org.junit.Before;
import org.junit.Test;
public class CameraPropertiesImplTest {
private static final String CAMERA_NAME = "test_camera";
private final CameraCharacteristics mockCharacteristics = mock(CameraCharacteristics.class);
private final CameraManager mockCameraManager = mock(CameraManager.class);
private CameraPropertiesImpl cameraProperties;
@Before
public void before() {
try {
when(mockCameraManager.getCameraCharacteristics(CAMERA_NAME)).thenReturn(mockCharacteristics);
cameraProperties = new CameraPropertiesImpl(CAMERA_NAME, mockCameraManager);
} catch (CameraAccessException e) {
fail();
}
}
@Test
public void ctor_shouldReturnValidInstance() throws CameraAccessException {
verify(mockCameraManager, times(1)).getCameraCharacteristics(CAMERA_NAME);
assertNotNull(cameraProperties);
}
@Test
@SuppressWarnings("unchecked")
public void getControlAutoExposureAvailableTargetFpsRangesTest() {
Range<Integer> mockRange = mock(Range.class);
Range<Integer>[] mockRanges = new Range[] {mockRange};
when(mockCharacteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES))
.thenReturn(mockRanges);
Range<Integer>[] actualRanges =
cameraProperties.getControlAutoExposureAvailableTargetFpsRanges();
verify(mockCharacteristics, times(1))
.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES);
assertArrayEquals(actualRanges, mockRanges);
}
@Test
@SuppressWarnings("unchecked")
public void getControlAutoExposureCompensationRangeTest() {
Range<Integer> mockRange = mock(Range.class);
when(mockCharacteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE))
.thenReturn(mockRange);
Range<Integer> actualRange = cameraProperties.getControlAutoExposureCompensationRange();
verify(mockCharacteristics, times(1)).get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE);
assertEquals(actualRange, mockRange);
}
@Test
public void getControlAutoExposureCompensationStep_shouldReturnDoubleWhenRationalIsNotNull() {
double expectedStep = 3.1415926535;
Rational mockRational = mock(Rational.class);
when(mockCharacteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP))
.thenReturn(mockRational);
when(mockRational.doubleValue()).thenReturn(expectedStep);
double actualSteps = cameraProperties.getControlAutoExposureCompensationStep();
verify(mockCharacteristics, times(1)).get(CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP);
assertEquals(actualSteps, expectedStep, 0);
}
@Test
public void getControlAutoExposureCompensationStep_shouldReturnZeroWhenRationalIsNull() {
double expectedStep = 0.0;
when(mockCharacteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP))
.thenReturn(null);
double actualSteps = cameraProperties.getControlAutoExposureCompensationStep();
verify(mockCharacteristics, times(1)).get(CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP);
assertEquals(actualSteps, expectedStep, 0);
}
@Test
public void getControlAutoFocusAvailableModesTest() {
int[] expectedAutoFocusModes = new int[] {0, 1, 2};
when(mockCharacteristics.get(CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES))
.thenReturn(expectedAutoFocusModes);
int[] actualAutoFocusModes = cameraProperties.getControlAutoFocusAvailableModes();
verify(mockCharacteristics, times(1)).get(CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES);
assertEquals(actualAutoFocusModes, expectedAutoFocusModes);
}
@Test
public void getControlMaxRegionsAutoExposureTest() {
int expectedRegions = 42;
when(mockCharacteristics.get(CameraCharacteristics.CONTROL_MAX_REGIONS_AE))
.thenReturn(expectedRegions);
int actualRegions = cameraProperties.getControlMaxRegionsAutoExposure();
verify(mockCharacteristics, times(1)).get(CameraCharacteristics.CONTROL_MAX_REGIONS_AE);
assertEquals(actualRegions, expectedRegions);
}
@Test
public void getControlMaxRegionsAutoFocusTest() {
int expectedRegions = 42;
when(mockCharacteristics.get(CameraCharacteristics.CONTROL_MAX_REGIONS_AF))
.thenReturn(expectedRegions);
int actualRegions = cameraProperties.getControlMaxRegionsAutoFocus();
verify(mockCharacteristics, times(1)).get(CameraCharacteristics.CONTROL_MAX_REGIONS_AF);
assertEquals(actualRegions, expectedRegions);
}
@Test
public void getDistortionCorrectionAvailableModesTest() {
int[] expectedCorrectionModes = new int[] {0, 1, 2};
when(mockCharacteristics.get(CameraCharacteristics.DISTORTION_CORRECTION_AVAILABLE_MODES))
.thenReturn(expectedCorrectionModes);
int[] actualCorrectionModes = cameraProperties.getDistortionCorrectionAvailableModes();
verify(mockCharacteristics, times(1))
.get(CameraCharacteristics.DISTORTION_CORRECTION_AVAILABLE_MODES);
assertEquals(actualCorrectionModes, expectedCorrectionModes);
}
@Test
public void getFlashInfoAvailableTest() {
boolean expectedAvailability = true;
when(mockCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE))
.thenReturn(expectedAvailability);
boolean actualAvailability = cameraProperties.getFlashInfoAvailable();
verify(mockCharacteristics, times(1)).get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
assertEquals(actualAvailability, expectedAvailability);
}
@Test
public void getLensFacingTest() {
int expectedFacing = 42;
when(mockCharacteristics.get(CameraCharacteristics.LENS_FACING)).thenReturn(expectedFacing);
int actualFacing = cameraProperties.getLensFacing();
verify(mockCharacteristics, times(1)).get(CameraCharacteristics.LENS_FACING);
assertEquals(actualFacing, expectedFacing);
}
@Test
public void getLensInfoMinimumFocusDistanceTest() {
Float expectedFocusDistance = new Float(3.14);
when(mockCharacteristics.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE))
.thenReturn(expectedFocusDistance);
Float actualFocusDistance = cameraProperties.getLensInfoMinimumFocusDistance();
verify(mockCharacteristics, times(1))
.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE);
assertEquals(actualFocusDistance, expectedFocusDistance);
}
@Test
public void getScalerAvailableMaxDigitalZoomTest() {
Float expectedDigitalZoom = new Float(3.14);
when(mockCharacteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM))
.thenReturn(expectedDigitalZoom);
Float actualDigitalZoom = cameraProperties.getScalerAvailableMaxDigitalZoom();
verify(mockCharacteristics, times(1))
.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM);
assertEquals(actualDigitalZoom, expectedDigitalZoom);
}
@Test
public void getScalerGetScalerMinZoomRatioTest() {
Range zoomRange = mock(Range.class);
when(mockCharacteristics.get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE))
.thenReturn(zoomRange);
Float minZoom = cameraProperties.getScalerMinZoomRatio();
verify(mockCharacteristics, times(1)).get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE);
assertEquals(zoomRange.getLower(), minZoom);
}
@Test
public void getScalerGetScalerMaxZoomRatioTest() {
Range zoomRange = mock(Range.class);
when(mockCharacteristics.get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE))
.thenReturn(zoomRange);
Float maxZoom = cameraProperties.getScalerMaxZoomRatio();
verify(mockCharacteristics, times(1)).get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE);
assertEquals(zoomRange.getUpper(), maxZoom);
}
@Test
public void getSensorInfoActiveArraySizeTest() {
Rect expectedArraySize = mock(Rect.class);
when(mockCharacteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE))
.thenReturn(expectedArraySize);
Rect actualArraySize = cameraProperties.getSensorInfoActiveArraySize();
verify(mockCharacteristics, times(1)).get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
assertEquals(actualArraySize, expectedArraySize);
}
@Test
public void getSensorInfoPixelArraySizeTest() {
Size expectedArraySize = mock(Size.class);
when(mockCharacteristics.get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE))
.thenReturn(expectedArraySize);
Size actualArraySize = cameraProperties.getSensorInfoPixelArraySize();
verify(mockCharacteristics, times(1)).get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE);
assertEquals(actualArraySize, expectedArraySize);
}
@Test
public void getSensorInfoPreCorrectionActiveArraySize() {
Rect expectedArraySize = mock(Rect.class);
when(mockCharacteristics.get(
CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE))
.thenReturn(expectedArraySize);
Rect actualArraySize = cameraProperties.getSensorInfoPreCorrectionActiveArraySize();
verify(mockCharacteristics, times(1))
.get(CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE);
assertEquals(actualArraySize, expectedArraySize);
}
@Test
public void getSensorOrientationTest() {
int expectedOrientation = 42;
when(mockCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION))
.thenReturn(expectedOrientation);
int actualOrientation = cameraProperties.getSensorOrientation();
verify(mockCharacteristics, times(1)).get(CameraCharacteristics.SENSOR_ORIENTATION);
assertEquals(actualOrientation, expectedOrientation);
}
@Test
public void getHardwareLevelTest() {
int expectedLevel = 42;
when(mockCharacteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL))
.thenReturn(expectedLevel);
int actualLevel = cameraProperties.getHardwareLevel();
verify(mockCharacteristics, times(1)).get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
assertEquals(actualLevel, expectedLevel);
}
@Test
public void getAvailableNoiseReductionModesTest() {
int[] expectedReductionModes = new int[] {0, 1, 2};
when(mockCharacteristics.get(
CameraCharacteristics.NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES))
.thenReturn(expectedReductionModes);
int[] actualReductionModes = cameraProperties.getAvailableNoiseReductionModes();
verify(mockCharacteristics, times(1))
.get(CameraCharacteristics.NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES);
assertEquals(actualReductionModes, expectedReductionModes);
}
}
| plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraPropertiesImplTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraPropertiesImplTest.java",
"repo_id": "plugins",
"token_count": 3839
} | 1,191 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.focuspoint;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.params.MeteringRectangle;
import android.util.Size;
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.CameraRegionUtils;
import io.flutter.plugins.camera.features.Point;
import io.flutter.plugins.camera.features.sensororientation.DeviceOrientationManager;
import io.flutter.plugins.camera.features.sensororientation.SensorOrientationFeature;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
public class FocusPointFeatureTest {
Size mockCameraBoundaries;
SensorOrientationFeature mockSensorOrientationFeature;
DeviceOrientationManager mockDeviceOrientationManager;
@Before
public void setUp() {
this.mockCameraBoundaries = mock(Size.class);
when(this.mockCameraBoundaries.getWidth()).thenReturn(100);
when(this.mockCameraBoundaries.getHeight()).thenReturn(100);
mockSensorOrientationFeature = mock(SensorOrientationFeature.class);
mockDeviceOrientationManager = mock(DeviceOrientationManager.class);
when(mockSensorOrientationFeature.getDeviceOrientationManager())
.thenReturn(mockDeviceOrientationManager);
when(mockDeviceOrientationManager.getLastUIOrientation())
.thenReturn(PlatformChannel.DeviceOrientation.LANDSCAPE_LEFT);
}
@Test
public void getDebugName_shouldReturnTheNameOfTheFeature() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
assertEquals("FocusPointFeature", focusPointFeature.getDebugName());
}
@Test
public void getValue_shouldReturnNullIfNotSet() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
Point actualPoint = focusPointFeature.getValue();
assertNull(focusPointFeature.getValue());
}
@Test
public void getValue_shouldEchoTheSetValue() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
focusPointFeature.setCameraBoundaries(this.mockCameraBoundaries);
Point expectedPoint = new Point(0.0, 0.0);
focusPointFeature.setValue(expectedPoint);
Point actualPoint = focusPointFeature.getValue();
assertEquals(expectedPoint, actualPoint);
}
@Test
public void setValue_shouldResetPointWhenXCoordIsNull() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
focusPointFeature.setCameraBoundaries(this.mockCameraBoundaries);
focusPointFeature.setValue(new Point(null, 0.0));
assertNull(focusPointFeature.getValue());
}
@Test
public void setValue_shouldResetPointWhenYCoordIsNull() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
focusPointFeature.setCameraBoundaries(this.mockCameraBoundaries);
focusPointFeature.setValue(new Point(0.0, null));
assertNull(focusPointFeature.getValue());
}
@Test
public void setValue_shouldSetPointWhenValidCoordsAreSupplied() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
focusPointFeature.setCameraBoundaries(this.mockCameraBoundaries);
Point point = new Point(0.0, 0.0);
focusPointFeature.setValue(point);
assertEquals(point, focusPointFeature.getValue());
}
@Test
public void setValue_shouldDetermineMeteringRectangleWhenValidBoundariesAndCoordsAreSupplied() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
when(mockCameraProperties.getControlMaxRegionsAutoFocus()).thenReturn(1);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
Size mockedCameraBoundaries = mock(Size.class);
focusPointFeature.setCameraBoundaries(mockedCameraBoundaries);
try (MockedStatic<CameraRegionUtils> mockedCameraRegionUtils =
Mockito.mockStatic(CameraRegionUtils.class)) {
focusPointFeature.setValue(new Point(0.5, 0.5));
mockedCameraRegionUtils.verify(
() ->
CameraRegionUtils.convertPointToMeteringRectangle(
mockedCameraBoundaries,
0.5,
0.5,
PlatformChannel.DeviceOrientation.LANDSCAPE_LEFT),
times(1));
}
}
@Test(expected = AssertionError.class)
public void setValue_shouldThrowAssertionErrorWhenNoValidBoundariesAreSet() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
when(mockCameraProperties.getControlMaxRegionsAutoFocus()).thenReturn(1);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
try (MockedStatic<CameraRegionUtils> mockedCameraRegionUtils =
Mockito.mockStatic(CameraRegionUtils.class)) {
focusPointFeature.setValue(new Point(0.5, 0.5));
}
}
@Test
public void setValue_shouldNotDetermineMeteringRectangleWhenNullCoordsAreSet() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
when(mockCameraProperties.getControlMaxRegionsAutoFocus()).thenReturn(1);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
Size mockedCameraBoundaries = mock(Size.class);
focusPointFeature.setCameraBoundaries(mockedCameraBoundaries);
try (MockedStatic<CameraRegionUtils> mockedCameraRegionUtils =
Mockito.mockStatic(CameraRegionUtils.class)) {
focusPointFeature.setValue(null);
focusPointFeature.setValue(new Point(null, 0.5));
focusPointFeature.setValue(new Point(0.5, null));
mockedCameraRegionUtils.verifyNoInteractions();
}
}
@Test
public void
setCameraBoundaries_shouldDetermineMeteringRectangleWhenValidBoundariesAndCoordsAreSupplied() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
when(mockCameraProperties.getControlMaxRegionsAutoFocus()).thenReturn(1);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
focusPointFeature.setCameraBoundaries(this.mockCameraBoundaries);
focusPointFeature.setValue(new Point(0.5, 0.5));
Size mockedCameraBoundaries = mock(Size.class);
try (MockedStatic<CameraRegionUtils> mockedCameraRegionUtils =
Mockito.mockStatic(CameraRegionUtils.class)) {
focusPointFeature.setCameraBoundaries(mockedCameraBoundaries);
mockedCameraRegionUtils.verify(
() ->
CameraRegionUtils.convertPointToMeteringRectangle(
mockedCameraBoundaries,
0.5,
0.5,
PlatformChannel.DeviceOrientation.LANDSCAPE_LEFT),
times(1));
}
}
@Test
public void checkIsSupported_shouldReturnFalseWhenMaxRegionsIsNull() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
focusPointFeature.setCameraBoundaries(new Size(100, 100));
when(mockCameraProperties.getControlMaxRegionsAutoFocus()).thenReturn(null);
assertFalse(focusPointFeature.checkIsSupported());
}
@Test
public void checkIsSupported_shouldReturnFalseWhenMaxRegionsIsZero() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
focusPointFeature.setCameraBoundaries(new Size(100, 100));
when(mockCameraProperties.getControlMaxRegionsAutoFocus()).thenReturn(0);
assertFalse(focusPointFeature.checkIsSupported());
}
@Test
public void checkIsSupported_shouldReturnTrueWhenMaxRegionsIsBiggerThenZero() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
focusPointFeature.setCameraBoundaries(new Size(100, 100));
when(mockCameraProperties.getControlMaxRegionsAutoFocus()).thenReturn(1);
assertTrue(focusPointFeature.checkIsSupported());
}
@Test
public void updateBuilder_shouldReturnWhenCheckIsSupportedIsFalse() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
CaptureRequest.Builder mockCaptureRequestBuilder = mock(CaptureRequest.Builder.class);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
when(mockCameraProperties.getControlMaxRegionsAutoFocus()).thenReturn(0);
focusPointFeature.updateBuilder(mockCaptureRequestBuilder);
verify(mockCaptureRequestBuilder, never()).set(any(), any());
}
@Test
public void updateBuilder_shouldSetMeteringRectangleWhenValidBoundariesAndCoordsAreSupplied() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
when(mockCameraProperties.getControlMaxRegionsAutoFocus()).thenReturn(1);
CaptureRequest.Builder mockCaptureRequestBuilder = mock(CaptureRequest.Builder.class);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
Size mockedCameraBoundaries = mock(Size.class);
MeteringRectangle mockedMeteringRectangle = mock(MeteringRectangle.class);
try (MockedStatic<CameraRegionUtils> mockedCameraRegionUtils =
Mockito.mockStatic(CameraRegionUtils.class)) {
mockedCameraRegionUtils
.when(
() ->
CameraRegionUtils.convertPointToMeteringRectangle(
mockedCameraBoundaries,
0.5,
0.5,
PlatformChannel.DeviceOrientation.LANDSCAPE_LEFT))
.thenReturn(mockedMeteringRectangle);
focusPointFeature.setCameraBoundaries(mockedCameraBoundaries);
focusPointFeature.setValue(new Point(0.5, 0.5));
focusPointFeature.updateBuilder(mockCaptureRequestBuilder);
}
verify(mockCaptureRequestBuilder, times(1))
.set(CaptureRequest.CONTROL_AE_REGIONS, new MeteringRectangle[] {mockedMeteringRectangle});
}
@Test
public void updateBuilder_shouldNotSetMeteringRectangleWhenNoValidBoundariesAreSupplied() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
when(mockCameraProperties.getControlMaxRegionsAutoFocus()).thenReturn(1);
CaptureRequest.Builder mockCaptureRequestBuilder = mock(CaptureRequest.Builder.class);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
MeteringRectangle mockedMeteringRectangle = mock(MeteringRectangle.class);
focusPointFeature.updateBuilder(mockCaptureRequestBuilder);
verify(mockCaptureRequestBuilder, times(1)).set(any(), isNull());
}
@Test
public void updateBuilder_shouldNotSetMeteringRectangleWhenNoValidCoordsAreSupplied() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
when(mockCameraProperties.getControlMaxRegionsAutoFocus()).thenReturn(1);
CaptureRequest.Builder mockCaptureRequestBuilder = mock(CaptureRequest.Builder.class);
FocusPointFeature focusPointFeature =
new FocusPointFeature(mockCameraProperties, mockSensorOrientationFeature);
focusPointFeature.setCameraBoundaries(this.mockCameraBoundaries);
focusPointFeature.setValue(null);
focusPointFeature.updateBuilder(mockCaptureRequestBuilder);
focusPointFeature.setValue(new Point(0d, null));
focusPointFeature.updateBuilder(mockCaptureRequestBuilder);
focusPointFeature.setValue(new Point(null, 0d));
focusPointFeature.updateBuilder(mockCaptureRequestBuilder);
verify(mockCaptureRequestBuilder, times(3)).set(any(), isNull());
}
}
| plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/focuspoint/FocusPointFeatureTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/focuspoint/FocusPointFeatureTest.java",
"repo_id": "plugins",
"token_count": 4401
} | 1,192 |
## NEXT
* Creates camera_android_camerax plugin for development.
* Adds CameraInfo class and removes unnecessary code from plugin.
* Adds CameraSelector class.
* Adds ProcessCameraProvider class.
* Bump CameraX version to 1.3.0-alpha02.
* Adds Camera and UseCase classes, along with methods for binding UseCases to a lifecycle with the ProcessCameraProvider.
* Bump CameraX version to 1.3.0-alpha03 and Kotlin version to 1.8.0.
* Changes instance manager to allow the separate creation of identical objects.
* Adds Preview and Surface classes, along with other methods needed to implement camera preview.
* Adds implementation of availableCameras().
* Implements camera preview, createCamera, initializeCamera, onCameraError, onDeviceOrientationChanged, and onCameraInitialized.
* Adds integration test to plugin.
| plugins/packages/camera/camera_android_camerax/CHANGELOG.md/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 199
} | 1,193 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.Nullable;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.WeakHashMap;
/**
* Maintains instances used to communicate with the corresponding objects in Dart.
*
* <p>When an instance is added with an identifier, either can be used to retrieve the other.
*
* <p>Added instances are added as a weak reference and a strong reference. When the strong
* reference is removed with `{@link #remove(long)}` and the weak reference is deallocated, the
* `finalizationListener` is made with the instance's identifier. However, if the strong reference
* is removed and then the identifier is retrieved with the intention to pass the identifier to Dart
* (e.g. calling {@link #getIdentifierForStrongReference(Object)}), the strong reference to the
* instance is recreated. The strong reference will then need to be removed manually again.
*/
@SuppressWarnings("unchecked")
public class InstanceManager {
// Identifiers are locked to a specific range to avoid collisions with objects
// created simultaneously from Dart.
// Host uses identifiers >= 2^16 and Dart is expected to use values n where,
// 0 <= n < 2^16.
private static final long MIN_HOST_CREATED_IDENTIFIER = 65536;
private static final long CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL = 30000;
/** Interface for listening when a weak reference of an instance is removed from the manager. */
public interface FinalizationListener {
void onFinalize(long identifier);
}
private final WeakHashMap<Object, Long> identifiers = new WeakHashMap<>();
private final HashMap<Long, WeakReference<Object>> weakInstances = new HashMap<>();
private final HashMap<Long, Object> strongInstances = new HashMap<>();
private final ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
private final HashMap<WeakReference<Object>, Long> weakReferencesToIdentifiers = new HashMap<>();
private final Handler handler = new Handler(Looper.getMainLooper());
private final FinalizationListener finalizationListener;
private long nextIdentifier = MIN_HOST_CREATED_IDENTIFIER;
private boolean isClosed = false;
/**
* Instantiate a new manager.
*
* <p>When the manager is no longer needed, {@link #close()} must be called.
*
* @param finalizationListener the listener for garbage collected weak references.
* @return a new `InstanceManager`.
*/
public static InstanceManager open(FinalizationListener finalizationListener) {
return new InstanceManager(finalizationListener);
}
private InstanceManager(FinalizationListener finalizationListener) {
this.finalizationListener = finalizationListener;
handler.postDelayed(
this::releaseAllFinalizedInstances, CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL);
}
/**
* Removes `identifier` and its associated strongly referenced instance, if present, from the
* manager.
*
* @param identifier the identifier paired to an instance.
* @param <T> the expected return type.
* @return the removed instance if the manager contains the given identifier, otherwise null.
*/
@Nullable
public <T> T remove(long identifier) {
assertManagerIsNotClosed();
return (T) strongInstances.remove(identifier);
}
/**
* Retrieves the identifier paired with an instance.
*
* <p>If the manager contains `instance`, as a strong or weak reference, the strong reference to
* `instance` will be recreated and will need to be removed again with {@link #remove(long)}.
*
* @param instance an instance that may be stored in the manager.
* @return the identifier associated with `instance` if the manager contains the value, otherwise
* null.
*/
@Nullable
public Long getIdentifierForStrongReference(Object instance) {
assertManagerIsNotClosed();
final Long identifier = identifiers.get(instance);
if (identifier != null) {
strongInstances.put(identifier, instance);
}
return identifier;
}
/**
* Adds a new instance that was instantiated from Dart.
*
* <p>If an instance or identifier has already been added, it will be replaced by the new values.
* The Dart InstanceManager is considered the source of truth and has the capability to overwrite
* stored pairs in response to hot restarts.
*
* @param instance the instance to be stored.
* @param identifier the identifier to be paired with instance. This value must be >= 0.
*/
public void addDartCreatedInstance(Object instance, long identifier) {
assertManagerIsNotClosed();
addInstance(instance, identifier);
}
/**
* Adds a new instance that was instantiated from the host platform.
*
* <p>If an instance has already been added, this will replace it. {@code #containsInstance} can
* be used to check if the object has already been added to avoid this.
*
* @param instance the instance to be stored.
* @return the unique identifier stored with instance.
*/
public long addHostCreatedInstance(Object instance) {
assertManagerIsNotClosed();
final long identifier = nextIdentifier++;
addInstance(instance, identifier);
return identifier;
}
/**
* Retrieves the instance associated with identifier.
*
* @param identifier the identifier paired to an instance.
* @param <T> the expected return type.
* @return the instance associated with `identifier` if the manager contains the value, otherwise
* null.
*/
@Nullable
public <T> T getInstance(long identifier) {
assertManagerIsNotClosed();
final WeakReference<T> instance = (WeakReference<T>) weakInstances.get(identifier);
if (instance != null) {
return instance.get();
}
return (T) strongInstances.get(identifier);
}
/**
* Returns whether this manager contains the given `instance`.
*
* @param instance the instance whose presence in this manager is to be tested.
* @return whether this manager contains the given `instance`.
*/
public boolean containsInstance(Object instance) {
assertManagerIsNotClosed();
return identifiers.containsKey(instance);
}
/**
* Closes the manager and releases resources.
*
* <p>Calling a method after calling this one will throw an {@link AssertionError}. This method
* excluded.
*/
public void close() {
handler.removeCallbacks(this::releaseAllFinalizedInstances);
isClosed = true;
}
private void releaseAllFinalizedInstances() {
WeakReference<Object> reference;
while ((reference = (WeakReference<Object>) referenceQueue.poll()) != null) {
final Long identifier = weakReferencesToIdentifiers.remove(reference);
if (identifier != null) {
weakInstances.remove(identifier);
strongInstances.remove(identifier);
finalizationListener.onFinalize(identifier);
}
}
handler.postDelayed(
this::releaseAllFinalizedInstances, CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL);
}
private void addInstance(Object instance, long identifier) {
if (identifier < 0) {
throw new IllegalArgumentException("Identifier must be >= 0.");
}
final WeakReference<Object> weakReference = new WeakReference<>(instance, referenceQueue);
identifiers.put(instance, identifier);
weakInstances.put(identifier, weakReference);
weakReferencesToIdentifiers.put(weakReference, identifier);
strongInstances.put(identifier, instance);
}
private void assertManagerIsNotClosed() {
if (isClosed) {
throw new AssertionError("Manager has already been closed.");
}
}
}
| plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/InstanceManager.java/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/InstanceManager.java",
"repo_id": "plugins",
"token_count": 2282
} | 1,194 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import io.flutter.embedding.engine.systemchannels.PlatformChannel.DeviceOrientation;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.CameraPermissionsManager.PermissionsRegistry;
import io.flutter.plugins.camerax.CameraPermissionsManager.ResultCallback;
import io.flutter.plugins.camerax.DeviceOrientationManager.DeviceOrientationChangeCallback;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraPermissionsErrorData;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.Result;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.SystemServicesFlutterApi.Reply;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class SystemServicesTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public InstanceManager mockInstanceManager;
@Test
public void requestCameraPermissionsTest() {
final SystemServicesHostApiImpl systemServicesHostApi =
new SystemServicesHostApiImpl(mockBinaryMessenger, mockInstanceManager);
final CameraXProxy mockCameraXProxy = mock(CameraXProxy.class);
final CameraPermissionsManager mockCameraPermissionsManager =
mock(CameraPermissionsManager.class);
final Activity mockActivity = mock(Activity.class);
final PermissionsRegistry mockPermissionsRegistry = mock(PermissionsRegistry.class);
final Result<CameraPermissionsErrorData> mockResult = mock(Result.class);
final Boolean enableAudio = false;
systemServicesHostApi.cameraXProxy = mockCameraXProxy;
systemServicesHostApi.setActivity(mockActivity);
systemServicesHostApi.setPermissionsRegistry(mockPermissionsRegistry);
when(mockCameraXProxy.createCameraPermissionsManager())
.thenReturn(mockCameraPermissionsManager);
final ArgumentCaptor<ResultCallback> resultCallbackCaptor =
ArgumentCaptor.forClass(ResultCallback.class);
systemServicesHostApi.requestCameraPermissions(enableAudio, mockResult);
// Test camera permissions are requested.
verify(mockCameraPermissionsManager)
.requestPermissions(
eq(mockActivity),
eq(mockPermissionsRegistry),
eq(enableAudio),
resultCallbackCaptor.capture());
ResultCallback resultCallback = (ResultCallback) resultCallbackCaptor.getValue();
// Test no error data is sent upon permissions request success.
resultCallback.onResult(null, null);
verify(mockResult).success(null);
// Test expected error data is sent upon permissions request failure.
final String testErrorCode = "TestErrorCode";
final String testErrorDescription = "Test error description.";
final ArgumentCaptor<CameraPermissionsErrorData> cameraPermissionsErrorDataCaptor =
ArgumentCaptor.forClass(CameraPermissionsErrorData.class);
resultCallback.onResult(testErrorCode, testErrorDescription);
verify(mockResult, times(2)).success(cameraPermissionsErrorDataCaptor.capture());
CameraPermissionsErrorData cameraPermissionsErrorData =
cameraPermissionsErrorDataCaptor.getValue();
assertEquals(cameraPermissionsErrorData.getErrorCode(), testErrorCode);
assertEquals(cameraPermissionsErrorData.getDescription(), testErrorDescription);
}
@Test
public void deviceOrientationChangeTest() {
final SystemServicesHostApiImpl systemServicesHostApi =
new SystemServicesHostApiImpl(mockBinaryMessenger, mockInstanceManager);
final CameraXProxy mockCameraXProxy = mock(CameraXProxy.class);
final Activity mockActivity = mock(Activity.class);
final DeviceOrientationManager mockDeviceOrientationManager =
mock(DeviceOrientationManager.class);
final Boolean isFrontFacing = true;
final int sensorOrientation = 90;
SystemServicesFlutterApiImpl systemServicesFlutterApi =
mock(SystemServicesFlutterApiImpl.class);
systemServicesHostApi.systemServicesFlutterApi = systemServicesFlutterApi;
systemServicesHostApi.cameraXProxy = mockCameraXProxy;
systemServicesHostApi.setActivity(mockActivity);
when(mockCameraXProxy.createDeviceOrientationManager(
eq(mockActivity),
eq(isFrontFacing),
eq(sensorOrientation),
any(DeviceOrientationChangeCallback.class)))
.thenReturn(mockDeviceOrientationManager);
final ArgumentCaptor<DeviceOrientationChangeCallback> deviceOrientationChangeCallbackCaptor =
ArgumentCaptor.forClass(DeviceOrientationChangeCallback.class);
systemServicesHostApi.startListeningForDeviceOrientationChange(
isFrontFacing, Long.valueOf(sensorOrientation));
// Test callback method defined in Flutter API is called when device orientation changes.
verify(mockCameraXProxy)
.createDeviceOrientationManager(
eq(mockActivity),
eq(isFrontFacing),
eq(sensorOrientation),
deviceOrientationChangeCallbackCaptor.capture());
DeviceOrientationChangeCallback deviceOrientationChangeCallback =
deviceOrientationChangeCallbackCaptor.getValue();
deviceOrientationChangeCallback.onChange(DeviceOrientation.PORTRAIT_DOWN);
verify(systemServicesFlutterApi)
.sendDeviceOrientationChangedEvent(
eq(DeviceOrientation.PORTRAIT_DOWN.toString()), any(Reply.class));
// Test that the DeviceOrientationManager starts listening for device orientation changes.
verify(mockDeviceOrientationManager).start();
}
}
| plugins/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/SystemServicesTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/SystemServicesTest.java",
"repo_id": "plugins",
"token_count": 1986
} | 1,195 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'camera.dart';
import 'camera_info.dart';
import 'camera_selector.dart';
import 'camerax_library.g.dart';
import 'java_object.dart';
import 'process_camera_provider.dart';
import 'system_services.dart';
/// Handles initialization of Flutter APIs for the Android CameraX library.
class AndroidCameraXCameraFlutterApis {
/// Creates a [AndroidCameraXCameraFlutterApis].
AndroidCameraXCameraFlutterApis({
JavaObjectFlutterApiImpl? javaObjectFlutterApi,
CameraFlutterApiImpl? cameraFlutterApi,
CameraInfoFlutterApiImpl? cameraInfoFlutterApi,
CameraSelectorFlutterApiImpl? cameraSelectorFlutterApi,
ProcessCameraProviderFlutterApiImpl? processCameraProviderFlutterApi,
SystemServicesFlutterApiImpl? systemServicesFlutterApi,
}) {
this.javaObjectFlutterApi =
javaObjectFlutterApi ?? JavaObjectFlutterApiImpl();
this.cameraInfoFlutterApi =
cameraInfoFlutterApi ?? CameraInfoFlutterApiImpl();
this.cameraSelectorFlutterApi =
cameraSelectorFlutterApi ?? CameraSelectorFlutterApiImpl();
this.processCameraProviderFlutterApi = processCameraProviderFlutterApi ??
ProcessCameraProviderFlutterApiImpl();
this.cameraFlutterApi = cameraFlutterApi ?? CameraFlutterApiImpl();
this.systemServicesFlutterApi =
systemServicesFlutterApi ?? SystemServicesFlutterApiImpl();
}
static bool _haveBeenSetUp = false;
/// Mutable instance containing all Flutter Apis for Android CameraX Camera.
///
/// This should only be changed for testing purposes.
static AndroidCameraXCameraFlutterApis instance =
AndroidCameraXCameraFlutterApis();
/// Handles callbacks methods for the native Java Object class.
late final JavaObjectFlutterApi javaObjectFlutterApi;
/// Flutter Api for [CameraInfo].
late final CameraInfoFlutterApiImpl cameraInfoFlutterApi;
/// Flutter Api for [CameraSelector].
late final CameraSelectorFlutterApiImpl cameraSelectorFlutterApi;
/// Flutter Api for [ProcessCameraProvider].
late final ProcessCameraProviderFlutterApiImpl
processCameraProviderFlutterApi;
/// Flutter Api for [Camera].
late final CameraFlutterApiImpl cameraFlutterApi;
/// Flutter Api for [SystemServices].
late final SystemServicesFlutterApiImpl systemServicesFlutterApi;
/// Ensures all the Flutter APIs have been setup to receive calls from native code.
void ensureSetUp() {
if (!_haveBeenSetUp) {
JavaObjectFlutterApi.setup(javaObjectFlutterApi);
CameraInfoFlutterApi.setup(cameraInfoFlutterApi);
CameraSelectorFlutterApi.setup(cameraSelectorFlutterApi);
ProcessCameraProviderFlutterApi.setup(processCameraProviderFlutterApi);
CameraFlutterApi.setup(cameraFlutterApi);
SystemServicesFlutterApi.setup(systemServicesFlutterApi);
_haveBeenSetUp = true;
}
}
}
| plugins/packages/camera/camera_android_camerax/lib/src/android_camera_camerax_flutter_api_impls.dart/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/lib/src/android_camera_camerax_flutter_api_impls.dart",
"repo_id": "plugins",
"token_count": 973
} | 1,196 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_android_camerax/src/camera_info.dart';
import 'package:camera_android_camerax/src/camerax_library.g.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'camera_info_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[TestCameraInfoHostApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('CameraInfo', () {
tearDown(() => TestCameraInfoHostApi.setup(null));
test('getSensorRotationDegreesTest', () async {
final MockTestCameraInfoHostApi mockApi = MockTestCameraInfoHostApi();
TestCameraInfoHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraInfo cameraInfo = CameraInfo.detached(
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(
cameraInfo,
0,
onCopy: (_) => CameraInfo.detached(),
);
when(mockApi.getSensorRotationDegrees(
instanceManager.getIdentifier(cameraInfo)))
.thenReturn(90);
expect(await cameraInfo.getSensorRotationDegrees(), equals(90));
verify(mockApi.getSensorRotationDegrees(0));
});
test('flutterApiCreateTest', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraInfoFlutterApi flutterApi = CameraInfoFlutterApiImpl(
instanceManager: instanceManager,
);
flutterApi.create(0);
expect(
instanceManager.getInstanceWithWeakReference(0), isA<CameraInfo>());
});
});
}
| plugins/packages/camera/camera_android_camerax/test/camera_info_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/test/camera_info_test.dart",
"repo_id": "plugins",
"token_count": 744
} | 1,197 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import camera_avfoundation;
@import XCTest;
@import AVFoundation;
#import <OCMock/OCMock.h>
@interface FLTCam : NSObject <FlutterTexture,
AVCaptureVideoDataOutputSampleBufferDelegate,
AVCaptureAudioDataOutputSampleBufferDelegate>
- (CGPoint)getCGPointForCoordsWithOrientation:(UIDeviceOrientation)orientation
x:(double)x
y:(double)y;
@end
@interface CameraUtilTests : XCTestCase
@property(readonly, nonatomic) FLTCam *camera;
@end
@implementation CameraUtilTests
- (void)setUp {
_camera = [[FLTCam alloc] init];
}
- (void)testGetCGPointForCoordsWithOrientation_ShouldRotateCoords {
CGPoint point;
point = [_camera getCGPointForCoordsWithOrientation:UIDeviceOrientationLandscapeLeft x:1 y:1];
XCTAssertTrue(CGPointEqualToPoint(point, CGPointMake(1, 1)),
@"Resulting coordinates are invalid.");
point = [_camera getCGPointForCoordsWithOrientation:UIDeviceOrientationPortrait x:0 y:1];
XCTAssertTrue(CGPointEqualToPoint(point, CGPointMake(1, 1)),
@"Resulting coordinates are invalid.");
point = [_camera getCGPointForCoordsWithOrientation:UIDeviceOrientationLandscapeRight x:0 y:0];
XCTAssertTrue(CGPointEqualToPoint(point, CGPointMake(1, 1)),
@"Resulting coordinates are invalid.");
point = [_camera getCGPointForCoordsWithOrientation:UIDeviceOrientationPortraitUpsideDown
x:1
y:0];
XCTAssertTrue(CGPointEqualToPoint(point, CGPointMake(1, 1)),
@"Resulting coordinates are invalid.");
}
@end
| plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraUtilTests.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraUtilTests.m",
"repo_id": "plugins",
"token_count": 849
} | 1,198 |
name: camera_example
description: Demonstrates how to use the camera plugin.
publish_to: none
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
camera_avfoundation:
# When depending on this package from a real application you should use:
# camera_avfoundation: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
camera_platform_interface: ^2.2.0
flutter:
sdk: flutter
path_provider: ^2.0.0
quiver: ^3.0.0
video_player: ^2.1.4
dev_dependencies:
build_runner: ^2.1.10
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| plugins/packages/camera/camera_avfoundation/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 325
} | 1,199 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FLTSavePhotoDelegate.h"
/**
API exposed for unit tests.
*/
@interface FLTSavePhotoDelegate ()
/// The completion handler block for capture and save photo operations.
/// Can be called from either main queue or IO queue.
/// Exposed for unit tests to manually trigger the completion.
@property(readonly, nonatomic) FLTSavePhotoDelegateCompletionHandler completionHandler;
/// Handler to write captured photo data into a file.
/// @param error the capture error.
/// @param photoDataProvider a closure that provides photo data.
- (void)handlePhotoCaptureResultWithError:(NSError *)error
photoDataProvider:(NSData * (^)(void))photoDataProvider;
@end
| plugins/packages/camera/camera_avfoundation/ios/Classes/FLTSavePhotoDelegate_Test.h/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/FLTSavePhotoDelegate_Test.h",
"repo_id": "plugins",
"token_count": 236
} | 1,200 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
/// The direction the camera is facing.
enum CameraLensDirection {
/// Front facing camera (a user looking at the screen is seen by the camera).
front,
/// Back facing camera (a user looking at the screen is not seen by the camera).
back,
/// External camera which may not be mounted to the device.
external,
}
/// Properties of a camera device.
@immutable
class CameraDescription {
/// Creates a new camera description with the given properties.
const CameraDescription({
required this.name,
required this.lensDirection,
required this.sensorOrientation,
});
/// The name of the camera device.
final String name;
/// The direction the camera is facing.
final CameraLensDirection lensDirection;
/// Clockwise angle through which the output image needs to be rotated to be upright on the device screen in its native orientation.
///
/// **Range of valid values:**
/// 0, 90, 180, 270
///
/// On Android, also defines the direction of rolling shutter readout, which
/// is from top to bottom in the sensor's coordinate system.
final int sensorOrientation;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is CameraDescription &&
runtimeType == other.runtimeType &&
name == other.name &&
lensDirection == other.lensDirection;
@override
int get hashCode => Object.hash(name, lensDirection);
@override
String toString() {
return '${objectRuntimeType(this, 'CameraDescription')}('
'$name, $lensDirection, $sensorOrientation)';
}
}
| plugins/packages/camera/camera_platform_interface/lib/src/types/camera_description.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/lib/src/types/camera_description.dart",
"repo_id": "plugins",
"token_count": 523
} | 1,201 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#104231)
// ignore: unnecessary_import
import 'dart:typed_data';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:camera_platform_interface/src/method_channel/type_conversion.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('CameraImageData can be created', () {
final CameraImageData cameraImage =
cameraImageFromPlatformData(<dynamic, dynamic>{
'format': 35,
'height': 1,
'width': 4,
'lensAperture': 1.8,
'sensorExposureTime': 9991324,
'sensorSensitivity': 92.0,
'planes': <dynamic>[
<dynamic, dynamic>{
'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
'bytesPerPixel': 1,
'bytesPerRow': 4,
'height': 1,
'width': 4
}
]
});
expect(cameraImage.height, 1);
expect(cameraImage.width, 4);
expect(cameraImage.format.group, ImageFormatGroup.yuv420);
expect(cameraImage.planes.length, 1);
});
test('CameraImageData has ImageFormatGroup.yuv420 for iOS', () {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
final CameraImageData cameraImage =
cameraImageFromPlatformData(<dynamic, dynamic>{
'format': 875704438,
'height': 1,
'width': 4,
'lensAperture': 1.8,
'sensorExposureTime': 9991324,
'sensorSensitivity': 92.0,
'planes': <dynamic>[
<dynamic, dynamic>{
'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
'bytesPerPixel': 1,
'bytesPerRow': 4,
'height': 1,
'width': 4
}
]
});
expect(cameraImage.format.group, ImageFormatGroup.yuv420);
});
test('CameraImageData has ImageFormatGroup.yuv420 for Android', () {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
final CameraImageData cameraImage =
cameraImageFromPlatformData(<dynamic, dynamic>{
'format': 35,
'height': 1,
'width': 4,
'lensAperture': 1.8,
'sensorExposureTime': 9991324,
'sensorSensitivity': 92.0,
'planes': <dynamic>[
<dynamic, dynamic>{
'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
'bytesPerPixel': 1,
'bytesPerRow': 4,
'height': 1,
'width': 4
}
]
});
expect(cameraImage.format.group, ImageFormatGroup.yuv420);
});
}
| plugins/packages/camera/camera_platform_interface/test/method_channel/type_conversion_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/test/method_channel/type_conversion_test.dart",
"repo_id": "plugins",
"token_count": 1152
} | 1,202 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:html';
import 'package:camera_web/src/types/types.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'helpers/helpers.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('CameraErrorCode', () {
group('toString returns a correct type for', () {
testWidgets('notSupported', (WidgetTester tester) async {
expect(
CameraErrorCode.notSupported.toString(),
equals('cameraNotSupported'),
);
});
testWidgets('notFound', (WidgetTester tester) async {
expect(
CameraErrorCode.notFound.toString(),
equals('cameraNotFound'),
);
});
testWidgets('notReadable', (WidgetTester tester) async {
expect(
CameraErrorCode.notReadable.toString(),
equals('cameraNotReadable'),
);
});
testWidgets('overconstrained', (WidgetTester tester) async {
expect(
CameraErrorCode.overconstrained.toString(),
equals('cameraOverconstrained'),
);
});
testWidgets('permissionDenied', (WidgetTester tester) async {
expect(
CameraErrorCode.permissionDenied.toString(),
equals('CameraAccessDenied'),
);
});
testWidgets('type', (WidgetTester tester) async {
expect(
CameraErrorCode.type.toString(),
equals('cameraType'),
);
});
testWidgets('abort', (WidgetTester tester) async {
expect(
CameraErrorCode.abort.toString(),
equals('cameraAbort'),
);
});
testWidgets('security', (WidgetTester tester) async {
expect(
CameraErrorCode.security.toString(),
equals('cameraSecurity'),
);
});
testWidgets('missingMetadata', (WidgetTester tester) async {
expect(
CameraErrorCode.missingMetadata.toString(),
equals('cameraMissingMetadata'),
);
});
testWidgets('orientationNotSupported', (WidgetTester tester) async {
expect(
CameraErrorCode.orientationNotSupported.toString(),
equals('orientationNotSupported'),
);
});
testWidgets('torchModeNotSupported', (WidgetTester tester) async {
expect(
CameraErrorCode.torchModeNotSupported.toString(),
equals('torchModeNotSupported'),
);
});
testWidgets('zoomLevelNotSupported', (WidgetTester tester) async {
expect(
CameraErrorCode.zoomLevelNotSupported.toString(),
equals('zoomLevelNotSupported'),
);
});
testWidgets('zoomLevelInvalid', (WidgetTester tester) async {
expect(
CameraErrorCode.zoomLevelInvalid.toString(),
equals('zoomLevelInvalid'),
);
});
testWidgets('notStarted', (WidgetTester tester) async {
expect(
CameraErrorCode.notStarted.toString(),
equals('cameraNotStarted'),
);
});
testWidgets('videoRecordingNotStarted', (WidgetTester tester) async {
expect(
CameraErrorCode.videoRecordingNotStarted.toString(),
equals('videoRecordingNotStarted'),
);
});
testWidgets('unknown', (WidgetTester tester) async {
expect(
CameraErrorCode.unknown.toString(),
equals('cameraUnknown'),
);
});
group('fromMediaError', () {
testWidgets('with aborted error code', (WidgetTester tester) async {
expect(
CameraErrorCode.fromMediaError(
FakeMediaError(MediaError.MEDIA_ERR_ABORTED),
).toString(),
equals('mediaErrorAborted'),
);
});
testWidgets('with network error code', (WidgetTester tester) async {
expect(
CameraErrorCode.fromMediaError(
FakeMediaError(MediaError.MEDIA_ERR_NETWORK),
).toString(),
equals('mediaErrorNetwork'),
);
});
testWidgets('with decode error code', (WidgetTester tester) async {
expect(
CameraErrorCode.fromMediaError(
FakeMediaError(MediaError.MEDIA_ERR_DECODE),
).toString(),
equals('mediaErrorDecode'),
);
});
testWidgets('with source not supported error code',
(WidgetTester tester) async {
expect(
CameraErrorCode.fromMediaError(
FakeMediaError(MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED),
).toString(),
equals('mediaErrorSourceNotSupported'),
);
});
testWidgets('with unknown error code', (WidgetTester tester) async {
expect(
CameraErrorCode.fromMediaError(
FakeMediaError(5),
).toString(),
equals('mediaErrorUnknown'),
);
});
});
});
});
}
| plugins/packages/camera/camera_web/example/integration_test/camera_error_code_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_web/example/integration_test/camera_error_code_test.dart",
"repo_id": "plugins",
"token_count": 2335
} | 1,203 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:html' as html;
import 'dart:ui';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'camera_service.dart';
import 'shims/dart_ui.dart' as ui;
import 'types/types.dart';
String _getViewType(int cameraId) => 'plugins.flutter.io/camera_$cameraId';
/// A camera initialized from the media devices in the current window.
/// See: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices
///
/// The obtained camera stream is constrained by [options] and fetched
/// with [CameraService.getMediaStreamForOptions].
///
/// The camera stream is displayed in the [videoElement] wrapped in the
/// [divElement] to avoid overriding the custom styles applied to
/// the video element in [_applyDefaultVideoStyles].
/// See: https://github.com/flutter/flutter/issues/79519
///
/// The camera stream can be played/stopped by calling [play]/[stop],
/// may capture a picture by calling [takePicture] or capture a video
/// by calling [startVideoRecording], [pauseVideoRecording],
/// [resumeVideoRecording] or [stopVideoRecording].
///
/// The camera zoom may be adjusted with [setZoomLevel]. The provided
/// zoom level must be a value in the range of [getMinZoomLevel] to
/// [getMaxZoomLevel].
///
/// The [textureId] is used to register a camera view with the id
/// defined by [_getViewType].
class Camera {
/// Creates a new instance of [Camera]
/// with the given [textureId] and optional
/// [options] and [window].
Camera({
required this.textureId,
required CameraService cameraService,
this.options = const CameraOptions(),
}) : _cameraService = cameraService;
// A torch mode constraint name.
// See: https://w3c.github.io/mediacapture-image/#dom-mediatracksupportedconstraints-torch
static const String _torchModeKey = 'torch';
/// The texture id used to register the camera view.
final int textureId;
/// The camera options used to initialize a camera, empty by default.
final CameraOptions options;
/// The video element that displays the camera stream.
/// Initialized in [initialize].
late final html.VideoElement videoElement;
/// The wrapping element for the [videoElement] to avoid overriding
/// the custom styles applied in [_applyDefaultVideoStyles].
/// Initialized in [initialize].
late final html.DivElement divElement;
/// The camera stream displayed in the [videoElement].
/// Initialized in [initialize] and [play], reset in [stop].
html.MediaStream? stream;
/// The stream of the camera video tracks that have ended playing.
///
/// This occurs when there is no more camera stream data, e.g.
/// the user has stopped the stream by changing the camera device,
/// revoked the camera permissions or ejected the camera device.
///
/// MediaStreamTrack.onended:
/// https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack/onended
Stream<html.MediaStreamTrack> get onEnded => onEndedController.stream;
/// The stream controller for the [onEnded] stream.
@visibleForTesting
final StreamController<html.MediaStreamTrack> onEndedController =
StreamController<html.MediaStreamTrack>.broadcast();
StreamSubscription<html.Event>? _onEndedSubscription;
/// The stream of the camera video recording errors.
///
/// This occurs when the video recording is not allowed or an unsupported
/// codec is used.
///
/// MediaRecorder.error:
/// https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/error_event
Stream<html.ErrorEvent> get onVideoRecordingError =>
videoRecordingErrorController.stream;
/// The stream controller for the [onVideoRecordingError] stream.
@visibleForTesting
final StreamController<html.ErrorEvent> videoRecordingErrorController =
StreamController<html.ErrorEvent>.broadcast();
StreamSubscription<html.Event>? _onVideoRecordingErrorSubscription;
/// The camera flash mode.
@visibleForTesting
FlashMode? flashMode;
/// The camera service used to get the media stream for the camera.
final CameraService _cameraService;
/// The current browser window used to access media devices.
@visibleForTesting
html.Window? window = html.window;
/// The recorder used to record a video from the camera.
@visibleForTesting
html.MediaRecorder? mediaRecorder;
/// Whether the video of the given type is supported.
@visibleForTesting
bool Function(String) isVideoTypeSupported =
html.MediaRecorder.isTypeSupported;
/// The list of consecutive video data files recorded with [mediaRecorder].
final List<html.Blob> _videoData = <html.Blob>[];
/// Completes when the video recording is stopped/finished.
Completer<XFile>? _videoAvailableCompleter;
/// A data listener fired when a new part of video data is available.
void Function(html.Event)? _videoDataAvailableListener;
/// A listener fired when a video recording is stopped.
void Function(html.Event)? _videoRecordingStoppedListener;
/// A builder to merge a list of blobs into a single blob.
@visibleForTesting
// TODO(stuartmorgan): Remove this 'ignore' once we don't analyze using 2.10
// any more. It's a false positive that is fixed in later versions.
// ignore: prefer_function_declarations_over_variables
html.Blob Function(List<html.Blob> blobs, String type) blobBuilder =
(List<html.Blob> blobs, String type) => html.Blob(blobs, type);
/// The stream that emits a [VideoRecordedEvent] when a video recording is created.
Stream<VideoRecordedEvent> get onVideoRecordedEvent =>
videoRecorderController.stream;
/// The stream controller for the [onVideoRecordedEvent] stream.
@visibleForTesting
final StreamController<VideoRecordedEvent> videoRecorderController =
StreamController<VideoRecordedEvent>.broadcast();
/// Initializes the camera stream displayed in the [videoElement].
/// Registers the camera view with [textureId] under [_getViewType] type.
/// Emits the camera default video track on the [onEnded] stream when it ends.
Future<void> initialize() async {
stream = await _cameraService.getMediaStreamForOptions(
options,
cameraId: textureId,
);
videoElement = html.VideoElement();
divElement = html.DivElement()
..style.setProperty('object-fit', 'cover')
..append(videoElement);
ui.platformViewRegistry.registerViewFactory(
_getViewType(textureId),
(_) => divElement,
);
videoElement
..autoplay = false
..muted = true
..srcObject = stream
..setAttribute('playsinline', '');
_applyDefaultVideoStyles(videoElement);
final List<html.MediaStreamTrack> videoTracks = stream!.getVideoTracks();
if (videoTracks.isNotEmpty) {
final html.MediaStreamTrack defaultVideoTrack = videoTracks.first;
_onEndedSubscription = defaultVideoTrack.onEnded.listen((html.Event _) {
onEndedController.add(defaultVideoTrack);
});
}
}
/// Starts the camera stream.
///
/// Initializes the camera source if the camera was previously stopped.
Future<void> play() async {
if (videoElement.srcObject == null) {
stream = await _cameraService.getMediaStreamForOptions(
options,
cameraId: textureId,
);
videoElement.srcObject = stream;
}
await videoElement.play();
}
/// Pauses the camera stream on the current frame.
void pause() {
videoElement.pause();
}
/// Stops the camera stream and resets the camera source.
void stop() {
final List<html.MediaStreamTrack> videoTracks = stream!.getVideoTracks();
if (videoTracks.isNotEmpty) {
onEndedController.add(videoTracks.first);
}
final List<html.MediaStreamTrack>? tracks = stream?.getTracks();
if (tracks != null) {
for (final html.MediaStreamTrack track in tracks) {
track.stop();
}
}
videoElement.srcObject = null;
stream = null;
}
/// Captures a picture and returns the saved file in a JPEG format.
///
/// Enables the camera flash (torch mode) for a period of taking a picture
/// if the flash mode is either [FlashMode.auto] or [FlashMode.always].
Future<XFile> takePicture() async {
final bool shouldEnableTorchMode =
flashMode == FlashMode.auto || flashMode == FlashMode.always;
if (shouldEnableTorchMode) {
_setTorchMode(enabled: true);
}
final int videoWidth = videoElement.videoWidth;
final int videoHeight = videoElement.videoHeight;
final html.CanvasElement canvas =
html.CanvasElement(width: videoWidth, height: videoHeight);
final bool isBackCamera = getLensDirection() == CameraLensDirection.back;
// Flip the picture horizontally if it is not taken from a back camera.
if (!isBackCamera) {
canvas.context2D
..translate(videoWidth, 0)
..scale(-1, 1);
}
canvas.context2D
.drawImageScaled(videoElement, 0, 0, videoWidth, videoHeight);
final html.Blob blob = await canvas.toBlob('image/jpeg');
if (shouldEnableTorchMode) {
_setTorchMode(enabled: false);
}
return XFile(html.Url.createObjectUrl(blob));
}
/// Returns a size of the camera video based on its first video track size.
///
/// Returns [Size.zero] if the camera is missing a video track or
/// the video track does not include the width or height setting.
Size getVideoSize() {
final List<html.MediaStreamTrack> videoTracks =
videoElement.srcObject?.getVideoTracks() ?? <html.MediaStreamTrack>[];
if (videoTracks.isEmpty) {
return Size.zero;
}
final html.MediaStreamTrack defaultVideoTrack = videoTracks.first;
final Map<dynamic, dynamic> defaultVideoTrackSettings =
defaultVideoTrack.getSettings();
final double? width = defaultVideoTrackSettings['width'] as double?;
final double? height = defaultVideoTrackSettings['height'] as double?;
if (width != null && height != null) {
return Size(width, height);
} else {
return Size.zero;
}
}
/// Sets the camera flash mode to [mode] by modifying the camera
/// torch mode constraint.
///
/// The torch mode is enabled for [FlashMode.torch] and
/// disabled for [FlashMode.off].
///
/// For [FlashMode.auto] and [FlashMode.always] the torch mode is enabled
/// only for a period of taking a picture in [takePicture].
///
/// Throws a [CameraWebException] if the torch mode is not supported
/// or the camera has not been initialized or started.
void setFlashMode(FlashMode mode) {
final html.MediaDevices? mediaDevices = window?.navigator.mediaDevices;
final Map<dynamic, dynamic>? supportedConstraints =
mediaDevices?.getSupportedConstraints();
final bool torchModeSupported =
supportedConstraints?[_torchModeKey] as bool? ?? false;
if (!torchModeSupported) {
throw CameraWebException(
textureId,
CameraErrorCode.torchModeNotSupported,
'The torch mode is not supported in the current browser.',
);
}
// Save the updated flash mode to be used later when taking a picture.
flashMode = mode;
// Enable the torch mode only if the flash mode is torch.
_setTorchMode(enabled: mode == FlashMode.torch);
}
/// Sets the camera torch mode constraint to [enabled].
///
/// Throws a [CameraWebException] if the torch mode is not supported
/// or the camera has not been initialized or started.
void _setTorchMode({required bool enabled}) {
final List<html.MediaStreamTrack> videoTracks =
stream?.getVideoTracks() ?? <html.MediaStreamTrack>[];
if (videoTracks.isNotEmpty) {
final html.MediaStreamTrack defaultVideoTrack = videoTracks.first;
final bool canEnableTorchMode =
defaultVideoTrack.getCapabilities()[_torchModeKey] as bool? ?? false;
if (canEnableTorchMode) {
defaultVideoTrack.applyConstraints(<String, Object>{
'advanced': <Object>[
<String, Object>{
_torchModeKey: enabled,
}
]
});
} else {
throw CameraWebException(
textureId,
CameraErrorCode.torchModeNotSupported,
'The torch mode is not supported by the current camera.',
);
}
} else {
throw CameraWebException(
textureId,
CameraErrorCode.notStarted,
'The camera has not been initialized or started.',
);
}
}
/// Returns the camera maximum zoom level.
///
/// Throws a [CameraWebException] if the zoom level is not supported
/// or the camera has not been initialized or started.
double getMaxZoomLevel() =>
_cameraService.getZoomLevelCapabilityForCamera(this).maximum;
/// Returns the camera minimum zoom level.
///
/// Throws a [CameraWebException] if the zoom level is not supported
/// or the camera has not been initialized or started.
double getMinZoomLevel() =>
_cameraService.getZoomLevelCapabilityForCamera(this).minimum;
/// Sets the camera zoom level to [zoom].
///
/// Throws a [CameraWebException] if the zoom level is invalid,
/// not supported or the camera has not been initialized or started.
void setZoomLevel(double zoom) {
final ZoomLevelCapability zoomLevelCapability =
_cameraService.getZoomLevelCapabilityForCamera(this);
if (zoom < zoomLevelCapability.minimum ||
zoom > zoomLevelCapability.maximum) {
throw CameraWebException(
textureId,
CameraErrorCode.zoomLevelInvalid,
'The provided zoom level must be in the range of ${zoomLevelCapability.minimum} to ${zoomLevelCapability.maximum}.',
);
}
zoomLevelCapability.videoTrack.applyConstraints(<String, Object>{
'advanced': <Object>[
<String, Object>{
ZoomLevelCapability.constraintName: zoom,
}
]
});
}
/// Returns a lens direction of this camera.
///
/// Returns null if the camera is missing a video track or
/// the video track does not include the facing mode setting.
CameraLensDirection? getLensDirection() {
final List<html.MediaStreamTrack> videoTracks =
videoElement.srcObject?.getVideoTracks() ?? <html.MediaStreamTrack>[];
if (videoTracks.isEmpty) {
return null;
}
final html.MediaStreamTrack defaultVideoTrack = videoTracks.first;
final Map<dynamic, dynamic> defaultVideoTrackSettings =
defaultVideoTrack.getSettings();
final String? facingMode =
defaultVideoTrackSettings['facingMode'] as String?;
if (facingMode != null) {
return _cameraService.mapFacingModeToLensDirection(facingMode);
} else {
return null;
}
}
/// Returns the registered view type of the camera.
String getViewType() => _getViewType(textureId);
/// Starts a new video recording using [html.MediaRecorder].
///
/// Throws a [CameraWebException] if the provided maximum video duration is invalid
/// or the browser does not support any of the available video mime types
/// from [_videoMimeType].
Future<void> startVideoRecording({Duration? maxVideoDuration}) async {
if (maxVideoDuration != null && maxVideoDuration.inMilliseconds <= 0) {
throw CameraWebException(
textureId,
CameraErrorCode.notSupported,
'The maximum video duration must be greater than 0 milliseconds.',
);
}
mediaRecorder ??=
html.MediaRecorder(videoElement.srcObject!, <String, Object>{
'mimeType': _videoMimeType,
});
_videoAvailableCompleter = Completer<XFile>();
_videoDataAvailableListener =
(html.Event event) => _onVideoDataAvailable(event, maxVideoDuration);
_videoRecordingStoppedListener =
(html.Event event) => _onVideoRecordingStopped(event, maxVideoDuration);
mediaRecorder!.addEventListener(
'dataavailable',
_videoDataAvailableListener,
);
mediaRecorder!.addEventListener(
'stop',
_videoRecordingStoppedListener,
);
_onVideoRecordingErrorSubscription =
mediaRecorder!.onError.listen((html.Event event) {
final html.ErrorEvent error = event as html.ErrorEvent;
if (error != null) {
videoRecordingErrorController.add(error);
}
});
if (maxVideoDuration != null) {
mediaRecorder!.start(maxVideoDuration.inMilliseconds);
} else {
// Don't pass the null duration as that will fire a `dataavailable` event directly.
mediaRecorder!.start();
}
}
void _onVideoDataAvailable(
html.Event event, [
Duration? maxVideoDuration,
]) {
final html.Blob? blob = (event as html.BlobEvent).data;
// Append the recorded part of the video to the list of all video data files.
if (blob != null) {
_videoData.add(blob);
}
// Stop the recorder if the video has a maxVideoDuration
// and the recording was not stopped manually.
if (maxVideoDuration != null && mediaRecorder!.state == 'recording') {
mediaRecorder!.stop();
}
}
Future<void> _onVideoRecordingStopped(
html.Event event, [
Duration? maxVideoDuration,
]) async {
if (_videoData.isNotEmpty) {
// Concatenate all video data files into a single blob.
final String videoType = _videoData.first.type;
final html.Blob videoBlob = blobBuilder(_videoData, videoType);
// Create a file containing the video blob.
final XFile file = XFile(
html.Url.createObjectUrl(videoBlob),
mimeType: _videoMimeType,
name: videoBlob.hashCode.toString(),
);
// Emit an event containing the recorded video file.
videoRecorderController.add(
VideoRecordedEvent(textureId, file, maxVideoDuration),
);
_videoAvailableCompleter?.complete(file);
}
// Clean up the media recorder with its event listeners and video data.
mediaRecorder!.removeEventListener(
'dataavailable',
_videoDataAvailableListener,
);
mediaRecorder!.removeEventListener(
'stop',
_videoDataAvailableListener,
);
await _onVideoRecordingErrorSubscription?.cancel();
mediaRecorder = null;
_videoDataAvailableListener = null;
_videoRecordingStoppedListener = null;
_videoData.clear();
}
/// Pauses the current video recording.
///
/// Throws a [CameraWebException] if the video recorder is uninitialized.
Future<void> pauseVideoRecording() async {
if (mediaRecorder == null) {
throw _videoRecordingNotStartedException;
}
mediaRecorder!.pause();
}
/// Resumes the current video recording.
///
/// Throws a [CameraWebException] if the video recorder is uninitialized.
Future<void> resumeVideoRecording() async {
if (mediaRecorder == null) {
throw _videoRecordingNotStartedException;
}
mediaRecorder!.resume();
}
/// Stops the video recording and returns the captured video file.
///
/// Throws a [CameraWebException] if the video recorder is uninitialized.
Future<XFile> stopVideoRecording() async {
if (mediaRecorder == null || _videoAvailableCompleter == null) {
throw _videoRecordingNotStartedException;
}
mediaRecorder!.stop();
return _videoAvailableCompleter!.future;
}
/// Disposes the camera by stopping the camera stream,
/// the video recording and reloading the camera source.
Future<void> dispose() async {
// Stop the camera stream.
stop();
await videoRecorderController.close();
mediaRecorder = null;
_videoDataAvailableListener = null;
// Reset the [videoElement] to its initial state.
videoElement
..srcObject = null
..load();
await _onEndedSubscription?.cancel();
_onEndedSubscription = null;
await onEndedController.close();
await _onVideoRecordingErrorSubscription?.cancel();
_onVideoRecordingErrorSubscription = null;
await videoRecordingErrorController.close();
}
/// Returns the first supported video mime type (amongst mp4 and webm)
/// to use when recording a video.
///
/// Throws a [CameraWebException] if the browser does not support
/// any of the available video mime types.
String get _videoMimeType {
const List<String> types = <String>[
'video/mp4',
'video/webm',
];
return types.firstWhere(
(String type) => isVideoTypeSupported(type),
orElse: () => throw CameraWebException(
textureId,
CameraErrorCode.notSupported,
'The browser does not support any of the following video types: ${types.join(',')}.',
),
);
}
CameraWebException get _videoRecordingNotStartedException =>
CameraWebException(
textureId,
CameraErrorCode.videoRecordingNotStarted,
'The video recorder is uninitialized. The recording might not have been started. Make sure to call `startVideoRecording` first.',
);
/// Applies default styles to the video [element].
void _applyDefaultVideoStyles(html.VideoElement element) {
final bool isBackCamera = getLensDirection() == CameraLensDirection.back;
// Flip the video horizontally if it is not taken from a back camera.
if (!isBackCamera) {
element.style.transform = 'scaleX(-1)';
}
element.style
..transformOrigin = 'center'
..pointerEvents = 'none'
..width = '100%'
..height = '100%'
..objectFit = 'cover';
}
}
| plugins/packages/camera/camera_web/lib/src/camera.dart/0 | {
"file_path": "plugins/packages/camera/camera_web/lib/src/camera.dart",
"repo_id": "plugins",
"token_count": 7071
} | 1,204 |
name: camera_windows
description: A Flutter plugin for getting information about and controlling the camera on Windows.
repository: https://github.com/flutter/plugins/tree/main/packages/camera/camera_windows
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22
version: 0.2.1+4
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: camera
platforms:
windows:
pluginClass: CameraWindows
dartPluginClass: CameraWindows
dependencies:
camera_platform_interface: ^2.3.1
cross_file: ^0.3.1
flutter:
sdk: flutter
stream_transform: ^2.0.0
dev_dependencies:
async: ^2.5.0
flutter_test:
sdk: flutter
| plugins/packages/camera/camera_windows/pubspec.yaml/0 | {
"file_path": "plugins/packages/camera/camera_windows/pubspec.yaml",
"repo_id": "plugins",
"token_count": 294
} | 1,205 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_ENGINE_LISTENER_H_
#define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_ENGINE_LISTENER_H_
#include <mfcaptureengine.h>
#include <cassert>
#include <functional>
namespace camera_windows {
// A class that implements callbacks for events from a |CaptureEngineListener|.
class CaptureEngineObserver {
public:
virtual ~CaptureEngineObserver() = default;
// Returns true if sample can be processed.
virtual bool IsReadyForSample() const = 0;
// Handles Capture Engine media events.
virtual void OnEvent(IMFMediaEvent* event) = 0;
// Updates texture buffer
virtual bool UpdateBuffer(uint8_t* data, uint32_t new_length) = 0;
// Handles capture timestamps updates.
// Used to stop timed recordings when recorded time is exceeded.
virtual void UpdateCaptureTime(uint64_t capture_time) = 0;
};
// Listener for Windows Media Foundation capture engine events and samples.
//
// Events are redirected to observers for processing. Samples are preprosessed
// and sent to the associated observer if it is ready to process samples.
class CaptureEngineListener : public IMFCaptureEngineOnSampleCallback,
public IMFCaptureEngineOnEventCallback {
public:
CaptureEngineListener(CaptureEngineObserver* observer) : observer_(observer) {
assert(observer);
}
~CaptureEngineListener() {}
// Disallow copy and move.
CaptureEngineListener(const CaptureEngineListener&) = delete;
CaptureEngineListener& operator=(const CaptureEngineListener&) = delete;
// IUnknown
STDMETHODIMP_(ULONG) AddRef();
STDMETHODIMP_(ULONG) Release();
STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv);
// IMFCaptureEngineOnEventCallback
STDMETHODIMP OnEvent(IMFMediaEvent* pEvent);
// IMFCaptureEngineOnSampleCallback
STDMETHODIMP_(HRESULT) OnSample(IMFSample* pSample);
private:
CaptureEngineObserver* observer_;
volatile ULONG ref_ = 0;
};
} // namespace camera_windows
#endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_ENGINE_LISTENER_H_
| plugins/packages/camera/camera_windows/windows/capture_engine_listener.h/0 | {
"file_path": "plugins/packages/camera/camera_windows/windows/capture_engine_listener.h",
"repo_id": "plugins",
"token_count": 690
} | 1,206 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_TEXTURE_HANDLER_H_
#define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_TEXTURE_HANDLER_H_
#include <flutter/texture_registrar.h>
#include <memory>
#include <mutex>
#include <string>
namespace camera_windows {
// Describes flutter desktop pixelbuffers pixel data order.
struct FlutterDesktopPixel {
uint8_t r = 0;
uint8_t g = 0;
uint8_t b = 0;
uint8_t a = 0;
};
// Describes MFVideoFormat_RGB32 data order.
struct MFVideoFormatRGB32Pixel {
uint8_t b = 0;
uint8_t g = 0;
uint8_t r = 0;
uint8_t x = 0;
};
// Handles the registration of Flutter textures, pixel buffers, and the
// conversion of texture formats.
class TextureHandler {
public:
TextureHandler(flutter::TextureRegistrar* texture_registrar)
: texture_registrar_(texture_registrar) {}
virtual ~TextureHandler();
// Prevent copying.
TextureHandler(TextureHandler const&) = delete;
TextureHandler& operator=(TextureHandler const&) = delete;
// Updates source data buffer with given data.
bool UpdateBuffer(uint8_t* data, uint32_t data_length);
// Registers texture and updates given texture_id pointer value.
int64_t RegisterTexture();
// Updates current preview texture size.
void UpdateTextureSize(uint32_t width, uint32_t height) {
preview_frame_width_ = width;
preview_frame_height_ = height;
}
// Sets software mirror state.
void SetMirrorPreviewState(bool mirror) { mirror_preview_ = mirror; }
private:
// Informs flutter texture registrar of updated texture.
void OnBufferUpdated();
// Converts local pixel buffer to flutter pixel buffer.
const FlutterDesktopPixelBuffer* ConvertPixelBufferForFlutter(size_t width,
size_t height);
// Checks if texture registrar, texture id and texture are available.
bool TextureRegistered() {
return texture_registrar_ && texture_ && texture_id_ > -1;
}
bool mirror_preview_ = true;
int64_t texture_id_ = -1;
uint32_t bytes_per_pixel_ = 4;
uint32_t source_buffer_size_ = 0;
uint32_t preview_frame_width_ = 0;
uint32_t preview_frame_height_ = 0;
std::vector<uint8_t> source_buffer_;
std::vector<uint8_t> dest_buffer_;
std::unique_ptr<flutter::TextureVariant> texture_;
std::unique_ptr<FlutterDesktopPixelBuffer> flutter_desktop_pixel_buffer_ =
nullptr;
flutter::TextureRegistrar* texture_registrar_ = nullptr;
std::mutex buffer_mutex_;
};
} // namespace camera_windows
#endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_TEXTURE_HANDLER_H_
| plugins/packages/camera/camera_windows/windows/texture_handler.h/0 | {
"file_path": "plugins/packages/camera/camera_windows/windows/texture_handler.h",
"repo_id": "plugins",
"token_count": 942
} | 1,207 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
/// Screen that shows an example of openFiles
class OpenMultipleImagesPage extends StatelessWidget {
/// Default Constructor
const OpenMultipleImagesPage({Key? key}) : super(key: key);
Future<void> _openImageFile(BuildContext context) async {
// #docregion MultiOpen
const XTypeGroup jpgsTypeGroup = XTypeGroup(
label: 'JPEGs',
extensions: <String>['jpg', 'jpeg'],
);
const XTypeGroup pngTypeGroup = XTypeGroup(
label: 'PNGs',
extensions: <String>['png'],
);
final List<XFile> files = await openFiles(acceptedTypeGroups: <XTypeGroup>[
jpgsTypeGroup,
pngTypeGroup,
]);
// #enddocregion MultiOpen
if (files.isEmpty) {
// Operation was canceled by the user.
return;
}
if (context.mounted) {
await showDialog<void>(
context: context,
builder: (BuildContext context) => MultipleImagesDisplay(files),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Open multiple images'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
// TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724
// ignore: deprecated_member_use
primary: Colors.blue,
// ignore: deprecated_member_use
onPrimary: Colors.white,
),
child: const Text('Press to open multiple images (png, jpg)'),
onPressed: () => _openImageFile(context),
),
],
),
),
);
}
}
/// Widget that displays a text file in a dialog
class MultipleImagesDisplay extends StatelessWidget {
/// Default Constructor
const MultipleImagesDisplay(this.files, {Key? key}) : super(key: key);
/// The files containing the images
final List<XFile> files;
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Gallery'),
// On web the filePath is a blob url
// while on other platforms it is a system path.
content: Center(
child: Row(
children: <Widget>[
...files.map(
(XFile file) => Flexible(
child: kIsWeb
? Image.network(file.path)
: Image.file(File(file.path))),
)
],
),
),
actions: <Widget>[
TextButton(
child: const Text('Close'),
onPressed: () {
Navigator.pop(context);
},
),
],
);
}
}
| plugins/packages/file_selector/file_selector/example/lib/open_multiple_images_page.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector/example/lib/open_multiple_images_page.dart",
"repo_id": "plugins",
"token_count": 1339
} | 1,208 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| plugins/packages/file_selector/file_selector/example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "plugins/packages/file_selector/file_selector/example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "plugins",
"token_count": 32
} | 1,209 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint file_selector_ios.podspec` to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'file_selector_ios'
s.version = '0.0.1'
s.summary = 'iOS implementation of file_selector.'
s.description = <<-DESC
Displays the native iOS document picker.
DESC
s.homepage = 'https://github.com/flutter/plugins/tree/main/packages/file_selector'
s.license = { :type => 'BSD', :file => '../LICENSE' }
s.author = { 'Flutter Dev Team' => '[email protected]' }
s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/file_selector/file_selector_ios' }
s.source_files = 'Classes/**/*.{h,m}'
s.module_map = 'Classes/FileSelectorPlugin.modulemap'
s.dependency 'Flutter'
s.platform = :ios, '9.0'
# Flutter.framework does not contain a i386 slice.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
s.swift_version = '5.0'
end
| plugins/packages/file_selector/file_selector_ios/ios/file_selector_ios.podspec/0 | {
"file_path": "plugins/packages/file_selector/file_selector_ios/ios/file_selector_ios.podspec",
"repo_id": "plugins",
"token_count": 492
} | 1,210 |
name: file_selector_linux_example
description: Local testbed for Linux file_selector implementation.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
file_selector_linux:
path: ../
file_selector_platform_interface: ^2.4.0
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| plugins/packages/file_selector/file_selector_linux/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/file_selector/file_selector_linux/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 172
} | 1,211 |
# file\_selector\_macos
The macOS implementation of [`file_selector`][1].
## Usage
This package is [endorsed][2], which means you can simply use `file_selector`
normally. This package will be automatically included in your app when you do.
### Entitlements
You will need to [add an entitlement][3] for either read-only access:
```xml
<key>com.apple.security.files.user-selected.read-only</key>
<true/>
```
or read/write access:
```xml
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
```
depending on your use case.
[1]: https://pub.dev/packages/file_selector
[2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
[3]: https://flutter.dev/desktop#entitlements-and-the-app-sandbox
| plugins/packages/file_selector/file_selector_macos/README.md/0 | {
"file_path": "plugins/packages/file_selector/file_selector_macos/README.md",
"repo_id": "plugins",
"token_count": 259
} | 1,212 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| plugins/packages/file_selector/file_selector_macos/example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "plugins/packages/file_selector/file_selector_macos/example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "plugins",
"token_count": 32
} | 1,213 |
name: file_selector_macos
description: macOS implementation of the file_selector plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/file_selector/file_selector_macos
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+file_selector%22
version: 0.9.0+4
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: file_selector
platforms:
macos:
dartPluginClass: FileSelectorMacOS
pluginClass: FileSelectorPlugin
dependencies:
cross_file: ^0.3.1
file_selector_platform_interface: ^2.2.0
flutter:
sdk: flutter
dev_dependencies:
build_runner: ^2.3.2
flutter_test:
sdk: flutter
mockito: ^5.3.2
pigeon: ^4.2.14
| plugins/packages/file_selector/file_selector_macos/pubspec.yaml/0 | {
"file_path": "plugins/packages/file_selector/file_selector_macos/pubspec.yaml",
"repo_id": "plugins",
"token_count": 326
} | 1,214 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
/// Convert list of XTypeGroups to a comma-separated string
String acceptedTypesToString(List<XTypeGroup>? acceptedTypes) {
if (acceptedTypes == null) {
return '';
}
final List<String> allTypes = <String>[];
for (final XTypeGroup group in acceptedTypes) {
// If any group allows everything, no filtering should be done.
if (group.allowsAny) {
return '';
}
_validateTypeGroup(group);
if (group.extensions != null) {
allTypes.addAll(group.extensions!.map(_normalizeExtension));
}
if (group.mimeTypes != null) {
allTypes.addAll(group.mimeTypes!);
}
if (group.webWildCards != null) {
allTypes.addAll(group.webWildCards!);
}
}
return allTypes.join(',');
}
/// Make sure that at least one of the supported fields is populated.
void _validateTypeGroup(XTypeGroup group) {
if ((group.extensions?.isEmpty ?? true) &&
(group.mimeTypes?.isEmpty ?? true) &&
(group.webWildCards?.isEmpty ?? true)) {
throw ArgumentError('Provided type group $group does not allow '
'all files, but does not set any of the web-supported filter '
'categories. At least one of "extensions", "mimeTypes", or '
'"webWildCards" must be non-empty for web if anything is '
'non-empty.');
}
}
/// Append a dot at the beggining if it is not there png -> .png
String _normalizeExtension(String ext) {
return ext.isNotEmpty && ext[0] != '.' ? '.$ext' : ext;
}
| plugins/packages/file_selector/file_selector_web/lib/src/utils.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_web/lib/src/utils.dart",
"repo_id": "plugins",
"token_count": 605
} | 1,215 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'fake_maps_controllers.dart';
Widget _mapWithCircles(Set<Circle> circles) {
return Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)),
circles: circles,
),
);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final FakePlatformViewsController fakePlatformViewsController =
FakePlatformViewsController();
setUpAll(() {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
SystemChannels.platform_views,
fakePlatformViewsController.fakePlatformViewsMethodHandler,
);
});
setUp(() {
fakePlatformViewsController.reset();
});
testWidgets('Initializing a circle', (WidgetTester tester) async {
const Circle c1 = Circle(circleId: CircleId('circle_1'));
await tester.pumpWidget(_mapWithCircles(<Circle>{c1}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.circlesToAdd.length, 1);
final Circle initializedCircle = platformGoogleMap.circlesToAdd.first;
expect(initializedCircle, equals(c1));
expect(platformGoogleMap.circleIdsToRemove.isEmpty, true);
expect(platformGoogleMap.circlesToChange.isEmpty, true);
});
testWidgets('Adding a circle', (WidgetTester tester) async {
const Circle c1 = Circle(circleId: CircleId('circle_1'));
const Circle c2 = Circle(circleId: CircleId('circle_2'));
await tester.pumpWidget(_mapWithCircles(<Circle>{c1}));
await tester.pumpWidget(_mapWithCircles(<Circle>{c1, c2}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.circlesToAdd.length, 1);
final Circle addedCircle = platformGoogleMap.circlesToAdd.first;
expect(addedCircle, equals(c2));
expect(platformGoogleMap.circleIdsToRemove.isEmpty, true);
expect(platformGoogleMap.circlesToChange.isEmpty, true);
});
testWidgets('Removing a circle', (WidgetTester tester) async {
const Circle c1 = Circle(circleId: CircleId('circle_1'));
await tester.pumpWidget(_mapWithCircles(<Circle>{c1}));
await tester.pumpWidget(_mapWithCircles(<Circle>{}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.circleIdsToRemove.length, 1);
expect(platformGoogleMap.circleIdsToRemove.first, equals(c1.circleId));
expect(platformGoogleMap.circlesToChange.isEmpty, true);
expect(platformGoogleMap.circlesToAdd.isEmpty, true);
});
testWidgets('Updating a circle', (WidgetTester tester) async {
const Circle c1 = Circle(circleId: CircleId('circle_1'));
const Circle c2 = Circle(circleId: CircleId('circle_1'), radius: 10);
await tester.pumpWidget(_mapWithCircles(<Circle>{c1}));
await tester.pumpWidget(_mapWithCircles(<Circle>{c2}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.circlesToChange.length, 1);
expect(platformGoogleMap.circlesToChange.first, equals(c2));
expect(platformGoogleMap.circleIdsToRemove.isEmpty, true);
expect(platformGoogleMap.circlesToAdd.isEmpty, true);
});
testWidgets('Updating a circle', (WidgetTester tester) async {
const Circle c1 = Circle(circleId: CircleId('circle_1'));
const Circle c2 = Circle(circleId: CircleId('circle_1'), radius: 10);
await tester.pumpWidget(_mapWithCircles(<Circle>{c1}));
await tester.pumpWidget(_mapWithCircles(<Circle>{c2}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.circlesToChange.length, 1);
final Circle update = platformGoogleMap.circlesToChange.first;
expect(update, equals(c2));
expect(update.radius, 10);
});
testWidgets('Multi Update', (WidgetTester tester) async {
Circle c1 = const Circle(circleId: CircleId('circle_1'));
Circle c2 = const Circle(circleId: CircleId('circle_2'));
final Set<Circle> prev = <Circle>{c1, c2};
c1 = const Circle(circleId: CircleId('circle_1'), visible: false);
c2 = const Circle(circleId: CircleId('circle_2'), radius: 10);
final Set<Circle> cur = <Circle>{c1, c2};
await tester.pumpWidget(_mapWithCircles(prev));
await tester.pumpWidget(_mapWithCircles(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.circlesToChange, cur);
expect(platformGoogleMap.circleIdsToRemove.isEmpty, true);
expect(platformGoogleMap.circlesToAdd.isEmpty, true);
});
testWidgets('Multi Update', (WidgetTester tester) async {
Circle c2 = const Circle(circleId: CircleId('circle_2'));
const Circle c3 = Circle(circleId: CircleId('circle_3'));
final Set<Circle> prev = <Circle>{c2, c3};
// c1 is added, c2 is updated, c3 is removed.
const Circle c1 = Circle(circleId: CircleId('circle_1'));
c2 = const Circle(circleId: CircleId('circle_2'), radius: 10);
final Set<Circle> cur = <Circle>{c1, c2};
await tester.pumpWidget(_mapWithCircles(prev));
await tester.pumpWidget(_mapWithCircles(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.circlesToChange.length, 1);
expect(platformGoogleMap.circlesToAdd.length, 1);
expect(platformGoogleMap.circleIdsToRemove.length, 1);
expect(platformGoogleMap.circlesToChange.first, equals(c2));
expect(platformGoogleMap.circlesToAdd.first, equals(c1));
expect(platformGoogleMap.circleIdsToRemove.first, equals(c3.circleId));
});
testWidgets('Partial Update', (WidgetTester tester) async {
const Circle c1 = Circle(circleId: CircleId('circle_1'));
const Circle c2 = Circle(circleId: CircleId('circle_2'));
Circle c3 = const Circle(circleId: CircleId('circle_3'));
final Set<Circle> prev = <Circle>{c1, c2, c3};
c3 = const Circle(circleId: CircleId('circle_3'), radius: 10);
final Set<Circle> cur = <Circle>{c1, c2, c3};
await tester.pumpWidget(_mapWithCircles(prev));
await tester.pumpWidget(_mapWithCircles(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.circlesToChange, <Circle>{c3});
expect(platformGoogleMap.circleIdsToRemove.isEmpty, true);
expect(platformGoogleMap.circlesToAdd.isEmpty, true);
});
testWidgets('Update non platform related attr', (WidgetTester tester) async {
Circle c1 = const Circle(circleId: CircleId('circle_1'));
final Set<Circle> prev = <Circle>{c1};
c1 = Circle(circleId: const CircleId('circle_1'), onTap: () {});
final Set<Circle> cur = <Circle>{c1};
await tester.pumpWidget(_mapWithCircles(prev));
await tester.pumpWidget(_mapWithCircles(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.circlesToChange.isEmpty, true);
expect(platformGoogleMap.circleIdsToRemove.isEmpty, true);
expect(platformGoogleMap.circlesToAdd.isEmpty, true);
});
}
/// This allows a value of type T or T? to be treated as a value of type T?.
///
/// We use this so that APIs that have become non-nullable can still be used
/// with `!` and `?` on the stable branch.
T? _ambiguate<T>(T? value) => value;
| plugins/packages/google_maps_flutter/google_maps_flutter/test/circle_updates_test.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/test/circle_updates_test.dart",
"repo_id": "plugins",
"token_count": 2845
} | 1,216 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.googlemaps;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.content.Context;
import android.os.Build;
import androidx.activity.ComponentActivity;
import androidx.test.core.app.ApplicationProvider;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(sdk = Build.VERSION_CODES.P)
public class GoogleMapControllerTest {
private Context context;
private ComponentActivity activity;
private GoogleMapController googleMapController;
@Mock BinaryMessenger mockMessenger;
@Mock GoogleMap mockGoogleMap;
@Before
public void before() {
MockitoAnnotations.initMocks(this);
context = ApplicationProvider.getApplicationContext();
activity = Robolectric.setupActivity(ComponentActivity.class);
googleMapController =
new GoogleMapController(0, context, mockMessenger, activity::getLifecycle, null);
googleMapController.init();
}
@Test
public void DisposeReleaseTheMap() throws InterruptedException {
googleMapController.onMapReady(mockGoogleMap);
assertTrue(googleMapController != null);
googleMapController.dispose();
assertNull(googleMapController.getView());
}
@Test
public void OnDestroyReleaseTheMap() throws InterruptedException {
googleMapController.onMapReady(mockGoogleMap);
assertTrue(googleMapController != null);
googleMapController.onDestroy(activity);
assertNull(googleMapController.getView());
}
@Test
public void InvalidateMapAfterMethodCalls() throws InterruptedException {
String[] methodsThatTriggerInvalidation = {
"markers#update",
"polygons#update",
"polylines#update",
"circles#update",
"map#setStyle",
"tileOverlays#update",
"tileOverlays#clearTileCache"
};
for (String methodName : methodsThatTriggerInvalidation) {
googleMapController =
new GoogleMapController(0, context, mockMessenger, activity::getLifecycle, null);
googleMapController.init();
mockGoogleMap = mock(GoogleMap.class);
googleMapController.onMapReady(mockGoogleMap);
MethodChannel.Result result = mock(MethodChannel.Result.class);
System.out.println(methodName);
googleMapController.onMethodCall(
new MethodCall(methodName, new HashMap<String, Object>()), result);
ArgumentCaptor<GoogleMap.OnMapLoadedCallback> argument =
ArgumentCaptor.forClass(GoogleMap.OnMapLoadedCallback.class);
verify(mockGoogleMap).setOnMapLoadedCallback(argument.capture());
MapView mapView = mock(MapView.class);
googleMapController.setView(mapView);
verify(mapView, never()).invalidate();
argument.getValue().onMapLoaded();
verify(mapView).invalidate();
}
}
@Test
public void InvalidateMapOnceAfterMethodCall() throws InterruptedException {
googleMapController.onMapReady(mockGoogleMap);
MethodChannel.Result result = mock(MethodChannel.Result.class);
googleMapController.onMethodCall(
new MethodCall("markers#update", new HashMap<String, Object>()), result);
googleMapController.onMethodCall(
new MethodCall("polygons#update", new HashMap<String, Object>()), result);
ArgumentCaptor<GoogleMap.OnMapLoadedCallback> argument =
ArgumentCaptor.forClass(GoogleMap.OnMapLoadedCallback.class);
verify(mockGoogleMap).setOnMapLoadedCallback(argument.capture());
MapView mapView = mock(MapView.class);
googleMapController.setView(mapView);
verify(mapView, never()).invalidate();
argument.getValue().onMapLoaded();
verify(mapView).invalidate();
}
@Test
public void MethodCalledAfterControllerIsDestroyed() throws InterruptedException {
googleMapController.onMapReady(mockGoogleMap);
MethodChannel.Result result = mock(MethodChannel.Result.class);
googleMapController.onMethodCall(
new MethodCall("markers#update", new HashMap<String, Object>()), result);
ArgumentCaptor<GoogleMap.OnMapLoadedCallback> argument =
ArgumentCaptor.forClass(GoogleMap.OnMapLoadedCallback.class);
verify(mockGoogleMap).setOnMapLoadedCallback(argument.capture());
MapView mapView = mock(MapView.class);
googleMapController.setView(mapView);
googleMapController.onDestroy(activity);
argument.getValue().onMapLoaded();
verify(mapView, never()).invalidate();
}
@Test
public void OnMapReadySetsPaddingIfInitialPaddingIsThere() {
float padding = 10f;
int paddingWithDensity = (int) (padding * googleMapController.density);
googleMapController.setInitialPadding(padding, padding, padding, padding);
googleMapController.onMapReady(mockGoogleMap);
verify(mockGoogleMap, times(1))
.setPadding(paddingWithDensity, paddingWithDensity, paddingWithDensity, paddingWithDensity);
}
@Test
public void SetPaddingStoresThePaddingValuesInInInitialPaddingWhenGoogleMapIsNull() {
assertNull(googleMapController.initialPadding);
googleMapController.setPadding(0f, 0f, 0f, 0f);
assertNotNull(googleMapController.initialPadding);
Assert.assertEquals(4, googleMapController.initialPadding.size());
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/GoogleMapControllerTest.java/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/GoogleMapControllerTest.java",
"repo_id": "plugins",
"token_count": 2023
} | 1,217 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 2.1.13
* Updates code for stricter lint checks.
* Updates code for new analysis options.
* Re-enable XCUITests: testUserInterface.
* Remove unnecessary `RunnerUITests` target from Podfile of the example app.
## 2.1.12
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
* Fixes violations of new analysis option use_named_constants.
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 2.1.11
* Precaches Google Maps services initialization and syncing.
## 2.1.10
* Splits iOS implementation out of `google_maps_flutter` as a federated
implementation.
| plugins/packages/google_maps_flutter/google_maps_flutter_ios/CHANGELOG.md/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 201
} | 1,218 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Flutter/Flutter.h>
#import <GoogleMaps/GoogleMaps.h>
// Defines circle controllable by Flutter.
@interface FLTGoogleMapCircleController : NSObject
- (instancetype)initCircleWithPosition:(CLLocationCoordinate2D)position
radius:(CLLocationDistance)radius
circleId:(NSString *)circleIdentifier
mapView:(GMSMapView *)mapView
options:(NSDictionary *)options;
- (void)removeCircle;
@end
@interface FLTCirclesController : NSObject
- (instancetype)init:(FlutterMethodChannel *)methodChannel
mapView:(GMSMapView *)mapView
registrar:(NSObject<FlutterPluginRegistrar> *)registrar;
- (void)addCircles:(NSArray *)circlesToAdd;
- (void)changeCircles:(NSArray *)circlesToChange;
- (void)removeCircleWithIdentifiers:(NSArray *)identifiers;
- (void)didTapCircleWithIdentifier:(NSString *)identifier;
- (bool)hasCircleWithIdentifier:(NSString *)identifier;
@end
| plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapCircleController.h/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapCircleController.h",
"repo_id": "plugins",
"token_count": 463
} | 1,219 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart' show VoidCallback;
import 'package:flutter/foundation.dart' show immutable;
import 'package:flutter/material.dart' show Color, Colors;
import 'types.dart';
/// Uniquely identifies a [Circle] among [GoogleMap] circles.
///
/// This does not have to be globally unique, only unique among the list.
@immutable
class CircleId extends MapsObjectId<Circle> {
/// Creates an immutable identifier for a [Circle].
const CircleId(String value) : super(value);
}
/// Draws a circle on the map.
@immutable
class Circle implements MapsObject<Circle> {
/// Creates an immutable representation of a [Circle] to draw on [GoogleMap].
const Circle({
required this.circleId,
this.consumeTapEvents = false,
this.fillColor = Colors.transparent,
this.center = const LatLng(0.0, 0.0),
this.radius = 0,
this.strokeColor = Colors.black,
this.strokeWidth = 10,
this.visible = true,
this.zIndex = 0,
this.onTap,
});
/// Uniquely identifies a [Circle].
final CircleId circleId;
@override
CircleId get mapsId => circleId;
/// True if the [Circle] consumes tap events.
///
/// If this is false, [onTap] callback will not be triggered.
final bool consumeTapEvents;
/// Fill color in ARGB format, the same format used by Color. The default value is transparent (0x00000000).
final Color fillColor;
/// Geographical location of the circle center.
final LatLng center;
/// Radius of the circle in meters; must be positive. The default value is 0.
final double radius;
/// Fill color in ARGB format, the same format used by Color. The default value is black (0xff000000).
final Color strokeColor;
/// The width of the circle's outline in screen points.
///
/// The width is constant and independent of the camera's zoom level.
/// The default value is 10.
/// Setting strokeWidth to 0 results in no stroke.
final int strokeWidth;
/// True if the circle is visible.
final bool visible;
/// The z-index of the circle, used to determine relative drawing order of
/// map overlays.
///
/// Overlays are drawn in order of z-index, so that lower values means drawn
/// earlier, and thus appearing to be closer to the surface of the Earth.
final int zIndex;
/// Callbacks to receive tap events for circle placed on this map.
final VoidCallback? onTap;
/// Creates a new [Circle] object whose values are the same as this instance,
/// unless overwritten by the specified parameters.
Circle copyWith({
bool? consumeTapEventsParam,
Color? fillColorParam,
LatLng? centerParam,
double? radiusParam,
Color? strokeColorParam,
int? strokeWidthParam,
bool? visibleParam,
int? zIndexParam,
VoidCallback? onTapParam,
}) {
return Circle(
circleId: circleId,
consumeTapEvents: consumeTapEventsParam ?? consumeTapEvents,
fillColor: fillColorParam ?? fillColor,
center: centerParam ?? center,
radius: radiusParam ?? radius,
strokeColor: strokeColorParam ?? strokeColor,
strokeWidth: strokeWidthParam ?? strokeWidth,
visible: visibleParam ?? visible,
zIndex: zIndexParam ?? zIndex,
onTap: onTapParam ?? onTap,
);
}
/// Creates a new [Circle] object whose values are the same as this instance.
@override
Circle clone() => copyWith();
/// Converts this object to something serializable in JSON.
@override
Object toJson() {
final Map<String, Object> json = <String, Object>{};
void addIfPresent(String fieldName, Object? value) {
if (value != null) {
json[fieldName] = value;
}
}
addIfPresent('circleId', circleId.value);
addIfPresent('consumeTapEvents', consumeTapEvents);
addIfPresent('fillColor', fillColor.value);
addIfPresent('center', center.toJson());
addIfPresent('radius', radius);
addIfPresent('strokeColor', strokeColor.value);
addIfPresent('strokeWidth', strokeWidth);
addIfPresent('visible', visible);
addIfPresent('zIndex', zIndex);
return json;
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is Circle &&
circleId == other.circleId &&
consumeTapEvents == other.consumeTapEvents &&
fillColor == other.fillColor &&
center == other.center &&
radius == other.radius &&
strokeColor == other.strokeColor &&
strokeWidth == other.strokeWidth &&
visible == other.visible &&
zIndex == other.zIndex;
}
@override
int get hashCode => circleId.hashCode;
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/circle.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/circle.dart",
"repo_id": "plugins",
"token_count": 1558
} | 1,220 |
{
"project_info": {
"project_number": "479882132969",
"firebase_url": "https://my-flutter-proj.firebaseio.com",
"project_id": "my-flutter-proj",
"storage_bucket": "my-flutter-proj.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:479882132969:android:c73fd19ff7e2c0be",
"android_client_info": {
"package_name": "io.flutter.plugins.cameraexample"
}
},
"oauth_client": [
{
"client_id": "479882132969-0d20fkjtr1p8evfomfkf3vmi50uajml2.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyCrZz9T0Pg0rDnpxfNuPBrOxGhXskfebXs"
}
],
"services": {
"analytics_service": {
"status": 1
},
"appinvite_service": {
"status": 1,
"other_platform_oauth_client": []
},
"ads_service": {
"status": 2
}
}
},
{
"client_info": {
"mobilesdk_app_id": "1:479882132969:android:632cdf3fc0a17139",
"android_client_info": {
"package_name": "io.flutter.plugins.firebasedynamiclinksexample"
}
},
"oauth_client": [
{
"client_id": "479882132969-32qusitiag53931ck80h121ajhlc5a7e.apps.googleusercontent.com",
"client_type": 1,
"android_info": {
"package_name": "io.flutter.plugins.firebasedynamiclinksexample",
"certificate_hash": "e733b7a303250b63e06de6f7c9767c517d69cfa0"
}
},
{
"client_id": "479882132969-0d20fkjtr1p8evfomfkf3vmi50uajml2.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyCrZz9T0Pg0rDnpxfNuPBrOxGhXskfebXs"
}
],
"services": {
"analytics_service": {
"status": 1
},
"appinvite_service": {
"status": 2,
"other_platform_oauth_client": [
{
"client_id": "479882132969-0d20fkjtr1p8evfomfkf3vmi50uajml2.apps.googleusercontent.com",
"client_type": 3
},
{
"client_id": "479882132969-gjp4e63ogu2h6guttj2ie6t3f10ic7i8.apps.googleusercontent.com",
"client_type": 2,
"ios_info": {
"bundle_id": "io.flutter.plugins.firebaseMlVisionExample"
}
}
]
},
"ads_service": {
"status": 2
}
}
},
{
"client_info": {
"mobilesdk_app_id": "1:479882132969:android:ae50362b4bc06086",
"android_client_info": {
"package_name": "io.flutter.plugins.firebasemlvisionexample"
}
},
"oauth_client": [
{
"client_id": "479882132969-9pp74fkgmtvt47t9rikc1p861v7n85tn.apps.googleusercontent.com",
"client_type": 1,
"android_info": {
"package_name": "io.flutter.plugins.firebasemlvisionexample",
"certificate_hash": "e733b7a303250b63e06de6f7c9767c517d69cfa0"
}
},
{
"client_id": "479882132969-0d20fkjtr1p8evfomfkf3vmi50uajml2.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyCrZz9T0Pg0rDnpxfNuPBrOxGhXskfebXs"
}
],
"services": {
"analytics_service": {
"status": 1
},
"appinvite_service": {
"status": 2,
"other_platform_oauth_client": [
{
"client_id": "479882132969-0d20fkjtr1p8evfomfkf3vmi50uajml2.apps.googleusercontent.com",
"client_type": 3
},
{
"client_id": "479882132969-gjp4e63ogu2h6guttj2ie6t3f10ic7i8.apps.googleusercontent.com",
"client_type": 2,
"ios_info": {
"bundle_id": "io.flutter.plugins.firebaseMlVisionExample"
}
}
]
},
"ads_service": {
"status": 2
}
}
},
{
"client_info": {
"mobilesdk_app_id": "1:479882132969:android:215a22700e1b466b",
"android_client_info": {
"package_name": "io.flutter.plugins.firebaseperformanceexample"
}
},
"oauth_client": [
{
"client_id": "479882132969-8h4kiv8m7ho4tvn6uuujsfcrf69unuf7.apps.googleusercontent.com",
"client_type": 1,
"android_info": {
"package_name": "io.flutter.plugins.firebaseperformanceexample",
"certificate_hash": "e733b7a303250b63e06de6f7c9767c517d69cfa0"
}
},
{
"client_id": "479882132969-0d20fkjtr1p8evfomfkf3vmi50uajml2.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyCrZz9T0Pg0rDnpxfNuPBrOxGhXskfebXs"
}
],
"services": {
"analytics_service": {
"status": 1
},
"appinvite_service": {
"status": 2,
"other_platform_oauth_client": [
{
"client_id": "479882132969-0d20fkjtr1p8evfomfkf3vmi50uajml2.apps.googleusercontent.com",
"client_type": 3
},
{
"client_id": "479882132969-gjp4e63ogu2h6guttj2ie6t3f10ic7i8.apps.googleusercontent.com",
"client_type": 2,
"ios_info": {
"bundle_id": "io.flutter.plugins.firebaseMlVisionExample"
}
}
]
},
"ads_service": {
"status": 2
}
}
},
{
"client_info": {
"mobilesdk_app_id": "1:479882132969:android:5e9f1f89e134dc86",
"android_client_info": {
"package_name": "io.flutter.plugins.googlesigninexample"
}
},
"oauth_client": [
{
"client_id": "479882132969-90ml692hkonp587sl0v0rurmnvkekgrg.apps.googleusercontent.com",
"client_type": 1,
"android_info": {
"package_name": "io.flutter.plugins.googlesigninexample",
"certificate_hash": "e733b7a303250b63e06de6f7c9767c517d69cfa0"
}
},
{
"client_id": "479882132969-0d20fkjtr1p8evfomfkf3vmi50uajml2.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyCrZz9T0Pg0rDnpxfNuPBrOxGhXskfebXs"
}
],
"services": {
"analytics_service": {
"status": 1
},
"appinvite_service": {
"status": 2,
"other_platform_oauth_client": [
{
"client_id": "479882132969-0d20fkjtr1p8evfomfkf3vmi50uajml2.apps.googleusercontent.com",
"client_type": 3
},
{
"client_id": "479882132969-gjp4e63ogu2h6guttj2ie6t3f10ic7i8.apps.googleusercontent.com",
"client_type": 2,
"ios_info": {
"bundle_id": "io.flutter.plugins.firebaseMlVisionExample"
}
}
]
},
"ads_service": {
"status": 2
}
}
}
],
"configuration_version": "1"
} | plugins/packages/google_sign_in/google_sign_in/example/android/app/google-services.json/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in/example/android/app/google-services.json",
"repo_id": "plugins",
"token_count": 4364
} | 1,221 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'google_sign_in_test.mocks.dart';
/// Verify that [GoogleSignInAccount] can be mocked even though it's unused
// ignore: avoid_implementing_value_types, must_be_immutable
class MockGoogleSignInAccount extends Mock implements GoogleSignInAccount {}
@GenerateMocks(<Type>[GoogleSignInPlatform])
void main() {
late MockGoogleSignInPlatform mockPlatform;
group('GoogleSignIn', () {
final GoogleSignInUserData kDefaultUser = GoogleSignInUserData(
email: '[email protected]',
id: '8162538176523816253123',
photoUrl: 'https://lh5.googleusercontent.com/photo.jpg',
displayName: 'John Doe',
serverAuthCode: '789');
setUp(() {
mockPlatform = MockGoogleSignInPlatform();
when(mockPlatform.isMock).thenReturn(true);
when(mockPlatform.signInSilently())
.thenAnswer((Invocation _) async => kDefaultUser);
when(mockPlatform.signIn())
.thenAnswer((Invocation _) async => kDefaultUser);
GoogleSignInPlatform.instance = mockPlatform;
});
test('signInSilently', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
await googleSignIn.signInSilently();
expect(googleSignIn.currentUser, isNotNull);
_verifyInit(mockPlatform);
verify(mockPlatform.signInSilently());
});
test('signIn', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
await googleSignIn.signIn();
expect(googleSignIn.currentUser, isNotNull);
_verifyInit(mockPlatform);
verify(mockPlatform.signIn());
});
test('clientId parameter is forwarded to implementation', () async {
const String fakeClientId = 'fakeClientId';
final GoogleSignIn googleSignIn = GoogleSignIn(clientId: fakeClientId);
await googleSignIn.signIn();
_verifyInit(mockPlatform, clientId: fakeClientId);
verify(mockPlatform.signIn());
});
test('serverClientId parameter is forwarded to implementation', () async {
const String fakeServerClientId = 'fakeServerClientId';
final GoogleSignIn googleSignIn =
GoogleSignIn(serverClientId: fakeServerClientId);
await googleSignIn.signIn();
_verifyInit(mockPlatform, serverClientId: fakeServerClientId);
verify(mockPlatform.signIn());
});
test('forceCodeForRefreshToken sent with init method call', () async {
final GoogleSignIn googleSignIn =
GoogleSignIn(forceCodeForRefreshToken: true);
await googleSignIn.signIn();
_verifyInit(mockPlatform, forceCodeForRefreshToken: true);
verify(mockPlatform.signIn());
});
test('signOut', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
await googleSignIn.signOut();
_verifyInit(mockPlatform);
verify(mockPlatform.signOut());
});
test('disconnect; null response', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
await googleSignIn.disconnect();
expect(googleSignIn.currentUser, isNull);
_verifyInit(mockPlatform);
verify(mockPlatform.disconnect());
});
test('isSignedIn', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
when(mockPlatform.isSignedIn()).thenAnswer((Invocation _) async => true);
final bool result = await googleSignIn.isSignedIn();
expect(result, isTrue);
_verifyInit(mockPlatform);
verify(mockPlatform.isSignedIn());
});
test('signIn works even if a previous call throws error in other zone',
() async {
final GoogleSignIn googleSignIn = GoogleSignIn();
when(mockPlatform.signInSilently()).thenThrow(Exception('Not a user'));
await runZonedGuarded(() async {
expect(await googleSignIn.signInSilently(), isNull);
}, (Object e, StackTrace st) {});
expect(await googleSignIn.signIn(), isNotNull);
_verifyInit(mockPlatform);
verify(mockPlatform.signInSilently());
verify(mockPlatform.signIn());
});
test('concurrent calls of the same method trigger sign in once', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
final List<Future<GoogleSignInAccount?>> futures =
<Future<GoogleSignInAccount?>>[
googleSignIn.signInSilently(),
googleSignIn.signInSilently(),
];
expect(futures.first, isNot(futures.last),
reason: 'Must return new Future');
final List<GoogleSignInAccount?> users = await Future.wait(futures);
expect(googleSignIn.currentUser, isNotNull);
expect(users, <GoogleSignInAccount?>[
googleSignIn.currentUser,
googleSignIn.currentUser
]);
_verifyInit(mockPlatform);
verify(mockPlatform.signInSilently()).called(1);
});
test('can sign in after previously failed attempt', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
when(mockPlatform.signInSilently()).thenThrow(Exception('Not a user'));
expect(await googleSignIn.signInSilently(), isNull);
expect(await googleSignIn.signIn(), isNotNull);
_verifyInit(mockPlatform);
verify(mockPlatform.signInSilently());
verify(mockPlatform.signIn());
});
test('concurrent calls of different signIn methods', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
final List<Future<GoogleSignInAccount?>> futures =
<Future<GoogleSignInAccount?>>[
googleSignIn.signInSilently(),
googleSignIn.signIn(),
];
expect(futures.first, isNot(futures.last));
final List<GoogleSignInAccount?> users = await Future.wait(futures);
expect(users.first, users.last, reason: 'Must return the same user');
expect(googleSignIn.currentUser, users.last);
_verifyInit(mockPlatform);
verify(mockPlatform.signInSilently());
verifyNever(mockPlatform.signIn());
});
test('can sign in after aborted flow', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
when(mockPlatform.signIn()).thenAnswer((Invocation _) async => null);
expect(await googleSignIn.signIn(), isNull);
when(mockPlatform.signIn())
.thenAnswer((Invocation _) async => kDefaultUser);
expect(await googleSignIn.signIn(), isNotNull);
});
test('signOut/disconnect methods always trigger native calls', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
final List<Future<GoogleSignInAccount?>> futures =
<Future<GoogleSignInAccount?>>[
googleSignIn.signOut(),
googleSignIn.signOut(),
googleSignIn.disconnect(),
googleSignIn.disconnect(),
];
await Future.wait(futures);
_verifyInit(mockPlatform);
verify(mockPlatform.signOut()).called(2);
verify(mockPlatform.disconnect()).called(2);
});
test('queue of many concurrent calls', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
final List<Future<GoogleSignInAccount?>> futures =
<Future<GoogleSignInAccount?>>[
googleSignIn.signInSilently(),
googleSignIn.signOut(),
googleSignIn.signIn(),
googleSignIn.disconnect(),
];
await Future.wait(futures);
_verifyInit(mockPlatform);
verifyInOrder(<Object>[
mockPlatform.signInSilently(),
mockPlatform.signOut(),
mockPlatform.signIn(),
mockPlatform.disconnect(),
]);
});
test('signInSilently suppresses errors by default', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
when(mockPlatform.signInSilently()).thenThrow(Exception('I am an error'));
expect(await googleSignIn.signInSilently(), isNull); // should not throw
});
test('signInSilently forwards exceptions', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
when(mockPlatform.signInSilently()).thenThrow(Exception('I am an error'));
expect(googleSignIn.signInSilently(suppressErrors: false),
throwsA(isInstanceOf<Exception>()));
});
test('signInSilently allows re-authentication to be requested', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
await googleSignIn.signInSilently();
expect(googleSignIn.currentUser, isNotNull);
await googleSignIn.signInSilently(reAuthenticate: true);
_verifyInit(mockPlatform);
verify(mockPlatform.signInSilently()).called(2);
});
test('can sign in after init failed before', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
when(mockPlatform.initWithParams(any))
.thenThrow(Exception('First init fails'));
expect(googleSignIn.signIn(), throwsA(isInstanceOf<Exception>()));
when(mockPlatform.initWithParams(any))
.thenAnswer((Invocation _) async {});
expect(await googleSignIn.signIn(), isNotNull);
});
test('created with standard factory uses correct options', () async {
final GoogleSignIn googleSignIn = GoogleSignIn.standard();
await googleSignIn.signInSilently();
expect(googleSignIn.currentUser, isNotNull);
_verifyInit(mockPlatform);
verify(mockPlatform.signInSilently());
});
test('created with defaultGamesSignIn factory uses correct options',
() async {
final GoogleSignIn googleSignIn = GoogleSignIn.games();
await googleSignIn.signInSilently();
expect(googleSignIn.currentUser, isNotNull);
_verifyInit(mockPlatform, signInOption: SignInOption.games);
verify(mockPlatform.signInSilently());
});
test('authentication', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
when(mockPlatform.getTokens(
email: anyNamed('email'),
shouldRecoverAuth: anyNamed('shouldRecoverAuth')))
.thenAnswer((Invocation _) async => GoogleSignInTokenData(
idToken: '123',
accessToken: '456',
serverAuthCode: '789',
));
await googleSignIn.signIn();
final GoogleSignInAccount user = googleSignIn.currentUser!;
final GoogleSignInAuthentication auth = await user.authentication;
expect(auth.accessToken, '456');
expect(auth.idToken, '123');
verify(mockPlatform.getTokens(
email: '[email protected]', shouldRecoverAuth: true));
});
test('requestScopes returns true once new scope is granted', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
when(mockPlatform.requestScopes(any))
.thenAnswer((Invocation _) async => true);
await googleSignIn.signIn();
final bool result =
await googleSignIn.requestScopes(<String>['testScope']);
expect(result, isTrue);
_verifyInit(mockPlatform);
verify(mockPlatform.signIn());
verify(mockPlatform.requestScopes(<String>['testScope']));
});
test('user starts as null', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
expect(googleSignIn.currentUser, isNull);
});
test('can sign in and sign out', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
await googleSignIn.signIn();
final GoogleSignInAccount user = googleSignIn.currentUser!;
expect(user.displayName, equals(kDefaultUser.displayName));
expect(user.email, equals(kDefaultUser.email));
expect(user.id, equals(kDefaultUser.id));
expect(user.photoUrl, equals(kDefaultUser.photoUrl));
expect(user.serverAuthCode, equals(kDefaultUser.serverAuthCode));
await googleSignIn.disconnect();
expect(googleSignIn.currentUser, isNull);
});
test('disconnect when signout already succeeds', () async {
final GoogleSignIn googleSignIn = GoogleSignIn();
await googleSignIn.disconnect();
expect(googleSignIn.currentUser, isNull);
});
});
}
void _verifyInit(
MockGoogleSignInPlatform mockSignIn, {
List<String> scopes = const <String>[],
SignInOption signInOption = SignInOption.standard,
String? hostedDomain,
String? clientId,
String? serverClientId,
bool forceCodeForRefreshToken = false,
}) {
verify(mockSignIn.initWithParams(argThat(
isA<SignInInitParameters>()
.having(
(SignInInitParameters p) => p.scopes,
'scopes',
scopes,
)
.having(
(SignInInitParameters p) => p.signInOption,
'signInOption',
signInOption,
)
.having(
(SignInInitParameters p) => p.hostedDomain,
'hostedDomain',
hostedDomain,
)
.having(
(SignInInitParameters p) => p.clientId,
'clientId',
clientId,
)
.having(
(SignInInitParameters p) => p.serverClientId,
'serverClientId',
serverClientId,
)
.having(
(SignInInitParameters p) => p.forceCodeForRefreshToken,
'forceCodeForRefreshToken',
forceCodeForRefreshToken,
),
)));
}
| plugins/packages/google_sign_in/google_sign_in/test/google_sign_in_test.dart/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in/test/google_sign_in_test.dart",
"repo_id": "plugins",
"token_count": 5155
} | 1,222 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>Google Sign-In Example</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>GoogleSignInExample</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>com.googleusercontent.apps.479882132969-9i9aqik3jfjd7qhci1nqf0bm2g71rm1u</string>
</array>
</dict>
</array>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
</dict>
</plist>
| plugins/packages/google_sign_in/google_sign_in_ios/example/ios/Runner/Info.plist/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_ios/example/ios/Runner/Info.plist",
"repo_id": "plugins",
"token_count": 798
} | 1,223 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:flutter/services.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
import 'src/utils.dart';
/// iOS implementation of [GoogleSignInPlatform].
class GoogleSignInIOS extends GoogleSignInPlatform {
/// This is only exposed for test purposes. It shouldn't be used by clients of
/// the plugin as it may break or change at any time.
@visibleForTesting
MethodChannel channel =
const MethodChannel('plugins.flutter.io/google_sign_in_ios');
/// Registers this class as the default instance of [GoogleSignInPlatform].
static void registerWith() {
GoogleSignInPlatform.instance = GoogleSignInIOS();
}
@override
Future<void> init({
List<String> scopes = const <String>[],
SignInOption signInOption = SignInOption.standard,
String? hostedDomain,
String? clientId,
}) {
return initWithParams(SignInInitParameters(
signInOption: signInOption,
scopes: scopes,
hostedDomain: hostedDomain,
clientId: clientId,
));
}
@override
Future<void> initWithParams(SignInInitParameters params) {
if (params.signInOption == SignInOption.games) {
throw PlatformException(
code: 'unsupported-options',
message: 'Games sign in is not supported on iOS');
}
return channel.invokeMethod<void>('init', <String, dynamic>{
'scopes': params.scopes,
'hostedDomain': params.hostedDomain,
'clientId': params.clientId,
'serverClientId': params.serverClientId,
});
}
@override
Future<GoogleSignInUserData?> signInSilently() {
return channel
.invokeMapMethod<String, dynamic>('signInSilently')
.then(getUserDataFromMap);
}
@override
Future<GoogleSignInUserData?> signIn() {
return channel
.invokeMapMethod<String, dynamic>('signIn')
.then(getUserDataFromMap);
}
@override
Future<GoogleSignInTokenData> getTokens(
{required String email, bool? shouldRecoverAuth = true}) {
return channel
.invokeMapMethod<String, dynamic>('getTokens', <String, dynamic>{
'email': email,
'shouldRecoverAuth': shouldRecoverAuth,
}).then((Map<String, dynamic>? result) => getTokenDataFromMap(result!));
}
@override
Future<void> signOut() {
return channel.invokeMapMethod<String, dynamic>('signOut');
}
@override
Future<void> disconnect() {
return channel.invokeMapMethod<String, dynamic>('disconnect');
}
@override
Future<bool> isSignedIn() async {
return (await channel.invokeMethod<bool>('isSignedIn'))!;
}
@override
Future<void> clearAuthCache({String? token}) async {
// There's nothing to be done here on iOS since the expired/invalid
// tokens are refreshed automatically by getTokens.
}
@override
Future<bool> requestScopes(List<String> scopes) async {
return (await channel.invokeMethod<bool>(
'requestScopes',
<String, List<String>>{'scopes': scopes},
))!;
}
}
| plugins/packages/google_sign_in/google_sign_in_ios/lib/google_sign_in_ios.dart/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_ios/lib/google_sign_in_ios.dart",
"repo_id": "plugins",
"token_count": 1121
} | 1,224 |
## 0.11.0
* **Breaking Change:** Migrates JS-interop to `package:google_identity_services_web`
* Uses the new Google Identity Authentication and Authorization JS SDKs. [Docs](https://developers.google.com/identity).
* Added "Migrating to v0.11" section to the `README.md`.
* Updates minimum Flutter version to 3.0.
## 0.10.2+1
* Updates code for `no_leading_underscores_for_local_identifiers` lint.
* Updates minimum Flutter version to 2.10.
* Renames generated folder to js_interop.
## 0.10.2
* Migrates to new platform-interface `initWithParams` method.
* Throws when unsupported `serverClientId` option is provided.
## 0.10.1+3
* Updates references to the obsolete master branch.
## 0.10.1+2
* Minor fixes for new analysis options.
## 0.10.1+1
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.10.1
* Updates minimum Flutter version to 2.8.
* Passes `plugin_name` to Google Sign-In's `init` method so new applications can
continue using this plugin after April 30th 2022. Issue [#88084](https://github.com/flutter/flutter/issues/88084).
## 0.10.0+5
* Internal code cleanup for stricter analysis options.
## 0.10.0+4
* Removes dependency on `meta`.
## 0.10.0+3
* Updated URL to the `google_sign_in` package in README.
## 0.10.0+2
* Add `implements` to pubspec.
## 0.10.0+1
* Updated installation instructions in README.
## 0.10.0
* Migrate to null-safety.
## 0.9.2+1
* Update Flutter SDK constraint.
## 0.9.2
* Throw PlatformExceptions from where the GMaps SDK may throw exceptions: `init()` and `signIn()`.
* Add two new JS-interop types to be able to unwrap JS errors in release mode.
* Align the fields of the thrown PlatformExceptions with the mobile version.
* Migrate tests to run with `flutter drive`
## 0.9.1+2
* Update package:e2e reference to use the local version in the flutter/plugins
repository.
## 0.9.1+1
* Remove Android folder from `google_sign_in_web`.
## 0.9.1
* Ensure the web code returns `null` when the user is not signed in, instead of a `null-object` User. Fixes [issue 52338](https://github.com/flutter/flutter/issues/52338).
## 0.9.0
* Add support for methods introduced in `google_sign_in_platform_interface` 1.1.0.
## 0.8.4
* Remove all `fakeConstructor$` from the generated facade. JS interop classes do not support non-external constructors.
## 0.8.3+2
* Make the pedantic dev_dependency explicit.
## 0.8.3+1
* Updated documentation with more instructions about Google Sign In web setup.
## 0.8.3
* Fix initialization error that causes https://github.com/flutter/flutter/issues/48527
* Throw a PlatformException when there's an initialization problem (like wrong server-side config).
* Throw a StateError when checking .initialized before calling .init()
* Update setup instructions in the README.
## 0.8.2+1
* Add a non-op Android implementation to avoid a flaky Gradle issue.
## 0.8.2
* Require Flutter SDK 1.12.13+hotfix.4 or greater.
## 0.8.1+2
* Remove the deprecated `author:` field from pubspec.yaml
* Require Flutter SDK 1.10.0 or greater.
## 0.8.1+1
* Add missing documentation.
## 0.8.1
* Add podspec to enable compilation on iOS.
## 0.8.0
* Flutter for web initial release
| plugins/packages/google_sign_in/google_sign_in_web/CHANGELOG.md/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_web/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 1083
} | 1,225 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>image_picker_example</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSCameraUsageDescription</key>
<string>Used to demonstrate image picker plugin</string>
<key>NSMicrophoneUsageDescription</key>
<string>Used to capture audio for image picker plugin</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Used to demonstrate image picker plugin</string>
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
</array>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>
| plugins/packages/image_picker/image_picker/example/ios/Runner/Info.plist/0 | {
"file_path": "plugins/packages/image_picker/image_picker/example/ios/Runner/Info.plist",
"repo_id": "plugins",
"token_count": 732
} | 1,226 |
name: image_picker
description: Flutter plugin for selecting images from the Android and iOS image
library, and taking new pictures with the camera.
repository: https://github.com/flutter/plugins/tree/main/packages/image_picker/image_picker
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+image_picker%22
version: 0.8.6+2
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
platforms:
android:
default_package: image_picker_android
ios:
default_package: image_picker_ios
web:
default_package: image_picker_for_web
dependencies:
flutter:
sdk: flutter
image_picker_android: ^0.8.4+11
image_picker_for_web: ^2.1.0
image_picker_ios: ^0.8.6+1
image_picker_platform_interface: ^2.6.1
dev_dependencies:
build_runner: ^2.1.10
cross_file: ^0.3.1+1 # Mockito generates a direct include.
flutter_test:
sdk: flutter
mockito: ^5.0.0
plugin_platform_interface: ^2.0.0
| plugins/packages/image_picker/image_picker/pubspec.yaml/0 | {
"file_path": "plugins/packages/image_picker/image_picker/pubspec.yaml",
"repo_id": "plugins",
"token_count": 429
} | 1,227 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.imagepicker;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.embedding.engine.plugins.lifecycle.FlutterLifecycleAdapter;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.PluginRegistry;
import java.io.File;
@SuppressWarnings("deprecation")
public class ImagePickerPlugin
implements MethodChannel.MethodCallHandler, FlutterPlugin, ActivityAware {
private class LifeCycleObserver
implements Application.ActivityLifecycleCallbacks, DefaultLifecycleObserver {
private final Activity thisActivity;
LifeCycleObserver(Activity activity) {
this.thisActivity = activity;
}
@Override
public void onCreate(@NonNull LifecycleOwner owner) {}
@Override
public void onStart(@NonNull LifecycleOwner owner) {}
@Override
public void onResume(@NonNull LifecycleOwner owner) {}
@Override
public void onPause(@NonNull LifecycleOwner owner) {}
@Override
public void onStop(@NonNull LifecycleOwner owner) {
onActivityStopped(thisActivity);
}
@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
onActivityDestroyed(thisActivity);
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
@Override
public void onActivityStarted(Activity activity) {}
@Override
public void onActivityResumed(Activity activity) {}
@Override
public void onActivityPaused(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
@Override
public void onActivityDestroyed(Activity activity) {
if (thisActivity == activity && activity.getApplicationContext() != null) {
((Application) activity.getApplicationContext())
.unregisterActivityLifecycleCallbacks(
this); // Use getApplicationContext() to avoid casting failures
}
}
@Override
public void onActivityStopped(Activity activity) {
if (thisActivity == activity) {
activityState.getDelegate().saveStateBeforeResult();
}
}
}
/**
* Move all activity-lifetime-bound states into this helper object, so that {@code setup} and
* {@code tearDown} would just become constructor and finalize calls of the helper object.
*/
private class ActivityState {
private Application application;
private Activity activity;
private ImagePickerDelegate delegate;
private MethodChannel channel;
private LifeCycleObserver observer;
private ActivityPluginBinding activityBinding;
// This is null when not using v2 embedding;
private Lifecycle lifecycle;
// Default constructor
ActivityState(
final Application application,
final Activity activity,
final BinaryMessenger messenger,
final MethodChannel.MethodCallHandler handler,
final PluginRegistry.Registrar registrar,
final ActivityPluginBinding activityBinding) {
this.application = application;
this.activity = activity;
this.activityBinding = activityBinding;
delegate = constructDelegate(activity);
channel = new MethodChannel(messenger, CHANNEL);
channel.setMethodCallHandler(handler);
observer = new LifeCycleObserver(activity);
if (registrar != null) {
// V1 embedding setup for activity listeners.
application.registerActivityLifecycleCallbacks(observer);
registrar.addActivityResultListener(delegate);
registrar.addRequestPermissionsResultListener(delegate);
} else {
// V2 embedding setup for activity listeners.
activityBinding.addActivityResultListener(delegate);
activityBinding.addRequestPermissionsResultListener(delegate);
lifecycle = FlutterLifecycleAdapter.getActivityLifecycle(activityBinding);
lifecycle.addObserver(observer);
}
}
// Only invoked by {@link #ImagePickerPlugin(ImagePickerDelegate, Activity)} for testing.
ActivityState(final ImagePickerDelegate delegate, final Activity activity) {
this.activity = activity;
this.delegate = delegate;
}
void release() {
if (activityBinding != null) {
activityBinding.removeActivityResultListener(delegate);
activityBinding.removeRequestPermissionsResultListener(delegate);
activityBinding = null;
}
if (lifecycle != null) {
lifecycle.removeObserver(observer);
lifecycle = null;
}
if (channel != null) {
channel.setMethodCallHandler(null);
channel = null;
}
if (application != null) {
application.unregisterActivityLifecycleCallbacks(observer);
application = null;
}
activity = null;
observer = null;
delegate = null;
}
Activity getActivity() {
return activity;
}
ImagePickerDelegate getDelegate() {
return delegate;
}
}
static final String METHOD_CALL_IMAGE = "pickImage";
static final String METHOD_CALL_MULTI_IMAGE = "pickMultiImage";
static final String METHOD_CALL_VIDEO = "pickVideo";
private static final String METHOD_CALL_RETRIEVE = "retrieve";
private static final int CAMERA_DEVICE_FRONT = 1;
private static final int CAMERA_DEVICE_REAR = 0;
private static final String CHANNEL = "plugins.flutter.io/image_picker_android";
private static final int SOURCE_CAMERA = 0;
private static final int SOURCE_GALLERY = 1;
private FlutterPluginBinding pluginBinding;
private ActivityState activityState;
@SuppressWarnings("deprecation")
public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) {
if (registrar.activity() == null) {
// If a background flutter view tries to register the plugin, there will be no activity from the registrar,
// we stop the registering process immediately because the ImagePicker requires an activity.
return;
}
Activity activity = registrar.activity();
Application application = null;
if (registrar.context() != null) {
application = (Application) (registrar.context().getApplicationContext());
}
ImagePickerPlugin plugin = new ImagePickerPlugin();
plugin.setup(registrar.messenger(), application, activity, registrar, null);
}
/**
* Default constructor for the plugin.
*
* <p>Use this constructor for production code.
*/
// See also: * {@link #ImagePickerPlugin(ImagePickerDelegate, Activity)} for testing.
public ImagePickerPlugin() {}
@VisibleForTesting
ImagePickerPlugin(final ImagePickerDelegate delegate, final Activity activity) {
activityState = new ActivityState(delegate, activity);
}
@VisibleForTesting
final ActivityState getActivityState() {
return activityState;
}
@Override
public void onAttachedToEngine(FlutterPluginBinding binding) {
pluginBinding = binding;
}
@Override
public void onDetachedFromEngine(FlutterPluginBinding binding) {
pluginBinding = null;
}
@Override
public void onAttachedToActivity(ActivityPluginBinding binding) {
setup(
pluginBinding.getBinaryMessenger(),
(Application) pluginBinding.getApplicationContext(),
binding.getActivity(),
null,
binding);
}
@Override
public void onDetachedFromActivity() {
tearDown();
}
@Override
public void onDetachedFromActivityForConfigChanges() {
onDetachedFromActivity();
}
@Override
public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) {
onAttachedToActivity(binding);
}
private void setup(
final BinaryMessenger messenger,
final Application application,
final Activity activity,
final PluginRegistry.Registrar registrar,
final ActivityPluginBinding activityBinding) {
activityState =
new ActivityState(application, activity, messenger, this, registrar, activityBinding);
}
private void tearDown() {
if (activityState != null) {
activityState.release();
activityState = null;
}
}
@VisibleForTesting
final ImagePickerDelegate constructDelegate(final Activity setupActivity) {
final ImagePickerCache cache = new ImagePickerCache(setupActivity);
final File externalFilesDirectory = setupActivity.getCacheDir();
final ExifDataCopier exifDataCopier = new ExifDataCopier();
final ImageResizer imageResizer = new ImageResizer(externalFilesDirectory, exifDataCopier);
return new ImagePickerDelegate(setupActivity, externalFilesDirectory, imageResizer, cache);
}
// MethodChannel.Result wrapper that responds on the platform thread.
private static class MethodResultWrapper implements MethodChannel.Result {
private MethodChannel.Result methodResult;
private Handler handler;
MethodResultWrapper(MethodChannel.Result result) {
methodResult = result;
handler = new Handler(Looper.getMainLooper());
}
@Override
public void success(final Object result) {
handler.post(
new Runnable() {
@Override
public void run() {
methodResult.success(result);
}
});
}
@Override
public void error(
final String errorCode, final String errorMessage, final Object errorDetails) {
handler.post(
new Runnable() {
@Override
public void run() {
methodResult.error(errorCode, errorMessage, errorDetails);
}
});
}
@Override
public void notImplemented() {
handler.post(
new Runnable() {
@Override
public void run() {
methodResult.notImplemented();
}
});
}
}
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result rawResult) {
if (activityState == null || activityState.getActivity() == null) {
rawResult.error("no_activity", "image_picker plugin requires a foreground activity.", null);
return;
}
MethodChannel.Result result = new MethodResultWrapper(rawResult);
int imageSource;
ImagePickerDelegate delegate = activityState.getDelegate();
if (call.argument("cameraDevice") != null) {
CameraDevice device;
int deviceIntValue = call.argument("cameraDevice");
if (deviceIntValue == CAMERA_DEVICE_FRONT) {
device = CameraDevice.FRONT;
} else {
device = CameraDevice.REAR;
}
delegate.setCameraDevice(device);
}
switch (call.method) {
case METHOD_CALL_IMAGE:
imageSource = call.argument("source");
switch (imageSource) {
case SOURCE_GALLERY:
delegate.chooseImageFromGallery(call, result);
break;
case SOURCE_CAMERA:
delegate.takeImageWithCamera(call, result);
break;
default:
throw new IllegalArgumentException("Invalid image source: " + imageSource);
}
break;
case METHOD_CALL_MULTI_IMAGE:
delegate.chooseMultiImageFromGallery(call, result);
break;
case METHOD_CALL_VIDEO:
imageSource = call.argument("source");
switch (imageSource) {
case SOURCE_GALLERY:
delegate.chooseVideoFromGallery(call, result);
break;
case SOURCE_CAMERA:
delegate.takeVideoWithCamera(call, result);
break;
default:
throw new IllegalArgumentException("Invalid video source: " + imageSource);
}
break;
case METHOD_CALL_RETRIEVE:
delegate.retrieveLostImage(result);
break;
default:
throw new IllegalArgumentException("Unknown method " + call.method);
}
}
}
| plugins/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerPlugin.java/0 | {
"file_path": "plugins/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerPlugin.java",
"repo_id": "plugins",
"token_count": 4386
} | 1,228 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FLTImagePickerImageUtil.h"
#import <MobileCoreServices/MobileCoreServices.h>
@interface GIFInfo ()
@property(strong, nonatomic, readwrite) NSArray<UIImage *> *images;
@property(assign, nonatomic, readwrite) NSTimeInterval interval;
@end
@implementation GIFInfo
- (instancetype)initWithImages:(NSArray<UIImage *> *)images interval:(NSTimeInterval)interval;
{
self = [super init];
if (self) {
self.images = images;
self.interval = interval;
}
return self;
}
@end
@implementation FLTImagePickerImageUtil : NSObject
+ (UIImage *)scaledImage:(UIImage *)image
maxWidth:(NSNumber *)maxWidth
maxHeight:(NSNumber *)maxHeight
isMetadataAvailable:(BOOL)isMetadataAvailable {
double originalWidth = image.size.width;
double originalHeight = image.size.height;
bool hasMaxWidth = maxWidth != nil;
bool hasMaxHeight = maxHeight != nil;
double width = hasMaxWidth ? MIN([maxWidth doubleValue], originalWidth) : originalWidth;
double height = hasMaxHeight ? MIN([maxHeight doubleValue], originalHeight) : originalHeight;
bool shouldDownscaleWidth = hasMaxWidth && [maxWidth doubleValue] < originalWidth;
bool shouldDownscaleHeight = hasMaxHeight && [maxHeight doubleValue] < originalHeight;
bool shouldDownscale = shouldDownscaleWidth || shouldDownscaleHeight;
if (shouldDownscale) {
double downscaledWidth = floor((height / originalHeight) * originalWidth);
double downscaledHeight = floor((width / originalWidth) * originalHeight);
if (width < height) {
if (!hasMaxWidth) {
width = downscaledWidth;
} else {
height = downscaledHeight;
}
} else if (height < width) {
if (!hasMaxHeight) {
height = downscaledHeight;
} else {
width = downscaledWidth;
}
} else {
if (originalWidth < originalHeight) {
width = downscaledWidth;
} else if (originalHeight < originalWidth) {
height = downscaledHeight;
}
}
}
if (!isMetadataAvailable) {
UIImage *imageToScale = [UIImage imageWithCGImage:image.CGImage
scale:1
orientation:image.imageOrientation];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 1.0);
[imageToScale drawInRect:CGRectMake(0, 0, width, height)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
// Scaling the image always rotate itself based on the current imageOrientation of the original
// Image. Set to orientationUp for the orignal image before scaling, so the scaled image doesn't
// mess up with the pixels.
UIImage *imageToScale = [UIImage imageWithCGImage:image.CGImage
scale:1
orientation:UIImageOrientationUp];
// The image orientation is manually set to UIImageOrientationUp which swapped the aspect ratio in
// some scenarios. For example, when the original image has orientation left, the horizontal
// pixels should be scaled to `width` and the vertical pixels should be scaled to `height`. After
// setting the orientation to up, we end up scaling the horizontal pixels to `height` and vertical
// to `width`. Below swap will solve this issue.
if ([image imageOrientation] == UIImageOrientationLeft ||
[image imageOrientation] == UIImageOrientationRight ||
[image imageOrientation] == UIImageOrientationLeftMirrored ||
[image imageOrientation] == UIImageOrientationRightMirrored) {
double temp = width;
width = height;
height = temp;
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 1.0);
[imageToScale drawInRect:CGRectMake(0, 0, width, height)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
+ (GIFInfo *)scaledGIFImage:(NSData *)data
maxWidth:(NSNumber *)maxWidth
maxHeight:(NSNumber *)maxHeight {
NSMutableDictionary<NSString *, id> *options = [NSMutableDictionary dictionary];
options[(NSString *)kCGImageSourceShouldCache] = @YES;
options[(NSString *)kCGImageSourceTypeIdentifierHint] = (NSString *)kUTTypeGIF;
CGImageSourceRef imageSource =
CGImageSourceCreateWithData((__bridge CFDataRef)data, (__bridge CFDictionaryRef)options);
size_t numberOfFrames = CGImageSourceGetCount(imageSource);
NSMutableArray<UIImage *> *images = [NSMutableArray arrayWithCapacity:numberOfFrames];
NSTimeInterval interval = 0.0;
for (size_t index = 0; index < numberOfFrames; index++) {
CGImageRef imageRef =
CGImageSourceCreateImageAtIndex(imageSource, index, (__bridge CFDictionaryRef)options);
NSDictionary *properties = (NSDictionary *)CFBridgingRelease(
CGImageSourceCopyPropertiesAtIndex(imageSource, index, NULL));
NSDictionary *gifProperties = properties[(NSString *)kCGImagePropertyGIFDictionary];
NSNumber *delay = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
if (delay == nil) {
delay = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
}
if (interval == 0.0) {
interval = [delay doubleValue];
}
UIImage *image = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:UIImageOrientationUp];
image = [self scaledImage:image maxWidth:maxWidth maxHeight:maxHeight isMetadataAvailable:YES];
[images addObject:image];
CGImageRelease(imageRef);
}
CFRelease(imageSource);
GIFInfo *info = [[GIFInfo alloc] initWithImages:images interval:interval];
return info;
}
@end
| plugins/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerImageUtil.m/0 | {
"file_path": "plugins/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerImageUtil.m",
"repo_id": "plugins",
"token_count": 2058
} | 1,229 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v3.0.3), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name
// @dart = 2.12
import 'dart:async';
import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List;
import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer;
import 'package:flutter/services.dart';
enum SourceCamera {
rear,
front,
}
enum SourceType {
camera,
gallery,
}
class MaxSize {
MaxSize({
this.width,
this.height,
});
double? width;
double? height;
Object encode() {
final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
pigeonMap['width'] = width;
pigeonMap['height'] = height;
return pigeonMap;
}
static MaxSize decode(Object message) {
final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
return MaxSize(
width: pigeonMap['width'] as double?,
height: pigeonMap['height'] as double?,
);
}
}
class SourceSpecification {
SourceSpecification({
required this.type,
this.camera,
});
SourceType type;
SourceCamera? camera;
Object encode() {
final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
pigeonMap['type'] = type.index;
pigeonMap['camera'] = camera?.index;
return pigeonMap;
}
static SourceSpecification decode(Object message) {
final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
return SourceSpecification(
type: SourceType.values[pigeonMap['type']! as int],
camera: pigeonMap['camera'] != null
? SourceCamera.values[pigeonMap['camera']! as int]
: null,
);
}
}
class _ImagePickerApiCodec extends StandardMessageCodec {
const _ImagePickerApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is MaxSize) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is SourceSpecification) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return MaxSize.decode(readValue(buffer)!);
case 129:
return SourceSpecification.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
class ImagePickerApi {
/// Constructor for [ImagePickerApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
ImagePickerApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _ImagePickerApiCodec();
Future<String?> pickImage(SourceSpecification arg_source, MaxSize arg_maxSize,
int? arg_imageQuality, bool arg_requestFullMetadata) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ImagePickerApi.pickImage', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = await channel.send(<Object?>[
arg_source,
arg_maxSize,
arg_imageQuality,
arg_requestFullMetadata
]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return (replyMap['result'] as String?);
}
}
Future<List<String?>?> pickMultiImage(MaxSize arg_maxSize,
int? arg_imageQuality, bool arg_requestFullMetadata) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ImagePickerApi.pickMultiImage', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = await channel.send(
<Object?>[arg_maxSize, arg_imageQuality, arg_requestFullMetadata])
as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return (replyMap['result'] as List<Object?>?)?.cast<String?>();
}
}
Future<String?> pickVideo(
SourceSpecification arg_source, int? arg_maxDurationSeconds) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ImagePickerApi.pickVideo', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_source, arg_maxDurationSeconds])
as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return (replyMap['result'] as String?);
}
}
}
| plugins/packages/image_picker/image_picker_ios/lib/src/messages.g.dart/0 | {
"file_path": "plugins/packages/image_picker/image_picker_ios/lib/src/messages.g.dart",
"repo_id": "plugins",
"token_count": 2361
} | 1,230 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Specifies the source where the picked image should come from.
enum ImageSource {
/// Opens up the device camera, letting the user to take a new picture.
camera,
/// Opens the user's photo gallery.
gallery,
}
| plugins/packages/image_picker/image_picker_platform_interface/lib/src/types/image_source.dart/0 | {
"file_path": "plugins/packages/image_picker/image_picker_platform_interface/lib/src/types/image_source.dart",
"repo_id": "plugins",
"token_count": 101
} | 1,231 |
org.gradle.jvmargs=-Xmx4G
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
| plugins/packages/in_app_purchase/in_app_purchase/example/android/gradle.properties/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase/example/android/gradle.properties",
"repo_id": "plugins",
"token_count": 38
} | 1,232 |
name: in_app_purchase_android
description: An implementation for the Android platform of the Flutter `in_app_purchase` plugin. This uses the Android BillingClient APIs.
repository: https://github.com/flutter/plugins/tree/main/packages/in_app_purchase/in_app_purchase_android
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+in_app_purchase%22
version: 0.2.4+1
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: in_app_purchase
platforms:
android:
package: io.flutter.plugins.inapppurchase
pluginClass: InAppPurchasePlugin
dependencies:
collection: ^1.15.0
flutter:
sdk: flutter
in_app_purchase_platform_interface: ^1.3.0
json_annotation: ^4.6.0
dev_dependencies:
build_runner: ^2.0.0
flutter_test:
sdk: flutter
json_serializable: ^6.3.1
mockito: ^5.1.0
test: ^1.16.0
| plugins/packages/in_app_purchase/in_app_purchase_android/pubspec.yaml/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/pubspec.yaml",
"repo_id": "plugins",
"token_count": 382
} | 1,233 |
## 0.3.6
* Updates minimum Flutter version to 3.3 and iOS 11.
## 0.3.5+2
* Fix a crash when `appStoreReceiptURL` is nil.
## 0.3.5+1
* Uses the new `sharedDarwinSource` flag when available.
## 0.3.5
* Updates minimum Flutter version to 3.0.
* Ignores a lint in the example app for backwards compatibility.
## 0.3.4+1
* Updates code for stricter lint checks.
## 0.3.4
* Adds macOS as a supported platform.
## 0.3.3
* Supports adding discount information to AppStorePurchaseParam.
* Fixes iOS Promotional Offers bug which prevents them from working.
## 0.3.2+2
* Updates imports for `prefer_relative_imports`.
## 0.3.2+1
* Updates minimum Flutter version to 2.10.
* Replaces deprecated ThemeData.primaryColor.
## 0.3.2
* Adds the `identifier` and `type` fields to the `SKProductDiscountWrapper` to reflect the changes in the [SKProductDiscount](https://developer.apple.com/documentation/storekit/skproductdiscount?language=objc) in iOS 12.2.
## 0.3.1+1
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 0.3.1
* Adds ability to purchase more than one of a product.
## 0.3.0+10
* Ignores deprecation warnings for upcoming styleFrom button API changes.
## 0.3.0+9
* Updates references to the obsolete master branch.
## 0.3.0+8
* Fixes a memory leak on iOS.
## 0.3.0+7
* Minor fixes for new analysis options.
## 0.3.0+6
* Removes unnecessary imports.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.3.0+5
* Migrates from `ui.hash*` to `Object.hash*`.
## 0.3.0+4
* Ensures that `NSError` instances with an unexpected value for the `userInfo` field don't crash the app, but send an explanatory message instead.
## 0.3.0+3
* Implements transaction caching for StoreKit ensuring transactions are delivered to the Flutter client.
## 0.3.0+2
* Internal code cleanup for stricter analysis options.
## 0.3.0+1
* Removes dependency on `meta`.
## 0.3.0
* **BREAKING CHANGE:** `InAppPurchaseStoreKitPlatform.restorePurchase()` emits an empty instance of `List<ProductDetails>` when there were no transactions to restore, indicating that the restore procedure has finished.
## 0.2.1
* Renames `in_app_purchase_ios` to `in_app_purchase_storekit` to facilitate
future macOS support.
| plugins/packages/in_app_purchase/in_app_purchase_storekit/CHANGELOG.md/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 771
} | 1,234 |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'enum_converters.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_SerializedEnums _$SerializedEnumsFromJson(Map json) => _SerializedEnums()
..response =
$enumDecode(_$SKPaymentTransactionStateWrapperEnumMap, json['response'])
..unit = $enumDecode(_$SKSubscriptionPeriodUnitEnumMap, json['unit'])
..discountPaymentMode = $enumDecode(
_$SKProductDiscountPaymentModeEnumMap, json['discountPaymentMode']);
const _$SKPaymentTransactionStateWrapperEnumMap = {
SKPaymentTransactionStateWrapper.purchasing: 0,
SKPaymentTransactionStateWrapper.purchased: 1,
SKPaymentTransactionStateWrapper.failed: 2,
SKPaymentTransactionStateWrapper.restored: 3,
SKPaymentTransactionStateWrapper.deferred: 4,
SKPaymentTransactionStateWrapper.unspecified: -1,
};
const _$SKSubscriptionPeriodUnitEnumMap = {
SKSubscriptionPeriodUnit.day: 0,
SKSubscriptionPeriodUnit.week: 1,
SKSubscriptionPeriodUnit.month: 2,
SKSubscriptionPeriodUnit.year: 3,
};
const _$SKProductDiscountPaymentModeEnumMap = {
SKProductDiscountPaymentMode.payAsYouGo: 0,
SKProductDiscountPaymentMode.payUpFront: 1,
SKProductDiscountPaymentMode.freeTrail: 2,
SKProductDiscountPaymentMode.unspecified: -1,
};
const _$SKProductDiscountTypeEnumMap = {
SKProductDiscountType.introductory: 0,
SKProductDiscountType.subscription: 1,
};
| plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/enum_converters.g.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/enum_converters.g.dart",
"repo_id": "plugins",
"token_count": 486
} | 1,235 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
export 'src/store_kit_wrappers/sk_payment_queue_delegate_wrapper.dart';
export 'src/store_kit_wrappers/sk_payment_queue_wrapper.dart';
export 'src/store_kit_wrappers/sk_payment_transaction_wrappers.dart';
export 'src/store_kit_wrappers/sk_product_wrapper.dart';
export 'src/store_kit_wrappers/sk_receipt_manager.dart';
export 'src/store_kit_wrappers/sk_request_maker.dart';
export 'src/store_kit_wrappers/sk_storefront_wrapper.dart';
| plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/store_kit_wrappers.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/store_kit_wrappers.dart",
"repo_id": "plugins",
"token_count": 203
} | 1,236 |
name: in_app_purchase_storekit
description: An implementation for the iOS and macOS platforms of the Flutter `in_app_purchase` plugin. This uses the StoreKit Framework.
repository: https://github.com/flutter/plugins/tree/main/packages/in_app_purchase/in_app_purchase_storekit
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+in_app_purchase%22
version: 0.3.6
environment:
sdk: '>=2.18.0 <3.0.0'
flutter: ">=3.3.0"
flutter:
plugin:
implements: in_app_purchase
platforms:
ios:
pluginClass: InAppPurchasePlugin
sharedDarwinSource: true
macos:
pluginClass: InAppPurchasePlugin
sharedDarwinSource: true
dependencies:
collection: ^1.15.0
flutter:
sdk: flutter
in_app_purchase_platform_interface: ^1.3.0
json_annotation: ^4.3.0
dev_dependencies:
build_runner: ^2.0.0
flutter_test:
sdk: flutter
json_serializable: ^6.0.0
test: ^1.16.0
| plugins/packages/in_app_purchase/in_app_purchase_storekit/pubspec.yaml/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/pubspec.yaml",
"repo_id": "plugins",
"token_count": 403
} | 1,237 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Exception codes for `PlatformException` returned by
// `authenticate`.
/// Indicates that the user has not yet configured a passcode (iOS) or
/// PIN/pattern/password (Android) on the device.
const String passcodeNotSet = 'PasscodeNotSet';
/// Indicates the user has not enrolled any biometrics on the device.
const String notEnrolled = 'NotEnrolled';
/// Indicates the device does not have hardware support for biometrics.
const String notAvailable = 'NotAvailable';
/// Indicates the device operating system is unsupported.
const String otherOperatingSystem = 'OtherOperatingSystem';
/// Indicates the API is temporarily locked out due to too many attempts.
const String lockedOut = 'LockedOut';
/// Indicates the API is locked out more persistently than [lockedOut].
/// Strong authentication like PIN/Pattern/Password is required to unlock.
const String permanentlyLockedOut = 'PermanentlyLockedOut';
/// Indicates that the biometricOnly parameter can't be true on Windows
const String biometricOnlyNotSupported = 'biometricOnlyNotSupported';
| plugins/packages/local_auth/local_auth/lib/error_codes.dart/0 | {
"file_path": "plugins/packages/local_auth/local_auth/lib/error_codes.dart",
"repo_id": "plugins",
"token_count": 299
} | 1,238 |
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="@color/success_color"/>
<size
android:width="40dp"
android:height="40dp"/>
</shape>
</item>
<item android:drawable="@drawable/ic_done_white_24dp"
android:bottom="8dp"
android:left="8dp"
android:right="8dp"
android:top="8dp"/>
</layer-list>
| plugins/packages/local_auth/local_auth_android/android/src/main/res/drawable/fingerprint_success_icon.xml/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/android/src/main/res/drawable/fingerprint_success_icon.xml",
"repo_id": "plugins",
"token_count": 213
} | 1,239 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.localauthexample">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
<application android:label="local_auth_example" android:icon="@mipmap/ic_launcher">
<activity android:name="io.flutter.embedding.android.FlutterFragmentActivity"
android:launchMode="singleTop"
android:theme="@style/Theme.AppCompat.Light"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data android:name="flutterEmbedding" android:value="2"/>
</application>
</manifest>
| plugins/packages/local_auth/local_auth_android/example/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/example/android/app/src/main/AndroidManifest.xml",
"repo_id": "plugins",
"token_count": 456
} | 1,240 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';
import 'package:local_auth_platform_interface/types/auth_messages.dart';
/// Android side authentication messages.
///
/// Provides default values for all messages.
@immutable
class AndroidAuthMessages extends AuthMessages {
/// Constructs a new instance.
const AndroidAuthMessages({
this.biometricHint,
this.biometricNotRecognized,
this.biometricRequiredTitle,
this.biometricSuccess,
this.cancelButton,
this.deviceCredentialsRequiredTitle,
this.deviceCredentialsSetupDescription,
this.goToSettingsButton,
this.goToSettingsDescription,
this.signInTitle,
});
/// Hint message advising the user how to authenticate with biometrics.
/// Maximum 60 characters.
final String? biometricHint;
/// Message to let the user know that authentication was failed.
/// Maximum 60 characters.
final String? biometricNotRecognized;
/// Message shown as a title in a dialog which indicates the user
/// has not set up biometric authentication on their device.
/// Maximum 60 characters.
final String? biometricRequiredTitle;
/// Message to let the user know that authentication was successful.
/// Maximum 60 characters
final String? biometricSuccess;
/// Message shown on a button that the user can click to leave the
/// current dialog.
/// Maximum 30 characters.
final String? cancelButton;
/// Message shown as a title in a dialog which indicates the user
/// has not set up credentials authentication on their device.
/// Maximum 60 characters.
final String? deviceCredentialsRequiredTitle;
/// Message advising the user to go to the settings and configure
/// device credentials on their device.
final String? deviceCredentialsSetupDescription;
/// Message shown on a button that the user can click to go to settings pages
/// from the current dialog.
/// Maximum 30 characters.
final String? goToSettingsButton;
/// Message advising the user to go to the settings and configure
/// biometric on their device.
final String? goToSettingsDescription;
/// Message shown as a title in a dialog which indicates the user
/// that they need to scan biometric to continue.
/// Maximum 60 characters.
final String? signInTitle;
@override
Map<String, String> get args {
return <String, String>{
'biometricHint': biometricHint ?? androidBiometricHint,
'biometricNotRecognized':
biometricNotRecognized ?? androidBiometricNotRecognized,
'biometricSuccess': biometricSuccess ?? androidBiometricSuccess,
'biometricRequired':
biometricRequiredTitle ?? androidBiometricRequiredTitle,
'cancelButton': cancelButton ?? androidCancelButton,
'deviceCredentialsRequired': deviceCredentialsRequiredTitle ??
androidDeviceCredentialsRequiredTitle,
'deviceCredentialsSetupDescription': deviceCredentialsSetupDescription ??
androidDeviceCredentialsSetupDescription,
'goToSetting': goToSettingsButton ?? goToSettings,
'goToSettingDescription':
goToSettingsDescription ?? androidGoToSettingsDescription,
'signInTitle': signInTitle ?? androidSignInTitle,
};
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is AndroidAuthMessages &&
runtimeType == other.runtimeType &&
biometricHint == other.biometricHint &&
biometricNotRecognized == other.biometricNotRecognized &&
biometricRequiredTitle == other.biometricRequiredTitle &&
biometricSuccess == other.biometricSuccess &&
cancelButton == other.cancelButton &&
deviceCredentialsRequiredTitle ==
other.deviceCredentialsRequiredTitle &&
deviceCredentialsSetupDescription ==
other.deviceCredentialsSetupDescription &&
goToSettingsButton == other.goToSettingsButton &&
goToSettingsDescription == other.goToSettingsDescription &&
signInTitle == other.signInTitle;
@override
int get hashCode => Object.hash(
super.hashCode,
biometricHint,
biometricNotRecognized,
biometricRequiredTitle,
biometricSuccess,
cancelButton,
deviceCredentialsRequiredTitle,
deviceCredentialsSetupDescription,
goToSettingsButton,
goToSettingsDescription,
signInTitle);
}
// Default strings for AndroidAuthMessages. Currently supports English.
// Intl.message must be string literals.
/// Message shown on a button that the user can click to go to settings pages
/// from the current dialog.
String get goToSettings => Intl.message('Go to settings',
desc: 'Message shown on a button that the user can click to go to '
'settings pages from the current dialog. Maximum 30 characters.');
/// Hint message advising the user how to authenticate with biometrics.
String get androidBiometricHint => Intl.message('Verify identity',
desc: 'Hint message advising the user how to authenticate with biometrics. '
'Maximum 60 characters.');
/// Message to let the user know that authentication was failed.
String get androidBiometricNotRecognized =>
Intl.message('Not recognized. Try again.',
desc: 'Message to let the user know that authentication was failed. '
'Maximum 60 characters.');
/// Message to let the user know that authentication was successful. It
String get androidBiometricSuccess => Intl.message('Success',
desc: 'Message to let the user know that authentication was successful. '
'Maximum 60 characters.');
/// Message shown on a button that the user can click to leave the
/// current dialog.
String get androidCancelButton => Intl.message('Cancel',
desc: 'Message shown on a button that the user can click to leave the '
'current dialog. Maximum 30 characters.');
/// Message shown as a title in a dialog which indicates the user
/// that they need to scan biometric to continue.
String get androidSignInTitle => Intl.message('Authentication required',
desc: 'Message shown as a title in a dialog which indicates the user '
'that they need to scan biometric to continue. Maximum 60 characters.');
/// Message shown as a title in a dialog which indicates the user
/// has not set up biometric authentication on their device.
String get androidBiometricRequiredTitle => Intl.message('Biometric required',
desc: 'Message shown as a title in a dialog which indicates the user '
'has not set up biometric authentication on their device. '
'Maximum 60 characters.');
/// Message shown as a title in a dialog which indicates the user
/// has not set up credentials authentication on their device.
String get androidDeviceCredentialsRequiredTitle =>
Intl.message('Device credentials required',
desc: 'Message shown as a title in a dialog which indicates the user '
'has not set up credentials authentication on their device. '
'Maximum 60 characters.');
/// Message advising the user to go to the settings and configure
/// device credentials on their device.
String get androidDeviceCredentialsSetupDescription =>
Intl.message('Device credentials required',
desc: 'Message advising the user to go to the settings and configure '
'device credentials on their device.');
/// Message advising the user to go to the settings and configure
/// biometric on their device.
String get androidGoToSettingsDescription => Intl.message(
'Biometric authentication is not set up on your device. Go to '
"'Settings > Security' to add biometric authentication.",
desc: 'Message advising the user to go to the settings and configure '
'biometric on their device.');
| plugins/packages/local_auth/local_auth_android/lib/types/auth_messages_android.dart/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/lib/types/auth_messages_android.dart",
"repo_id": "plugins",
"token_count": 2315
} | 1,241 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:local_auth_platform_interface/local_auth_platform_interface.dart';
import 'types/auth_messages_ios.dart';
export 'package:local_auth_ios/types/auth_messages_ios.dart';
export 'package:local_auth_platform_interface/types/auth_messages.dart';
export 'package:local_auth_platform_interface/types/auth_options.dart';
export 'package:local_auth_platform_interface/types/biometric_type.dart';
const MethodChannel _channel =
MethodChannel('plugins.flutter.io/local_auth_ios');
/// The implementation of [LocalAuthPlatform] for iOS.
class LocalAuthIOS extends LocalAuthPlatform {
/// Registers this class as the default instance of [LocalAuthPlatform].
static void registerWith() {
LocalAuthPlatform.instance = LocalAuthIOS();
}
@override
Future<bool> authenticate({
required String localizedReason,
required Iterable<AuthMessages> authMessages,
AuthenticationOptions options = const AuthenticationOptions(),
}) async {
assert(localizedReason.isNotEmpty);
final Map<String, Object> args = <String, Object>{
'localizedReason': localizedReason,
'useErrorDialogs': options.useErrorDialogs,
'stickyAuth': options.stickyAuth,
'sensitiveTransaction': options.sensitiveTransaction,
'biometricOnly': options.biometricOnly,
};
args.addAll(const IOSAuthMessages().args);
for (final AuthMessages messages in authMessages) {
if (messages is IOSAuthMessages) {
args.addAll(messages.args);
}
}
return (await _channel.invokeMethod<bool>('authenticate', args)) ?? false;
}
@override
Future<bool> deviceSupportsBiometrics() async {
return (await _channel.invokeMethod<bool>('deviceSupportsBiometrics')) ??
false;
}
@override
Future<List<BiometricType>> getEnrolledBiometrics() async {
final List<String> result = (await _channel.invokeListMethod<String>(
'getEnrolledBiometrics',
)) ??
<String>[];
final List<BiometricType> biometrics = <BiometricType>[];
for (final String value in result) {
switch (value) {
case 'face':
biometrics.add(BiometricType.face);
break;
case 'fingerprint':
biometrics.add(BiometricType.fingerprint);
break;
case 'iris':
biometrics.add(BiometricType.iris);
break;
}
}
return biometrics;
}
@override
Future<bool> isDeviceSupported() async =>
(await _channel.invokeMethod<bool>('isDeviceSupported')) ?? false;
/// Always returns false as this method is not supported on iOS.
@override
Future<bool> stopAuthentication() async {
return false;
}
}
| plugins/packages/local_auth/local_auth_ios/lib/local_auth_ios.dart/0 | {
"file_path": "plugins/packages/local_auth/local_auth_ios/lib/local_auth_ios.dart",
"repo_id": "plugins",
"token_count": 1012
} | 1,242 |
name: local_auth_windows
description: Windows implementation of the local_auth plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/local_auth/local_auth_windows
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+local_auth%22
version: 1.0.5
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: local_auth
platforms:
windows:
pluginClass: LocalAuthPlugin
dartPluginClass: LocalAuthWindows
dependencies:
flutter:
sdk: flutter
local_auth_platform_interface: ^1.0.1
dev_dependencies:
flutter_test:
sdk: flutter
pigeon: ^5.0.1
| plugins/packages/local_auth/local_auth_windows/pubspec.yaml/0 | {
"file_path": "plugins/packages/local_auth/local_auth_windows/pubspec.yaml",
"repo_id": "plugins",
"token_count": 276
} | 1,243 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:quick_actions_platform_interface/quick_actions_platform_interface.dart';
export 'package:quick_actions_platform_interface/types/types.dart';
const MethodChannel _channel =
MethodChannel('plugins.flutter.io/quick_actions_android');
/// An implementation of [QuickActionsPlatform] that for Android.
class QuickActionsAndroid extends QuickActionsPlatform {
/// Registers this class as the default instance of [QuickActionsPlatform].
static void registerWith() {
QuickActionsPlatform.instance = QuickActionsAndroid();
}
/// The MethodChannel that is being used by this implementation of the plugin.
@visibleForTesting
MethodChannel get channel => _channel;
@override
Future<void> initialize(QuickActionHandler handler) async {
channel.setMethodCallHandler((MethodCall call) async {
assert(call.method == 'launch');
handler(call.arguments as String);
});
final String? action =
await channel.invokeMethod<String?>('getLaunchAction');
if (action != null) {
handler(action);
}
}
@override
Future<void> setShortcutItems(List<ShortcutItem> items) async {
final List<Map<String, String?>> itemsList =
items.map(_serializeItem).toList();
await channel.invokeMethod<void>('setShortcutItems', itemsList);
}
@override
Future<void> clearShortcutItems() =>
channel.invokeMethod<void>('clearShortcutItems');
Map<String, String?> _serializeItem(ShortcutItem item) {
return <String, String?>{
'type': item.type,
'localizedTitle': item.localizedTitle,
'icon': item.icon,
};
}
}
| plugins/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart",
"repo_id": "plugins",
"token_count": 586
} | 1,244 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import '../method_channel/method_channel_quick_actions.dart';
import '../types/types.dart';
/// The interface that implementations of quick_actions must implement.
///
/// Platform implementations should extend this class rather than implement it as `quick_actions`
/// does not consider newly added methods to be breaking changes. Extending this class
/// (using `extends`) ensures that the subclass will get the default implementation, while
/// platform implementations that `implements` this interface will be broken by newly added
/// [QuickActionsPlatform] methods.
abstract class QuickActionsPlatform extends PlatformInterface {
/// Constructs a QuickActionsPlatform.
QuickActionsPlatform() : super(token: _token);
static final Object _token = Object();
static QuickActionsPlatform _instance = MethodChannelQuickActions();
/// The default instance of [QuickActionsPlatform] to use.
///
/// Defaults to [MethodChannelQuickActions].
static QuickActionsPlatform get instance => _instance;
/// Platform-specific plugins should set this with their own platform-specific
/// class that extends [QuickActionsPlatform] when they register themselves.
// TODO(amirh): Extract common platform interface logic.
// https://github.com/flutter/flutter/issues/43368
static set instance(QuickActionsPlatform instance) {
PlatformInterface.verify(instance, _token);
_instance = instance;
}
/// Initializes this plugin.
///
/// Call this once before any further interaction with the plugin.
Future<void> initialize(QuickActionHandler handler) async {
throw UnimplementedError('initialize() has not been implemented.');
}
/// Sets the [ShortcutItem]s to become the app's quick actions.
Future<void> setShortcutItems(List<ShortcutItem> items) async {
throw UnimplementedError('setShortcutItems() has not been implemented.');
}
/// Removes all [ShortcutItem]s registered for the app.
Future<void> clearShortcutItems() {
throw UnimplementedError('clearShortcutItems() has not been implemented.');
}
}
| plugins/packages/quick_actions/quick_actions_platform_interface/lib/platform_interface/quick_actions_platform.dart/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_platform_interface/lib/platform_interface/quick_actions_platform.dart",
"repo_id": "plugins",
"token_count": 593
} | 1,245 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| plugins/packages/shared_preferences/shared_preferences/example/android/gradle.properties/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences/example/android/gradle.properties",
"repo_id": "plugins",
"token_count": 30
} | 1,246 |
# shared\_preferences\_android
The Android implementation of [`shared_preferences`][1].
## Usage
This package is [endorsed][2], which means you can simply use `shared_preferences`
normally. This package will be automatically included in your app when you do.
[1]: https://pub.dev/packages/shared_preferences
[2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
| plugins/packages/shared_preferences/shared_preferences_android/README.md/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_android/README.md",
"repo_id": "plugins",
"token_count": 127
} | 1,247 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.sharedpreferencesexample">
<application
android:label="example"
android:icon="@mipmap/ic_launcher">
<activity
android:name="io.flutter.embedding.android.FlutterActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
| plugins/packages/shared_preferences/shared_preferences_android/example/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_android/example/android/app/src/main/AndroidManifest.xml",
"repo_id": "plugins",
"token_count": 920
} | 1,248 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'package:flutter/material.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'SharedPreferences Demo',
home: SharedPreferencesDemo(),
);
}
}
class SharedPreferencesDemo extends StatefulWidget {
const SharedPreferencesDemo({Key? key}) : super(key: key);
@override
SharedPreferencesDemoState createState() => SharedPreferencesDemoState();
}
class SharedPreferencesDemoState extends State<SharedPreferencesDemo> {
final SharedPreferencesStorePlatform _prefs =
SharedPreferencesStorePlatform.instance;
late Future<int> _counter;
// Includes the prefix because this is using the platform interface directly,
// but the prefix (which the native code assumes is present) is added by the
// app-facing package.
static const String _prefKey = 'flutter.counter';
Future<void> _incrementCounter() async {
final Map<String, Object> values = await _prefs.getAll();
final int counter = ((values[_prefKey] as int?) ?? 0) + 1;
setState(() {
_counter = _prefs.setValue('Int', _prefKey, counter).then((bool success) {
return counter;
});
});
}
@override
void initState() {
super.initState();
_counter = _prefs.getAll().then((Map<String, Object> values) {
return (values[_prefKey] as int?) ?? 0;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('SharedPreferences Demo'),
),
body: Center(
child: FutureBuilder<int>(
future: _counter,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return const CircularProgressIndicator();
case ConnectionState.active:
case ConnectionState.done:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text(
'Button tapped ${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n\n'
'This should persist across restarts.',
);
}
}
})),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
| plugins/packages/shared_preferences/shared_preferences_android/example/lib/main.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_android/example/lib/main.dart",
"repo_id": "plugins",
"token_count": 1222
} | 1,249 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('SharedPreferencesFoundation', () {
const Map<String, Object> kTestValues = <String, Object>{
'flutter.String': 'hello world',
'flutter.bool': true,
'flutter.int': 42,
'flutter.double': 3.14159,
'flutter.List': <String>['foo', 'bar'],
};
const Map<String, Object> kTestValues2 = <String, Object>{
'flutter.String': 'goodbye world',
'flutter.bool': false,
'flutter.int': 1337,
'flutter.double': 2.71828,
'flutter.List': <String>['baz', 'quox'],
};
late SharedPreferencesStorePlatform preferences;
setUp(() async {
preferences = SharedPreferencesStorePlatform.instance;
});
tearDown(() {
preferences.clear();
});
// Normally the app-facing package adds the prefix, but since this test
// bypasses the app-facing package it needs to be manually added.
String prefixedKey(String key) {
return 'flutter.$key';
}
testWidgets('reading', (WidgetTester _) async {
final Map<String, Object> values = await preferences.getAll();
expect(values[prefixedKey('String')], isNull);
expect(values[prefixedKey('bool')], isNull);
expect(values[prefixedKey('int')], isNull);
expect(values[prefixedKey('double')], isNull);
expect(values[prefixedKey('List')], isNull);
});
testWidgets('writing', (WidgetTester _) async {
await Future.wait(<Future<bool>>[
preferences.setValue(
'String', prefixedKey('String'), kTestValues2['flutter.String']!),
preferences.setValue(
'Bool', prefixedKey('bool'), kTestValues2['flutter.bool']!),
preferences.setValue(
'Int', prefixedKey('int'), kTestValues2['flutter.int']!),
preferences.setValue(
'Double', prefixedKey('double'), kTestValues2['flutter.double']!),
preferences.setValue(
'StringList', prefixedKey('List'), kTestValues2['flutter.List']!)
]);
final Map<String, Object> values = await preferences.getAll();
expect(values[prefixedKey('String')], kTestValues2['flutter.String']);
expect(values[prefixedKey('bool')], kTestValues2['flutter.bool']);
expect(values[prefixedKey('int')], kTestValues2['flutter.int']);
expect(values[prefixedKey('double')], kTestValues2['flutter.double']);
expect(values[prefixedKey('List')], kTestValues2['flutter.List']);
});
testWidgets('removing', (WidgetTester _) async {
final String key = prefixedKey('testKey');
await preferences.setValue('String', key, kTestValues['flutter.String']!);
await preferences.setValue('Bool', key, kTestValues['flutter.bool']!);
await preferences.setValue('Int', key, kTestValues['flutter.int']!);
await preferences.setValue('Double', key, kTestValues['flutter.double']!);
await preferences.setValue(
'StringList', key, kTestValues['flutter.List']!);
await preferences.remove(key);
final Map<String, Object> values = await preferences.getAll();
expect(values[key], isNull);
});
testWidgets('clearing', (WidgetTester _) async {
await preferences.setValue(
'String', 'String', kTestValues['flutter.String']!);
await preferences.setValue('Bool', 'bool', kTestValues['flutter.bool']!);
await preferences.setValue('Int', 'int', kTestValues['flutter.int']!);
await preferences.setValue(
'Double', 'double', kTestValues['flutter.double']!);
await preferences.setValue(
'StringList', 'List', kTestValues['flutter.List']!);
await preferences.clear();
final Map<String, Object> values = await preferences.getAll();
expect(values['String'], null);
expect(values['bool'], null);
expect(values['int'], null);
expect(values['double'], null);
expect(values['List'], null);
});
});
}
| plugins/packages/shared_preferences/shared_preferences_foundation/example/integration_test/shared_preferences_test.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_foundation/example/integration_test/shared_preferences_test.dart",
"repo_id": "plugins",
"token_count": 1633
} | 1,250 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/messages.g.dart',
dartTestOut: 'test/test_api.g.dart',
swiftOut: 'darwin/Classes/messages.g.swift',
copyrightHeader: 'pigeons/copyright_header.txt',
))
@HostApi(dartHostTestHandler: 'TestUserDefaultsApi')
abstract class UserDefaultsApi {
void remove(String key);
// TODO(stuartmorgan): Give these setters better Swift signatures (_,forKey:)
// once https://github.com/flutter/flutter/issues/105932 is fixed.
void setBool(String key, bool value);
void setDouble(String key, double value);
void setValue(String key, Object value);
// TODO(stuartmorgan): Make these non-nullable once
// https://github.com/flutter/flutter/issues/97848 is fixed.
Map<String?, Object?> getAll();
void clear();
}
| plugins/packages/shared_preferences/shared_preferences_foundation/pigeons/messages.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_foundation/pigeons/messages.dart",
"repo_id": "plugins",
"token_count": 327
} | 1,251 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'method_channel_shared_preferences.dart';
/// The interface that implementations of shared_preferences must implement.
///
/// Platform implementations should extend this class rather than implement it as `shared_preferences`
/// does not consider newly added methods to be breaking changes. Extending this class
/// (using `extends`) ensures that the subclass will get the default implementation, while
/// platform implementations that `implements` this interface will be broken by newly added
/// [SharedPreferencesStorePlatform] methods.
abstract class SharedPreferencesStorePlatform extends PlatformInterface {
/// Constructs a SharedPreferencesStorePlatform.
SharedPreferencesStorePlatform() : super(token: _token);
static final Object _token = Object();
/// The default instance of [SharedPreferencesStorePlatform] to use.
///
/// Defaults to [MethodChannelSharedPreferencesStore].
static SharedPreferencesStorePlatform get instance => _instance;
/// Platform-specific plugins should set this with their own platform-specific
/// class that extends [SharedPreferencesStorePlatform] when they register themselves.
static set instance(SharedPreferencesStorePlatform instance) {
if (!instance.isMock) {
PlatformInterface.verify(instance, _token);
}
_instance = instance;
}
static SharedPreferencesStorePlatform _instance =
MethodChannelSharedPreferencesStore();
/// Only mock implementations should set this to true.
///
/// Mockito mocks are implementing this class with `implements` which is forbidden for anything
/// other than mocks (see class docs). This property provides a backdoor for mockito mocks to
/// skip the verification that the class isn't implemented with `implements`.
@visibleForTesting
@Deprecated('Use MockPlatformInterfaceMixin instead')
bool get isMock => false;
/// Removes the value associated with the [key].
Future<bool> remove(String key);
/// Stores the [value] associated with the [key].
///
/// The [valueType] must match the type of [value] as follows:
///
/// * Value type "Bool" must be passed if the value is of type `bool`.
/// * Value type "Double" must be passed if the value is of type `double`.
/// * Value type "Int" must be passed if the value is of type `int`.
/// * Value type "String" must be passed if the value is of type `String`.
/// * Value type "StringList" must be passed if the value is of type `List<String>`.
Future<bool> setValue(String valueType, String key, Object value);
/// Removes all keys and values in the store.
Future<bool> clear();
/// Returns all key/value pairs persisted in this store.
Future<Map<String, Object>> getAll();
}
/// Stores data in memory.
///
/// Data does not persist across application restarts. This is useful in unit-tests.
class InMemorySharedPreferencesStore extends SharedPreferencesStorePlatform {
/// Instantiates an empty in-memory preferences store.
InMemorySharedPreferencesStore.empty() : _data = <String, Object>{};
/// Instantiates an in-memory preferences store containing a copy of [data].
InMemorySharedPreferencesStore.withData(Map<String, Object> data)
: _data = Map<String, Object>.from(data);
final Map<String, Object> _data;
@override
Future<bool> clear() async {
_data.clear();
return true;
}
@override
Future<Map<String, Object>> getAll() async {
return Map<String, Object>.from(_data);
}
@override
Future<bool> remove(String key) async {
_data.remove(key);
return true;
}
@override
Future<bool> setValue(String valueType, String key, Object value) async {
_data[key] = value;
return true;
}
}
| plugins/packages/shared_preferences/shared_preferences_platform_interface/lib/shared_preferences_platform_interface.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_platform_interface/lib/shared_preferences_platform_interface.dart",
"repo_id": "plugins",
"token_count": 1095
} | 1,252 |
name: shared_preferences_web
description: Web platform implementation of shared_preferences
repository: https://github.com/flutter/plugins/tree/main/packages/shared_preferences/shared_preferences_web
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22
version: 2.0.4
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: shared_preferences
platforms:
web:
pluginClass: SharedPreferencesPlugin
fileName: shared_preferences_web.dart
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
shared_preferences_platform_interface: ^2.0.0
dev_dependencies:
flutter_test:
sdk: flutter
| plugins/packages/shared_preferences/shared_preferences_web/pubspec.yaml/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_web/pubspec.yaml",
"repo_id": "plugins",
"token_count": 303
} | 1,253 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:url_launcher/link.dart';
import 'package:url_launcher/src/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import 'mocks/mock_url_launcher_platform.dart';
void main() {
late MockUrlLauncher mock;
setUp(() {
mock = MockUrlLauncher();
UrlLauncherPlatform.instance = mock;
});
group('Link', () {
testWidgets('handles null uri correctly', (WidgetTester tester) async {
bool isBuilt = false;
FollowLink? followLink;
final Link link = Link(
uri: null,
builder: (BuildContext context, FollowLink? followLink2) {
isBuilt = true;
followLink = followLink2;
return Container();
},
);
await tester.pumpWidget(link);
expect(link.isDisabled, isTrue);
expect(isBuilt, isTrue);
expect(followLink, isNull);
});
testWidgets('calls url_launcher for external URLs with blank target',
(WidgetTester tester) async {
FollowLink? followLink;
await tester.pumpWidget(Link(
uri: Uri.parse('http://example.com/foobar'),
target: LinkTarget.blank,
builder: (BuildContext context, FollowLink? followLink2) {
followLink = followLink2;
return Container();
},
));
mock
..setLaunchExpectations(
url: 'http://example.com/foobar',
launchMode: PreferredLaunchMode.externalApplication,
universalLinksOnly: false,
enableJavaScript: true,
enableDomStorage: true,
headers: <String, String>{},
webOnlyWindowName: null,
)
..setResponse(true);
await followLink!();
expect(mock.canLaunchCalled, isTrue);
expect(mock.launchCalled, isTrue);
});
testWidgets('calls url_launcher for external URLs with self target',
(WidgetTester tester) async {
FollowLink? followLink;
await tester.pumpWidget(Link(
uri: Uri.parse('http://example.com/foobar'),
target: LinkTarget.self,
builder: (BuildContext context, FollowLink? followLink2) {
followLink = followLink2;
return Container();
},
));
mock
..setLaunchExpectations(
url: 'http://example.com/foobar',
launchMode: PreferredLaunchMode.inAppWebView,
universalLinksOnly: false,
enableJavaScript: true,
enableDomStorage: true,
headers: <String, String>{},
webOnlyWindowName: null,
)
..setResponse(true);
await followLink!();
expect(mock.canLaunchCalled, isTrue);
expect(mock.launchCalled, isTrue);
});
testWidgets('pushes to framework for internal route names',
(WidgetTester tester) async {
final Uri uri = Uri.parse('/foo/bar');
FollowLink? followLink;
await tester.pumpWidget(MaterialApp(
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => Link(
uri: uri,
builder: (BuildContext context, FollowLink? followLink2) {
followLink = followLink2;
return Container();
},
),
'/foo/bar': (BuildContext context) => Container(),
},
));
bool frameworkCalled = false;
final Future<ByteData> Function(Object?, String) originalPushFunction =
pushRouteToFrameworkFunction;
pushRouteToFrameworkFunction = (Object? _, String __) {
frameworkCalled = true;
return Future<ByteData>.value(ByteData(0));
};
await followLink!();
// Shouldn't use url_launcher when uri is an internal route name.
expect(mock.canLaunchCalled, isFalse);
expect(mock.launchCalled, isFalse);
// A route should have been pushed to the framework.
expect(frameworkCalled, true);
// Restore the original function.
pushRouteToFrameworkFunction = originalPushFunction;
});
});
}
| plugins/packages/url_launcher/url_launcher/test/link_test.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher/test/link_test.dart",
"repo_id": "plugins",
"token_count": 1796
} | 1,254 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.urllauncher;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.os.Bundle;
import androidx.test.core.app.ApplicationProvider;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.BinaryMessenger.BinaryMessageHandler;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel.Result;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class MethodCallHandlerImplTest {
private static final String CHANNEL_NAME = "plugins.flutter.io/url_launcher_android";
private UrlLauncher urlLauncher;
private MethodCallHandlerImpl methodCallHandler;
@Before
public void setUp() {
urlLauncher = new UrlLauncher(ApplicationProvider.getApplicationContext(), /*activity=*/ null);
methodCallHandler = new MethodCallHandlerImpl(urlLauncher);
}
@Test
public void startListening_registersChannel() {
BinaryMessenger messenger = mock(BinaryMessenger.class);
methodCallHandler.startListening(messenger);
verify(messenger, times(1))
.setMessageHandler(eq(CHANNEL_NAME), any(BinaryMessageHandler.class));
}
@Test
public void startListening_unregistersExistingChannel() {
BinaryMessenger firstMessenger = mock(BinaryMessenger.class);
BinaryMessenger secondMessenger = mock(BinaryMessenger.class);
methodCallHandler.startListening(firstMessenger);
methodCallHandler.startListening(secondMessenger);
// Unregisters the first and then registers the second.
verify(firstMessenger, times(1)).setMessageHandler(CHANNEL_NAME, null);
verify(secondMessenger, times(1))
.setMessageHandler(eq(CHANNEL_NAME), any(BinaryMessageHandler.class));
}
@Test
public void stopListening_unregistersExistingChannel() {
BinaryMessenger messenger = mock(BinaryMessenger.class);
methodCallHandler.startListening(messenger);
methodCallHandler.stopListening();
verify(messenger, times(1)).setMessageHandler(CHANNEL_NAME, null);
}
@Test
public void stopListening_doesNothingWhenUnset() {
BinaryMessenger messenger = mock(BinaryMessenger.class);
methodCallHandler.stopListening();
verify(messenger, never()).setMessageHandler(CHANNEL_NAME, null);
}
@Test
public void onMethodCall_canLaunchReturnsTrue() {
urlLauncher = mock(UrlLauncher.class);
methodCallHandler = new MethodCallHandlerImpl(urlLauncher);
String url = "foo";
when(urlLauncher.canLaunch(url)).thenReturn(true);
Result result = mock(Result.class);
Map<String, Object> args = new HashMap<>();
args.put("url", url);
methodCallHandler.onMethodCall(new MethodCall("canLaunch", args), result);
verify(result, times(1)).success(true);
}
@Test
public void onMethodCall_canLaunchReturnsFalse() {
urlLauncher = mock(UrlLauncher.class);
methodCallHandler = new MethodCallHandlerImpl(urlLauncher);
String url = "foo";
when(urlLauncher.canLaunch(url)).thenReturn(false);
Result result = mock(Result.class);
Map<String, Object> args = new HashMap<>();
args.put("url", url);
methodCallHandler.onMethodCall(new MethodCall("canLaunch", args), result);
verify(result, times(1)).success(false);
}
@Test
public void onMethodCall_launchReturnsNoActivityError() {
// Setup mock objects
urlLauncher = mock(UrlLauncher.class);
Result result = mock(Result.class);
// Setup expected values
String url = "foo";
boolean useWebView = false;
boolean enableJavaScript = false;
boolean enableDomStorage = false;
// Setup arguments map send on the method channel
Map<String, Object> args = new HashMap<>();
args.put("url", url);
args.put("useWebView", useWebView);
args.put("enableJavaScript", enableJavaScript);
args.put("enableDomStorage", enableDomStorage);
args.put("headers", new HashMap<>());
// Mock the launch method on the urlLauncher class
when(urlLauncher.launch(
eq(url), any(Bundle.class), eq(useWebView), eq(enableJavaScript), eq(enableDomStorage)))
.thenReturn(UrlLauncher.LaunchStatus.NO_ACTIVITY);
// Act by calling the "launch" method on the method channel
methodCallHandler = new MethodCallHandlerImpl(urlLauncher);
methodCallHandler.onMethodCall(new MethodCall("launch", args), result);
// Verify the results and assert
verify(result, times(1))
.error("NO_ACTIVITY", "Launching a URL requires a foreground activity.", null);
}
@Test
public void onMethodCall_launchReturnsActivityNotFoundError() {
// Setup mock objects
urlLauncher = mock(UrlLauncher.class);
Result result = mock(Result.class);
// Setup expected values
String url = "foo";
boolean useWebView = false;
boolean enableJavaScript = false;
boolean enableDomStorage = false;
// Setup arguments map send on the method channel
Map<String, Object> args = new HashMap<>();
args.put("url", url);
args.put("useWebView", useWebView);
args.put("enableJavaScript", enableJavaScript);
args.put("enableDomStorage", enableDomStorage);
args.put("headers", new HashMap<>());
// Mock the launch method on the urlLauncher class
when(urlLauncher.launch(
eq(url), any(Bundle.class), eq(useWebView), eq(enableJavaScript), eq(enableDomStorage)))
.thenReturn(UrlLauncher.LaunchStatus.ACTIVITY_NOT_FOUND);
// Act by calling the "launch" method on the method channel
methodCallHandler = new MethodCallHandlerImpl(urlLauncher);
methodCallHandler.onMethodCall(new MethodCall("launch", args), result);
// Verify the results and assert
verify(result, times(1))
.error(
"ACTIVITY_NOT_FOUND",
String.format("No Activity found to handle intent { %s }", url),
null);
}
@Test
public void onMethodCall_launchReturnsTrue() {
// Setup mock objects
urlLauncher = mock(UrlLauncher.class);
Result result = mock(Result.class);
// Setup expected values
String url = "foo";
boolean useWebView = false;
boolean enableJavaScript = false;
boolean enableDomStorage = false;
// Setup arguments map send on the method channel
Map<String, Object> args = new HashMap<>();
args.put("url", url);
args.put("useWebView", useWebView);
args.put("enableJavaScript", enableJavaScript);
args.put("enableDomStorage", enableDomStorage);
args.put("headers", new HashMap<>());
// Mock the launch method on the urlLauncher class
when(urlLauncher.launch(
eq(url), any(Bundle.class), eq(useWebView), eq(enableJavaScript), eq(enableDomStorage)))
.thenReturn(UrlLauncher.LaunchStatus.OK);
// Act by calling the "launch" method on the method channel
methodCallHandler = new MethodCallHandlerImpl(urlLauncher);
methodCallHandler.onMethodCall(new MethodCall("launch", args), result);
// Verify the results and assert
verify(result, times(1)).success(true);
}
@Test
public void onMethodCall_closeWebView() {
urlLauncher = mock(UrlLauncher.class);
methodCallHandler = new MethodCallHandlerImpl(urlLauncher);
String url = "foo";
when(urlLauncher.canLaunch(url)).thenReturn(true);
Result result = mock(Result.class);
Map<String, Object> args = new HashMap<>();
args.put("url", url);
methodCallHandler.onMethodCall(new MethodCall("closeWebView", args), result);
verify(urlLauncher, times(1)).closeWebView();
verify(result, times(1)).success(null);
}
}
| plugins/packages/url_launcher/url_launcher_android/android/src/test/java/io/flutter/plugins/urllauncher/MethodCallHandlerImplTest.java/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_android/android/src/test/java/io/flutter/plugins/urllauncher/MethodCallHandlerImplTest.java",
"repo_id": "plugins",
"token_count": 2694
} | 1,255 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PACKAGES_URL_LAUNCHER_URL_LAUNCHER_LINUX_LINUX_INCLUDE_URL_LAUNCHER_URL_LAUNCHER_PLUGIN_H_
#define PACKAGES_URL_LAUNCHER_URL_LAUNCHER_LINUX_LINUX_INCLUDE_URL_LAUNCHER_URL_LAUNCHER_PLUGIN_H_
// A plugin to launch URLs.
#include <flutter_linux/flutter_linux.h>
G_BEGIN_DECLS
#ifdef FLUTTER_PLUGIN_IMPL
#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default")))
#else
#define FLUTTER_PLUGIN_EXPORT
#endif
G_DECLARE_FINAL_TYPE(FlUrlLauncherPlugin, fl_url_launcher_plugin, FL,
URL_LAUNCHER_PLUGIN, GObject)
FLUTTER_PLUGIN_EXPORT FlUrlLauncherPlugin* fl_url_launcher_plugin_new(
FlPluginRegistrar* registrar);
FLUTTER_PLUGIN_EXPORT void url_launcher_plugin_register_with_registrar(
FlPluginRegistrar* registrar);
G_END_DECLS
#endif // PACKAGES_URL_LAUNCHER_URL_LAUNCHER_LINUX_LINUX_INCLUDE_URL_LAUNCHER_URL_LAUNCHER_PLUGIN_H_
| plugins/packages/url_launcher/url_launcher_linux/linux/include/url_launcher_linux/url_launcher_plugin.h/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_linux/linux/include/url_launcher_linux/url_launcher_plugin.h",
"repo_id": "plugins",
"token_count": 435
} | 1,256 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| plugins/packages/url_launcher/url_launcher_macos/example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_macos/example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "plugins",
"token_count": 32
} | 1,257 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 2.1.1
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
## 2.1.0
* Adds a new `launchUrl` method corresponding to the new app-facing interface.
## 2.0.5
* Updates code for new analysis options.
* Update to use the `verify` method introduced in platform_plugin_interface 2.1.0.
## 2.0.4
* Silenced warnings that may occur during build when using a very
recent version of Flutter relating to null safety.
## 2.0.3
* Migrate `pushRouteNameToFramework` to use ChannelBuffers API.
## 2.0.2
* Update platform_plugin_interface version requirement.
## 2.0.1
* Fix SDK range.
## 2.0.0
* Migrate to null safety.
## 1.0.10
* Update Flutter SDK constraint.
## 1.0.9
* Laid the groundwork for introducing a Link widget.
## 1.0.8
* Added webOnlyWindowName parameter
## 1.0.7
* Update lower bound of dart dependency to 2.1.0.
## 1.0.6
* Make the pedantic dev_dependency explicit.
## 1.0.5
* Make the `PlatformInterface` `_token` non `const` (as `const` `Object`s are not unique).
## 1.0.4
* Use the common PlatformInterface code from plugin_platform_interface.
* [TEST ONLY BREAKING CHANGE] remove UrlLauncherPlatform.isMock, we're not increasing the major version
as doing so for platform interfaces has bad implications, given that this is only going to break
test code, and that the plugin is young and shouldn't have third-party users we've decided to land
this as a patch bump.
## 1.0.3
* Minor DartDoc changes and add a lint for missing DartDocs.
## 1.0.2
* Use package URI in test directory to import code from lib.
## 1.0.1
* Enforce that UrlLauncherPlatform isn't implemented with `implements`.
## 1.0.0
* Initial release.
| plugins/packages/url_launcher/url_launcher_platform_interface/CHANGELOG.md/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_platform_interface/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 570
} | 1,258 |
The code in this directory is a stripped down, and modified version of `package:platform_detect`.
You can find the original file in Workiva's repository, here:
* https://github.com/Workiva/platform_detect/blob/77d160f1c3be4e20dc085a094209e8cab4aec135/lib/src/browser.dart
| plugins/packages/url_launcher/url_launcher_web/lib/src/third_party/platform_detect/README.md/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_web/lib/src/third_party/platform_detect/README.md",
"repo_id": "plugins",
"token_count": 94
} | 1,259 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';
Future<void> main() async {
final FlutterDriver driver = await FlutterDriver.connect();
tearDownAll(() async {
await driver.close();
});
// TODO(cyanglaz): Use TabBar tabs to navigate between pages after https://github.com/flutter/flutter/issues/16991 is fixed.
// TODO(cyanglaz): Un-skip the test after https://github.com/flutter/flutter/issues/43012 is fixed
test('Push a page contains video and pop back, do not crash.', () async {
final SerializableFinder pushTab = find.byValueKey('push_tab');
await driver.waitFor(pushTab);
await driver.tap(pushTab);
await driver.waitForAbsent(pushTab);
await driver.waitFor(find.byValueKey('home_page'));
await driver.waitUntilNoTransientCallbacks();
final Health health = await driver.checkHealth();
expect(health.status, HealthStatus.ok);
}, skip: 'Cirrus CI currently hangs while playing videos');
}
| plugins/packages/video_player/video_player/example/test_driver/video_player_test.dart/0 | {
"file_path": "plugins/packages/video_player/video_player/example/test_driver/video_player_test.dart",
"repo_id": "plugins",
"token_count": 368
} | 1,260 |
# video\_player\_android
The Android implementation of [`video_player`][1].
## Usage
This package is [endorsed][2], which means you can simply use `video_player`
normally. This package will be automatically included in your app when you do.
[1]: https://pub.dev/packages/video_player
[2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
| plugins/packages/video_player/video_player_android/README.md/0 | {
"file_path": "plugins/packages/video_player/video_player_android/README.md",
"repo_id": "plugins",
"token_count": 119
} | 1,261 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import os.log;
@import XCTest;
@import CoreGraphics;
@interface VideoPlayerUITests : XCTestCase
@property(nonatomic, strong) XCUIApplication *app;
@end
@implementation VideoPlayerUITests
- (void)setUp {
self.continueAfterFailure = NO;
self.app = [[XCUIApplication alloc] init];
[self.app launch];
}
- (void)testPlayVideo {
XCUIApplication *app = self.app;
XCUIElement *remoteTab = [app.otherElements
elementMatchingPredicate:[NSPredicate predicateWithFormat:@"selected == YES"]];
XCTAssertTrue([remoteTab waitForExistenceWithTimeout:30.0]);
XCTAssertTrue([remoteTab.label containsString:@"Remote"]);
XCUIElement *playButton = app.staticTexts[@"Play"];
XCTAssertTrue([playButton waitForExistenceWithTimeout:30.0]);
[playButton tap];
NSPredicate *find1xButton = [NSPredicate predicateWithFormat:@"label CONTAINS '1.0x'"];
XCUIElement *playbackSpeed1x = [app.staticTexts elementMatchingPredicate:find1xButton];
BOOL foundPlaybackSpeed1x = [playbackSpeed1x waitForExistenceWithTimeout:30.0];
XCTAssertTrue(foundPlaybackSpeed1x);
[playbackSpeed1x tap];
XCUIElement *playbackSpeed5xButton = app.buttons[@"5.0x"];
XCTAssertTrue([playbackSpeed5xButton waitForExistenceWithTimeout:30.0]);
[playbackSpeed5xButton tap];
NSPredicate *find5xButton = [NSPredicate predicateWithFormat:@"label CONTAINS '5.0x'"];
XCUIElement *playbackSpeed5x = [app.staticTexts elementMatchingPredicate:find5xButton];
BOOL foundPlaybackSpeed5x = [playbackSpeed5x waitForExistenceWithTimeout:30.0];
XCTAssertTrue(foundPlaybackSpeed5x);
// Cycle through tabs.
for (NSString *tabName in @[ @"Asset mp4", @"Remote mp4" ]) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"label BEGINSWITH %@", tabName];
XCUIElement *unselectedTab = [app.staticTexts elementMatchingPredicate:predicate];
XCTAssertTrue([unselectedTab waitForExistenceWithTimeout:30.0]);
XCTAssertFalse(unselectedTab.isSelected);
[unselectedTab tap];
XCUIElement *selectedTab = [app.otherElements
elementMatchingPredicate:[NSPredicate predicateWithFormat:@"label BEGINSWITH %@", tabName]];
XCTAssertTrue([selectedTab waitForExistenceWithTimeout:30.0]);
XCTAssertTrue(selectedTab.isSelected);
}
}
@end
| plugins/packages/video_player/video_player_avfoundation/example/ios/RunnerUITests/VideoPlayerUITests.m/0 | {
"file_path": "plugins/packages/video_player/video_player_avfoundation/example/ios/RunnerUITests/VideoPlayerUITests.m",
"repo_id": "plugins",
"token_count": 847
} | 1,262 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:html' as html;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
import 'duration_utils.dart';
// An error code value to error name Map.
// See: https://developer.mozilla.org/en-US/docs/Web/API/MediaError/code
const Map<int, String> _kErrorValueToErrorName = <int, String>{
1: 'MEDIA_ERR_ABORTED',
2: 'MEDIA_ERR_NETWORK',
3: 'MEDIA_ERR_DECODE',
4: 'MEDIA_ERR_SRC_NOT_SUPPORTED',
};
// An error code value to description Map.
// See: https://developer.mozilla.org/en-US/docs/Web/API/MediaError/code
const Map<int, String> _kErrorValueToErrorDescription = <int, String>{
1: 'The user canceled the fetching of the video.',
2: 'A network error occurred while fetching the video, despite having previously been available.',
3: 'An error occurred while trying to decode the video, despite having previously been determined to be usable.',
4: 'The video has been found to be unsuitable (missing or in a format not supported by your browser).',
};
// The default error message, when the error is an empty string
// See: https://developer.mozilla.org/en-US/docs/Web/API/MediaError/message
const String _kDefaultErrorMessage =
'No further diagnostic information can be determined or provided.';
/// Wraps a [html.VideoElement] so its API complies with what is expected by the plugin.
class VideoPlayer {
/// Create a [VideoPlayer] from a [html.VideoElement] instance.
VideoPlayer({
required html.VideoElement videoElement,
@visibleForTesting StreamController<VideoEvent>? eventController,
}) : _videoElement = videoElement,
_eventController = eventController ?? StreamController<VideoEvent>();
final StreamController<VideoEvent> _eventController;
final html.VideoElement _videoElement;
bool _isInitialized = false;
bool _isBuffering = false;
/// Returns the [Stream] of [VideoEvent]s from the inner [html.VideoElement].
Stream<VideoEvent> get events => _eventController.stream;
/// Initializes the wrapped [html.VideoElement].
///
/// This method sets the required DOM attributes so videos can [play] programmatically,
/// and attaches listeners to the internal events from the [html.VideoElement]
/// to react to them / expose them through the [VideoPlayer.events] stream.
void initialize() {
_videoElement
..autoplay = false
..controls = false;
// Allows Safari iOS to play the video inline
_videoElement.setAttribute('playsinline', 'true');
// Set autoplay to false since most browsers won't autoplay a video unless it is muted
_videoElement.setAttribute('autoplay', 'false');
_videoElement.onCanPlay.listen((dynamic _) {
if (!_isInitialized) {
_isInitialized = true;
_sendInitialized();
}
});
_videoElement.onCanPlayThrough.listen((dynamic _) {
setBuffering(false);
});
_videoElement.onPlaying.listen((dynamic _) {
setBuffering(false);
});
_videoElement.onWaiting.listen((dynamic _) {
setBuffering(true);
_sendBufferingRangesUpdate();
});
// The error event fires when some form of error occurs while attempting to load or perform the media.
_videoElement.onError.listen((html.Event _) {
setBuffering(false);
// The Event itself (_) doesn't contain info about the actual error.
// We need to look at the HTMLMediaElement.error.
// See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error
final html.MediaError error = _videoElement.error!;
_eventController.addError(PlatformException(
code: _kErrorValueToErrorName[error.code]!,
message: error.message != '' ? error.message : _kDefaultErrorMessage,
details: _kErrorValueToErrorDescription[error.code],
));
});
_videoElement.onEnded.listen((dynamic _) {
setBuffering(false);
_eventController.add(VideoEvent(eventType: VideoEventType.completed));
});
}
/// Attempts to play the video.
///
/// If this method is called programmatically (without user interaction), it
/// might fail unless the video is completely muted (or it has no Audio tracks).
///
/// When called from some user interaction (a tap on a button), the above
/// limitation should disappear.
Future<void> play() {
return _videoElement.play().catchError((Object e) {
// play() attempts to begin playback of the media. It returns
// a Promise which can get rejected in case of failure to begin
// playback for any reason, such as permission issues.
// The rejection handler is called with a DomException.
// See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play
final html.DomException exception = e as html.DomException;
_eventController.addError(PlatformException(
code: exception.name,
message: exception.message,
));
}, test: (Object e) => e is html.DomException);
}
/// Pauses the video in the current position.
void pause() {
_videoElement.pause();
}
/// Controls whether the video should start again after it finishes.
// ignore: use_setters_to_change_properties
void setLooping(bool value) {
_videoElement.loop = value;
}
/// Sets the volume at which the media will be played.
///
/// Values must fall between 0 and 1, where 0 is muted and 1 is the loudest.
///
/// When volume is set to 0, the `muted` property is also applied to the
/// [html.VideoElement]. This is required for auto-play on the web.
void setVolume(double volume) {
assert(volume >= 0 && volume <= 1);
// TODO(ditman): Do we need to expose a "muted" API?
// https://github.com/flutter/flutter/issues/60721
_videoElement.muted = !(volume > 0.0);
_videoElement.volume = volume;
}
/// Sets the playback `speed`.
///
/// A `speed` of 1.0 is "normal speed," values lower than 1.0 make the media
/// play slower than normal, higher values make it play faster.
///
/// `speed` cannot be negative.
///
/// The audio is muted when the fast forward or slow motion is outside a useful
/// range (for example, Gecko mutes the sound outside the range 0.25 to 4.0).
///
/// The pitch of the audio is corrected by default.
void setPlaybackSpeed(double speed) {
assert(speed > 0);
_videoElement.playbackRate = speed;
}
/// Moves the playback head to a new `position`.
///
/// `position` cannot be negative.
void seekTo(Duration position) {
assert(!position.isNegative);
_videoElement.currentTime = position.inMilliseconds.toDouble() / 1000;
}
/// Returns the current playback head position as a [Duration].
Duration getPosition() {
_sendBufferingRangesUpdate();
return Duration(milliseconds: (_videoElement.currentTime * 1000).round());
}
/// Disposes of the current [html.VideoElement].
void dispose() {
_videoElement.removeAttribute('src');
_videoElement.load();
}
// Sends an [VideoEventType.initialized] [VideoEvent] with info about the wrapped video.
void _sendInitialized() {
final Duration? duration =
convertNumVideoDurationToPluginDuration(_videoElement.duration);
final Size? size = _videoElement.videoHeight.isFinite
? Size(
_videoElement.videoWidth.toDouble(),
_videoElement.videoHeight.toDouble(),
)
: null;
_eventController.add(
VideoEvent(
eventType: VideoEventType.initialized,
duration: duration,
size: size,
),
);
}
/// Caches the current "buffering" state of the video.
///
/// If the current buffering state is different from the previous one
/// ([_isBuffering]), this dispatches a [VideoEvent].
@visibleForTesting
void setBuffering(bool buffering) {
if (_isBuffering != buffering) {
_isBuffering = buffering;
_eventController.add(VideoEvent(
eventType: _isBuffering
? VideoEventType.bufferingStart
: VideoEventType.bufferingEnd,
));
}
}
// Broadcasts the [html.VideoElement.buffered] status through the [events] stream.
void _sendBufferingRangesUpdate() {
_eventController.add(VideoEvent(
buffered: _toDurationRange(_videoElement.buffered),
eventType: VideoEventType.bufferingUpdate,
));
}
// Converts from [html.TimeRanges] to our own List<DurationRange>.
List<DurationRange> _toDurationRange(html.TimeRanges buffered) {
final List<DurationRange> durationRange = <DurationRange>[];
for (int i = 0; i < buffered.length; i++) {
durationRange.add(DurationRange(
Duration(milliseconds: (buffered.start(i) * 1000).round()),
Duration(milliseconds: (buffered.end(i) * 1000).round()),
));
}
return durationRange;
}
}
| plugins/packages/video_player/video_player_web/lib/src/video_player.dart/0 | {
"file_path": "plugins/packages/video_player/video_player_web/lib/src/video_player.dart",
"repo_id": "plugins",
"token_count": 2967
} | 1,263 |
h1 {
color: blue;
} | plugins/packages/webview_flutter/webview_flutter/example/assets/www/styles/style.css/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter/example/assets/www/styles/style.css",
"repo_id": "plugins",
"token_count": 13
} | 1,264 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:webview_flutter_example/main.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
void main() {
setUp(() {
WebViewPlatform.instance = FakeWebViewPlatform();
});
testWidgets('Test snackbar from ScaffoldMessenger',
(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: WebViewExample()));
expect(find.byIcon(Icons.favorite), findsOneWidget);
await tester.tap(find.byIcon(Icons.favorite));
await tester.pump();
expect(find.byType(SnackBar), findsOneWidget);
});
}
class FakeWebViewPlatform extends WebViewPlatform {
@override
PlatformWebViewController createPlatformWebViewController(
PlatformWebViewControllerCreationParams params,
) {
return FakeWebViewController(params);
}
@override
PlatformWebViewWidget createPlatformWebViewWidget(
PlatformWebViewWidgetCreationParams params,
) {
return FakeWebViewWidget(params);
}
@override
PlatformWebViewCookieManager createPlatformCookieManager(
PlatformWebViewCookieManagerCreationParams params,
) {
return FakeCookieManager(params);
}
@override
PlatformNavigationDelegate createPlatformNavigationDelegate(
PlatformNavigationDelegateCreationParams params,
) {
return FakeNavigationDelegate(params);
}
}
class FakeWebViewController extends PlatformWebViewController {
FakeWebViewController(super.params) : super.implementation();
@override
Future<void> setJavaScriptMode(JavaScriptMode javaScriptMode) async {}
@override
Future<void> setBackgroundColor(Color color) async {}
@override
Future<void> setPlatformNavigationDelegate(
PlatformNavigationDelegate handler,
) async {}
@override
Future<void> addJavaScriptChannel(
JavaScriptChannelParams javaScriptChannelParams) async {}
@override
Future<void> loadRequest(LoadRequestParams params) async {}
@override
Future<String?> currentUrl() async {
return 'https://www.google.com';
}
}
class FakeCookieManager extends PlatformWebViewCookieManager {
FakeCookieManager(super.params) : super.implementation();
}
class FakeWebViewWidget extends PlatformWebViewWidget {
FakeWebViewWidget(super.params) : super.implementation();
@override
Widget build(BuildContext context) {
return Container();
}
}
class FakeNavigationDelegate extends PlatformNavigationDelegate {
FakeNavigationDelegate(super.params) : super.implementation();
@override
Future<void> setOnNavigationRequest(
NavigationRequestCallback onNavigationRequest,
) async {}
@override
Future<void> setOnPageFinished(PageEventCallback onPageFinished) async {}
@override
Future<void> setOnPageStarted(PageEventCallback onPageStarted) async {}
@override
Future<void> setOnProgress(ProgressCallback onProgress) async {}
@override
Future<void> setOnWebResourceError(
WebResourceErrorCallback onWebResourceError,
) async {}
}
| plugins/packages/webview_flutter/webview_flutter/example/test/main_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter/example/test/main_test.dart",
"repo_id": "plugins",
"token_count": 975
} | 1,265 |
// Mocks generated by Mockito 5.3.2 from annotations
// in webview_flutter/test/webview_controller_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i5;
import 'dart:ui' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'package:webview_flutter_platform_interface/src/platform_navigation_delegate.dart'
as _i6;
import 'package:webview_flutter_platform_interface/src/platform_webview_controller.dart'
as _i4;
import 'package:webview_flutter_platform_interface/src/webview_platform.dart'
as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakePlatformWebViewControllerCreationParams_0 extends _i1.SmartFake
implements _i2.PlatformWebViewControllerCreationParams {
_FakePlatformWebViewControllerCreationParams_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeObject_1 extends _i1.SmartFake implements Object {
_FakeObject_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeOffset_2 extends _i1.SmartFake implements _i3.Offset {
_FakeOffset_2(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakePlatformNavigationDelegateCreationParams_3 extends _i1.SmartFake
implements _i2.PlatformNavigationDelegateCreationParams {
_FakePlatformNavigationDelegateCreationParams_3(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [PlatformWebViewController].
///
/// See the documentation for Mockito's code generation for more information.
class MockPlatformWebViewController extends _i1.Mock
implements _i4.PlatformWebViewController {
MockPlatformWebViewController() {
_i1.throwOnMissingStub(this);
}
@override
_i2.PlatformWebViewControllerCreationParams get params => (super.noSuchMethod(
Invocation.getter(#params),
returnValue: _FakePlatformWebViewControllerCreationParams_0(
this,
Invocation.getter(#params),
),
) as _i2.PlatformWebViewControllerCreationParams);
@override
_i5.Future<void> loadFile(String? absoluteFilePath) => (super.noSuchMethod(
Invocation.method(
#loadFile,
[absoluteFilePath],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> loadFlutterAsset(String? key) => (super.noSuchMethod(
Invocation.method(
#loadFlutterAsset,
[key],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> loadHtmlString(
String? html, {
String? baseUrl,
}) =>
(super.noSuchMethod(
Invocation.method(
#loadHtmlString,
[html],
{#baseUrl: baseUrl},
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> loadRequest(_i2.LoadRequestParams? params) =>
(super.noSuchMethod(
Invocation.method(
#loadRequest,
[params],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<String?> currentUrl() => (super.noSuchMethod(
Invocation.method(
#currentUrl,
[],
),
returnValue: _i5.Future<String?>.value(),
) as _i5.Future<String?>);
@override
_i5.Future<bool> canGoBack() => (super.noSuchMethod(
Invocation.method(
#canGoBack,
[],
),
returnValue: _i5.Future<bool>.value(false),
) as _i5.Future<bool>);
@override
_i5.Future<bool> canGoForward() => (super.noSuchMethod(
Invocation.method(
#canGoForward,
[],
),
returnValue: _i5.Future<bool>.value(false),
) as _i5.Future<bool>);
@override
_i5.Future<void> goBack() => (super.noSuchMethod(
Invocation.method(
#goBack,
[],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> goForward() => (super.noSuchMethod(
Invocation.method(
#goForward,
[],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> reload() => (super.noSuchMethod(
Invocation.method(
#reload,
[],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> clearCache() => (super.noSuchMethod(
Invocation.method(
#clearCache,
[],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> clearLocalStorage() => (super.noSuchMethod(
Invocation.method(
#clearLocalStorage,
[],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setPlatformNavigationDelegate(
_i6.PlatformNavigationDelegate? handler) =>
(super.noSuchMethod(
Invocation.method(
#setPlatformNavigationDelegate,
[handler],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> runJavaScript(String? javaScript) => (super.noSuchMethod(
Invocation.method(
#runJavaScript,
[javaScript],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<Object> runJavaScriptReturningResult(String? javaScript) =>
(super.noSuchMethod(
Invocation.method(
#runJavaScriptReturningResult,
[javaScript],
),
returnValue: _i5.Future<Object>.value(_FakeObject_1(
this,
Invocation.method(
#runJavaScriptReturningResult,
[javaScript],
),
)),
) as _i5.Future<Object>);
@override
_i5.Future<void> addJavaScriptChannel(
_i4.JavaScriptChannelParams? javaScriptChannelParams) =>
(super.noSuchMethod(
Invocation.method(
#addJavaScriptChannel,
[javaScriptChannelParams],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> removeJavaScriptChannel(String? javaScriptChannelName) =>
(super.noSuchMethod(
Invocation.method(
#removeJavaScriptChannel,
[javaScriptChannelName],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<String?> getTitle() => (super.noSuchMethod(
Invocation.method(
#getTitle,
[],
),
returnValue: _i5.Future<String?>.value(),
) as _i5.Future<String?>);
@override
_i5.Future<void> scrollTo(
int? x,
int? y,
) =>
(super.noSuchMethod(
Invocation.method(
#scrollTo,
[
x,
y,
],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> scrollBy(
int? x,
int? y,
) =>
(super.noSuchMethod(
Invocation.method(
#scrollBy,
[
x,
y,
],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<_i3.Offset> getScrollPosition() => (super.noSuchMethod(
Invocation.method(
#getScrollPosition,
[],
),
returnValue: _i5.Future<_i3.Offset>.value(_FakeOffset_2(
this,
Invocation.method(
#getScrollPosition,
[],
),
)),
) as _i5.Future<_i3.Offset>);
@override
_i5.Future<void> enableZoom(bool? enabled) => (super.noSuchMethod(
Invocation.method(
#enableZoom,
[enabled],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setBackgroundColor(_i3.Color? color) => (super.noSuchMethod(
Invocation.method(
#setBackgroundColor,
[color],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setJavaScriptMode(_i2.JavaScriptMode? javaScriptMode) =>
(super.noSuchMethod(
Invocation.method(
#setJavaScriptMode,
[javaScriptMode],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setUserAgent(String? userAgent) => (super.noSuchMethod(
Invocation.method(
#setUserAgent,
[userAgent],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
}
/// A class which mocks [PlatformNavigationDelegate].
///
/// See the documentation for Mockito's code generation for more information.
class MockPlatformNavigationDelegate extends _i1.Mock
implements _i6.PlatformNavigationDelegate {
MockPlatformNavigationDelegate() {
_i1.throwOnMissingStub(this);
}
@override
_i2.PlatformNavigationDelegateCreationParams get params =>
(super.noSuchMethod(
Invocation.getter(#params),
returnValue: _FakePlatformNavigationDelegateCreationParams_3(
this,
Invocation.getter(#params),
),
) as _i2.PlatformNavigationDelegateCreationParams);
@override
_i5.Future<void> setOnNavigationRequest(
_i6.NavigationRequestCallback? onNavigationRequest) =>
(super.noSuchMethod(
Invocation.method(
#setOnNavigationRequest,
[onNavigationRequest],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnPageStarted(_i6.PageEventCallback? onPageStarted) =>
(super.noSuchMethod(
Invocation.method(
#setOnPageStarted,
[onPageStarted],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnPageFinished(_i6.PageEventCallback? onPageFinished) =>
(super.noSuchMethod(
Invocation.method(
#setOnPageFinished,
[onPageFinished],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnProgress(_i6.ProgressCallback? onProgress) =>
(super.noSuchMethod(
Invocation.method(
#setOnProgress,
[onProgress],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnWebResourceError(
_i6.WebResourceErrorCallback? onWebResourceError) =>
(super.noSuchMethod(
Invocation.method(
#setOnWebResourceError,
[onWebResourceError],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
}
| plugins/packages/webview_flutter/webview_flutter/test/webview_controller_test.mocks.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter/test/webview_controller_test.mocks.dart",
"repo_id": "plugins",
"token_count": 5941
} | 1,266 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import android.webkit.DownloadListener;
import androidx.annotation.NonNull;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.DownloadListenerHostApi;
/**
* Host api implementation for {@link DownloadListener}.
*
* <p>Handles creating {@link DownloadListener}s that intercommunicate with a paired Dart object.
*/
public class DownloadListenerHostApiImpl implements DownloadListenerHostApi {
private final InstanceManager instanceManager;
private final DownloadListenerCreator downloadListenerCreator;
private final DownloadListenerFlutterApiImpl flutterApi;
/**
* Implementation of {@link DownloadListener} that passes arguments of callback methods to Dart.
*/
public static class DownloadListenerImpl implements DownloadListener {
private final DownloadListenerFlutterApiImpl flutterApi;
/**
* Creates a {@link DownloadListenerImpl} that passes arguments of callbacks methods to Dart.
*
* @param flutterApi handles sending messages to Dart
*/
public DownloadListenerImpl(@NonNull DownloadListenerFlutterApiImpl flutterApi) {
this.flutterApi = flutterApi;
}
@Override
public void onDownloadStart(
String url,
String userAgent,
String contentDisposition,
String mimetype,
long contentLength) {
flutterApi.onDownloadStart(
this, url, userAgent, contentDisposition, mimetype, contentLength, reply -> {});
}
}
/** Handles creating {@link DownloadListenerImpl}s for a {@link DownloadListenerHostApiImpl}. */
public static class DownloadListenerCreator {
/**
* Creates a {@link DownloadListenerImpl}.
*
* @param flutterApi handles sending messages to Dart
* @return the created {@link DownloadListenerImpl}
*/
public DownloadListenerImpl createDownloadListener(DownloadListenerFlutterApiImpl flutterApi) {
return new DownloadListenerImpl(flutterApi);
}
}
/**
* Creates a host API that handles creating {@link DownloadListener}s.
*
* @param instanceManager maintains instances stored to communicate with Dart objects
* @param downloadListenerCreator handles creating {@link DownloadListenerImpl}s
* @param flutterApi handles sending messages to Dart
*/
public DownloadListenerHostApiImpl(
InstanceManager instanceManager,
DownloadListenerCreator downloadListenerCreator,
DownloadListenerFlutterApiImpl flutterApi) {
this.instanceManager = instanceManager;
this.downloadListenerCreator = downloadListenerCreator;
this.flutterApi = flutterApi;
}
@Override
public void create(Long instanceId) {
final DownloadListener downloadListener =
downloadListenerCreator.createDownloadListener(flutterApi);
instanceManager.addDartCreatedInstance(downloadListener, instanceId);
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/DownloadListenerHostApiImpl.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/DownloadListenerHostApiImpl.java",
"repo_id": "plugins",
"token_count": 911
} | 1,267 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import android.webkit.WebStorage;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebStorageHostApi;
/**
* Host api implementation for {@link WebStorage}.
*
* <p>Handles creating {@link WebStorage}s that intercommunicate with a paired Dart object.
*/
public class WebStorageHostApiImpl implements WebStorageHostApi {
private final InstanceManager instanceManager;
private final WebStorageCreator webStorageCreator;
/** Handles creating {@link WebStorage} for a {@link WebStorageHostApiImpl}. */
public static class WebStorageCreator {
/**
* Creates a {@link WebStorage}.
*
* @return the created {@link WebStorage}. Defaults to {@link WebStorage#getInstance}
*/
public WebStorage createWebStorage() {
return WebStorage.getInstance();
}
}
/**
* Creates a host API that handles creating {@link WebStorage} and invoke its methods.
*
* @param instanceManager maintains instances stored to communicate with Dart objects
* @param webStorageCreator handles creating {@link WebStorage}s
*/
public WebStorageHostApiImpl(
InstanceManager instanceManager, WebStorageCreator webStorageCreator) {
this.instanceManager = instanceManager;
this.webStorageCreator = webStorageCreator;
}
@Override
public void create(Long instanceId) {
instanceManager.addDartCreatedInstance(webStorageCreator.createWebStorage(), instanceId);
}
@Override
public void deleteAllData(Long instanceId) {
final WebStorage webStorage = (WebStorage) instanceManager.getInstance(instanceId);
webStorage.deleteAllData();
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebStorageHostApiImpl.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebStorageHostApiImpl.java",
"repo_id": "plugins",
"token_count": 534
} | 1,268 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.res.AssetManager;
import io.flutter.plugin.common.PluginRegistry.Registrar;
import io.flutter.plugins.webviewflutter.FlutterAssetManager.RegistrarFlutterAssetManager;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
@SuppressWarnings("deprecation")
public class RegistrarFlutterAssetManagerTest {
@Mock AssetManager mockAssetManager;
@Mock Registrar mockRegistrar;
RegistrarFlutterAssetManager testRegistrarFlutterAssetManager;
@Before
public void setUp() {
mockAssetManager = mock(AssetManager.class);
mockRegistrar = mock(Registrar.class);
testRegistrarFlutterAssetManager =
new RegistrarFlutterAssetManager(mockAssetManager, mockRegistrar);
}
@Test
public void list() {
try {
when(mockAssetManager.list("test/path"))
.thenReturn(new String[] {"index.html", "styles.css"});
String[] actualFilePaths = testRegistrarFlutterAssetManager.list("test/path");
verify(mockAssetManager).list("test/path");
assertArrayEquals(new String[] {"index.html", "styles.css"}, actualFilePaths);
} catch (IOException ex) {
fail();
}
}
@Test
public void registrar_getAssetFilePathByName() {
testRegistrarFlutterAssetManager.getAssetFilePathByName("sample_movie.mp4");
verify(mockRegistrar).lookupKeyForAsset("sample_movie.mp4");
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/RegistrarFlutterAssetManagerTest.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/RegistrarFlutterAssetManagerTest.java",
"repo_id": "plugins",
"token_count": 619
} | 1,269 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'android_webview.dart';
/// Object specifying creation parameters for creating a [AndroidWebViewCookieManager].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformWebViewCookieManagerCreationParams] for
/// more information.
@immutable
class AndroidWebViewCookieManagerCreationParams
extends PlatformWebViewCookieManagerCreationParams {
/// Creates a new [AndroidWebViewCookieManagerCreationParams] instance.
const AndroidWebViewCookieManagerCreationParams._(
// This parameter prevents breaking changes later.
// ignore: avoid_unused_constructor_parameters
PlatformWebViewCookieManagerCreationParams params,
) : super();
/// Creates a [AndroidWebViewCookieManagerCreationParams] instance based on [PlatformWebViewCookieManagerCreationParams].
factory AndroidWebViewCookieManagerCreationParams.fromPlatformWebViewCookieManagerCreationParams(
PlatformWebViewCookieManagerCreationParams params) {
return AndroidWebViewCookieManagerCreationParams._(params);
}
}
/// Handles all cookie operations for the Android platform.
class AndroidWebViewCookieManager extends PlatformWebViewCookieManager {
/// Creates a new [AndroidWebViewCookieManager].
AndroidWebViewCookieManager(
PlatformWebViewCookieManagerCreationParams params, {
CookieManager? cookieManager,
}) : _cookieManager = cookieManager ?? CookieManager.instance,
super.implementation(
params is AndroidWebViewCookieManagerCreationParams
? params
: AndroidWebViewCookieManagerCreationParams
.fromPlatformWebViewCookieManagerCreationParams(params),
);
final CookieManager _cookieManager;
@override
Future<bool> clearCookies() {
return _cookieManager.clearCookies();
}
@override
Future<void> setCookie(WebViewCookie cookie) {
if (!_isValidPath(cookie.path)) {
throw ArgumentError(
'The path property for the provided cookie was not given a legal value.');
}
return _cookieManager.setCookie(
cookie.domain,
'${Uri.encodeComponent(cookie.name)}=${Uri.encodeComponent(cookie.value)}; path=${cookie.path}',
);
}
bool _isValidPath(String path) {
// Permitted ranges based on RFC6265bis: https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-02#section-4.1.1
for (final int char in path.codeUnits) {
if ((char < 0x20 || char > 0x3A) && (char < 0x3C || char > 0x7E)) {
return false;
}
}
return true;
}
}
| plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_cookie_manager.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_cookie_manager.dart",
"repo_id": "plugins",
"token_count": 942
} | 1,270 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:webview_flutter_android/src/android_webview.dart'
as android_webview;
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_platform_interface/src/webview_platform.dart';
import 'android_webview_cookie_manager_test.mocks.dart';
@GenerateMocks(<Type>[android_webview.CookieManager])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('clearCookies should call android_webview.clearCookies', () async {
final android_webview.CookieManager mockCookieManager = MockCookieManager();
when(mockCookieManager.clearCookies())
.thenAnswer((_) => Future<bool>.value(true));
final AndroidWebViewCookieManagerCreationParams params =
AndroidWebViewCookieManagerCreationParams
.fromPlatformWebViewCookieManagerCreationParams(
const PlatformWebViewCookieManagerCreationParams());
final bool hasClearedCookies = await AndroidWebViewCookieManager(params,
cookieManager: mockCookieManager)
.clearCookies();
expect(hasClearedCookies, true);
verify(mockCookieManager.clearCookies());
});
test('setCookie should throw ArgumentError for cookie with invalid path', () {
final AndroidWebViewCookieManagerCreationParams params =
AndroidWebViewCookieManagerCreationParams
.fromPlatformWebViewCookieManagerCreationParams(
const PlatformWebViewCookieManagerCreationParams());
final AndroidWebViewCookieManager androidCookieManager =
AndroidWebViewCookieManager(params, cookieManager: MockCookieManager());
expect(
() => androidCookieManager.setCookie(const WebViewCookie(
name: 'foo',
value: 'bar',
domain: 'flutter.dev',
path: 'invalid;path',
)),
throwsA(const TypeMatcher<ArgumentError>()),
);
});
test(
'setCookie should call android_webview.csetCookie with properly formatted cookie value',
() {
final android_webview.CookieManager mockCookieManager = MockCookieManager();
final AndroidWebViewCookieManagerCreationParams params =
AndroidWebViewCookieManagerCreationParams
.fromPlatformWebViewCookieManagerCreationParams(
const PlatformWebViewCookieManagerCreationParams());
AndroidWebViewCookieManager(params, cookieManager: mockCookieManager)
.setCookie(const WebViewCookie(
name: 'foo&',
value: 'bar@',
domain: 'flutter.dev',
));
verify(mockCookieManager.setCookie(
'flutter.dev',
'foo%26=bar%40; path=/',
));
});
}
| plugins/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.dart",
"repo_id": "plugins",
"token_count": 1053
} | 1,271 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'webview_platform.dart';
/// Signature for callbacks that report a pending navigation request.
typedef NavigationRequestCallback = FutureOr<NavigationDecision> Function(
NavigationRequest navigationRequest);
/// Signature for callbacks that report page events triggered by the native web view.
typedef PageEventCallback = void Function(String url);
/// Signature for callbacks that report loading progress of a page.
typedef ProgressCallback = void Function(int progress);
/// Signature for callbacks that report a resource loading error.
typedef WebResourceErrorCallback = void Function(WebResourceError error);
/// An interface defining navigation events that occur on the native platform.
///
/// The [PlatformWebViewController] is notifying this delegate on events that
/// happened on the platform's webview. Platform implementations should
/// implement this class and pass an instance to the [PlatformWebViewController].
abstract class PlatformNavigationDelegate extends PlatformInterface {
/// Creates a new [PlatformNavigationDelegate]
factory PlatformNavigationDelegate(
PlatformNavigationDelegateCreationParams params) {
assert(
WebViewPlatform.instance != null,
'A platform implementation for `webview_flutter` has not been set. Please '
'ensure that an implementation of `WebViewPlatform` has been set to '
'`WebViewPlatform.instance` before use. For unit testing, '
'`WebViewPlatform.instance` can be set with your own test implementation.',
);
final PlatformNavigationDelegate callbackDelegate =
WebViewPlatform.instance!.createPlatformNavigationDelegate(params);
PlatformInterface.verify(callbackDelegate, _token);
return callbackDelegate;
}
/// Used by the platform implementation to create a new [PlatformNavigationDelegate].
///
/// Should only be used by platform implementations because they can't extend
/// a class that only contains a factory constructor.
@protected
PlatformNavigationDelegate.implementation(this.params) : super(token: _token);
static final Object _token = Object();
/// The parameters used to initialize the [PlatformNavigationDelegate].
final PlatformNavigationDelegateCreationParams params;
/// Invoked when a navigation request is pending.
///
/// See [PlatformWebViewController.setPlatformNavigationDelegate].
Future<void> setOnNavigationRequest(
NavigationRequestCallback onNavigationRequest,
) {
throw UnimplementedError(
'setOnNavigationRequest is not implemented on the current platform.');
}
/// Invoked when a page has started loading.
///
/// See [PlatformWebViewController.setPlatformNavigationDelegate].
Future<void> setOnPageStarted(
PageEventCallback onPageStarted,
) {
throw UnimplementedError(
'setOnPageStarted is not implemented on the current platform.');
}
/// Invoked when a page has finished loading.
///
/// See [PlatformWebViewController.setPlatformNavigationDelegate].
Future<void> setOnPageFinished(
PageEventCallback onPageFinished,
) {
throw UnimplementedError(
'setOnPageFinished is not implemented on the current platform.');
}
/// Invoked when a page is loading to report the progress.
///
/// See [PlatformWebViewController.setPlatformNavigationDelegate].
Future<void> setOnProgress(
ProgressCallback onProgress,
) {
throw UnimplementedError(
'setOnProgress is not implemented on the current platform.');
}
/// Invoked when a resource loading error occurred.
///
/// See [PlatformWebViewController.setPlatformNavigationDelegate].
Future<void> setOnWebResourceError(
WebResourceErrorCallback onWebResourceError,
) {
throw UnimplementedError(
'setOnWebResourceError is not implemented on the current platform.');
}
}
| plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_navigation_delegate.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_navigation_delegate.dart",
"repo_id": "plugins",
"token_count": 1132
} | 1,272 |
## 0.2.2
* Updates `WebWebViewController.loadRequest` to only set the src of the iFrame
when `LoadRequestParams.headers` and `LoadRequestParams.body` are empty and is
using the HTTP GET request method. [#118573](https://github.com/flutter/flutter/issues/118573).
* Parses the `content-type` header of XHR responses to extract the correct
MIME-type and charset. [#118090](https://github.com/flutter/flutter/issues/118090).
* Sets `width` and `height` of widget the way the Engine wants, to remove distracting
warnings from the development console.
* Updates minimum Flutter version to 3.0.
## 0.2.1
* Adds auto registration of the `WebViewPlatform` implementation.
## 0.2.0
* **BREAKING CHANGE** Updates platform implementation to `2.0.0` release of
`webview_flutter_platform_interface`. See README for updated usage.
* Updates minimum Flutter version to 2.10.
## 0.1.0+4
* Fixes incorrect escaping of some characters when setting the HTML to the iframe element.
## 0.1.0+3
* Minor fixes for new analysis options.
## 0.1.0+2
* Removes unnecessary imports.
* Fixes unit tests to run on latest `master` version of Flutter.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.1.0+1
* Adds an explanation of registering the implementation in the README.
## 0.1.0
* First web implementation for webview_flutter
| plugins/packages/webview_flutter/webview_flutter_web/CHANGELOG.md/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_web/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 431
} | 1,273 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <OCMock/OCMock.h>
#import <XCTest/XCTest.h>
@import webview_flutter_wkwebview;
@interface FWFWebViewFlutterWKWebViewExternalAPITests : XCTestCase
@end
@implementation FWFWebViewFlutterWKWebViewExternalAPITests
- (void)testWebViewForIdentifier {
WKWebView *webView = [[WKWebView alloc] init];
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
[instanceManager addDartCreatedInstance:webView withIdentifier:0];
id<FlutterPluginRegistry> mockPluginRegistry = OCMProtocolMock(@protocol(FlutterPluginRegistry));
OCMStub([mockPluginRegistry valuePublishedByPlugin:@"FLTWebViewFlutterPlugin"])
.andReturn(instanceManager);
XCTAssertEqualObjects(
[FWFWebViewFlutterWKWebViewExternalAPI webViewForIdentifier:0
withPluginRegistry:mockPluginRegistry],
webView);
}
@end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFWebViewFlutterWKWebViewExternalAPITests.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFWebViewFlutterWKWebViewExternalAPITests.m",
"repo_id": "plugins",
"token_count": 380
} | 1,274 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FWFDataConverters.h"
#import <Flutter/Flutter.h>
NSURLRequest *_Nullable FWFNSURLRequestFromRequestData(FWFNSUrlRequestData *data) {
NSURL *url = [NSURL URLWithString:data.url];
if (!url) {
return nil;
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
if (!request) {
return nil;
}
if (data.httpMethod) {
[request setHTTPMethod:data.httpMethod];
}
if (data.httpBody) {
[request setHTTPBody:data.httpBody.data];
}
[request setAllHTTPHeaderFields:data.allHttpHeaderFields];
return request;
}
extern NSHTTPCookie *_Nullable FWFNSHTTPCookieFromCookieData(FWFNSHttpCookieData *data) {
NSMutableDictionary<NSHTTPCookiePropertyKey, id> *properties = [NSMutableDictionary dictionary];
for (int i = 0; i < data.propertyKeys.count; i++) {
NSHTTPCookiePropertyKey cookieKey =
FWFNSHTTPCookiePropertyKeyFromEnumData(data.propertyKeys[i]);
if (!cookieKey) {
// Some keys aren't supported on all versions, so this ignores keys
// that require a higher version or are unsupported.
continue;
}
[properties setObject:data.propertyValues[i] forKey:cookieKey];
}
return [NSHTTPCookie cookieWithProperties:properties];
}
NSKeyValueObservingOptions FWFNSKeyValueObservingOptionsFromEnumData(
FWFNSKeyValueObservingOptionsEnumData *data) {
switch (data.value) {
case FWFNSKeyValueObservingOptionsEnumNewValue:
return NSKeyValueObservingOptionNew;
case FWFNSKeyValueObservingOptionsEnumOldValue:
return NSKeyValueObservingOptionOld;
case FWFNSKeyValueObservingOptionsEnumInitialValue:
return NSKeyValueObservingOptionInitial;
case FWFNSKeyValueObservingOptionsEnumPriorNotification:
return NSKeyValueObservingOptionPrior;
}
return -1;
}
NSHTTPCookiePropertyKey _Nullable FWFNSHTTPCookiePropertyKeyFromEnumData(
FWFNSHttpCookiePropertyKeyEnumData *data) {
switch (data.value) {
case FWFNSHttpCookiePropertyKeyEnumComment:
return NSHTTPCookieComment;
case FWFNSHttpCookiePropertyKeyEnumCommentUrl:
return NSHTTPCookieCommentURL;
case FWFNSHttpCookiePropertyKeyEnumDiscard:
return NSHTTPCookieDiscard;
case FWFNSHttpCookiePropertyKeyEnumDomain:
return NSHTTPCookieDomain;
case FWFNSHttpCookiePropertyKeyEnumExpires:
return NSHTTPCookieExpires;
case FWFNSHttpCookiePropertyKeyEnumMaximumAge:
return NSHTTPCookieMaximumAge;
case FWFNSHttpCookiePropertyKeyEnumName:
return NSHTTPCookieName;
case FWFNSHttpCookiePropertyKeyEnumOriginUrl:
return NSHTTPCookieOriginURL;
case FWFNSHttpCookiePropertyKeyEnumPath:
return NSHTTPCookiePath;
case FWFNSHttpCookiePropertyKeyEnumPort:
return NSHTTPCookiePort;
case FWFNSHttpCookiePropertyKeyEnumSameSitePolicy:
if (@available(iOS 13.0, *)) {
return NSHTTPCookieSameSitePolicy;
} else {
return nil;
}
case FWFNSHttpCookiePropertyKeyEnumSecure:
return NSHTTPCookieSecure;
case FWFNSHttpCookiePropertyKeyEnumValue:
return NSHTTPCookieValue;
case FWFNSHttpCookiePropertyKeyEnumVersion:
return NSHTTPCookieVersion;
}
return nil;
}
extern WKUserScript *FWFWKUserScriptFromScriptData(FWFWKUserScriptData *data) {
return [[WKUserScript alloc]
initWithSource:data.source
injectionTime:FWFWKUserScriptInjectionTimeFromEnumData(data.injectionTime)
forMainFrameOnly:data.isMainFrameOnly.boolValue];
}
WKUserScriptInjectionTime FWFWKUserScriptInjectionTimeFromEnumData(
FWFWKUserScriptInjectionTimeEnumData *data) {
switch (data.value) {
case FWFWKUserScriptInjectionTimeEnumAtDocumentStart:
return WKUserScriptInjectionTimeAtDocumentStart;
case FWFWKUserScriptInjectionTimeEnumAtDocumentEnd:
return WKUserScriptInjectionTimeAtDocumentEnd;
}
return -1;
}
API_AVAILABLE(ios(10.0))
WKAudiovisualMediaTypes FWFWKAudiovisualMediaTypeFromEnumData(
FWFWKAudiovisualMediaTypeEnumData *data) {
switch (data.value) {
case FWFWKAudiovisualMediaTypeEnumNone:
return WKAudiovisualMediaTypeNone;
case FWFWKAudiovisualMediaTypeEnumAudio:
return WKAudiovisualMediaTypeAudio;
case FWFWKAudiovisualMediaTypeEnumVideo:
return WKAudiovisualMediaTypeVideo;
case FWFWKAudiovisualMediaTypeEnumAll:
return WKAudiovisualMediaTypeAll;
}
return -1;
}
NSString *_Nullable FWFWKWebsiteDataTypeFromEnumData(FWFWKWebsiteDataTypeEnumData *data) {
switch (data.value) {
case FWFWKWebsiteDataTypeEnumCookies:
return WKWebsiteDataTypeCookies;
case FWFWKWebsiteDataTypeEnumMemoryCache:
return WKWebsiteDataTypeMemoryCache;
case FWFWKWebsiteDataTypeEnumDiskCache:
return WKWebsiteDataTypeDiskCache;
case FWFWKWebsiteDataTypeEnumOfflineWebApplicationCache:
return WKWebsiteDataTypeOfflineWebApplicationCache;
case FWFWKWebsiteDataTypeEnumLocalStorage:
return WKWebsiteDataTypeLocalStorage;
case FWFWKWebsiteDataTypeEnumSessionStorage:
return WKWebsiteDataTypeSessionStorage;
case FWFWKWebsiteDataTypeEnumWebSQLDatabases:
return WKWebsiteDataTypeWebSQLDatabases;
case FWFWKWebsiteDataTypeEnumIndexedDBDatabases:
return WKWebsiteDataTypeIndexedDBDatabases;
}
return nil;
}
FWFWKNavigationActionData *FWFWKNavigationActionDataFromNavigationAction(
WKNavigationAction *action) {
return [FWFWKNavigationActionData
makeWithRequest:FWFNSUrlRequestDataFromNSURLRequest(action.request)
targetFrame:FWFWKFrameInfoDataFromWKFrameInfo(action.targetFrame)
navigationType:FWFWKNavigationTypeFromWKNavigationType(action.navigationType)];
}
FWFNSUrlRequestData *FWFNSUrlRequestDataFromNSURLRequest(NSURLRequest *request) {
return [FWFNSUrlRequestData
makeWithUrl:request.URL.absoluteString
httpMethod:request.HTTPMethod
httpBody:request.HTTPBody
? [FlutterStandardTypedData typedDataWithBytes:request.HTTPBody]
: nil
allHttpHeaderFields:request.allHTTPHeaderFields ? request.allHTTPHeaderFields : @{}];
}
FWFWKFrameInfoData *FWFWKFrameInfoDataFromWKFrameInfo(WKFrameInfo *info) {
return [FWFWKFrameInfoData makeWithIsMainFrame:@(info.isMainFrame)];
}
WKNavigationActionPolicy FWFWKNavigationActionPolicyFromEnumData(
FWFWKNavigationActionPolicyEnumData *data) {
switch (data.value) {
case FWFWKNavigationActionPolicyEnumAllow:
return WKNavigationActionPolicyAllow;
case FWFWKNavigationActionPolicyEnumCancel:
return WKNavigationActionPolicyCancel;
}
return -1;
}
FWFNSErrorData *FWFNSErrorDataFromNSError(NSError *error) {
return [FWFNSErrorData makeWithCode:@(error.code)
domain:error.domain
localizedDescription:error.localizedDescription];
}
FWFNSKeyValueChangeKeyEnumData *FWFNSKeyValueChangeKeyEnumDataFromNSKeyValueChangeKey(
NSKeyValueChangeKey key) {
if ([key isEqualToString:NSKeyValueChangeIndexesKey]) {
return [FWFNSKeyValueChangeKeyEnumData makeWithValue:FWFNSKeyValueChangeKeyEnumIndexes];
} else if ([key isEqualToString:NSKeyValueChangeKindKey]) {
return [FWFNSKeyValueChangeKeyEnumData makeWithValue:FWFNSKeyValueChangeKeyEnumKind];
} else if ([key isEqualToString:NSKeyValueChangeNewKey]) {
return [FWFNSKeyValueChangeKeyEnumData makeWithValue:FWFNSKeyValueChangeKeyEnumNewValue];
} else if ([key isEqualToString:NSKeyValueChangeNotificationIsPriorKey]) {
return [FWFNSKeyValueChangeKeyEnumData
makeWithValue:FWFNSKeyValueChangeKeyEnumNotificationIsPrior];
} else if ([key isEqualToString:NSKeyValueChangeOldKey]) {
return [FWFNSKeyValueChangeKeyEnumData makeWithValue:FWFNSKeyValueChangeKeyEnumOldValue];
}
return nil;
}
FWFWKScriptMessageData *FWFWKScriptMessageDataFromWKScriptMessage(WKScriptMessage *message) {
return [FWFWKScriptMessageData makeWithName:message.name body:message.body];
}
FWFWKNavigationType FWFWKNavigationTypeFromWKNavigationType(WKNavigationType type) {
switch (type) {
case WKNavigationTypeLinkActivated:
return FWFWKNavigationTypeLinkActivated;
case WKNavigationTypeFormSubmitted:
return FWFWKNavigationTypeFormResubmitted;
case WKNavigationTypeBackForward:
return FWFWKNavigationTypeBackForward;
case WKNavigationTypeReload:
return FWFWKNavigationTypeReload;
case WKNavigationTypeFormResubmitted:
return FWFWKNavigationTypeFormResubmitted;
case WKNavigationTypeOther:
return FWFWKNavigationTypeOther;
}
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFDataConverters.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFDataConverters.m",
"repo_id": "plugins",
"token_count": 3265
} | 1,275 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as path;
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'common/instance_manager.dart';
import 'common/weak_reference_utils.dart';
import 'foundation/foundation.dart';
import 'web_kit/web_kit.dart';
import 'webkit_proxy.dart';
/// Media types that can require a user gesture to begin playing.
///
/// See [WebKitWebViewControllerCreationParams.mediaTypesRequiringUserAction].
enum PlaybackMediaTypes {
/// A media type that contains audio.
audio,
/// A media type that contains video.
video;
WKAudiovisualMediaType _toWKAudiovisualMediaType() {
switch (this) {
case PlaybackMediaTypes.audio:
return WKAudiovisualMediaType.audio;
case PlaybackMediaTypes.video:
return WKAudiovisualMediaType.video;
}
}
}
/// Object specifying creation parameters for a [WebKitWebViewController].
@immutable
class WebKitWebViewControllerCreationParams
extends PlatformWebViewControllerCreationParams {
/// Constructs a [WebKitWebViewControllerCreationParams].
WebKitWebViewControllerCreationParams({
@visibleForTesting this.webKitProxy = const WebKitProxy(),
this.mediaTypesRequiringUserAction = const <PlaybackMediaTypes>{
PlaybackMediaTypes.audio,
PlaybackMediaTypes.video,
},
this.allowsInlineMediaPlayback = false,
@visibleForTesting InstanceManager? instanceManager,
}) : _instanceManager = instanceManager ?? NSObject.globalInstanceManager {
_configuration = webKitProxy.createWebViewConfiguration(
instanceManager: _instanceManager,
);
if (mediaTypesRequiringUserAction.isEmpty) {
_configuration.setMediaTypesRequiringUserActionForPlayback(
<WKAudiovisualMediaType>{WKAudiovisualMediaType.none},
);
} else {
_configuration.setMediaTypesRequiringUserActionForPlayback(
mediaTypesRequiringUserAction
.map<WKAudiovisualMediaType>(
(PlaybackMediaTypes type) => type._toWKAudiovisualMediaType(),
)
.toSet(),
);
}
_configuration.setAllowsInlineMediaPlayback(allowsInlineMediaPlayback);
}
/// Constructs a [WebKitWebViewControllerCreationParams] using a
/// [PlatformWebViewControllerCreationParams].
WebKitWebViewControllerCreationParams.fromPlatformWebViewControllerCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformWebViewControllerCreationParams params, {
@visibleForTesting WebKitProxy webKitProxy = const WebKitProxy(),
Set<PlaybackMediaTypes> mediaTypesRequiringUserAction =
const <PlaybackMediaTypes>{
PlaybackMediaTypes.audio,
PlaybackMediaTypes.video,
},
bool allowsInlineMediaPlayback = false,
@visibleForTesting InstanceManager? instanceManager,
}) : this(
webKitProxy: webKitProxy,
mediaTypesRequiringUserAction: mediaTypesRequiringUserAction,
allowsInlineMediaPlayback: allowsInlineMediaPlayback,
instanceManager: instanceManager,
);
late final WKWebViewConfiguration _configuration;
/// Media types that require a user gesture to begin playing.
///
/// Defaults to include [PlaybackMediaTypes.audio] and
/// [PlaybackMediaTypes.video].
final Set<PlaybackMediaTypes> mediaTypesRequiringUserAction;
/// Whether inline playback of HTML5 videos is allowed.
///
/// Defaults to false.
final bool allowsInlineMediaPlayback;
/// Handles constructing objects and calling static methods for the WebKit
/// native library.
@visibleForTesting
final WebKitProxy webKitProxy;
// Maintains instances used to communicate with the native objects they
// represent.
final InstanceManager _instanceManager;
}
/// An implementation of [PlatformWebViewController] with the WebKit api.
class WebKitWebViewController extends PlatformWebViewController {
/// Constructs a [WebKitWebViewController].
WebKitWebViewController(PlatformWebViewControllerCreationParams params)
: super.implementation(params is WebKitWebViewControllerCreationParams
? params
: WebKitWebViewControllerCreationParams
.fromPlatformWebViewControllerCreationParams(params)) {
_webView.addObserver(
_webView,
keyPath: 'estimatedProgress',
options: <NSKeyValueObservingOptions>{
NSKeyValueObservingOptions.newValue,
},
);
}
/// The WebKit WebView being controlled.
late final WKWebView _webView = _webKitParams.webKitProxy.createWebView(
_webKitParams._configuration,
observeValue: withWeakRefenceTo(this, (
WeakReference<WebKitWebViewController> weakReference,
) {
return (
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
) {
final ProgressCallback? progressCallback =
weakReference.target?._currentNavigationDelegate?._onProgress;
if (progressCallback != null) {
final double progress =
change[NSKeyValueChangeKey.newValue]! as double;
progressCallback((progress * 100).round());
}
};
}),
instanceManager: _webKitParams._instanceManager,
);
final Map<String, WebKitJavaScriptChannelParams> _javaScriptChannelParams =
<String, WebKitJavaScriptChannelParams>{};
bool _zoomEnabled = true;
WebKitNavigationDelegate? _currentNavigationDelegate;
WebKitWebViewControllerCreationParams get _webKitParams =>
params as WebKitWebViewControllerCreationParams;
/// Identifier used to retrieve the underlying native `WKWebView`.
///
/// This is typically used by other plugins to retrieve the native `WKWebView`
/// from an `FWFInstanceManager`.
///
/// See Objective-C method
/// `FLTWebViewFlutterPlugin:webViewForIdentifier:withPluginRegistry`.
int get webViewIdentifier =>
_webKitParams._instanceManager.getIdentifier(_webView)!;
@override
Future<void> loadFile(String absoluteFilePath) {
return _webView.loadFileUrl(
absoluteFilePath,
readAccessUrl: path.dirname(absoluteFilePath),
);
}
@override
Future<void> loadFlutterAsset(String key) {
assert(key.isNotEmpty);
return _webView.loadFlutterAsset(key);
}
@override
Future<void> loadHtmlString(String html, {String? baseUrl}) {
return _webView.loadHtmlString(html, baseUrl: baseUrl);
}
@override
Future<void> loadRequest(LoadRequestParams params) {
if (!params.uri.hasScheme) {
throw ArgumentError(
'LoadRequestParams#uri is required to have a scheme.',
);
}
return _webView.loadRequest(NSUrlRequest(
url: params.uri.toString(),
allHttpHeaderFields: params.headers,
httpMethod: describeEnum(params.method),
httpBody: params.body,
));
}
@override
Future<void> addJavaScriptChannel(
JavaScriptChannelParams javaScriptChannelParams,
) {
final WebKitJavaScriptChannelParams webKitParams =
javaScriptChannelParams is WebKitJavaScriptChannelParams
? javaScriptChannelParams
: WebKitJavaScriptChannelParams.fromJavaScriptChannelParams(
javaScriptChannelParams);
_javaScriptChannelParams[webKitParams.name] = webKitParams;
final String wrapperSource =
'window.${webKitParams.name} = webkit.messageHandlers.${webKitParams.name};';
final WKUserScript wrapperScript = WKUserScript(
wrapperSource,
WKUserScriptInjectionTime.atDocumentStart,
isMainFrameOnly: false,
);
_webView.configuration.userContentController.addUserScript(wrapperScript);
return _webView.configuration.userContentController.addScriptMessageHandler(
webKitParams._messageHandler,
webKitParams.name,
);
}
@override
Future<void> removeJavaScriptChannel(String javaScriptChannelName) async {
assert(javaScriptChannelName.isNotEmpty);
if (!_javaScriptChannelParams.containsKey(javaScriptChannelName)) {
return;
}
await _resetUserScripts(removedJavaScriptChannel: javaScriptChannelName);
}
@override
Future<String?> currentUrl() => _webView.getUrl();
@override
Future<bool> canGoBack() => _webView.canGoBack();
@override
Future<bool> canGoForward() => _webView.canGoForward();
@override
Future<void> goBack() => _webView.goBack();
@override
Future<void> goForward() => _webView.goForward();
@override
Future<void> reload() => _webView.reload();
@override
Future<void> clearCache() {
return _webView.configuration.websiteDataStore.removeDataOfTypes(
<WKWebsiteDataType>{
WKWebsiteDataType.memoryCache,
WKWebsiteDataType.diskCache,
WKWebsiteDataType.offlineWebApplicationCache,
},
DateTime.fromMillisecondsSinceEpoch(0),
);
}
@override
Future<void> clearLocalStorage() {
return _webView.configuration.websiteDataStore.removeDataOfTypes(
<WKWebsiteDataType>{WKWebsiteDataType.localStorage},
DateTime.fromMillisecondsSinceEpoch(0),
);
}
@override
Future<void> runJavaScript(String javaScript) async {
try {
await _webView.evaluateJavaScript(javaScript);
} on PlatformException catch (exception) {
// WebKit will throw an error when the type of the evaluated value is
// unsupported. This also goes for `null` and `undefined` on iOS 14+. For
// example, when running a void function. For ease of use, this specific
// error is ignored when no return value is expected.
final Object? details = exception.details;
if (details is! NSError ||
details.code != WKErrorCode.javaScriptResultTypeIsUnsupported) {
rethrow;
}
}
}
@override
Future<Object> runJavaScriptReturningResult(String javaScript) async {
final Object? result = await _webView.evaluateJavaScript(javaScript);
if (result == null) {
throw ArgumentError(
'Result of JavaScript execution returned a `null` value. '
'Use `runJavascript` when expecting a null return value.',
);
}
return result;
}
@override
Future<String?> getTitle() => _webView.getTitle();
@override
Future<void> scrollTo(int x, int y) {
return _webView.scrollView.setContentOffset(Point<double>(
x.toDouble(),
y.toDouble(),
));
}
@override
Future<void> scrollBy(int x, int y) {
return _webView.scrollView.scrollBy(Point<double>(
x.toDouble(),
y.toDouble(),
));
}
@override
Future<Offset> getScrollPosition() async {
final Point<double> offset = await _webView.scrollView.getContentOffset();
return Offset(offset.x, offset.y);
}
/// Whether horizontal swipe gestures trigger page navigation.
Future<void> setAllowsBackForwardNavigationGestures(bool enabled) {
return _webView.setAllowsBackForwardNavigationGestures(enabled);
}
@override
Future<void> setBackgroundColor(Color color) {
return Future.wait(<Future<void>>[
_webView.setOpaque(false),
_webView.setBackgroundColor(Colors.transparent),
// This method must be called last.
_webView.scrollView.setBackgroundColor(color),
]);
}
@override
Future<void> setJavaScriptMode(JavaScriptMode javaScriptMode) {
switch (javaScriptMode) {
case JavaScriptMode.disabled:
return _webView.configuration.preferences.setJavaScriptEnabled(false);
case JavaScriptMode.unrestricted:
return _webView.configuration.preferences.setJavaScriptEnabled(true);
}
}
@override
Future<void> setUserAgent(String? userAgent) {
return _webView.setCustomUserAgent(userAgent);
}
@override
Future<void> enableZoom(bool enabled) async {
if (_zoomEnabled == enabled) {
return;
}
_zoomEnabled = enabled;
if (enabled) {
await _resetUserScripts();
} else {
await _disableZoom();
}
}
@override
Future<void> setPlatformNavigationDelegate(
covariant WebKitNavigationDelegate handler,
) {
_currentNavigationDelegate = handler;
return Future.wait(<Future<void>>[
_webView.setUIDelegate(handler._uiDelegate),
_webView.setNavigationDelegate(handler._navigationDelegate)
]);
}
Future<void> _disableZoom() {
const WKUserScript userScript = WKUserScript(
"var meta = document.createElement('meta');\n"
"meta.name = 'viewport';\n"
"meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, "
"user-scalable=no';\n"
"var head = document.getElementsByTagName('head')[0];head.appendChild(meta);",
WKUserScriptInjectionTime.atDocumentEnd,
isMainFrameOnly: true,
);
return _webView.configuration.userContentController
.addUserScript(userScript);
}
// WKWebView does not support removing a single user script, so all user
// scripts and all message handlers are removed instead. And the JavaScript
// channels that shouldn't be removed are re-registered. Note that this
// workaround could interfere with exposing support for custom scripts from
// applications.
Future<void> _resetUserScripts({String? removedJavaScriptChannel}) async {
_webView.configuration.userContentController.removeAllUserScripts();
// TODO(bparrishMines): This can be replaced with
// `removeAllScriptMessageHandlers` once Dart supports runtime version
// checking. (e.g. The equivalent to @availability in Objective-C.)
_javaScriptChannelParams.keys.forEach(
_webView.configuration.userContentController.removeScriptMessageHandler,
);
_javaScriptChannelParams.remove(removedJavaScriptChannel);
await Future.wait(<Future<void>>[
for (JavaScriptChannelParams params in _javaScriptChannelParams.values)
addJavaScriptChannel(params),
// Zoom is disabled with a WKUserScript, so this adds it back if it was
// removed above.
if (!_zoomEnabled) _disableZoom(),
]);
}
}
/// An implementation of [JavaScriptChannelParams] with the WebKit api.
///
/// See [WebKitWebViewController.addJavaScriptChannel].
@immutable
class WebKitJavaScriptChannelParams extends JavaScriptChannelParams {
/// Constructs a [WebKitJavaScriptChannelParams].
WebKitJavaScriptChannelParams({
required super.name,
required super.onMessageReceived,
@visibleForTesting WebKitProxy webKitProxy = const WebKitProxy(),
}) : assert(name.isNotEmpty),
_messageHandler = webKitProxy.createScriptMessageHandler(
didReceiveScriptMessage: withWeakRefenceTo(
onMessageReceived,
(WeakReference<void Function(JavaScriptMessage)> weakReference) {
return (
WKUserContentController controller,
WKScriptMessage message,
) {
if (weakReference.target != null) {
weakReference.target!(
JavaScriptMessage(message: message.body!.toString()),
);
}
};
},
),
);
/// Constructs a [WebKitJavaScriptChannelParams] using a
/// [JavaScriptChannelParams].
WebKitJavaScriptChannelParams.fromJavaScriptChannelParams(
JavaScriptChannelParams params, {
@visibleForTesting WebKitProxy webKitProxy = const WebKitProxy(),
}) : this(
name: params.name,
onMessageReceived: params.onMessageReceived,
webKitProxy: webKitProxy,
);
final WKScriptMessageHandler _messageHandler;
}
/// Object specifying creation parameters for a [WebKitWebViewWidget].
@immutable
class WebKitWebViewWidgetCreationParams
extends PlatformWebViewWidgetCreationParams {
/// Constructs a [WebKitWebViewWidgetCreationParams].
WebKitWebViewWidgetCreationParams({
super.key,
required super.controller,
super.layoutDirection,
super.gestureRecognizers,
@visibleForTesting InstanceManager? instanceManager,
}) : _instanceManager = instanceManager ?? NSObject.globalInstanceManager;
/// Constructs a [WebKitWebViewWidgetCreationParams] using a
/// [PlatformWebViewWidgetCreationParams].
WebKitWebViewWidgetCreationParams.fromPlatformWebViewWidgetCreationParams(
PlatformWebViewWidgetCreationParams params, {
InstanceManager? instanceManager,
}) : this(
key: params.key,
controller: params.controller,
layoutDirection: params.layoutDirection,
gestureRecognizers: params.gestureRecognizers,
instanceManager: instanceManager,
);
// Maintains instances used to communicate with the native objects they
// represent.
final InstanceManager _instanceManager;
}
/// An implementation of [PlatformWebViewWidget] with the WebKit api.
class WebKitWebViewWidget extends PlatformWebViewWidget {
/// Constructs a [WebKitWebViewWidget].
WebKitWebViewWidget(PlatformWebViewWidgetCreationParams params)
: super.implementation(
params is WebKitWebViewWidgetCreationParams
? params
: WebKitWebViewWidgetCreationParams
.fromPlatformWebViewWidgetCreationParams(params),
);
WebKitWebViewWidgetCreationParams get _webKitParams =>
params as WebKitWebViewWidgetCreationParams;
@override
Widget build(BuildContext context) {
return UiKitView(
key: _webKitParams.key,
viewType: 'plugins.flutter.io/webview',
onPlatformViewCreated: (_) {},
layoutDirection: params.layoutDirection,
gestureRecognizers: params.gestureRecognizers,
creationParams: _webKitParams._instanceManager.getIdentifier(
(params.controller as WebKitWebViewController)._webView),
creationParamsCodec: const StandardMessageCodec(),
);
}
}
/// An implementation of [WebResourceError] with the WebKit API.
class WebKitWebResourceError extends WebResourceError {
WebKitWebResourceError._(this._nsError, {required bool isForMainFrame})
: super(
errorCode: _nsError.code,
description: _nsError.localizedDescription,
errorType: _toWebResourceErrorType(_nsError.code),
isForMainFrame: isForMainFrame,
);
static WebResourceErrorType? _toWebResourceErrorType(int code) {
switch (code) {
case WKErrorCode.unknown:
return WebResourceErrorType.unknown;
case WKErrorCode.webContentProcessTerminated:
return WebResourceErrorType.webContentProcessTerminated;
case WKErrorCode.webViewInvalidated:
return WebResourceErrorType.webViewInvalidated;
case WKErrorCode.javaScriptExceptionOccurred:
return WebResourceErrorType.javaScriptExceptionOccurred;
case WKErrorCode.javaScriptResultTypeIsUnsupported:
return WebResourceErrorType.javaScriptResultTypeIsUnsupported;
}
return null;
}
/// A string representing the domain of the error.
String? get domain => _nsError.domain;
final NSError _nsError;
}
/// Object specifying creation parameters for a [WebKitNavigationDelegate].
@immutable
class WebKitNavigationDelegateCreationParams
extends PlatformNavigationDelegateCreationParams {
/// Constructs a [WebKitNavigationDelegateCreationParams].
const WebKitNavigationDelegateCreationParams({
@visibleForTesting this.webKitProxy = const WebKitProxy(),
});
/// Constructs a [WebKitNavigationDelegateCreationParams] using a
/// [PlatformNavigationDelegateCreationParams].
const WebKitNavigationDelegateCreationParams.fromPlatformNavigationDelegateCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformNavigationDelegateCreationParams params, {
@visibleForTesting WebKitProxy webKitProxy = const WebKitProxy(),
}) : this(webKitProxy: webKitProxy);
/// Handles constructing objects and calling static methods for the WebKit
/// native library.
@visibleForTesting
final WebKitProxy webKitProxy;
}
/// An implementation of [PlatformNavigationDelegate] with the WebKit API.
class WebKitNavigationDelegate extends PlatformNavigationDelegate {
/// Constructs a [WebKitNavigationDelegate].
WebKitNavigationDelegate(PlatformNavigationDelegateCreationParams params)
: super.implementation(params is WebKitNavigationDelegateCreationParams
? params
: WebKitNavigationDelegateCreationParams
.fromPlatformNavigationDelegateCreationParams(params)) {
final WeakReference<WebKitNavigationDelegate> weakThis =
WeakReference<WebKitNavigationDelegate>(this);
_navigationDelegate =
(this.params as WebKitNavigationDelegateCreationParams)
.webKitProxy
.createNavigationDelegate(
didFinishNavigation: (WKWebView webView, String? url) {
if (weakThis.target?._onPageFinished != null) {
weakThis.target!._onPageFinished!(url ?? '');
}
},
didStartProvisionalNavigation: (WKWebView webView, String? url) {
if (weakThis.target?._onPageStarted != null) {
weakThis.target!._onPageStarted!(url ?? '');
}
},
decidePolicyForNavigationAction: (
WKWebView webView,
WKNavigationAction action,
) async {
if (weakThis.target?._onNavigationRequest != null) {
final NavigationDecision decision =
await weakThis.target!._onNavigationRequest!(NavigationRequest(
url: action.request.url,
isMainFrame: action.targetFrame.isMainFrame,
));
switch (decision) {
case NavigationDecision.prevent:
return WKNavigationActionPolicy.cancel;
case NavigationDecision.navigate:
return WKNavigationActionPolicy.allow;
}
}
return WKNavigationActionPolicy.allow;
},
didFailNavigation: (WKWebView webView, NSError error) {
if (weakThis.target?._onWebResourceError != null) {
weakThis.target!._onWebResourceError!(
WebKitWebResourceError._(error, isForMainFrame: true),
);
}
},
didFailProvisionalNavigation: (WKWebView webView, NSError error) {
if (weakThis.target?._onWebResourceError != null) {
weakThis.target!._onWebResourceError!(
WebKitWebResourceError._(error, isForMainFrame: true),
);
}
},
webViewWebContentProcessDidTerminate: (WKWebView webView) {
if (weakThis.target?._onWebResourceError != null) {
weakThis.target!._onWebResourceError!(
WebKitWebResourceError._(
const NSError(
code: WKErrorCode.webContentProcessTerminated,
// Value from https://developer.apple.com/documentation/webkit/wkerrordomain?language=objc.
domain: 'WKErrorDomain',
localizedDescription: '',
),
isForMainFrame: true,
),
);
}
},
);
_uiDelegate = (this.params as WebKitNavigationDelegateCreationParams)
.webKitProxy
.createUIDelegate(
onCreateWebView: (
WKWebView webView,
WKWebViewConfiguration configuration,
WKNavigationAction navigationAction,
) {
if (!navigationAction.targetFrame.isMainFrame) {
webView.loadRequest(navigationAction.request);
}
},
);
}
// Used to set `WKWebView.setNavigationDelegate` in `WebKitWebViewController`.
late final WKNavigationDelegate _navigationDelegate;
// Used to set `WKWebView.setUIDelegate` in `WebKitWebViewController`.
late final WKUIDelegate _uiDelegate;
PageEventCallback? _onPageFinished;
PageEventCallback? _onPageStarted;
ProgressCallback? _onProgress;
WebResourceErrorCallback? _onWebResourceError;
NavigationRequestCallback? _onNavigationRequest;
@override
Future<void> setOnPageFinished(PageEventCallback onPageFinished) async {
_onPageFinished = onPageFinished;
}
@override
Future<void> setOnPageStarted(PageEventCallback onPageStarted) async {
_onPageStarted = onPageStarted;
}
@override
Future<void> setOnProgress(ProgressCallback onProgress) async {
_onProgress = onProgress;
}
@override
Future<void> setOnWebResourceError(
WebResourceErrorCallback onWebResourceError,
) async {
_onWebResourceError = onWebResourceError;
}
@override
Future<void> setOnNavigationRequest(
NavigationRequestCallback onNavigationRequest,
) async {
_onNavigationRequest = onNavigationRequest;
}
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/webkit_webview_controller.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/webkit_webview_controller.dart",
"repo_id": "plugins",
"token_count": 8976
} | 1,276 |
// Mocks generated by Mockito 5.3.2 from annotations
// in webview_flutter_wkwebview/test/src/ui_kit/ui_kit_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i4;
import 'package:mockito/mockito.dart' as _i1;
import 'package:webview_flutter_wkwebview/src/common/web_kit.g.dart' as _i3;
import '../common/test_web_kit.g.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
/// A class which mocks [TestWKWebViewConfigurationHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWKWebViewConfigurationHostApi extends _i1.Mock
implements _i2.TestWKWebViewConfigurationHostApi {
MockTestWKWebViewConfigurationHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(int? identifier) => super.noSuchMethod(
Invocation.method(
#create,
[identifier],
),
returnValueForMissingStub: null,
);
@override
void createFromWebView(
int? identifier,
int? webViewIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#createFromWebView,
[
identifier,
webViewIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
void setAllowsInlineMediaPlayback(
int? identifier,
bool? allow,
) =>
super.noSuchMethod(
Invocation.method(
#setAllowsInlineMediaPlayback,
[
identifier,
allow,
],
),
returnValueForMissingStub: null,
);
@override
void setMediaTypesRequiringUserActionForPlayback(
int? identifier,
List<_i3.WKAudiovisualMediaTypeEnumData?>? types,
) =>
super.noSuchMethod(
Invocation.method(
#setMediaTypesRequiringUserActionForPlayback,
[
identifier,
types,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestWKWebViewHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWKWebViewHostApi extends _i1.Mock
implements _i2.TestWKWebViewHostApi {
MockTestWKWebViewHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? identifier,
int? configurationIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
identifier,
configurationIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
void setUIDelegate(
int? identifier,
int? uiDelegateIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#setUIDelegate,
[
identifier,
uiDelegateIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
void setNavigationDelegate(
int? identifier,
int? navigationDelegateIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#setNavigationDelegate,
[
identifier,
navigationDelegateIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
String? getUrl(int? identifier) => (super.noSuchMethod(Invocation.method(
#getUrl,
[identifier],
)) as String?);
@override
double getEstimatedProgress(int? identifier) => (super.noSuchMethod(
Invocation.method(
#getEstimatedProgress,
[identifier],
),
returnValue: 0.0,
) as double);
@override
void loadRequest(
int? identifier,
_i3.NSUrlRequestData? request,
) =>
super.noSuchMethod(
Invocation.method(
#loadRequest,
[
identifier,
request,
],
),
returnValueForMissingStub: null,
);
@override
void loadHtmlString(
int? identifier,
String? string,
String? baseUrl,
) =>
super.noSuchMethod(
Invocation.method(
#loadHtmlString,
[
identifier,
string,
baseUrl,
],
),
returnValueForMissingStub: null,
);
@override
void loadFileUrl(
int? identifier,
String? url,
String? readAccessUrl,
) =>
super.noSuchMethod(
Invocation.method(
#loadFileUrl,
[
identifier,
url,
readAccessUrl,
],
),
returnValueForMissingStub: null,
);
@override
void loadFlutterAsset(
int? identifier,
String? key,
) =>
super.noSuchMethod(
Invocation.method(
#loadFlutterAsset,
[
identifier,
key,
],
),
returnValueForMissingStub: null,
);
@override
bool canGoBack(int? identifier) => (super.noSuchMethod(
Invocation.method(
#canGoBack,
[identifier],
),
returnValue: false,
) as bool);
@override
bool canGoForward(int? identifier) => (super.noSuchMethod(
Invocation.method(
#canGoForward,
[identifier],
),
returnValue: false,
) as bool);
@override
void goBack(int? identifier) => super.noSuchMethod(
Invocation.method(
#goBack,
[identifier],
),
returnValueForMissingStub: null,
);
@override
void goForward(int? identifier) => super.noSuchMethod(
Invocation.method(
#goForward,
[identifier],
),
returnValueForMissingStub: null,
);
@override
void reload(int? identifier) => super.noSuchMethod(
Invocation.method(
#reload,
[identifier],
),
returnValueForMissingStub: null,
);
@override
String? getTitle(int? identifier) => (super.noSuchMethod(Invocation.method(
#getTitle,
[identifier],
)) as String?);
@override
void setAllowsBackForwardNavigationGestures(
int? identifier,
bool? allow,
) =>
super.noSuchMethod(
Invocation.method(
#setAllowsBackForwardNavigationGestures,
[
identifier,
allow,
],
),
returnValueForMissingStub: null,
);
@override
void setCustomUserAgent(
int? identifier,
String? userAgent,
) =>
super.noSuchMethod(
Invocation.method(
#setCustomUserAgent,
[
identifier,
userAgent,
],
),
returnValueForMissingStub: null,
);
@override
_i4.Future<Object?> evaluateJavaScript(
int? identifier,
String? javaScriptString,
) =>
(super.noSuchMethod(
Invocation.method(
#evaluateJavaScript,
[
identifier,
javaScriptString,
],
),
returnValue: _i4.Future<Object?>.value(),
) as _i4.Future<Object?>);
}
/// A class which mocks [TestUIScrollViewHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestUIScrollViewHostApi extends _i1.Mock
implements _i2.TestUIScrollViewHostApi {
MockTestUIScrollViewHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void createFromWebView(
int? identifier,
int? webViewIdentifier,
) =>
super.noSuchMethod(
Invocation.method(
#createFromWebView,
[
identifier,
webViewIdentifier,
],
),
returnValueForMissingStub: null,
);
@override
List<double?> getContentOffset(int? identifier) => (super.noSuchMethod(
Invocation.method(
#getContentOffset,
[identifier],
),
returnValue: <double?>[],
) as List<double?>);
@override
void scrollBy(
int? identifier,
double? x,
double? y,
) =>
super.noSuchMethod(
Invocation.method(
#scrollBy,
[
identifier,
x,
y,
],
),
returnValueForMissingStub: null,
);
@override
void setContentOffset(
int? identifier,
double? x,
double? y,
) =>
super.noSuchMethod(
Invocation.method(
#setContentOffset,
[
identifier,
x,
y,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestUIViewHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestUIViewHostApi extends _i1.Mock implements _i2.TestUIViewHostApi {
MockTestUIViewHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void setBackgroundColor(
int? identifier,
int? value,
) =>
super.noSuchMethod(
Invocation.method(
#setBackgroundColor,
[
identifier,
value,
],
),
returnValueForMissingStub: null,
);
@override
void setOpaque(
int? identifier,
bool? opaque,
) =>
super.noSuchMethod(
Invocation.method(
#setOpaque,
[
identifier,
opaque,
],
),
returnValueForMissingStub: null,
);
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/test/src/ui_kit/ui_kit_test.mocks.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/test/src/ui_kit/ui_kit_test.mocks.dart",
"repo_id": "plugins",
"token_count": 4671
} | 1,277 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:colorize/colorize.dart';
import 'package:file/file.dart';
import 'package:git/git.dart';
import 'package:path/path.dart' as p;
import 'package:platform/platform.dart';
import 'package:pub_semver/pub_semver.dart';
import 'core.dart';
import 'package_command.dart';
import 'process_runner.dart';
import 'repository_package.dart';
/// Enumeration options for package looping commands.
enum PackageLoopingType {
/// Only enumerates the top level packages, without including any of their
/// subpackages.
topLevelOnly,
/// Enumerates the top level packages and any example packages they contain.
includeExamples,
/// Enumerates all packages recursively, including both example and
/// non-example subpackages.
includeAllSubpackages,
}
/// Possible outcomes of a command run for a package.
enum RunState {
/// The command succeeded for the package.
succeeded,
/// The command was skipped for the package.
skipped,
/// The command was skipped for the package because it was explicitly excluded
/// in the command arguments.
excluded,
/// The command failed for the package.
failed,
}
/// The result of a [runForPackage] call.
class PackageResult {
/// A successful result.
PackageResult.success() : this._(RunState.succeeded);
/// A run that was skipped as explained in [reason].
PackageResult.skip(String reason)
: this._(RunState.skipped, <String>[reason]);
/// A run that was excluded by the command invocation.
PackageResult.exclude() : this._(RunState.excluded);
/// A run that failed.
///
/// If [errors] are provided, they will be listed in the summary, otherwise
/// the summary will simply show that the package failed.
PackageResult.fail([List<String> errors = const <String>[]])
: this._(RunState.failed, errors);
const PackageResult._(this.state, [this.details = const <String>[]]);
/// The state the package run completed with.
final RunState state;
/// Information about the result:
/// - For `succeeded`, this is empty.
/// - For `skipped`, it contains a single entry describing why the run was
/// skipped.
/// - For `failed`, it contains zero or more specific error details to be
/// shown in the summary.
final List<String> details;
}
/// An abstract base class for a command that iterates over a set of packages
/// controlled by a standard set of flags, running some actions on each package,
/// and collecting and reporting the success/failure of those actions.
abstract class PackageLoopingCommand extends PackageCommand {
/// Creates a command to operate on [packagesDir] with the given environment.
PackageLoopingCommand(
Directory packagesDir, {
ProcessRunner processRunner = const ProcessRunner(),
Platform platform = const LocalPlatform(),
GitDir? gitDir,
}) : super(packagesDir,
processRunner: processRunner, platform: platform, gitDir: gitDir) {
argParser.addOption(
_skipByFlutterVersionArg,
help: 'Skip any packages that require a Flutter version newer than '
'the provided version.',
);
argParser.addOption(
_skipByDartVersionArg,
help: 'Skip any packages that require a Dart version newer than '
'the provided version.',
);
}
static const String _skipByFlutterVersionArg =
'skip-if-not-supporting-flutter-version';
static const String _skipByDartVersionArg =
'skip-if-not-supporting-dart-version';
/// Packages that had at least one [logWarning] call.
final Set<PackageEnumerationEntry> _packagesWithWarnings =
<PackageEnumerationEntry>{};
/// Number of warnings that happened outside of a [runForPackage] call.
int _otherWarningCount = 0;
/// The package currently being run by [runForPackage].
PackageEnumerationEntry? _currentPackageEntry;
/// Called during [run] before any calls to [runForPackage]. This provides an
/// opportunity to fail early if the command can't be run (e.g., because the
/// arguments are invalid), and to set up any run-level state.
Future<void> initializeRun() async {}
/// Returns the packages to process. By default, this returns the packages
/// defined by the standard tooling flags and the [inculdeSubpackages] option,
/// but can be overridden for custom package enumeration.
///
/// Note: Consistent behavior across commands whenever possibel is a goal for
/// this tool, so this should be overridden only in rare cases.
Stream<PackageEnumerationEntry> getPackagesToProcess() async* {
switch (packageLoopingType) {
case PackageLoopingType.topLevelOnly:
yield* getTargetPackages(filterExcluded: false);
break;
case PackageLoopingType.includeExamples:
await for (final PackageEnumerationEntry packageEntry
in getTargetPackages(filterExcluded: false)) {
yield packageEntry;
yield* Stream<PackageEnumerationEntry>.fromIterable(packageEntry
.package
.getExamples()
.map((RepositoryPackage package) => PackageEnumerationEntry(
package,
excluded: packageEntry.excluded)));
}
break;
case PackageLoopingType.includeAllSubpackages:
yield* getTargetPackagesAndSubpackages(filterExcluded: false);
break;
}
}
/// Runs the command for [package], returning a list of errors.
///
/// Errors may either be an empty string if there is no context that should
/// be included in the final error summary (e.g., a command that only has a
/// single failure mode), or strings that should be listed for that package
/// in the final summary. An empty list indicates success.
Future<PackageResult> runForPackage(RepositoryPackage package);
/// Called during [run] after all calls to [runForPackage]. This provides an
/// opportunity to do any cleanup of run-level state.
Future<void> completeRun() async {}
/// If [captureOutput], this is called just before exiting with all captured
/// [output].
Future<void> handleCapturedOutput(List<String> output) async {}
/// Whether or not the output (if any) of [runForPackage] is long, or short.
///
/// This changes the logging that happens at the start of each package's
/// run; long output gets a banner-style message to make it easier to find,
/// while short output gets a single-line entry.
///
/// When this is false, runForPackage output should be indented if possible,
/// to make the output structure easier to follow.
bool get hasLongOutput => true;
/// Whether to loop over top-level packages only, or some or all of their
/// sub-packages as well.
PackageLoopingType get packageLoopingType => PackageLoopingType.topLevelOnly;
/// The text to output at the start when reporting one or more failures.
/// This will be followed by a list of packages that reported errors, with
/// the per-package details if any.
///
/// This only needs to be overridden if the summary should provide extra
/// context.
String get failureListHeader => 'The following packages had errors:';
/// The text to output at the end when reporting one or more failures. This
/// will be printed immediately after the a list of packages that reported
/// errors.
///
/// This only needs to be overridden if the summary should provide extra
/// context.
String get failureListFooter => 'See above for full details.';
/// The summary string used for a successful run in the final overview output.
String get successSummaryMessage => 'ran';
/// If true, all printing (including the summary) will be redirected to a
/// buffer, and provided in a call to [handleCapturedOutput] at the end of
/// the run.
///
/// Capturing output will disable any colorizing of output from this base
/// class.
bool get captureOutput => false;
// ----------------------------------------
/// Logs that a warning occurred, and prints `warningMessage` in yellow.
///
/// Warnings are not surfaced in CI summaries, so this is only useful for
/// highlighting something when someone is already looking though the log
/// messages. DO NOT RELY on someone noticing a warning; instead, use it for
/// things that might be useful to someone debugging an unexpected result.
void logWarning(String warningMessage) {
_printColorized(warningMessage, Styles.YELLOW);
if (_currentPackageEntry != null) {
_packagesWithWarnings.add(_currentPackageEntry!);
} else {
++_otherWarningCount;
}
}
/// Returns the relative path from [from] to [entity] in Posix style.
///
/// This should be used when, for example, printing package-relative paths in
/// status or error messages.
String getRelativePosixPath(
FileSystemEntity entity, {
required Directory from,
}) =>
p.posix.joinAll(path.split(path.relative(entity.path, from: from.path)));
/// The suggested indentation for printed output.
String get indentation => hasLongOutput ? '' : ' ';
// ----------------------------------------
@override
Future<void> run() async {
bool succeeded;
if (captureOutput) {
final List<String> output = <String>[];
final ZoneSpecification logSwitchSpecification = ZoneSpecification(
print: (Zone self, ZoneDelegate parent, Zone zone, String message) {
output.add(message);
});
succeeded = await runZoned<Future<bool>>(_runInternal,
zoneSpecification: logSwitchSpecification);
await handleCapturedOutput(output);
} else {
succeeded = await _runInternal();
}
if (!succeeded) {
throw ToolExit(exitCommandFoundErrors);
}
}
Future<bool> _runInternal() async {
_packagesWithWarnings.clear();
_otherWarningCount = 0;
_currentPackageEntry = null;
final String minFlutterVersionArg = getStringArg(_skipByFlutterVersionArg);
final Version? minFlutterVersion = minFlutterVersionArg.isEmpty
? null
: Version.parse(minFlutterVersionArg);
final String minDartVersionArg = getStringArg(_skipByDartVersionArg);
final Version? minDartVersion =
minDartVersionArg.isEmpty ? null : Version.parse(minDartVersionArg);
final DateTime runStart = DateTime.now();
await initializeRun();
final List<PackageEnumerationEntry> targetPackages =
await getPackagesToProcess().toList();
final Map<PackageEnumerationEntry, PackageResult> results =
<PackageEnumerationEntry, PackageResult>{};
for (final PackageEnumerationEntry entry in targetPackages) {
final DateTime packageStart = DateTime.now();
_currentPackageEntry = entry;
_printPackageHeading(entry, startTime: runStart);
// Command implementations should never see excluded packages; they are
// included at this level only for logging.
if (entry.excluded) {
results[entry] = PackageResult.exclude();
continue;
}
PackageResult result;
try {
result = await _runForPackageIfSupported(entry.package,
minFlutterVersion: minFlutterVersion,
minDartVersion: minDartVersion);
} catch (e, stack) {
printError(e.toString());
printError(stack.toString());
result = PackageResult.fail(<String>['Unhandled exception']);
}
if (result.state == RunState.skipped) {
_printColorized('${indentation}SKIPPING: ${result.details.first}',
Styles.DARK_GRAY);
}
results[entry] = result;
// Only log an elapsed time for long output; for short output, comparing
// the relative timestamps of successive entries should be trivial.
if (shouldLogTiming && hasLongOutput) {
final Duration elapsedTime = DateTime.now().difference(packageStart);
_printColorized(
'\n[${entry.package.displayName} completed in '
'${elapsedTime.inMinutes}m ${elapsedTime.inSeconds % 60}s]',
Styles.DARK_GRAY);
}
}
_currentPackageEntry = null;
completeRun();
print('\n');
// If there were any errors reported, summarize them and exit.
if (results.values
.any((PackageResult result) => result.state == RunState.failed)) {
_printFailureSummary(targetPackages, results);
return false;
}
// Otherwise, print a summary of what ran for ease of auditing that all the
// expected tests ran.
_printRunSummary(targetPackages, results);
print('\n');
_printSuccess('No issues found!');
return true;
}
/// Returns the result of running [runForPackage] if the package is supported
/// by any run constraints, or a skip result if it is not.
Future<PackageResult> _runForPackageIfSupported(
RepositoryPackage package, {
Version? minFlutterVersion,
Version? minDartVersion,
}) async {
if (minFlutterVersion != null) {
final Pubspec pubspec = package.parsePubspec();
final VersionConstraint? flutterConstraint =
pubspec.environment?['flutter'];
if (flutterConstraint != null &&
!flutterConstraint.allows(minFlutterVersion)) {
return PackageResult.skip(
'Does not support Flutter $minFlutterVersion');
}
}
if (minDartVersion != null) {
final Pubspec pubspec = package.parsePubspec();
final VersionConstraint? dartConstraint = pubspec.environment?['sdk'];
if (dartConstraint != null && !dartConstraint.allows(minDartVersion)) {
return PackageResult.skip('Does not support Dart $minDartVersion');
}
}
return runForPackage(package);
}
void _printSuccess(String message) {
captureOutput ? print(message) : printSuccess(message);
}
void _printError(String message) {
captureOutput ? print(message) : printError(message);
}
/// Prints the status message indicating that the command is being run for
/// [package].
///
/// Something is always printed to make it easier to distinguish between
/// a command running for a package and producing no output, and a command
/// not having been run for a package.
void _printPackageHeading(PackageEnumerationEntry entry,
{required DateTime startTime}) {
final String packageDisplayName = entry.package.displayName;
String heading = entry.excluded
? 'Not running for $packageDisplayName; excluded'
: 'Running for $packageDisplayName';
if (shouldLogTiming) {
final Duration relativeTime = DateTime.now().difference(startTime);
final String timeString = _formatDurationAsRelativeTime(relativeTime);
heading =
hasLongOutput ? '$heading [@$timeString]' : '[$timeString] $heading';
}
if (hasLongOutput) {
heading = '''
============================================================
|| $heading
============================================================
''';
} else if (!entry.excluded) {
heading = '$heading...';
}
_printColorized(heading, entry.excluded ? Styles.DARK_GRAY : Styles.CYAN);
}
/// Prints a summary of packges run, packages skipped, and warnings.
void _printRunSummary(List<PackageEnumerationEntry> packages,
Map<PackageEnumerationEntry, PackageResult> results) {
final Set<PackageEnumerationEntry> skippedPackages = results.entries
.where((MapEntry<PackageEnumerationEntry, PackageResult> entry) =>
entry.value.state == RunState.skipped)
.map((MapEntry<PackageEnumerationEntry, PackageResult> entry) =>
entry.key)
.toSet();
final int skipCount = skippedPackages.length +
packages
.where((PackageEnumerationEntry package) => package.excluded)
.length;
// Split the warnings into those from packages that ran, and those that
// were skipped.
final Set<PackageEnumerationEntry> skippedPackagesWithWarnings =
_packagesWithWarnings.intersection(skippedPackages);
final int skippedWarningCount = skippedPackagesWithWarnings.length;
final int runWarningCount =
_packagesWithWarnings.length - skippedWarningCount;
final String runWarningSummary =
runWarningCount > 0 ? ' ($runWarningCount with warnings)' : '';
final String skippedWarningSummary =
runWarningCount > 0 ? ' ($skippedWarningCount with warnings)' : '';
print('------------------------------------------------------------');
if (hasLongOutput) {
_printPerPackageRunOverview(packages, skipped: skippedPackages);
}
print(
'Ran for ${packages.length - skipCount} package(s)$runWarningSummary');
if (skipCount > 0) {
print('Skipped $skipCount package(s)$skippedWarningSummary');
}
if (_otherWarningCount > 0) {
print('$_otherWarningCount warnings not associated with a package');
}
}
/// Prints a one-line-per-package overview of the run results for each
/// package.
void _printPerPackageRunOverview(
List<PackageEnumerationEntry> packageEnumeration,
{required Set<PackageEnumerationEntry> skipped}) {
print('Run overview:');
for (final PackageEnumerationEntry entry in packageEnumeration) {
final bool hadWarning = _packagesWithWarnings.contains(entry);
Styles style;
String summary;
if (entry.excluded) {
summary = 'excluded';
style = Styles.DARK_GRAY;
} else if (skipped.contains(entry)) {
summary = 'skipped';
style = hadWarning ? Styles.LIGHT_YELLOW : Styles.DARK_GRAY;
} else {
summary = successSummaryMessage;
style = hadWarning ? Styles.YELLOW : Styles.GREEN;
}
if (hadWarning) {
summary += ' (with warning)';
}
if (!captureOutput) {
summary = (Colorize(summary)..apply(style)).toString();
}
print(' ${entry.package.displayName} - $summary');
}
print('');
}
/// Prints a summary of all of the failures from [results].
void _printFailureSummary(List<PackageEnumerationEntry> packageEnumeration,
Map<PackageEnumerationEntry, PackageResult> results) {
const String indentation = ' ';
_printError(failureListHeader);
for (final PackageEnumerationEntry entry in packageEnumeration) {
final PackageResult result = results[entry]!;
if (result.state == RunState.failed) {
final String errorIndentation = indentation * 2;
String errorDetails = '';
if (result.details.isNotEmpty) {
errorDetails =
':\n$errorIndentation${result.details.join('\n$errorIndentation')}';
}
_printError('$indentation${entry.package.displayName}$errorDetails');
}
}
_printError(failureListFooter);
}
/// Prints [message] in [color] unless [captureOutput] is set, in which case
/// it is printed without color.
void _printColorized(String message, Styles color) {
if (captureOutput) {
print(message);
} else {
print(Colorize(message)..apply(color));
}
}
/// Returns a duration [d] formatted as minutes:seconds. Does not use hours,
/// since time logging is primarily intended for CI, where durations should
/// always be less than an hour.
String _formatDurationAsRelativeTime(Duration d) {
return '${d.inMinutes}:${(d.inSeconds % 60).toString().padLeft(2, '0')}';
}
}
| plugins/script/tool/lib/src/common/package_looping_command.dart/0 | {
"file_path": "plugins/script/tool/lib/src/common/package_looping_command.dart",
"repo_id": "plugins",
"token_count": 6297
} | 1,278 |
# android_view
An example of an Android app that integrates a Flutter add-to-app module at a
view level.
## tl;dr
If you're just looking to get up and running quickly, these bash commands will
fetch packages and set up dependencies (note that the above commands assume
you're building for both iOS and Android, with both toolchains installed):
```bash
#!/bin/bash
set -e
cd flutter_module_using_plugin/
flutter pub get
# For Android builds:
open -a "Android Studio" ../android_view # macOS only
# Or open the ../android_fullscreen folder in Android Studio for other platforms.
```
## Getting Started
For more information about Flutter, check out
[flutter.dev](https://flutter.dev).
For instructions on how to integrate Flutter modules into your existing
applications, see Flutter's
[add-to-app documentation](https://flutter.dev/docs/development/add-to-app).
| samples/add_to_app/android_view/README.md/0 | {
"file_path": "samples/add_to_app/android_view/README.md",
"repo_id": "samples",
"token_count": 247
} | 1,279 |
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="160dp">
<com.google.android.material.card.MaterialCardView
android:id="@+id/androidCard"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginHorizontal="36dp"
android:layout_marginVertical="24dp"
app:cardBackgroundColor="#F1F1F1"
app:cardCornerRadius="16dp"
app:cardElevation="16dp">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/cellNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAppearance="?attr/textAppearanceHeadline3"/>
</FrameLayout>
</com.google.android.material.card.MaterialCardView>
</FrameLayout>
| samples/add_to_app/android_view/android_view/app/src/main/res/layout/android_card.xml/0 | {
"file_path": "samples/add_to_app/android_view/android_view/app/src/main/res/layout/android_card.xml",
"repo_id": "samples",
"token_count": 507
} | 1,280 |
<resources>
<string name="app_name">Flutter View Integration</string>
</resources> | samples/add_to_app/android_view/android_view/app/src/main/res/values/strings.xml/0 | {
"file_path": "samples/add_to_app/android_view/android_view/app/src/main/res/values/strings.xml",
"repo_id": "samples",
"token_count": 26
} | 1,281 |
# books
Mimics a real world use-case of embedding Flutter into an existing Android app
and demonstrates using [Pigeon](https://pub.dev/packages/pigeon) to communicate
between Flutter and the host application.
## Description
These apps integrate the `flutter_books` module using the simpler build-together
project setup. They simulate a mock scenario where an existing book catalog
list app already exists. Flutter is used to implement an additional book details
page.
* Similar to [`fullscreen`](../fullscreen).
* An existing books catalog app is already implemented in Kotlin and Swift.
* The platform-side app has existing middleware constraints that should also
be the middleware foundation for the additional Flutter screen.
* On Android, the Kotlin app already uses GSON and OkHttp for networking and
references the Google Books API as a data source. These same libraries also
underpin the data fetched and shown in the Flutter screen.
* On iOS, the Swift app does a similar fetch and parse of the Google Books API
using iOS's built-in libraries.
* The platform application interfaces with the Flutter book details page using
idiomatic platform API conventions rather than Flutter conventions.
* On Android, the Flutter activity receives the book to show via activity
intent and returns the edited book by setting the result intent on the
activity. No Flutter concepts are leaked into the consumer activity.
* On iOS, Storyboards are used to design the presentation of the books, just
as one might do in a full UIKit app.
* The [pigeon](https://pub.dev/packages/pigeon) plugin is used to generate
interop APIs and data classes. The same `Book` model class is used within the
Kotlin/Swift program, the Dart program and in the interop between Kotlin/Swift
and Dart. No manual platform channel plumbing needed for interop.
* The `api.dart/java/mm` files generated from the
`flutter_module_books/pigeon/schema.dart` file are checked into source
control. Therefore `pigeon` is only a dev dependency with no runtime
requirements.
* If the `schema.dart` is modified, the generated classes can be updated with
```bash
flutter pub run pigeon --input pigeon/schema.dart \
--dart_out lib/api.dart \
--objc_header_out ../ios_books/IosBooks/api.h \
--objc_source_out ../ios_books/IosBooks/api.m \
--objc_prefix BK \
--java_out ../android_books/app/src/main/java/dev/flutter/example/books/Api.java \
--java_package "dev.flutter.example.books"
```
in the `flutter_module_books` directory.
Once you've understood the basics of add-to-app with `android_fullscreen` and
`ios_fullscreen`, this is a good sample to demonstrate how to integrate Flutter
in a slightly more realistic setting with existing business logic.
## tl;dr
If you're just looking to get up and running quickly, these bash commands will
fetch packages and set up dependencies (note that the above commands assume
you're building for both iOS and Android, with both toolchains installed):
```bash
#!/bin/bash
set -e
cd flutter_module_books/
flutter pub get
# For Android builds:
open -a "Android Studio" ../android_books # macOS only
# Or open the ../android_books folder in Android Studio for other platforms.
# For iOS builds:
cd ../ios_books
pod install
open IosBooks.xcworkspace
```
## Requirements
* Flutter
* Android Studio
* Cocoapods (iOS)
## Questions/issues
See [add_to_app/README.md](../README.md) for further help.
| samples/add_to_app/books/README.md/0 | {
"file_path": "samples/add_to_app/books/README.md",
"repo_id": "samples",
"token_count": 1028
} | 1,282 |
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon> | samples/add_to_app/books/android_books/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml/0 | {
"file_path": "samples/add_to_app/books/android_books/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml",
"repo_id": "samples",
"token_count": 98
} | 1,283 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import Flutter
import UIKit
class ViewController: UITableViewController, BKHostBookApi {
private var books: [BKBook] = []
private var api: BKFlutterBookApi!
private var editingIndex: Int = -1
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Books"
let appDelegate = UIApplication.shared.delegate as! AppDelegate
BKHostBookApiSetup(appDelegate.engine.binaryMessenger, self)
api = BKFlutterBookApi.init(binaryMessenger: appDelegate.engine.binaryMessenger)
if let url = URL(
string: "https://www.googleapis.com/books/v1/volumes?q=greenwood+tulsa&maxResults=15")
{
self.loadBooks(url: url) { (newBooks) in
if let newBooks = newBooks {
self.books = newBooks
self.tableView.reloadData()
}
}
}
}
/**
Loads a JSON file from the supplied URL, parses it and calls the callback with the array of
parsed books on the main thread.
*/
func loadBooks(url: URL, completion: @escaping ([BKBook]?) -> Void) {
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
do {
if let json = try JSONSerialization.jsonObject(with: data, options: [])
as? [String: Any]
{
var newBooks: [BKBook] = []
for item in json["items"] as! [[String: Any]] {
let volumeInfo = item["volumeInfo"] as! [String: Any]
let title = volumeInfo["title"] as! String
let subtitle = volumeInfo["subtitle"] as! String?
let authors = (volumeInfo["authors"] as! [String]).joined(separator: " & ")
let pageCount = volumeInfo["pageCount"] as! Int32
let publishedDate = volumeInfo["publishedDate"] as! String
let summary = volumeInfo["description"] as! String?
let imageLinks = volumeInfo["imageLinks"] as! [String: Any]
let thumbnail: BKThumbnail = BKThumbnail.init()
thumbnail.url = imageLinks["thumbnail"] as! String?
let book: BKBook = BKBook.init()
book.author = authors
book.title = title
book.subtitle = subtitle
book.title = title
book.pageCount = NSNumber.init(value: pageCount)
book.publishDate = publishedDate
book.summary = summary
book.thumbnail = thumbnail
newBooks.append(book)
}
DispatchQueue.main.async {
completion(newBooks)
}
}
} catch let error {
print("json decode error: \(error)")
completion(nil)
}
}
}.resume()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.books.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
-> UITableViewCell
{
let cell: BookCell = self.tableView.dequeueReusableCell(withIdentifier: "BookCell") as! BookCell
let bookInfo = books[indexPath.row]
cell.title.text = bookInfo.title
cell.subtitle.text = bookInfo.subtitle
if let author = bookInfo.author {
cell.byLine.text = "by: \(author)"
}
weak var weakSelf = self
let editAction = UIAction(title: "Edit") { (action) in
if let weakSelf = weakSelf {
weakSelf.editItem(index: indexPath.row)
}
}
cell.editButton.removeTarget(nil, action: nil, for: .allEvents)
cell.editButton.addAction(editAction, for: UIControl.Event.touchUpInside)
return cell
}
/**
Presents the FlutterViewController that edits the book at the supplied index.
*/
func editItem(index: Int) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let flutterViewController = FlutterViewController.init(
engine: appDelegate.engine, nibName: nil, bundle: nil)
self.editingIndex = index
api.displayBookDetailsBook(self.books[index]) { (error) in
if let error = error {
print(error)
}
}
self.present(flutterViewController, animated: true, completion: nil)
}
/**
Called by Pigeon when the FlutterViewController is dismissed without accepting any edits.
*/
func cancelWithError(_ error: AutoreleasingUnsafeMutablePointer<FlutterError?>) {
self.editingIndex = -1
self.dismiss(animated: true, completion: nil)
}
/**
Called by Pigeon when edits to the book are accepted in the FlutterViewController.
*/
func finishEditingBook(_ input: BKBook, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) {
self.books[editingIndex] = input
self.tableView.reloadData()
self.editingIndex = -1
self.dismiss(animated: true, completion: nil)
}
}
| samples/add_to_app/books/ios_books/IosBooks/ViewController.swift/0 | {
"file_path": "samples/add_to_app/books/ios_books/IosBooks/ViewController.swift",
"repo_id": "samples",
"token_count": 1981
} | 1,284 |
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/launch_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Launch Flutter Activity"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
<TextView
android:id="@+id/counter_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:text="Current counter: 0"
app:layout_constraintBottom_toTopOf="@+id/launch_button"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:ignore="HardcodedText" />
</androidx.constraintlayout.widget.ConstraintLayout> | samples/add_to_app/fullscreen/android_fullscreen/app/src/main/res/layout/activity_main.xml/0 | {
"file_path": "samples/add_to_app/fullscreen/android_fullscreen/app/src/main/res/layout/activity_main.xml",
"repo_id": "samples",
"token_count": 536
} | 1,285 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.