text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// 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.types;
// Mirrors focus_mode.dart
public enum FocusMode {
auto("auto"),
locked("locked");
private final String strValue;
FocusMode(String strValue) {
this.strValue = strValue;
}
public static FocusMode getValueForString(String modeStr) {
for (FocusMode value : values()) {
if (value.strValue.equals(modeStr)) return value;
}
return null;
}
@Override
public String toString() {
return strValue;
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/types/FocusMode.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/types/FocusMode.java",
"repo_id": "plugins",
"token_count": 208
} | 1,400 |
// 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.types;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ExposureModeTest {
@Test
public void getValueForString_returnsCorrectValues() {
assertEquals(
"Returns ExposureMode.auto for 'auto'",
ExposureMode.getValueForString("auto"),
ExposureMode.auto);
assertEquals(
"Returns ExposureMode.locked for 'locked'",
ExposureMode.getValueForString("locked"),
ExposureMode.locked);
}
@Test
public void getValueForString_returnsNullForNonexistantValue() {
assertEquals(
"Returns null for 'nonexistant'", ExposureMode.getValueForString("nonexistant"), null);
}
@Test
public void toString_returnsCorrectValue() {
assertEquals("Returns 'auto' for ExposureMode.auto", ExposureMode.auto.toString(), "auto");
assertEquals(
"Returns 'locked' for ExposureMode.locked", ExposureMode.locked.toString(), "locked");
}
}
| plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/types/ExposureModeTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/types/ExposureModeTest.java",
"repo_id": "plugins",
"token_count": 382
} | 1,401 |
// 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:async/async.dart';
import 'package:camera_android/src/android_camera.dart';
import 'package:camera_android/src/utils.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'method_channel_mock.dart';
const String _channelName = 'plugins.flutter.io/camera_android';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('registers instance', () async {
AndroidCamera.registerWith();
expect(CameraPlatform.instance, isA<AndroidCamera>());
});
test('registration does not set message handlers', () async {
AndroidCamera.registerWith();
// Setting up a handler requires bindings to be initialized, and since
// registerWith is called very early in initialization the bindings won't
// have been initialized. While registerWith could intialize them, that
// could slow down startup, so instead the handler should be set up lazily.
final ByteData? response =
await _ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.handlePlatformMessage(
AndroidCamera.deviceEventChannelName,
const StandardMethodCodec().encodeMethodCall(const MethodCall(
'orientation_changed',
<String, Object>{'orientation': 'portraitDown'})),
(ByteData? data) {});
expect(response, null);
});
group('Creation, Initialization & Disposal Tests', () {
test('Should send creation data and receive back a camera id', () async {
// Arrange
final MethodChannelMock cameraMockChannel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{
'create': <String, dynamic>{
'cameraId': 1,
'imageFormatGroup': 'unknown',
}
});
final AndroidCamera camera = AndroidCamera();
// Act
final int cameraId = await camera.createCamera(
const CameraDescription(
name: 'Test',
lensDirection: CameraLensDirection.back,
sensorOrientation: 0),
ResolutionPreset.high,
);
// Assert
expect(cameraMockChannel.log, <Matcher>[
isMethodCall(
'create',
arguments: <String, Object?>{
'cameraName': 'Test',
'resolutionPreset': 'high',
'enableAudio': false
},
),
]);
expect(cameraId, 1);
});
test('Should throw CameraException when create throws a PlatformException',
() {
// Arrange
MethodChannelMock(channelName: _channelName, methods: <String, dynamic>{
'create': PlatformException(
code: 'TESTING_ERROR_CODE',
message: 'Mock error message used during testing.',
)
});
final AndroidCamera camera = AndroidCamera();
// Act
expect(
() => camera.createCamera(
const CameraDescription(
name: 'Test',
lensDirection: CameraLensDirection.back,
sensorOrientation: 0,
),
ResolutionPreset.high,
),
throwsA(
isA<CameraException>()
.having(
(CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE')
.having((CameraException e) => e.description, 'description',
'Mock error message used during testing.'),
),
);
});
test('Should throw CameraException when create throws a PlatformException',
() {
// Arrange
MethodChannelMock(channelName: _channelName, methods: <String, dynamic>{
'create': PlatformException(
code: 'TESTING_ERROR_CODE',
message: 'Mock error message used during testing.',
)
});
final AndroidCamera camera = AndroidCamera();
// Act
expect(
() => camera.createCamera(
const CameraDescription(
name: 'Test',
lensDirection: CameraLensDirection.back,
sensorOrientation: 0,
),
ResolutionPreset.high,
),
throwsA(
isA<CameraException>()
.having(
(CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE')
.having((CameraException e) => e.description, 'description',
'Mock error message used during testing.'),
),
);
});
test(
'Should throw CameraException when initialize throws a PlatformException',
() {
// Arrange
MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{
'initialize': PlatformException(
code: 'TESTING_ERROR_CODE',
message: 'Mock error message used during testing.',
)
},
);
final AndroidCamera camera = AndroidCamera();
// Act
expect(
() => camera.initializeCamera(0),
throwsA(
isA<CameraException>()
.having(
(CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE')
.having(
(CameraException e) => e.description,
'description',
'Mock error message used during testing.',
),
),
);
},
);
test('Should send initialization data', () async {
// Arrange
final MethodChannelMock cameraMockChannel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{
'create': <String, dynamic>{
'cameraId': 1,
'imageFormatGroup': 'unknown',
},
'initialize': null
});
final AndroidCamera camera = AndroidCamera();
final int cameraId = await camera.createCamera(
const CameraDescription(
name: 'Test',
lensDirection: CameraLensDirection.back,
sensorOrientation: 0,
),
ResolutionPreset.high,
);
// Act
final Future<void> initializeFuture = camera.initializeCamera(cameraId);
camera.cameraEventStreamController.add(CameraInitializedEvent(
cameraId,
1920,
1080,
ExposureMode.auto,
true,
FocusMode.auto,
true,
));
await initializeFuture;
// Assert
expect(cameraId, 1);
expect(cameraMockChannel.log, <Matcher>[
anything,
isMethodCall(
'initialize',
arguments: <String, Object?>{
'cameraId': 1,
'imageFormatGroup': 'unknown',
},
),
]);
});
test('Should send a disposal call on dispose', () async {
// Arrange
final MethodChannelMock cameraMockChannel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{
'create': <String, dynamic>{'cameraId': 1},
'initialize': null,
'dispose': <String, dynamic>{'cameraId': 1}
});
final AndroidCamera camera = AndroidCamera();
final int cameraId = await camera.createCamera(
const CameraDescription(
name: 'Test',
lensDirection: CameraLensDirection.back,
sensorOrientation: 0,
),
ResolutionPreset.high,
);
final Future<void> initializeFuture = camera.initializeCamera(cameraId);
camera.cameraEventStreamController.add(CameraInitializedEvent(
cameraId,
1920,
1080,
ExposureMode.auto,
true,
FocusMode.auto,
true,
));
await initializeFuture;
// Act
await camera.dispose(cameraId);
// Assert
expect(cameraId, 1);
expect(cameraMockChannel.log, <Matcher>[
anything,
anything,
isMethodCall(
'dispose',
arguments: <String, Object?>{'cameraId': 1},
),
]);
});
});
group('Event Tests', () {
late AndroidCamera camera;
late int cameraId;
setUp(() async {
MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{
'create': <String, dynamic>{'cameraId': 1},
'initialize': null
},
);
camera = AndroidCamera();
cameraId = await camera.createCamera(
const CameraDescription(
name: 'Test',
lensDirection: CameraLensDirection.back,
sensorOrientation: 0,
),
ResolutionPreset.high,
);
final Future<void> initializeFuture = camera.initializeCamera(cameraId);
camera.cameraEventStreamController.add(CameraInitializedEvent(
cameraId,
1920,
1080,
ExposureMode.auto,
true,
FocusMode.auto,
true,
));
await initializeFuture;
});
test('Should receive initialized event', () async {
// Act
final Stream<CameraInitializedEvent> eventStream =
camera.onCameraInitialized(cameraId);
final StreamQueue<CameraInitializedEvent> streamQueue =
StreamQueue<CameraInitializedEvent>(eventStream);
// Emit test events
final CameraInitializedEvent event = CameraInitializedEvent(
cameraId,
3840,
2160,
ExposureMode.auto,
true,
FocusMode.auto,
true,
);
await camera.handleCameraMethodCall(
MethodCall('initialized', event.toJson()), cameraId);
// Assert
expect(await streamQueue.next, event);
// Clean up
await streamQueue.cancel();
});
test('Should receive resolution changes', () async {
// Act
final Stream<CameraResolutionChangedEvent> resolutionStream =
camera.onCameraResolutionChanged(cameraId);
final StreamQueue<CameraResolutionChangedEvent> streamQueue =
StreamQueue<CameraResolutionChangedEvent>(resolutionStream);
// Emit test events
final CameraResolutionChangedEvent fhdEvent =
CameraResolutionChangedEvent(cameraId, 1920, 1080);
final CameraResolutionChangedEvent uhdEvent =
CameraResolutionChangedEvent(cameraId, 3840, 2160);
await camera.handleCameraMethodCall(
MethodCall('resolution_changed', fhdEvent.toJson()), cameraId);
await camera.handleCameraMethodCall(
MethodCall('resolution_changed', uhdEvent.toJson()), cameraId);
await camera.handleCameraMethodCall(
MethodCall('resolution_changed', fhdEvent.toJson()), cameraId);
await camera.handleCameraMethodCall(
MethodCall('resolution_changed', uhdEvent.toJson()), cameraId);
// Assert
expect(await streamQueue.next, fhdEvent);
expect(await streamQueue.next, uhdEvent);
expect(await streamQueue.next, fhdEvent);
expect(await streamQueue.next, uhdEvent);
// Clean up
await streamQueue.cancel();
});
test('Should receive camera closing events', () async {
// Act
final Stream<CameraClosingEvent> eventStream =
camera.onCameraClosing(cameraId);
final StreamQueue<CameraClosingEvent> streamQueue =
StreamQueue<CameraClosingEvent>(eventStream);
// Emit test events
final CameraClosingEvent event = CameraClosingEvent(cameraId);
await camera.handleCameraMethodCall(
MethodCall('camera_closing', event.toJson()), cameraId);
await camera.handleCameraMethodCall(
MethodCall('camera_closing', event.toJson()), cameraId);
await camera.handleCameraMethodCall(
MethodCall('camera_closing', event.toJson()), cameraId);
// Assert
expect(await streamQueue.next, event);
expect(await streamQueue.next, event);
expect(await streamQueue.next, event);
// Clean up
await streamQueue.cancel();
});
test('Should receive camera error events', () async {
// Act
final Stream<CameraErrorEvent> errorStream =
camera.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(errorStream);
// Emit test events
final CameraErrorEvent event =
CameraErrorEvent(cameraId, 'Error Description');
await camera.handleCameraMethodCall(
MethodCall('error', event.toJson()), cameraId);
await camera.handleCameraMethodCall(
MethodCall('error', event.toJson()), cameraId);
await camera.handleCameraMethodCall(
MethodCall('error', event.toJson()), cameraId);
// Assert
expect(await streamQueue.next, event);
expect(await streamQueue.next, event);
expect(await streamQueue.next, event);
// Clean up
await streamQueue.cancel();
});
test('Should receive device orientation change events', () async {
// Act
final Stream<DeviceOrientationChangedEvent> eventStream =
camera.onDeviceOrientationChanged();
final StreamQueue<DeviceOrientationChangedEvent> streamQueue =
StreamQueue<DeviceOrientationChangedEvent>(eventStream);
// Emit test events
const DeviceOrientationChangedEvent event =
DeviceOrientationChangedEvent(DeviceOrientation.portraitUp);
for (int i = 0; i < 3; i++) {
await _ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.handlePlatformMessage(
AndroidCamera.deviceEventChannelName,
const StandardMethodCodec().encodeMethodCall(
MethodCall('orientation_changed', event.toJson())),
null);
}
// Assert
expect(await streamQueue.next, event);
expect(await streamQueue.next, event);
expect(await streamQueue.next, event);
// Clean up
await streamQueue.cancel();
});
});
group('Function Tests', () {
late AndroidCamera camera;
late int cameraId;
setUp(() async {
MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{
'create': <String, dynamic>{'cameraId': 1},
'initialize': null
},
);
camera = AndroidCamera();
cameraId = await camera.createCamera(
const CameraDescription(
name: 'Test',
lensDirection: CameraLensDirection.back,
sensorOrientation: 0,
),
ResolutionPreset.high,
);
final Future<void> initializeFuture = camera.initializeCamera(cameraId);
camera.cameraEventStreamController.add(
CameraInitializedEvent(
cameraId,
1920,
1080,
ExposureMode.auto,
true,
FocusMode.auto,
true,
),
);
await initializeFuture;
});
test('Should fetch CameraDescription instances for available cameras',
() async {
// Arrange
final List<dynamic> returnData = <dynamic>[
<String, dynamic>{
'name': 'Test 1',
'lensFacing': 'front',
'sensorOrientation': 1
},
<String, dynamic>{
'name': 'Test 2',
'lensFacing': 'back',
'sensorOrientation': 2
}
];
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'availableCameras': returnData},
);
// Act
final List<CameraDescription> cameras = await camera.availableCameras();
// Assert
expect(channel.log, <Matcher>[
isMethodCall('availableCameras', arguments: null),
]);
expect(cameras.length, returnData.length);
for (int i = 0; i < returnData.length; i++) {
final Map<String, Object?> typedData =
(returnData[i] as Map<dynamic, dynamic>).cast<String, Object?>();
final CameraDescription cameraDescription = CameraDescription(
name: typedData['name']! as String,
lensDirection:
parseCameraLensDirection(typedData['lensFacing']! as String),
sensorOrientation: typedData['sensorOrientation']! as int,
);
expect(cameras[i], cameraDescription);
}
});
test(
'Should throw CameraException when availableCameras throws a PlatformException',
() {
// Arrange
MethodChannelMock(channelName: _channelName, methods: <String, dynamic>{
'availableCameras': PlatformException(
code: 'TESTING_ERROR_CODE',
message: 'Mock error message used during testing.',
)
});
// Act
expect(
camera.availableCameras,
throwsA(
isA<CameraException>()
.having(
(CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE')
.having((CameraException e) => e.description, 'description',
'Mock error message used during testing.'),
),
);
});
test('Should take a picture and return an XFile instance', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'takePicture': '/test/path.jpg'});
// Act
final XFile file = await camera.takePicture(cameraId);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('takePicture', arguments: <String, Object?>{
'cameraId': cameraId,
}),
]);
expect(file.path, '/test/path.jpg');
});
test('Should prepare for video recording', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'prepareForVideoRecording': null},
);
// Act
await camera.prepareForVideoRecording();
// Assert
expect(channel.log, <Matcher>[
isMethodCall('prepareForVideoRecording', arguments: null),
]);
});
test('Should start recording a video', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'startVideoRecording': null},
);
// Act
await camera.startVideoRecording(cameraId);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('startVideoRecording', arguments: <String, Object?>{
'cameraId': cameraId,
'maxVideoDuration': null,
'enableStream': false,
}),
]);
});
test('Should pass maxVideoDuration when starting recording a video',
() async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'startVideoRecording': null},
);
// Act
await camera.startVideoRecording(
cameraId,
maxVideoDuration: const Duration(seconds: 10),
);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('startVideoRecording', arguments: <String, Object?>{
'cameraId': cameraId,
'maxVideoDuration': 10000,
'enableStream': false,
}),
]);
});
test(
'Should pass enableStream if callback is passed when starting recording a video',
() async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'startVideoRecording': null},
);
// Act
await camera.startVideoCapturing(
VideoCaptureOptions(cameraId,
streamCallback: (CameraImageData imageData) {}),
);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('startVideoRecording', arguments: <String, Object?>{
'cameraId': cameraId,
'maxVideoDuration': null,
'enableStream': true,
}),
]);
});
test('Should stop a video recording and return the file', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'stopVideoRecording': '/test/path.mp4'},
);
// Act
final XFile file = await camera.stopVideoRecording(cameraId);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('stopVideoRecording', arguments: <String, Object?>{
'cameraId': cameraId,
}),
]);
expect(file.path, '/test/path.mp4');
});
test('Should pause a video recording', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'pauseVideoRecording': null},
);
// Act
await camera.pauseVideoRecording(cameraId);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('pauseVideoRecording', arguments: <String, Object?>{
'cameraId': cameraId,
}),
]);
});
test('Should resume a video recording', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'resumeVideoRecording': null},
);
// Act
await camera.resumeVideoRecording(cameraId);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('resumeVideoRecording', arguments: <String, Object?>{
'cameraId': cameraId,
}),
]);
});
test('Should set the flash mode', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'setFlashMode': null},
);
// Act
await camera.setFlashMode(cameraId, FlashMode.torch);
await camera.setFlashMode(cameraId, FlashMode.always);
await camera.setFlashMode(cameraId, FlashMode.auto);
await camera.setFlashMode(cameraId, FlashMode.off);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('setFlashMode', arguments: <String, Object?>{
'cameraId': cameraId,
'mode': 'torch'
}),
isMethodCall('setFlashMode', arguments: <String, Object?>{
'cameraId': cameraId,
'mode': 'always'
}),
isMethodCall('setFlashMode',
arguments: <String, Object?>{'cameraId': cameraId, 'mode': 'auto'}),
isMethodCall('setFlashMode',
arguments: <String, Object?>{'cameraId': cameraId, 'mode': 'off'}),
]);
});
test('Should set the exposure mode', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'setExposureMode': null},
);
// Act
await camera.setExposureMode(cameraId, ExposureMode.auto);
await camera.setExposureMode(cameraId, ExposureMode.locked);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('setExposureMode',
arguments: <String, Object?>{'cameraId': cameraId, 'mode': 'auto'}),
isMethodCall('setExposureMode', arguments: <String, Object?>{
'cameraId': cameraId,
'mode': 'locked'
}),
]);
});
test('Should set the exposure point', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'setExposurePoint': null},
);
// Act
await camera.setExposurePoint(cameraId, const Point<double>(0.5, 0.5));
await camera.setExposurePoint(cameraId, null);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('setExposurePoint', arguments: <String, Object?>{
'cameraId': cameraId,
'x': 0.5,
'y': 0.5,
'reset': false
}),
isMethodCall('setExposurePoint', arguments: <String, Object?>{
'cameraId': cameraId,
'x': null,
'y': null,
'reset': true
}),
]);
});
test('Should get the min exposure offset', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'getMinExposureOffset': 2.0},
);
// Act
final double minExposureOffset =
await camera.getMinExposureOffset(cameraId);
// Assert
expect(minExposureOffset, 2.0);
expect(channel.log, <Matcher>[
isMethodCall('getMinExposureOffset', arguments: <String, Object?>{
'cameraId': cameraId,
}),
]);
});
test('Should get the max exposure offset', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'getMaxExposureOffset': 2.0},
);
// Act
final double maxExposureOffset =
await camera.getMaxExposureOffset(cameraId);
// Assert
expect(maxExposureOffset, 2.0);
expect(channel.log, <Matcher>[
isMethodCall('getMaxExposureOffset', arguments: <String, Object?>{
'cameraId': cameraId,
}),
]);
});
test('Should get the exposure offset step size', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'getExposureOffsetStepSize': 0.25},
);
// Act
final double stepSize = await camera.getExposureOffsetStepSize(cameraId);
// Assert
expect(stepSize, 0.25);
expect(channel.log, <Matcher>[
isMethodCall('getExposureOffsetStepSize', arguments: <String, Object?>{
'cameraId': cameraId,
}),
]);
});
test('Should set the exposure offset', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'setExposureOffset': 0.6},
);
// Act
final double actualOffset = await camera.setExposureOffset(cameraId, 0.5);
// Assert
expect(actualOffset, 0.6);
expect(channel.log, <Matcher>[
isMethodCall('setExposureOffset', arguments: <String, Object?>{
'cameraId': cameraId,
'offset': 0.5,
}),
]);
});
test('Should set the focus mode', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'setFocusMode': null},
);
// Act
await camera.setFocusMode(cameraId, FocusMode.auto);
await camera.setFocusMode(cameraId, FocusMode.locked);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('setFocusMode',
arguments: <String, Object?>{'cameraId': cameraId, 'mode': 'auto'}),
isMethodCall('setFocusMode', arguments: <String, Object?>{
'cameraId': cameraId,
'mode': 'locked'
}),
]);
});
test('Should set the exposure point', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'setFocusPoint': null},
);
// Act
await camera.setFocusPoint(cameraId, const Point<double>(0.5, 0.5));
await camera.setFocusPoint(cameraId, null);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('setFocusPoint', arguments: <String, Object?>{
'cameraId': cameraId,
'x': 0.5,
'y': 0.5,
'reset': false
}),
isMethodCall('setFocusPoint', arguments: <String, Object?>{
'cameraId': cameraId,
'x': null,
'y': null,
'reset': true
}),
]);
});
test('Should build a texture widget as preview widget', () async {
// Act
final Widget widget = camera.buildPreview(cameraId);
// Act
expect(widget is Texture, isTrue);
expect((widget as Texture).textureId, cameraId);
});
test('Should throw MissingPluginException when handling unknown method',
() {
final AndroidCamera camera = AndroidCamera();
expect(
() => camera.handleCameraMethodCall(
const MethodCall('unknown_method'), 1),
throwsA(isA<MissingPluginException>()));
});
test('Should get the max zoom level', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'getMaxZoomLevel': 10.0},
);
// Act
final double maxZoomLevel = await camera.getMaxZoomLevel(cameraId);
// Assert
expect(maxZoomLevel, 10.0);
expect(channel.log, <Matcher>[
isMethodCall('getMaxZoomLevel', arguments: <String, Object?>{
'cameraId': cameraId,
}),
]);
});
test('Should get the min zoom level', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'getMinZoomLevel': 1.0},
);
// Act
final double maxZoomLevel = await camera.getMinZoomLevel(cameraId);
// Assert
expect(maxZoomLevel, 1.0);
expect(channel.log, <Matcher>[
isMethodCall('getMinZoomLevel', arguments: <String, Object?>{
'cameraId': cameraId,
}),
]);
});
test('Should set the zoom level', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'setZoomLevel': null},
);
// Act
await camera.setZoomLevel(cameraId, 2.0);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('setZoomLevel',
arguments: <String, Object?>{'cameraId': cameraId, 'zoom': 2.0}),
]);
});
test('Should throw CameraException when illegal zoom level is supplied',
() async {
// Arrange
MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{
'setZoomLevel': PlatformException(
code: 'ZOOM_ERROR',
message: 'Illegal zoom error',
)
},
);
// Act & assert
expect(
() => camera.setZoomLevel(cameraId, -1.0),
throwsA(isA<CameraException>()
.having((CameraException e) => e.code, 'code', 'ZOOM_ERROR')
.having((CameraException e) => e.description, 'description',
'Illegal zoom error')));
});
test('Should lock the capture orientation', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'lockCaptureOrientation': null},
);
// Act
await camera.lockCaptureOrientation(
cameraId, DeviceOrientation.portraitUp);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('lockCaptureOrientation', arguments: <String, Object?>{
'cameraId': cameraId,
'orientation': 'portraitUp'
}),
]);
});
test('Should unlock the capture orientation', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'unlockCaptureOrientation': null},
);
// Act
await camera.unlockCaptureOrientation(cameraId);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('unlockCaptureOrientation',
arguments: <String, Object?>{'cameraId': cameraId}),
]);
});
test('Should pause the camera preview', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'pausePreview': null},
);
// Act
await camera.pausePreview(cameraId);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('pausePreview',
arguments: <String, Object?>{'cameraId': cameraId}),
]);
});
test('Should resume the camera preview', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{'resumePreview': null},
);
// Act
await camera.resumePreview(cameraId);
// Assert
expect(channel.log, <Matcher>[
isMethodCall('resumePreview',
arguments: <String, Object?>{'cameraId': cameraId}),
]);
});
test('Should start streaming', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{
'startImageStream': null,
'stopImageStream': null,
},
);
// Act
final StreamSubscription<CameraImageData> subscription = camera
.onStreamedFrameAvailable(cameraId)
.listen((CameraImageData imageData) {});
// Assert
expect(channel.log, <Matcher>[
isMethodCall('startImageStream', arguments: null),
]);
subscription.cancel();
});
test('Should stop streaming', () async {
// Arrange
final MethodChannelMock channel = MethodChannelMock(
channelName: _channelName,
methods: <String, dynamic>{
'startImageStream': null,
'stopImageStream': null,
},
);
// Act
final StreamSubscription<CameraImageData> subscription = camera
.onStreamedFrameAvailable(cameraId)
.listen((CameraImageData imageData) {});
subscription.cancel();
// Assert
expect(channel.log, <Matcher>[
isMethodCall('startImageStream', arguments: null),
isMethodCall('stopImageStream', arguments: null),
]);
});
});
}
/// 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/camera/camera_android/test/android_camera_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_android/test/android_camera_test.dart",
"repo_id": "plugins",
"token_count": 14704
} | 1,402 |
// 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.Manifest;
import android.Manifest.permission;
import android.app.Activity;
import android.content.pm.PackageManager;
import androidx.annotation.VisibleForTesting;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
final class CameraPermissionsManager {
interface PermissionsRegistry {
@SuppressWarnings("deprecation")
void addListener(
io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener handler);
}
interface ResultCallback {
void onResult(String errorCode, String errorDescription);
}
/**
* Camera access permission errors handled when camera is created. See {@code MethodChannelCamera}
* in {@code camera/camera_platform_interface} for details.
*/
private static final String CAMERA_PERMISSIONS_REQUEST_ONGOING =
"CameraPermissionsRequestOngoing";
private static final String CAMERA_PERMISSIONS_REQUEST_ONGOING_MESSAGE =
"Another request is ongoing and multiple requests cannot be handled at once.";
private static final String CAMERA_ACCESS_DENIED = "CameraAccessDenied";
private static final String CAMERA_ACCESS_DENIED_MESSAGE = "Camera access permission was denied.";
private static final String AUDIO_ACCESS_DENIED = "AudioAccessDenied";
private static final String AUDIO_ACCESS_DENIED_MESSAGE = "Audio access permission was denied.";
private static final int CAMERA_REQUEST_ID = 9796;
@VisibleForTesting boolean ongoing = false;
void requestPermissions(
Activity activity,
PermissionsRegistry permissionsRegistry,
boolean enableAudio,
ResultCallback callback) {
if (ongoing) {
callback.onResult(
CAMERA_PERMISSIONS_REQUEST_ONGOING, CAMERA_PERMISSIONS_REQUEST_ONGOING_MESSAGE);
return;
}
if (!hasCameraPermission(activity) || (enableAudio && !hasAudioPermission(activity))) {
permissionsRegistry.addListener(
new CameraRequestPermissionsListener(
(String errorCode, String errorDescription) -> {
ongoing = false;
callback.onResult(errorCode, errorDescription);
}));
ongoing = true;
ActivityCompat.requestPermissions(
activity,
enableAudio
? new String[] {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}
: new String[] {Manifest.permission.CAMERA},
CAMERA_REQUEST_ID);
} else {
// Permissions already exist. Call the callback with success.
callback.onResult(null, null);
}
}
private boolean hasCameraPermission(Activity activity) {
return ContextCompat.checkSelfPermission(activity, permission.CAMERA)
== PackageManager.PERMISSION_GRANTED;
}
private boolean hasAudioPermission(Activity activity) {
return ContextCompat.checkSelfPermission(activity, permission.RECORD_AUDIO)
== PackageManager.PERMISSION_GRANTED;
}
@VisibleForTesting
@SuppressWarnings("deprecation")
static final class CameraRequestPermissionsListener
implements io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener {
// There's no way to unregister permission listeners in the v1 embedding, so we'll be called
// duplicate times in cases where the user denies and then grants a permission. Keep track of if
// we've responded before and bail out of handling the callback manually if this is a repeat
// call.
boolean alreadyCalled = false;
final ResultCallback callback;
@VisibleForTesting
CameraRequestPermissionsListener(ResultCallback callback) {
this.callback = callback;
}
@Override
public boolean onRequestPermissionsResult(int id, String[] permissions, int[] grantResults) {
if (alreadyCalled || id != CAMERA_REQUEST_ID) {
return false;
}
alreadyCalled = true;
// grantResults could be empty if the permissions request with the user is interrupted
// https://developer.android.com/reference/android/app/Activity#onRequestPermissionsResult(int,%20java.lang.String[],%20int[])
if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
callback.onResult(CAMERA_ACCESS_DENIED, CAMERA_ACCESS_DENIED_MESSAGE);
} else if (grantResults.length > 1 && grantResults[1] != PackageManager.PERMISSION_GRANTED) {
callback.onResult(AUDIO_ACCESS_DENIED, AUDIO_ACCESS_DENIED_MESSAGE);
} else {
callback.onResult(null, null);
}
return true;
}
}
}
| plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraPermissionsManager.java/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraPermissionsManager.java",
"repo_id": "plugins",
"token_count": 1598
} | 1,403 |
// 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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import androidx.camera.core.Camera;
import io.flutter.plugin.common.BinaryMessenger;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class CameraTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public Camera camera;
InstanceManager testInstanceManager;
@Before
public void setUp() {
testInstanceManager = InstanceManager.open(identifier -> {});
}
@After
public void tearDown() {
testInstanceManager.close();
}
@Test
public void flutterApiCreateTest() {
final CameraFlutterApiImpl spyFlutterApi =
spy(new CameraFlutterApiImpl(mockBinaryMessenger, testInstanceManager));
spyFlutterApi.create(camera, reply -> {});
final long identifier =
Objects.requireNonNull(testInstanceManager.getIdentifierForStrongReference(camera));
verify(spyFlutterApi).create(eq(identifier), any());
}
}
| plugins/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraTest.java",
"repo_id": "plugins",
"token_count": 497
} | 1,404 |
// 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:io';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:video_player/video_player.dart';
import 'camera_controller.dart';
import 'camera_preview.dart';
/// Camera example home widget.
class CameraExampleHome extends StatefulWidget {
/// Default Constructor
const CameraExampleHome({super.key});
@override
State<CameraExampleHome> createState() {
return _CameraExampleHomeState();
}
}
/// Returns a suitable camera icon for [direction].
IconData getCameraLensIcon(CameraLensDirection direction) {
switch (direction) {
case CameraLensDirection.back:
return Icons.camera_rear;
case CameraLensDirection.front:
return Icons.camera_front;
case CameraLensDirection.external:
return Icons.camera;
}
// This enum is from a different package, so a new value could be added at
// any time. The example should keep working if that happens.
// ignore: dead_code
return Icons.camera;
}
void _logError(String code, String? message) {
// ignore: avoid_print
print('Error: $code${message == null ? '' : '\nError Message: $message'}');
}
class _CameraExampleHomeState extends State<CameraExampleHome>
with WidgetsBindingObserver, TickerProviderStateMixin {
CameraController? controller;
XFile? imageFile;
XFile? videoFile;
VideoPlayerController? videoController;
VoidCallback? videoPlayerListener;
bool enableAudio = true;
double _minAvailableExposureOffset = 0.0;
double _maxAvailableExposureOffset = 0.0;
double _currentExposureOffset = 0.0;
late AnimationController _flashModeControlRowAnimationController;
late Animation<double> _flashModeControlRowAnimation;
late AnimationController _exposureModeControlRowAnimationController;
late Animation<double> _exposureModeControlRowAnimation;
late AnimationController _focusModeControlRowAnimationController;
late Animation<double> _focusModeControlRowAnimation;
double _minAvailableZoom = 1.0;
double _maxAvailableZoom = 1.0;
double _currentScale = 1.0;
double _baseScale = 1.0;
// Counting pointers (number of user fingers on screen)
int _pointers = 0;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_flashModeControlRowAnimationController = AnimationController(
duration: const Duration(milliseconds: 300),
vsync: this,
);
_flashModeControlRowAnimation = CurvedAnimation(
parent: _flashModeControlRowAnimationController,
curve: Curves.easeInCubic,
);
_exposureModeControlRowAnimationController = AnimationController(
duration: const Duration(milliseconds: 300),
vsync: this,
);
_exposureModeControlRowAnimation = CurvedAnimation(
parent: _exposureModeControlRowAnimationController,
curve: Curves.easeInCubic,
);
_focusModeControlRowAnimationController = AnimationController(
duration: const Duration(milliseconds: 300),
vsync: this,
);
_focusModeControlRowAnimation = CurvedAnimation(
parent: _focusModeControlRowAnimationController,
curve: Curves.easeInCubic,
);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_flashModeControlRowAnimationController.dispose();
_exposureModeControlRowAnimationController.dispose();
super.dispose();
}
// #docregion AppLifecycle
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
final CameraController? cameraController = controller;
// App state changed before we got the chance to initialize.
if (cameraController == null || !cameraController.value.isInitialized) {
return;
}
if (state == AppLifecycleState.inactive) {
cameraController.dispose();
} else if (state == AppLifecycleState.resumed) {
onNewCameraSelected(cameraController.description);
}
}
// #enddocregion AppLifecycle
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Camera example'),
),
body: Column(
children: <Widget>[
Expanded(
child: Container(
decoration: BoxDecoration(
color: Colors.black,
border: Border.all(
color:
controller != null && controller!.value.isRecordingVideo
? Colors.redAccent
: Colors.grey,
width: 3.0,
),
),
child: Padding(
padding: const EdgeInsets.all(1.0),
child: Center(
child: _cameraPreviewWidget(),
),
),
),
),
_captureControlRowWidget(),
_modeControlRowWidget(),
Padding(
padding: const EdgeInsets.all(5.0),
child: Row(
children: <Widget>[
_cameraTogglesRowWidget(),
_thumbnailWidget(),
],
),
),
],
),
);
}
/// Display the preview from the camera (or a message if the preview is not available).
Widget _cameraPreviewWidget() {
final CameraController? cameraController = controller;
if (cameraController == null || !cameraController.value.isInitialized) {
return const Text(
'Tap a camera',
style: TextStyle(
color: Colors.white,
fontSize: 24.0,
fontWeight: FontWeight.w900,
),
);
} else {
return Listener(
onPointerDown: (_) => _pointers++,
onPointerUp: (_) => _pointers--,
child: CameraPreview(
controller!,
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onScaleStart: _handleScaleStart,
onScaleUpdate: _handleScaleUpdate,
onTapDown: (TapDownDetails details) =>
onViewFinderTap(details, constraints),
);
}),
),
);
}
}
void _handleScaleStart(ScaleStartDetails details) {
_baseScale = _currentScale;
}
Future<void> _handleScaleUpdate(ScaleUpdateDetails details) async {
// When there are not exactly two fingers on screen don't scale
if (controller == null || _pointers != 2) {
return;
}
_currentScale = (_baseScale * details.scale)
.clamp(_minAvailableZoom, _maxAvailableZoom);
await controller!.setZoomLevel(_currentScale);
}
/// Display the thumbnail of the captured image or video.
Widget _thumbnailWidget() {
final VideoPlayerController? localVideoController = videoController;
return Expanded(
child: Align(
alignment: Alignment.centerRight,
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
if (localVideoController == null && imageFile == null)
Container()
else
SizedBox(
width: 64.0,
height: 64.0,
child: (localVideoController == null)
? (
// The captured image on the web contains a network-accessible URL
// pointing to a location within the browser. It may be displayed
// either with Image.network or Image.memory after loading the image
// bytes to memory.
kIsWeb
? Image.network(imageFile!.path)
: Image.file(File(imageFile!.path)))
: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.pink)),
child: Center(
child: AspectRatio(
aspectRatio:
localVideoController.value.size != null
? localVideoController.value.aspectRatio
: 1.0,
child: VideoPlayer(localVideoController)),
),
),
),
],
),
),
);
}
/// Display a bar with buttons to change the flash and exposure modes
Widget _modeControlRowWidget() {
return Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
IconButton(
icon: const Icon(Icons.flash_on),
color: Colors.blue,
onPressed: () {}, // TODO(camsim99): Add functionality back here.
),
// The exposure and focus mode are currently not supported on the web.
...!kIsWeb
? <Widget>[
IconButton(
icon: const Icon(Icons.exposure),
color: Colors.blue,
onPressed:
() {}, // TODO(camsim99): Add functionality back here.
),
IconButton(
icon: const Icon(Icons.filter_center_focus),
color: Colors.blue,
onPressed:
() {}, // TODO(camsim99): Add functionality back here.
)
]
: <Widget>[],
IconButton(
icon: Icon(enableAudio ? Icons.volume_up : Icons.volume_mute),
color: Colors.blue,
onPressed: () {}, // TODO(camsim99): Add functionality back here.
),
IconButton(
icon: Icon(controller?.value.isCaptureOrientationLocked ?? false
? Icons.screen_lock_rotation
: Icons.screen_rotation),
color: Colors.blue,
onPressed: () {}, // TODO(camsim99): Add functionality back here.
),
],
),
_flashModeControlRowWidget(),
_exposureModeControlRowWidget(),
_focusModeControlRowWidget(),
],
);
}
Widget _flashModeControlRowWidget() {
return SizeTransition(
sizeFactor: _flashModeControlRowAnimation,
child: ClipRect(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
IconButton(
icon: const Icon(Icons.flash_off),
color: controller?.value.flashMode == FlashMode.off
? Colors.orange
: Colors.blue,
onPressed: () {}, // TODO(camsim99): Add functionality back here.
),
IconButton(
icon: const Icon(Icons.flash_auto),
color: controller?.value.flashMode == FlashMode.auto
? Colors.orange
: Colors.blue,
onPressed: () {}, // TODO(camsim99): Add functionality back here.
),
IconButton(
icon: const Icon(Icons.flash_on),
color: controller?.value.flashMode == FlashMode.always
? Colors.orange
: Colors.blue,
onPressed: () {}, // TODO(camsim99): Add functionality back here.
),
IconButton(
icon: const Icon(Icons.highlight),
color: controller?.value.flashMode == FlashMode.torch
? Colors.orange
: Colors.blue,
onPressed: () {}, // TODO(camsim99): Add functionality back here.
),
],
),
),
);
}
Widget _exposureModeControlRowWidget() {
final ButtonStyle styleAuto = TextButton.styleFrom(
// TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724
// ignore: deprecated_member_use
primary: controller?.value.exposureMode == ExposureMode.auto
? Colors.orange
: Colors.blue,
);
final ButtonStyle styleLocked = TextButton.styleFrom(
// TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724
// ignore: deprecated_member_use
primary: controller?.value.exposureMode == ExposureMode.locked
? Colors.orange
: Colors.blue,
);
return SizeTransition(
sizeFactor: _exposureModeControlRowAnimation,
child: ClipRect(
child: Container(
color: Colors.grey.shade50,
child: Column(
children: <Widget>[
const Center(
child: Text('Exposure Mode'),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
TextButton(
style: styleAuto,
onPressed:
() {}, // TODO(camsim99): Add functionality back here.
onLongPress: () {
if (controller != null) {
controller!.setExposurePoint(null);
showInSnackBar('Resetting exposure point');
}
},
child: const Text('AUTO'),
),
TextButton(
style: styleLocked,
onPressed:
() {}, // TODO(camsim99): Add functionality back here.
child: const Text('LOCKED'),
),
TextButton(
style: styleLocked,
onPressed:
() {}, // TODO(camsim99): Add functionality back here.
child: const Text('RESET OFFSET'),
),
],
),
const Center(
child: Text('Exposure Offset'),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(_minAvailableExposureOffset.toString()),
Slider(
value: _currentExposureOffset,
min: _minAvailableExposureOffset,
max: _maxAvailableExposureOffset,
label: _currentExposureOffset.toString(),
onChanged: _minAvailableExposureOffset ==
_maxAvailableExposureOffset
? null
: setExposureOffset,
),
Text(_maxAvailableExposureOffset.toString()),
],
),
],
),
),
),
);
}
Widget _focusModeControlRowWidget() {
final ButtonStyle styleAuto = TextButton.styleFrom(
// TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724
// ignore: deprecated_member_use
primary: controller?.value.focusMode == FocusMode.auto
? Colors.orange
: Colors.blue,
);
final ButtonStyle styleLocked = TextButton.styleFrom(
// TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724
// ignore: deprecated_member_use
primary: controller?.value.focusMode == FocusMode.locked
? Colors.orange
: Colors.blue,
);
return SizeTransition(
sizeFactor: _focusModeControlRowAnimation,
child: ClipRect(
child: Container(
color: Colors.grey.shade50,
child: Column(
children: <Widget>[
const Center(
child: Text('Focus Mode'),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
TextButton(
style: styleAuto,
onPressed:
() {}, // TODO(camsim99): Add functionality back here.
onLongPress: () {
if (controller != null) {
controller!.setFocusPoint(null);
}
showInSnackBar('Resetting focus point');
},
child: const Text('AUTO'),
),
TextButton(
style: styleLocked,
onPressed:
() {}, // TODO(camsim99): Add functionality back here.
child: const Text('LOCKED'),
),
],
),
],
),
),
),
);
}
/// Display the control bar with buttons to take pictures and record videos.
Widget _captureControlRowWidget() {
final CameraController? cameraController = controller;
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
IconButton(
icon: const Icon(Icons.camera_alt),
color: Colors.blue,
onPressed: () {}, // TODO(camsim99): Add functionality back here.
),
IconButton(
icon: const Icon(Icons.videocam),
color: Colors.blue,
onPressed: () {}, // TODO(camsim99): Add functionality back here.
),
IconButton(
icon: cameraController != null &&
cameraController.value.isRecordingPaused
? const Icon(Icons.play_arrow)
: const Icon(Icons.pause),
color: Colors.blue,
onPressed: () {}, // TODO(camsim99): Add functionality back here.
),
IconButton(
icon: const Icon(Icons.stop),
color: Colors.red,
onPressed: () {}, // TODO(camsim99): Add functionality back here.
),
IconButton(
icon: const Icon(Icons.pause_presentation),
color:
cameraController != null && cameraController.value.isPreviewPaused
? Colors.red
: Colors.blue,
onPressed:
cameraController == null ? null : onPausePreviewButtonPressed,
),
],
);
}
/// Display a row of toggle to select the camera (or a message if no camera is available).
Widget _cameraTogglesRowWidget() {
final List<Widget> toggles = <Widget>[];
void onChanged(CameraDescription? description) {
if (description == null) {
return;
}
onNewCameraSelected(description);
}
if (_cameras.isEmpty) {
SchedulerBinding.instance.addPostFrameCallback((_) async {
showInSnackBar('No camera found.');
});
return const Text('None');
} else {
for (final CameraDescription cameraDescription in _cameras) {
toggles.add(
SizedBox(
width: 90.0,
child: RadioListTile<CameraDescription>(
title: Icon(getCameraLensIcon(cameraDescription.lensDirection)),
groupValue: controller?.description,
value: cameraDescription,
onChanged:
controller != null && controller!.value.isRecordingVideo
? null
: onChanged,
),
),
);
}
}
return Row(children: toggles);
}
String timestamp() => DateTime.now().millisecondsSinceEpoch.toString();
void showInSnackBar(String message) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(message)));
}
void onViewFinderTap(TapDownDetails details, BoxConstraints constraints) {
if (controller == null) {
return;
}
final CameraController cameraController = controller!;
final Offset offset = Offset(
details.localPosition.dx / constraints.maxWidth,
details.localPosition.dy / constraints.maxHeight,
);
cameraController.setExposurePoint(offset);
cameraController.setFocusPoint(offset);
}
Future<void> onNewCameraSelected(CameraDescription cameraDescription) async {
final CameraController? oldController = controller;
if (oldController != null) {
// `controller` needs to be set to null before getting disposed,
// to avoid a race condition when we use the controller that is being
// disposed. This happens when camera permission dialog shows up,
// which triggers `didChangeAppLifecycleState`, which disposes and
// re-creates the controller.
controller = null;
await oldController.dispose();
}
final CameraController cameraController = CameraController(
cameraDescription,
kIsWeb ? ResolutionPreset.max : ResolutionPreset.medium,
enableAudio: enableAudio,
imageFormatGroup: ImageFormatGroup.jpeg,
);
controller = cameraController;
// If the controller is updated then update the UI.
cameraController.addListener(() {
if (mounted) {
setState(() {});
}
if (cameraController.value.hasError) {
showInSnackBar(
'Camera error ${cameraController.value.errorDescription}');
}
});
try {
await cameraController.initialize();
await Future.wait(<Future<Object?>>[
// The exposure mode is currently not supported on the web.
...!kIsWeb
? <Future<Object?>>[
cameraController.getMinExposureOffset().then(
(double value) => _minAvailableExposureOffset = value),
cameraController
.getMaxExposureOffset()
.then((double value) => _maxAvailableExposureOffset = value)
]
: <Future<Object?>>[],
cameraController
.getMaxZoomLevel()
.then((double value) => _maxAvailableZoom = value),
cameraController
.getMinZoomLevel()
.then((double value) => _minAvailableZoom = value),
]);
} on CameraException catch (e) {
switch (e.code) {
case 'CameraAccessDenied':
showInSnackBar('You have denied camera access.');
break;
case 'CameraAccessDeniedWithoutPrompt':
// iOS only
showInSnackBar('Please go to Settings app to enable camera access.');
break;
case 'CameraAccessRestricted':
// iOS only
showInSnackBar('Camera access is restricted.');
break;
case 'AudioAccessDenied':
showInSnackBar('You have denied audio access.');
break;
case 'AudioAccessDeniedWithoutPrompt':
// iOS only
showInSnackBar('Please go to Settings app to enable audio access.');
break;
case 'AudioAccessRestricted':
// iOS only
showInSnackBar('Audio access is restricted.');
break;
default:
_showCameraException(e);
break;
}
}
if (mounted) {
setState(() {});
}
}
void onTakePictureButtonPressed() {
takePicture().then((XFile? file) {
if (mounted) {
setState(() {
imageFile = file;
videoController?.dispose();
videoController = null;
});
if (file != null) {
showInSnackBar('Picture saved to ${file.path}');
}
}
});
}
void onFlashModeButtonPressed() {
if (_flashModeControlRowAnimationController.value == 1) {
_flashModeControlRowAnimationController.reverse();
} else {
_flashModeControlRowAnimationController.forward();
_exposureModeControlRowAnimationController.reverse();
_focusModeControlRowAnimationController.reverse();
}
}
void onExposureModeButtonPressed() {
if (_exposureModeControlRowAnimationController.value == 1) {
_exposureModeControlRowAnimationController.reverse();
} else {
_exposureModeControlRowAnimationController.forward();
_flashModeControlRowAnimationController.reverse();
_focusModeControlRowAnimationController.reverse();
}
}
void onFocusModeButtonPressed() {
if (_focusModeControlRowAnimationController.value == 1) {
_focusModeControlRowAnimationController.reverse();
} else {
_focusModeControlRowAnimationController.forward();
_flashModeControlRowAnimationController.reverse();
_exposureModeControlRowAnimationController.reverse();
}
}
void onAudioModeButtonPressed() {
enableAudio = !enableAudio;
if (controller != null) {
onNewCameraSelected(controller!.description);
}
}
Future<void> onCaptureOrientationLockButtonPressed() async {
try {
if (controller != null) {
final CameraController cameraController = controller!;
if (cameraController.value.isCaptureOrientationLocked) {
await cameraController.unlockCaptureOrientation();
showInSnackBar('Capture orientation unlocked');
} else {
await cameraController.lockCaptureOrientation();
showInSnackBar(
'Capture orientation locked to ${cameraController.value.lockedCaptureOrientation.toString().split('.').last}');
}
}
} on CameraException catch (e) {
_showCameraException(e);
}
}
void onSetFlashModeButtonPressed(FlashMode mode) {
setFlashMode(mode).then((_) {
if (mounted) {
setState(() {});
}
showInSnackBar('Flash mode set to ${mode.toString().split('.').last}');
});
}
void onSetExposureModeButtonPressed(ExposureMode mode) {
setExposureMode(mode).then((_) {
if (mounted) {
setState(() {});
}
showInSnackBar('Exposure mode set to ${mode.toString().split('.').last}');
});
}
void onSetFocusModeButtonPressed(FocusMode mode) {
setFocusMode(mode).then((_) {
if (mounted) {
setState(() {});
}
showInSnackBar('Focus mode set to ${mode.toString().split('.').last}');
});
}
void onVideoRecordButtonPressed() {
startVideoRecording().then((_) {
if (mounted) {
setState(() {});
}
});
}
void onStopButtonPressed() {
stopVideoRecording().then((XFile? file) {
if (mounted) {
setState(() {});
}
if (file != null) {
showInSnackBar('Video recorded to ${file.path}');
videoFile = file;
_startVideoPlayer();
}
});
}
Future<void> onPausePreviewButtonPressed() async {
final CameraController? cameraController = controller;
if (cameraController == null || !cameraController.value.isInitialized) {
showInSnackBar('Error: select a camera first.');
return;
}
if (cameraController.value.isPreviewPaused) {
await cameraController.resumePreview();
} else {
await cameraController.pausePreview();
}
if (mounted) {
setState(() {});
}
}
void onPauseButtonPressed() {
pauseVideoRecording().then((_) {
if (mounted) {
setState(() {});
}
showInSnackBar('Video recording paused');
});
}
void onResumeButtonPressed() {
resumeVideoRecording().then((_) {
if (mounted) {
setState(() {});
}
showInSnackBar('Video recording resumed');
});
}
Future<void> startVideoRecording() async {
final CameraController? cameraController = controller;
if (cameraController == null || !cameraController.value.isInitialized) {
showInSnackBar('Error: select a camera first.');
return;
}
if (cameraController.value.isRecordingVideo) {
// A recording is already started, do nothing.
return;
}
try {
await cameraController.startVideoRecording();
} on CameraException catch (e) {
_showCameraException(e);
return;
}
}
Future<XFile?> stopVideoRecording() async {
final CameraController? cameraController = controller;
if (cameraController == null || !cameraController.value.isRecordingVideo) {
return null;
}
try {
return cameraController.stopVideoRecording();
} on CameraException catch (e) {
_showCameraException(e);
return null;
}
}
Future<void> pauseVideoRecording() async {
final CameraController? cameraController = controller;
if (cameraController == null || !cameraController.value.isRecordingVideo) {
return;
}
try {
await cameraController.pauseVideoRecording();
} on CameraException catch (e) {
_showCameraException(e);
rethrow;
}
}
Future<void> resumeVideoRecording() async {
final CameraController? cameraController = controller;
if (cameraController == null || !cameraController.value.isRecordingVideo) {
return;
}
try {
await cameraController.resumeVideoRecording();
} on CameraException catch (e) {
_showCameraException(e);
rethrow;
}
}
Future<void> setFlashMode(FlashMode mode) async {
if (controller == null) {
return;
}
try {
await controller!.setFlashMode(mode);
} on CameraException catch (e) {
_showCameraException(e);
rethrow;
}
}
Future<void> setExposureMode(ExposureMode mode) async {
if (controller == null) {
return;
}
try {
await controller!.setExposureMode(mode);
} on CameraException catch (e) {
_showCameraException(e);
rethrow;
}
}
Future<void> setExposureOffset(double offset) async {
if (controller == null) {
return;
}
setState(() {
_currentExposureOffset = offset;
});
try {
offset = await controller!.setExposureOffset(offset);
} on CameraException catch (e) {
_showCameraException(e);
rethrow;
}
}
Future<void> setFocusMode(FocusMode mode) async {
if (controller == null) {
return;
}
try {
await controller!.setFocusMode(mode);
} on CameraException catch (e) {
_showCameraException(e);
rethrow;
}
}
Future<void> _startVideoPlayer() async {
if (videoFile == null) {
return;
}
final VideoPlayerController vController = kIsWeb
? VideoPlayerController.network(videoFile!.path)
: VideoPlayerController.file(File(videoFile!.path));
videoPlayerListener = () {
if (videoController != null && videoController!.value.size != null) {
// Refreshing the state to update video player with the correct ratio.
if (mounted) {
setState(() {});
}
videoController!.removeListener(videoPlayerListener!);
}
};
vController.addListener(videoPlayerListener!);
await vController.setLooping(true);
await vController.initialize();
await videoController?.dispose();
if (mounted) {
setState(() {
imageFile = null;
videoController = vController;
});
}
await vController.play();
}
Future<XFile?> takePicture() async {
final CameraController? cameraController = controller;
if (cameraController == null || !cameraController.value.isInitialized) {
showInSnackBar('Error: select a camera first.');
return null;
}
if (cameraController.value.isTakingPicture) {
// A capture is already pending, do nothing.
return null;
}
try {
final XFile file = await cameraController.takePicture();
return file;
} on CameraException catch (e) {
_showCameraException(e);
return null;
}
}
void _showCameraException(CameraException e) {
_logError(e.code, e.description);
showInSnackBar('Error: ${e.code}\n${e.description}');
}
}
/// CameraApp is the Main Application.
class CameraApp extends StatelessWidget {
/// Default Constructor
const CameraApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: CameraExampleHome(),
);
}
}
List<CameraDescription> _cameras = <CameraDescription>[];
Future<void> main() async {
// Fetch the available cameras before initializing the app.
try {
WidgetsFlutterBinding.ensureInitialized();
_cameras = await availableCameras();
} on CameraException catch (e) {
_logError(e.code, e.description);
}
runApp(const CameraApp());
}
| plugins/packages/camera/camera_android_camerax/example/lib/main.dart/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/example/lib/main.dart",
"repo_id": "plugins",
"token_count": 14368
} | 1,405 |
// 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:camera_platform_interface/camera_platform_interface.dart'
show CameraException, DeviceOrientationChangedEvent;
import 'package:flutter/services.dart';
import 'android_camera_camerax_flutter_api_impls.dart';
import 'camerax_library.g.dart';
// Ignoring lint indicating this class only contains static members
// as this class is a wrapper for various Android system services.
// ignore_for_file: avoid_classes_with_only_static_members
/// Utility class that offers access to Android system services needed for
/// camera usage and other informational streams.
class SystemServices {
/// Stream that emits the device orientation whenever it is changed.
///
/// Values may start being added to the stream once
/// `startListeningForDeviceOrientationChange(...)` is called.
static final StreamController<DeviceOrientationChangedEvent>
deviceOrientationChangedStreamController =
StreamController<DeviceOrientationChangedEvent>.broadcast();
/// Stream that emits the errors caused by camera usage on the native side.
static final StreamController<String> cameraErrorStreamController =
StreamController<String>.broadcast();
/// Requests permission to access the camera and audio if specified.
static Future<void> requestCameraPermissions(bool enableAudio,
{BinaryMessenger? binaryMessenger}) {
final SystemServicesHostApiImpl api =
SystemServicesHostApiImpl(binaryMessenger: binaryMessenger);
return api.sendCameraPermissionsRequest(enableAudio);
}
/// Requests that [deviceOrientationChangedStreamController] start
/// emitting values for any change in device orientation.
static void startListeningForDeviceOrientationChange(
bool isFrontFacing, int sensorOrientation,
{BinaryMessenger? binaryMessenger}) {
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
final SystemServicesHostApi api =
SystemServicesHostApi(binaryMessenger: binaryMessenger);
api.startListeningForDeviceOrientationChange(
isFrontFacing, sensorOrientation);
}
/// Stops the [deviceOrientationChangedStreamController] from emitting values
/// for changes in device orientation.
static void stopListeningForDeviceOrientationChange(
{BinaryMessenger? binaryMessenger}) {
final SystemServicesHostApi api =
SystemServicesHostApi(binaryMessenger: binaryMessenger);
api.stopListeningForDeviceOrientationChange();
}
}
/// Host API implementation of [SystemServices].
class SystemServicesHostApiImpl extends SystemServicesHostApi {
/// Creates a [SystemServicesHostApiImpl].
SystemServicesHostApiImpl({this.binaryMessenger})
: super(binaryMessenger: binaryMessenger);
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Requests permission to access the camera and audio if specified.
///
/// Will complete normally if permissions are successfully granted; otherwise,
/// will throw a [CameraException].
Future<void> sendCameraPermissionsRequest(bool enableAudio) async {
final CameraPermissionsErrorData? error =
await requestCameraPermissions(enableAudio);
if (error != null) {
throw CameraException(
error.errorCode,
error.description,
);
}
}
}
/// Flutter API implementation of [SystemServices].
class SystemServicesFlutterApiImpl implements SystemServicesFlutterApi {
/// Constructs a [SystemServicesFlutterApiImpl].
SystemServicesFlutterApiImpl({
this.binaryMessenger,
});
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Callback method for any changes in device orientation.
///
/// Will only be called if
/// `SystemServices.startListeningForDeviceOrientationChange(...)` was called
/// to start listening for device orientation updates.
@override
void onDeviceOrientationChanged(String orientation) {
final DeviceOrientation deviceOrientation =
deserializeDeviceOrientation(orientation);
if (deviceOrientation == null) {
return;
}
SystemServices.deviceOrientationChangedStreamController
.add(DeviceOrientationChangedEvent(deviceOrientation));
}
/// Deserializes device orientation in [String] format into a
/// [DeviceOrientation].
DeviceOrientation deserializeDeviceOrientation(String orientation) {
switch (orientation) {
case 'LANDSCAPE_LEFT':
return DeviceOrientation.landscapeLeft;
case 'LANDSCAPE_RIGHT':
return DeviceOrientation.landscapeRight;
case 'PORTRAIT_DOWN':
return DeviceOrientation.portraitDown;
case 'PORTRAIT_UP':
return DeviceOrientation.portraitUp;
default:
throw ArgumentError(
'"$orientation" is not a valid DeviceOrientation value');
}
}
/// Callback method for any errors caused by camera usage on the Java side.
@override
void onCameraError(String errorDescription) {
SystemServices.cameraErrorStreamController.add(errorDescription);
}
}
| plugins/packages/camera/camera_android_camerax/lib/src/system_services.dart/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/lib/src/system_services.dart",
"repo_id": "plugins",
"token_count": 1608
} | 1,406 |
// 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/camerax_library.g.dart'
show CameraPermissionsErrorData;
import 'package:camera_android_camerax/src/system_services.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart'
show CameraException, DeviceOrientationChangedEvent;
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'system_services_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[TestSystemServicesHostApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('SystemServices', () {
tearDown(() => TestProcessCameraProviderHostApi.setup(null));
test(
'requestCameraPermissionsFromInstance completes normally without errors test',
() async {
final MockTestSystemServicesHostApi mockApi =
MockTestSystemServicesHostApi();
TestSystemServicesHostApi.setup(mockApi);
when(mockApi.requestCameraPermissions(true))
.thenAnswer((_) async => null);
await SystemServices.requestCameraPermissions(true);
verify(mockApi.requestCameraPermissions(true));
});
test(
'requestCameraPermissionsFromInstance throws CameraException if there was a request error',
() {
final MockTestSystemServicesHostApi mockApi =
MockTestSystemServicesHostApi();
TestSystemServicesHostApi.setup(mockApi);
final CameraPermissionsErrorData error = CameraPermissionsErrorData(
errorCode: 'Test error code',
description: 'Test error description',
);
when(mockApi.requestCameraPermissions(true))
.thenAnswer((_) async => error);
expect(
() async => SystemServices.requestCameraPermissions(true),
throwsA(isA<CameraException>()
.having((CameraException e) => e.code, 'code', 'Test error code')
.having((CameraException e) => e.description, 'description',
'Test error description')));
verify(mockApi.requestCameraPermissions(true));
});
test('startListeningForDeviceOrientationChangeTest', () async {
final MockTestSystemServicesHostApi mockApi =
MockTestSystemServicesHostApi();
TestSystemServicesHostApi.setup(mockApi);
SystemServices.startListeningForDeviceOrientationChange(true, 90);
verify(mockApi.startListeningForDeviceOrientationChange(true, 90));
});
test('stopListeningForDeviceOrientationChangeTest', () async {
final MockTestSystemServicesHostApi mockApi =
MockTestSystemServicesHostApi();
TestSystemServicesHostApi.setup(mockApi);
SystemServices.stopListeningForDeviceOrientationChange();
verify(mockApi.stopListeningForDeviceOrientationChange());
});
test('onDeviceOrientationChanged adds new orientation to stream', () {
SystemServices.deviceOrientationChangedStreamController.stream
.listen((DeviceOrientationChangedEvent event) {
expect(event.orientation, equals(DeviceOrientation.landscapeLeft));
});
SystemServicesFlutterApiImpl()
.onDeviceOrientationChanged('LANDSCAPE_LEFT');
});
test(
'onDeviceOrientationChanged throws error if new orientation is invalid',
() {
expect(
() => SystemServicesFlutterApiImpl()
.onDeviceOrientationChanged('FAKE_ORIENTATION'),
throwsA(isA<ArgumentError>().having(
(ArgumentError e) => e.message,
'message',
'"FAKE_ORIENTATION" is not a valid DeviceOrientation value')));
});
test('onCameraError adds new error to stream', () {
const String testErrorDescription = 'Test error description!';
SystemServices.cameraErrorStreamController.stream
.listen((String errorDescription) {
expect(errorDescription, equals(testErrorDescription));
});
SystemServicesFlutterApiImpl().onCameraError(testErrorDescription);
});
});
}
| plugins/packages/camera/camera_android_camerax/test/system_services_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/test/system_services_test.dart",
"repo_id": "plugins",
"token_count": 1554
} | 1,407 |
// 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 camera_avfoundation.Test;
@import XCTest;
@import Flutter;
#import <OCMock/OCMock.h>
@interface CameraOrientationTests : XCTestCase
@end
@implementation CameraOrientationTests
- (void)testOrientationNotifications {
id mockMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
CameraPlugin *cameraPlugin = [[CameraPlugin alloc] initWithRegistry:nil messenger:mockMessenger];
[mockMessenger setExpectationOrderMatters:YES];
[self rotate:UIDeviceOrientationPortraitUpsideDown
expectedChannelOrientation:@"portraitDown"
cameraPlugin:cameraPlugin
messenger:mockMessenger];
[self rotate:UIDeviceOrientationPortrait
expectedChannelOrientation:@"portraitUp"
cameraPlugin:cameraPlugin
messenger:mockMessenger];
[self rotate:UIDeviceOrientationLandscapeRight
expectedChannelOrientation:@"landscapeLeft"
cameraPlugin:cameraPlugin
messenger:mockMessenger];
[self rotate:UIDeviceOrientationLandscapeLeft
expectedChannelOrientation:@"landscapeRight"
cameraPlugin:cameraPlugin
messenger:mockMessenger];
OCMReject([mockMessenger sendOnChannel:[OCMArg any] message:[OCMArg any]]);
// No notification when flat.
[cameraPlugin
orientationChanged:[self createMockNotificationForOrientation:UIDeviceOrientationFaceUp]];
// No notification when facedown.
[cameraPlugin
orientationChanged:[self createMockNotificationForOrientation:UIDeviceOrientationFaceDown]];
OCMVerifyAll(mockMessenger);
}
- (void)testOrientationUpdateMustBeOnCaptureSessionQueue {
XCTestExpectation *queueExpectation = [self
expectationWithDescription:@"Orientation update must happen on the capture session queue"];
CameraPlugin *camera = [[CameraPlugin alloc] initWithRegistry:nil messenger:nil];
const char *captureSessionQueueSpecific = "capture_session_queue";
dispatch_queue_set_specific(camera.captureSessionQueue, captureSessionQueueSpecific,
(void *)captureSessionQueueSpecific, NULL);
FLTCam *mockCam = OCMClassMock([FLTCam class]);
camera.camera = mockCam;
OCMStub([mockCam setDeviceOrientation:UIDeviceOrientationLandscapeLeft])
.andDo(^(NSInvocation *invocation) {
if (dispatch_get_specific(captureSessionQueueSpecific)) {
[queueExpectation fulfill];
}
});
[camera orientationChanged:
[self createMockNotificationForOrientation:UIDeviceOrientationLandscapeLeft]];
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)rotate:(UIDeviceOrientation)deviceOrientation
expectedChannelOrientation:(NSString *)channelOrientation
cameraPlugin:(CameraPlugin *)cameraPlugin
messenger:(NSObject<FlutterBinaryMessenger> *)messenger {
XCTestExpectation *orientationExpectation = [self expectationWithDescription:channelOrientation];
OCMExpect([messenger
sendOnChannel:[OCMArg any]
message:[OCMArg checkWithBlock:^BOOL(NSData *data) {
NSObject<FlutterMethodCodec> *codec = [FlutterStandardMethodCodec sharedInstance];
FlutterMethodCall *methodCall = [codec decodeMethodCall:data];
[orientationExpectation fulfill];
return
[methodCall.method isEqualToString:@"orientation_changed"] &&
[methodCall.arguments isEqualToDictionary:@{@"orientation" : channelOrientation}];
}]]);
[cameraPlugin orientationChanged:[self createMockNotificationForOrientation:deviceOrientation]];
[self waitForExpectationsWithTimeout:30.0 handler:nil];
}
- (void)testOrientationChanged_noRetainCycle {
dispatch_queue_t captureSessionQueue = dispatch_queue_create("capture_session_queue", NULL);
FLTCam *mockCam = OCMClassMock([FLTCam class]);
FLTThreadSafeMethodChannel *mockChannel = OCMClassMock([FLTThreadSafeMethodChannel class]);
__weak CameraPlugin *weakCamera;
@autoreleasepool {
CameraPlugin *camera = [[CameraPlugin alloc] initWithRegistry:nil messenger:nil];
weakCamera = camera;
camera.captureSessionQueue = captureSessionQueue;
camera.camera = mockCam;
camera.deviceEventMethodChannel = mockChannel;
[camera orientationChanged:
[self createMockNotificationForOrientation:UIDeviceOrientationLandscapeLeft]];
}
// Sanity check
XCTAssertNil(weakCamera, @"Camera must have been deallocated.");
// Must check in captureSessionQueue since orientationChanged dispatches to this queue.
XCTestExpectation *expectation =
[self expectationWithDescription:@"Dispatched to capture session queue"];
dispatch_async(captureSessionQueue, ^{
OCMVerify(never(), [mockCam setDeviceOrientation:UIDeviceOrientationLandscapeLeft]);
OCMVerify(never(), [mockChannel invokeMethod:@"orientation_changed" arguments:OCMOCK_ANY]);
[expectation fulfill];
});
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (NSNotification *)createMockNotificationForOrientation:(UIDeviceOrientation)deviceOrientation {
UIDevice *mockDevice = OCMClassMock([UIDevice class]);
OCMStub([mockDevice orientation]).andReturn(deviceOrientation);
return [NSNotification notificationWithName:@"orientation_test" object:mockDevice];
}
@end
| plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraOrientationTests.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraOrientationTests.m",
"repo_id": "plugins",
"token_count": 2000
} | 1,408 |
// 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;
@interface ThreadSafeFlutterResultTests : XCTestCase
@end
@implementation ThreadSafeFlutterResultTests
- (void)testAsyncSendSuccess_ShouldCallResultOnMainThread {
XCTestExpectation *expectation = [self expectationWithDescription:@"Result finished"];
FLTThreadSafeFlutterResult *threadSafeFlutterResult =
[[FLTThreadSafeFlutterResult alloc] initWithResult:^(id _Nullable result) {
XCTAssert(NSThread.isMainThread);
[expectation fulfill];
}];
dispatch_queue_t dispatchQueue = dispatch_queue_create("test dispatchqueue", NULL);
dispatch_async(dispatchQueue, ^{
[threadSafeFlutterResult sendSuccess];
});
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)testSyncSendSuccess_ShouldCallResultOnMainThread {
XCTestExpectation *expectation = [self expectationWithDescription:@"Result finished"];
FLTThreadSafeFlutterResult *threadSafeFlutterResult =
[[FLTThreadSafeFlutterResult alloc] initWithResult:^(id _Nullable result) {
XCTAssert(NSThread.isMainThread);
[expectation fulfill];
}];
[threadSafeFlutterResult sendSuccess];
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)testSendNotImplemented_ShouldSendNotImplementedToFlutterResult {
XCTestExpectation *expectation = [self expectationWithDescription:@"Result finished"];
FLTThreadSafeFlutterResult *threadSafeFlutterResult =
[[FLTThreadSafeFlutterResult alloc] initWithResult:^(id _Nullable result) {
XCTAssert([result isKindOfClass:FlutterMethodNotImplemented.class]);
[expectation fulfill];
}];
dispatch_queue_t dispatchQueue = dispatch_queue_create("test dispatchqueue", NULL);
dispatch_async(dispatchQueue, ^{
[threadSafeFlutterResult sendNotImplemented];
});
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)testSendErrorDetails_ShouldSendErrorToFlutterResult {
NSString *errorCode = @"errorCode";
NSString *errorMessage = @"message";
NSString *errorDetails = @"error details";
XCTestExpectation *expectation = [self expectationWithDescription:@"Result finished"];
FLTThreadSafeFlutterResult *threadSafeFlutterResult =
[[FLTThreadSafeFlutterResult alloc] initWithResult:^(id _Nullable result) {
XCTAssert([result isKindOfClass:FlutterError.class]);
FlutterError *error = (FlutterError *)result;
XCTAssertEqualObjects(error.code, errorCode);
XCTAssertEqualObjects(error.message, errorMessage);
XCTAssertEqualObjects(error.details, errorDetails);
[expectation fulfill];
}];
dispatch_queue_t dispatchQueue = dispatch_queue_create("test dispatchqueue", NULL);
dispatch_async(dispatchQueue, ^{
[threadSafeFlutterResult sendErrorWithCode:errorCode message:errorMessage details:errorDetails];
});
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)testSendNSError_ShouldSendErrorToFlutterResult {
NSError *originalError = [[NSError alloc] initWithDomain:NSURLErrorDomain code:404 userInfo:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"Result finished"];
FLTThreadSafeFlutterResult *threadSafeFlutterResult =
[[FLTThreadSafeFlutterResult alloc] initWithResult:^(id _Nullable result) {
XCTAssert([result isKindOfClass:FlutterError.class]);
FlutterError *error = (FlutterError *)result;
NSString *constructedErrorCode =
[NSString stringWithFormat:@"Error %d", (int)originalError.code];
XCTAssertEqualObjects(error.code, constructedErrorCode);
[expectation fulfill];
}];
dispatch_queue_t dispatchQueue = dispatch_queue_create("test dispatchqueue", NULL);
dispatch_async(dispatchQueue, ^{
[threadSafeFlutterResult sendError:originalError];
});
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)testSendResult_ShouldSendResultToFlutterResult {
NSString *resultData = @"resultData";
XCTestExpectation *expectation = [self expectationWithDescription:@"Result finished"];
FLTThreadSafeFlutterResult *threadSafeFlutterResult =
[[FLTThreadSafeFlutterResult alloc] initWithResult:^(id _Nullable result) {
XCTAssertEqualObjects(result, resultData);
[expectation fulfill];
}];
dispatch_queue_t dispatchQueue = dispatch_queue_create("test dispatchqueue", NULL);
dispatch_async(dispatchQueue, ^{
[threadSafeFlutterResult sendSuccessWithData:resultData];
});
[self waitForExpectationsWithTimeout:1 handler:nil];
}
@end
| plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/ThreadSafeFlutterResultTests.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/ThreadSafeFlutterResultTests.m",
"repo_id": "plugins",
"token_count": 1579
} | 1,409 |
// 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 "CameraProperties.h"
#pragma mark - flash mode
FLTFlashMode FLTGetFLTFlashModeForString(NSString *mode) {
if ([mode isEqualToString:@"off"]) {
return FLTFlashModeOff;
} else if ([mode isEqualToString:@"auto"]) {
return FLTFlashModeAuto;
} else if ([mode isEqualToString:@"always"]) {
return FLTFlashModeAlways;
} else if ([mode isEqualToString:@"torch"]) {
return FLTFlashModeTorch;
} else {
NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSURLErrorUnknown
userInfo:@{
NSLocalizedDescriptionKey : [NSString
stringWithFormat:@"Unknown flash mode %@", mode]
}];
@throw error;
}
}
AVCaptureFlashMode FLTGetAVCaptureFlashModeForFLTFlashMode(FLTFlashMode mode) {
switch (mode) {
case FLTFlashModeOff:
return AVCaptureFlashModeOff;
case FLTFlashModeAuto:
return AVCaptureFlashModeAuto;
case FLTFlashModeAlways:
return AVCaptureFlashModeOn;
case FLTFlashModeTorch:
default:
return -1;
}
}
#pragma mark - exposure mode
NSString *FLTGetStringForFLTExposureMode(FLTExposureMode mode) {
switch (mode) {
case FLTExposureModeAuto:
return @"auto";
case FLTExposureModeLocked:
return @"locked";
}
NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSURLErrorUnknown
userInfo:@{
NSLocalizedDescriptionKey : [NSString
stringWithFormat:@"Unknown string for exposure mode"]
}];
@throw error;
}
FLTExposureMode FLTGetFLTExposureModeForString(NSString *mode) {
if ([mode isEqualToString:@"auto"]) {
return FLTExposureModeAuto;
} else if ([mode isEqualToString:@"locked"]) {
return FLTExposureModeLocked;
} else {
NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSURLErrorUnknown
userInfo:@{
NSLocalizedDescriptionKey : [NSString
stringWithFormat:@"Unknown exposure mode %@", mode]
}];
@throw error;
}
}
#pragma mark - focus mode
NSString *FLTGetStringForFLTFocusMode(FLTFocusMode mode) {
switch (mode) {
case FLTFocusModeAuto:
return @"auto";
case FLTFocusModeLocked:
return @"locked";
}
NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSURLErrorUnknown
userInfo:@{
NSLocalizedDescriptionKey : [NSString
stringWithFormat:@"Unknown string for focus mode"]
}];
@throw error;
}
FLTFocusMode FLTGetFLTFocusModeForString(NSString *mode) {
if ([mode isEqualToString:@"auto"]) {
return FLTFocusModeAuto;
} else if ([mode isEqualToString:@"locked"]) {
return FLTFocusModeLocked;
} else {
NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSURLErrorUnknown
userInfo:@{
NSLocalizedDescriptionKey : [NSString
stringWithFormat:@"Unknown focus mode %@", mode]
}];
@throw error;
}
}
#pragma mark - device orientation
UIDeviceOrientation FLTGetUIDeviceOrientationForString(NSString *orientation) {
if ([orientation isEqualToString:@"portraitDown"]) {
return UIDeviceOrientationPortraitUpsideDown;
} else if ([orientation isEqualToString:@"landscapeLeft"]) {
return UIDeviceOrientationLandscapeRight;
} else if ([orientation isEqualToString:@"landscapeRight"]) {
return UIDeviceOrientationLandscapeLeft;
} else if ([orientation isEqualToString:@"portraitUp"]) {
return UIDeviceOrientationPortrait;
} else {
NSError *error = [NSError
errorWithDomain:NSCocoaErrorDomain
code:NSURLErrorUnknown
userInfo:@{
NSLocalizedDescriptionKey :
[NSString stringWithFormat:@"Unknown device orientation %@", orientation]
}];
@throw error;
}
}
NSString *FLTGetStringForUIDeviceOrientation(UIDeviceOrientation orientation) {
switch (orientation) {
case UIDeviceOrientationPortraitUpsideDown:
return @"portraitDown";
case UIDeviceOrientationLandscapeRight:
return @"landscapeLeft";
case UIDeviceOrientationLandscapeLeft:
return @"landscapeRight";
case UIDeviceOrientationPortrait:
default:
return @"portraitUp";
};
}
#pragma mark - resolution preset
FLTResolutionPreset FLTGetFLTResolutionPresetForString(NSString *preset) {
if ([preset isEqualToString:@"veryLow"]) {
return FLTResolutionPresetVeryLow;
} else if ([preset isEqualToString:@"low"]) {
return FLTResolutionPresetLow;
} else if ([preset isEqualToString:@"medium"]) {
return FLTResolutionPresetMedium;
} else if ([preset isEqualToString:@"high"]) {
return FLTResolutionPresetHigh;
} else if ([preset isEqualToString:@"veryHigh"]) {
return FLTResolutionPresetVeryHigh;
} else if ([preset isEqualToString:@"ultraHigh"]) {
return FLTResolutionPresetUltraHigh;
} else if ([preset isEqualToString:@"max"]) {
return FLTResolutionPresetMax;
} else {
NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSURLErrorUnknown
userInfo:@{
NSLocalizedDescriptionKey : [NSString
stringWithFormat:@"Unknown resolution preset %@", preset]
}];
@throw error;
}
}
#pragma mark - video format
OSType FLTGetVideoFormatFromString(NSString *videoFormatString) {
if ([videoFormatString isEqualToString:@"bgra8888"]) {
return kCVPixelFormatType_32BGRA;
} else if ([videoFormatString isEqualToString:@"yuv420"]) {
return kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
} else {
NSLog(@"The selected imageFormatGroup is not supported by iOS. Defaulting to brga8888");
return kCVPixelFormatType_32BGRA;
}
}
| plugins/packages/camera/camera_avfoundation/ios/Classes/CameraProperties.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/CameraProperties.m",
"repo_id": "plugins",
"token_count": 3284
} | 1,410 |
// 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.
/// Expose XFile
export 'package:cross_file/cross_file.dart';
export 'src/events/camera_event.dart';
export 'src/events/device_event.dart';
export 'src/platform_interface/camera_platform.dart';
export 'src/types/types.dart';
| plugins/packages/camera/camera_platform_interface/lib/camera_platform_interface.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/lib/camera_platform_interface.dart",
"repo_id": "plugins",
"token_count": 121
} | 1,411 |
// 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 '../../camera_platform_interface.dart';
/// Parses a string into a corresponding CameraLensDirection.
CameraLensDirection parseCameraLensDirection(String string) {
switch (string) {
case 'front':
return CameraLensDirection.front;
case 'back':
return CameraLensDirection.back;
case 'external':
return CameraLensDirection.external;
}
throw ArgumentError('Unknown CameraLensDirection value');
}
/// Returns the device orientation as a String.
String serializeDeviceOrientation(DeviceOrientation orientation) {
switch (orientation) {
case DeviceOrientation.portraitUp:
return 'portraitUp';
case DeviceOrientation.portraitDown:
return 'portraitDown';
case DeviceOrientation.landscapeRight:
return 'landscapeRight';
case DeviceOrientation.landscapeLeft:
return 'landscapeLeft';
}
}
/// Returns the device orientation for a given String.
DeviceOrientation deserializeDeviceOrientation(String str) {
switch (str) {
case 'portraitUp':
return DeviceOrientation.portraitUp;
case 'portraitDown':
return DeviceOrientation.portraitDown;
case 'landscapeRight':
return DeviceOrientation.landscapeRight;
case 'landscapeLeft':
return DeviceOrientation.landscapeLeft;
default:
throw ArgumentError('"$str" is not a valid DeviceOrientation value');
}
}
| plugins/packages/camera/camera_platform_interface/lib/src/utils/utils.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/lib/src/utils/utils.dart",
"repo_id": "plugins",
"token_count": 510
} | 1,412 |
// 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_platform_interface/camera_platform_interface.dart';
import 'package:camera_platform_interface/src/utils/utils.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('Utility methods', () {
test(
'Should return CameraLensDirection when valid value is supplied when parsing camera lens direction',
() {
expect(
parseCameraLensDirection('back'),
CameraLensDirection.back,
);
expect(
parseCameraLensDirection('front'),
CameraLensDirection.front,
);
expect(
parseCameraLensDirection('external'),
CameraLensDirection.external,
);
});
test(
'Should throw ArgumentException when invalid value is supplied when parsing camera lens direction',
() {
expect(
() => parseCameraLensDirection('test'),
throwsA(isArgumentError),
);
});
test('serializeDeviceOrientation() should serialize correctly', () {
expect(serializeDeviceOrientation(DeviceOrientation.portraitUp),
'portraitUp');
expect(serializeDeviceOrientation(DeviceOrientation.portraitDown),
'portraitDown');
expect(serializeDeviceOrientation(DeviceOrientation.landscapeRight),
'landscapeRight');
expect(serializeDeviceOrientation(DeviceOrientation.landscapeLeft),
'landscapeLeft');
});
test('deserializeDeviceOrientation() should deserialize correctly', () {
expect(deserializeDeviceOrientation('portraitUp'),
DeviceOrientation.portraitUp);
expect(deserializeDeviceOrientation('portraitDown'),
DeviceOrientation.portraitDown);
expect(deserializeDeviceOrientation('landscapeRight'),
DeviceOrientation.landscapeRight);
expect(deserializeDeviceOrientation('landscapeLeft'),
DeviceOrientation.landscapeLeft);
});
});
}
| plugins/packages/camera/camera_platform_interface/test/utils/utils_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/test/utils/utils_test.dart",
"repo_id": "plugins",
"token_count": 777
} | 1,413 |
// 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';
void main() => runApp(const MyApp());
/// App for testing
class MyApp extends StatelessWidget {
/// Default Constructor
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const Directionality(
textDirection: TextDirection.ltr,
child: Text('Testing... Look at the console output for results!'),
);
}
}
| plugins/packages/camera/camera_web/example/lib/main.dart/0 | {
"file_path": "plugins/packages/camera/camera_web/example/lib/main.dart",
"repo_id": "plugins",
"token_count": 179
} | 1,414 |
// 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 'types.dart';
/// An exception thrown when the camera with id [cameraId] reports
/// an initialization, configuration or video streaming error,
/// or enters into an unexpected state.
///
/// This error should be emitted on the `onCameraError` stream
/// of the camera platform.
class CameraWebException implements Exception {
/// Creates a new instance of [CameraWebException]
/// with the given error [cameraId], [code] and [description].
CameraWebException(this.cameraId, this.code, this.description);
/// The id of the camera this exception is associated to.
int cameraId;
/// The error code of this exception.
CameraErrorCode code;
/// The description of this exception.
String description;
@override
String toString() => 'CameraWebException($cameraId, $code, $description)';
}
| plugins/packages/camera/camera_web/lib/src/types/camera_web_exception.dart/0 | {
"file_path": "plugins/packages/camera/camera_web/lib/src/types/camera_web_exception.dart",
"repo_id": "plugins",
"token_count": 249
} | 1,415 |
// 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.
#include "capture_controller.h"
#include <comdef.h>
#include <wincodec.h>
#include <wrl/client.h>
#include <cassert>
#include <chrono>
#include "com_heap_ptr.h"
#include "photo_handler.h"
#include "preview_handler.h"
#include "record_handler.h"
#include "string_utils.h"
#include "texture_handler.h"
namespace camera_windows {
using Microsoft::WRL::ComPtr;
CameraResult GetCameraResult(HRESULT hr) {
if (SUCCEEDED(hr)) {
return CameraResult::kSuccess;
}
return hr == E_ACCESSDENIED ? CameraResult::kAccessDenied
: CameraResult::kError;
}
CaptureControllerImpl::CaptureControllerImpl(
CaptureControllerListener* listener)
: capture_controller_listener_(listener), CaptureController(){};
CaptureControllerImpl::~CaptureControllerImpl() {
ResetCaptureController();
capture_controller_listener_ = nullptr;
};
// static
bool CaptureControllerImpl::EnumerateVideoCaptureDeviceSources(
IMFActivate*** devices, UINT32* count) {
ComPtr<IMFAttributes> attributes;
HRESULT hr = MFCreateAttributes(&attributes, 1);
if (FAILED(hr)) {
return false;
}
hr = attributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
if (FAILED(hr)) {
return false;
}
hr = MFEnumDeviceSources(attributes.Get(), devices, count);
if (FAILED(hr)) {
return false;
}
return true;
}
HRESULT CaptureControllerImpl::CreateDefaultAudioCaptureSource() {
audio_source_ = nullptr;
ComHeapPtr<IMFActivate*> devices;
UINT32 count = 0;
ComPtr<IMFAttributes> attributes;
HRESULT hr = MFCreateAttributes(&attributes, 1);
if (SUCCEEDED(hr)) {
hr = attributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_GUID);
}
if (SUCCEEDED(hr)) {
hr = MFEnumDeviceSources(attributes.Get(), &devices, &count);
}
if (SUCCEEDED(hr) && count > 0) {
ComHeapPtr<wchar_t> audio_device_id;
UINT32 audio_device_id_size;
// Use first audio device.
hr = devices[0]->GetAllocatedString(
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_ENDPOINT_ID, &audio_device_id,
&audio_device_id_size);
if (SUCCEEDED(hr)) {
ComPtr<IMFAttributes> audio_capture_source_attributes;
hr = MFCreateAttributes(&audio_capture_source_attributes, 2);
if (SUCCEEDED(hr)) {
hr = audio_capture_source_attributes->SetGUID(
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_GUID);
}
if (SUCCEEDED(hr)) {
hr = audio_capture_source_attributes->SetString(
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_ENDPOINT_ID,
audio_device_id);
}
if (SUCCEEDED(hr)) {
hr = MFCreateDeviceSource(audio_capture_source_attributes.Get(),
audio_source_.GetAddressOf());
}
}
}
return hr;
}
HRESULT CaptureControllerImpl::CreateVideoCaptureSourceForDevice(
const std::string& video_device_id) {
video_source_ = nullptr;
ComPtr<IMFAttributes> video_capture_source_attributes;
HRESULT hr = MFCreateAttributes(&video_capture_source_attributes, 2);
if (FAILED(hr)) {
return hr;
}
hr = video_capture_source_attributes->SetGUID(
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);
if (FAILED(hr)) {
return hr;
}
hr = video_capture_source_attributes->SetString(
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK,
Utf16FromUtf8(video_device_id).c_str());
if (FAILED(hr)) {
return hr;
}
hr = MFCreateDeviceSource(video_capture_source_attributes.Get(),
video_source_.GetAddressOf());
return hr;
}
HRESULT CaptureControllerImpl::CreateD3DManagerWithDX11Device() {
// TODO: Use existing ANGLE device
HRESULT hr = S_OK;
hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr,
D3D11_CREATE_DEVICE_VIDEO_SUPPORT, nullptr, 0,
D3D11_SDK_VERSION, &dx11_device_, nullptr, nullptr);
if (FAILED(hr)) {
return hr;
}
// Enable multithread protection
ComPtr<ID3D10Multithread> multi_thread;
hr = dx11_device_.As(&multi_thread);
if (FAILED(hr)) {
return hr;
}
multi_thread->SetMultithreadProtected(TRUE);
hr = MFCreateDXGIDeviceManager(&dx_device_reset_token_,
dxgi_device_manager_.GetAddressOf());
if (FAILED(hr)) {
return hr;
}
hr = dxgi_device_manager_->ResetDevice(dx11_device_.Get(),
dx_device_reset_token_);
return hr;
}
HRESULT CaptureControllerImpl::CreateCaptureEngine() {
assert(!video_device_id_.empty());
HRESULT hr = S_OK;
ComPtr<IMFAttributes> attributes;
// Creates capture engine only if not already initialized by test framework
if (!capture_engine_) {
ComPtr<IMFCaptureEngineClassFactory> capture_engine_factory;
hr = CoCreateInstance(CLSID_MFCaptureEngineClassFactory, nullptr,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&capture_engine_factory));
if (FAILED(hr)) {
return hr;
}
// Creates CaptureEngine.
hr = capture_engine_factory->CreateInstance(CLSID_MFCaptureEngine,
IID_PPV_ARGS(&capture_engine_));
if (FAILED(hr)) {
return hr;
}
}
hr = CreateD3DManagerWithDX11Device();
if (FAILED(hr)) {
return hr;
}
// Creates video source only if not already initialized by test framework
if (!video_source_) {
hr = CreateVideoCaptureSourceForDevice(video_device_id_);
if (FAILED(hr)) {
return hr;
}
}
// Creates audio source only if not already initialized by test framework
if (record_audio_ && !audio_source_) {
hr = CreateDefaultAudioCaptureSource();
if (FAILED(hr)) {
return hr;
}
}
if (!capture_engine_callback_handler_) {
capture_engine_callback_handler_ =
ComPtr<CaptureEngineListener>(new CaptureEngineListener(this));
}
hr = MFCreateAttributes(&attributes, 2);
if (FAILED(hr)) {
return hr;
}
hr = attributes->SetUnknown(MF_CAPTURE_ENGINE_D3D_MANAGER,
dxgi_device_manager_.Get());
if (FAILED(hr)) {
return hr;
}
hr = attributes->SetUINT32(MF_CAPTURE_ENGINE_USE_VIDEO_DEVICE_ONLY,
!record_audio_);
if (FAILED(hr)) {
return hr;
}
// Check MF_CAPTURE_ENGINE_INITIALIZED event handling
// for response process.
hr = capture_engine_->Initialize(capture_engine_callback_handler_.Get(),
attributes.Get(), audio_source_.Get(),
video_source_.Get());
return hr;
}
void CaptureControllerImpl::ResetCaptureController() {
if (record_handler_ && record_handler_->CanStop()) {
if (record_handler_->IsContinuousRecording()) {
StopRecord();
} else if (record_handler_->IsTimedRecording()) {
StopTimedRecord();
}
}
if (preview_handler_) {
StopPreview();
}
// Shuts down the media foundation platform object.
// Releases all resources including threads.
// Application should call MFShutdown the same number of times as MFStartup
if (media_foundation_started_) {
MFShutdown();
}
// States
media_foundation_started_ = false;
capture_engine_state_ = CaptureEngineState::kNotInitialized;
preview_frame_width_ = 0;
preview_frame_height_ = 0;
capture_engine_callback_handler_ = nullptr;
capture_engine_ = nullptr;
audio_source_ = nullptr;
video_source_ = nullptr;
base_preview_media_type_ = nullptr;
base_capture_media_type_ = nullptr;
if (dxgi_device_manager_) {
dxgi_device_manager_->ResetDevice(dx11_device_.Get(),
dx_device_reset_token_);
}
dxgi_device_manager_ = nullptr;
dx11_device_ = nullptr;
record_handler_ = nullptr;
preview_handler_ = nullptr;
photo_handler_ = nullptr;
texture_handler_ = nullptr;
}
bool CaptureControllerImpl::InitCaptureDevice(
flutter::TextureRegistrar* texture_registrar, const std::string& device_id,
bool record_audio, ResolutionPreset resolution_preset) {
assert(capture_controller_listener_);
if (IsInitialized()) {
capture_controller_listener_->OnCreateCaptureEngineFailed(
CameraResult::kError, "Capture device already initialized");
return false;
} else if (capture_engine_state_ == CaptureEngineState::kInitializing) {
capture_controller_listener_->OnCreateCaptureEngineFailed(
CameraResult::kError, "Capture device already initializing");
return false;
}
capture_engine_state_ = CaptureEngineState::kInitializing;
resolution_preset_ = resolution_preset;
record_audio_ = record_audio;
texture_registrar_ = texture_registrar;
video_device_id_ = device_id;
// MFStartup must be called before using Media Foundation.
if (!media_foundation_started_) {
HRESULT hr = MFStartup(MF_VERSION);
if (FAILED(hr)) {
capture_controller_listener_->OnCreateCaptureEngineFailed(
GetCameraResult(hr), "Failed to create camera");
ResetCaptureController();
return false;
}
media_foundation_started_ = true;
}
HRESULT hr = CreateCaptureEngine();
if (FAILED(hr)) {
capture_controller_listener_->OnCreateCaptureEngineFailed(
GetCameraResult(hr), "Failed to create camera");
ResetCaptureController();
return false;
}
return true;
}
void CaptureControllerImpl::TakePicture(const std::string& file_path) {
assert(capture_engine_callback_handler_);
assert(capture_engine_);
if (!IsInitialized()) {
return OnPicture(CameraResult::kError, "Not initialized");
}
HRESULT hr = S_OK;
if (!base_capture_media_type_) {
// Enumerates mediatypes and finds media type for video capture.
hr = FindBaseMediaTypes();
if (FAILED(hr)) {
return OnPicture(GetCameraResult(hr),
"Failed to initialize photo capture");
}
}
if (!photo_handler_) {
photo_handler_ = std::make_unique<PhotoHandler>();
} else if (photo_handler_->IsTakingPhoto()) {
return OnPicture(CameraResult::kError, "Photo already requested");
}
// Check MF_CAPTURE_ENGINE_PHOTO_TAKEN event handling
// for response process.
hr = photo_handler_->TakePhoto(file_path, capture_engine_.Get(),
base_capture_media_type_.Get());
if (FAILED(hr)) {
// Destroy photo handler on error cases to make sure state is resetted.
photo_handler_ = nullptr;
return OnPicture(GetCameraResult(hr), "Failed to take photo");
}
}
uint32_t CaptureControllerImpl::GetMaxPreviewHeight() const {
switch (resolution_preset_) {
case ResolutionPreset::kLow:
return 240;
break;
case ResolutionPreset::kMedium:
return 480;
break;
case ResolutionPreset::kHigh:
return 720;
break;
case ResolutionPreset::kVeryHigh:
return 1080;
break;
case ResolutionPreset::kUltraHigh:
return 2160;
break;
case ResolutionPreset::kMax:
case ResolutionPreset::kAuto:
default:
// no limit.
return 0xffffffff;
break;
}
}
// Finds best media type for given source stream index and max height;
bool FindBestMediaType(DWORD source_stream_index, IMFCaptureSource* source,
IMFMediaType** target_media_type, uint32_t max_height,
uint32_t* target_frame_width,
uint32_t* target_frame_height,
float minimum_accepted_framerate = 15.f) {
assert(source);
ComPtr<IMFMediaType> media_type;
uint32_t best_width = 0;
uint32_t best_height = 0;
float best_framerate = 0.f;
// Loop native media types.
for (int i = 0;; i++) {
if (FAILED(source->GetAvailableDeviceMediaType(
source_stream_index, i, media_type.GetAddressOf()))) {
break;
}
uint32_t frame_rate_numerator, frame_rate_denominator;
if (FAILED(MFGetAttributeRatio(media_type.Get(), MF_MT_FRAME_RATE,
&frame_rate_numerator,
&frame_rate_denominator)) ||
!frame_rate_denominator) {
continue;
}
float frame_rate =
static_cast<float>(frame_rate_numerator) / frame_rate_denominator;
if (frame_rate < minimum_accepted_framerate) {
continue;
}
uint32_t frame_width;
uint32_t frame_height;
if (SUCCEEDED(MFGetAttributeSize(media_type.Get(), MF_MT_FRAME_SIZE,
&frame_width, &frame_height))) {
// Update target mediatype
if (frame_height <= max_height &&
(best_width < frame_width || best_height < frame_height ||
best_framerate < frame_rate)) {
media_type.CopyTo(target_media_type);
best_width = frame_width;
best_height = frame_height;
best_framerate = frame_rate;
}
}
}
if (target_frame_width && target_frame_height) {
*target_frame_width = best_width;
*target_frame_height = best_height;
}
return *target_media_type != nullptr;
}
HRESULT CaptureControllerImpl::FindBaseMediaTypes() {
if (!IsInitialized()) {
return E_FAIL;
}
ComPtr<IMFCaptureSource> source;
HRESULT hr = capture_engine_->GetSource(&source);
if (FAILED(hr)) {
return hr;
}
// Find base media type for previewing.
if (!FindBestMediaType(
(DWORD)MF_CAPTURE_ENGINE_PREFERRED_SOURCE_STREAM_FOR_VIDEO_PREVIEW,
source.Get(), base_preview_media_type_.GetAddressOf(),
GetMaxPreviewHeight(), &preview_frame_width_,
&preview_frame_height_)) {
return E_FAIL;
}
// Find base media type for record and photo capture.
if (!FindBestMediaType(
(DWORD)MF_CAPTURE_ENGINE_PREFERRED_SOURCE_STREAM_FOR_VIDEO_RECORD,
source.Get(), base_capture_media_type_.GetAddressOf(), 0xffffffff,
nullptr, nullptr)) {
return E_FAIL;
}
return S_OK;
}
void CaptureControllerImpl::StartRecord(const std::string& file_path,
int64_t max_video_duration_ms) {
assert(capture_engine_);
if (!IsInitialized()) {
return OnRecordStarted(CameraResult::kError,
"Camera not initialized. Camera should be "
"disposed and reinitialized.");
}
HRESULT hr = S_OK;
if (!base_capture_media_type_) {
// Enumerates mediatypes and finds media type for video capture.
hr = FindBaseMediaTypes();
if (FAILED(hr)) {
return OnRecordStarted(GetCameraResult(hr),
"Failed to initialize video recording");
}
}
if (!record_handler_) {
record_handler_ = std::make_unique<RecordHandler>(record_audio_);
} else if (!record_handler_->CanStart()) {
return OnRecordStarted(
CameraResult::kError,
"Recording cannot be started. Previous recording must be stopped "
"first.");
}
// Check MF_CAPTURE_ENGINE_RECORD_STARTED event handling for response
// process.
hr = record_handler_->StartRecord(file_path, max_video_duration_ms,
capture_engine_.Get(),
base_capture_media_type_.Get());
if (FAILED(hr)) {
// Destroy record handler on error cases to make sure state is resetted.
record_handler_ = nullptr;
return OnRecordStarted(GetCameraResult(hr),
"Failed to start video recording");
}
}
void CaptureControllerImpl::StopRecord() {
assert(capture_controller_listener_);
if (!IsInitialized()) {
return OnRecordStopped(CameraResult::kError,
"Camera not initialized. Camera should be "
"disposed and reinitialized.");
}
if (!record_handler_ && !record_handler_->CanStop()) {
return OnRecordStopped(CameraResult::kError,
"Recording cannot be stopped.");
}
// Check MF_CAPTURE_ENGINE_RECORD_STOPPED event handling for response
// process.
HRESULT hr = record_handler_->StopRecord(capture_engine_.Get());
if (FAILED(hr)) {
return OnRecordStopped(GetCameraResult(hr),
"Failed to stop video recording");
}
}
// Stops timed recording. Called internally when requested time is passed.
// Check MF_CAPTURE_ENGINE_RECORD_STOPPED event handling for response process.
void CaptureControllerImpl::StopTimedRecord() {
assert(capture_controller_listener_);
if (!record_handler_ || !record_handler_->IsTimedRecording()) {
return;
}
HRESULT hr = record_handler_->StopRecord(capture_engine_.Get());
if (FAILED(hr)) {
// Destroy record handler on error cases to make sure state is resetted.
record_handler_ = nullptr;
return capture_controller_listener_->OnVideoRecordFailed(
GetCameraResult(hr), "Failed to record video");
}
}
// Starts capturing preview frames using preview handler
// After first frame is captured, OnPreviewStarted is called
void CaptureControllerImpl::StartPreview() {
assert(capture_engine_callback_handler_);
assert(capture_engine_);
assert(texture_handler_);
if (!IsInitialized() || !texture_handler_) {
return OnPreviewStarted(CameraResult::kError,
"Camera not initialized. Camera should be "
"disposed and reinitialized.");
}
HRESULT hr = S_OK;
if (!base_preview_media_type_) {
// Enumerates mediatypes and finds media type for video capture.
hr = FindBaseMediaTypes();
if (FAILED(hr)) {
return OnPreviewStarted(GetCameraResult(hr),
"Failed to initialize video preview");
}
}
texture_handler_->UpdateTextureSize(preview_frame_width_,
preview_frame_height_);
// TODO(loic-sharma): This does not handle duplicate calls properly.
// See: https://github.com/flutter/flutter/issues/108404
if (!preview_handler_) {
preview_handler_ = std::make_unique<PreviewHandler>();
} else if (preview_handler_->IsInitialized()) {
return OnPreviewStarted(CameraResult::kSuccess, "");
} else {
return OnPreviewStarted(CameraResult::kError, "Preview already exists");
}
// Check MF_CAPTURE_ENGINE_PREVIEW_STARTED event handling for response
// process.
hr = preview_handler_->StartPreview(capture_engine_.Get(),
base_preview_media_type_.Get(),
capture_engine_callback_handler_.Get());
if (FAILED(hr)) {
// Destroy preview handler on error cases to make sure state is resetted.
preview_handler_ = nullptr;
return OnPreviewStarted(GetCameraResult(hr),
"Failed to start video preview");
}
}
// Stops preview. Called by destructor
// Use PausePreview and ResumePreview methods to for
// pausing and resuming the preview.
// Check MF_CAPTURE_ENGINE_PREVIEW_STOPPED event handling for response
// process.
HRESULT CaptureControllerImpl::StopPreview() {
assert(capture_engine_);
if (!IsInitialized() || !preview_handler_) {
return S_OK;
}
// Requests to stop preview.
return preview_handler_->StopPreview(capture_engine_.Get());
}
// Marks preview as paused.
// When preview is paused, captured frames are not processed for preview
// and flutter texture is not updated
void CaptureControllerImpl::PausePreview() {
assert(capture_controller_listener_);
if (!preview_handler_ || !preview_handler_->IsInitialized()) {
return capture_controller_listener_->OnPausePreviewFailed(
CameraResult::kError, "Preview not started");
}
if (preview_handler_->PausePreview()) {
capture_controller_listener_->OnPausePreviewSucceeded();
} else {
capture_controller_listener_->OnPausePreviewFailed(
CameraResult::kError, "Failed to pause preview");
}
}
// Marks preview as not paused.
// When preview is not paused, captured frames are processed for preview
// and flutter texture is updated.
void CaptureControllerImpl::ResumePreview() {
assert(capture_controller_listener_);
if (!preview_handler_ || !preview_handler_->IsInitialized()) {
return capture_controller_listener_->OnResumePreviewFailed(
CameraResult::kError, "Preview not started");
}
if (preview_handler_->ResumePreview()) {
capture_controller_listener_->OnResumePreviewSucceeded();
} else {
capture_controller_listener_->OnResumePreviewFailed(
CameraResult::kError, "Failed to pause preview");
}
}
// Handles capture engine events.
// Called via IMFCaptureEngineOnEventCallback implementation.
// Implements CaptureEngineObserver::OnEvent.
void CaptureControllerImpl::OnEvent(IMFMediaEvent* event) {
if (!IsInitialized() &&
capture_engine_state_ != CaptureEngineState::kInitializing) {
return;
}
GUID extended_type_guid;
if (SUCCEEDED(event->GetExtendedType(&extended_type_guid))) {
std::string error;
HRESULT event_hr;
if (FAILED(event->GetStatus(&event_hr))) {
return;
}
if (FAILED(event_hr)) {
// Reads system error
_com_error err(event_hr);
error = Utf8FromUtf16(err.ErrorMessage());
}
CameraResult event_result = GetCameraResult(event_hr);
if (extended_type_guid == MF_CAPTURE_ENGINE_ERROR) {
OnCaptureEngineError(event_result, error);
} else if (extended_type_guid == MF_CAPTURE_ENGINE_INITIALIZED) {
OnCaptureEngineInitialized(event_result, error);
} else if (extended_type_guid == MF_CAPTURE_ENGINE_PREVIEW_STARTED) {
// Preview is marked as started after first frame is captured.
// This is because, CaptureEngine might inform that preview is started
// even if error is thrown right after.
} else if (extended_type_guid == MF_CAPTURE_ENGINE_PREVIEW_STOPPED) {
OnPreviewStopped(event_result, error);
} else if (extended_type_guid == MF_CAPTURE_ENGINE_RECORD_STARTED) {
OnRecordStarted(event_result, error);
} else if (extended_type_guid == MF_CAPTURE_ENGINE_RECORD_STOPPED) {
OnRecordStopped(event_result, error);
} else if (extended_type_guid == MF_CAPTURE_ENGINE_PHOTO_TAKEN) {
OnPicture(event_result, error);
} else if (extended_type_guid == MF_CAPTURE_ENGINE_CAMERA_STREAM_BLOCKED) {
// TODO: Inform capture state to flutter.
} else if (extended_type_guid ==
MF_CAPTURE_ENGINE_CAMERA_STREAM_UNBLOCKED) {
// TODO: Inform capture state to flutter.
}
}
}
// Handles Picture event and informs CaptureControllerListener.
void CaptureControllerImpl::OnPicture(CameraResult result,
const std::string& error) {
if (result == CameraResult::kSuccess && photo_handler_) {
if (capture_controller_listener_) {
std::string path = photo_handler_->GetPhotoPath();
capture_controller_listener_->OnTakePictureSucceeded(path);
}
photo_handler_->OnPhotoTaken();
} else {
if (capture_controller_listener_) {
capture_controller_listener_->OnTakePictureFailed(result, error);
}
// Destroy photo handler on error cases to make sure state is resetted.
photo_handler_ = nullptr;
}
}
// Handles CaptureEngineInitialized event and informs
// CaptureControllerListener.
void CaptureControllerImpl::OnCaptureEngineInitialized(
CameraResult result, const std::string& error) {
if (capture_controller_listener_) {
if (result != CameraResult::kSuccess) {
capture_controller_listener_->OnCreateCaptureEngineFailed(
result, "Failed to initialize capture engine");
ResetCaptureController();
return;
}
// Create texture handler and register new texture.
texture_handler_ = std::make_unique<TextureHandler>(texture_registrar_);
int64_t texture_id = texture_handler_->RegisterTexture();
if (texture_id >= 0) {
capture_controller_listener_->OnCreateCaptureEngineSucceeded(texture_id);
capture_engine_state_ = CaptureEngineState::kInitialized;
} else {
capture_controller_listener_->OnCreateCaptureEngineFailed(
CameraResult::kError, "Failed to create texture_id");
// Reset state
ResetCaptureController();
}
}
}
// Handles CaptureEngineError event and informs CaptureControllerListener.
void CaptureControllerImpl::OnCaptureEngineError(CameraResult result,
const std::string& error) {
if (capture_controller_listener_) {
capture_controller_listener_->OnCaptureError(result, error);
}
// TODO: If MF_CAPTURE_ENGINE_ERROR is returned,
// should capture controller be reinitialized automatically?
}
// Handles PreviewStarted event and informs CaptureControllerListener.
// This should be called only after first frame has been received or
// in error cases.
void CaptureControllerImpl::OnPreviewStarted(CameraResult result,
const std::string& error) {
if (preview_handler_ && result == CameraResult::kSuccess) {
preview_handler_->OnPreviewStarted();
} else {
// Destroy preview handler on error cases to make sure state is resetted.
preview_handler_ = nullptr;
}
if (capture_controller_listener_) {
if (result == CameraResult::kSuccess && preview_frame_width_ > 0 &&
preview_frame_height_ > 0) {
capture_controller_listener_->OnStartPreviewSucceeded(
preview_frame_width_, preview_frame_height_);
} else {
capture_controller_listener_->OnStartPreviewFailed(result, error);
}
}
};
// Handles PreviewStopped event.
void CaptureControllerImpl::OnPreviewStopped(CameraResult result,
const std::string& error) {
// Preview handler is destroyed if preview is stopped as it
// does not have any use anymore.
preview_handler_ = nullptr;
};
// Handles RecordStarted event and informs CaptureControllerListener.
void CaptureControllerImpl::OnRecordStarted(CameraResult result,
const std::string& error) {
if (result == CameraResult::kSuccess && record_handler_) {
record_handler_->OnRecordStarted();
if (capture_controller_listener_) {
capture_controller_listener_->OnStartRecordSucceeded();
}
} else {
if (capture_controller_listener_) {
capture_controller_listener_->OnStartRecordFailed(result, error);
}
// Destroy record handler on error cases to make sure state is resetted.
record_handler_ = nullptr;
}
};
// Handles RecordStopped event and informs CaptureControllerListener.
void CaptureControllerImpl::OnRecordStopped(CameraResult result,
const std::string& error) {
if (capture_controller_listener_ && record_handler_) {
// Always calls OnStopRecord listener methods
// to handle separate stop record request for timed records.
if (result == CameraResult::kSuccess) {
std::string path = record_handler_->GetRecordPath();
capture_controller_listener_->OnStopRecordSucceeded(path);
if (record_handler_->IsTimedRecording()) {
capture_controller_listener_->OnVideoRecordSucceeded(
path, (record_handler_->GetRecordedDuration() / 1000));
}
} else {
capture_controller_listener_->OnStopRecordFailed(result, error);
if (record_handler_->IsTimedRecording()) {
capture_controller_listener_->OnVideoRecordFailed(result, error);
}
}
}
if (result == CameraResult::kSuccess && record_handler_) {
record_handler_->OnRecordStopped();
} else {
// Destroy record handler on error cases to make sure state is resetted.
record_handler_ = nullptr;
}
}
// Updates texture handlers buffer with given data.
// Called via IMFCaptureEngineOnSampleCallback implementation.
// Implements CaptureEngineObserver::UpdateBuffer.
bool CaptureControllerImpl::UpdateBuffer(uint8_t* buffer,
uint32_t data_length) {
if (!texture_handler_) {
return false;
}
return texture_handler_->UpdateBuffer(buffer, data_length);
}
// Handles capture time update from each processed frame.
// Stops timed recordings if requested recording duration has passed.
// Called via IMFCaptureEngineOnSampleCallback implementation.
// Implements CaptureEngineObserver::UpdateCaptureTime.
void CaptureControllerImpl::UpdateCaptureTime(uint64_t capture_time_us) {
if (!IsInitialized()) {
return;
}
if (preview_handler_ && preview_handler_->IsStarting()) {
// Informs that first frame is captured successfully and preview has
// started.
OnPreviewStarted(CameraResult::kSuccess, "");
}
// Checks if max_video_duration_ms is passed.
if (record_handler_) {
record_handler_->UpdateRecordingTime(capture_time_us);
if (record_handler_->ShouldStopTimedRecording()) {
StopTimedRecord();
}
}
}
} // namespace camera_windows
| plugins/packages/camera/camera_windows/windows/capture_controller.cpp/0 | {
"file_path": "plugins/packages/camera/camera_windows/windows/capture_controller.cpp",
"repo_id": "plugins",
"token_count": 11413
} | 1,416 |
// 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_STRING_UTILS_H_
#define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_STRING_UTILS_H_
#include <shobjidl.h>
#include <string>
namespace camera_windows {
// Converts the given UTF-16 string to UTF-8.
std::string Utf8FromUtf16(const std::wstring& utf16_string);
// Converts the given UTF-8 string to UTF-16.
std::wstring Utf16FromUtf8(const std::string& utf8_string);
} // namespace camera_windows
#endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_STRING_UTILS_H_
| plugins/packages/camera/camera_windows/windows/string_utils.h/0 | {
"file_path": "plugins/packages/camera/camera_windows/windows/string_utils.h",
"repo_id": "plugins",
"token_count": 241
} | 1,417 |
<?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="DefaultLocale"
message="Implicitly using the default locale is a common source of bugs: Use `String.format(Locale, ...)` instead"
errorLine1=" String.format("
errorLine2=" ^">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="180"
column="17"/>
</issue>
<issue
id="DefaultLocale"
message="Implicitly using the default locale is a common source of bugs: Use `String.format(Locale, ...)` instead"
errorLine1=" String.format("
errorLine2=" ^">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="186"
column="17"/>
</issue>
<issue
id="DefaultLocale"
message="Implicitly using the default locale is a common source of bugs: Use `String.format(Locale, ...)` instead"
errorLine1=" String.format("
errorLine2=" ^">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java"
line="192"
column="17"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" && Objects.equals(errorObject.message, this.message)"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/ErrorObject.java"
line="50"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" && Objects.equals(errorObject.data, this.data);"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/ErrorObject.java"
line="51"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#hashCode`"
errorLine1=" hash = hash * 31 + Objects.hashCode(message);"
errorLine2=" ~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/ErrorObject.java"
line="60"
column="32"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#hashCode`"
errorLine1=" hash = hash * 31 + Objects.hashCode(data);"
errorLine2=" ~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/ErrorObject.java"
line="61"
column="32"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" return Objects.equals(isolate.id, this.id)"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetVmResponse.java"
line="114"
column="24"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" && Objects.equals(isolate.runnable, this.runnable)"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetVmResponse.java"
line="115"
column="24"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" && Objects.equals(isolate.extensionRpcList, this.extensionRpcList);"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetVmResponse.java"
line="116"
column="24"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#hash`"
errorLine1=" return Objects.hash(id, runnable, extensionRpcList);"
errorLine2=" ~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetVmResponse.java"
line="124"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" return Objects.equals(this.name, widgetProperty.name)"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetWidgetDiagnosticsResponse.java"
line="178"
column="24"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" && Objects.equals(this.value, widgetProperty.value)"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetWidgetDiagnosticsResponse.java"
line="179"
column="24"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" && Objects.equals(this.description, widgetProperty.description);"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetWidgetDiagnosticsResponse.java"
line="180"
column="24"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#hash`"
errorLine1=" return Objects.hash(name, value, description);"
errorLine2=" ~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetWidgetDiagnosticsResponse.java"
line="186"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" return Objects.equals(objRequest.id, this.id)"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="136"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" && Objects.equals(objRequest.method, this.method)"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="137"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" && Objects.equals(objRequest.params, this.params);"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="138"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#hashCode`"
errorLine1=" int hash = Objects.hashCode(id);"
errorLine2=" ~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="146"
column="24"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#hashCode`"
errorLine1=" hash = hash * 31 + Objects.hashCode(method);"
errorLine2=" ~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="147"
column="32"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#hashCode`"
errorLine1=" hash = hash * 31 + Objects.hashCode(params);"
errorLine2=" ~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java"
line="148"
column="32"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" return Objects.equals(objResponse.id, this.id)"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="141"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" && Objects.equals(objResponse.result, this.result)"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="142"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" && Objects.equals(objResponse.error, this.error);"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="143"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#hashCode`"
errorLine1=" int hash = Objects.hashCode(id);"
errorLine2=" ~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="151"
column="24"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#hashCode`"
errorLine1=" hash = hash * 31 + Objects.hashCode(result);"
errorLine2=" ~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="152"
column="32"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#hashCode`"
errorLine1=" hash = hash * 31 + Objects.hashCode(error);"
errorLine2=" ~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java"
line="153"
column="32"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" return Objects.equals(actionId, otherAction.actionId);"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/api/SyntheticAction.java"
line="56"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#hashCode`"
errorLine1=" return Objects.hashCode(actionId);"
errorLine2=" ~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/api/SyntheticAction.java"
line="64"
column="20"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" return Objects.equals(widget.valueKey, this.valueKey)"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/model/WidgetInfo.java"
line="78"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" && Objects.equals(widget.runtimeType, this.runtimeType)"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/model/WidgetInfo.java"
line="79"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" && Objects.equals(widget.text, this.text)"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/model/WidgetInfo.java"
line="80"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#equals`"
errorLine1=" && Objects.equals(widget.tooltip, this.tooltip);"
errorLine2=" ~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/model/WidgetInfo.java"
line="81"
column="22"/>
</issue>
<issue
id="NewApi"
message="Call requires API level 19 (current min is 16): `java.util.Objects#hash`"
errorLine1=" return Objects.hash(valueKey, runtimeType, text, tooltip);"
errorLine2=" ~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/model/WidgetInfo.java"
line="89"
column="20"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
errorLine1=" ((io.flutter.embedding.android.FlutterView) flutterView).getAttachedFlutterEngine();"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmServiceUtil.java"
line="83"
column="68"/>
</issue>
</issues>
| plugins/packages/espresso/android/lint-baseline.xml/0 | {
"file_path": "plugins/packages/espresso/android/lint-baseline.xml",
"repo_id": "plugins",
"token_count": 7782
} | 1,418 |
// 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 androidx.test.espresso.flutter.api;
import static androidx.test.espresso.flutter.common.Constants.DEFAULT_INTERACTION_TIMEOUT;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.Objects;
import javax.annotation.Nonnull;
/**
* Base Flutter synthetic action.
*
* <p>A synthetic action is not a real gesture event issued to the Android system, rather it's an
* action that's performed via Flutter engine. It's supposed to be used for complex interactions or
* those that are brittle if performed through Android system. Most of the actions should be
* associated with a {@link WidgetMatcher}, but some may not, e.g. an action that checks the
* rendering status of the entire {@link io.flutter.view.FlutterView}.
*/
@Beta
public abstract class SyntheticAction {
@Expose
@SerializedName("command")
protected String actionId;
@Expose
@SerializedName("timeout")
protected long timeOutInMillis;
protected SyntheticAction(@Nonnull String actionId) {
this(actionId, DEFAULT_INTERACTION_TIMEOUT.toMillis());
}
protected SyntheticAction(@Nonnull String actionId, long timeOutInMillis) {
this.actionId = checkNotNull(actionId);
this.timeOutInMillis = timeOutInMillis;
}
@Override
public String toString() {
return actionId;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (obj instanceof SyntheticAction) {
SyntheticAction otherAction = (SyntheticAction) obj;
return Objects.equals(actionId, otherAction.actionId);
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hashCode(actionId);
}
}
| plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/api/SyntheticAction.java/0 | {
"file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/api/SyntheticAction.java",
"repo_id": "plugins",
"token_count": 620
} | 1,419 |
// 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 androidx.test.espresso.flutter.internal.jsonrpc.message;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.isNullOrEmpty;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import java.util.Objects;
import javax.annotation.Nullable;
/**
* JSON-RPC 2.0 request object.
*
* <p>See https://www.jsonrpc.org/specification for detailed specification.
*/
public final class JsonRpcRequest {
private static final Gson gson = new Gson();
private static final String JSON_RPC_VERSION = "2.0";
/** Specifying the version of the JSON-RPC protocol. Must be "2.0". */
@SerializedName("jsonrpc")
private final String version;
/**
* An identifier of the request. Could be String, a number, or null. In this implementation, we
* always use String as the type. If null, this is a notification and no response is required.
*/
@Nullable private final String id;
/** A String containing the name of the method to be invoked. */
private final String method;
/** Parameter values to be used during the invocation of the method. */
private JsonObject params;
/**
* Deserializes the given Json string to a {@code JsonRpcRequest} object.
*
* @param jsonString the string from which the object is to be deserialized.
* @return the deserialized object.
*/
public static JsonRpcRequest fromJson(String jsonString) {
checkArgument(!isNullOrEmpty(jsonString), "Json string cannot be null or empty.");
JsonRpcRequest request = gson.fromJson(jsonString, JsonRpcRequest.class);
checkState(JSON_RPC_VERSION.equals(request.getVersion()), "JSON-RPC version must be 2.0.");
checkState(
!isNullOrEmpty(request.getMethod()), "JSON-RPC request must contain the method field.");
return request;
}
/**
* Constructs with the given method name. The JSON-RPC version will be defaulted to "2.0".
*
* @param method the method name of this request.
*/
private JsonRpcRequest(String method) {
this(null, method);
}
/**
* Constructs with the given id and method name. The JSON-RPC version will be defaulted to "2.0".
*
* @param id the id of this request.
* @param method the method name of this request.
*/
private JsonRpcRequest(@Nullable String id, String method) {
this.version = JSON_RPC_VERSION;
this.id = id;
this.method = checkNotNull(method, "JSON-RPC request method cannot be null.");
}
/**
* Gets the JSON-RPC version.
*
* @return the JSON-RPC version. Should always be "2.0".
*/
public String getVersion() {
return version;
}
/**
* Gets the id of this JSON-RPC request.
*
* @return the id of this request. Returns null if this is a notification request.
*/
public String getId() {
return id;
}
/**
* Gets the method name of this JSON-RPC request.
*
* @return the method name.
*/
public String getMethod() {
return method;
}
/** Gets the params used in this request. */
public JsonObject getParams() {
return params;
}
/**
* Serializes this object to its equivalent Json representation.
*
* @return the Json representation of this object.
*/
public String toJson() {
return gson.toJson(this);
}
/**
* Equivalent to {@link #toJson()}.
*
* @return the Json representation of this object.
*/
@Override
public String toString() {
return toJson();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof JsonRpcRequest) {
JsonRpcRequest objRequest = (JsonRpcRequest) obj;
return Objects.equals(objRequest.id, this.id)
&& Objects.equals(objRequest.method, this.method)
&& Objects.equals(objRequest.params, this.params);
} else {
return false;
}
}
@Override
public int hashCode() {
int hash = Objects.hashCode(id);
hash = hash * 31 + Objects.hashCode(method);
hash = hash * 31 + Objects.hashCode(params);
return hash;
}
/** Builder for {@link JsonRpcRequest}. */
public static class Builder {
/** The request id. Could be null if the request is a notification. */
@Nullable private String id;
/** A String containing the name of the method to be invoked. */
private String method;
/** Parameter values to be used during the invocation of the method. */
private JsonObject params = new JsonObject();
/** Empty constructor. */
public Builder() {}
/**
* Constructs an instance with the given method name.
*
* @param method the method name of this request builder.
*/
public Builder(String method) {
this.method = method;
}
/** Sets the id of this request builder. */
public Builder setId(@Nullable String id) {
this.id = id;
return this;
}
/** Sets the method name of this request builder. */
public Builder setMethod(String method) {
this.method = method;
return this;
}
/** Sets the params of this request builder. */
public Builder setParams(JsonObject params) {
this.params = params;
return this;
}
/** Sugar method to add a {@code String} param to this request builder. */
public Builder addParam(String tag, String value) {
params.addProperty(tag, value);
return this;
}
/** Sugar method to add an integer param to this request builder. */
public Builder addParam(String tag, int value) {
params.addProperty(tag, value);
return this;
}
/** Sugar method to add a {@code boolean} param to this request builder. */
public Builder addParam(String tag, boolean value) {
params.addProperty(tag, value);
return this;
}
/** Builds and returns a {@code JsonRpcRequest} instance out of this builder. */
public JsonRpcRequest build() {
JsonRpcRequest request = new JsonRpcRequest(id, method);
if (params != null && params.size() != 0) {
request.params = this.params;
}
return request;
}
}
}
| plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java/0 | {
"file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcRequest.java",
"repo_id": "plugins",
"token_count": 2150
} | 1,420 |
// 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 androidx.test.espresso.flutter.matcher;
import android.view.View;
import androidx.test.espresso.flutter.api.WidgetMatcher;
import androidx.test.espresso.flutter.model.WidgetInfo;
import io.flutter.embedding.android.FlutterView;
import javax.annotation.Nonnull;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
/** A collection of matchers that match a Flutter view or Flutter widgets. */
public final class FlutterMatchers {
/**
* Returns a matcher that matches a {@link FlutterView} or a legacy {@code
* io.flutter.view.FlutterView}.
*/
public static Matcher<View> isFlutterView() {
return new IsFlutterViewMatcher();
}
/**
* Returns a matcher that matches a Flutter widget's tooltip.
*
* @param tooltip the tooltip String to match. Cannot be {@code null}.
*/
public static WidgetMatcher withTooltip(@Nonnull String tooltip) {
return new WithTooltipMatcher(tooltip);
}
/**
* Returns a matcher that matches a Flutter widget's value key.
*
* @param valueKey the value key String to match. Cannot be {@code null}.
*/
public static WidgetMatcher withValueKey(@Nonnull String valueKey) {
return new WithValueKeyMatcher(valueKey);
}
/**
* Returns a matcher that matches a Flutter widget's runtime type.
*
* <p>Usage:
*
* <p>{@code withType("TextField")} can be used to match a Flutter <a
* href="https://api.flutter.dev/flutter/material/TextField-class.html">TextField</a> widget.
*
* @param type the type String to match. Cannot be {@code null}.
*/
public static WidgetMatcher withType(@Nonnull String type) {
return new WithTypeMatcher(type);
}
/**
* Returns a matcher that matches a Flutter widget's text.
*
* @param text the text String to match. Cannot be {@code null}.
*/
public static WidgetMatcher withText(@Nonnull String text) {
return new WithTextMatcher(text);
}
/**
* Returns a matcher that matches a Flutter widget based on the given ancestor matcher.
*
* @param ancestorMatcher the ancestor to match on. Cannot be null.
* @param widgetMatcher the widget to match on. Cannot be null.
*/
public static WidgetMatcher isDescendantOf(
@Nonnull WidgetMatcher ancestorMatcher, @Nonnull WidgetMatcher widgetMatcher) {
return new IsDescendantOfMatcher(ancestorMatcher, widgetMatcher);
}
/**
* Returns a matcher that checks the existence of a Flutter widget.
*
* <p>Note, this matcher only guarantees that the widget exists in Flutter's widget tree, but not
* necessarily displayed on screen, e.g. the widget is in the cache extend of a Scrollable, but
* not scrolled onto the screen.
*/
public static Matcher<WidgetInfo> isExisting() {
return new IsExistingMatcher();
}
static final class IsFlutterViewMatcher extends TypeSafeMatcher<View> {
private IsFlutterViewMatcher() {}
@Override
public void describeTo(Description description) {
description.appendText("is a FlutterView");
}
@SuppressWarnings("deprecation")
@Override
public boolean matchesSafely(View flutterView) {
return flutterView instanceof FlutterView
|| (flutterView instanceof io.flutter.view.FlutterView);
}
}
}
| plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/matcher/FlutterMatchers.java/0 | {
"file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/matcher/FlutterMatchers.java",
"repo_id": "plugins",
"token_count": 1115
} | 1,421 |
name: espresso_example
description: Demonstrates how to use the espresso plugin.
publish_to: none
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
dev_dependencies:
espresso:
# When depending on this package from a real application you should use:
# espresso: ^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: ../
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| plugins/packages/espresso/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/espresso/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 242
} | 1,422 |
// 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 "FFSFileSelectorPlugin.h"
#import "FFSFileSelectorPlugin_Test.h"
#import "messages.g.h"
#import <objc/runtime.h>
@implementation FFSFileSelectorPlugin
#pragma mark - FFSFileSelectorApi
- (void)openFileSelectorWithConfig:(FFSFileSelectorConfig *)config
completion:(void (^)(NSArray<NSString *> *_Nullable,
FlutterError *_Nullable))completion {
UIDocumentPickerViewController *documentPicker =
self.documentPickerViewControllerOverride
?: [[UIDocumentPickerViewController alloc]
initWithDocumentTypes:config.utis
inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
if (@available(iOS 11.0, *)) {
documentPicker.allowsMultipleSelection = config.allowMultiSelection.boolValue;
}
UIViewController *presentingVC =
self.presentingViewControllerOverride
?: UIApplication.sharedApplication.delegate.window.rootViewController;
if (presentingVC) {
objc_setAssociatedObject(documentPicker, @selector(openFileSelectorWithConfig:completion:),
completion, OBJC_ASSOCIATION_COPY_NONATOMIC);
[presentingVC presentViewController:documentPicker animated:YES completion:nil];
} else {
completion(nil, [FlutterError errorWithCode:@"error"
message:@"Missing root view controller."
details:nil]);
}
}
#pragma mark - FlutterPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
FFSFileSelectorPlugin *plugin = [[FFSFileSelectorPlugin alloc] init];
FFSFileSelectorApiSetup(registrar.messenger, plugin);
}
#pragma mark - UIDocumentPickerDelegate
// This method is only called in iOS < 11.0. The new codepath is
// documentPicker:didPickDocumentsAtURLs:, implemented below.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
- (void)documentPicker:(UIDocumentPickerViewController *)controller
didPickDocumentAtURL:(NSURL *)url {
[self sendBackResults:@[ url.path ] error:nil forPicker:controller];
}
#pragma clang diagnostic pop
- (void)documentPicker:(UIDocumentPickerViewController *)controller
didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
NSMutableArray *paths = [NSMutableArray arrayWithCapacity:urls.count];
for (NSURL *url in urls) {
[paths addObject:url.path];
};
[self sendBackResults:paths error:nil forPicker:controller];
}
- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
[self sendBackResults:@[] error:nil forPicker:controller];
}
#pragma mark - Helper Methods
- (void)sendBackResults:(NSArray<NSString *> *)results
error:(FlutterError *)error
forPicker:(UIDocumentPickerViewController *)picker {
void (^completionBlock)(NSArray<NSString *> *, FlutterError *) =
objc_getAssociatedObject(picker, @selector(openFileSelectorWithConfig:completion:));
if (completionBlock) {
completionBlock(results, error);
objc_setAssociatedObject(picker, @selector(openFileSelectorWithConfig:completion:), nil,
OBJC_ASSOCIATION_ASSIGN);
}
}
@end
| plugins/packages/file_selector/file_selector_ios/ios/Classes/FFSFileSelectorPlugin.m/0 | {
"file_path": "plugins/packages/file_selector/file_selector_ios/ios/Classes/FFSFileSelectorPlugin.m",
"repo_id": "plugins",
"token_count": 1314
} | 1,423 |
// 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_linux/file_selector_linux.dart';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late FileSelectorLinux plugin;
late List<MethodCall> log;
setUp(() {
plugin = FileSelectorLinux();
log = <MethodCall>[];
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
plugin.channel,
(MethodCall methodCall) async {
log.add(methodCall);
return null;
},
);
});
test('registers instance', () {
FileSelectorLinux.registerWith();
expect(FileSelectorPlatform.instance, isA<FileSelectorLinux>());
});
group('#openFile', () {
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
macUTIs: <String>['public.text'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
macUTIs: <String>['public.image'],
webWildCards: <String>['image/*'],
);
await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
<String, Object>{
'label': 'text',
'extensions': <String>['*.txt'],
'mimeTypes': <String>['text/plain'],
},
<String, Object>{
'label': 'image',
'extensions': <String>['*.jpg'],
'mimeTypes': <String>['image/jpg'],
},
],
'initialDirectory': null,
'confirmButtonText': null,
'multiple': false,
},
);
});
test('passes initialDirectory correctly', () async {
await plugin.openFile(initialDirectory: '/example/directory');
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'initialDirectory': '/example/directory',
'confirmButtonText': null,
'multiple': false,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.openFile(confirmButtonText: 'Open File');
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'initialDirectory': null,
'confirmButtonText': 'Open File',
'multiple': false,
},
);
});
test('throws for a type group that does not support Linux', () async {
const XTypeGroup group = XTypeGroup(
label: 'images',
webWildCards: <String>['images/*'],
);
await expectLater(
plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]),
throwsArgumentError);
});
test('passes a wildcard group correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'any',
);
await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]);
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
<String, Object>{
'label': 'any',
'extensions': <String>['*'],
},
],
'initialDirectory': null,
'confirmButtonText': null,
'multiple': false,
},
);
});
});
group('#openFiles', () {
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
macUTIs: <String>['public.text'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
macUTIs: <String>['public.image'],
webWildCards: <String>['image/*'],
);
await plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
<String, Object>{
'label': 'text',
'extensions': <String>['*.txt'],
'mimeTypes': <String>['text/plain'],
},
<String, Object>{
'label': 'image',
'extensions': <String>['*.jpg'],
'mimeTypes': <String>['image/jpg'],
},
],
'initialDirectory': null,
'confirmButtonText': null,
'multiple': true,
},
);
});
test('passes initialDirectory correctly', () async {
await plugin.openFiles(initialDirectory: '/example/directory');
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'initialDirectory': '/example/directory',
'confirmButtonText': null,
'multiple': true,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.openFiles(confirmButtonText: 'Open File');
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'initialDirectory': null,
'confirmButtonText': 'Open File',
'multiple': true,
},
);
});
test('throws for a type group that does not support Linux', () async {
const XTypeGroup group = XTypeGroup(
label: 'images',
webWildCards: <String>['images/*'],
);
await expectLater(
plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]),
throwsArgumentError);
});
test('passes a wildcard group correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'any',
);
await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]);
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
<String, Object>{
'label': 'any',
'extensions': <String>['*'],
},
],
'initialDirectory': null,
'confirmButtonText': null,
'multiple': false,
},
);
});
});
group('#getSavePath', () {
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
macUTIs: <String>['public.text'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
macUTIs: <String>['public.image'],
webWildCards: <String>['image/*'],
);
await plugin
.getSavePath(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
<String, Object>{
'label': 'text',
'extensions': <String>['*.txt'],
'mimeTypes': <String>['text/plain'],
},
<String, Object>{
'label': 'image',
'extensions': <String>['*.jpg'],
'mimeTypes': <String>['image/jpg'],
},
],
'initialDirectory': null,
'suggestedName': null,
'confirmButtonText': null,
},
);
});
test('passes initialDirectory correctly', () async {
await plugin.getSavePath(initialDirectory: '/example/directory');
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
'initialDirectory': '/example/directory',
'suggestedName': null,
'confirmButtonText': null,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.getSavePath(confirmButtonText: 'Open File');
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
'initialDirectory': null,
'suggestedName': null,
'confirmButtonText': 'Open File',
},
);
});
test('throws for a type group that does not support Linux', () async {
const XTypeGroup group = XTypeGroup(
label: 'images',
webWildCards: <String>['images/*'],
);
await expectLater(
plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]),
throwsArgumentError);
});
test('passes a wildcard group correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'any',
);
await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]);
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
<String, Object>{
'label': 'any',
'extensions': <String>['*'],
},
],
'initialDirectory': null,
'confirmButtonText': null,
'multiple': false,
},
);
});
});
group('#getDirectoryPath', () {
test('passes initialDirectory correctly', () async {
await plugin.getDirectoryPath(initialDirectory: '/example/directory');
expectMethodCall(
log,
'getDirectoryPath',
arguments: <String, dynamic>{
'initialDirectory': '/example/directory',
'confirmButtonText': null,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.getDirectoryPath(confirmButtonText: 'Select Folder');
expectMethodCall(
log,
'getDirectoryPath',
arguments: <String, dynamic>{
'initialDirectory': null,
'confirmButtonText': 'Select Folder',
},
);
});
});
group('#getDirectoryPaths', () {
test('passes initialDirectory correctly', () async {
await plugin.getDirectoryPaths(initialDirectory: '/example/directory');
expectMethodCall(
log,
'getDirectoryPath',
arguments: <String, dynamic>{
'initialDirectory': '/example/directory',
'confirmButtonText': null,
'multiple': true,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.getDirectoryPaths(
confirmButtonText: 'Select one or mode folders');
expectMethodCall(
log,
'getDirectoryPath',
arguments: <String, dynamic>{
'initialDirectory': null,
'confirmButtonText': 'Select one or mode folders',
'multiple': true,
},
);
});
test('passes multiple flag correctly', () async {
await plugin.getDirectoryPaths();
expectMethodCall(
log,
'getDirectoryPath',
arguments: <String, dynamic>{
'initialDirectory': null,
'confirmButtonText': null,
'multiple': true,
},
);
});
});
}
void expectMethodCall(
List<MethodCall> log,
String methodName, {
Map<String, dynamic>? arguments,
}) {
expect(log, <Matcher>[isMethodCall(methodName, arguments: arguments)]);
}
/// 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/file_selector/file_selector_linux/test/file_selector_linux_test.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_linux/test/file_selector_linux_test.dart",
"repo_id": "plugins",
"token_count": 5486
} | 1,424 |
// 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:typed_data';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter/material.dart';
/// Screen that allows the user to select a save location using `getSavePath`,
/// then writes text to a file at that location.
class SaveTextPage extends StatelessWidget {
/// Default Constructor
SaveTextPage({Key? key}) : super(key: key);
final TextEditingController _nameController = TextEditingController();
final TextEditingController _contentController = TextEditingController();
Future<void> _saveFile() async {
final String fileName = _nameController.text;
final String? path = await FileSelectorPlatform.instance.getSavePath(
suggestedName: fileName,
);
if (path == null) {
// Operation was canceled by the user.
return;
}
final String text = _contentController.text;
final Uint8List fileData = Uint8List.fromList(text.codeUnits);
const String fileMimeType = 'text/plain';
final XFile textFile =
XFile.fromData(fileData, mimeType: fileMimeType, name: fileName);
await textFile.saveTo(path);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Save text into a file'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
width: 300,
child: TextField(
minLines: 1,
maxLines: 12,
controller: _nameController,
decoration: const InputDecoration(
hintText: '(Optional) Suggest File Name',
),
),
),
SizedBox(
width: 300,
child: TextField(
minLines: 1,
maxLines: 12,
controller: _contentController,
decoration: const InputDecoration(
hintText: 'Enter File Contents',
),
),
),
const SizedBox(height: 10),
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,
),
onPressed: _saveFile,
child: const Text('Press to save a text file'),
),
],
),
),
);
}
}
| plugins/packages/file_selector/file_selector_macos/example/lib/save_text_page.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_macos/example/lib/save_text_page.dart",
"repo_id": "plugins",
"token_count": 1276
} | 1,425 |
// 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 (v4.2.14), 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, unnecessary_import
import 'dart:async';
import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List;
import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;
import 'package:flutter/services.dart';
/// A Pigeon representation of the macOS portion of an `XTypeGroup`.
class AllowedTypes {
AllowedTypes({
required this.extensions,
required this.mimeTypes,
required this.utis,
});
List<String?> extensions;
List<String?> mimeTypes;
List<String?> utis;
Object encode() {
return <Object?>[
extensions,
mimeTypes,
utis,
];
}
static AllowedTypes decode(Object result) {
result as List<Object?>;
return AllowedTypes(
extensions: (result[0] as List<Object?>?)!.cast<String?>(),
mimeTypes: (result[1] as List<Object?>?)!.cast<String?>(),
utis: (result[2] as List<Object?>?)!.cast<String?>(),
);
}
}
/// Options for save panels.
///
/// These correspond to NSSavePanel properties (which are, by extension
/// NSOpenPanel properties as well).
class SavePanelOptions {
SavePanelOptions({
this.allowedFileTypes,
this.directoryPath,
this.nameFieldStringValue,
this.prompt,
});
AllowedTypes? allowedFileTypes;
String? directoryPath;
String? nameFieldStringValue;
String? prompt;
Object encode() {
return <Object?>[
allowedFileTypes?.encode(),
directoryPath,
nameFieldStringValue,
prompt,
];
}
static SavePanelOptions decode(Object result) {
result as List<Object?>;
return SavePanelOptions(
allowedFileTypes: result[0] != null
? AllowedTypes.decode(result[0]! as List<Object?>)
: null,
directoryPath: result[1] as String?,
nameFieldStringValue: result[2] as String?,
prompt: result[3] as String?,
);
}
}
/// Options for open panels.
///
/// These correspond to NSOpenPanel properties.
class OpenPanelOptions {
OpenPanelOptions({
required this.allowsMultipleSelection,
required this.canChooseDirectories,
required this.canChooseFiles,
required this.baseOptions,
});
bool allowsMultipleSelection;
bool canChooseDirectories;
bool canChooseFiles;
SavePanelOptions baseOptions;
Object encode() {
return <Object?>[
allowsMultipleSelection,
canChooseDirectories,
canChooseFiles,
baseOptions.encode(),
];
}
static OpenPanelOptions decode(Object result) {
result as List<Object?>;
return OpenPanelOptions(
allowsMultipleSelection: result[0]! as bool,
canChooseDirectories: result[1]! as bool,
canChooseFiles: result[2]! as bool,
baseOptions: SavePanelOptions.decode(result[3]! as List<Object?>),
);
}
}
class _FileSelectorApiCodec extends StandardMessageCodec {
const _FileSelectorApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is AllowedTypes) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is OpenPanelOptions) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else if (value is SavePanelOptions) {
buffer.putUint8(130);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return AllowedTypes.decode(readValue(buffer)!);
case 129:
return OpenPanelOptions.decode(readValue(buffer)!);
case 130:
return SavePanelOptions.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
class FileSelectorApi {
/// Constructor for [FileSelectorApi]. 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.
FileSelectorApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _FileSelectorApiCodec();
/// Shows an open panel with the given [options], returning the list of
/// selected paths.
///
/// An empty list corresponds to a cancelled selection.
Future<List<String?>> displayOpenPanel(OpenPanelOptions arg_options) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FileSelectorApi.displayOpenPanel', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_options]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as List<Object?>?)!.cast<String?>();
}
}
/// Shows a save panel with the given [options], returning the selected path.
///
/// A null return corresponds to a cancelled save.
Future<String?> displaySavePanel(SavePanelOptions arg_options) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FileSelectorApi.displaySavePanel', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_options]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return (replyList[0] as String?);
}
}
}
| plugins/packages/file_selector/file_selector_macos/lib/src/messages.g.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_macos/lib/src/messages.g.dart",
"repo_id": "plugins",
"token_count": 2421
} | 1,426 |
// 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:plugin_platform_interface/plugin_platform_interface.dart';
import '../../file_selector_platform_interface.dart';
import '../method_channel/method_channel_file_selector.dart';
/// The interface that implementations of file_selector must implement.
///
/// Platform implementations should extend this class rather than implement it as `file_selector`
/// 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
/// [FileSelectorPlatform] methods.
abstract class FileSelectorPlatform extends PlatformInterface {
/// Constructs a FileSelectorPlatform.
FileSelectorPlatform() : super(token: _token);
static final Object _token = Object();
static FileSelectorPlatform _instance = MethodChannelFileSelector();
/// The default instance of [FileSelectorPlatform] to use.
///
/// Defaults to [MethodChannelFileSelector].
static FileSelectorPlatform get instance => _instance;
/// Platform-specific plugins should set this with their own platform-specific
/// class that extends [FileSelectorPlatform] when they register themselves.
static set instance(FileSelectorPlatform instance) {
PlatformInterface.verify(instance, _token);
_instance = instance;
}
/// Opens a file dialog for loading files and returns a file path.
/// Returns `null` if user cancels the operation.
Future<XFile?> openFile({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) {
throw UnimplementedError('openFile() has not been implemented.');
}
/// Opens a file dialog for loading files and returns a list of file paths.
Future<List<XFile>> openFiles({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) {
throw UnimplementedError('openFiles() has not been implemented.');
}
/// Opens a file dialog for saving files and returns a file path at which to save.
/// Returns `null` if user cancels the operation.
Future<String?> getSavePath({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? suggestedName,
String? confirmButtonText,
}) {
throw UnimplementedError('getSavePath() has not been implemented.');
}
/// Opens a file dialog for loading directories and returns a directory path.
/// Returns `null` if user cancels the operation.
Future<String?> getDirectoryPath({
String? initialDirectory,
String? confirmButtonText,
}) {
throw UnimplementedError('getDirectoryPath() has not been implemented.');
}
/// Opens a file dialog for loading directories and returns multiple directory paths.
Future<List<String>> getDirectoryPaths({
String? initialDirectory,
String? confirmButtonText,
}) {
throw UnimplementedError('getDirectoryPaths() has not been implemented.');
}
}
| plugins/packages/file_selector/file_selector_platform_interface/lib/src/platform_interface/file_selector_interface.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_platform_interface/lib/src/platform_interface/file_selector_interface.dart",
"repo_id": "plugins",
"token_count": 877
} | 1,427 |
name: file_selector_web_integration_tests
publish_to: none
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
file_selector_platform_interface: ^2.2.0
file_selector_web:
path: ../
flutter:
sdk: flutter
dev_dependencies:
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
| plugins/packages/file_selector/file_selector_web/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/file_selector/file_selector_web/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 166
} | 1,428 |
// 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';
import 'package:file_selector_windows/file_selector_windows.dart';
import 'package:file_selector_windows/src/messages.g.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'file_selector_windows_test.mocks.dart';
import 'test_api.g.dart';
@GenerateMocks(<Type>[TestFileSelectorApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final FileSelectorWindows plugin = FileSelectorWindows();
late MockTestFileSelectorApi mockApi;
setUp(() {
mockApi = MockTestFileSelectorApi();
TestFileSelectorApi.setup(mockApi);
});
test('registered instance', () {
FileSelectorWindows.registerWith();
expect(FileSelectorPlatform.instance, isA<FileSelectorWindows>());
});
group('#openFile', () {
setUp(() {
when(mockApi.showOpenDialog(any, any, any)).thenReturn(<String?>['foo']);
});
test('simple call works', () async {
final XFile? file = await plugin.openFile();
expect(file!.path, 'foo');
final VerificationResult result =
verify(mockApi.showOpenDialog(captureAny, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(options.allowMultiple, false);
expect(options.selectFolders, false);
});
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
macUTIs: <String>['public.text'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
macUTIs: <String>['public.image']);
await plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
final VerificationResult result =
verify(mockApi.showOpenDialog(captureAny, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(
_typeGroupListsMatch(options.allowedTypes, <TypeGroup>[
TypeGroup(label: 'text', extensions: <String>['txt']),
TypeGroup(label: 'image', extensions: <String>['jpg']),
]),
true);
});
test('passes initialDirectory correctly', () async {
await plugin.openFile(initialDirectory: '/example/directory');
verify(mockApi.showOpenDialog(any, '/example/directory', null));
});
test('passes confirmButtonText correctly', () async {
await plugin.openFile(confirmButtonText: 'Open File');
verify(mockApi.showOpenDialog(any, null, 'Open File'));
});
test('throws for a type group that does not support Windows', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
mimeTypes: <String>['text/plain'],
);
await expectLater(
plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]),
throwsArgumentError);
});
test('allows a wildcard group', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
);
await expectLater(
plugin.openFile(acceptedTypeGroups: <XTypeGroup>[group]), completes);
});
});
group('#openFiles', () {
setUp(() {
when(mockApi.showOpenDialog(any, any, any))
.thenReturn(<String?>['foo', 'bar']);
});
test('simple call works', () async {
final List<XFile> file = await plugin.openFiles();
expect(file[0].path, 'foo');
expect(file[1].path, 'bar');
final VerificationResult result =
verify(mockApi.showOpenDialog(captureAny, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(options.allowMultiple, true);
expect(options.selectFolders, false);
});
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
macUTIs: <String>['public.text'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
macUTIs: <String>['public.image']);
await plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
final VerificationResult result =
verify(mockApi.showOpenDialog(captureAny, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(
_typeGroupListsMatch(options.allowedTypes, <TypeGroup>[
TypeGroup(label: 'text', extensions: <String>['txt']),
TypeGroup(label: 'image', extensions: <String>['jpg']),
]),
true);
});
test('passes initialDirectory correctly', () async {
await plugin.openFiles(initialDirectory: '/example/directory');
verify(mockApi.showOpenDialog(any, '/example/directory', null));
});
test('passes confirmButtonText correctly', () async {
await plugin.openFiles(confirmButtonText: 'Open Files');
verify(mockApi.showOpenDialog(any, null, 'Open Files'));
});
test('throws for a type group that does not support Windows', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
mimeTypes: <String>['text/plain'],
);
await expectLater(
plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]),
throwsArgumentError);
});
test('allows a wildcard group', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
);
await expectLater(
plugin.openFiles(acceptedTypeGroups: <XTypeGroup>[group]), completes);
});
});
group('#getDirectoryPath', () {
setUp(() {
when(mockApi.showOpenDialog(any, any, any)).thenReturn(<String?>['foo']);
});
test('simple call works', () async {
final String? path = await plugin.getDirectoryPath();
expect(path, 'foo');
final VerificationResult result =
verify(mockApi.showOpenDialog(captureAny, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(options.allowMultiple, false);
expect(options.selectFolders, true);
});
test('passes initialDirectory correctly', () async {
await plugin.getDirectoryPath(initialDirectory: '/example/directory');
verify(mockApi.showOpenDialog(any, '/example/directory', null));
});
test('passes confirmButtonText correctly', () async {
await plugin.getDirectoryPath(confirmButtonText: 'Open Directory');
verify(mockApi.showOpenDialog(any, null, 'Open Directory'));
});
});
group('#getSavePath', () {
setUp(() {
when(mockApi.showSaveDialog(any, any, any, any))
.thenReturn(<String?>['foo']);
});
test('simple call works', () async {
final String? path = await plugin.getSavePath();
expect(path, 'foo');
final VerificationResult result =
verify(mockApi.showSaveDialog(captureAny, null, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(options.allowMultiple, false);
expect(options.selectFolders, false);
});
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
macUTIs: <String>['public.text'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
macUTIs: <String>['public.image']);
await plugin
.getSavePath(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
final VerificationResult result =
verify(mockApi.showSaveDialog(captureAny, null, null, null));
final SelectionOptions options = result.captured[0] as SelectionOptions;
expect(
_typeGroupListsMatch(options.allowedTypes, <TypeGroup>[
TypeGroup(label: 'text', extensions: <String>['txt']),
TypeGroup(label: 'image', extensions: <String>['jpg']),
]),
true);
});
test('passes initialDirectory correctly', () async {
await plugin.getSavePath(initialDirectory: '/example/directory');
verify(mockApi.showSaveDialog(any, '/example/directory', null, null));
});
test('passes suggestedName correctly', () async {
await plugin.getSavePath(suggestedName: 'baz.txt');
verify(mockApi.showSaveDialog(any, null, 'baz.txt', null));
});
test('passes confirmButtonText correctly', () async {
await plugin.getSavePath(confirmButtonText: 'Save File');
verify(mockApi.showSaveDialog(any, null, null, 'Save File'));
});
test('throws for a type group that does not support Windows', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
mimeTypes: <String>['text/plain'],
);
await expectLater(
plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]),
throwsArgumentError);
});
test('allows a wildcard group', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
);
await expectLater(
plugin.getSavePath(acceptedTypeGroups: <XTypeGroup>[group]),
completes);
});
});
}
// True if the given options match.
//
// This is needed because Pigeon data classes don't have custom equality checks,
// so only match for identical instances.
bool _typeGroupListsMatch(List<TypeGroup?> a, List<TypeGroup?> b) {
if (a.length != b.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!_typeGroupsMatch(a[i], b[i])) {
return false;
}
}
return true;
}
// True if the given type groups match.
//
// This is needed because Pigeon data classes don't have custom equality checks,
// so only match for identical instances.
bool _typeGroupsMatch(TypeGroup? a, TypeGroup? b) {
return a!.label == b!.label && listEquals(a.extensions, b.extensions);
}
| plugins/packages/file_selector/file_selector_windows/test/file_selector_windows_test.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_windows/test/file_selector_windows_test.dart",
"repo_id": "plugins",
"token_count": 4077
} | 1,429 |
// 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.
#include "test/test_file_dialog_controller.h"
#include <windows.h>
#include <functional>
#include <memory>
#include <variant>
namespace file_selector_windows {
namespace test {
TestFileDialogController::TestFileDialogController(IFileDialog* dialog,
MockShow mock_show)
: dialog_(dialog),
mock_show_(std::move(mock_show)),
FileDialogController(dialog) {}
TestFileDialogController::~TestFileDialogController() {}
HRESULT TestFileDialogController::SetFolder(IShellItem* folder) {
wchar_t* path_chars = nullptr;
if (SUCCEEDED(folder->GetDisplayName(SIGDN_FILESYSPATH, &path_chars))) {
set_folder_path_ = path_chars;
} else {
set_folder_path_ = L"";
}
return FileDialogController::SetFolder(folder);
}
HRESULT TestFileDialogController::SetFileTypes(UINT count,
COMDLG_FILTERSPEC* filters) {
filter_groups_.clear();
for (unsigned int i = 0; i < count; ++i) {
filter_groups_.push_back(
DialogFilter(filters[i].pszName, filters[i].pszSpec));
}
return FileDialogController::SetFileTypes(count, filters);
}
HRESULT TestFileDialogController::SetOkButtonLabel(const wchar_t* text) {
ok_button_label_ = text;
return FileDialogController::SetOkButtonLabel(text);
}
HRESULT TestFileDialogController::Show(HWND parent) {
mock_result_ = mock_show_(*this, parent);
if (std::holds_alternative<std::monostate>(mock_result_)) {
return HRESULT_FROM_WIN32(ERROR_CANCELLED);
}
return S_OK;
}
HRESULT TestFileDialogController::GetResult(IShellItem** out_item) const {
*out_item = std::get<IShellItemPtr>(mock_result_);
(*out_item)->AddRef();
return S_OK;
}
HRESULT TestFileDialogController::GetResults(
IShellItemArray** out_items) const {
*out_items = std::get<IShellItemArrayPtr>(mock_result_);
(*out_items)->AddRef();
return S_OK;
}
std::wstring TestFileDialogController::GetSetFolderPath() const {
return set_folder_path_;
}
std::wstring TestFileDialogController::GetDialogFolderPath() const {
IShellItemPtr item;
if (!SUCCEEDED(dialog_->GetFolder(&item))) {
return L"";
}
wchar_t* path_chars = nullptr;
if (!SUCCEEDED(item->GetDisplayName(SIGDN_FILESYSPATH, &path_chars))) {
return L"";
}
std::wstring path(path_chars);
::CoTaskMemFree(path_chars);
return path;
}
std::wstring TestFileDialogController::GetFileName() const {
wchar_t* name_chars = nullptr;
if (!SUCCEEDED(dialog_->GetFileName(&name_chars))) {
return L"";
}
std::wstring name(name_chars);
::CoTaskMemFree(name_chars);
return name;
}
const std::vector<DialogFilter>& TestFileDialogController::GetFileTypes()
const {
return filter_groups_;
}
std::wstring TestFileDialogController::GetOkButtonLabel() const {
return ok_button_label_;
}
// ----------------------------------------
TestFileDialogControllerFactory::TestFileDialogControllerFactory(
MockShow mock_show)
: mock_show_(std::move(mock_show)) {}
TestFileDialogControllerFactory::~TestFileDialogControllerFactory() {}
std::unique_ptr<FileDialogController>
TestFileDialogControllerFactory::CreateController(IFileDialog* dialog) const {
return std::make_unique<TestFileDialogController>(dialog, mock_show_);
}
} // namespace test
} // namespace file_selector_windows
| plugins/packages/file_selector/file_selector_windows/windows/test/test_file_dialog_controller.cpp/0 | {
"file_path": "plugins/packages/file_selector/file_selector_windows/windows/test/test_file_dialog_controller.cpp",
"repo_id": "plugins",
"token_count": 1274
} | 1,430 |
// 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.embedding.engine.plugins.lifecycle;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
/** Provides a static method for extracting lifecycle objects from Flutter plugin bindings. */
public class FlutterLifecycleAdapter {
private static final String TAG = "FlutterLifecycleAdapter";
/**
* Returns the lifecycle object for the activity a plugin is bound to.
*
* <p>Returns null if the Flutter engine version does not include the lifecycle extraction code.
* (this probably means the Flutter engine version is too old).
*/
@NonNull
public static Lifecycle getActivityLifecycle(
@NonNull ActivityPluginBinding activityPluginBinding) {
HiddenLifecycleReference reference =
(HiddenLifecycleReference) activityPluginBinding.getLifecycle();
return reference.getLifecycle();
}
}
| plugins/packages/flutter_plugin_android_lifecycle/android/src/main/java/io/flutter/embedding/engine/plugins/lifecycle/FlutterLifecycleAdapter.java/0 | {
"file_path": "plugins/packages/flutter_plugin_android_lifecycle/android/src/main/java/io/flutter/embedding/engine/plugins/lifecycle/FlutterLifecycleAdapter.java",
"repo_id": "plugins",
"token_count": 308
} | 1,431 |
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.1'
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
| plugins/packages/google_maps_flutter/google_maps_flutter/example/android/build.gradle/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/example/android/build.gradle",
"repo_id": "plugins",
"token_count": 202
} | 1,432 |
// 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:google_maps_flutter_android/google_maps_flutter_android.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'animate_camera.dart';
import 'lite_mode.dart';
import 'map_click.dart';
import 'map_coordinates.dart';
import 'map_ui.dart';
import 'marker_icons.dart';
import 'move_camera.dart';
import 'padding.dart';
import 'page.dart';
import 'place_circle.dart';
import 'place_marker.dart';
import 'place_polygon.dart';
import 'place_polyline.dart';
import 'scrolling_map.dart';
import 'snapshot.dart';
import 'tile_overlay.dart';
final List<GoogleMapExampleAppPage> _allPages = <GoogleMapExampleAppPage>[
const MapUiPage(),
const MapCoordinatesPage(),
const MapClickPage(),
const AnimateCameraPage(),
const MoveCameraPage(),
const PlaceMarkerPage(),
const MarkerIconsPage(),
const ScrollingMapPage(),
const PlacePolylinePage(),
const PlacePolygonPage(),
const PlaceCirclePage(),
const PaddingPage(),
const SnapshotPage(),
const LiteModePage(),
const TileOverlayPage(),
];
/// MapsDemo is the Main Application.
class MapsDemo extends StatelessWidget {
/// Default Constructor
const MapsDemo({Key? key}) : super(key: key);
void _pushPage(BuildContext context, GoogleMapExampleAppPage page) {
Navigator.of(context).push(MaterialPageRoute<void>(
builder: (_) => Scaffold(
appBar: AppBar(title: Text(page.title)),
body: page,
)));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('GoogleMaps examples')),
body: ListView.builder(
itemCount: _allPages.length,
itemBuilder: (_, int index) => ListTile(
leading: _allPages[index].leading,
title: Text(_allPages[index].title),
onTap: () => _pushPage(context, _allPages[index]),
),
),
);
}
}
void main() {
final GoogleMapsFlutterPlatform mapsImplementation =
GoogleMapsFlutterPlatform.instance;
if (mapsImplementation is GoogleMapsFlutterAndroid) {
mapsImplementation.useAndroidViewSurface = true;
}
runApp(const MaterialApp(home: MapsDemo()));
}
| plugins/packages/google_maps_flutter/google_maps_flutter/example/lib/main.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/example/lib/main.dart",
"repo_id": "plugins",
"token_count": 853
} | 1,433 |
name: google_maps_flutter_example
description: Demonstrates how to use the google_maps_flutter plugin.
publish_to: none
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
cupertino_icons: ^1.0.5
flutter:
sdk: flutter
flutter_plugin_android_lifecycle: ^2.0.1
google_maps_flutter:
# When depending on this package from a real application you should use:
# google_maps_flutter: ^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: ../
google_maps_flutter_android: ^2.1.10
google_maps_flutter_platform_interface: ^2.2.1
dev_dependencies:
build_runner: ^2.1.10
espresso: ^0.2.0
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/
| plugins/packages/google_maps_flutter/google_maps_flutter/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 378
} | 1,434 |
// 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 android.app.Activity;
import android.app.Application.ActivityLifecycleCallbacks;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.Lifecycle.Event;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;
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;
/**
* Plugin for controlling a set of GoogleMap views to be shown as overlays on top of the Flutter
* view. The overlay should be hidden during transformations or while Flutter is rendering on top of
* the map. A Texture drawn using GoogleMap bitmap snapshots can then be shown instead of the
* overlay.
*/
public class GoogleMapsPlugin implements FlutterPlugin, ActivityAware {
@Nullable private Lifecycle lifecycle;
private static final String VIEW_TYPE = "plugins.flutter.dev/google_maps_android";
@SuppressWarnings("deprecation")
public static void registerWith(
final io.flutter.plugin.common.PluginRegistry.Registrar registrar) {
final Activity activity = registrar.activity();
if (activity == null) {
// When a background flutter view tries to register the plugin, the registrar has no activity.
// We stop the registration process as this plugin is foreground only.
return;
}
if (activity instanceof LifecycleOwner) {
registrar
.platformViewRegistry()
.registerViewFactory(
VIEW_TYPE,
new GoogleMapFactory(
registrar.messenger(),
registrar.context(),
new LifecycleProvider() {
@Override
public Lifecycle getLifecycle() {
return ((LifecycleOwner) activity).getLifecycle();
}
}));
} else {
registrar
.platformViewRegistry()
.registerViewFactory(
VIEW_TYPE,
new GoogleMapFactory(
registrar.messenger(),
registrar.context(),
new ProxyLifecycleProvider(activity)));
}
}
public GoogleMapsPlugin() {}
// FlutterPlugin
@Override
public void onAttachedToEngine(FlutterPluginBinding binding) {
binding
.getPlatformViewRegistry()
.registerViewFactory(
VIEW_TYPE,
new GoogleMapFactory(
binding.getBinaryMessenger(),
binding.getApplicationContext(),
new LifecycleProvider() {
@Nullable
@Override
public Lifecycle getLifecycle() {
return lifecycle;
}
}));
}
@Override
public void onDetachedFromEngine(FlutterPluginBinding binding) {}
// ActivityAware
@Override
public void onAttachedToActivity(ActivityPluginBinding binding) {
lifecycle = FlutterLifecycleAdapter.getActivityLifecycle(binding);
}
@Override
public void onDetachedFromActivity() {
lifecycle = null;
}
@Override
public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) {
onAttachedToActivity(binding);
}
@Override
public void onDetachedFromActivityForConfigChanges() {
onDetachedFromActivity();
}
/**
* This class provides a {@link LifecycleOwner} for the activity driven by {@link
* ActivityLifecycleCallbacks}.
*
* <p>This is used in the case where a direct Lifecycle/Owner is not available.
*/
private static final class ProxyLifecycleProvider
implements ActivityLifecycleCallbacks, LifecycleOwner, LifecycleProvider {
private final LifecycleRegistry lifecycle = new LifecycleRegistry(this);
private final int registrarActivityHashCode;
private ProxyLifecycleProvider(Activity activity) {
this.registrarActivityHashCode = activity.hashCode();
activity.getApplication().registerActivityLifecycleCallbacks(this);
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (activity.hashCode() != registrarActivityHashCode) {
return;
}
lifecycle.handleLifecycleEvent(Event.ON_CREATE);
}
@Override
public void onActivityStarted(Activity activity) {
if (activity.hashCode() != registrarActivityHashCode) {
return;
}
lifecycle.handleLifecycleEvent(Event.ON_START);
}
@Override
public void onActivityResumed(Activity activity) {
if (activity.hashCode() != registrarActivityHashCode) {
return;
}
lifecycle.handleLifecycleEvent(Event.ON_RESUME);
}
@Override
public void onActivityPaused(Activity activity) {
if (activity.hashCode() != registrarActivityHashCode) {
return;
}
lifecycle.handleLifecycleEvent(Event.ON_PAUSE);
}
@Override
public void onActivityStopped(Activity activity) {
if (activity.hashCode() != registrarActivityHashCode) {
return;
}
lifecycle.handleLifecycleEvent(Event.ON_STOP);
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
@Override
public void onActivityDestroyed(Activity activity) {
if (activity.hashCode() != registrarActivityHashCode) {
return;
}
activity.getApplication().unregisterActivityLifecycleCallbacks(this);
lifecycle.handleLifecycleEvent(Event.ON_DESTROY);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return lifecycle;
}
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/GoogleMapsPlugin.java/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/GoogleMapsPlugin.java",
"repo_id": "plugins",
"token_count": 2239
} | 1,435 |
// 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 com.google.android.gms.maps.model.TileProvider;
/** Receiver of TileOverlayOptions configuration. */
interface TileOverlaySink {
void setFadeIn(boolean fadeIn);
void setTransparency(float transparency);
void setZIndex(float zIndex);
void setVisible(boolean visible);
void setTileProvider(TileProvider tileProvider);
}
| plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/TileOverlaySink.java/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/TileOverlaySink.java",
"repo_id": "plugins",
"token_count": 152
} | 1,436 |
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 31
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
applicationId "io.flutter.plugins.googlemapsexample"
minSdkVersion 20
targetSdkVersion 28
multiDexEnabled true
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
defaultConfig {
manifestPlaceholders = [mapsApiKey: "$System.env.MAPS_API_KEY"]
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
testOptions {
unitTests {
includeAndroidResources = true
}
}
dependencies {
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
api 'androidx.test:core:1.2.0'
testImplementation 'com.google.android.gms:play-services-maps:17.0.0'
}
}
flutter {
source '../..'
}
| plugins/packages/google_maps_flutter/google_maps_flutter_android/example/android/app/build.gradle/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/example/android/app/build.gradle",
"repo_id": "plugins",
"token_count": 808
} | 1,437 |
org.gradle.jvmargs=-Xmx4G
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
| plugins/packages/google_maps_flutter/google_maps_flutter_android/example/android/gradle.properties/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/example/android/gradle.properties",
"repo_id": "plugins",
"token_count": 38
} | 1,438 |
// 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:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'example_google_map.dart';
import 'page.dart';
const CameraPosition _kInitialPosition =
CameraPosition(target: LatLng(-33.852, 151.211), zoom: 11.0);
class MapCoordinatesPage extends GoogleMapExampleAppPage {
const MapCoordinatesPage({Key? key})
: super(const Icon(Icons.map), 'Map coordinates', key: key);
@override
Widget build(BuildContext context) {
return const _MapCoordinatesBody();
}
}
class _MapCoordinatesBody extends StatefulWidget {
const _MapCoordinatesBody();
@override
State<StatefulWidget> createState() => _MapCoordinatesBodyState();
}
class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> {
_MapCoordinatesBodyState();
ExampleGoogleMapController? mapController;
LatLngBounds _visibleRegion = LatLngBounds(
southwest: const LatLng(0, 0),
northeast: const LatLng(0, 0),
);
@override
Widget build(BuildContext context) {
final ExampleGoogleMap googleMap = ExampleGoogleMap(
onMapCreated: onMapCreated,
initialCameraPosition: _kInitialPosition,
onCameraIdle:
_updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758
);
return NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification scrollState) {
_updateVisibleRegion();
return true;
},
child: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: Center(
child: SizedBox(
width: 300.0,
height: 200.0,
child: googleMap,
),
),
),
if (mapController != null)
Center(
child: Text('VisibleRegion:'
'\nnortheast: ${_visibleRegion.northeast},'
'\nsouthwest: ${_visibleRegion.southwest}'),
),
// Add a block at the bottom of this list to allow validation that the visible region of the map
// does not change when scrolled under the safe view on iOS.
// https://github.com/flutter/flutter/issues/107913
const SizedBox(
width: 300,
height: 1000,
),
],
),
);
}
Future<void> onMapCreated(ExampleGoogleMapController controller) async {
final LatLngBounds visibleRegion = await controller.getVisibleRegion();
setState(() {
mapController = controller;
_visibleRegion = visibleRegion;
});
}
Future<void> _updateVisibleRegion() async {
final LatLngBounds visibleRegion = await mapController!.getVisibleRegion();
setState(() {
_visibleRegion = visibleRegion;
});
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_coordinates.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_coordinates.dart",
"repo_id": "plugins",
"token_count": 1207
} | 1,439 |
// 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>
NS_ASSUME_NONNULL_BEGIN
@interface FLTGoogleMapJSONConversions : NSObject
+ (CLLocationCoordinate2D)locationFromLatLong:(NSArray *)latlong;
+ (CGPoint)pointFromArray:(NSArray *)array;
+ (NSArray *)arrayFromLocation:(CLLocationCoordinate2D)location;
+ (UIColor *)colorFromRGBA:(NSNumber *)data;
+ (NSArray<CLLocation *> *)pointsFromLatLongs:(NSArray *)data;
+ (NSArray<NSArray<CLLocation *> *> *)holesFromPointsArray:(NSArray *)data;
+ (nullable NSDictionary<NSString *, id> *)dictionaryFromPosition:
(nullable GMSCameraPosition *)position;
+ (NSDictionary<NSString *, NSNumber *> *)dictionaryFromPoint:(CGPoint)point;
+ (nullable NSDictionary *)dictionaryFromCoordinateBounds:(nullable GMSCoordinateBounds *)bounds;
+ (nullable GMSCameraPosition *)cameraPostionFromDictionary:(nullable NSDictionary *)channelValue;
+ (CGPoint)pointFromDictionary:(NSDictionary *)dictionary;
+ (GMSCoordinateBounds *)coordinateBoundsFromLatLongs:(NSArray *)latlongs;
+ (GMSMapViewType)mapViewTypeFromTypeValue:(NSNumber *)value;
+ (nullable GMSCameraUpdate *)cameraUpdateFromChannelValue:(NSArray *)channelValue;
@end
NS_ASSUME_NONNULL_END
| plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/FLTGoogleMapJSONConversions.h/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/FLTGoogleMapJSONConversions.h",
"repo_id": "plugins",
"token_count": 437
} | 1,440 |
// 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 "GoogleMapPolylineController.h"
#import "FLTGoogleMapJSONConversions.h"
@interface FLTGoogleMapPolylineController ()
@property(strong, nonatomic) GMSPolyline *polyline;
@property(weak, nonatomic) GMSMapView *mapView;
@end
@implementation FLTGoogleMapPolylineController
- (instancetype)initPolylineWithPath:(GMSMutablePath *)path
identifier:(NSString *)identifier
mapView:(GMSMapView *)mapView {
self = [super init];
if (self) {
_polyline = [GMSPolyline polylineWithPath:path];
_mapView = mapView;
_polyline.userData = @[ identifier ];
}
return self;
}
- (void)removePolyline {
self.polyline.map = nil;
}
- (void)setConsumeTapEvents:(BOOL)consumes {
self.polyline.tappable = consumes;
}
- (void)setVisible:(BOOL)visible {
self.polyline.map = visible ? self.mapView : nil;
}
- (void)setZIndex:(int)zIndex {
self.polyline.zIndex = zIndex;
}
- (void)setPoints:(NSArray<CLLocation *> *)points {
GMSMutablePath *path = [GMSMutablePath path];
for (CLLocation *location in points) {
[path addCoordinate:location.coordinate];
}
self.polyline.path = path;
}
- (void)setColor:(UIColor *)color {
self.polyline.strokeColor = color;
}
- (void)setStrokeWidth:(CGFloat)width {
self.polyline.strokeWidth = width;
}
- (void)setGeodesic:(BOOL)isGeodesic {
self.polyline.geodesic = isGeodesic;
}
- (void)interpretPolylineOptions:(NSDictionary *)data
registrar:(NSObject<FlutterPluginRegistrar> *)registrar {
NSNumber *consumeTapEvents = data[@"consumeTapEvents"];
if (consumeTapEvents && consumeTapEvents != (id)[NSNull null]) {
[self setConsumeTapEvents:[consumeTapEvents boolValue]];
}
NSNumber *visible = data[@"visible"];
if (visible && visible != (id)[NSNull null]) {
[self setVisible:[visible boolValue]];
}
NSNumber *zIndex = data[@"zIndex"];
if (zIndex && zIndex != (id)[NSNull null]) {
[self setZIndex:[zIndex intValue]];
}
NSArray *points = data[@"points"];
if (points && points != (id)[NSNull null]) {
[self setPoints:[FLTGoogleMapJSONConversions pointsFromLatLongs:points]];
}
NSNumber *strokeColor = data[@"color"];
if (strokeColor && strokeColor != (id)[NSNull null]) {
[self setColor:[FLTGoogleMapJSONConversions colorFromRGBA:strokeColor]];
}
NSNumber *strokeWidth = data[@"width"];
if (strokeWidth && strokeWidth != (id)[NSNull null]) {
[self setStrokeWidth:[strokeWidth intValue]];
}
NSNumber *geodesic = data[@"geodesic"];
if (geodesic && geodesic != (id)[NSNull null]) {
[self setGeodesic:geodesic.boolValue];
}
}
@end
@interface FLTPolylinesController ()
@property(strong, nonatomic) NSMutableDictionary *polylineIdentifierToController;
@property(strong, nonatomic) FlutterMethodChannel *methodChannel;
@property(weak, nonatomic) NSObject<FlutterPluginRegistrar> *registrar;
@property(weak, nonatomic) GMSMapView *mapView;
@end
;
@implementation FLTPolylinesController
- (instancetype)init:(FlutterMethodChannel *)methodChannel
mapView:(GMSMapView *)mapView
registrar:(NSObject<FlutterPluginRegistrar> *)registrar {
self = [super init];
if (self) {
_methodChannel = methodChannel;
_mapView = mapView;
_polylineIdentifierToController = [NSMutableDictionary dictionaryWithCapacity:1];
_registrar = registrar;
}
return self;
}
- (void)addPolylines:(NSArray *)polylinesToAdd {
for (NSDictionary *polyline in polylinesToAdd) {
GMSMutablePath *path = [FLTPolylinesController getPath:polyline];
NSString *identifier = polyline[@"polylineId"];
FLTGoogleMapPolylineController *controller =
[[FLTGoogleMapPolylineController alloc] initPolylineWithPath:path
identifier:identifier
mapView:self.mapView];
[controller interpretPolylineOptions:polyline registrar:self.registrar];
self.polylineIdentifierToController[identifier] = controller;
}
}
- (void)changePolylines:(NSArray *)polylinesToChange {
for (NSDictionary *polyline in polylinesToChange) {
NSString *identifier = polyline[@"polylineId"];
FLTGoogleMapPolylineController *controller = self.polylineIdentifierToController[identifier];
if (!controller) {
continue;
}
[controller interpretPolylineOptions:polyline registrar:self.registrar];
}
}
- (void)removePolylineWithIdentifiers:(NSArray *)identifiers {
for (NSString *identifier in identifiers) {
FLTGoogleMapPolylineController *controller = self.polylineIdentifierToController[identifier];
if (!controller) {
continue;
}
[controller removePolyline];
[self.polylineIdentifierToController removeObjectForKey:identifier];
}
}
- (void)didTapPolylineWithIdentifier:(NSString *)identifier {
if (!identifier) {
return;
}
FLTGoogleMapPolylineController *controller = self.polylineIdentifierToController[identifier];
if (!controller) {
return;
}
[self.methodChannel invokeMethod:@"polyline#onTap" arguments:@{@"polylineId" : identifier}];
}
- (bool)hasPolylineWithIdentifier:(NSString *)identifier {
if (!identifier) {
return false;
}
return self.polylineIdentifierToController[identifier] != nil;
}
+ (GMSMutablePath *)getPath:(NSDictionary *)polyline {
NSArray *pointArray = polyline[@"points"];
NSArray<CLLocation *> *points = [FLTGoogleMapJSONConversions pointsFromLatLongs:pointArray];
GMSMutablePath *path = [GMSMutablePath path];
for (CLLocation *location in points) {
[path addCoordinate:location.coordinate];
}
return path;
}
@end
| plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapPolylineController.m/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapPolylineController.m",
"repo_id": "plugins",
"token_count": 2145
} | 1,441 |
// 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';
// 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:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import '../../google_maps_flutter_platform_interface.dart';
import '../types/utils/map_configuration_serialization.dart';
/// The interface that platform-specific implementations of `google_maps_flutter` must extend.
///
/// Avoid `implements` of this interface. Using `implements` makes adding any new
/// methods here a breaking change for end users of your platform!
///
/// Do `extends GoogleMapsFlutterPlatform` instead, so new methods added here are
/// inherited in your code with the default implementation (that throws at runtime),
/// rather than breaking your users at compile time.
abstract class GoogleMapsFlutterPlatform extends PlatformInterface {
/// Constructs a GoogleMapsFlutterPlatform.
GoogleMapsFlutterPlatform() : super(token: _token);
static final Object _token = Object();
static GoogleMapsFlutterPlatform _instance = MethodChannelGoogleMapsFlutter();
/// The default instance of [GoogleMapsFlutterPlatform] to use.
///
/// Defaults to [MethodChannelGoogleMapsFlutter].
static GoogleMapsFlutterPlatform get instance => _instance;
/// Platform-specific plugins should set this with their own platform-specific
/// class that extends [GoogleMapsFlutterPlatform] when they register themselves.
static set instance(GoogleMapsFlutterPlatform instance) {
PlatformInterface.verify(instance, _token);
_instance = instance;
}
/// /// Initializes the platform interface with [id].
///
/// This method is called when the plugin is first initialized.
Future<void> init(int mapId) {
throw UnimplementedError('init() has not been implemented.');
}
/// Updates configuration options of the map user interface - deprecated, use
/// updateMapConfiguration instead.
///
/// Change listeners are notified once the update has been made on the
/// platform side.
///
/// The returned [Future] completes after listeners have been notified.
Future<void> updateMapOptions(
Map<String, dynamic> optionsUpdate, {
required int mapId,
}) {
throw UnimplementedError('updateMapOptions() has not been implemented.');
}
/// Updates configuration options of the map user interface.
///
/// Change listeners are notified once the update has been made on the
/// platform side.
///
/// The returned [Future] completes after listeners have been notified.
Future<void> updateMapConfiguration(
MapConfiguration configuration, {
required int mapId,
}) {
return updateMapOptions(jsonForMapConfiguration(configuration),
mapId: mapId);
}
/// Updates marker configuration.
///
/// Change listeners are notified once the update has been made on the
/// platform side.
///
/// The returned [Future] completes after listeners have been notified.
Future<void> updateMarkers(
MarkerUpdates markerUpdates, {
required int mapId,
}) {
throw UnimplementedError('updateMarkers() has not been implemented.');
}
/// Updates polygon configuration.
///
/// Change listeners are notified once the update has been made on the
/// platform side.
///
/// The returned [Future] completes after listeners have been notified.
Future<void> updatePolygons(
PolygonUpdates polygonUpdates, {
required int mapId,
}) {
throw UnimplementedError('updatePolygons() has not been implemented.');
}
/// Updates polyline configuration.
///
/// Change listeners are notified once the update has been made on the
/// platform side.
///
/// The returned [Future] completes after listeners have been notified.
Future<void> updatePolylines(
PolylineUpdates polylineUpdates, {
required int mapId,
}) {
throw UnimplementedError('updatePolylines() has not been implemented.');
}
/// Updates circle configuration.
///
/// Change listeners are notified once the update has been made on the
/// platform side.
///
/// The returned [Future] completes after listeners have been notified.
Future<void> updateCircles(
CircleUpdates circleUpdates, {
required int mapId,
}) {
throw UnimplementedError('updateCircles() has not been implemented.');
}
/// Updates tile overlay configuration.
///
/// Change listeners are notified once the update has been made on the
/// platform side.
///
/// The returned [Future] completes after listeners have been notified.
Future<void> updateTileOverlays({
required Set<TileOverlay> newTileOverlays,
required int mapId,
}) {
throw UnimplementedError('updateTileOverlays() has not been implemented.');
}
/// Clears the tile cache so that all tiles will be requested again from the
/// [TileProvider].
///
/// The current tiles from this tile overlay will also be
/// cleared from the map after calling this method. The Google Maps SDK maintains a small
/// in-memory cache of tiles. If you want to cache tiles for longer, you
/// should implement an on-disk cache.
Future<void> clearTileCache(
TileOverlayId tileOverlayId, {
required int mapId,
}) {
throw UnimplementedError('clearTileCache() has not been implemented.');
}
/// Starts an animated change of the map camera position.
///
/// The returned [Future] completes after the change has been started on the
/// platform side.
Future<void> animateCamera(
CameraUpdate cameraUpdate, {
required int mapId,
}) {
throw UnimplementedError('animateCamera() has not been implemented.');
}
/// Changes the map camera position.
///
/// The returned [Future] completes after the change has been made on the
/// platform side.
Future<void> moveCamera(
CameraUpdate cameraUpdate, {
required int mapId,
}) {
throw UnimplementedError('moveCamera() has not been implemented.');
}
/// Sets the styling of the base map.
///
/// Set to `null` to clear any previous custom styling.
///
/// If problems were detected with the [mapStyle], including un-parsable
/// styling JSON, unrecognized feature type, unrecognized element type, or
/// invalid styler keys: [MapStyleException] is thrown and the current
/// style is left unchanged.
///
/// The style string can be generated using [map style tool](https://mapstyle.withgoogle.com/).
Future<void> setMapStyle(
String? mapStyle, {
required int mapId,
}) {
throw UnimplementedError('setMapStyle() has not been implemented.');
}
/// Return the region that is visible in a map.
Future<LatLngBounds> getVisibleRegion({
required int mapId,
}) {
throw UnimplementedError('getVisibleRegion() has not been implemented.');
}
/// Return [ScreenCoordinate] of the [LatLng] in the current map view.
///
/// A projection is used to translate between on screen location and geographic coordinates.
/// Screen location is in screen pixels (not display pixels) with respect to the top left corner
/// of the map, not necessarily of the whole screen.
Future<ScreenCoordinate> getScreenCoordinate(
LatLng latLng, {
required int mapId,
}) {
throw UnimplementedError('getScreenCoordinate() has not been implemented.');
}
/// Returns [LatLng] corresponding to the [ScreenCoordinate] in the current map view.
///
/// A projection is used to translate between on screen location and geographic coordinates.
/// Screen location is in screen pixels (not display pixels) with respect to the top left corner
/// of the map, not necessarily of the whole screen.
Future<LatLng> getLatLng(
ScreenCoordinate screenCoordinate, {
required int mapId,
}) {
throw UnimplementedError('getLatLng() has not been implemented.');
}
/// Programmatically show the Info Window for a [Marker].
///
/// The `markerId` must match one of the markers on the map.
/// An invalid `markerId` triggers an "Invalid markerId" error.
///
/// * See also:
/// * [hideMarkerInfoWindow] to hide the Info Window.
/// * [isMarkerInfoWindowShown] to check if the Info Window is showing.
Future<void> showMarkerInfoWindow(
MarkerId markerId, {
required int mapId,
}) {
throw UnimplementedError(
'showMarkerInfoWindow() has not been implemented.');
}
/// Programmatically hide the Info Window for a [Marker].
///
/// The `markerId` must match one of the markers on the map.
/// An invalid `markerId` triggers an "Invalid markerId" error.
///
/// * See also:
/// * [showMarkerInfoWindow] to show the Info Window.
/// * [isMarkerInfoWindowShown] to check if the Info Window is showing.
Future<void> hideMarkerInfoWindow(
MarkerId markerId, {
required int mapId,
}) {
throw UnimplementedError(
'hideMarkerInfoWindow() has not been implemented.');
}
/// Returns `true` when the [InfoWindow] is showing, `false` otherwise.
///
/// The `markerId` must match one of the markers on the map.
/// An invalid `markerId` triggers an "Invalid markerId" error.
///
/// * See also:
/// * [showMarkerInfoWindow] to show the Info Window.
/// * [hideMarkerInfoWindow] to hide the Info Window.
Future<bool> isMarkerInfoWindowShown(
MarkerId markerId, {
required int mapId,
}) {
throw UnimplementedError('updateMapOptions() has not been implemented.');
}
/// Returns the current zoom level of the map.
Future<double> getZoomLevel({
required int mapId,
}) {
throw UnimplementedError('getZoomLevel() has not been implemented.');
}
/// Returns the image bytes of the map.
///
/// Returns null if a snapshot cannot be created.
Future<Uint8List?> takeSnapshot({
required int mapId,
}) {
throw UnimplementedError('takeSnapshot() has not been implemented.');
}
// The following are the 11 possible streams of data from the native side
// into the plugin
/// The Camera started moving.
Stream<CameraMoveStartedEvent> onCameraMoveStarted({required int mapId}) {
throw UnimplementedError('onCameraMoveStarted() has not been implemented.');
}
/// The Camera finished moving to a new [CameraPosition].
Stream<CameraMoveEvent> onCameraMove({required int mapId}) {
throw UnimplementedError('onCameraMove() has not been implemented.');
}
/// The Camera is now idle.
Stream<CameraIdleEvent> onCameraIdle({required int mapId}) {
throw UnimplementedError('onCameraMove() has not been implemented.');
}
/// A [Marker] has been tapped.
Stream<MarkerTapEvent> onMarkerTap({required int mapId}) {
throw UnimplementedError('onMarkerTap() has not been implemented.');
}
/// An [InfoWindow] has been tapped.
Stream<InfoWindowTapEvent> onInfoWindowTap({required int mapId}) {
throw UnimplementedError('onInfoWindowTap() has not been implemented.');
}
/// A [Marker] has been dragged to a different [LatLng] position.
Stream<MarkerDragStartEvent> onMarkerDragStart({required int mapId}) {
throw UnimplementedError('onMarkerDragEnd() has not been implemented.');
}
/// A [Marker] has been dragged to a different [LatLng] position.
Stream<MarkerDragEvent> onMarkerDrag({required int mapId}) {
throw UnimplementedError('onMarkerDragEnd() has not been implemented.');
}
/// A [Marker] has been dragged to a different [LatLng] position.
Stream<MarkerDragEndEvent> onMarkerDragEnd({required int mapId}) {
throw UnimplementedError('onMarkerDragEnd() has not been implemented.');
}
/// A [Polyline] has been tapped.
Stream<PolylineTapEvent> onPolylineTap({required int mapId}) {
throw UnimplementedError('onPolylineTap() has not been implemented.');
}
/// A [Polygon] has been tapped.
Stream<PolygonTapEvent> onPolygonTap({required int mapId}) {
throw UnimplementedError('onPolygonTap() has not been implemented.');
}
/// A [Circle] has been tapped.
Stream<CircleTapEvent> onCircleTap({required int mapId}) {
throw UnimplementedError('onCircleTap() has not been implemented.');
}
/// A Map has been tapped at a certain [LatLng].
Stream<MapTapEvent> onTap({required int mapId}) {
throw UnimplementedError('onTap() has not been implemented.');
}
/// A Map has been long-pressed at a certain [LatLng].
Stream<MapLongPressEvent> onLongPress({required int mapId}) {
throw UnimplementedError('onLongPress() has not been implemented.');
}
/// Dispose of whatever resources the `mapId` is holding on to.
void dispose({required int mapId}) {
throw UnimplementedError('dispose() has not been implemented.');
}
/// Returns a widget displaying the map view - deprecated, use
/// [buildViewWithConfiguration] instead.
Widget buildView(
int creationId,
PlatformViewCreatedCallback onPlatformViewCreated, {
required CameraPosition initialCameraPosition,
Set<Marker> markers = const <Marker>{},
Set<Polygon> polygons = const <Polygon>{},
Set<Polyline> polylines = const <Polyline>{},
Set<Circle> circles = const <Circle>{},
Set<TileOverlay> tileOverlays = const <TileOverlay>{},
Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers =
const <Factory<OneSequenceGestureRecognizer>>{},
// TODO(stuartmorgan): Replace with a structured type that's part of the
// interface. See https://github.com/flutter/flutter/issues/70330.
Map<String, dynamic> mapOptions = const <String, dynamic>{},
}) {
throw UnimplementedError('buildView() has not been implemented.');
}
/// Returns a widget displaying the map view - deprecated, use
/// [buildViewWithConfiguration] instead.
///
/// This method is similar to [buildView], but contains a parameter for
/// platforms that require a text direction.
///
/// Default behavior passes all parameters except `textDirection` to
/// [buildView]. This is for backward compatibility with existing
/// implementations. Platforms that use the text direction should override
/// this as the primary implementation, and delegate to it from buildView.
Widget buildViewWithTextDirection(
int creationId,
PlatformViewCreatedCallback onPlatformViewCreated, {
required CameraPosition initialCameraPosition,
required TextDirection textDirection,
Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers,
Set<Marker> markers = const <Marker>{},
Set<Polygon> polygons = const <Polygon>{},
Set<Polyline> polylines = const <Polyline>{},
Set<Circle> circles = const <Circle>{},
Set<TileOverlay> tileOverlays = const <TileOverlay>{},
Map<String, dynamic> mapOptions = const <String, dynamic>{},
}) {
return buildView(
creationId,
onPlatformViewCreated,
initialCameraPosition: initialCameraPosition,
markers: markers,
polygons: polygons,
polylines: polylines,
circles: circles,
tileOverlays: tileOverlays,
gestureRecognizers: gestureRecognizers,
mapOptions: mapOptions,
);
}
/// Returns a widget displaying the map view.
Widget buildViewWithConfiguration(
int creationId,
PlatformViewCreatedCallback onPlatformViewCreated, {
required MapWidgetConfiguration widgetConfiguration,
MapConfiguration mapConfiguration = const MapConfiguration(),
MapObjects mapObjects = const MapObjects(),
}) {
return buildViewWithTextDirection(
creationId,
onPlatformViewCreated,
initialCameraPosition: widgetConfiguration.initialCameraPosition,
textDirection: widgetConfiguration.textDirection,
markers: mapObjects.markers,
polygons: mapObjects.polygons,
polylines: mapObjects.polylines,
circles: mapObjects.circles,
tileOverlays: mapObjects.tileOverlays,
gestureRecognizers: widgetConfiguration.gestureRecognizers,
mapOptions: jsonForMapConfiguration(mapConfiguration),
);
}
/// Populates [GoogleMapsFlutterInspectorPlatform.instance] to allow
/// inspecting the platform map state.
@visibleForTesting
void enableDebugInspection() {
throw UnimplementedError(
'enableDebugInspection() has not been implemented.');
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/platform_interface/google_maps_flutter_platform.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/platform_interface/google_maps_flutter_platform.dart",
"repo_id": "plugins",
"token_count": 4905
} | 1,442 |
// 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 'types.dart';
/// [Marker] update events to be applied to the [GoogleMap].
///
/// Used in [GoogleMapController] when the map is updated.
// (Do not re-export)
class MarkerUpdates extends MapsObjectUpdates<Marker> {
/// Computes [MarkerUpdates] given previous and current [Marker]s.
MarkerUpdates.from(Set<Marker> previous, Set<Marker> current)
: super.from(previous, current, objectName: 'marker');
/// Set of Markers to be added in this update.
Set<Marker> get markersToAdd => objectsToAdd;
/// Set of MarkerIds to be removed in this update.
Set<MarkerId> get markerIdsToRemove => objectIdsToRemove.cast<MarkerId>();
/// Set of Markers to be changed in this update.
Set<Marker> get markersToChange => objectsToChange;
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/marker_updates.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/marker_updates.dart",
"repo_id": "plugins",
"token_count": 283
} | 1,443 |
// 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 '../types.dart';
import 'maps_object.dart';
/// Converts an [Iterable] of Markers in a Map of MarkerId -> Marker.
Map<MarkerId, Marker> keyByMarkerId(Iterable<Marker> markers) {
return keyByMapsObjectId<Marker>(markers).cast<MarkerId, Marker>();
}
/// Converts a Set of Markers into something serializable in JSON.
Object serializeMarkerSet(Set<Marker> markers) {
return serializeMapsObjectSet(markers);
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/marker.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/marker.dart",
"repo_id": "plugins",
"token_count": 184
} | 1,444 |
// 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.
// These tests render an app with a small map widget, and use its map controller
// to compute values of the default projection.
// (Tests methods that can't be mocked in `google_maps_controller_test.dart`)
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart'
show GoogleMap, GoogleMapController;
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:integration_test/integration_test.dart';
// This value is used when comparing long~num, like LatLng values.
const double _acceptableLatLngDelta = 0.0000000001;
// This value is used when comparing pixel measurements, mostly to gloss over
// browser rounding errors.
const int _acceptablePixelDelta = 1;
/// Test Google Map Controller
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('Methods that require a proper Projection', () {
const LatLng center = LatLng(43.3078, -5.6958);
const Size size = Size(320, 240);
const CameraPosition initialCamera = CameraPosition(
target: center,
zoom: 14,
);
late Completer<GoogleMapController> controllerCompleter;
late void Function(GoogleMapController) onMapCreated;
setUp(() {
controllerCompleter = Completer<GoogleMapController>();
onMapCreated = (GoogleMapController mapController) {
controllerCompleter.complete(mapController);
};
});
group('getScreenCoordinate', () {
testWidgets('target of map is in center of widget',
(WidgetTester tester) async {
await pumpCenteredMap(
tester,
initialCamera: initialCamera,
size: size,
onMapCreated: onMapCreated,
);
final GoogleMapController controller = await controllerCompleter.future;
final ScreenCoordinate screenPosition =
await controller.getScreenCoordinate(center);
expect(
screenPosition.x,
closeTo(size.width / 2, _acceptablePixelDelta),
);
expect(
screenPosition.y,
closeTo(size.height / 2, _acceptablePixelDelta),
);
});
testWidgets('NorthWest of visible region corresponds to x:0, y:0',
(WidgetTester tester) async {
await pumpCenteredMap(
tester,
initialCamera: initialCamera,
size: size,
onMapCreated: onMapCreated,
);
final GoogleMapController controller = await controllerCompleter.future;
final LatLngBounds bounds = await controller.getVisibleRegion();
final LatLng northWest = LatLng(
bounds.northeast.latitude,
bounds.southwest.longitude,
);
final ScreenCoordinate screenPosition =
await controller.getScreenCoordinate(northWest);
expect(screenPosition.x, closeTo(0, _acceptablePixelDelta));
expect(screenPosition.y, closeTo(0, _acceptablePixelDelta));
});
testWidgets(
'SouthEast of visible region corresponds to x:size.width, y:size.height',
(WidgetTester tester) async {
await pumpCenteredMap(
tester,
initialCamera: initialCamera,
size: size,
onMapCreated: onMapCreated,
);
final GoogleMapController controller = await controllerCompleter.future;
final LatLngBounds bounds = await controller.getVisibleRegion();
final LatLng southEast = LatLng(
bounds.southwest.latitude,
bounds.northeast.longitude,
);
final ScreenCoordinate screenPosition =
await controller.getScreenCoordinate(southEast);
expect(screenPosition.x, closeTo(size.width, _acceptablePixelDelta));
expect(screenPosition.y, closeTo(size.height, _acceptablePixelDelta));
});
});
group('getLatLng', () {
testWidgets('Center of widget is the target of map',
(WidgetTester tester) async {
await pumpCenteredMap(
tester,
initialCamera: initialCamera,
size: size,
onMapCreated: onMapCreated,
);
final GoogleMapController controller = await controllerCompleter.future;
final LatLng coords = await controller.getLatLng(
ScreenCoordinate(x: size.width ~/ 2, y: size.height ~/ 2),
);
expect(
coords.latitude,
closeTo(center.latitude, _acceptableLatLngDelta),
);
expect(
coords.longitude,
closeTo(center.longitude, _acceptableLatLngDelta),
);
});
testWidgets('Top-left of widget is NorthWest bound of map',
(WidgetTester tester) async {
await pumpCenteredMap(
tester,
initialCamera: initialCamera,
size: size,
onMapCreated: onMapCreated,
);
final GoogleMapController controller = await controllerCompleter.future;
final LatLngBounds bounds = await controller.getVisibleRegion();
final LatLng northWest = LatLng(
bounds.northeast.latitude,
bounds.southwest.longitude,
);
final LatLng coords = await controller.getLatLng(
const ScreenCoordinate(x: 0, y: 0),
);
expect(
coords.latitude,
closeTo(northWest.latitude, _acceptableLatLngDelta),
);
expect(
coords.longitude,
closeTo(northWest.longitude, _acceptableLatLngDelta),
);
});
testWidgets('Bottom-right of widget is SouthWest bound of map',
(WidgetTester tester) async {
await pumpCenteredMap(
tester,
initialCamera: initialCamera,
size: size,
onMapCreated: onMapCreated,
);
final GoogleMapController controller = await controllerCompleter.future;
final LatLngBounds bounds = await controller.getVisibleRegion();
final LatLng southEast = LatLng(
bounds.southwest.latitude,
bounds.northeast.longitude,
);
final LatLng coords = await controller.getLatLng(
ScreenCoordinate(x: size.width.toInt(), y: size.height.toInt()),
);
expect(
coords.latitude,
closeTo(southEast.latitude, _acceptableLatLngDelta),
);
expect(
coords.longitude,
closeTo(southEast.longitude, _acceptableLatLngDelta),
);
});
});
});
}
// Pumps a CenteredMap Widget into a given tester, with some parameters
Future<void> pumpCenteredMap(
WidgetTester tester, {
required CameraPosition initialCamera,
Size? size,
void Function(GoogleMapController)? onMapCreated,
}) async {
await tester.pumpWidget(
CenteredMap(
initialCamera: initialCamera,
size: size ?? const Size(320, 240),
onMapCreated: onMapCreated,
),
);
// This is needed to kick-off the rendering of the JS Map flutter widget
await tester.pump();
}
/// Renders a Map widget centered on the screen.
/// This depends in `package:google_maps_flutter` to work.
class CenteredMap extends StatelessWidget {
const CenteredMap({
required this.initialCamera,
required this.size,
required this.onMapCreated,
Key? key,
}) : super(key: key);
/// A function that receives the [GoogleMapController] of the Map widget once initialized.
final void Function(GoogleMapController)? onMapCreated;
/// The size of the rendered map widget.
final Size size;
/// The initial camera position (center + zoom level) of the Map widget.
final CameraPosition initialCamera;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: SizedBox.fromSize(
size: size,
child: GoogleMap(
initialCameraPosition: initialCamera,
onMapCreated: onMapCreated,
),
),
),
),
);
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/projection_test.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/projection_test.dart",
"repo_id": "plugins",
"token_count": 3273
} | 1,445 |
// 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.
part of google_maps_flutter_web;
/// The `MarkerController` class wraps a [gmaps.Marker], how it handles events, and its associated (optional) [gmaps.InfoWindow] widget.
class MarkerController {
/// Creates a `MarkerController`, which wraps a [gmaps.Marker] object, its `onTap`/`onDrag` behavior, and its associated [gmaps.InfoWindow].
MarkerController({
required gmaps.Marker marker,
gmaps.InfoWindow? infoWindow,
bool consumeTapEvents = false,
LatLngCallback? onDragStart,
LatLngCallback? onDrag,
LatLngCallback? onDragEnd,
ui.VoidCallback? onTap,
}) : _marker = marker,
_infoWindow = infoWindow,
_consumeTapEvents = consumeTapEvents {
if (onTap != null) {
marker.onClick.listen((gmaps.MapMouseEvent event) {
onTap.call();
});
}
if (onDragStart != null) {
marker.onDragstart.listen((gmaps.MapMouseEvent event) {
if (marker != null) {
marker.position = event.latLng;
}
onDragStart.call(event.latLng ?? _nullGmapsLatLng);
});
}
if (onDrag != null) {
marker.onDrag.listen((gmaps.MapMouseEvent event) {
if (marker != null) {
marker.position = event.latLng;
}
onDrag.call(event.latLng ?? _nullGmapsLatLng);
});
}
if (onDragEnd != null) {
marker.onDragend.listen((gmaps.MapMouseEvent event) {
if (marker != null) {
marker.position = event.latLng;
}
onDragEnd.call(event.latLng ?? _nullGmapsLatLng);
});
}
}
gmaps.Marker? _marker;
final bool _consumeTapEvents;
final gmaps.InfoWindow? _infoWindow;
bool _infoWindowShown = false;
/// Returns `true` if this Controller will use its own `onTap` handler to consume events.
bool get consumeTapEvents => _consumeTapEvents;
/// Returns `true` if the [gmaps.InfoWindow] associated to this marker is being shown.
bool get infoWindowShown => _infoWindowShown;
/// Returns the [gmaps.Marker] associated to this controller.
gmaps.Marker? get marker => _marker;
/// Returns the [gmaps.InfoWindow] associated to the marker.
@visibleForTesting
gmaps.InfoWindow? get infoWindow => _infoWindow;
/// Updates the options of the wrapped [gmaps.Marker] object.
///
/// This cannot be called after [remove].
void update(
gmaps.MarkerOptions options, {
HtmlElement? newInfoWindowContent,
}) {
assert(_marker != null, 'Cannot `update` Marker after calling `remove`.');
_marker!.options = options;
if (_infoWindow != null && newInfoWindowContent != null) {
_infoWindow!.content = newInfoWindowContent;
}
}
/// Disposes of the currently wrapped [gmaps.Marker].
void remove() {
if (_marker != null) {
_infoWindowShown = false;
_marker!.visible = false;
_marker!.map = null;
_marker = null;
}
}
/// Hide the associated [gmaps.InfoWindow].
///
/// This cannot be called after [remove].
void hideInfoWindow() {
assert(_marker != null, 'Cannot `hideInfoWindow` on a `remove`d Marker.');
if (_infoWindow != null) {
_infoWindow!.close();
_infoWindowShown = false;
}
}
/// Show the associated [gmaps.InfoWindow].
///
/// This cannot be called after [remove].
void showInfoWindow() {
assert(_marker != null, 'Cannot `showInfoWindow` on a `remove`d Marker.');
if (_infoWindow != null) {
_infoWindow!.open(_marker!.map, _marker);
_infoWindowShown = true;
}
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker.dart",
"repo_id": "plugins",
"token_count": 1377
} | 1,446 |
// 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/services.dart' show MethodCall;
/// A fake backend that can be used to test components that require a valid
/// [GoogleSignInAccount].
///
/// Example usage:
///
/// ```
/// GoogleSignIn googleSignIn;
/// FakeSignInBackend fakeSignInBackend;
///
/// setUp(() {
/// googleSignIn = GoogleSignIn();
/// fakeSignInBackend = FakeSignInBackend();
/// fakeSignInBackend.user = FakeUser(
/// id: 123,
/// email: '[email protected]',
/// );
/// googleSignIn.channel.setMockMethodCallHandler(
/// fakeSignInBackend.handleMethodCall);
/// });
/// ```
///
class FakeSignInBackend {
/// A [FakeUser] object.
///
/// This does not represent the signed-in user, but rather an object that will
/// be returned when [GoogleSignIn.signIn] or [GoogleSignIn.signInSilently] is
/// called.
late FakeUser user;
/// Handles method calls that would normally be sent to the native backend.
/// Returns with the expected values based on the current [user].
Future<dynamic> handleMethodCall(MethodCall methodCall) async {
switch (methodCall.method) {
case 'init':
// do nothing
return null;
case 'getTokens':
return <String, String?>{
'idToken': user.idToken,
'accessToken': user.accessToken,
};
case 'signIn':
return user._asMap;
case 'signInSilently':
return user._asMap;
case 'signOut':
return <String, String>{};
case 'disconnect':
return <String, String>{};
}
}
}
/// Represents a fake user that can be used with the [FakeSignInBackend] to
/// obtain a [GoogleSignInAccount] and simulate authentication.
class FakeUser {
/// Any of the given parameters can be null.
const FakeUser({
this.id,
this.email,
this.displayName,
this.photoUrl,
this.serverAuthCode,
this.idToken,
this.accessToken,
});
/// Will be converted into [GoogleSignInUserData.id].
final String? id;
/// Will be converted into [GoogleSignInUserData.email].
final String? email;
/// Will be converted into [GoogleSignInUserData.displayName].
final String? displayName;
/// Will be converted into [GoogleSignInUserData.photoUrl].
final String? photoUrl;
/// Will be converted into [GoogleSignInUserData.serverAuthCode].
final String? serverAuthCode;
/// Will be converted into [GoogleSignInTokenData.idToken].
final String? idToken;
/// Will be converted into [GoogleSignInTokenData.accessToken].
final String? accessToken;
Map<String, String?> get _asMap => <String, String?>{
'id': id,
'email': email,
'displayName': displayName,
'photoUrl': photoUrl,
'serverAuthCode': serverAuthCode,
'idToken': idToken,
};
}
| plugins/packages/google_sign_in/google_sign_in/lib/testing.dart/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in/lib/testing.dart",
"repo_id": "plugins",
"token_count": 1033
} | 1,447 |
// 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.googlesignin;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* A class for running tasks in a background thread.
*
* <p>TODO(jackson): If this class is useful for other plugins, consider including it in a shared
* library or in the Flutter engine
*/
public final class BackgroundTaskRunner {
/**
* Interface that callers of this API can implement to be notified when a {@link
* #runInBackground(Callable,Callback) background task} has completed.
*/
public interface Callback<T> {
/**
* Invoked on the UI thread when the specified future has completed (calling {@code get()} on
* the future is guaranteed not to block). If the future completed with an exception, then
* {@code get()} will throw an {@code ExecutionException}.
*/
void run(Future<T> future);
}
private final ThreadPoolExecutor executor;
/**
* Creates a new background processor with the given number of threads.
*
* @param threads The fixed number of threads in ther pool.
*/
public BackgroundTaskRunner(int threads) {
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
// Only keeps idle threads open for 1 second if we've got more threads than cores.
executor = new ThreadPoolExecutor(threads, threads, 1, TimeUnit.SECONDS, workQueue);
}
/**
* Executes the specified task in a background thread and notifies the specified callback once the
* task has completed (either successfully or with an exception).
*
* <p>The callback will be notified on the UI thread.
*/
public <T> void runInBackground(Callable<T> task, final Callback<T> callback) {
final ListenableFuture<T> future = runInBackground(task);
future.addListener(
new Runnable() {
@Override
public void run() {
callback.run(future);
}
},
Executors.uiThreadExecutor());
}
/**
* Executes the specified task in a background thread and returns a future with which the caller
* can be notified of task completion.
*
* <p>Note: the future will be notified on the background thread. To be notified on the UI thread,
* use {@link #runInBackground(Callable,Callback)}.
*/
public <T> ListenableFuture<T> runInBackground(final Callable<T> task) {
final SettableFuture<T> future = SettableFuture.create();
executor.execute(
new Runnable() {
@Override
public void run() {
if (!future.isCancelled()) {
try {
future.set(task.call());
} catch (Throwable t) {
future.setException(t);
}
}
}
});
return future;
}
}
| plugins/packages/google_sign_in/google_sign_in_android/android/src/main/java/io/flutter/plugins/googlesignin/BackgroundTaskRunner.java/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_android/android/src/main/java/io/flutter/plugins/googlesignin/BackgroundTaskRunner.java",
"repo_id": "plugins",
"token_count": 1102
} | 1,448 |
name: google_sign_in_android
description: Android implementation of the google_sign_in plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/google_sign_in/google_sign_in_android
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+google_sign_in%22
version: 6.1.6
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: google_sign_in
platforms:
android:
dartPluginClass: GoogleSignInAndroid
package: io.flutter.plugins.googlesignin
pluginClass: GoogleSignInPlugin
dependencies:
flutter:
sdk: flutter
google_sign_in_platform_interface: ^2.2.0
dev_dependencies:
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
# The example deliberately includes limited-use secrets.
false_secrets:
- /example/android/app/google-services.json
- /example/lib/main.dart
| plugins/packages/google_sign_in/google_sign_in_android/pubspec.yaml/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_android/pubspec.yaml",
"repo_id": "plugins",
"token_count": 380
} | 1,449 |
// 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/widgets.dart';
import 'package:quiver/core.dart';
/// Default configuration options to use when signing in.
///
/// See also https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInOptions
enum SignInOption {
/// Default configuration. Provides stable user ID and basic profile information.
///
/// See also https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInOptions.html#DEFAULT_SIGN_IN.
standard,
/// Recommended configuration for Games sign in.
///
/// This is currently only supported on Android and will throw an error if used
/// on other platforms.
///
/// See also https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInOptions.html#public-static-final-googlesigninoptions-default_games_sign_in.
games
}
/// The parameters to use when initializing the sign in process.
///
/// See:
/// https://developers.google.com/identity/sign-in/web/reference#gapiauth2initparams
@immutable
class SignInInitParameters {
/// The parameters to use when initializing the sign in process.
const SignInInitParameters({
this.scopes = const <String>[],
this.signInOption = SignInOption.standard,
this.hostedDomain,
this.clientId,
this.serverClientId,
this.forceCodeForRefreshToken = false,
});
/// The list of OAuth scope codes to request when signing in.
final List<String> scopes;
/// The user experience to use when signing in. [SignInOption.games] is
/// only supported on Android.
final SignInOption signInOption;
/// Restricts sign in to accounts of the user in the specified domain.
/// By default, the list of accounts will not be restricted.
final String? hostedDomain;
/// The OAuth client ID of the app.
///
/// The default is null, which means that the client ID will be sourced from a
/// configuration file, if required on the current platform. A value specified
/// here takes precedence over a value specified in a configuration file.
/// See also:
///
/// * [Platform Integration](https://github.com/flutter/plugins/tree/main/packages/google_sign_in/google_sign_in#platform-integration),
/// where you can find the details about the configuration files.
final String? clientId;
/// The OAuth client ID of the backend server.
///
/// The default is null, which means that the server client ID will be sourced
/// from a configuration file, if available and supported on the current
/// platform. A value specified here takes precedence over a value specified
/// in a configuration file.
///
/// See also:
///
/// * [Platform Integration](https://github.com/flutter/plugins/tree/main/packages/google_sign_in/google_sign_in#platform-integration),
/// where you can find the details about the configuration files.
final String? serverClientId;
/// If true, ensures the authorization code can be exchanged for an access
/// token.
///
/// This is only used on Android.
final bool forceCodeForRefreshToken;
}
/// Holds information about the signed in user.
class GoogleSignInUserData {
/// Uses the given data to construct an instance.
GoogleSignInUserData({
required this.email,
required this.id,
this.displayName,
this.photoUrl,
this.idToken,
this.serverAuthCode,
});
/// The display name of the signed in user.
///
/// Not guaranteed to be present for all users, even when configured.
String? displayName;
/// The email address of the signed in user.
///
/// Applications should not key users by email address since a Google account's
/// email address can change. Use [id] as a key instead.
///
/// _Important_: Do not use this returned email address to communicate the
/// currently signed in user to your backend server. Instead, send an ID token
/// which can be securely validated on the server. See [idToken].
String email;
/// The unique ID for the Google account.
///
/// This is the preferred unique key to use for a user record.
///
/// _Important_: Do not use this returned Google ID to communicate the
/// currently signed in user to your backend server. Instead, send an ID token
/// which can be securely validated on the server. See [idToken].
String id;
/// The photo url of the signed in user if the user has a profile picture.
///
/// Not guaranteed to be present for all users, even when configured.
String? photoUrl;
/// A token that can be sent to your own server to verify the authentication
/// data.
String? idToken;
/// Server auth code used to access Google Login
String? serverAuthCode;
@override
// TODO(stuartmorgan): Make this class immutable in the next breaking change.
// ignore: avoid_equals_and_hash_code_on_mutable_classes
int get hashCode => hashObjects(
<String?>[displayName, email, id, photoUrl, idToken, serverAuthCode]);
@override
// TODO(stuartmorgan): Make this class immutable in the next breaking change.
// ignore: avoid_equals_and_hash_code_on_mutable_classes
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other is! GoogleSignInUserData) {
return false;
}
final GoogleSignInUserData otherUserData = other;
return otherUserData.displayName == displayName &&
otherUserData.email == email &&
otherUserData.id == id &&
otherUserData.photoUrl == photoUrl &&
otherUserData.idToken == idToken &&
otherUserData.serverAuthCode == serverAuthCode;
}
}
/// Holds authentication data after sign in.
class GoogleSignInTokenData {
/// Build `GoogleSignInTokenData`.
GoogleSignInTokenData({
this.idToken,
this.accessToken,
this.serverAuthCode,
});
/// An OpenID Connect ID token for the authenticated user.
String? idToken;
/// The OAuth2 access token used to access Google services.
String? accessToken;
/// Server auth code used to access Google Login
String? serverAuthCode;
@override
// TODO(stuartmorgan): Make this class immutable in the next breaking change.
// ignore: avoid_equals_and_hash_code_on_mutable_classes
int get hashCode => hash3(idToken, accessToken, serverAuthCode);
@override
// TODO(stuartmorgan): Make this class immutable in the next breaking change.
// ignore: avoid_equals_and_hash_code_on_mutable_classes
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other is! GoogleSignInTokenData) {
return false;
}
final GoogleSignInTokenData otherTokenData = other;
return otherTokenData.idToken == idToken &&
otherTokenData.accessToken == accessToken &&
otherTokenData.serverAuthCode == serverAuthCode;
}
}
| plugins/packages/google_sign_in/google_sign_in_platform_interface/lib/src/types.dart/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_platform_interface/lib/src/types.dart",
"repo_id": "plugins",
"token_count": 2055
} | 1,450 |
// 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:google_identity_services_web/id.dart';
import 'jsify_as.dart';
/// A CredentialResponse with null `credential`.
final CredentialResponse nullCredential =
jsifyAs<CredentialResponse>(<String, Object?>{
'credential': null,
});
/// A CredentialResponse wrapping a known good JWT Token as its `credential`.
final CredentialResponse goodCredential =
jsifyAs<CredentialResponse>(<String, Object?>{
'credential': goodJwtToken,
});
/// A JWT token with predefined values.
///
/// 'email': '[email protected]',
/// 'sub': '123456',
/// 'name': 'Vincent Adultman',
/// 'picture': 'https://thispersondoesnotexist.com/image?x=.jpg',
///
/// Signed with HS256 and the private key: 'symmetric-encryption-is-weak'
const String goodJwtToken =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.$goodPayload.lqzULA_U3YzEl_-fL7YLU-kFXmdD2ttJLTv-UslaNQ4';
/// The payload of a JWT token that contains predefined values.
///
/// 'email': '[email protected]',
/// 'sub': '123456',
/// 'name': 'Vincent Adultman',
/// 'picture': 'https://thispersondoesnotexist.com/image?x=.jpg',
const String goodPayload =
'eyJlbWFpbCI6ImFkdWx0bWFuQGV4YW1wbGUuY29tIiwic3ViIjoiMTIzNDU2IiwibmFtZSI6IlZpbmNlbnQgQWR1bHRtYW4iLCJwaWN0dXJlIjoiaHR0cHM6Ly90aGlzcGVyc29uZG9lc25vdGV4aXN0LmNvbS9pbWFnZT94PS5qcGcifQ';
// More encrypted JWT Tokens may be created on https://jwt.io.
//
// First, decode the `goodJwtToken` above, modify to your heart's
// content, and add a new credential here.
//
// (New tokens can also be created with `package:jose` and `dart:convert`.)
| plugins/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jwt_examples.dart/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jwt_examples.dart",
"repo_id": "plugins",
"token_count": 671
} | 1,451 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.imagepicker">
<application>
<provider
android:name="io.flutter.plugins.imagepicker.ImagePickerFileProvider"
android:authorities="${applicationId}.flutter.image_provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/flutter_image_picker_file_paths" />
</provider>
</application>
</manifest>
| plugins/packages/image_picker/image_picker_android/android/src/main/AndroidManifest.xml/0 | {
"file_path": "plugins/packages/image_picker/image_picker_android/android/src/main/AndroidManifest.xml",
"repo_id": "plugins",
"token_count": 275
} | 1,452 |
// 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 'camera_device.dart';
export 'image_options.dart';
export 'image_picker_options.dart';
export 'image_source.dart';
export 'lost_data_response.dart';
export 'multi_image_picker_options.dart';
export 'picked_file/picked_file.dart';
export 'retrieve_type.dart';
/// Denotes that an image is being picked.
const String kTypeImage = 'image';
/// Denotes that a video is being picked.
const String kTypeVideo = 'video';
| plugins/packages/image_picker/image_picker_platform_interface/lib/src/types/types.dart/0 | {
"file_path": "plugins/packages/image_picker/image_picker_platform_interface/lib/src/types/types.dart",
"repo_id": "plugins",
"token_count": 181
} | 1,453 |
// Mocks generated by Mockito 5.1.0 from annotations
// in image_picker_windows/example/windows/flutter/ephemeral/.plugin_symlinks/image_picker_windows/test/image_picker_windows_test.dart.
// Do not manually edit this file.
import 'dart:async' as _i3;
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'
as _i2;
import 'package:mockito/mockito.dart' as _i1;
// 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
/// A class which mocks [FileSelectorPlatform].
///
/// See the documentation for Mockito's code generation for more information.
class MockFileSelectorPlatform extends _i1.Mock
implements _i2.FileSelectorPlatform {
MockFileSelectorPlatform() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<_i2.XFile?> openFile(
{List<_i2.XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText}) =>
(super.noSuchMethod(
Invocation.method(#openFile, [], {
#acceptedTypeGroups: acceptedTypeGroups,
#initialDirectory: initialDirectory,
#confirmButtonText: confirmButtonText
}),
returnValue: Future<_i2.XFile?>.value()) as _i3.Future<_i2.XFile?>);
@override
_i3.Future<List<_i2.XFile>> openFiles(
{List<_i2.XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText}) =>
(super.noSuchMethod(
Invocation.method(#openFiles, [], {
#acceptedTypeGroups: acceptedTypeGroups,
#initialDirectory: initialDirectory,
#confirmButtonText: confirmButtonText
}),
returnValue: Future<List<_i2.XFile>>.value(<_i2.XFile>[]))
as _i3.Future<List<_i2.XFile>>);
@override
_i3.Future<String?> getSavePath(
{List<_i2.XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? suggestedName,
String? confirmButtonText}) =>
(super.noSuchMethod(
Invocation.method(#getSavePath, [], {
#acceptedTypeGroups: acceptedTypeGroups,
#initialDirectory: initialDirectory,
#suggestedName: suggestedName,
#confirmButtonText: confirmButtonText
}),
returnValue: Future<String?>.value()) as _i3.Future<String?>);
@override
_i3.Future<String?> getDirectoryPath(
{String? initialDirectory, String? confirmButtonText}) =>
(super.noSuchMethod(
Invocation.method(#getDirectoryPath, [], {
#initialDirectory: initialDirectory,
#confirmButtonText: confirmButtonText
}),
returnValue: Future<String?>.value()) as _i3.Future<String?>);
}
| plugins/packages/image_picker/image_picker_windows/test/image_picker_windows_test.mocks.dart/0 | {
"file_path": "plugins/packages/image_picker/image_picker_windows/test/image_picker_windows_test.mocks.dart",
"repo_id": "plugins",
"token_count": 1300
} | 1,454 |
// 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:shared_preferences/shared_preferences.dart';
// ignore: avoid_classes_with_only_static_members
/// A store of consumable items.
///
/// This is a development prototype tha stores consumables in the shared
/// preferences. Do not use this in real world apps.
class ConsumableStore {
static const String _kPrefKey = 'consumables';
static Future<void> _writes = Future<void>.value();
/// Adds a consumable with ID `id` to the store.
///
/// The consumable is only added after the returned Future is complete.
static Future<void> save(String id) {
_writes = _writes.then((void _) => _doSave(id));
return _writes;
}
/// Consumes a consumable with ID `id` from the store.
///
/// The consumable was only consumed after the returned Future is complete.
static Future<void> consume(String id) {
_writes = _writes.then((void _) => _doConsume(id));
return _writes;
}
/// Returns the list of consumables from the store.
static Future<List<String>> load() async {
return (await SharedPreferences.getInstance()).getStringList(_kPrefKey) ??
<String>[];
}
static Future<void> _doSave(String id) async {
final List<String> cached = await load();
final SharedPreferences prefs = await SharedPreferences.getInstance();
cached.add(id);
await prefs.setStringList(_kPrefKey, cached);
}
static Future<void> _doConsume(String id) async {
final List<String> cached = await load();
final SharedPreferences prefs = await SharedPreferences.getInstance();
cached.remove(id);
await prefs.setStringList(_kPrefKey, cached);
}
}
| plugins/packages/in_app_purchase/in_app_purchase/example/lib/consumable_store.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase/example/lib/consumable_store.dart",
"repo_id": "plugins",
"token_count": 563
} | 1,455 |
// 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.inapppurchase;
import android.content.Context;
import androidx.annotation.NonNull;
import com.android.billingclient.api.BillingClient;
import io.flutter.plugin.common.MethodChannel;
/** Responsible for creating a {@link BillingClient} object. */
interface BillingClientFactory {
/**
* Creates and returns a {@link BillingClient}.
*
* @param context The context used to create the {@link BillingClient}.
* @param channel The method channel used to create the {@link BillingClient}.
* @return The {@link BillingClient} object that is created.
*/
BillingClient createBillingClient(@NonNull Context context, @NonNull MethodChannel channel);
}
| plugins/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/BillingClientFactory.java/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/BillingClientFactory.java",
"repo_id": "plugins",
"token_count": 243
} | 1,456 |
// 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 '../../billing_client_wrappers.dart';
import 'types.dart';
/// This parameter object for upgrading or downgrading an existing subscription.
class ChangeSubscriptionParam {
/// Creates a new change subscription param object with given data
ChangeSubscriptionParam({
required this.oldPurchaseDetails,
this.prorationMode,
});
/// The purchase object of the existing subscription that the user needs to
/// upgrade/downgrade from.
final GooglePlayPurchaseDetails oldPurchaseDetails;
/// The proration mode.
///
/// This is an optional parameter that indicates how to handle the existing
/// subscription when the new subscription comes into effect.
final ProrationMode? prorationMode;
}
| plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/types/change_subscription_param.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/types/change_subscription_param.dart",
"repo_id": "plugins",
"token_count": 220
} | 1,457 |
name: in_app_purchase_platform_interface
description: A common platform interface for the in_app_purchase plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/in_app_purchase/in_app_purchase_platform_interface
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+in_app_purchase%22
# NOTE: We strongly prefer non-breaking changes, even at the expense of a
# less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes
version: 1.3.2
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
plugin_platform_interface: ^2.1.0
dev_dependencies:
flutter_test:
sdk: flutter
mockito: ^5.0.0
| plugins/packages/in_app_purchase/in_app_purchase_platform_interface/pubspec.yaml/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_platform_interface/pubspec.yaml",
"repo_id": "plugins",
"token_count": 277
} | 1,458 |
// 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 <Foundation/Foundation.h>
#import <StoreKit/StoreKit.h>
NS_ASSUME_NONNULL_BEGIN
typedef void (^ProductRequestCompletion)(SKProductsResponse *_Nullable response,
NSError *_Nullable errror);
@interface FIAPRequestHandler : NSObject
- (instancetype)initWithRequest:(SKRequest *)request;
- (void)startProductRequestWithCompletionHandler:(ProductRequestCompletion)completion;
@end
NS_ASSUME_NONNULL_END
| plugins/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/FIAPRequestHandler.h/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/FIAPRequestHandler.h",
"repo_id": "plugins",
"token_count": 219
} | 1,459 |
// 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 "FIAObjectTranslator.h"
#import "FIAPaymentQueueHandler.h"
#import "Stubs.h"
@import in_app_purchase_storekit;
API_AVAILABLE(ios(13.0))
API_UNAVAILABLE(tvos, macos, watchos)
@interface FIAPPaymentQueueDelegateTests : XCTestCase
@property(strong, nonatomic) FlutterMethodChannel *channel;
@property(strong, nonatomic) SKPaymentTransaction *transaction;
@property(strong, nonatomic) SKStorefront *storefront;
@end
@implementation FIAPPaymentQueueDelegateTests
- (void)setUp {
self.channel = OCMClassMock(FlutterMethodChannel.class);
NSDictionary *transactionMap = @{
@"transactionIdentifier" : [NSNull null],
@"transactionState" : @(SKPaymentTransactionStatePurchasing),
@"payment" : [NSNull null],
@"error" : [FIAObjectTranslator getMapFromNSError:[NSError errorWithDomain:@"test_stub"
code:123
userInfo:@{}]],
@"transactionTimeStamp" : @([NSDate date].timeIntervalSince1970),
@"originalTransaction" : [NSNull null],
};
self.transaction = [[SKPaymentTransactionStub alloc] initWithMap:transactionMap];
NSDictionary *storefrontMap = @{
@"countryCode" : @"USA",
@"identifier" : @"unique_identifier",
};
self.storefront = [[SKStorefrontStub alloc] initWithMap:storefrontMap];
}
- (void)tearDown {
self.channel = nil;
}
- (void)testShouldContinueTransaction {
if (@available(iOS 13.0, *)) {
FIAPPaymentQueueDelegate *delegate =
[[FIAPPaymentQueueDelegate alloc] initWithMethodChannel:self.channel];
OCMStub([self.channel
invokeMethod:@"shouldContinueTransaction"
arguments:[FIAObjectTranslator getMapFromSKStorefront:self.storefront
andSKPaymentTransaction:self.transaction]
result:([OCMArg invokeBlockWithArgs:[NSNumber numberWithBool:NO], nil])]);
BOOL shouldContinue = [delegate paymentQueue:OCMClassMock(SKPaymentQueue.class)
shouldContinueTransaction:self.transaction
inStorefront:self.storefront];
XCTAssertFalse(shouldContinue);
}
}
- (void)testShouldContinueTransaction_should_default_to_yes {
if (@available(iOS 13.0, *)) {
FIAPPaymentQueueDelegate *delegate =
[[FIAPPaymentQueueDelegate alloc] initWithMethodChannel:self.channel];
OCMStub([self.channel invokeMethod:@"shouldContinueTransaction"
arguments:[FIAObjectTranslator getMapFromSKStorefront:self.storefront
andSKPaymentTransaction:self.transaction]
result:[OCMArg any]]);
BOOL shouldContinue = [delegate paymentQueue:OCMClassMock(SKPaymentQueue.class)
shouldContinueTransaction:self.transaction
inStorefront:self.storefront];
XCTAssertTrue(shouldContinue);
}
}
#if TARGET_OS_IOS
- (void)testShouldShowPriceConsentIfNeeded {
if (@available(iOS 13.4, *)) {
FIAPPaymentQueueDelegate *delegate =
[[FIAPPaymentQueueDelegate alloc] initWithMethodChannel:self.channel];
OCMStub([self.channel
invokeMethod:@"shouldShowPriceConsent"
arguments:nil
result:([OCMArg invokeBlockWithArgs:[NSNumber numberWithBool:NO], nil])]);
BOOL shouldShow =
[delegate paymentQueueShouldShowPriceConsent:OCMClassMock(SKPaymentQueue.class)];
XCTAssertFalse(shouldShow);
}
}
#endif
#if TARGET_OS_IOS
- (void)testShouldShowPriceConsentIfNeeded_should_default_to_yes {
if (@available(iOS 13.4, *)) {
FIAPPaymentQueueDelegate *delegate =
[[FIAPPaymentQueueDelegate alloc] initWithMethodChannel:self.channel];
OCMStub([self.channel invokeMethod:@"shouldShowPriceConsent"
arguments:nil
result:[OCMArg any]]);
BOOL shouldShow =
[delegate paymentQueueShouldShowPriceConsent:OCMClassMock(SKPaymentQueue.class)];
XCTAssertTrue(shouldShow);
}
}
#endif
@end
| plugins/packages/in_app_purchase/in_app_purchase_storekit/example/ios/RunnerTests/FIAPPaymentQueueDeleteTests.m/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/example/ios/RunnerTests/FIAPPaymentQueueDeleteTests.m",
"repo_id": "plugins",
"token_count": 1870
} | 1,460 |
// 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:json_annotation/json_annotation.dart';
part 'sk_storefront_wrapper.g.dart';
/// Contains the location and unique identifier of an Apple App Store storefront.
///
/// Dart wrapper around StoreKit's
/// [SKStorefront](https://developer.apple.com/documentation/storekit/skstorefront?language=objc).
@JsonSerializable(createToJson: true)
@immutable
class SKStorefrontWrapper {
/// Creates a new [SKStorefrontWrapper] with the provided information.
// TODO(stuartmorgan): Temporarily ignore const warning in other parts of the
// federated package, and remove this.
// ignore: prefer_const_constructors_in_immutables
SKStorefrontWrapper({
required this.countryCode,
required this.identifier,
});
/// Constructs an instance of the [SKStorefrontWrapper] from a key value map
/// of data.
///
/// The map needs to have named string keys with values matching the names and
/// types of all of the members on this class. The `map` parameter must not be
/// null.
factory SKStorefrontWrapper.fromJson(Map<String, dynamic> map) {
return _$SKStorefrontWrapperFromJson(map);
}
/// The three-letter code representing the country or region associated with
/// the App Store storefront.
final String countryCode;
/// A value defined by Apple that uniquely identifies an App Store storefront.
final String identifier;
@override
bool operator ==(Object other) {
if (identical(other, this)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is SKStorefrontWrapper &&
other.countryCode == countryCode &&
other.identifier == identifier;
}
@override
int get hashCode => Object.hash(
countryCode,
identifier,
);
@override
String toString() => _$SKStorefrontWrapperToJson(this).toString();
/// Converts the instance to a key value map which can be used to serialize
/// to JSON format.
Map<String, dynamic> toMap() => _$SKStorefrontWrapperToJson(this);
}
| plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_storefront_wrapper.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_storefront_wrapper.dart",
"repo_id": "plugins",
"token_count": 684
} | 1,461 |
// 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 "FIAPaymentQueueHandler.h"
#import "FIAPPaymentQueueDelegate.h"
#import "FIATransactionCache.h"
@interface FIAPaymentQueueHandler ()
/// The SKPaymentQueue instance connected to the App Store and responsible for processing
/// transactions.
@property(strong, nonatomic) SKPaymentQueue *queue;
/// Callback method that is called each time the App Store indicates transactions are updated.
@property(nullable, copy, nonatomic) TransactionsUpdated transactionsUpdated;
/// Callback method that is called each time the App Store indicates transactions are removed.
@property(nullable, copy, nonatomic) TransactionsRemoved transactionsRemoved;
/// Callback method that is called each time the App Store indicates transactions failed to restore.
@property(nullable, copy, nonatomic) RestoreTransactionFailed restoreTransactionFailed;
/// Callback method that is called each time the App Store indicates restoring of transactions has
/// finished.
@property(nullable, copy, nonatomic)
RestoreCompletedTransactionsFinished paymentQueueRestoreCompletedTransactionsFinished;
/// Callback method that is called each time an in-app purchase has been initiated from the App
/// Store.
@property(nullable, copy, nonatomic) ShouldAddStorePayment shouldAddStorePayment;
/// Callback method that is called each time the App Store indicates downloads are updated.
@property(nullable, copy, nonatomic) UpdatedDownloads updatedDownloads;
/// The transaction cache responsible for caching transactions.
///
/// Keeps track of transactions that arrive when the Flutter client is not
/// actively observing for transactions.
@property(strong, nonatomic, nonnull) FIATransactionCache *transactionCache;
/// Indicates if the Flutter client is observing transactions.
///
/// When the client is not observing, transactions are cached and send to the
/// client as soon as it starts observing. The Flutter client can start
/// observing by sending a startObservingPaymentQueue message and stop by
/// sending a stopObservingPaymentQueue message.
@property(atomic, assign, readwrite, getter=isObservingTransactions) BOOL observingTransactions;
@end
@implementation FIAPaymentQueueHandler
- (instancetype)initWithQueue:(nonnull SKPaymentQueue *)queue
transactionsUpdated:(nullable TransactionsUpdated)transactionsUpdated
transactionRemoved:(nullable TransactionsRemoved)transactionsRemoved
restoreTransactionFailed:(nullable RestoreTransactionFailed)restoreTransactionFailed
restoreCompletedTransactionsFinished:
(nullable RestoreCompletedTransactionsFinished)restoreCompletedTransactionsFinished
shouldAddStorePayment:(nullable ShouldAddStorePayment)shouldAddStorePayment
updatedDownloads:(nullable UpdatedDownloads)updatedDownloads {
return [[FIAPaymentQueueHandler alloc] initWithQueue:queue
transactionsUpdated:transactionsUpdated
transactionRemoved:transactionsRemoved
restoreTransactionFailed:restoreTransactionFailed
restoreCompletedTransactionsFinished:restoreCompletedTransactionsFinished
shouldAddStorePayment:shouldAddStorePayment
updatedDownloads:updatedDownloads
transactionCache:[[FIATransactionCache alloc] init]];
}
- (instancetype)initWithQueue:(nonnull SKPaymentQueue *)queue
transactionsUpdated:(nullable TransactionsUpdated)transactionsUpdated
transactionRemoved:(nullable TransactionsRemoved)transactionsRemoved
restoreTransactionFailed:(nullable RestoreTransactionFailed)restoreTransactionFailed
restoreCompletedTransactionsFinished:
(nullable RestoreCompletedTransactionsFinished)restoreCompletedTransactionsFinished
shouldAddStorePayment:(nullable ShouldAddStorePayment)shouldAddStorePayment
updatedDownloads:(nullable UpdatedDownloads)updatedDownloads
transactionCache:(nonnull FIATransactionCache *)transactionCache {
self = [super init];
if (self) {
_queue = queue;
_transactionsUpdated = transactionsUpdated;
_transactionsRemoved = transactionsRemoved;
_restoreTransactionFailed = restoreTransactionFailed;
_paymentQueueRestoreCompletedTransactionsFinished = restoreCompletedTransactionsFinished;
_shouldAddStorePayment = shouldAddStorePayment;
_updatedDownloads = updatedDownloads;
_transactionCache = transactionCache;
[_queue addTransactionObserver:self];
if (@available(iOS 13.0, macOS 10.15, *)) {
queue.delegate = self.delegate;
}
}
return self;
}
- (void)startObservingPaymentQueue {
self.observingTransactions = YES;
[self processCachedTransactions];
}
- (void)stopObservingPaymentQueue {
// When the client stops observing transaction, the transaction observer is
// not removed from the SKPaymentQueue. The FIAPaymentQueueHandler will cache
// trasnactions in memory when the client is not observing, allowing the app
// to process these transactions if it starts observing again during the same
// lifetime of the app.
//
// If the app is killed, cached transactions will be removed from memory;
// however, the App Store will re-deliver the transactions as soon as the app
// is started again, since the cached transactions have not been acknowledged
// by the client (by sending the `finishTransaction` message).
self.observingTransactions = NO;
}
- (void)processCachedTransactions {
NSArray *cachedObjects =
[self.transactionCache getObjectsForKey:TransactionCacheKeyUpdatedTransactions];
if (cachedObjects.count != 0) {
self.transactionsUpdated(cachedObjects);
}
cachedObjects = [self.transactionCache getObjectsForKey:TransactionCacheKeyUpdatedDownloads];
if (cachedObjects.count != 0) {
self.updatedDownloads(cachedObjects);
}
cachedObjects = [self.transactionCache getObjectsForKey:TransactionCacheKeyRemovedTransactions];
if (cachedObjects.count != 0) {
self.transactionsRemoved(cachedObjects);
}
[self.transactionCache clear];
}
- (BOOL)addPayment:(SKPayment *)payment {
for (SKPaymentTransaction *transaction in self.queue.transactions) {
if ([transaction.payment.productIdentifier isEqualToString:payment.productIdentifier]) {
return NO;
}
}
[self.queue addPayment:payment];
return YES;
}
- (void)finishTransaction:(SKPaymentTransaction *)transaction {
[self.queue finishTransaction:transaction];
}
- (void)restoreTransactions:(nullable NSString *)applicationName {
if (applicationName) {
[self.queue restoreCompletedTransactionsWithApplicationUsername:applicationName];
} else {
[self.queue restoreCompletedTransactions];
}
}
#if TARGET_OS_IOS
- (void)presentCodeRedemptionSheet {
if (@available(iOS 14, *)) {
[self.queue presentCodeRedemptionSheet];
} else {
NSLog(@"presentCodeRedemptionSheet is only available on iOS 14 or newer");
}
}
#endif
#if TARGET_OS_IOS
- (void)showPriceConsentIfNeeded {
[self.queue showPriceConsentIfNeeded];
}
#endif
#pragma mark - observing
// Sent when the transaction array has changed (additions or state changes). Client should check
// state of transactions and finish as appropriate.
- (void)paymentQueue:(SKPaymentQueue *)queue
updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
if (!self.observingTransactions) {
[_transactionCache addObjects:transactions forKey:TransactionCacheKeyUpdatedTransactions];
return;
}
// notify dart through callbacks.
self.transactionsUpdated(transactions);
}
// Sent when transactions are removed from the queue (via finishTransaction:).
- (void)paymentQueue:(SKPaymentQueue *)queue
removedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
if (!self.observingTransactions) {
[_transactionCache addObjects:transactions forKey:TransactionCacheKeyRemovedTransactions];
return;
}
self.transactionsRemoved(transactions);
}
// Sent when an error is encountered while adding transactions from the user's purchase history back
// to the queue.
- (void)paymentQueue:(SKPaymentQueue *)queue
restoreCompletedTransactionsFailedWithError:(NSError *)error {
self.restoreTransactionFailed(error);
}
// Sent when all transactions from the user's purchase history have successfully been added back to
// the queue.
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue {
self.paymentQueueRestoreCompletedTransactionsFinished();
}
// Sent when the download state has changed.
- (void)paymentQueue:(SKPaymentQueue *)queue updatedDownloads:(NSArray<SKDownload *> *)downloads {
if (!self.observingTransactions) {
[_transactionCache addObjects:downloads forKey:TransactionCacheKeyUpdatedDownloads];
return;
}
self.updatedDownloads(downloads);
}
// Sent when a user initiates an IAP buy from the App Store
- (BOOL)paymentQueue:(SKPaymentQueue *)queue
shouldAddStorePayment:(SKPayment *)payment
forProduct:(SKProduct *)product {
return (self.shouldAddStorePayment(payment, product));
}
- (NSArray<SKPaymentTransaction *> *)getUnfinishedTransactions {
return self.queue.transactions;
}
@end
| plugins/packages/in_app_purchase/in_app_purchase_storekit/macos/Classes/FIAPaymentQueueHandler.m/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/macos/Classes/FIAPaymentQueueHandler.m",
"repo_id": "plugins",
"token_count": 2930
} | 1,462 |
# integration_test (moved)
## MOVED
This package has [moved to the Flutter
SDK](https://github.com/flutter/flutter/tree/master/packages/integration_test),
and the pub.dev version is deprecated.
As of Flutter 2.0, include it in your pubspec's
dev dependencies section, as follows:
```
dev_dependencies:
integration_test:
sdk: flutter
```
For the latest documentation, see [Integration
testing](https://flutter.dev/docs/testing/integration-tests).
| plugins/packages/integration_test/README.md/0 | {
"file_path": "plugins/packages/integration_test/README.md",
"repo_id": "plugins",
"token_count": 145
} | 1,463 |
## 2.1.4
* Updates minimum Flutter version to 3.0.
* Updates documentation for Android version 8 and below theme compatibility.
## 2.1.3
* Updates minimum Flutter version to 2.10.
* Removes unused `intl` dependency.
## 2.1.2
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 2.1.1
* Replaces `USE_FINGERPRINT` permission with `USE_BIOMETRIC` in README and example project.
## 2.1.0
* Adds Windows support.
## 2.0.2
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 2.0.1
* Restores the ability to import `error_codes.dart`.
* Updates README to match API changes in 2.0, and to improve clarity in
general.
* Removes unnecessary imports.
## 2.0.0
* Migrates plugin to federated architecture.
* Adds OS version support information to README.
* BREAKING CHANGE: Deprecated method `authenticateWithBiometrics` has been removed.
Use `authenticate` instead.
* BREAKING CHANGE: Enum `BiometricType` has been expanded with options for `strong` and `weak`,
and applications should be updated to handle these accordingly.
* BREAKING CHANGE: Parameters of `authenticate` have been changed.
Example:
```dart
// Old way of calling `authenticate`.
Future<bool> authenticate(
localizedReason: 'localized reason',
useErrorDialogs: true,
stickyAuth: false,
androidAuthStrings: const AndroidAuthMessages(),
iOSAuthStrings: const IOSAuthMessages(),
sensitiveTransaction: true,
biometricOnly: false,
);
// New way of calling `authenticate`.
Future<bool> authenticate(
localizedReason: 'localized reason',
authMessages: const <AuthMessages>[
IOSAuthMessages(),
AndroidAuthMessages()
],
options: const AuthenticationOptions(
useErrorDialogs: true,
stickyAuth: false,
sensitiveTransaction: true,
biometricOnly: false,
),
);
```
## 1.1.11
* Adds support `localizedFallbackTitle` in authenticateWithBiometrics on iOS.
## 1.1.10
* Removes dependency on `meta`.
## 1.1.9
* Updates code for analysis option changes.
* Updates Android compileSdkVersion to 31.
## 1.1.8
* Update minimum Flutter SDK to 2.5 and iOS deployment target to 9.0.
* Updated Android lint settings.
## 1.1.7
* Remove references to the Android V1 embedding.
## 1.1.6
* Migrate maven repository from jcenter to mavenCentral.
## 1.1.5
* Updated grammatical errors and inaccurate information in README.
## 1.1.4
* Add debug assertion that `localizedReason` in `LocalAuthentication.authenticateWithBiometrics` must not be empty.
## 1.1.3
* Fix crashes due to threading issues in iOS implementation.
## 1.1.2
* Update Jetpack dependencies to latest stable versions.
## 1.1.1
* Update flutter_plugin_android_lifecycle dependency to 2.0.1 to fix an R8 issue
on some versions.
## 1.1.0
* Migrate to null safety.
* Allow pin, passcode, and pattern authentication with `authenticate` method.
* Fix incorrect error handling switch case fallthrough.
* Update README for Android Integration.
* Update the example app: remove the deprecated `RaisedButton` and `FlatButton` widgets.
* Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276)).
* **Breaking change**. Parameter names refactored to use the generic `biometric` prefix in place of `fingerprint` in the `AndroidAuthMessages` class
* `fingerprintHint` is now `biometricHint`
* `fingerprintNotRecognized`is now `biometricNotRecognized`
* `fingerprintSuccess`is now `biometricSuccess`
* `fingerprintRequiredTitle` is now `biometricRequiredTitle`
## 0.6.3+5
* Update Flutter SDK constraint.
## 0.6.3+4
* Update Dart SDK constraint in example.
## 0.6.3+3
* Update android compileSdkVersion to 29.
## 0.6.3+2
* Keep handling deprecated Android v1 classes for backward compatibility.
## 0.6.3+1
* Update package:e2e -> package:integration_test
## 0.6.3
* Increase upper range of `package:platform` constraint to allow 3.X versions.
## 0.6.2+4
* Update package:e2e reference to use the local version in the flutter/plugins
repository.
## 0.6.2+3
* Post-v2 Android embedding cleanup.
## 0.6.2+2
* Update lower bound of dart dependency to 2.1.0.
## 0.6.2+1
* Fix CocoaPods podspec lint warnings.
## 0.6.2
* Remove Android dependencies fallback.
* Require Flutter SDK 1.12.13+hotfix.5 or greater.
* Fix block implicitly retains 'self' warning.
## 0.6.1+4
* Replace deprecated `getFlutterEngine` call on Android.
## 0.6.1+3
* Make the pedantic dev_dependency explicit.
## 0.6.1+2
* Support v2 embedding.
## 0.6.1+1
* Remove the deprecated `author:` field from pubspec.yaml
* Migrate the plugin to the pubspec platforms manifest.
* Require Flutter SDK 1.10.0 or greater.
## 0.6.1
* Added ability to stop authentication (For Android).
## 0.6.0+3
* Remove AndroidX warnings.
## 0.6.0+2
* Update and migrate iOS example project.
* Define clang module for iOS.
## 0.6.0+1
* Update the `intl` constraint to ">=0.15.1 <0.17.0" (0.16.0 isn't really a breaking change).
## 0.6.0
* Define a new parameter for signaling that the transaction is sensitive.
* Up the biometric version to beta01.
* Handle no device credential error.
## 0.5.3
* Add face id detection as well by not relying on FingerprintCompat.
## 0.5.2+4
* Update README to fix syntax error.
## 0.5.2+3
* Update documentation to clarify the need for FragmentActivity.
## 0.5.2+2
* Add missing template type parameter to `invokeMethod` calls.
* Bump minimum Flutter version to 1.5.0.
* Replace invokeMethod with invokeMapMethod wherever necessary.
## 0.5.2+1
* Use post instead of postDelayed to show the dialog onResume.
## 0.5.2
* Executor thread needs to be UI thread.
## 0.5.1
* Fix crash on Android versions earlier than 28.
* [`authenticateWithBiometrics`](https://pub.dev/documentation/local_auth/latest/local_auth/LocalAuthentication/authenticateWithBiometrics.html) will not return result unless Biometric Dialog is closed.
* Added two more error codes `LockedOut` and `PermanentlyLockedOut`.
## 0.5.0
* **Breaking change**. Update the Android API to use androidx Biometric package. This gives
the prompt the updated Material look. However, it also requires the activity to be a
FragmentActivity. Users can switch to FlutterFragmentActivity in their main app to migrate.
## 0.4.0+1
* Log a more detailed warning at build time about the previous AndroidX
migration.
## 0.4.0
* **Breaking change**. Migrate from the deprecated original Android Support
Library to AndroidX. This shouldn't result in any functional changes, but it
requires any Android apps using this plugin to [also
migrate](https://developer.android.com/jetpack/androidx/migrate) if they're
using the original support library.
## 0.3.1
* Fix crash on Android versions earlier than 24.
## 0.3.0
* **Breaking change**. Add canCheckBiometrics and getAvailableBiometrics which leads to a new API.
## 0.2.1
* Updated Gradle tooling to match Android Studio 3.1.2.
## 0.2.0
* **Breaking change**. Set SDK constraints to match the Flutter beta release.
## 0.1.2
* Fixed Dart 2 type error.
## 0.1.1
* Simplified and upgraded Android project template to Android SDK 27.
* Updated package description.
## 0.1.0
* **Breaking change**. Upgraded to Gradle 4.1 and Android Studio Gradle plugin
3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in
order to use this version of the plugin. Instructions can be found
[here](https://github.com/flutter/flutter/wiki/Updating-Flutter-projects-to-Gradle-4.1-and-Android-Studio-Gradle-plugin-3.0.1).
## 0.0.3
* Add FLT prefix to iOS types
## 0.0.2+1
* Update messaging to support Face ID.
## 0.0.2
* Support stickyAuth mode.
## 0.0.1
* Initial release of local authentication plugin.
| plugins/packages/local_auth/local_auth/CHANGELOG.md/0 | {
"file_path": "plugins/packages/local_auth/local_auth/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 2523
} | 1,464 |
#Sun Jan 03 14:07:08 CST 2021
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip
| plugins/packages/local_auth/local_auth/example/android/gradle/wrapper/gradle-wrapper.properties/0 | {
"file_path": "plugins/packages/local_auth/local_auth/example/android/gradle/wrapper/gradle-wrapper.properties",
"repo_id": "plugins",
"token_count": 83
} | 1,465 |
<?xml version="1.0" encoding="UTF-8"?>
<issues format="5" by="lint 4.1.1" client="gradle" variant="debug" version="4.1.1">
<issue
id="NewApi"
message="`@android:style/Theme.Material.Dialog.Alert` requires API level 21 (current min is 16)"
errorLine1=" <style name="AlertDialogCustom" parent="@android:style/Theme.Material.Dialog.Alert">"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/values/styles.xml"
line="3"
column="35"/>
</issue>
<issue
id="NewApi"
message="`android:colorAccent` requires API level 21 (current min is 16)"
errorLine1=" <item name="android:colorAccent">#FF009688</item>"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/values/styles.xml"
line="7"
column="11"/>
</issue>
<issue
id="OldTargetApi"
message="Not targeting the latest versions of Android; compatibility modes apply. Consider testing and updating this version. Consult the `android.os.Build.VERSION_CODES` javadoc for details."
errorLine1=" <uses-sdk android:targetSdkVersion="29"/>"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/AndroidManifest.xml"
line="3"
column="15"/>
</issue>
<issue
id="UseCompoundDrawables"
message="This tag and its children can be replaced by one `<TextView/>` and a compound drawable"
errorLine1=" <LinearLayout"
errorLine2=" ~~~~~~~~~~~~">
<location
file="src/main/res/layout/scan_fp.xml"
line="26"
column="4"/>
</issue>
<issue
id="ContentDescription"
message="Missing `contentDescription` attribute on image"
errorLine1=" <ImageView"
errorLine2=" ~~~~~~~~~">
<location
file="src/main/res/layout/scan_fp.xml"
line="30"
column="6"/>
</issue>
</issues>
| plugins/packages/local_auth/local_auth_android/android/lint-baseline.xml/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/android/lint-baseline.xml",
"repo_id": "plugins",
"token_count": 1025
} | 1,466 |
// 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.localauth;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.NativeActivity;
import android.content.Context;
import androidx.biometric.BiometricManager;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Lifecycle;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.embedding.engine.plugins.lifecycle.HiddenLifecycleReference;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.localauth.AuthenticationHelper.AuthCompletionHandler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
public class LocalAuthTest {
@Test
public void authenticate_returnsErrorWhenAuthInProgress() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
plugin.authInProgress.set(true);
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
plugin.onMethodCall(new MethodCall("authenticate", null), mockResult);
verify(mockResult).error("auth_in_progress", "Authentication in progress", null);
}
@Test
public void authenticate_returnsErrorWithNoForegroundActivity() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
plugin.onMethodCall(new MethodCall("authenticate", null), mockResult);
verify(mockResult)
.error("no_activity", "local_auth plugin requires a foreground activity", null);
}
@Test
public void authenticate_returnsErrorWhenActivityNotFragmentActivity() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
setPluginActivity(plugin, buildMockActivityWithContext(mock(NativeActivity.class)));
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
plugin.onMethodCall(new MethodCall("authenticate", null), mockResult);
verify(mockResult)
.error(
"no_fragment_activity",
"local_auth plugin requires activity to be a FragmentActivity.",
null);
}
@Test
public void authenticate_returnsErrorWhenDeviceNotSupported() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
setPluginActivity(plugin, buildMockActivityWithContext(mock(FragmentActivity.class)));
plugin.onMethodCall(new MethodCall("authenticate", null), mockResult);
assertFalse(plugin.authInProgress.get());
verify(mockResult).error("NotAvailable", "Required security features not enabled", null);
}
@Test
public void authenticate_properlyConfiguresBiometricOnlyAuthenticationRequest() {
final LocalAuthPlugin plugin = spy(new LocalAuthPlugin());
setPluginActivity(plugin, buildMockActivityWithContext(mock(FragmentActivity.class)));
when(plugin.isDeviceSupported()).thenReturn(true);
final BiometricManager mockBiometricManager = mock(BiometricManager.class);
when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK))
.thenReturn(BiometricManager.BIOMETRIC_SUCCESS);
when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL))
.thenReturn(BiometricManager.BIOMETRIC_SUCCESS);
plugin.setBiometricManager(mockBiometricManager);
ArgumentCaptor<Boolean> allowCredentialsCaptor = ArgumentCaptor.forClass(Boolean.class);
doNothing()
.when(plugin)
.sendAuthenticationRequest(
any(MethodCall.class),
any(AuthCompletionHandler.class),
allowCredentialsCaptor.capture());
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("biometricOnly", true);
plugin.onMethodCall(new MethodCall("authenticate", arguments), mockResult);
assertFalse(allowCredentialsCaptor.getValue());
}
@Test
@Config(sdk = 30)
public void authenticate_properlyConfiguresBiometricAndDeviceCredentialAuthenticationRequest() {
final LocalAuthPlugin plugin = spy(new LocalAuthPlugin());
setPluginActivity(plugin, buildMockActivityWithContext(mock(FragmentActivity.class)));
when(plugin.isDeviceSupported()).thenReturn(true);
final BiometricManager mockBiometricManager = mock(BiometricManager.class);
when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL))
.thenReturn(BiometricManager.BIOMETRIC_SUCCESS);
plugin.setBiometricManager(mockBiometricManager);
ArgumentCaptor<Boolean> allowCredentialsCaptor = ArgumentCaptor.forClass(Boolean.class);
doNothing()
.when(plugin)
.sendAuthenticationRequest(
any(MethodCall.class),
any(AuthCompletionHandler.class),
allowCredentialsCaptor.capture());
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("biometricOnly", false);
plugin.onMethodCall(new MethodCall("authenticate", arguments), mockResult);
assertTrue(allowCredentialsCaptor.getValue());
}
@Test
@Config(sdk = 30)
public void authenticate_properlyConfiguresDeviceCredentialOnlyAuthenticationRequest() {
final LocalAuthPlugin plugin = spy(new LocalAuthPlugin());
setPluginActivity(plugin, buildMockActivityWithContext(mock(FragmentActivity.class)));
when(plugin.isDeviceSupported()).thenReturn(true);
final BiometricManager mockBiometricManager = mock(BiometricManager.class);
when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK))
.thenReturn(BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED);
when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL))
.thenReturn(BiometricManager.BIOMETRIC_SUCCESS);
plugin.setBiometricManager(mockBiometricManager);
ArgumentCaptor<Boolean> allowCredentialsCaptor = ArgumentCaptor.forClass(Boolean.class);
doNothing()
.when(plugin)
.sendAuthenticationRequest(
any(MethodCall.class),
any(AuthCompletionHandler.class),
allowCredentialsCaptor.capture());
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("biometricOnly", false);
plugin.onMethodCall(new MethodCall("authenticate", arguments), mockResult);
assertTrue(allowCredentialsCaptor.getValue());
}
@Test
public void isDeviceSupportedReturnsFalse() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
plugin.onMethodCall(new MethodCall("isDeviceSupported", null), mockResult);
verify(mockResult).success(false);
}
@Test
public void deviceSupportsBiometrics_returnsTrueForPresentNonEnrolledBiometrics() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
final BiometricManager mockBiometricManager = mock(BiometricManager.class);
when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK))
.thenReturn(BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED);
plugin.setBiometricManager(mockBiometricManager);
plugin.onMethodCall(new MethodCall("deviceSupportsBiometrics", null), mockResult);
verify(mockResult).success(true);
}
@Test
public void deviceSupportsBiometrics_returnsTrueForPresentEnrolledBiometrics() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
final BiometricManager mockBiometricManager = mock(BiometricManager.class);
when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK))
.thenReturn(BiometricManager.BIOMETRIC_SUCCESS);
plugin.setBiometricManager(mockBiometricManager);
plugin.onMethodCall(new MethodCall("deviceSupportsBiometrics", null), mockResult);
verify(mockResult).success(true);
}
@Test
public void deviceSupportsBiometrics_returnsFalseForNoBiometricHardware() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
final BiometricManager mockBiometricManager = mock(BiometricManager.class);
when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK))
.thenReturn(BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE);
plugin.setBiometricManager(mockBiometricManager);
plugin.onMethodCall(new MethodCall("deviceSupportsBiometrics", null), mockResult);
verify(mockResult).success(false);
}
@Test
public void deviceSupportsBiometrics_returnsFalseForNullBiometricManager() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
plugin.setBiometricManager(null);
plugin.onMethodCall(new MethodCall("deviceSupportsBiometrics", null), mockResult);
verify(mockResult).success(false);
}
@Test
public void onDetachedFromActivity_ShouldReleaseActivity() {
final Activity mockActivity = mock(Activity.class);
final ActivityPluginBinding mockActivityBinding = mock(ActivityPluginBinding.class);
when(mockActivityBinding.getActivity()).thenReturn(mockActivity);
Context mockContext = mock(Context.class);
when(mockActivity.getBaseContext()).thenReturn(mockContext);
when(mockActivity.getApplicationContext()).thenReturn(mockContext);
final HiddenLifecycleReference mockLifecycleReference = mock(HiddenLifecycleReference.class);
when(mockActivityBinding.getLifecycle()).thenReturn(mockLifecycleReference);
final Lifecycle mockLifecycle = mock(Lifecycle.class);
when(mockLifecycleReference.getLifecycle()).thenReturn(mockLifecycle);
final FlutterPluginBinding mockPluginBinding = mock(FlutterPluginBinding.class);
final FlutterEngine mockFlutterEngine = mock(FlutterEngine.class);
when(mockPluginBinding.getFlutterEngine()).thenReturn(mockFlutterEngine);
DartExecutor mockDartExecutor = mock(DartExecutor.class);
when(mockFlutterEngine.getDartExecutor()).thenReturn(mockDartExecutor);
final LocalAuthPlugin plugin = new LocalAuthPlugin();
plugin.onAttachedToEngine(mockPluginBinding);
plugin.onAttachedToActivity(mockActivityBinding);
assertNotNull(plugin.getActivity());
plugin.onDetachedFromActivity();
assertNull(plugin.getActivity());
}
@Test
public void getEnrolledBiometrics_shouldReturnError_whenNoActivity() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
plugin.onMethodCall(new MethodCall("getEnrolledBiometrics", null), mockResult);
verify(mockResult)
.error("no_activity", "local_auth plugin requires a foreground activity", null);
}
@Test
public void getEnrolledBiometrics_shouldReturnError_whenFinishingActivity() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
final Activity mockActivity = buildMockActivityWithContext(mock(Activity.class));
when(mockActivity.isFinishing()).thenReturn(true);
setPluginActivity(plugin, mockActivity);
plugin.onMethodCall(new MethodCall("getEnrolledBiometrics", null), mockResult);
verify(mockResult)
.error("no_activity", "local_auth plugin requires a foreground activity", null);
}
@Test
public void getEnrolledBiometrics_shouldReturnEmptyList_withoutHardwarePresent() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
setPluginActivity(plugin, buildMockActivityWithContext(mock(Activity.class)));
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
final BiometricManager mockBiometricManager = mock(BiometricManager.class);
when(mockBiometricManager.canAuthenticate(anyInt()))
.thenReturn(BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE);
plugin.setBiometricManager(mockBiometricManager);
plugin.onMethodCall(new MethodCall("getEnrolledBiometrics", null), mockResult);
verify(mockResult).success(Collections.emptyList());
}
@Test
public void getEnrolledBiometrics_shouldReturnEmptyList_withNoMethodsEnrolled() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
setPluginActivity(plugin, buildMockActivityWithContext(mock(Activity.class)));
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
final BiometricManager mockBiometricManager = mock(BiometricManager.class);
when(mockBiometricManager.canAuthenticate(anyInt()))
.thenReturn(BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED);
plugin.setBiometricManager(mockBiometricManager);
plugin.onMethodCall(new MethodCall("getEnrolledBiometrics", null), mockResult);
verify(mockResult).success(Collections.emptyList());
}
@Test
public void getEnrolledBiometrics_shouldOnlyAddEnrolledBiometrics() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
setPluginActivity(plugin, buildMockActivityWithContext(mock(Activity.class)));
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
final BiometricManager mockBiometricManager = mock(BiometricManager.class);
when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK))
.thenReturn(BiometricManager.BIOMETRIC_SUCCESS);
when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG))
.thenReturn(BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED);
plugin.setBiometricManager(mockBiometricManager);
plugin.onMethodCall(new MethodCall("getEnrolledBiometrics", null), mockResult);
verify(mockResult)
.success(
new ArrayList<String>() {
{
add("weak");
}
});
}
@Test
public void getEnrolledBiometrics_shouldAddStrongBiometrics() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
setPluginActivity(plugin, buildMockActivityWithContext(mock(Activity.class)));
final MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
final BiometricManager mockBiometricManager = mock(BiometricManager.class);
when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK))
.thenReturn(BiometricManager.BIOMETRIC_SUCCESS);
when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG))
.thenReturn(BiometricManager.BIOMETRIC_SUCCESS);
plugin.setBiometricManager(mockBiometricManager);
plugin.onMethodCall(new MethodCall("getEnrolledBiometrics", null), mockResult);
verify(mockResult)
.success(
new ArrayList<String>() {
{
add("weak");
add("strong");
}
});
}
@Test
@Config(sdk = 22)
public void isDeviceSecure_returnsFalseOnBelowApi23() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
assertFalse(plugin.isDeviceSecure());
}
@Test
@Config(sdk = 23)
public void isDeviceSecure_returnsTrueIfDeviceIsSecure() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
KeyguardManager mockKeyguardManager = mock(KeyguardManager.class);
plugin.setKeyguardManager(mockKeyguardManager);
when(mockKeyguardManager.isDeviceSecure()).thenReturn(true);
assertTrue(plugin.isDeviceSecure());
when(mockKeyguardManager.isDeviceSecure()).thenReturn(false);
assertFalse(plugin.isDeviceSecure());
}
@Test
@Config(sdk = 30)
public void
canAuthenticateWithDeviceCredential_returnsTrueIfHasBiometricManagerSupportAboveApi30() {
final LocalAuthPlugin plugin = new LocalAuthPlugin();
final BiometricManager mockBiometricManager = mock(BiometricManager.class);
plugin.setBiometricManager(mockBiometricManager);
when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL))
.thenReturn(BiometricManager.BIOMETRIC_SUCCESS);
assertTrue(plugin.canAuthenticateWithDeviceCredential());
when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL))
.thenReturn(BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED);
assertFalse(plugin.canAuthenticateWithDeviceCredential());
}
private Activity buildMockActivityWithContext(Activity mockActivity) {
final Context mockContext = mock(Context.class);
when(mockActivity.getBaseContext()).thenReturn(mockContext);
when(mockActivity.getApplicationContext()).thenReturn(mockContext);
return mockActivity;
}
private void setPluginActivity(LocalAuthPlugin plugin, Activity activity) {
final HiddenLifecycleReference mockLifecycleReference = mock(HiddenLifecycleReference.class);
final FlutterPluginBinding mockPluginBinding = mock(FlutterPluginBinding.class);
final ActivityPluginBinding mockActivityBinding = mock(ActivityPluginBinding.class);
final FlutterEngine mockFlutterEngine = mock(FlutterEngine.class);
final DartExecutor mockDartExecutor = mock(DartExecutor.class);
when(mockPluginBinding.getFlutterEngine()).thenReturn(mockFlutterEngine);
when(mockFlutterEngine.getDartExecutor()).thenReturn(mockDartExecutor);
when(mockActivityBinding.getActivity()).thenReturn(activity);
when(mockActivityBinding.getLifecycle()).thenReturn(mockLifecycleReference);
plugin.onAttachedToEngine(mockPluginBinding);
plugin.onAttachedToActivity(mockActivityBinding);
}
}
| plugins/packages/local_auth/local_auth_android/android/src/test/java/io/flutter/plugins/localauth/LocalAuthTest.java/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/android/src/test/java/io/flutter/plugins/localauth/LocalAuthTest.java",
"repo_id": "plugins",
"token_count": 6123
} | 1,467 |
include ':app'
| plugins/packages/local_auth/local_auth_android/example/android/settings_aar.gradle/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/example/android/settings_aar.gradle",
"repo_id": "plugins",
"token_count": 6
} | 1,468 |
// 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.
/// Abstract class for storing platform specific strings.
abstract class AuthMessages {
/// Constructs an instance of [AuthMessages].
const AuthMessages();
/// Returns all platform-specific messages as a map.
Map<String, String> get args;
}
| plugins/packages/local_auth/local_auth_platform_interface/lib/types/auth_messages.dart/0 | {
"file_path": "plugins/packages/local_auth/local_auth_platform_interface/lib/types/auth_messages.dart",
"repo_id": "plugins",
"token_count": 106
} | 1,469 |
// 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_LOCAL_AUTH_LOCAL_AUTH_WINDOWS_WINDOWS_TEST_MOCKS_H_
#define PACKAGES_LOCAL_AUTH_LOCAL_AUTH_WINDOWS_WINDOWS_TEST_MOCKS_H_
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "../local_auth.h"
namespace local_auth_windows {
namespace test {
namespace {
using ::testing::_;
class MockUserConsentVerifier : public UserConsentVerifier {
public:
explicit MockUserConsentVerifier(){};
virtual ~MockUserConsentVerifier() = default;
MOCK_METHOD(winrt::Windows::Foundation::IAsyncOperation<
winrt::Windows::Security::Credentials::UI::
UserConsentVerificationResult>,
RequestVerificationForWindowAsync, (std::wstring localizedReason),
(override));
MOCK_METHOD(winrt::Windows::Foundation::IAsyncOperation<
winrt::Windows::Security::Credentials::UI::
UserConsentVerifierAvailability>,
CheckAvailabilityAsync, (), (override));
// Disallow copy and move.
MockUserConsentVerifier(const MockUserConsentVerifier&) = delete;
MockUserConsentVerifier& operator=(const MockUserConsentVerifier&) = delete;
};
} // namespace
} // namespace test
} // namespace local_auth_windows
#endif // PACKAGES_LOCAL_AUTH_LOCAL_AUTH_WINDOWS_WINDOWS_TEST_MOCKS_H_
| plugins/packages/local_auth/local_auth_windows/windows/test/mocks.h/0 | {
"file_path": "plugins/packages/local_auth/local_auth_windows/windows/test/mocks.h",
"repo_id": "plugins",
"token_count": 556
} | 1,470 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| plugins/packages/path_provider/path_provider/example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "plugins/packages/path_provider/path_provider/example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "plugins",
"token_count": 32
} | 1,471 |
# path\_provider\_android
The Android implementation of [`path_provider`][1].
## Usage
This package is [endorsed][2], which means you can simply use `path_provider`
normally. This package will be automatically included in your app when you do.
[1]: https://pub.dev/packages/path_provider
[2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
| plugins/packages/path_provider/path_provider_android/README.md/0 | {
"file_path": "plugins/packages/path_provider/path_provider_android/README.md",
"repo_id": "plugins",
"token_count": 123
} | 1,472 |
// 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.1.5), 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
// ignore_for_file: avoid_relative_lib_imports
// @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';
import 'package:flutter_test/flutter_test.dart';
// The following line is edited by hand to avoid confusing dart with overloaded types.
import 'package:path_provider_android/messages.g.dart';
class _TestPathProviderApiCodec extends StandardMessageCodec {
const _TestPathProviderApiCodec();
}
abstract class TestPathProviderApi {
static const MessageCodec<Object?> codec = _TestPathProviderApiCodec();
String? getTemporaryPath();
String? getApplicationSupportPath();
String? getApplicationDocumentsPath();
String? getExternalStoragePath();
List<String?> getExternalCachePaths();
List<String?> getExternalStoragePaths(StorageDirectory directory);
static void setup(TestPathProviderApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getTemporaryPath', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
// ignore message
final String? output = api.getTemporaryPath();
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getApplicationSupportPath', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
// ignore message
final String? output = api.getApplicationSupportPath();
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getApplicationDocumentsPath',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
// ignore message
final String? output = api.getApplicationDocumentsPath();
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getExternalStoragePath', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
// ignore message
final String? output = api.getExternalStoragePath();
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getExternalCachePaths', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
// ignore message
final List<String?> output = api.getExternalCachePaths();
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getExternalStoragePaths', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.PathProviderApi.getExternalStoragePaths was null.');
final List<Object?> args = (message as List<Object?>?)!;
/// TODO(gaaclarke): The following line was tweaked by hand to address
/// https://github.com/flutter/flutter/issues/105742. Alternatively
/// the tests could be written with a mock BinaryMessenger but this is
/// how we want to address it eventually.
final StorageDirectory? arg_directory =
StorageDirectory.values[args[0] as int];
assert(arg_directory != null,
'Argument for dev.flutter.pigeon.PathProviderApi.getExternalStoragePaths was null, expected non-null StorageDirectory.');
final List<String?> output =
api.getExternalStoragePaths(arg_directory!);
return <Object?, Object?>{'result': output};
});
}
}
}
}
| plugins/packages/path_provider/path_provider_android/test/messages_test.g.dart/0 | {
"file_path": "plugins/packages/path_provider/path_provider_android/test/messages_test.g.dart",
"repo_id": "plugins",
"token_count": 2075
} | 1,473 |
// Mocks generated by Mockito 5.3.2 from annotations
// in path_provider_foundation/test/path_provider_foundation_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:mockito/mockito.dart' as _i1;
import 'package:path_provider_foundation/messages.g.dart' as _i3;
import 'messages_test.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 [TestPathProviderApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestPathProviderApi extends _i1.Mock
implements _i2.TestPathProviderApi {
MockTestPathProviderApi() {
_i1.throwOnMissingStub(this);
}
@override
String? getDirectoryPath(_i3.DirectoryType? type) =>
(super.noSuchMethod(Invocation.method(
#getDirectoryPath,
[type],
)) as String?);
}
| plugins/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.mocks.dart/0 | {
"file_path": "plugins/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.mocks.dart",
"repo_id": "plugins",
"token_count": 452
} | 1,474 |
# path_provider_platform_interface
A common platform interface for the [`path_provider`][1] plugin.
This interface allows platform-specific implementations of the `path_provider`
plugin, as well as the plugin itself, to ensure they are supporting the
same interface.
# Usage
To implement a new platform-specific implementation of `path_provider`, extend
[`PathProviderPlatform`][2] with an implementation that performs the
platform-specific behavior, and when you register your plugin, set the default
`PathProviderPlatform` by calling
`PathProviderPlatform.instance = MyPlatformPathProvider()`.
# Note on breaking changes
Strongly prefer non-breaking changes (such as adding a method to the interface)
over breaking changes for this package.
See https://flutter.dev/go/platform-interface-breaking-changes for a discussion
on why a less-clean interface is preferable to a breaking change.
[1]: ../
[2]: lib/path_provider_platform_interface.dart
| plugins/packages/path_provider/path_provider_platform_interface/README.md/0 | {
"file_path": "plugins/packages/path_provider/path_provider_platform_interface/README.md",
"repo_id": "plugins",
"token_count": 238
} | 1,475 |
# plugin_platform_interface
This package provides a base class for platform interfaces of [federated flutter plugins](https://flutter.dev/go/federated-plugins).
Platform implementations should extend their platform interface classes rather than implement it as
newly added methods to platform interfaces are not considered as breaking changes. Extending a platform
interface ensures that subclasses will get the default implementations from the base class, while
platform implementations that `implements` their platform interface will be broken by newly added methods.
This class package provides common functionality for platform interface to enforce that they are extended
and not implemented.
## Sample usage:
```dart
abstract class UrlLauncherPlatform extends PlatformInterface {
UrlLauncherPlatform() : super(token: _token);
static UrlLauncherPlatform _instance = MethodChannelUrlLauncher();
static final Object _token = Object();
static UrlLauncherPlatform get instance => _instance;
/// Platform-specific plugins should set this with their own platform-specific
/// class that extends [UrlLauncherPlatform] when they register themselves.
static set instance(UrlLauncherPlatform instance) {
PlatformInterface.verify(instance, _token);
_instance = instance;
}
}
```
This guarantees that UrlLauncherPlatform.instance cannot be set to an object that `implements`
UrlLauncherPlatform (it can only be set to an object that `extends` UrlLauncherPlatform).
## Mocking or faking platform interfaces
Test implementations of platform interfaces, such as those using `mockito`'s
`Mock` or `test`'s `Fake`, will fail the verification done by `verify`.
This package provides a `MockPlatformInterfaceMixin` which can be used in test
code only to disable the `extends` enforcement.
For example, a Mockito mock of a platform interface can be created with:
```dart
class UrlLauncherPlatformMock extends Mock
with MockPlatformInterfaceMixin
implements UrlLauncherPlatform {}
```
| plugins/packages/plugin_platform_interface/README.md/0 | {
"file_path": "plugins/packages/plugin_platform_interface/README.md",
"repo_id": "plugins",
"token_count": 485
} | 1,476 |
<?xml version="1.0" encoding="utf-8"?>
<vector
android:height="108dp"
android:width="108dp"
android:viewportHeight="108"
android:viewportWidth="108"
xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="#FF2196F3"
android:pathData="M0,0h108v108h-108z"/>
<path android:fillColor="#00000000" android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
</vector>
| plugins/packages/quick_actions/quick_actions/example/android/app/src/main/res/drawable/ic_launcher_background.xml/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions/example/android/app/src/main/res/drawable/ic_launcher_background.xml",
"repo_id": "plugins",
"token_count": 1900
} | 1,477 |
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
| plugins/packages/quick_actions/quick_actions_android/example/android/app/gradle/wrapper/gradle-wrapper.properties/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_android/example/android/app/gradle/wrapper/gradle-wrapper.properties",
"repo_id": "plugins",
"token_count": 73
} | 1,478 |
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
| plugins/packages/quick_actions/quick_actions_android/example/android/gradle/wrapper/gradle-wrapper.properties/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_android/example/android/gradle/wrapper/gradle-wrapper.properties",
"repo_id": "plugins",
"token_count": 73
} | 1,479 |
// 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 Foundation
@testable import quick_actions_ios
final class MockShortcutItemParser: ShortcutItemParser {
var parseShortcutItemsStub: ((_ items: [[String: Any]]) -> [UIApplicationShortcutItem])? = nil
func parseShortcutItems(_ items: [[String: Any]]) -> [UIApplicationShortcutItem] {
return parseShortcutItemsStub?(items) ?? []
}
}
| plugins/packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/Mocks/MockShortcutItemParser.swift/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/Mocks/MockShortcutItemParser.swift",
"repo_id": "plugins",
"token_count": 153
} | 1,480 |
// 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/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:quick_actions_ios/quick_actions_ios.dart';
import 'package:quick_actions_platform_interface/quick_actions_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('$QuickActionsIos', () {
late List<MethodCall> log;
setUp(() {
log = <MethodCall>[];
});
QuickActionsIos buildQuickActionsPlugin() {
final QuickActionsIos quickActions = QuickActionsIos();
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(quickActions.channel,
(MethodCall methodCall) async {
log.add(methodCall);
return '';
});
return quickActions;
}
test('registerWith() registers correct instance', () {
QuickActionsIos.registerWith();
expect(QuickActionsPlatform.instance, isA<QuickActionsIos>());
});
group('#initialize', () {
test('passes getLaunchAction on launch method', () {
final QuickActionsIos quickActions = buildQuickActionsPlugin();
quickActions.initialize((String type) {});
expect(
log,
<Matcher>[
isMethodCall('getLaunchAction', arguments: null),
],
);
});
test('initialize', () async {
final QuickActionsIos quickActions = buildQuickActionsPlugin();
final Completer<bool> quickActionsHandler = Completer<bool>();
await quickActions
.initialize((_) => quickActionsHandler.complete(true));
expect(
log,
<Matcher>[
isMethodCall('getLaunchAction', arguments: null),
],
);
log.clear();
expect(quickActionsHandler.future, completion(isTrue));
});
});
group('#setShortCutItems', () {
test('passes shortcutItem through channel', () {
final QuickActionsIos quickActions = buildQuickActionsPlugin();
quickActions.initialize((String type) {});
quickActions.setShortcutItems(<ShortcutItem>[
const ShortcutItem(
type: 'test', localizedTitle: 'title', icon: 'icon.svg')
]);
expect(
log,
<Matcher>[
isMethodCall('getLaunchAction', arguments: null),
isMethodCall('setShortcutItems', arguments: <Map<String, String>>[
<String, String>{
'type': 'test',
'localizedTitle': 'title',
'icon': 'icon.svg',
}
]),
],
);
});
test('setShortcutItems with demo data', () async {
const String type = 'type';
const String localizedTitle = 'localizedTitle';
const String icon = 'icon';
final QuickActionsIos quickActions = buildQuickActionsPlugin();
await quickActions.setShortcutItems(
const <ShortcutItem>[
ShortcutItem(type: type, localizedTitle: localizedTitle, icon: icon)
],
);
expect(
log,
<Matcher>[
isMethodCall(
'setShortcutItems',
arguments: <Map<String, String>>[
<String, String>{
'type': type,
'localizedTitle': localizedTitle,
'icon': icon,
}
],
),
],
);
log.clear();
});
});
group('#clearShortCutItems', () {
test('send clearShortcutItems through channel', () {
final QuickActionsIos quickActions = buildQuickActionsPlugin();
quickActions.initialize((String type) {});
quickActions.clearShortcutItems();
expect(
log,
<Matcher>[
isMethodCall('getLaunchAction', arguments: null),
isMethodCall('clearShortcutItems', arguments: null),
],
);
});
test('clearShortcutItems', () {
final QuickActionsIos quickActions = buildQuickActionsPlugin();
quickActions.clearShortcutItems();
expect(
log,
<Matcher>[
isMethodCall('clearShortcutItems', arguments: null),
],
);
log.clear();
});
});
});
group('$ShortcutItem', () {
test('Shortcut item can be constructed', () {
const String type = 'type';
const String localizedTitle = 'title';
const String icon = 'foo';
const ShortcutItem item =
ShortcutItem(type: type, localizedTitle: localizedTitle, icon: icon);
expect(item.type, type);
expect(item.localizedTitle, localizedTitle);
expect(item.icon, icon);
});
});
}
/// 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/quick_actions/quick_actions_ios/test/quick_actions_ios_test.dart/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_ios/test/quick_actions_ios_test.dart",
"repo_id": "plugins",
"token_count": 2278
} | 1,481 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| plugins/packages/shared_preferences/shared_preferences/example/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences/example/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "plugins",
"token_count": 32
} | 1,482 |
// 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:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
/// Wraps NSUserDefaults (on iOS) and SharedPreferences (on Android), providing
/// a persistent store for simple data.
///
/// Data is persisted to disk asynchronously.
class SharedPreferences {
SharedPreferences._(this._preferenceCache);
static const String _prefix = 'flutter.';
static Completer<SharedPreferences>? _completer;
static SharedPreferencesStorePlatform get _store =>
SharedPreferencesStorePlatform.instance;
/// Loads and parses the [SharedPreferences] for this app from disk.
///
/// Because this is reading from disk, it shouldn't be awaited in
/// performance-sensitive blocks.
static Future<SharedPreferences> getInstance() async {
if (_completer == null) {
final Completer<SharedPreferences> completer =
Completer<SharedPreferences>();
try {
final Map<String, Object> preferencesMap =
await _getSharedPreferencesMap();
completer.complete(SharedPreferences._(preferencesMap));
} on Exception catch (e) {
// If there's an error, explicitly return the future with an error.
// then set the completer to null so we can retry.
completer.completeError(e);
final Future<SharedPreferences> sharedPrefsFuture = completer.future;
_completer = null;
return sharedPrefsFuture;
}
_completer = completer;
}
return _completer!.future;
}
/// The cache that holds all preferences.
///
/// It is instantiated to the current state of the SharedPreferences or
/// NSUserDefaults object and then kept in sync via setter methods in this
/// class.
///
/// It is NOT guaranteed that this cache and the device prefs will remain
/// in sync since the setter method might fail for any reason.
final Map<String, Object> _preferenceCache;
/// Returns all keys in the persistent storage.
Set<String> getKeys() => Set<String>.from(_preferenceCache.keys);
/// Reads a value of any type from persistent storage.
Object? get(String key) => _preferenceCache[key];
/// Reads a value from persistent storage, throwing an exception if it's not a
/// bool.
bool? getBool(String key) => _preferenceCache[key] as bool?;
/// Reads a value from persistent storage, throwing an exception if it's not
/// an int.
int? getInt(String key) => _preferenceCache[key] as int?;
/// Reads a value from persistent storage, throwing an exception if it's not a
/// double.
double? getDouble(String key) => _preferenceCache[key] as double?;
/// Reads a value from persistent storage, throwing an exception if it's not a
/// String.
String? getString(String key) => _preferenceCache[key] as String?;
/// Returns true if persistent storage the contains the given [key].
bool containsKey(String key) => _preferenceCache.containsKey(key);
/// Reads a set of string values from persistent storage, throwing an
/// exception if it's not a string set.
List<String>? getStringList(String key) {
List<dynamic>? list = _preferenceCache[key] as List<dynamic>?;
if (list != null && list is! List<String>) {
list = list.cast<String>().toList();
_preferenceCache[key] = list;
}
// Make a copy of the list so that later mutations won't propagate
return list?.toList() as List<String>?;
}
/// Saves a boolean [value] to persistent storage in the background.
Future<bool> setBool(String key, bool value) => _setValue('Bool', key, value);
/// Saves an integer [value] to persistent storage in the background.
Future<bool> setInt(String key, int value) => _setValue('Int', key, value);
/// Saves a double [value] to persistent storage in the background.
///
/// Android doesn't support storing doubles, so it will be stored as a float.
Future<bool> setDouble(String key, double value) =>
_setValue('Double', key, value);
/// Saves a string [value] to persistent storage in the background.
///
/// Note: Due to limitations in Android's SharedPreferences,
/// values cannot start with any one of the following:
///
/// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBhIGxpc3Qu'
/// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBCaWdJbnRlZ2Vy'
/// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBEb3VibGUu'
Future<bool> setString(String key, String value) =>
_setValue('String', key, value);
/// Saves a list of strings [value] to persistent storage in the background.
Future<bool> setStringList(String key, List<String> value) =>
_setValue('StringList', key, value);
/// Removes an entry from persistent storage.
Future<bool> remove(String key) {
final String prefixedKey = '$_prefix$key';
_preferenceCache.remove(key);
return _store.remove(prefixedKey);
}
Future<bool> _setValue(String valueType, String key, Object value) {
ArgumentError.checkNotNull(value, 'value');
final String prefixedKey = '$_prefix$key';
if (value is List<String>) {
// Make a copy of the list so that later mutations won't propagate
_preferenceCache[key] = value.toList();
} else {
_preferenceCache[key] = value;
}
return _store.setValue(valueType, prefixedKey, value);
}
/// Always returns true.
/// On iOS, synchronize is marked deprecated. On Android, we commit every set.
@Deprecated('This method is now a no-op, and should no longer be called.')
Future<bool> commit() async => true;
/// Completes with true once the user preferences for the app has been cleared.
Future<bool> clear() {
_preferenceCache.clear();
return _store.clear();
}
/// Fetches the latest values from the host platform.
///
/// Use this method to observe modifications that were made in native code
/// (without using the plugin) while the app is running.
Future<void> reload() async {
final Map<String, Object> preferences =
await SharedPreferences._getSharedPreferencesMap();
_preferenceCache.clear();
_preferenceCache.addAll(preferences);
}
static Future<Map<String, Object>> _getSharedPreferencesMap() async {
final Map<String, Object> fromSystem = await _store.getAll();
assert(fromSystem != null);
// Strip the flutter. prefix from the returned preferences.
final Map<String, Object> preferencesMap = <String, Object>{};
for (final String key in fromSystem.keys) {
assert(key.startsWith(_prefix));
preferencesMap[key.substring(_prefix.length)] = fromSystem[key]!;
}
return preferencesMap;
}
/// Initializes the shared preferences with mock values for testing.
///
/// If the singleton instance has been initialized already, it is nullified.
@visibleForTesting
static void setMockInitialValues(Map<String, Object> values) {
final Map<String, Object> newValues =
values.map<String, Object>((String key, Object value) {
String newKey = key;
if (!key.startsWith(_prefix)) {
newKey = '$_prefix$key';
}
return MapEntry<String, Object>(newKey, value);
});
SharedPreferencesStorePlatform.instance =
InMemorySharedPreferencesStore.withData(newValues);
_completer = null;
}
}
| plugins/packages/shared_preferences/shared_preferences/lib/shared_preferences.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences/lib/shared_preferences.dart",
"repo_id": "plugins",
"token_count": 2385
} | 1,483 |
// 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 Foundation
#if os(iOS)
import Flutter
#elseif os(macOS)
import FlutterMacOS
#endif
public class SharedPreferencesPlugin: NSObject, FlutterPlugin, UserDefaultsApi {
public static func register(with registrar: FlutterPluginRegistrar) {
let instance = SharedPreferencesPlugin()
// Workaround for https://github.com/flutter/flutter/issues/118103.
#if os(iOS)
let messenger = registrar.messenger()
#else
let messenger = registrar.messenger
#endif
UserDefaultsApiSetup.setUp(binaryMessenger: messenger, api: instance)
}
func getAll() -> [String? : Any?] {
return getAllPrefs();
}
func setBool(key: String, value: Bool) {
UserDefaults.standard.set(value, forKey: key)
}
func setDouble(key: String, value: Double) {
UserDefaults.standard.set(value, forKey: key)
}
func setValue(key: String, value: Any) {
UserDefaults.standard.set(value, forKey: key)
}
func remove(key: String) {
UserDefaults.standard.removeObject(forKey: key)
}
func clear() {
let defaults = UserDefaults.standard
for (key, _) in getAllPrefs() {
defaults.removeObject(forKey: key)
}
}
}
/// Returns all preferences stored by this plugin.
private func getAllPrefs() -> [String: Any] {
var filteredPrefs: [String: Any] = [:]
if let appDomain = Bundle.main.bundleIdentifier,
let prefs = UserDefaults.standard.persistentDomain(forName: appDomain)
{
for (key, value) in prefs where key.hasPrefix("flutter.") {
filteredPrefs[key] = value
}
}
return filteredPrefs
}
| plugins/packages/shared_preferences/shared_preferences_foundation/darwin/Classes/SharedPreferencesPlugin.swift/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_foundation/darwin/Classes/SharedPreferencesPlugin.swift",
"repo_id": "plugins",
"token_count": 588
} | 1,484 |
// 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:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
import 'messages.g.dart';
typedef _Setter = Future<void> Function(String key, Object value);
/// iOS and macOS implementation of shared_preferences.
class SharedPreferencesFoundation extends SharedPreferencesStorePlatform {
final UserDefaultsApi _api = UserDefaultsApi();
late final Map<String, _Setter> _setters = <String, _Setter>{
'Bool': (String key, Object value) {
return _api.setBool(key, value as bool);
},
'Double': (String key, Object value) {
return _api.setDouble(key, value as double);
},
'Int': (String key, Object value) {
return _api.setValue(key, value as int);
},
'String': (String key, Object value) {
return _api.setValue(key, value as String);
},
'StringList': (String key, Object value) {
return _api.setValue(key, value as List<String?>);
},
};
/// Registers this class as the default instance of
/// [SharedPreferencesStorePlatform].
static void registerWith() {
SharedPreferencesStorePlatform.instance = SharedPreferencesFoundation();
}
@override
Future<bool> clear() async {
await _api.clear();
return true;
}
@override
Future<Map<String, Object>> getAll() async {
final Map<String?, Object?> result = await _api.getAll();
return result.cast<String, Object>();
}
@override
Future<bool> remove(String key) async {
await _api.remove(key);
return true;
}
@override
Future<bool> setValue(String valueType, String key, Object value) async {
final _Setter? setter = _setters[valueType];
if (setter == null) {
throw PlatformException(
code: 'InvalidOperation',
message: '"$valueType" is not a supported type.');
}
await setter(key, value);
return true;
}
}
| plugins/packages/shared_preferences/shared_preferences_foundation/lib/shared_preferences_foundation.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_foundation/lib/shared_preferences_foundation.dart",
"repo_id": "plugins",
"token_count": 711
} | 1,485 |
// 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/memory.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider_linux/path_provider_linux.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
import 'package:shared_preferences_linux/shared_preferences_linux.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
void main() {
late MemoryFileSystem fs;
late PathProviderLinux pathProvider;
SharedPreferencesLinux.registerWith();
setUp(() {
fs = MemoryFileSystem.test();
pathProvider = FakePathProviderLinux();
});
Future<String> getFilePath() async {
final String? directory = await pathProvider.getApplicationSupportPath();
return path.join(directory!, 'shared_preferences.json');
}
Future<void> writeTestFile(String value) async {
fs.file(await getFilePath())
..createSync(recursive: true)
..writeAsStringSync(value);
}
Future<String> readTestFile() async {
return fs.file(await getFilePath()).readAsStringSync();
}
SharedPreferencesLinux getPreferences() {
final SharedPreferencesLinux prefs = SharedPreferencesLinux();
prefs.fs = fs;
prefs.pathProvider = pathProvider;
return prefs;
}
test('registered instance', () {
SharedPreferencesLinux.registerWith();
expect(
SharedPreferencesStorePlatform.instance, isA<SharedPreferencesLinux>());
});
test('getAll', () async {
await writeTestFile('{"key1": "one", "key2": 2}');
final SharedPreferencesLinux prefs = getPreferences();
final Map<String, Object> values = await prefs.getAll();
expect(values, hasLength(2));
expect(values['key1'], 'one');
expect(values['key2'], 2);
});
test('remove', () async {
await writeTestFile('{"key1":"one","key2":2}');
final SharedPreferencesLinux prefs = getPreferences();
await prefs.remove('key2');
expect(await readTestFile(), '{"key1":"one"}');
});
test('setValue', () async {
await writeTestFile('{}');
final SharedPreferencesLinux prefs = getPreferences();
await prefs.setValue('', 'key1', 'one');
await prefs.setValue('', 'key2', 2);
expect(await readTestFile(), '{"key1":"one","key2":2}');
});
test('clear', () async {
await writeTestFile('{"key1":"one","key2":2}');
final SharedPreferencesLinux prefs = getPreferences();
await prefs.clear();
expect(await readTestFile(), '{}');
});
}
/// Fake implementation of PathProviderLinux that returns hard-coded paths,
/// allowing tests to run on any platform.
///
/// Note that this should only be used with an in-memory filesystem, as the
/// path it returns is a root path that does not actually exist on Linux.
class FakePathProviderLinux extends PathProviderPlatform
implements PathProviderLinux {
@override
Future<String?> getApplicationSupportPath() async => r'/appsupport';
@override
Future<String?> getTemporaryPath() async => null;
@override
Future<String?> getLibraryPath() async => null;
@override
Future<String?> getApplicationDocumentsPath() async => null;
@override
Future<String?> getDownloadsPath() async => null;
}
| plugins/packages/shared_preferences/shared_preferences_linux/test/shared_preferences_linux_test.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_linux/test/shared_preferences_linux_test.dart",
"repo_id": "plugins",
"token_count": 1089
} | 1,486 |
# url_launcher_example
Demonstrates how to use the url_launcher plugin.
| plugins/packages/url_launcher/url_launcher/example/README.md/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher/example/README.md",
"repo_id": "plugins",
"token_count": 23
} | 1,487 |
// 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' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:url_launcher/url_launcher.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('canLaunch', (WidgetTester _) async {
expect(
await canLaunchUrl(Uri(scheme: 'randomscheme', path: 'a_path')), false);
// Generally all devices should have some default browser.
expect(await canLaunchUrl(Uri(scheme: 'http', host: 'flutter.dev')), true);
expect(await canLaunchUrl(Uri(scheme: 'https', host: 'flutter.dev')), true);
// SMS handling is available by default on most platforms.
if (kIsWeb || !(Platform.isLinux || Platform.isWindows)) {
expect(await canLaunchUrl(Uri(scheme: 'sms', path: '5555555555')), true);
}
// Sanity-check legacy API.
// ignore: deprecated_member_use
expect(await canLaunch('randomstring'), false);
// Generally all devices should have some default browser.
// ignore: deprecated_member_use
expect(await canLaunch('https://flutter.dev'), true);
});
}
| plugins/packages/url_launcher/url_launcher/example/integration_test/url_launcher_test.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher/example/integration_test/url_launcher_test.dart",
"repo_id": "plugins",
"token_count": 454
} | 1,488 |
// 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.
// Run this example with: flutter run -t lib/encoding.dart -d emulator
// This file is used to extract code samples for the README.md file.
// Run update-excerpts if you modify this file.
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
/// Encode [params] so it produces a correct query string.
/// Workaround for: https://github.com/dart-lang/sdk/issues/43838
// #docregion encode-query-parameters
String? encodeQueryParameters(Map<String, String> params) {
return params.entries
.map((MapEntry<String, String> e) =>
'${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}')
.join('&');
}
// #enddocregion encode-query-parameters
void main() => runApp(
// TODO(goderbauer): Make this const when this package requires Flutter 3.8 or later.
// ignore: prefer_const_constructors
MaterialApp(
// TODO(goderbauer): Make this const when this package requires Flutter 3.8 or later.
// ignore: prefer_const_constructors
home: Material(
// TODO(goderbauer): Make this const when this package requires Flutter 3.8 or later.
// ignore: prefer_const_constructors
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: const <Widget>[
ElevatedButton(
onPressed: _composeMail,
child: Text('Compose an email'),
),
ElevatedButton(
onPressed: _composeSms,
child: Text('Compose a SMS'),
),
],
),
),
),
);
void _composeMail() {
// #docregion encode-query-parameters
final Uri emailLaunchUri = Uri(
scheme: 'mailto',
path: '[email protected]',
query: encodeQueryParameters(<String, String>{
'subject': 'Example Subject & Symbols are allowed!',
}),
);
launchUrl(emailLaunchUri);
// #enddocregion encode-query-parameters
}
void _composeSms() {
// #docregion sms
final Uri smsLaunchUri = Uri(
scheme: 'sms',
path: '0118 999 881 999 119 7253',
queryParameters: <String, String>{
'body': Uri.encodeComponent('Example Subject & Symbols are allowed!'),
},
);
// #enddocregion sms
launchUrl(smsLaunchUri);
}
| plugins/packages/url_launcher/url_launcher/example/lib/encoding.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher/example/lib/encoding.dart",
"repo_id": "plugins",
"token_count": 977
} | 1,489 |
// 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 desired mode to launch a URL.
///
/// Support for these modes varies by platform. Platforms that do not support
/// the requested mode may substitute another mode. See [launchUrl] for more
/// details.
enum LaunchMode {
/// Leaves the decision of how to launch the URL to the platform
/// implementation.
platformDefault,
/// Loads the URL in an in-app web view (e.g., Safari View Controller).
inAppWebView,
/// Passes the URL to the OS to be handled by another application.
externalApplication,
/// Passes the URL to the OS to be handled by another non-browser application.
externalNonBrowserApplication,
}
/// Additional configuration options for [LaunchMode.inAppWebView].
@immutable
class WebViewConfiguration {
/// Creates a new WebViewConfiguration with the given settings.
const WebViewConfiguration({
this.enableJavaScript = true,
this.enableDomStorage = true,
this.headers = const <String, String>{},
});
/// Whether or not JavaScript is enabled for the web content.
///
/// Disabling this may not be supported on all platforms.
final bool enableJavaScript;
/// Whether or not DOM storage is enabled for the web content.
///
/// Disabling this may not be supported on all platforms.
final bool enableDomStorage;
/// Additional headers to pass in the load request.
///
/// On Android, this may work even when not loading in an in-app web view.
/// When loading in an external browsers, this sets
/// [Browser.EXTRA_HEADERS](https://developer.android.com/reference/android/provider/Browser#EXTRA_HEADERS)
/// Not all browsers support this, so it is not guaranteed to be honored.
final Map<String, String> headers;
}
| plugins/packages/url_launcher/url_launcher/lib/src/types.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher/lib/src/types.dart",
"repo_id": "plugins",
"token_count": 501
} | 1,490 |
rootProject.name = 'url_launcher_android'
| plugins/packages/url_launcher/url_launcher_android/android/settings.gradle/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_android/android/settings.gradle",
"repo_id": "plugins",
"token_count": 14
} | 1,491 |
// 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.
#include "my_application.h"
#include <flutter_linux/flutter_linux.h>
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
gtk_widget_show(GTK_WIDGET(header_bar));
gtk_header_bar_set_title(header_bar, "example");
gtk_header_bar_set_show_close_button(header_bar, TRUE);
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
gtk_window_set_default_size(window, 1280, 720);
gtk_widget_show(GTK_WIDGET(window));
g_autoptr(FlDartProject) project = fl_dart_project_new();
FlView* view = fl_view_new(project);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
return MY_APPLICATION(g_object_new(my_application_get_type(), nullptr));
}
| plugins/packages/url_launcher/url_launcher_linux/example/linux/my_application.cc/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_linux/example/linux/my_application.cc",
"repo_id": "plugins",
"token_count": 575
} | 1,492 |
// 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/services.dart';
import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
const MethodChannel _channel =
MethodChannel('plugins.flutter.io/url_launcher_macos');
/// An implementation of [UrlLauncherPlatform] for macOS.
class UrlLauncherMacOS extends UrlLauncherPlatform {
/// Registers this class as the default instance of [UrlLauncherPlatform].
static void registerWith() {
UrlLauncherPlatform.instance = UrlLauncherMacOS();
}
@override
final LinkDelegate? linkDelegate = null;
@override
Future<bool> canLaunch(String url) {
return _channel.invokeMethod<bool>(
'canLaunch',
<String, Object>{'url': url},
).then((bool? value) => value ?? false);
}
@override
Future<bool> launch(
String url, {
required bool useSafariVC,
required bool useWebView,
required bool enableJavaScript,
required bool enableDomStorage,
required bool universalLinksOnly,
required Map<String, String> headers,
String? webOnlyWindowName,
}) {
return _channel.invokeMethod<bool>(
'launch',
<String, Object>{
'url': url,
'enableJavaScript': enableJavaScript,
'enableDomStorage': enableDomStorage,
'universalLinksOnly': universalLinksOnly,
'headers': headers,
},
).then((bool? value) => value ?? false);
}
}
| plugins/packages/url_launcher/url_launcher_macos/lib/url_launcher_macos.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_macos/lib/url_launcher_macos.dart",
"repo_id": "plugins",
"token_count": 553
} | 1,493 |
// 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_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/method_channel_url_launcher.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Store the initial instance before any tests change it.
final UrlLauncherPlatform initialInstance = UrlLauncherPlatform.instance;
group('$UrlLauncherPlatform', () {
test('$MethodChannelUrlLauncher() is the default instance', () {
expect(initialInstance, isInstanceOf<MethodChannelUrlLauncher>());
});
test('Cannot be implemented with `implements`', () {
expect(() {
UrlLauncherPlatform.instance = ImplementsUrlLauncherPlatform();
// In versions of `package:plugin_platform_interface` prior to fixing
// https://github.com/flutter/flutter/issues/109339, an attempt to
// implement a platform interface using `implements` would sometimes
// throw a `NoSuchMethodError` and other times throw an
// `AssertionError`. After the issue is fixed, an `AssertionError` will
// always be thrown. For the purpose of this test, we don't really care
// what exception is thrown, so just allow any exception.
}, throwsA(anything));
});
test('Can be mocked with `implements`', () {
final UrlLauncherPlatformMock mock = UrlLauncherPlatformMock();
UrlLauncherPlatform.instance = mock;
});
test('Can be extended', () {
UrlLauncherPlatform.instance = ExtendsUrlLauncherPlatform();
});
});
group('$MethodChannelUrlLauncher', () {
const MethodChannel channel =
MethodChannel('plugins.flutter.io/url_launcher');
final List<MethodCall> log = <MethodCall>[];
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (MethodCall methodCall) async {
log.add(methodCall);
// Return null explicitly instead of relying on the implicit null
// returned by the method channel if no return statement is specified.
return null;
});
final MethodChannelUrlLauncher launcher = MethodChannelUrlLauncher();
tearDown(() {
log.clear();
});
test('canLaunch', () async {
await launcher.canLaunch('http://example.com/');
expect(
log,
<Matcher>[
isMethodCall('canLaunch', arguments: <String, Object>{
'url': 'http://example.com/',
})
],
);
});
test('canLaunch should return false if platform returns null', () async {
final bool canLaunch = await launcher.canLaunch('http://example.com/');
expect(canLaunch, false);
});
test('launch', () async {
await launcher.launch(
'http://example.com/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{},
);
expect(
log,
<Matcher>[
isMethodCall('launch', arguments: <String, Object>{
'url': 'http://example.com/',
'useSafariVC': true,
'useWebView': false,
'enableJavaScript': false,
'enableDomStorage': false,
'universalLinksOnly': false,
'headers': <String, String>{},
})
],
);
});
test('launch with headers', () async {
await launcher.launch(
'http://example.com/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{'key': 'value'},
);
expect(
log,
<Matcher>[
isMethodCall('launch', arguments: <String, Object>{
'url': 'http://example.com/',
'useSafariVC': true,
'useWebView': false,
'enableJavaScript': false,
'enableDomStorage': false,
'universalLinksOnly': false,
'headers': <String, String>{'key': 'value'},
})
],
);
});
test('launch force SafariVC', () async {
await launcher.launch(
'http://example.com/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{},
);
expect(
log,
<Matcher>[
isMethodCall('launch', arguments: <String, Object>{
'url': 'http://example.com/',
'useSafariVC': true,
'useWebView': false,
'enableJavaScript': false,
'enableDomStorage': false,
'universalLinksOnly': false,
'headers': <String, String>{},
})
],
);
});
test('launch universal links only', () async {
await launcher.launch(
'http://example.com/',
useSafariVC: false,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: true,
headers: const <String, String>{},
);
expect(
log,
<Matcher>[
isMethodCall('launch', arguments: <String, Object>{
'url': 'http://example.com/',
'useSafariVC': false,
'useWebView': false,
'enableJavaScript': false,
'enableDomStorage': false,
'universalLinksOnly': true,
'headers': <String, String>{},
})
],
);
});
test('launch force WebView', () async {
await launcher.launch(
'http://example.com/',
useSafariVC: true,
useWebView: true,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{},
);
expect(
log,
<Matcher>[
isMethodCall('launch', arguments: <String, Object>{
'url': 'http://example.com/',
'useSafariVC': true,
'useWebView': true,
'enableJavaScript': false,
'enableDomStorage': false,
'universalLinksOnly': false,
'headers': <String, String>{},
})
],
);
});
test('launch force WebView enable javascript', () async {
await launcher.launch(
'http://example.com/',
useSafariVC: true,
useWebView: true,
enableJavaScript: true,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{},
);
expect(
log,
<Matcher>[
isMethodCall('launch', arguments: <String, Object>{
'url': 'http://example.com/',
'useSafariVC': true,
'useWebView': true,
'enableJavaScript': true,
'enableDomStorage': false,
'universalLinksOnly': false,
'headers': <String, String>{},
})
],
);
});
test('launch force WebView enable DOM storage', () async {
await launcher.launch(
'http://example.com/',
useSafariVC: true,
useWebView: true,
enableJavaScript: false,
enableDomStorage: true,
universalLinksOnly: false,
headers: const <String, String>{},
);
expect(
log,
<Matcher>[
isMethodCall('launch', arguments: <String, Object>{
'url': 'http://example.com/',
'useSafariVC': true,
'useWebView': true,
'enableJavaScript': false,
'enableDomStorage': true,
'universalLinksOnly': false,
'headers': <String, String>{},
})
],
);
});
test('launch force SafariVC to false', () async {
await launcher.launch(
'http://example.com/',
useSafariVC: false,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{},
);
expect(
log,
<Matcher>[
isMethodCall('launch', arguments: <String, Object>{
'url': 'http://example.com/',
'useSafariVC': false,
'useWebView': false,
'enableJavaScript': false,
'enableDomStorage': false,
'universalLinksOnly': false,
'headers': <String, String>{},
})
],
);
});
test('launch should return false if platform returns null', () async {
final bool launched = await launcher.launch(
'http://example.com/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{},
);
expect(launched, false);
});
test('closeWebView default behavior', () async {
await launcher.closeWebView();
expect(
log,
<Matcher>[isMethodCall('closeWebView', arguments: null)],
);
});
});
}
class UrlLauncherPlatformMock extends Mock
with MockPlatformInterfaceMixin
implements UrlLauncherPlatform {}
class ImplementsUrlLauncherPlatform extends Mock
implements UrlLauncherPlatform {}
class ExtendsUrlLauncherPlatform extends UrlLauncherPlatform {
@override
final LinkDelegate? linkDelegate = null;
}
/// 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/url_launcher/url_launcher_platform_interface/test/method_channel_url_launcher_test.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_platform_interface/test/method_channel_url_launcher_test.dart",
"repo_id": "plugins",
"token_count": 4431
} | 1,494 |
// 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:js_util';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart' show urlStrategy;
import 'package:url_launcher_platform_interface/link.dart';
/// The unique identifier for the view type to be used for link platform views.
const String linkViewType = '__url_launcher::link';
/// The name of the property used to set the viewId on the DOM element.
const String linkViewIdProperty = '__url_launcher::link::viewId';
/// Signature for a function that takes a unique [id] and creates an HTML element.
typedef HtmlViewFactory = html.Element Function(int viewId);
/// Factory that returns the link DOM element for each unique view id.
HtmlViewFactory get linkViewFactory => LinkViewController._viewFactory;
/// The delegate for building the [Link] widget on the web.
///
/// It uses a platform view to render an anchor element in the DOM.
class WebLinkDelegate extends StatefulWidget {
/// Creates a delegate for the given [link].
const WebLinkDelegate(this.link, {Key? key}) : super(key: key);
/// Information about the link built by the app.
final LinkInfo link;
@override
WebLinkDelegateState createState() => WebLinkDelegateState();
}
/// The link delegate used on the web platform.
///
/// For external URIs, it lets the browser do its thing. For app route names, it
/// pushes the route name to the framework.
class WebLinkDelegateState extends State<WebLinkDelegate> {
late LinkViewController _controller;
@override
void didUpdateWidget(WebLinkDelegate oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.link.uri != oldWidget.link.uri) {
_controller.setUri(widget.link.uri);
}
if (widget.link.target != oldWidget.link.target) {
_controller.setTarget(widget.link.target);
}
}
Future<void> _followLink() {
LinkViewController.registerHitTest(_controller);
return Future<void>.value();
}
@override
Widget build(BuildContext context) {
return Stack(
fit: StackFit.passthrough,
children: <Widget>[
widget.link.builder(
context,
widget.link.isDisabled ? null : _followLink,
),
Positioned.fill(
child: PlatformViewLink(
viewType: linkViewType,
onCreatePlatformView: (PlatformViewCreationParams params) {
_controller = LinkViewController.fromParams(params);
return _controller
..setUri(widget.link.uri)
..setTarget(widget.link.target);
},
surfaceFactory:
(BuildContext context, PlatformViewController controller) {
return PlatformViewSurface(
controller: controller,
gestureRecognizers: const <
Factory<OneSequenceGestureRecognizer>>{},
hitTestBehavior: PlatformViewHitTestBehavior.transparent,
);
},
),
),
],
);
}
}
/// Controls link views.
class LinkViewController extends PlatformViewController {
/// Creates a [LinkViewController] instance with the unique [viewId].
LinkViewController(this.viewId) {
if (_instances.isEmpty) {
// This is the first controller being created, attach the global click
// listener.
_clickSubscription = html.window.onClick.listen(_onGlobalClick);
}
_instances[viewId] = this;
}
/// Creates and initializes a [LinkViewController] instance with the given
/// platform view [params].
factory LinkViewController.fromParams(
PlatformViewCreationParams params,
) {
final int viewId = params.id;
final LinkViewController controller = LinkViewController(viewId);
controller._initialize().then((_) {
/// Because _initialize is async, it can happen that [LinkViewController.dispose]
/// may get called before this `then` callback.
/// Check that the `controller` that was created by this factory is not
/// disposed before calling `onPlatformViewCreated`.
if (_instances[viewId] == controller) {
params.onPlatformViewCreated(viewId);
}
});
return controller;
}
static final Map<int, LinkViewController> _instances =
<int, LinkViewController>{};
static html.Element _viewFactory(int viewId) {
return _instances[viewId]!._element;
}
static int? _hitTestedViewId;
static late StreamSubscription<html.MouseEvent> _clickSubscription;
static void _onGlobalClick(html.MouseEvent event) {
final int? viewId = getViewIdFromTarget(event);
_instances[viewId]?._onDomClick(event);
// After the DOM click event has been received, clean up the hit test state
// so we can start fresh on the next click.
unregisterHitTest();
}
/// Call this method to indicate that a hit test has been registered for the
/// given [controller].
///
/// The [onClick] callback is invoked when the anchor element receives a
/// `click` from the browser.
static void registerHitTest(LinkViewController controller) {
_hitTestedViewId = controller.viewId;
}
/// Removes all information about previously registered hit tests.
static void unregisterHitTest() {
_hitTestedViewId = null;
}
@override
final int viewId;
late html.Element _element;
bool get _isInitialized => _element != null;
Future<void> _initialize() async {
_element = html.Element.tag('a');
setProperty(_element, linkViewIdProperty, viewId);
_element.style
..opacity = '0'
..display = 'block'
..width = '100%'
..height = '100%'
..cursor = 'unset';
// This is recommended on MDN:
// - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-target
_element.setAttribute('rel', 'noreferrer noopener');
final Map<String, dynamic> args = <String, dynamic>{
'id': viewId,
'viewType': linkViewType,
};
await SystemChannels.platform_views.invokeMethod<void>('create', args);
}
void _onDomClick(html.MouseEvent event) {
final bool isHitTested = _hitTestedViewId == viewId;
if (!isHitTested) {
// There was no hit test registered for this click. This means the click
// landed on the anchor element but not on the underlying widget. In this
// case, we prevent the browser from following the click.
event.preventDefault();
return;
}
if (_uri != null && _uri!.hasScheme) {
// External links will be handled by the browser, so we don't have to do
// anything.
return;
}
// A uri that doesn't have a scheme is an internal route name. In this
// case, we push it via Flutter's navigation system instead of letting the
// browser handle it.
event.preventDefault();
final String routeName = _uri.toString();
pushRouteNameToFramework(null, routeName);
}
Uri? _uri;
/// Set the [Uri] value for this link.
///
/// When Uri is null, the `href` attribute of the link is removed.
void setUri(Uri? uri) {
assert(_isInitialized);
_uri = uri;
if (uri == null) {
_element.removeAttribute('href');
} else {
String href = uri.toString();
// in case an internal uri is given, the url mus be properly encoded
// using the currently used [UrlStrategy]
if (!uri.hasScheme) {
href = urlStrategy?.prepareExternalUrl(href) ?? href;
}
_element.setAttribute('href', href);
}
}
/// Set the [LinkTarget] value for this link.
void setTarget(LinkTarget target) {
assert(_isInitialized);
_element.setAttribute('target', _getHtmlTarget(target));
}
String _getHtmlTarget(LinkTarget target) {
switch (target) {
case LinkTarget.defaultTarget:
case LinkTarget.self:
return '_self';
case LinkTarget.blank:
return '_blank';
}
// The enum comes from a different package, which could get a new value at
// any time, so provide a fallback that ensures this won't break when used
// with a version that contains new values. This is deliberately outside
// the switch rather than a `default` so that the linter will flag the
// switch as needing an update.
return '_self';
}
@override
Future<void> clearFocus() async {
// Currently this does nothing on Flutter Web.
// TODO(het): Implement this. See https://github.com/flutter/flutter/issues/39496
}
@override
Future<void> dispatchPointerEvent(PointerEvent event) async {
// We do not dispatch pointer events to HTML views because they may contain
// cross-origin iframes, which only accept user-generated events.
}
@override
Future<void> dispose() async {
if (_isInitialized) {
assert(_instances[viewId] == this);
_instances.remove(viewId);
if (_instances.isEmpty) {
await _clickSubscription.cancel();
}
await SystemChannels.platform_views.invokeMethod<void>('dispose', viewId);
}
}
}
/// Finds the view id of the DOM element targeted by the [event].
int? getViewIdFromTarget(html.Event event) {
final html.Element? linkElement = getLinkElementFromTarget(event);
if (linkElement != null) {
// TODO(stuartmorgan): Remove this ignore (and change to getProperty<int>)
// once the templated version is available on stable. On master (2.8) this
// is already not necessary.
// ignore: return_of_invalid_type
return getProperty(linkElement, linkViewIdProperty);
}
return null;
}
/// Finds the targeted DOM element by the [event].
///
/// It handles the case where the target element is inside a shadow DOM too.
html.Element? getLinkElementFromTarget(html.Event event) {
final html.EventTarget? target = event.target;
if (target != null && target is html.Element) {
if (isLinkElement(target)) {
return target;
}
if (target.shadowRoot != null) {
final html.Node? child = target.shadowRoot!.lastChild;
if (child != null && child is html.Element && isLinkElement(child)) {
return child;
}
}
}
return null;
}
/// Checks if the given [element] is a link that was created by
/// [LinkViewController].
bool isLinkElement(html.Element? element) {
return element != null &&
element.tagName == 'A' &&
hasProperty(element, linkViewIdProperty);
}
| plugins/packages/url_launcher/url_launcher_web/lib/src/link.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_web/lib/src/link.dart",
"repo_id": "plugins",
"token_count": 3670
} | 1,495 |
// 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_test/flutter_test.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import 'package:url_launcher_windows/src/messages.g.dart';
import 'package:url_launcher_windows/url_launcher_windows.dart';
void main() {
late _FakeUrlLauncherApi api;
late UrlLauncherWindows plugin;
setUp(() {
api = _FakeUrlLauncherApi();
plugin = UrlLauncherWindows(api: api);
});
test('registers instance', () {
UrlLauncherWindows.registerWith();
expect(UrlLauncherPlatform.instance, isA<UrlLauncherWindows>());
});
group('canLaunch', () {
test('handles true', () async {
api.canLaunch = true;
final bool result = await plugin.canLaunch('http://example.com/');
expect(result, isTrue);
expect(api.argument, 'http://example.com/');
});
test('handles false', () async {
api.canLaunch = false;
final bool result = await plugin.canLaunch('http://example.com/');
expect(result, isFalse);
expect(api.argument, 'http://example.com/');
});
});
group('launch', () {
test('handles success', () async {
api.canLaunch = true;
expect(
plugin.launch(
'http://example.com/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{},
),
completes);
expect(api.argument, 'http://example.com/');
});
test('handles failure', () async {
api.canLaunch = false;
await expectLater(
plugin.launch(
'http://example.com/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{},
),
throwsA(isA<PlatformException>()));
expect(api.argument, 'http://example.com/');
});
});
}
class _FakeUrlLauncherApi implements UrlLauncherApi {
/// The argument that was passed to an API call.
String? argument;
/// Controls the behavior of the fake implementations.
///
/// - [canLaunchUrl] returns this value.
/// - [launchUrl] throws if this is false.
bool canLaunch = false;
@override
Future<bool> canLaunchUrl(String url) async {
argument = url;
return canLaunch;
}
@override
Future<void> launchUrl(String url) async {
argument = url;
if (!canLaunch) {
throw PlatformException(code: 'Failed');
}
}
}
| plugins/packages/url_launcher/url_launcher_windows/test/url_launcher_windows_test.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_windows/test/url_launcher_windows_test.dart",
"repo_id": "plugins",
"token_count": 1117
} | 1,496 |
// 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.videoplayerexample;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineCache;
import io.flutter.embedding.engine.FlutterJNI;
import io.flutter.embedding.engine.loader.FlutterLoader;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugins.videoplayer.VideoPlayerPlugin;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class FlutterActivityTest {
@Test
public void disposeAllPlayers() {
VideoPlayerPlugin videoPlayerPlugin = spy(new VideoPlayerPlugin());
FlutterLoader flutterLoader = mock(FlutterLoader.class);
FlutterJNI flutterJNI = mock(FlutterJNI.class);
ArgumentCaptor<FlutterPlugin.FlutterPluginBinding> pluginBindingCaptor =
ArgumentCaptor.forClass(FlutterPlugin.FlutterPluginBinding.class);
when(flutterJNI.isAttached()).thenReturn(true);
FlutterEngine engine =
spy(new FlutterEngine(RuntimeEnvironment.application, flutterLoader, flutterJNI));
FlutterEngineCache.getInstance().put("my_flutter_engine", engine);
engine.getPlugins().add(videoPlayerPlugin);
verify(videoPlayerPlugin, times(1)).onAttachedToEngine(pluginBindingCaptor.capture());
engine.destroy();
verify(videoPlayerPlugin, times(1)).onDetachedFromEngine(pluginBindingCaptor.capture());
verify(videoPlayerPlugin, times(1)).initialize();
}
}
| plugins/packages/video_player/video_player/example/android/app/src/test/java/io/flutter/plugins/videoplayerexample/FlutterActivityTest.java/0 | {
"file_path": "plugins/packages/video_player/video_player/example/android/app/src/test/java/io/flutter/plugins/videoplayerexample/FlutterActivityTest.java",
"repo_id": "plugins",
"token_count": 663
} | 1,497 |
// 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:io';
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:video_player/video_player.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
class FakeController extends ValueNotifier<VideoPlayerValue>
implements VideoPlayerController {
FakeController() : super(VideoPlayerValue(duration: Duration.zero));
FakeController.value(VideoPlayerValue value) : super(value);
@override
Future<void> dispose() async {
super.dispose();
}
@override
int textureId = VideoPlayerController.kUninitializedTextureId;
@override
String get dataSource => '';
@override
Map<String, String> get httpHeaders => <String, String>{};
@override
DataSourceType get dataSourceType => DataSourceType.file;
@override
String get package => '';
@override
Future<Duration> get position async => value.position;
@override
Future<void> seekTo(Duration moment) async {}
@override
Future<void> setVolume(double volume) async {}
@override
Future<void> setPlaybackSpeed(double speed) async {}
@override
Future<void> initialize() async {}
@override
Future<void> pause() async {}
@override
Future<void> play() async {}
@override
Future<void> setLooping(bool looping) async {}
@override
VideoFormat? get formatHint => null;
@override
Future<ClosedCaptionFile> get closedCaptionFile => _loadClosedCaption();
@override
VideoPlayerOptions? get videoPlayerOptions => null;
@override
void setCaptionOffset(Duration delay) {}
@override
Future<void> setClosedCaptionFile(
Future<ClosedCaptionFile>? closedCaptionFile,
) async {}
}
Future<ClosedCaptionFile> _loadClosedCaption() async =>
_FakeClosedCaptionFile();
class _FakeClosedCaptionFile extends ClosedCaptionFile {
@override
List<Caption> get captions {
return <Caption>[
const Caption(
text: 'one',
number: 0,
start: Duration(milliseconds: 100),
end: Duration(milliseconds: 200),
),
const Caption(
text: 'two',
number: 1,
start: Duration(milliseconds: 300),
end: Duration(milliseconds: 400),
),
];
}
}
void main() {
late FakeVideoPlayerPlatform fakeVideoPlayerPlatform;
setUp(() {
fakeVideoPlayerPlatform = FakeVideoPlayerPlatform();
VideoPlayerPlatform.instance = fakeVideoPlayerPlatform;
});
void verifyPlayStateRespondsToLifecycle(
VideoPlayerController controller, {
required bool shouldPlayInBackground,
}) {
expect(controller.value.isPlaying, true);
_ambiguate(WidgetsBinding.instance)!
.handleAppLifecycleStateChanged(AppLifecycleState.paused);
expect(controller.value.isPlaying, shouldPlayInBackground);
_ambiguate(WidgetsBinding.instance)!
.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
expect(controller.value.isPlaying, true);
}
testWidgets('update texture', (WidgetTester tester) async {
final FakeController controller = FakeController();
await tester.pumpWidget(VideoPlayer(controller));
expect(find.byType(Texture), findsNothing);
controller.textureId = 123;
controller.value = controller.value.copyWith(
duration: const Duration(milliseconds: 100),
isInitialized: true,
);
await tester.pump();
expect(find.byType(Texture), findsOneWidget);
});
testWidgets('update controller', (WidgetTester tester) async {
final FakeController controller1 = FakeController();
controller1.textureId = 101;
await tester.pumpWidget(VideoPlayer(controller1));
expect(
find.byWidgetPredicate(
(Widget widget) => widget is Texture && widget.textureId == 101,
),
findsOneWidget);
final FakeController controller2 = FakeController();
controller2.textureId = 102;
await tester.pumpWidget(VideoPlayer(controller2));
expect(
find.byWidgetPredicate(
(Widget widget) => widget is Texture && widget.textureId == 102,
),
findsOneWidget);
});
testWidgets('non-zero rotationCorrection value is used',
(WidgetTester tester) async {
final FakeController controller = FakeController.value(
VideoPlayerValue(duration: Duration.zero, rotationCorrection: 180));
controller.textureId = 1;
await tester.pumpWidget(VideoPlayer(controller));
final Transform actualRotationCorrection =
find.byType(Transform).evaluate().single.widget as Transform;
final Float64List actualRotationCorrectionStorage =
actualRotationCorrection.transform.storage;
final Float64List expectedMatrixStorage =
Matrix4.rotationZ(math.pi).storage;
expect(actualRotationCorrectionStorage.length,
equals(expectedMatrixStorage.length));
for (int i = 0; i < actualRotationCorrectionStorage.length; i++) {
expect(actualRotationCorrectionStorage[i],
moreOrLessEquals(expectedMatrixStorage[i]));
}
});
testWidgets('no transform when rotationCorrection is zero',
(WidgetTester tester) async {
final FakeController controller =
FakeController.value(VideoPlayerValue(duration: Duration.zero));
controller.textureId = 1;
await tester.pumpWidget(VideoPlayer(controller));
expect(find.byType(Transform), findsNothing);
});
group('ClosedCaption widget', () {
testWidgets('uses a default text style', (WidgetTester tester) async {
const String text = 'foo';
await tester
.pumpWidget(const MaterialApp(home: ClosedCaption(text: text)));
final Text textWidget = tester.widget<Text>(find.text(text));
expect(textWidget.style!.fontSize, 36.0);
expect(textWidget.style!.color, Colors.white);
});
testWidgets('uses given text and style', (WidgetTester tester) async {
const String text = 'foo';
const TextStyle textStyle = TextStyle(fontSize: 14.725);
await tester.pumpWidget(const MaterialApp(
home: ClosedCaption(
text: text,
textStyle: textStyle,
),
));
expect(find.text(text), findsOneWidget);
final Text textWidget = tester.widget<Text>(find.text(text));
expect(textWidget.style!.fontSize, textStyle.fontSize);
});
testWidgets('handles null text', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: ClosedCaption()));
expect(find.byType(Text), findsNothing);
});
testWidgets('handles empty text', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: ClosedCaption(text: '')));
expect(find.byType(Text), findsNothing);
});
testWidgets('Passes text contrast ratio guidelines',
(WidgetTester tester) async {
const String text = 'foo';
await tester.pumpWidget(const MaterialApp(
home: Scaffold(
backgroundColor: Colors.white,
body: ClosedCaption(text: text),
),
));
expect(find.text(text), findsOneWidget);
await expectLater(tester, meetsGuideline(textContrastGuideline));
}, skip: isBrowser);
});
group('VideoPlayerController', () {
group('initialize', () {
test('started app lifecycle observing', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
await controller.play();
verifyPlayStateRespondsToLifecycle(controller,
shouldPlayInBackground: false);
});
test('asset', () async {
final VideoPlayerController controller = VideoPlayerController.asset(
'a.avi',
);
await controller.initialize();
expect(fakeVideoPlayerPlatform.dataSources[0].asset, 'a.avi');
expect(fakeVideoPlayerPlatform.dataSources[0].package, null);
});
test('network', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
expect(
fakeVideoPlayerPlatform.dataSources[0].uri,
'https://127.0.0.1',
);
expect(
fakeVideoPlayerPlatform.dataSources[0].formatHint,
null,
);
expect(
fakeVideoPlayerPlatform.dataSources[0].httpHeaders,
<String, String>{},
);
});
test('network with hint', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
formatHint: VideoFormat.dash,
);
await controller.initialize();
expect(
fakeVideoPlayerPlatform.dataSources[0].uri,
'https://127.0.0.1',
);
expect(
fakeVideoPlayerPlatform.dataSources[0].formatHint,
VideoFormat.dash,
);
expect(
fakeVideoPlayerPlatform.dataSources[0].httpHeaders,
<String, String>{},
);
});
test('network with some headers', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
httpHeaders: <String, String>{'Authorization': 'Bearer token'},
);
await controller.initialize();
expect(
fakeVideoPlayerPlatform.dataSources[0].uri,
'https://127.0.0.1',
);
expect(
fakeVideoPlayerPlatform.dataSources[0].formatHint,
null,
);
expect(
fakeVideoPlayerPlatform.dataSources[0].httpHeaders,
<String, String>{'Authorization': 'Bearer token'},
);
});
test('init errors', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'http://testing.com/invalid_url',
);
late Object error;
fakeVideoPlayerPlatform.forceInitError = true;
await controller.initialize().catchError((Object e) => error = e);
final PlatformException platformEx = error as PlatformException;
expect(platformEx.code, equals('VideoError'));
});
test('file', () async {
final VideoPlayerController controller =
VideoPlayerController.file(File('a.avi'));
await controller.initialize();
final String uri = fakeVideoPlayerPlatform.dataSources[0].uri!;
expect(uri.startsWith('file:///'), true, reason: 'Actual string: $uri');
expect(uri.endsWith('/a.avi'), true, reason: 'Actual string: $uri');
}, skip: kIsWeb /* Web does not support file assets. */);
test('file with special characters', () async {
final VideoPlayerController controller =
VideoPlayerController.file(File('A #1 Hit?.avi'));
await controller.initialize();
final String uri = fakeVideoPlayerPlatform.dataSources[0].uri!;
expect(uri.startsWith('file:///'), true, reason: 'Actual string: $uri');
expect(uri.endsWith('/A%20%231%20Hit%3F.avi'), true,
reason: 'Actual string: $uri');
}, skip: kIsWeb /* Web does not support file assets. */);
test('successful initialize on controller with error clears error',
() async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
fakeVideoPlayerPlatform.forceInitError = true;
await controller.initialize().catchError((dynamic e) {});
expect(controller.value.hasError, equals(true));
fakeVideoPlayerPlatform.forceInitError = false;
await controller.initialize();
expect(controller.value.hasError, equals(false));
});
});
test('contentUri', () async {
final VideoPlayerController controller =
VideoPlayerController.contentUri(Uri.parse('content://video'));
await controller.initialize();
expect(fakeVideoPlayerPlatform.dataSources[0].uri, 'content://video');
});
test('dispose', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
expect(
controller.textureId, VideoPlayerController.kUninitializedTextureId);
expect(await controller.position, Duration.zero);
await controller.initialize();
await controller.dispose();
expect(controller.textureId, 0);
expect(await controller.position, isNull);
});
test('calling dispose() on disposed controller does not throw', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
await controller.dispose();
expect(() async => controller.dispose(), returnsNormally);
});
test('play', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
expect(controller.value.isPlaying, isFalse);
await controller.play();
expect(controller.value.isPlaying, isTrue);
// The two last calls will be "play" and then "setPlaybackSpeed". The
// reason for this is that "play" calls "setPlaybackSpeed" internally.
expect(
fakeVideoPlayerPlatform
.calls[fakeVideoPlayerPlatform.calls.length - 2],
'play');
expect(fakeVideoPlayerPlatform.calls.last, 'setPlaybackSpeed');
});
test('play before initialized does not call platform', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
expect(controller.value.isInitialized, isFalse);
await controller.play();
expect(fakeVideoPlayerPlatform.calls, isEmpty);
});
test('play restarts from beginning if video is at end', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
const Duration nonzeroDuration = Duration(milliseconds: 100);
controller.value = controller.value.copyWith(duration: nonzeroDuration);
await controller.seekTo(nonzeroDuration);
expect(controller.value.isPlaying, isFalse);
expect(controller.value.position, nonzeroDuration);
await controller.play();
expect(controller.value.isPlaying, isTrue);
expect(controller.value.position, Duration.zero);
});
test('setLooping', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
expect(controller.value.isLooping, isFalse);
await controller.setLooping(true);
expect(controller.value.isLooping, isTrue);
});
test('pause', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
await controller.play();
expect(controller.value.isPlaying, isTrue);
await controller.pause();
expect(controller.value.isPlaying, isFalse);
expect(fakeVideoPlayerPlatform.calls.last, 'pause');
});
group('seekTo', () {
test('works', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
expect(await controller.position, Duration.zero);
await controller.seekTo(const Duration(milliseconds: 500));
expect(await controller.position, const Duration(milliseconds: 500));
});
test('before initialized does not call platform', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
expect(controller.value.isInitialized, isFalse);
await controller.seekTo(const Duration(milliseconds: 500));
expect(fakeVideoPlayerPlatform.calls, isEmpty);
});
test('clamps values that are too high or low', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
expect(await controller.position, Duration.zero);
await controller.seekTo(const Duration(seconds: 100));
expect(await controller.position, const Duration(seconds: 1));
await controller.seekTo(const Duration(seconds: -100));
expect(await controller.position, Duration.zero);
});
});
group('setVolume', () {
test('works', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
expect(controller.value.volume, 1.0);
const double volume = 0.5;
await controller.setVolume(volume);
expect(controller.value.volume, volume);
});
test('clamps values that are too high or low', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
expect(controller.value.volume, 1.0);
await controller.setVolume(-1);
expect(controller.value.volume, 0.0);
await controller.setVolume(11);
expect(controller.value.volume, 1.0);
});
});
group('setPlaybackSpeed', () {
test('works', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
expect(controller.value.playbackSpeed, 1.0);
const double speed = 1.5;
await controller.setPlaybackSpeed(speed);
expect(controller.value.playbackSpeed, speed);
});
test('rejects negative values', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
expect(controller.value.playbackSpeed, 1.0);
expect(() => controller.setPlaybackSpeed(-1), throwsArgumentError);
});
});
group('scrubbing', () {
testWidgets('restarts on release if already playing',
(WidgetTester tester) async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
final VideoProgressIndicator progressWidget =
VideoProgressIndicator(controller, allowScrubbing: true);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: progressWidget,
));
await controller.play();
expect(controller.value.isPlaying, isTrue);
final Rect progressRect = tester.getRect(find.byWidget(progressWidget));
await tester.dragFrom(progressRect.center, const Offset(1.0, 0.0));
await tester.pumpAndSettle();
expect(controller.value.position, lessThan(controller.value.duration));
expect(controller.value.isPlaying, isTrue);
await controller.pause();
});
testWidgets('does not restart when dragging to end',
(WidgetTester tester) async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
final VideoProgressIndicator progressWidget =
VideoProgressIndicator(controller, allowScrubbing: true);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: progressWidget,
));
await controller.play();
expect(controller.value.isPlaying, isTrue);
final Rect progressRect = tester.getRect(find.byWidget(progressWidget));
await tester.dragFrom(progressRect.center, progressRect.centerRight);
await tester.pumpAndSettle();
expect(controller.value.position, controller.value.duration);
expect(controller.value.isPlaying, isFalse);
});
});
group('caption', () {
test('works when seeking', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
closedCaptionFile: _loadClosedCaption(),
);
await controller.initialize();
expect(controller.value.position, Duration.zero);
expect(controller.value.caption.text, '');
await controller.seekTo(const Duration(milliseconds: 100));
expect(controller.value.caption.text, 'one');
await controller.seekTo(const Duration(milliseconds: 250));
expect(controller.value.caption.text, '');
await controller.seekTo(const Duration(milliseconds: 300));
expect(controller.value.caption.text, 'two');
await controller.seekTo(const Duration(milliseconds: 301));
expect(controller.value.caption.text, 'two');
await controller.seekTo(const Duration(milliseconds: 500));
expect(controller.value.caption.text, '');
await controller.seekTo(const Duration(milliseconds: 300));
expect(controller.value.caption.text, 'two');
await controller.seekTo(const Duration(milliseconds: 301));
expect(controller.value.caption.text, 'two');
});
test('works when seeking with captionOffset positive', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
closedCaptionFile: _loadClosedCaption(),
);
await controller.initialize();
controller.setCaptionOffset(const Duration(milliseconds: 100));
expect(controller.value.position, Duration.zero);
expect(controller.value.caption.text, '');
await controller.seekTo(const Duration(milliseconds: 100));
expect(controller.value.caption.text, 'one');
await controller.seekTo(const Duration(milliseconds: 101));
expect(controller.value.caption.text, '');
await controller.seekTo(const Duration(milliseconds: 250));
expect(controller.value.caption.text, 'two');
await controller.seekTo(const Duration(milliseconds: 300));
expect(controller.value.caption.text, 'two');
await controller.seekTo(const Duration(milliseconds: 301));
expect(controller.value.caption.text, '');
await controller.seekTo(const Duration(milliseconds: 500));
expect(controller.value.caption.text, '');
await controller.seekTo(const Duration(milliseconds: 300));
expect(controller.value.caption.text, 'two');
await controller.seekTo(const Duration(milliseconds: 301));
expect(controller.value.caption.text, '');
});
test('works when seeking with captionOffset negative', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
closedCaptionFile: _loadClosedCaption(),
);
await controller.initialize();
controller.setCaptionOffset(const Duration(milliseconds: -100));
expect(controller.value.position, Duration.zero);
expect(controller.value.caption.text, '');
await controller.seekTo(const Duration(milliseconds: 100));
expect(controller.value.caption.text, '');
await controller.seekTo(const Duration(milliseconds: 200));
expect(controller.value.caption.text, 'one');
await controller.seekTo(const Duration(milliseconds: 250));
expect(controller.value.caption.text, 'one');
await controller.seekTo(const Duration(milliseconds: 300));
expect(controller.value.caption.text, 'one');
await controller.seekTo(const Duration(milliseconds: 301));
expect(controller.value.caption.text, '');
await controller.seekTo(const Duration(milliseconds: 400));
expect(controller.value.caption.text, 'two');
await controller.seekTo(const Duration(milliseconds: 500));
expect(controller.value.caption.text, 'two');
await controller.seekTo(const Duration(milliseconds: 600));
expect(controller.value.caption.text, '');
await controller.seekTo(const Duration(milliseconds: 300));
expect(controller.value.caption.text, 'one');
});
test('setClosedCaptionFile loads caption file', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
expect(controller.closedCaptionFile, null);
await controller.setClosedCaptionFile(_loadClosedCaption());
expect(
(await controller.closedCaptionFile)!.captions,
(await _loadClosedCaption()).captions,
);
});
test('setClosedCaptionFile removes/changes caption file', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
closedCaptionFile: _loadClosedCaption(),
);
await controller.initialize();
expect(
(await controller.closedCaptionFile)!.captions,
(await _loadClosedCaption()).captions,
);
await controller.setClosedCaptionFile(null);
expect(controller.closedCaptionFile, null);
});
});
group('Platform callbacks', () {
testWidgets('playing completed', (WidgetTester tester) async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
const Duration nonzeroDuration = Duration(milliseconds: 100);
controller.value = controller.value.copyWith(duration: nonzeroDuration);
expect(controller.value.isPlaying, isFalse);
await controller.play();
expect(controller.value.isPlaying, isTrue);
final StreamController<VideoEvent> fakeVideoEventStream =
fakeVideoPlayerPlatform.streams[controller.textureId]!;
fakeVideoEventStream
.add(VideoEvent(eventType: VideoEventType.completed));
await tester.pumpAndSettle();
expect(controller.value.isPlaying, isFalse);
expect(controller.value.position, nonzeroDuration);
});
testWidgets('buffering status', (WidgetTester tester) async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
);
await controller.initialize();
expect(controller.value.isBuffering, false);
expect(controller.value.buffered, isEmpty);
final StreamController<VideoEvent> fakeVideoEventStream =
fakeVideoPlayerPlatform.streams[controller.textureId]!;
fakeVideoEventStream
.add(VideoEvent(eventType: VideoEventType.bufferingStart));
await tester.pumpAndSettle();
expect(controller.value.isBuffering, isTrue);
const Duration bufferStart = Duration.zero;
const Duration bufferEnd = Duration(milliseconds: 500);
fakeVideoEventStream.add(VideoEvent(
eventType: VideoEventType.bufferingUpdate,
buffered: <DurationRange>[
DurationRange(bufferStart, bufferEnd),
]));
await tester.pumpAndSettle();
expect(controller.value.isBuffering, isTrue);
expect(controller.value.buffered.length, 1);
expect(controller.value.buffered[0].toString(),
DurationRange(bufferStart, bufferEnd).toString());
fakeVideoEventStream
.add(VideoEvent(eventType: VideoEventType.bufferingEnd));
await tester.pumpAndSettle();
expect(controller.value.isBuffering, isFalse);
});
});
});
group('DurationRange', () {
test('uses given values', () {
const Duration start = Duration(seconds: 2);
const Duration end = Duration(seconds: 8);
final DurationRange range = DurationRange(start, end);
expect(range.start, start);
expect(range.end, end);
expect(range.toString(), contains('start: $start, end: $end'));
});
test('calculates fractions', () {
const Duration start = Duration(seconds: 2);
const Duration end = Duration(seconds: 8);
const Duration total = Duration(seconds: 10);
final DurationRange range = DurationRange(start, end);
expect(range.startFraction(total), .2);
expect(range.endFraction(total), .8);
});
});
group('VideoPlayerValue', () {
test('uninitialized()', () {
final VideoPlayerValue uninitialized = VideoPlayerValue.uninitialized();
expect(uninitialized.duration, equals(Duration.zero));
expect(uninitialized.position, equals(Duration.zero));
expect(uninitialized.caption, equals(Caption.none));
expect(uninitialized.captionOffset, equals(Duration.zero));
expect(uninitialized.buffered, isEmpty);
expect(uninitialized.isPlaying, isFalse);
expect(uninitialized.isLooping, isFalse);
expect(uninitialized.isBuffering, isFalse);
expect(uninitialized.volume, 1.0);
expect(uninitialized.playbackSpeed, 1.0);
expect(uninitialized.errorDescription, isNull);
expect(uninitialized.size, equals(Size.zero));
expect(uninitialized.isInitialized, isFalse);
expect(uninitialized.hasError, isFalse);
expect(uninitialized.aspectRatio, 1.0);
});
test('erroneous()', () {
const String errorMessage = 'foo';
final VideoPlayerValue error = VideoPlayerValue.erroneous(errorMessage);
expect(error.duration, equals(Duration.zero));
expect(error.position, equals(Duration.zero));
expect(error.caption, equals(Caption.none));
expect(error.captionOffset, equals(Duration.zero));
expect(error.buffered, isEmpty);
expect(error.isPlaying, isFalse);
expect(error.isLooping, isFalse);
expect(error.isBuffering, isFalse);
expect(error.volume, 1.0);
expect(error.playbackSpeed, 1.0);
expect(error.errorDescription, errorMessage);
expect(error.size, equals(Size.zero));
expect(error.isInitialized, isFalse);
expect(error.hasError, isTrue);
expect(error.aspectRatio, 1.0);
});
test('toString()', () {
const Duration duration = Duration(seconds: 5);
const Size size = Size(400, 300);
const Duration position = Duration(seconds: 1);
const Caption caption = Caption(
text: 'foo', number: 0, start: Duration.zero, end: Duration.zero);
const Duration captionOffset = Duration(milliseconds: 250);
final List<DurationRange> buffered = <DurationRange>[
DurationRange(Duration.zero, const Duration(seconds: 4))
];
const bool isInitialized = true;
const bool isPlaying = true;
const bool isLooping = true;
const bool isBuffering = true;
const double volume = 0.5;
const double playbackSpeed = 1.5;
final VideoPlayerValue value = VideoPlayerValue(
duration: duration,
size: size,
position: position,
caption: caption,
captionOffset: captionOffset,
buffered: buffered,
isInitialized: isInitialized,
isPlaying: isPlaying,
isLooping: isLooping,
isBuffering: isBuffering,
volume: volume,
playbackSpeed: playbackSpeed,
);
expect(
value.toString(),
'VideoPlayerValue(duration: 0:00:05.000000, '
'size: Size(400.0, 300.0), '
'position: 0:00:01.000000, '
'caption: Caption(number: 0, start: 0:00:00.000000, end: 0:00:00.000000, text: foo), '
'captionOffset: 0:00:00.250000, '
'buffered: [DurationRange(start: 0:00:00.000000, end: 0:00:04.000000)], '
'isInitialized: true, '
'isPlaying: true, '
'isLooping: true, '
'isBuffering: true, '
'volume: 0.5, '
'playbackSpeed: 1.5, '
'errorDescription: null)');
});
group('copyWith()', () {
test('exact copy', () {
final VideoPlayerValue original = VideoPlayerValue.uninitialized();
final VideoPlayerValue exactCopy = original.copyWith();
expect(exactCopy.toString(), original.toString());
});
test('errorDescription is not persisted when copy with null', () {
final VideoPlayerValue original = VideoPlayerValue.erroneous('error');
final VideoPlayerValue copy = original.copyWith(errorDescription: null);
expect(copy.errorDescription, null);
});
test('errorDescription is changed when copy with another error', () {
final VideoPlayerValue original = VideoPlayerValue.erroneous('error');
final VideoPlayerValue copy =
original.copyWith(errorDescription: 'new error');
expect(copy.errorDescription, 'new error');
});
test('errorDescription is changed when copy with error', () {
final VideoPlayerValue original = VideoPlayerValue.uninitialized();
final VideoPlayerValue copy =
original.copyWith(errorDescription: 'new error');
expect(copy.errorDescription, 'new error');
});
});
group('aspectRatio', () {
test('640x480 -> 4:3', () {
final VideoPlayerValue value = VideoPlayerValue(
isInitialized: true,
size: const Size(640, 480),
duration: const Duration(seconds: 1),
);
expect(value.aspectRatio, 4 / 3);
});
test('no size -> 1.0', () {
final VideoPlayerValue value = VideoPlayerValue(
isInitialized: true,
duration: const Duration(seconds: 1),
);
expect(value.aspectRatio, 1.0);
});
test('height = 0 -> 1.0', () {
final VideoPlayerValue value = VideoPlayerValue(
isInitialized: true,
size: const Size(640, 0),
duration: const Duration(seconds: 1),
);
expect(value.aspectRatio, 1.0);
});
test('width = 0 -> 1.0', () {
final VideoPlayerValue value = VideoPlayerValue(
isInitialized: true,
size: const Size(0, 480),
duration: const Duration(seconds: 1),
);
expect(value.aspectRatio, 1.0);
});
test('negative aspect ratio -> 1.0', () {
final VideoPlayerValue value = VideoPlayerValue(
isInitialized: true,
size: const Size(640, -480),
duration: const Duration(seconds: 1),
);
expect(value.aspectRatio, 1.0);
});
});
});
group('VideoPlayerOptions', () {
test('setMixWithOthers', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true));
await controller.initialize();
expect(controller.videoPlayerOptions!.mixWithOthers, true);
});
test('true allowBackgroundPlayback continues playback', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
videoPlayerOptions: VideoPlayerOptions(
allowBackgroundPlayback: true,
),
);
await controller.initialize();
await controller.play();
verifyPlayStateRespondsToLifecycle(
controller,
shouldPlayInBackground: true,
);
});
test('false allowBackgroundPlayback pauses playback', () async {
final VideoPlayerController controller = VideoPlayerController.network(
'https://127.0.0.1',
videoPlayerOptions: VideoPlayerOptions(),
);
await controller.initialize();
await controller.play();
verifyPlayStateRespondsToLifecycle(
controller,
shouldPlayInBackground: false,
);
});
});
test('VideoProgressColors', () {
const Color playedColor = Color.fromRGBO(0, 0, 255, 0.75);
const Color bufferedColor = Color.fromRGBO(0, 255, 0, 0.5);
const Color backgroundColor = Color.fromRGBO(255, 255, 0, 0.25);
const VideoProgressColors colors = VideoProgressColors(
playedColor: playedColor,
bufferedColor: bufferedColor,
backgroundColor: backgroundColor);
expect(colors.playedColor, playedColor);
expect(colors.bufferedColor, bufferedColor);
expect(colors.backgroundColor, backgroundColor);
});
}
class FakeVideoPlayerPlatform extends VideoPlayerPlatform {
Completer<bool> initialized = Completer<bool>();
List<String> calls = <String>[];
List<DataSource> dataSources = <DataSource>[];
final Map<int, StreamController<VideoEvent>> streams =
<int, StreamController<VideoEvent>>{};
bool forceInitError = false;
int nextTextureId = 0;
final Map<int, Duration> _positions = <int, Duration>{};
@override
Future<int?> create(DataSource dataSource) async {
calls.add('create');
final StreamController<VideoEvent> stream = StreamController<VideoEvent>();
streams[nextTextureId] = stream;
if (forceInitError) {
stream.addError(PlatformException(
code: 'VideoError', message: 'Video player had error XYZ'));
} else {
stream.add(VideoEvent(
eventType: VideoEventType.initialized,
size: const Size(100, 100),
duration: const Duration(seconds: 1)));
}
dataSources.add(dataSource);
return nextTextureId++;
}
@override
Future<void> dispose(int textureId) async {
calls.add('dispose');
}
@override
Future<void> init() async {
calls.add('init');
initialized.complete(true);
}
@override
Stream<VideoEvent> videoEventsFor(int textureId) {
return streams[textureId]!.stream;
}
@override
Future<void> pause(int textureId) async {
calls.add('pause');
}
@override
Future<void> play(int textureId) async {
calls.add('play');
}
@override
Future<Duration> getPosition(int textureId) async {
calls.add('position');
return _positions[textureId] ?? Duration.zero;
}
@override
Future<void> seekTo(int textureId, Duration position) async {
calls.add('seekTo');
_positions[textureId] = position;
}
@override
Future<void> setLooping(int textureId, bool looping) async {
calls.add('setLooping');
}
@override
Future<void> setVolume(int textureId, double volume) async {
calls.add('setVolume');
}
@override
Future<void> setPlaybackSpeed(int textureId, double speed) async {
calls.add('setPlaybackSpeed');
}
@override
Future<void> setMixWithOthers(bool mixWithOthers) async {
calls.add('setMixWithOthers');
}
@override
Widget buildView(int textureId) {
return Texture(textureId: textureId);
}
}
/// 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/video_player/video_player/test/video_player_test.dart/0 | {
"file_path": "plugins/packages/video_player/video_player/test/video_player_test.dart",
"repo_id": "plugins",
"token_count": 14894
} | 1,498 |
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">www.sample-videos.com</domain>
<domain includeSubdomains="true">184.72.239.149</domain>
</domain-config>
</network-security-config> | plugins/packages/video_player/video_player_android/example/android/app/src/main/res/xml/network_security_config.xml/0 | {
"file_path": "plugins/packages/video_player/video_player_android/example/android/app/src/main/res/xml/network_security_config.xml",
"repo_id": "plugins",
"token_count": 112
} | 1,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.