text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.4.2'
}
}
allprojects {
repositories {
// See https://github.com/flutter/flutter/wiki/Plugins-and-Packages-repository-structure#gradle-structure for more info.
def artifactRepoKey = 'ARTIFACT_HUB_REPOSITORY'
if (System.getenv().containsKey(artifactRepoKey)) {
println "Using artifact hub"
maven { url System.getenv(artifactRepoKey) }
}
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
tasks.register("clean", Delete) {
delete rootProject.buildDir
}
| packages/packages/video_player/video_player/example/android/build.gradle/0 | {
"file_path": "packages/packages/video_player/video_player/example/android/build.gradle",
"repo_id": "packages",
"token_count": 360
} | 1,300 |
// 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
/// An example of using the plugin, controlling lifecycle and playback of the
/// video.
library;
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
void main() {
runApp(
MaterialApp(
home: _App(),
),
);
}
class _App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
key: const ValueKey<String>('home_page'),
appBar: AppBar(
title: const Text('Video player example'),
actions: <Widget>[
IconButton(
key: const ValueKey<String>('push_tab'),
icon: const Icon(Icons.navigation),
onPressed: () {
Navigator.push<_PlayerVideoAndPopPage>(
context,
MaterialPageRoute<_PlayerVideoAndPopPage>(
builder: (BuildContext context) => _PlayerVideoAndPopPage(),
),
);
},
)
],
bottom: const TabBar(
isScrollable: true,
tabs: <Widget>[
Tab(
icon: Icon(Icons.cloud),
text: 'Remote',
),
Tab(icon: Icon(Icons.insert_drive_file), text: 'Asset'),
Tab(icon: Icon(Icons.list), text: 'List example'),
],
),
),
body: TabBarView(
children: <Widget>[
_BumbleBeeRemoteVideo(),
_ButterFlyAssetVideo(),
_ButterFlyAssetVideoInList(),
],
),
),
);
}
}
class _ButterFlyAssetVideoInList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
const _ExampleCard(title: 'Item a'),
const _ExampleCard(title: 'Item b'),
const _ExampleCard(title: 'Item c'),
const _ExampleCard(title: 'Item d'),
const _ExampleCard(title: 'Item e'),
const _ExampleCard(title: 'Item f'),
const _ExampleCard(title: 'Item g'),
Card(
child: Column(children: <Widget>[
Column(
children: <Widget>[
const ListTile(
leading: Icon(Icons.cake),
title: Text('Video video'),
),
Stack(
alignment: FractionalOffset.bottomRight +
const FractionalOffset(-0.1, -0.1),
children: <Widget>[
_ButterFlyAssetVideo(),
Image.asset('assets/flutter-mark-square-64.png'),
]),
],
),
])),
const _ExampleCard(title: 'Item h'),
const _ExampleCard(title: 'Item i'),
const _ExampleCard(title: 'Item j'),
const _ExampleCard(title: 'Item k'),
const _ExampleCard(title: 'Item l'),
],
);
}
}
/// A filler card to show the video in a list of scrolling contents.
class _ExampleCard extends StatelessWidget {
const _ExampleCard({required this.title});
final String title;
@override
Widget build(BuildContext context) {
return Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: const Icon(Icons.airline_seat_flat_angled),
title: Text(title),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: OverflowBar(
alignment: MainAxisAlignment.end,
spacing: 8.0,
children: <Widget>[
TextButton(
child: const Text('BUY TICKETS'),
onPressed: () {
/* ... */
},
),
TextButton(
child: const Text('SELL TICKETS'),
onPressed: () {
/* ... */
},
),
],
),
),
],
),
);
}
}
class _ButterFlyAssetVideo extends StatefulWidget {
@override
_ButterFlyAssetVideoState createState() => _ButterFlyAssetVideoState();
}
class _ButterFlyAssetVideoState extends State<_ButterFlyAssetVideo> {
late VideoPlayerController _controller;
@override
void initState() {
super.initState();
_controller = VideoPlayerController.asset('assets/Butterfly-209.mp4');
_controller.addListener(() {
setState(() {});
});
_controller.setLooping(true);
_controller.initialize().then((_) => setState(() {}));
_controller.play();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
padding: const EdgeInsets.only(top: 20.0),
),
const Text('With assets mp4'),
Container(
padding: const EdgeInsets.all(20),
child: AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
VideoPlayer(_controller),
_ControlsOverlay(controller: _controller),
VideoProgressIndicator(_controller, allowScrubbing: true),
],
),
),
),
],
),
);
}
}
class _BumbleBeeRemoteVideo extends StatefulWidget {
@override
_BumbleBeeRemoteVideoState createState() => _BumbleBeeRemoteVideoState();
}
class _BumbleBeeRemoteVideoState extends State<_BumbleBeeRemoteVideo> {
late VideoPlayerController _controller;
Future<ClosedCaptionFile> _loadCaptions() async {
final String fileContents = await DefaultAssetBundle.of(context)
.loadString('assets/bumble_bee_captions.vtt');
return WebVTTCaptionFile(
fileContents); // For vtt files, use WebVTTCaptionFile
}
@override
void initState() {
super.initState();
_controller = VideoPlayerController.networkUrl(
Uri.parse(
'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4'),
closedCaptionFile: _loadCaptions(),
videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
);
_controller.addListener(() {
setState(() {});
});
_controller.setLooping(true);
_controller.initialize();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: <Widget>[
Container(padding: const EdgeInsets.only(top: 20.0)),
const Text('With remote mp4'),
Container(
padding: const EdgeInsets.all(20),
child: AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
VideoPlayer(_controller),
ClosedCaption(text: _controller.value.caption.text),
_ControlsOverlay(controller: _controller),
VideoProgressIndicator(_controller, allowScrubbing: true),
],
),
),
),
],
),
);
}
}
class _ControlsOverlay extends StatelessWidget {
const _ControlsOverlay({required this.controller});
static const List<Duration> _exampleCaptionOffsets = <Duration>[
Duration(seconds: -10),
Duration(seconds: -3),
Duration(seconds: -1, milliseconds: -500),
Duration(milliseconds: -250),
Duration.zero,
Duration(milliseconds: 250),
Duration(seconds: 1, milliseconds: 500),
Duration(seconds: 3),
Duration(seconds: 10),
];
static const List<double> _examplePlaybackRates = <double>[
0.25,
0.5,
1.0,
1.5,
2.0,
3.0,
5.0,
10.0,
];
final VideoPlayerController controller;
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
AnimatedSwitcher(
duration: const Duration(milliseconds: 50),
reverseDuration: const Duration(milliseconds: 200),
child: controller.value.isPlaying
? const SizedBox.shrink()
: const ColoredBox(
color: Colors.black26,
child: Center(
child: Icon(
Icons.play_arrow,
color: Colors.white,
size: 100.0,
semanticLabel: 'Play',
),
),
),
),
GestureDetector(
onTap: () {
controller.value.isPlaying ? controller.pause() : controller.play();
},
),
Align(
alignment: Alignment.topLeft,
child: PopupMenuButton<Duration>(
initialValue: controller.value.captionOffset,
tooltip: 'Caption Offset',
onSelected: (Duration delay) {
controller.setCaptionOffset(delay);
},
itemBuilder: (BuildContext context) {
return <PopupMenuItem<Duration>>[
for (final Duration offsetDuration in _exampleCaptionOffsets)
PopupMenuItem<Duration>(
value: offsetDuration,
child: Text('${offsetDuration.inMilliseconds}ms'),
)
];
},
child: Padding(
padding: const EdgeInsets.symmetric(
// Using less vertical padding as the text is also longer
// horizontally, so it feels like it would need more spacing
// horizontally (matching the aspect ratio of the video).
vertical: 12,
horizontal: 16,
),
child: Text('${controller.value.captionOffset.inMilliseconds}ms'),
),
),
),
Align(
alignment: Alignment.topRight,
child: PopupMenuButton<double>(
initialValue: controller.value.playbackSpeed,
tooltip: 'Playback speed',
onSelected: (double speed) {
controller.setPlaybackSpeed(speed);
},
itemBuilder: (BuildContext context) {
return <PopupMenuItem<double>>[
for (final double speed in _examplePlaybackRates)
PopupMenuItem<double>(
value: speed,
child: Text('${speed}x'),
)
];
},
child: Padding(
padding: const EdgeInsets.symmetric(
// Using less vertical padding as the text is also longer
// horizontally, so it feels like it would need more spacing
// horizontally (matching the aspect ratio of the video).
vertical: 12,
horizontal: 16,
),
child: Text('${controller.value.playbackSpeed}x'),
),
),
),
],
);
}
}
class _PlayerVideoAndPopPage extends StatefulWidget {
@override
_PlayerVideoAndPopPageState createState() => _PlayerVideoAndPopPageState();
}
class _PlayerVideoAndPopPageState extends State<_PlayerVideoAndPopPage> {
late VideoPlayerController _videoPlayerController;
bool startedPlaying = false;
@override
void initState() {
super.initState();
_videoPlayerController =
VideoPlayerController.asset('assets/Butterfly-209.mp4');
_videoPlayerController.addListener(() {
if (startedPlaying && !_videoPlayerController.value.isPlaying) {
Navigator.pop(context);
}
});
}
@override
void dispose() {
_videoPlayerController.dispose();
super.dispose();
}
Future<bool> started() async {
await _videoPlayerController.initialize();
await _videoPlayerController.play();
startedPlaying = true;
return true;
}
@override
Widget build(BuildContext context) {
return Material(
child: Center(
child: FutureBuilder<bool>(
future: started(),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
if (snapshot.data ?? false) {
return AspectRatio(
aspectRatio: _videoPlayerController.value.aspectRatio,
child: VideoPlayer(_videoPlayerController),
);
} else {
return const Text('waiting for video to load');
}
},
),
),
);
}
}
| packages/packages/video_player/video_player/example/lib/main.dart/0 | {
"file_path": "packages/packages/video_player/video_player/example/lib/main.dart",
"repo_id": "packages",
"token_count": 6181
} | 1,301 |
// 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:convert';
import 'closed_caption_file.dart';
/// Represents a [ClosedCaptionFile], parsed from the SubRip file format.
/// See: https://en.wikipedia.org/wiki/SubRip
class SubRipCaptionFile extends ClosedCaptionFile {
/// Parses a string into a [ClosedCaptionFile], assuming [fileContents] is in
/// the SubRip file format.
/// * See: https://en.wikipedia.org/wiki/SubRip
SubRipCaptionFile(this.fileContents)
: _captions = _parseCaptionsFromSubRipString(fileContents);
/// The entire body of the SubRip file.
// TODO(cyanglaz): Remove this public member as it doesn't seem need to exist.
// https://github.com/flutter/flutter/issues/90471
final String fileContents;
@override
List<Caption> get captions => _captions;
final List<Caption> _captions;
}
List<Caption> _parseCaptionsFromSubRipString(String file) {
final List<Caption> captions = <Caption>[];
for (final List<String> captionLines in _readSubRipFile(file)) {
if (captionLines.length < 3) {
break;
}
final int captionNumber = int.parse(captionLines[0]);
final _CaptionRange captionRange =
_CaptionRange.fromSubRipString(captionLines[1]);
final String text = captionLines.sublist(2).join('\n');
final Caption newCaption = Caption(
number: captionNumber,
start: captionRange.start,
end: captionRange.end,
text: text,
);
if (newCaption.start != newCaption.end) {
captions.add(newCaption);
}
}
return captions;
}
class _CaptionRange {
_CaptionRange(this.start, this.end);
final Duration start;
final Duration end;
// Assumes format from an SubRip file.
// For example:
// 00:01:54,724 --> 00:01:56,760
static _CaptionRange fromSubRipString(String line) {
final RegExp format =
RegExp(_subRipTimeStamp + _subRipArrow + _subRipTimeStamp);
if (!format.hasMatch(line)) {
return _CaptionRange(Duration.zero, Duration.zero);
}
final List<String> times = line.split(_subRipArrow);
final Duration start = _parseSubRipTimestamp(times[0]);
final Duration end = _parseSubRipTimestamp(times[1]);
return _CaptionRange(start, end);
}
}
// Parses a time stamp in an SubRip file into a Duration.
// For example:
//
// _parseSubRipTimestamp('00:01:59,084')
// returns
// Duration(hours: 0, minutes: 1, seconds: 59, milliseconds: 084)
Duration _parseSubRipTimestamp(String timestampString) {
if (!RegExp(_subRipTimeStamp).hasMatch(timestampString)) {
return Duration.zero;
}
final List<String> commaSections = timestampString.split(',');
final List<String> hoursMinutesSeconds = commaSections[0].split(':');
final int hours = int.parse(hoursMinutesSeconds[0]);
final int minutes = int.parse(hoursMinutesSeconds[1]);
final int seconds = int.parse(hoursMinutesSeconds[2]);
final int milliseconds = int.parse(commaSections[1]);
return Duration(
hours: hours,
minutes: minutes,
seconds: seconds,
milliseconds: milliseconds,
);
}
// Reads on SubRip file and splits it into Lists of strings where each list is one
// caption.
List<List<String>> _readSubRipFile(String file) {
final List<String> lines = LineSplitter.split(file).toList();
final List<List<String>> captionStrings = <List<String>>[];
List<String> currentCaption = <String>[];
int lineIndex = 0;
for (final String line in lines) {
final bool isLineBlank = line.trim().isEmpty;
if (!isLineBlank) {
currentCaption.add(line);
}
if (isLineBlank || lineIndex == lines.length - 1) {
captionStrings.add(currentCaption);
currentCaption = <String>[];
}
lineIndex += 1;
}
return captionStrings;
}
const String _subRipTimeStamp = r'\d\d:\d\d:\d\d,\d\d\d';
const String _subRipArrow = r' --> ';
| packages/packages/video_player/video_player/lib/src/sub_rip.dart/0 | {
"file_path": "packages/packages/video_player/video_player/lib/src/sub_rip.dart",
"repo_id": "packages",
"token_count": 1406
} | 1,302 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.videoplayer">
</manifest>
| packages/packages/video_player/video_player_android/android/src/main/AndroidManifest.xml/0 | {
"file_path": "packages/packages/video_player/video_player_android/android/src/main/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 47
} | 1,303 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.videoplayerexample">
<application
android:icon="@mipmap/ic_launcher"
android:label="video_player_example"
android:networkSecurityConfig="@xml/network_security_config">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:hardwareAccelerated="true"
android:name="io.flutter.embedding.android.FlutterActivity"
android:theme="@style/LaunchTheme"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data android:name="flutterEmbedding" android:value="2"/>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
| packages/packages/video_player/video_player_android/example/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "packages/packages/video_player/video_player_android/example/android/app/src/main/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 339
} | 1,304 |
// 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:typed_data';
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_player_android/video_player_android.dart';
// TODO(stuartmorgan): Remove the use of MiniController in tests, as that is
// testing test code; tests should instead be written directly against the
// platform interface. (These tests were copied from the app-facing package
// during federation and minimally modified, which is why they currently use the
// controller.)
import 'package:video_player_example/mini_controller.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
const Duration _playDuration = Duration(seconds: 1);
const String _videoAssetKey = 'assets/Butterfly-209.mp4';
// Returns the URL to load an asset from this example app as a network source.
//
// TODO(stuartmorgan): Convert this to a local `HttpServer` that vends the
// assets directly, https://github.com/flutter/flutter/issues/95420
String getUrlForAssetAsNetworkSource(String assetKey) {
return 'https://github.com/flutter/packages/blob/'
// This hash can be rolled forward to pick up newly-added assets.
'2e1673307ff7454aff40b47024eaed49a9e77e81'
'/packages/video_player/video_player/example/'
'$assetKey'
'?raw=true';
}
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
late MiniController controller;
tearDown(() async => controller.dispose());
group('asset videos', () {
setUp(() {
controller = MiniController.asset(_videoAssetKey);
});
testWidgets('registers expected implementation',
(WidgetTester tester) async {
AndroidVideoPlayer.registerWith();
expect(VideoPlayerPlatform.instance, isA<AndroidVideoPlayer>());
});
testWidgets('can be initialized', (WidgetTester tester) async {
await controller.initialize();
expect(controller.value.isInitialized, true);
expect(await controller.position, Duration.zero);
expect(controller.value.duration,
const Duration(seconds: 7, milliseconds: 540));
});
testWidgets('can be played', (WidgetTester tester) async {
await controller.initialize();
await controller.play();
await tester.pumpAndSettle(_playDuration);
expect(await controller.position, greaterThan(Duration.zero));
});
testWidgets('can seek', (WidgetTester tester) async {
await controller.initialize();
await controller.seekTo(const Duration(seconds: 3));
expect(await controller.position, const Duration(seconds: 3));
});
testWidgets('can be paused', (WidgetTester tester) async {
await controller.initialize();
// Play for a second, then pause, and then wait a second.
await controller.play();
await tester.pumpAndSettle(_playDuration);
await controller.pause();
await tester.pumpAndSettle(_playDuration);
final Duration pausedPosition = (await controller.position)!;
await tester.pumpAndSettle(_playDuration);
// Verify that we stopped playing after the pause.
expect(await controller.position, pausedPosition);
});
});
group('file-based videos', () {
setUp(() async {
// Load the data from the asset.
final String tempDir = (await getTemporaryDirectory()).path;
final ByteData bytes = await rootBundle.load(_videoAssetKey);
// Write it to a file to use as a source.
final String filename = _videoAssetKey.split('/').last;
final File file = File('$tempDir/$filename');
await file.writeAsBytes(bytes.buffer.asInt8List());
controller = MiniController.file(file);
});
testWidgets('test video player using static file() method as constructor',
(WidgetTester tester) async {
await controller.initialize();
await controller.play();
await tester.pumpAndSettle(_playDuration);
expect(await controller.position, greaterThan(Duration.zero));
});
});
group('network videos', () {
setUp(() {
final String videoUrl = getUrlForAssetAsNetworkSource(_videoAssetKey);
controller = MiniController.network(videoUrl);
});
testWidgets('reports buffering status', (WidgetTester tester) async {
await controller.initialize();
final Completer<void> started = Completer<void>();
final Completer<void> ended = Completer<void>();
controller.addListener(() {
if (!started.isCompleted && controller.value.isBuffering) {
started.complete();
}
if (started.isCompleted &&
!controller.value.isBuffering &&
!ended.isCompleted) {
ended.complete();
}
});
await controller.play();
await controller.seekTo(const Duration(seconds: 5));
await tester.pumpAndSettle(_playDuration);
await controller.pause();
expect(await controller.position, greaterThan(Duration.zero));
await expectLater(started.future, completes);
await expectLater(ended.future, completes);
});
testWidgets('live stream duration != 0', (WidgetTester tester) async {
final MiniController livestreamController = MiniController.network(
'https://flutter.github.io/assets-for-api-docs/assets/videos/hls/bee.m3u8',
);
await livestreamController.initialize();
expect(livestreamController.value.isInitialized, true);
// Live streams should have either a positive duration or C.TIME_UNSET if the duration is unknown
// See https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/Player.html#getDuration--
expect(livestreamController.value.duration,
(Duration duration) => duration != Duration.zero);
});
});
}
| packages/packages/video_player/video_player_android/example/integration_test/video_player_test.dart/0 | {
"file_path": "packages/packages/video_player/video_player_android/example/integration_test/video_player_test.dart",
"repo_id": "packages",
"token_count": 2061
} | 1,305 |
{
"images" : [
{
"filename" : "[email protected]",
"idiom" : "iphone",
"scale" : "2x",
"size" : "20x20"
},
{
"filename" : "[email protected]",
"idiom" : "iphone",
"scale" : "3x",
"size" : "20x20"
},
{
"filename" : "[email protected]",
"idiom" : "iphone",
"scale" : "1x",
"size" : "29x29"
},
{
"filename" : "[email protected]",
"idiom" : "iphone",
"scale" : "2x",
"size" : "29x29"
},
{
"filename" : "[email protected]",
"idiom" : "iphone",
"scale" : "3x",
"size" : "29x29"
},
{
"filename" : "[email protected]",
"idiom" : "iphone",
"scale" : "2x",
"size" : "40x40"
},
{
"filename" : "[email protected]",
"idiom" : "iphone",
"scale" : "3x",
"size" : "40x40"
},
{
"filename" : "[email protected]",
"idiom" : "iphone",
"scale" : "2x",
"size" : "60x60"
},
{
"filename" : "[email protected]",
"idiom" : "iphone",
"scale" : "3x",
"size" : "60x60"
},
{
"filename" : "[email protected]",
"idiom" : "ipad",
"scale" : "1x",
"size" : "20x20"
},
{
"filename" : "[email protected]",
"idiom" : "ipad",
"scale" : "2x",
"size" : "20x20"
},
{
"filename" : "[email protected]",
"idiom" : "ipad",
"scale" : "1x",
"size" : "29x29"
},
{
"filename" : "[email protected]",
"idiom" : "ipad",
"scale" : "2x",
"size" : "29x29"
},
{
"filename" : "[email protected]",
"idiom" : "ipad",
"scale" : "1x",
"size" : "40x40"
},
{
"filename" : "[email protected]",
"idiom" : "ipad",
"scale" : "2x",
"size" : "40x40"
},
{
"filename" : "[email protected]",
"idiom" : "ipad",
"scale" : "1x",
"size" : "76x76"
},
{
"filename" : "[email protected]",
"idiom" : "ipad",
"scale" : "2x",
"size" : "76x76"
},
{
"filename" : "[email protected]",
"idiom" : "ipad",
"scale" : "2x",
"size" : "83.5x83.5"
},
{
"idiom" : "ios-marketing",
"scale" : "1x",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
| packages/packages/video_player/video_player_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json/0 | {
"file_path": "packages/packages/video_player/video_player_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json",
"repo_id": "packages",
"token_count": 1513
} | 1,306 |
// 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:video_player_avfoundation/src/messages.g.dart';
import 'package:video_player_avfoundation/video_player_avfoundation.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
import 'test_api.g.dart';
class _ApiLogger implements TestHostVideoPlayerApi {
final List<String> log = <String>[];
TextureMessage? textureMessage;
CreateMessage? createMessage;
PositionMessage? positionMessage;
LoopingMessage? loopingMessage;
VolumeMessage? volumeMessage;
PlaybackSpeedMessage? playbackSpeedMessage;
MixWithOthersMessage? mixWithOthersMessage;
@override
TextureMessage create(CreateMessage arg) {
log.add('create');
createMessage = arg;
return TextureMessage(textureId: 3);
}
@override
void dispose(TextureMessage arg) {
log.add('dispose');
textureMessage = arg;
}
@override
void initialize() {
log.add('init');
}
@override
void pause(TextureMessage arg) {
log.add('pause');
textureMessage = arg;
}
@override
void play(TextureMessage arg) {
log.add('play');
textureMessage = arg;
}
@override
void setMixWithOthers(MixWithOthersMessage arg) {
log.add('setMixWithOthers');
mixWithOthersMessage = arg;
}
@override
PositionMessage position(TextureMessage arg) {
log.add('position');
textureMessage = arg;
return PositionMessage(textureId: arg.textureId, position: 234);
}
@override
Future<void> seekTo(PositionMessage arg) async {
log.add('seekTo');
positionMessage = arg;
}
@override
void setLooping(LoopingMessage arg) {
log.add('setLooping');
loopingMessage = arg;
}
@override
void setVolume(VolumeMessage arg) {
log.add('setVolume');
volumeMessage = arg;
}
@override
void setPlaybackSpeed(PlaybackSpeedMessage arg) {
log.add('setPlaybackSpeed');
playbackSpeedMessage = arg;
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('registration', () async {
AVFoundationVideoPlayer.registerWith();
expect(VideoPlayerPlatform.instance, isA<AVFoundationVideoPlayer>());
});
group('$AVFoundationVideoPlayer', () {
final AVFoundationVideoPlayer player = AVFoundationVideoPlayer();
late _ApiLogger log;
setUp(() {
log = _ApiLogger();
TestHostVideoPlayerApi.setup(log);
});
test('init', () async {
await player.init();
expect(
log.log.last,
'init',
);
});
test('dispose', () async {
await player.dispose(1);
expect(log.log.last, 'dispose');
expect(log.textureMessage?.textureId, 1);
});
test('create with asset', () async {
final int? textureId = await player.create(DataSource(
sourceType: DataSourceType.asset,
asset: 'someAsset',
package: 'somePackage',
));
expect(log.log.last, 'create');
expect(log.createMessage?.asset, 'someAsset');
expect(log.createMessage?.packageName, 'somePackage');
expect(textureId, 3);
});
test('create with incorrect asset throws exception', () async {
try {
await player.create(DataSource(
sourceType: DataSourceType.asset,
asset: '/path/to/incorrect_asset',
));
fail('should throw PlatformException');
} catch (e) {
expect(e, isException);
}
});
test('create with network', () async {
final int? textureId = await player.create(DataSource(
sourceType: DataSourceType.network,
uri: 'someUri',
formatHint: VideoFormat.dash,
));
expect(log.log.last, 'create');
expect(log.createMessage?.asset, null);
expect(log.createMessage?.uri, 'someUri');
expect(log.createMessage?.packageName, null);
expect(log.createMessage?.formatHint, 'dash');
expect(log.createMessage?.httpHeaders, <String, String>{});
expect(textureId, 3);
});
test('create with network (some headers)', () async {
final int? textureId = await player.create(DataSource(
sourceType: DataSourceType.network,
uri: 'someUri',
httpHeaders: <String, String>{'Authorization': 'Bearer token'},
));
expect(log.log.last, 'create');
expect(log.createMessage?.asset, null);
expect(log.createMessage?.uri, 'someUri');
expect(log.createMessage?.packageName, null);
expect(log.createMessage?.formatHint, null);
expect(log.createMessage?.httpHeaders,
<String, String>{'Authorization': 'Bearer token'});
expect(textureId, 3);
});
test('create with file', () async {
final int? textureId = await player.create(DataSource(
sourceType: DataSourceType.file,
uri: 'someUri',
));
expect(log.log.last, 'create');
expect(log.createMessage?.uri, 'someUri');
expect(textureId, 3);
});
test('setLooping', () async {
await player.setLooping(1, true);
expect(log.log.last, 'setLooping');
expect(log.loopingMessage?.textureId, 1);
expect(log.loopingMessage?.isLooping, true);
});
test('play', () async {
await player.play(1);
expect(log.log.last, 'play');
expect(log.textureMessage?.textureId, 1);
});
test('pause', () async {
await player.pause(1);
expect(log.log.last, 'pause');
expect(log.textureMessage?.textureId, 1);
});
test('setMixWithOthers', () async {
await player.setMixWithOthers(true);
expect(log.log.last, 'setMixWithOthers');
expect(log.mixWithOthersMessage?.mixWithOthers, true);
await player.setMixWithOthers(false);
expect(log.log.last, 'setMixWithOthers');
expect(log.mixWithOthersMessage?.mixWithOthers, false);
});
test('setVolume', () async {
await player.setVolume(1, 0.7);
expect(log.log.last, 'setVolume');
expect(log.volumeMessage?.textureId, 1);
expect(log.volumeMessage?.volume, 0.7);
});
test('setPlaybackSpeed', () async {
await player.setPlaybackSpeed(1, 1.5);
expect(log.log.last, 'setPlaybackSpeed');
expect(log.playbackSpeedMessage?.textureId, 1);
expect(log.playbackSpeedMessage?.speed, 1.5);
});
test('seekTo', () async {
await player.seekTo(1, const Duration(milliseconds: 12345));
expect(log.log.last, 'seekTo');
expect(log.positionMessage?.textureId, 1);
expect(log.positionMessage?.position, 12345);
});
test('getPosition', () async {
final Duration position = await player.getPosition(1);
expect(log.log.last, 'position');
expect(log.textureMessage?.textureId, 1);
expect(position, const Duration(milliseconds: 234));
});
test('videoEventsFor', () async {
const String mockChannel = 'flutter.io/videoPlayer/videoEvents123';
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMessageHandler(
mockChannel,
(ByteData? message) async {
final MethodCall methodCall =
const StandardMethodCodec().decodeMethodCall(message);
if (methodCall.method == 'listen') {
await TestDefaultBinaryMessengerBinding
.instance.defaultBinaryMessenger
.handlePlatformMessage(
mockChannel,
const StandardMethodCodec()
.encodeSuccessEnvelope(<String, dynamic>{
'event': 'initialized',
'duration': 98765,
'width': 1920,
'height': 1080,
}),
(ByteData? data) {});
await TestDefaultBinaryMessengerBinding
.instance.defaultBinaryMessenger
.handlePlatformMessage(
mockChannel,
const StandardMethodCodec()
.encodeSuccessEnvelope(<String, dynamic>{
'event': 'completed',
}),
(ByteData? data) {});
await TestDefaultBinaryMessengerBinding
.instance.defaultBinaryMessenger
.handlePlatformMessage(
mockChannel,
const StandardMethodCodec()
.encodeSuccessEnvelope(<String, dynamic>{
'event': 'bufferingUpdate',
'values': <List<dynamic>>[
<int>[0, 1234],
<int>[1235, 4000],
],
}),
(ByteData? data) {});
await TestDefaultBinaryMessengerBinding
.instance.defaultBinaryMessenger
.handlePlatformMessage(
mockChannel,
const StandardMethodCodec()
.encodeSuccessEnvelope(<String, dynamic>{
'event': 'bufferingStart',
}),
(ByteData? data) {});
await TestDefaultBinaryMessengerBinding
.instance.defaultBinaryMessenger
.handlePlatformMessage(
mockChannel,
const StandardMethodCodec()
.encodeSuccessEnvelope(<String, dynamic>{
'event': 'bufferingEnd',
}),
(ByteData? data) {});
await TestDefaultBinaryMessengerBinding
.instance.defaultBinaryMessenger
.handlePlatformMessage(
mockChannel,
const StandardMethodCodec()
.encodeSuccessEnvelope(<String, dynamic>{
'event': 'isPlayingStateUpdate',
'isPlaying': true,
}),
(ByteData? data) {});
await TestDefaultBinaryMessengerBinding
.instance.defaultBinaryMessenger
.handlePlatformMessage(
mockChannel,
const StandardMethodCodec()
.encodeSuccessEnvelope(<String, dynamic>{
'event': 'isPlayingStateUpdate',
'isPlaying': false,
}),
(ByteData? data) {});
return const StandardMethodCodec().encodeSuccessEnvelope(null);
} else if (methodCall.method == 'cancel') {
return const StandardMethodCodec().encodeSuccessEnvelope(null);
} else {
fail('Expected listen or cancel');
}
},
);
expect(
player.videoEventsFor(123),
emitsInOrder(<dynamic>[
VideoEvent(
eventType: VideoEventType.initialized,
duration: const Duration(milliseconds: 98765),
size: const Size(1920, 1080),
),
VideoEvent(eventType: VideoEventType.completed),
VideoEvent(
eventType: VideoEventType.bufferingUpdate,
buffered: <DurationRange>[
DurationRange(
Duration.zero,
const Duration(milliseconds: 1234),
),
DurationRange(
const Duration(milliseconds: 1235),
const Duration(milliseconds: 4000),
),
]),
VideoEvent(eventType: VideoEventType.bufferingStart),
VideoEvent(eventType: VideoEventType.bufferingEnd),
VideoEvent(
eventType: VideoEventType.isPlayingStateUpdate,
isPlaying: true,
),
VideoEvent(
eventType: VideoEventType.isPlayingStateUpdate,
isPlaying: false,
),
]));
});
});
}
| packages/packages/video_player/video_player_avfoundation/test/avfoundation_video_player_test.dart/0 | {
"file_path": "packages/packages/video_player/video_player_avfoundation/test/avfoundation_video_player_test.dart",
"repo_id": "packages",
"token_count": 5539
} | 1,307 |
name: test_app
description: An example app for web benchmarks testing.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ^3.1.0
dependencies:
flutter:
sdk: flutter
flutter_test:
sdk: flutter
web_benchmarks:
path: ../../
flutter:
uses-material-design: true
| packages/packages/web_benchmarks/testing/test_app/pubspec.yaml/0 | {
"file_path": "packages/packages/web_benchmarks/testing/test_app/pubspec.yaml",
"repo_id": "packages",
"token_count": 118
} | 1,308 |
include ':app'
def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
}
plugins.each { name, path ->
def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
include ":$name"
project(":$name").projectDir = pluginDirectory
}
// See https://github.com/flutter/flutter/wiki/Plugins-and-Packages-repository-structure#gradle-structure for more info.
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "gradle.plugin.com.google.cloud.artifactregistry:artifactregistry-gradle-plugin:2.2.1"
}
}
apply plugin: "com.google.cloud.artifactregistry.gradle-plugin"
| packages/packages/webview_flutter/webview_flutter/example/android/settings.gradle/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter/example/android/settings.gradle",
"repo_id": "packages",
"token_count": 309
} | 1,309 |
// 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.
/// Re-export the classes from the webview_flutter_platform_interface through
/// the `platform_interface.dart` file so we don't accidentally break any
/// non-endorsed existing implementations of the interface.
library;
export 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart'
show
AutoMediaPlaybackPolicy,
CreationParams,
JavascriptChannel,
JavascriptChannelRegistry,
JavascriptMessage,
JavascriptMessageHandler,
JavascriptMode,
WebResourceError,
WebResourceErrorType,
WebSetting,
WebSettings,
WebViewCookie,
WebViewPlatform,
WebViewPlatformCallbacksHandler,
WebViewPlatformController,
WebViewPlatformCreatedCallback,
WebViewRequest,
WebViewRequestMethod;
| packages/packages/webview_flutter/webview_flutter/lib/src/legacy/platform_interface.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter/lib/src/legacy/platform_interface.dart",
"repo_id": "packages",
"token_count": 358
} | 1,310 |
// Mocks generated by Mockito 5.4.4 from annotations
// in webview_flutter/test/webview_cookie_manager_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i4;
import 'package:mockito/mockito.dart' as _i1;
import 'package:webview_flutter_platform_interface/src/platform_webview_cookie_manager.dart'
as _i3;
import 'package:webview_flutter_platform_interface/src/types/types.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: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakePlatformWebViewCookieManagerCreationParams_0 extends _i1.SmartFake
implements _i2.PlatformWebViewCookieManagerCreationParams {
_FakePlatformWebViewCookieManagerCreationParams_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [PlatformWebViewCookieManager].
///
/// See the documentation for Mockito's code generation for more information.
class MockPlatformWebViewCookieManager extends _i1.Mock
implements _i3.PlatformWebViewCookieManager {
MockPlatformWebViewCookieManager() {
_i1.throwOnMissingStub(this);
}
@override
_i2.PlatformWebViewCookieManagerCreationParams get params =>
(super.noSuchMethod(
Invocation.getter(#params),
returnValue: _FakePlatformWebViewCookieManagerCreationParams_0(
this,
Invocation.getter(#params),
),
) as _i2.PlatformWebViewCookieManagerCreationParams);
@override
_i4.Future<bool> clearCookies() => (super.noSuchMethod(
Invocation.method(
#clearCookies,
[],
),
returnValue: _i4.Future<bool>.value(false),
) as _i4.Future<bool>);
@override
_i4.Future<void> setCookie(_i2.WebViewCookie? cookie) => (super.noSuchMethod(
Invocation.method(
#setCookie,
[cookie],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
}
| packages/packages/webview_flutter/webview_flutter/test/webview_cookie_manager_test.mocks.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter/test/webview_cookie_manager_test.mocks.dart",
"repo_id": "packages",
"token_count": 980
} | 1,311 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import android.webkit.DownloadListener;
import androidx.annotation.NonNull;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.DownloadListenerHostApi;
/**
* Host api implementation for {@link DownloadListener}.
*
* <p>Handles creating {@link DownloadListener}s that intercommunicate with a paired Dart object.
*/
public class DownloadListenerHostApiImpl implements DownloadListenerHostApi {
private final InstanceManager instanceManager;
private final DownloadListenerCreator downloadListenerCreator;
private final DownloadListenerFlutterApiImpl flutterApi;
/**
* Implementation of {@link DownloadListener} that passes arguments of callback methods to Dart.
*/
public static class DownloadListenerImpl implements DownloadListener {
private final DownloadListenerFlutterApiImpl flutterApi;
/**
* Creates a {@link DownloadListenerImpl} that passes arguments of callbacks methods to Dart.
*
* @param flutterApi handles sending messages to Dart
*/
public DownloadListenerImpl(@NonNull DownloadListenerFlutterApiImpl flutterApi) {
this.flutterApi = flutterApi;
}
@Override
public void onDownloadStart(
@NonNull String url,
@NonNull String userAgent,
@NonNull String contentDisposition,
@NonNull String mimetype,
long contentLength) {
flutterApi.onDownloadStart(
this, url, userAgent, contentDisposition, mimetype, contentLength, reply -> {});
}
}
/** Handles creating {@link DownloadListenerImpl}s for a {@link DownloadListenerHostApiImpl}. */
public static class DownloadListenerCreator {
/**
* Creates a {@link DownloadListenerImpl}.
*
* @param flutterApi handles sending messages to Dart
* @return the created {@link DownloadListenerImpl}
*/
@NonNull
public DownloadListenerImpl createDownloadListener(
@NonNull DownloadListenerFlutterApiImpl flutterApi) {
return new DownloadListenerImpl(flutterApi);
}
}
/**
* Creates a host API that handles creating {@link DownloadListener}s.
*
* @param instanceManager maintains instances stored to communicate with Dart objects
* @param downloadListenerCreator handles creating {@link DownloadListenerImpl}s
* @param flutterApi handles sending messages to Dart
*/
public DownloadListenerHostApiImpl(
@NonNull InstanceManager instanceManager,
@NonNull DownloadListenerCreator downloadListenerCreator,
@NonNull DownloadListenerFlutterApiImpl flutterApi) {
this.instanceManager = instanceManager;
this.downloadListenerCreator = downloadListenerCreator;
this.flutterApi = flutterApi;
}
@Override
public void create(@NonNull Long instanceId) {
final DownloadListener downloadListener =
downloadListenerCreator.createDownloadListener(flutterApi);
instanceManager.addDartCreatedInstance(downloadListener, instanceId);
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/DownloadListenerHostApiImpl.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/DownloadListenerHostApiImpl.java",
"repo_id": "packages",
"token_count": 953
} | 1,312 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import android.os.Build;
import android.webkit.PermissionRequest;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.PermissionRequestHostApi;
import java.util.List;
import java.util.Objects;
/**
* Host API implementation for `PermissionRequest`.
*
* <p>This class may handle instantiating and adding native object instances that are attached to a
* Dart instance or handle method calls on the associated native class or an instance of the class.
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class PermissionRequestHostApiImpl implements PermissionRequestHostApi {
// To ease adding additional methods, this value is added prematurely.
@SuppressWarnings({"unused", "FieldCanBeLocal"})
private final BinaryMessenger binaryMessenger;
private final InstanceManager instanceManager;
/**
* Constructs a {@link PermissionRequestHostApiImpl}.
*
* @param binaryMessenger used to communicate with Dart over asynchronous messages
* @param instanceManager maintains instances stored to communicate with attached Dart objects
*/
public PermissionRequestHostApiImpl(
@NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) {
this.binaryMessenger = binaryMessenger;
this.instanceManager = instanceManager;
}
@Override
public void grant(@NonNull Long instanceId, @NonNull List<String> resources) {
getPermissionRequestInstance(instanceId).grant(resources.toArray(new String[0]));
}
@Override
public void deny(@NonNull Long instanceId) {
getPermissionRequestInstance(instanceId).deny();
}
private PermissionRequest getPermissionRequestInstance(@NonNull Long identifier) {
return Objects.requireNonNull(instanceManager.getInstance(identifier));
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/PermissionRequestHostApiImpl.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/PermissionRequestHostApiImpl.java",
"repo_id": "packages",
"token_count": 579
} | 1,313 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import static org.junit.Assert.assertEquals;
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 static org.mockito.Mockito.when;
import android.webkit.WebChromeClient.FileChooserParams;
import io.flutter.plugin.common.BinaryMessenger;
import java.util.Arrays;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class FileChooserParamsTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public FileChooserParams mockFileChooserParams;
@Mock public BinaryMessenger mockBinaryMessenger;
InstanceManager instanceManager;
@Before
public void setUp() {
instanceManager = InstanceManager.create(identifier -> {});
}
@After
public void tearDown() {
instanceManager.stopFinalizationListener();
}
@Test
public void flutterApiCreate() {
final FileChooserParamsFlutterApiImpl spyFlutterApi =
spy(new FileChooserParamsFlutterApiImpl(mockBinaryMessenger, instanceManager));
when(mockFileChooserParams.isCaptureEnabled()).thenReturn(true);
when(mockFileChooserParams.getAcceptTypes()).thenReturn(new String[] {"my", "list"});
when(mockFileChooserParams.getMode()).thenReturn(FileChooserParams.MODE_OPEN_MULTIPLE);
when(mockFileChooserParams.getFilenameHint()).thenReturn("filenameHint");
spyFlutterApi.create(mockFileChooserParams, reply -> {});
final long identifier =
Objects.requireNonNull(
instanceManager.getIdentifierForStrongReference(mockFileChooserParams));
final ArgumentCaptor<GeneratedAndroidWebView.FileChooserMode> modeCaptor =
ArgumentCaptor.forClass(GeneratedAndroidWebView.FileChooserMode.class);
verify(spyFlutterApi)
.create(
eq(identifier),
eq(true),
eq(Arrays.asList("my", "list")),
modeCaptor.capture(),
eq("filenameHint"),
any());
assertEquals(modeCaptor.getValue(), GeneratedAndroidWebView.FileChooserMode.OPEN_MULTIPLE);
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/FileChooserParamsTest.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/FileChooserParamsTest.java",
"repo_id": "packages",
"token_count": 916
} | 1,314 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
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.content.Context;
import android.os.Build;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterView;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebViewFlutterApi;
import io.flutter.plugins.webviewflutter.WebViewHostApiImpl.WebViewPlatformView;
import java.util.HashMap;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class WebViewTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public WebViewPlatformView mockWebView;
@Mock WebViewHostApiImpl.WebViewProxy mockWebViewProxy;
@Mock Context mockContext;
@Mock BinaryMessenger mockBinaryMessenger;
InstanceManager testInstanceManager;
WebViewHostApiImpl testHostApiImpl;
@Before
public void setUp() {
testInstanceManager = InstanceManager.create(identifier -> {});
when(mockWebViewProxy.createWebView(mockContext, mockBinaryMessenger, testInstanceManager))
.thenReturn(mockWebView);
testHostApiImpl =
new WebViewHostApiImpl(
testInstanceManager, mockBinaryMessenger, mockWebViewProxy, mockContext);
testHostApiImpl.create(0L);
}
@After
public void tearDown() {
testInstanceManager.stopFinalizationListener();
}
@Test
public void loadData() {
testHostApiImpl.loadData(
0L, "VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==", "text/plain", "base64");
verify(mockWebView)
.loadData("VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==", "text/plain", "base64");
}
@Test
public void loadDataWithNullValues() {
testHostApiImpl.loadData(0L, "VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==", null, null);
verify(mockWebView).loadData("VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==", null, null);
}
@Test
public void loadDataWithBaseUrl() {
testHostApiImpl.loadDataWithBaseUrl(
0L,
"https://flutter.dev",
"VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==",
"text/plain",
"base64",
"about:blank");
verify(mockWebView)
.loadDataWithBaseURL(
"https://flutter.dev",
"VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==",
"text/plain",
"base64",
"about:blank");
}
@Test
public void loadDataWithBaseUrlAndNullValues() {
testHostApiImpl.loadDataWithBaseUrl(
0L, null, "VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==", null, null, null);
verify(mockWebView)
.loadDataWithBaseURL(null, "VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==", null, null, null);
}
@Test
public void loadUrl() {
testHostApiImpl.loadUrl(0L, "https://www.google.com", new HashMap<>());
verify(mockWebView).loadUrl("https://www.google.com", new HashMap<>());
}
@Test
public void postUrl() {
testHostApiImpl.postUrl(0L, "https://www.google.com", new byte[] {0x01, 0x02});
verify(mockWebView).postUrl("https://www.google.com", new byte[] {0x01, 0x02});
}
@Test
public void getUrl() {
when(mockWebView.getUrl()).thenReturn("https://www.google.com");
assertEquals(testHostApiImpl.getUrl(0L), "https://www.google.com");
}
@Test
public void canGoBack() {
when(mockWebView.canGoBack()).thenReturn(true);
assertEquals(testHostApiImpl.canGoBack(0L), true);
}
@Test
public void canGoForward() {
when(mockWebView.canGoForward()).thenReturn(false);
assertEquals(testHostApiImpl.canGoForward(0L), false);
}
@Test
public void goBack() {
testHostApiImpl.goBack(0L);
verify(mockWebView).goBack();
}
@Test
public void goForward() {
testHostApiImpl.goForward(0L);
verify(mockWebView).goForward();
}
@Test
public void reload() {
testHostApiImpl.reload(0L);
verify(mockWebView).reload();
}
@Test
public void clearCache() {
testHostApiImpl.clearCache(0L, false);
verify(mockWebView).clearCache(false);
}
@Test
public void evaluateJavaScript() {
final String[] successValue = new String[1];
testHostApiImpl.evaluateJavascript(
0L,
"2 + 2",
new GeneratedAndroidWebView.Result<String>() {
@Override
public void success(String result) {
successValue[0] = result;
}
@Override
public void error(@NonNull Throwable error) {}
});
@SuppressWarnings("unchecked")
final ArgumentCaptor<ValueCallback<String>> callbackCaptor =
ArgumentCaptor.forClass(ValueCallback.class);
verify(mockWebView).evaluateJavascript(eq("2 + 2"), callbackCaptor.capture());
callbackCaptor.getValue().onReceiveValue("da result");
assertEquals(successValue[0], "da result");
}
@Test
public void getTitle() {
when(mockWebView.getTitle()).thenReturn("My title");
assertEquals(testHostApiImpl.getTitle(0L), "My title");
}
@Test
public void scrollTo() {
testHostApiImpl.scrollTo(0L, 12L, 13L);
verify(mockWebView).scrollTo(12, 13);
}
@Test
public void scrollBy() {
testHostApiImpl.scrollBy(0L, 15L, 23L);
verify(mockWebView).scrollBy(15, 23);
}
@Test
public void getScrollX() {
when(mockWebView.getScrollX()).thenReturn(55);
assertEquals((long) testHostApiImpl.getScrollX(0L), 55);
}
@Test
public void getScrollY() {
when(mockWebView.getScrollY()).thenReturn(23);
assertEquals((long) testHostApiImpl.getScrollY(0L), 23);
}
@Test
public void getScrollPosition() {
when(mockWebView.getScrollX()).thenReturn(1);
when(mockWebView.getScrollY()).thenReturn(2);
final GeneratedAndroidWebView.WebViewPoint position = testHostApiImpl.getScrollPosition(0L);
assertEquals((long) position.getX(), 1L);
assertEquals((long) position.getY(), 2L);
}
@Test
public void setWebViewClient() {
final WebViewClient mockWebViewClient = mock(WebViewClient.class);
testInstanceManager.addDartCreatedInstance(mockWebViewClient, 1L);
testHostApiImpl.setWebViewClient(0L, 1L);
verify(mockWebView).setWebViewClient(mockWebViewClient);
}
@Test
public void addJavaScriptChannel() {
final JavaScriptChannel javaScriptChannel =
new JavaScriptChannel(mock(JavaScriptChannelFlutterApiImpl.class), "aName", null);
testInstanceManager.addDartCreatedInstance(javaScriptChannel, 1L);
testHostApiImpl.addJavaScriptChannel(0L, 1L);
verify(mockWebView).addJavascriptInterface(javaScriptChannel, "aName");
}
@Test
public void removeJavaScriptChannel() {
final JavaScriptChannel javaScriptChannel =
new JavaScriptChannel(mock(JavaScriptChannelFlutterApiImpl.class), "aName", null);
testInstanceManager.addDartCreatedInstance(javaScriptChannel, 1L);
testHostApiImpl.removeJavaScriptChannel(0L, 1L);
verify(mockWebView).removeJavascriptInterface("aName");
}
@Test
public void setDownloadListener() {
final DownloadListener mockDownloadListener = mock(DownloadListener.class);
testInstanceManager.addDartCreatedInstance(mockDownloadListener, 1L);
testHostApiImpl.setDownloadListener(0L, 1L);
verify(mockWebView).setDownloadListener(mockDownloadListener);
}
@Test
public void setWebChromeClient() {
final WebChromeClient mockWebChromeClient = mock(WebChromeClient.class);
testInstanceManager.addDartCreatedInstance(mockWebChromeClient, 1L);
testHostApiImpl.setWebChromeClient(0L, 1L);
verify(mockWebView).setWebChromeClient(mockWebChromeClient);
}
@Test
public void defaultWebChromeClientIsSecureWebChromeClient() {
final WebViewPlatformView webView = new WebViewPlatformView(mockContext, null, null);
assertTrue(
webView.getWebChromeClient() instanceof WebChromeClientHostApiImpl.SecureWebChromeClient);
assertFalse(
webView.getWebChromeClient() instanceof WebChromeClientHostApiImpl.WebChromeClientImpl);
}
@Test
public void defaultWebChromeClientDoesNotAttemptToCommunicateWithDart() {
final WebViewPlatformView webView = new WebViewPlatformView(mockContext, null, null);
// This shouldn't throw an Exception.
Objects.requireNonNull(webView.getWebChromeClient()).onProgressChanged(webView, 0);
}
@Test
public void disposeDoesNotCallDestroy() {
final boolean[] destroyCalled = {false};
final WebViewPlatformView webView =
new WebViewPlatformView(mockContext, null, null) {
@Override
public void destroy() {
destroyCalled[0] = true;
}
};
webView.dispose();
assertFalse(destroyCalled[0]);
}
@Test
public void destroyWebViewWhenDisposedFromJavaObjectHostApi() {
final boolean[] destroyCalled = {false};
final WebViewPlatformView webView =
new WebViewPlatformView(mockContext, null, null) {
@Override
public void destroy() {
destroyCalled[0] = true;
}
};
testInstanceManager.addDartCreatedInstance(webView, 1);
final JavaObjectHostApiImpl javaObjectHostApi = new JavaObjectHostApiImpl(testInstanceManager);
javaObjectHostApi.dispose(1L);
assertTrue(destroyCalled[0]);
}
@Test
public void flutterApiCreate() {
final InstanceManager instanceManager = InstanceManager.create(identifier -> {});
final WebViewFlutterApiImpl flutterApiImpl =
new WebViewFlutterApiImpl(mockBinaryMessenger, instanceManager);
final WebViewFlutterApi mockFlutterApi = mock(WebViewFlutterApi.class);
flutterApiImpl.setApi(mockFlutterApi);
flutterApiImpl.create(mockWebView, reply -> {});
final long instanceIdentifier =
Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(mockWebView));
verify(mockFlutterApi).create(eq(instanceIdentifier), any());
instanceManager.stopFinalizationListener();
}
@Test
public void setImportantForAutofillForParentFlutterView() {
final WebViewPlatformView webView =
new WebViewPlatformView(
mockContext,
mockBinaryMessenger,
testInstanceManager,
(int version) -> version <= Build.VERSION_CODES.O);
final WebViewPlatformView webViewSpy = spy(webView);
final FlutterView mockFlutterView = mock(FlutterView.class);
when(webViewSpy.getParent()).thenReturn(mockFlutterView);
webViewSpy.onAttachedToWindow();
verify(mockFlutterView).setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_YES);
}
@Test
public void onScrollChanged() {
final InstanceManager instanceManager = InstanceManager.create(identifier -> {});
final WebViewFlutterApiImpl flutterApiImpl =
new WebViewFlutterApiImpl(mockBinaryMessenger, instanceManager);
final WebViewFlutterApi mockFlutterApi = mock(WebViewFlutterApi.class);
flutterApiImpl.setApi(mockFlutterApi);
flutterApiImpl.create(mockWebView, reply -> {});
flutterApiImpl.onScrollChanged(mockWebView, 0L, 1L, 2L, 3L, reply -> {});
final long instanceIdentifier =
Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(mockWebView));
verify(mockFlutterApi)
.onScrollChanged(eq(instanceIdentifier), eq(0L), eq(1L), eq(2L), eq(3L), any());
instanceManager.stopFinalizationListener();
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewTest.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewTest.java",
"repo_id": "packages",
"token_count": 4626
} | 1,315 |
// 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.
/// A decision on how to handle a navigation request.
enum NavigationDecision {
/// Prevent the navigation from taking place.
prevent,
/// Allow the navigation to take place.
navigate,
}
| packages/packages/webview_flutter/webview_flutter_android/example/lib/legacy/navigation_decision.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/example/lib/legacy/navigation_decision.dart",
"repo_id": "packages",
"token_count": 90
} | 1,316 |
// 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:typed_data';
import 'package:flutter/widgets.dart';
// ignore: implementation_imports
import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart';
import '../android_webview.dart' as android_webview;
import '../weak_reference_utils.dart';
import 'webview_android_cookie_manager.dart';
/// Creates a [Widget] with a [android_webview.WebView].
class WebViewAndroidWidget extends StatefulWidget {
/// Constructs a [WebViewAndroidWidget].
const WebViewAndroidWidget({
super.key,
required this.creationParams,
required this.callbacksHandler,
required this.javascriptChannelRegistry,
required this.onBuildWidget,
@visibleForTesting this.webViewProxy = const WebViewProxy(),
@visibleForTesting
this.flutterAssetManager = const android_webview.FlutterAssetManager(),
@visibleForTesting this.webStorage,
});
/// Initial parameters used to setup the WebView.
final CreationParams creationParams;
/// Handles callbacks that are made by [android_webview.WebViewClient], [android_webview.DownloadListener], and [android_webview.WebChromeClient].
final WebViewPlatformCallbacksHandler callbacksHandler;
/// Manages named JavaScript channels and forwarding incoming messages on the correct channel.
final JavascriptChannelRegistry javascriptChannelRegistry;
/// Handles constructing [android_webview.WebView]s and calling static methods.
///
/// This should only be changed for testing purposes.
final WebViewProxy webViewProxy;
/// Manages access to Flutter assets that are part of the Android App bundle.
///
/// This should only be changed for testing purposes.
final android_webview.FlutterAssetManager flutterAssetManager;
/// Callback to build a widget once [android_webview.WebView] has been initialized.
final Widget Function(WebViewAndroidPlatformController controller)
onBuildWidget;
/// Manages the JavaScript storage APIs.
final android_webview.WebStorage? webStorage;
@override
State<StatefulWidget> createState() => _WebViewAndroidWidgetState();
}
class _WebViewAndroidWidgetState extends State<WebViewAndroidWidget> {
late final WebViewAndroidPlatformController controller;
@override
void initState() {
super.initState();
controller = WebViewAndroidPlatformController(
creationParams: widget.creationParams,
callbacksHandler: widget.callbacksHandler,
javascriptChannelRegistry: widget.javascriptChannelRegistry,
webViewProxy: widget.webViewProxy,
flutterAssetManager: widget.flutterAssetManager,
webStorage: widget.webStorage,
);
}
@override
Widget build(BuildContext context) {
return widget.onBuildWidget(controller);
}
}
/// Implementation of [WebViewPlatformController] with the Android WebView api.
class WebViewAndroidPlatformController extends WebViewPlatformController {
/// Construct a [WebViewAndroidPlatformController].
WebViewAndroidPlatformController({
required CreationParams creationParams,
required this.callbacksHandler,
required this.javascriptChannelRegistry,
@visibleForTesting this.webViewProxy = const WebViewProxy(),
@visibleForTesting
this.flutterAssetManager = const android_webview.FlutterAssetManager(),
@visibleForTesting android_webview.WebStorage? webStorage,
}) : webStorage = webStorage ?? android_webview.WebStorage.instance,
assert(creationParams.webSettings?.hasNavigationDelegate != null),
super(callbacksHandler) {
webView = webViewProxy.createWebView();
webView.settings.setDomStorageEnabled(true);
webView.settings.setJavaScriptCanOpenWindowsAutomatically(true);
webView.settings.setSupportMultipleWindows(true);
webView.settings.setLoadWithOverviewMode(true);
webView.settings.setUseWideViewPort(true);
webView.settings.setDisplayZoomControls(false);
webView.settings.setBuiltInZoomControls(true);
_setCreationParams(creationParams);
webView.setDownloadListener(downloadListener);
webView.setWebChromeClient(webChromeClient);
webView.setWebViewClient(webViewClient);
final String? initialUrl = creationParams.initialUrl;
if (initialUrl != null) {
loadUrl(initialUrl, <String, String>{});
}
}
final Map<String, WebViewAndroidJavaScriptChannel> _javaScriptChannels =
<String, WebViewAndroidJavaScriptChannel>{};
late final android_webview.WebViewClient _webViewClient =
webViewProxy.createWebViewClient(
onPageStarted: withWeakReferenceTo(this, (
WeakReference<WebViewAndroidPlatformController> weakReference,
) {
return (_, String url) {
weakReference.target?.callbacksHandler.onPageStarted(url);
};
}),
onPageFinished: withWeakReferenceTo(this, (
WeakReference<WebViewAndroidPlatformController> weakReference,
) {
return (_, String url) {
weakReference.target?.callbacksHandler.onPageFinished(url);
};
}),
onReceivedError: withWeakReferenceTo(this, (
WeakReference<WebViewAndroidPlatformController> weakReference,
) {
return (
_,
int errorCode,
String description,
String failingUrl,
) {
weakReference.target?.callbacksHandler
.onWebResourceError(WebResourceError(
errorCode: errorCode,
description: description,
failingUrl: failingUrl,
errorType: _errorCodeToErrorType(errorCode),
));
};
}),
onReceivedRequestError: withWeakReferenceTo(this, (
WeakReference<WebViewAndroidPlatformController> weakReference,
) {
return (
_,
android_webview.WebResourceRequest request,
android_webview.WebResourceError error,
) {
if (request.isForMainFrame) {
weakReference.target?.callbacksHandler
.onWebResourceError(WebResourceError(
errorCode: error.errorCode,
description: error.description,
failingUrl: request.url,
errorType: _errorCodeToErrorType(error.errorCode),
));
}
};
}),
urlLoading: withWeakReferenceTo(this, (
WeakReference<WebViewAndroidPlatformController> weakReference,
) {
return (_, String url) {
weakReference.target?._handleNavigationRequest(
url: url,
isForMainFrame: true,
);
};
}),
requestLoading: withWeakReferenceTo(this, (
WeakReference<WebViewAndroidPlatformController> weakReference,
) {
return (_, android_webview.WebResourceRequest request) {
weakReference.target?._handleNavigationRequest(
url: request.url,
isForMainFrame: request.isForMainFrame,
);
};
}),
);
bool _hasNavigationDelegate = false;
bool _hasProgressTracking = false;
/// Represents the WebView maintained by platform code.
late final android_webview.WebView webView;
/// Handles callbacks that are made by [android_webview.WebViewClient], [android_webview.DownloadListener], and [android_webview.WebChromeClient].
final WebViewPlatformCallbacksHandler callbacksHandler;
/// Manages named JavaScript channels and forwarding incoming messages on the correct channel.
final JavascriptChannelRegistry javascriptChannelRegistry;
/// Handles constructing [android_webview.WebView]s and calling static methods.
///
/// This should only be changed for testing purposes.
final WebViewProxy webViewProxy;
/// Manages access to Flutter assets that are part of the Android App bundle.
///
/// This should only be changed for testing purposes.
final android_webview.FlutterAssetManager flutterAssetManager;
/// Receives callbacks when content should be downloaded instead.
@visibleForTesting
late final android_webview.DownloadListener downloadListener =
android_webview.DownloadListener(
onDownloadStart: withWeakReferenceTo(
this,
(WeakReference<WebViewAndroidPlatformController> weakReference) {
return (
String url,
String userAgent,
String contentDisposition,
String mimetype,
int contentLength,
) {
weakReference.target?._handleNavigationRequest(
url: url,
isForMainFrame: true,
);
};
},
),
);
/// Handles JavaScript dialogs, favicons, titles, new windows, and the progress for [android_webview.WebView].
@visibleForTesting
late final android_webview.WebChromeClient webChromeClient =
android_webview.WebChromeClient(
onProgressChanged: withWeakReferenceTo(
this,
(WeakReference<WebViewAndroidPlatformController> weakReference) {
return (_, int progress) {
final WebViewAndroidPlatformController? controller =
weakReference.target;
if (controller != null && controller._hasProgressTracking) {
controller.callbacksHandler.onProgress(progress);
}
};
},
));
/// Manages the JavaScript storage APIs.
final android_webview.WebStorage webStorage;
/// Receive various notifications and requests for [android_webview.WebView].
@visibleForTesting
android_webview.WebViewClient get webViewClient => _webViewClient;
@override
Future<void> loadHtmlString(String html, {String? baseUrl}) {
return webView.loadDataWithBaseUrl(
baseUrl: baseUrl,
data: html,
mimeType: 'text/html',
);
}
@override
Future<void> loadFile(String absoluteFilePath) {
final String url = absoluteFilePath.startsWith('file://')
? absoluteFilePath
: 'file://$absoluteFilePath';
webView.settings.setAllowFileAccess(true);
return webView.loadUrl(url, <String, String>{});
}
@override
Future<void> loadFlutterAsset(String key) async {
final String assetFilePath =
await flutterAssetManager.getAssetFilePathByName(key);
final List<String> pathElements = assetFilePath.split('/');
final String fileName = pathElements.removeLast();
final List<String?> paths =
await flutterAssetManager.list(pathElements.join('/'));
if (!paths.contains(fileName)) {
throw ArgumentError(
'Asset for key "$key" not found.',
'key',
);
}
return webView.loadUrl(
'file:///android_asset/$assetFilePath',
<String, String>{},
);
}
@override
Future<void> loadUrl(
String url,
Map<String, String>? headers,
) {
return webView.loadUrl(url, headers ?? <String, String>{});
}
/// When making a POST request, headers are ignored. As a workaround, make
/// the request manually and load the response data using [loadHTMLString].
@override
Future<void> loadRequest(
WebViewRequest request,
) async {
if (!request.uri.hasScheme) {
throw ArgumentError('WebViewRequest#uri is required to have a scheme.');
}
switch (request.method) {
case WebViewRequestMethod.get:
return webView.loadUrl(request.uri.toString(), request.headers);
case WebViewRequestMethod.post:
return webView.postUrl(
request.uri.toString(), request.body ?? Uint8List(0));
}
// The enum comes from a different package, which could get a new value at
// any time, so a fallback case is necessary. Since there is no reasonable
// default behavior, throw to alert the client that they need an updated
// version. This is deliberately outside the switch rather than a `default`
// so that the linter will flag the switch as needing an update.
// ignore: dead_code
throw UnimplementedError(
'This version of webview_android_widget currently has no '
'implementation for HTTP method ${request.method.serialize()} in '
'loadRequest.');
}
@override
Future<String?> currentUrl() => webView.getUrl();
@override
Future<bool> canGoBack() => webView.canGoBack();
@override
Future<bool> canGoForward() => webView.canGoForward();
@override
Future<void> goBack() => webView.goBack();
@override
Future<void> goForward() => webView.goForward();
@override
Future<void> reload() => webView.reload();
@override
Future<void> clearCache() {
webView.clearCache(true);
return webStorage.deleteAllData();
}
@override
Future<void> updateSettings(WebSettings setting) async {
_hasProgressTracking = setting.hasProgressTracking ?? _hasProgressTracking;
await Future.wait(<Future<void>>[
_setUserAgent(setting.userAgent),
if (setting.hasNavigationDelegate != null)
_setHasNavigationDelegate(setting.hasNavigationDelegate!),
if (setting.javascriptMode != null)
_setJavaScriptMode(setting.javascriptMode!),
if (setting.debuggingEnabled != null)
_setDebuggingEnabled(setting.debuggingEnabled!),
if (setting.zoomEnabled != null) _setZoomEnabled(setting.zoomEnabled!),
]);
}
@override
Future<String> evaluateJavascript(String javascript) async {
return runJavascriptReturningResult(javascript);
}
@override
Future<void> runJavascript(String javascript) async {
await webView.evaluateJavascript(javascript);
}
@override
Future<String> runJavascriptReturningResult(String javascript) async {
return await webView.evaluateJavascript(javascript) ?? '';
}
@override
Future<void> addJavascriptChannels(Set<String> javascriptChannelNames) {
return Future.wait(
javascriptChannelNames.where(
(String channelName) {
return !_javaScriptChannels.containsKey(channelName);
},
).map<Future<void>>(
(String channelName) {
final WebViewAndroidJavaScriptChannel javaScriptChannel =
WebViewAndroidJavaScriptChannel(
channelName, javascriptChannelRegistry);
_javaScriptChannels[channelName] = javaScriptChannel;
return webView.addJavaScriptChannel(javaScriptChannel);
},
),
);
}
@override
Future<void> removeJavascriptChannels(
Set<String> javascriptChannelNames,
) {
return Future.wait(
javascriptChannelNames.where(
(String channelName) {
return _javaScriptChannels.containsKey(channelName);
},
).map<Future<void>>(
(String channelName) {
final WebViewAndroidJavaScriptChannel javaScriptChannel =
_javaScriptChannels[channelName]!;
_javaScriptChannels.remove(channelName);
return webView.removeJavaScriptChannel(javaScriptChannel);
},
),
);
}
@override
Future<String?> getTitle() => webView.getTitle();
@override
Future<void> scrollTo(int x, int y) => webView.scrollTo(x, y);
@override
Future<void> scrollBy(int x, int y) => webView.scrollBy(x, y);
@override
Future<int> getScrollX() => webView.getScrollX();
@override
Future<int> getScrollY() => webView.getScrollY();
void _setCreationParams(CreationParams creationParams) {
final WebSettings? webSettings = creationParams.webSettings;
if (webSettings != null) {
updateSettings(webSettings);
}
final String? userAgent = creationParams.userAgent;
if (userAgent != null) {
webView.settings.setUserAgentString(userAgent);
}
webView.settings.setMediaPlaybackRequiresUserGesture(
creationParams.autoMediaPlaybackPolicy !=
AutoMediaPlaybackPolicy.always_allow,
);
final Color? backgroundColor = creationParams.backgroundColor;
if (backgroundColor != null) {
webView.setBackgroundColor(backgroundColor);
}
addJavascriptChannels(creationParams.javascriptChannelNames);
// TODO(BeMacized): Remove once platform implementations
// are able to register themselves (Flutter >=2.8),
// https://github.com/flutter/flutter/issues/94224
WebViewCookieManagerPlatform.instance ??= WebViewAndroidCookieManager();
creationParams.cookies
.forEach(WebViewCookieManagerPlatform.instance!.setCookie);
}
Future<void> _setHasNavigationDelegate(bool hasNavigationDelegate) {
_hasNavigationDelegate = hasNavigationDelegate;
return _webViewClient.setSynchronousReturnValueForShouldOverrideUrlLoading(
hasNavigationDelegate,
);
}
Future<void> _setJavaScriptMode(JavascriptMode mode) {
switch (mode) {
case JavascriptMode.disabled:
return webView.settings.setJavaScriptEnabled(false);
case JavascriptMode.unrestricted:
return webView.settings.setJavaScriptEnabled(true);
}
}
Future<void> _setDebuggingEnabled(bool debuggingEnabled) {
return webViewProxy.setWebContentsDebuggingEnabled(debuggingEnabled);
}
Future<void> _setUserAgent(WebSetting<String?> userAgent) {
if (userAgent.isPresent) {
// If the string is empty, the system default value will be used.
return webView.settings.setUserAgentString(userAgent.value ?? '');
}
return Future<void>.value();
}
Future<void> _setZoomEnabled(bool zoomEnabled) {
return webView.settings.setSupportZoom(zoomEnabled);
}
static WebResourceErrorType _errorCodeToErrorType(int errorCode) {
switch (errorCode) {
case android_webview.WebViewClient.errorAuthentication:
return WebResourceErrorType.authentication;
case android_webview.WebViewClient.errorBadUrl:
return WebResourceErrorType.badUrl;
case android_webview.WebViewClient.errorConnect:
return WebResourceErrorType.connect;
case android_webview.WebViewClient.errorFailedSslHandshake:
return WebResourceErrorType.failedSslHandshake;
case android_webview.WebViewClient.errorFile:
return WebResourceErrorType.file;
case android_webview.WebViewClient.errorFileNotFound:
return WebResourceErrorType.fileNotFound;
case android_webview.WebViewClient.errorHostLookup:
return WebResourceErrorType.hostLookup;
case android_webview.WebViewClient.errorIO:
return WebResourceErrorType.io;
case android_webview.WebViewClient.errorProxyAuthentication:
return WebResourceErrorType.proxyAuthentication;
case android_webview.WebViewClient.errorRedirectLoop:
return WebResourceErrorType.redirectLoop;
case android_webview.WebViewClient.errorTimeout:
return WebResourceErrorType.timeout;
case android_webview.WebViewClient.errorTooManyRequests:
return WebResourceErrorType.tooManyRequests;
case android_webview.WebViewClient.errorUnknown:
return WebResourceErrorType.unknown;
case android_webview.WebViewClient.errorUnsafeResource:
return WebResourceErrorType.unsafeResource;
case android_webview.WebViewClient.errorUnsupportedAuthScheme:
return WebResourceErrorType.unsupportedAuthScheme;
case android_webview.WebViewClient.errorUnsupportedScheme:
return WebResourceErrorType.unsupportedScheme;
}
throw ArgumentError(
'Could not find a WebResourceErrorType for errorCode: $errorCode',
);
}
void _handleNavigationRequest({
required String url,
required bool isForMainFrame,
}) {
if (!_hasNavigationDelegate) {
return;
}
final FutureOr<bool> returnValue = callbacksHandler.onNavigationRequest(
url: url,
isForMainFrame: isForMainFrame,
);
if (returnValue is bool && returnValue) {
loadUrl(url, <String, String>{});
} else if (returnValue is Future<bool>) {
returnValue.then((bool shouldLoadUrl) {
if (shouldLoadUrl) {
loadUrl(url, <String, String>{});
}
});
}
}
}
/// Exposes a channel to receive calls from javaScript.
class WebViewAndroidJavaScriptChannel
extends android_webview.JavaScriptChannel {
/// Creates a [WebViewAndroidJavaScriptChannel].
WebViewAndroidJavaScriptChannel(
super.channelName,
this.javascriptChannelRegistry,
) : super(
postMessage: withWeakReferenceTo(
javascriptChannelRegistry,
(WeakReference<JavascriptChannelRegistry> weakReference) {
return (String message) {
weakReference.target?.onJavascriptChannelMessage(
channelName,
message,
);
};
},
),
);
/// Manages named JavaScript channels and forwarding incoming messages on the correct channel.
final JavascriptChannelRegistry javascriptChannelRegistry;
}
/// Handles constructing [android_webview.WebView]s and calling static methods.
///
/// This should only be used for testing purposes.
@visibleForTesting
class WebViewProxy {
/// Creates a [WebViewProxy].
const WebViewProxy();
/// Constructs a [android_webview.WebView].
android_webview.WebView createWebView() {
return android_webview.WebView();
}
/// Constructs a [android_webview.WebViewClient].
android_webview.WebViewClient createWebViewClient({
void Function(android_webview.WebView webView, String url)? onPageStarted,
void Function(android_webview.WebView webView, String url)? onPageFinished,
void Function(
android_webview.WebView webView,
android_webview.WebResourceRequest request,
android_webview.WebResourceError error,
)? onReceivedRequestError,
void Function(
android_webview.WebView webView,
int errorCode,
String description,
String failingUrl,
)? onReceivedError,
void Function(android_webview.WebView webView,
android_webview.WebResourceRequest request)?
requestLoading,
void Function(android_webview.WebView webView, String url)? urlLoading,
}) {
return android_webview.WebViewClient(
onPageStarted: onPageStarted,
onPageFinished: onPageFinished,
onReceivedRequestError: onReceivedRequestError,
onReceivedError: onReceivedError,
requestLoading: requestLoading,
urlLoading: urlLoading,
);
}
/// Enables debugging of web contents (HTML / CSS / JavaScript) loaded into any WebViews of this application.
///
/// This flag can be enabled in order to facilitate debugging of web layouts
/// and JavaScript code running inside WebViews. Please refer to
/// [android_webview.WebView] documentation for the debugging guide. The
/// default is false.
///
/// See [android_webview.WebView].setWebContentsDebuggingEnabled.
Future<void> setWebContentsDebuggingEnabled(bool enabled) {
return android_webview.WebView.setWebContentsDebuggingEnabled(enabled);
}
}
| packages/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_widget.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_widget.dart",
"repo_id": "packages",
"token_count": 7832
} | 1,317 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:webview_flutter_android/src/android_webview.dart';
import 'package:webview_flutter_android/src/instance_manager.dart';
import 'instance_manager_test.mocks.dart';
import 'test_android_webview.g.dart';
@GenerateMocks(<Type>[TestInstanceManagerHostApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('InstanceManager', () {
test('addHostCreatedInstance', () {
final CopyableObject object = CopyableObject();
final InstanceManager instanceManager =
InstanceManager(onWeakReferenceRemoved: (_) {});
instanceManager.addHostCreatedInstance(object, 0);
expect(instanceManager.getIdentifier(object), 0);
expect(
instanceManager.getInstanceWithWeakReference(0),
object,
);
});
test('addHostCreatedInstance prevents already used objects and ids', () {
final CopyableObject object = CopyableObject();
final InstanceManager instanceManager =
InstanceManager(onWeakReferenceRemoved: (_) {});
instanceManager.addHostCreatedInstance(object, 0);
expect(
() => instanceManager.addHostCreatedInstance(object, 0),
throwsAssertionError,
);
expect(
() => instanceManager.addHostCreatedInstance(CopyableObject(), 0),
throwsAssertionError,
);
});
test('addFlutterCreatedInstance', () {
final CopyableObject object = CopyableObject();
final InstanceManager instanceManager =
InstanceManager(onWeakReferenceRemoved: (_) {});
instanceManager.addDartCreatedInstance(object);
final int? instanceId = instanceManager.getIdentifier(object);
expect(instanceId, isNotNull);
expect(
instanceManager.getInstanceWithWeakReference(instanceId!),
object,
);
});
test('removeWeakReference', () {
final CopyableObject object = CopyableObject();
int? weakInstanceId;
final InstanceManager instanceManager =
InstanceManager(onWeakReferenceRemoved: (int instanceId) {
weakInstanceId = instanceId;
});
instanceManager.addHostCreatedInstance(object, 0);
expect(instanceManager.removeWeakReference(object), 0);
expect(
instanceManager.getInstanceWithWeakReference(0),
isA<CopyableObject>(),
);
expect(weakInstanceId, 0);
});
test('removeWeakReference removes only weak reference', () {
final CopyableObject object = CopyableObject();
final InstanceManager instanceManager =
InstanceManager(onWeakReferenceRemoved: (_) {});
instanceManager.addHostCreatedInstance(object, 0);
expect(instanceManager.removeWeakReference(object), 0);
final CopyableObject copy = instanceManager.getInstanceWithWeakReference(
0,
)!;
expect(identical(object, copy), isFalse);
});
test('removeStrongReference', () {
final CopyableObject object = CopyableObject();
final InstanceManager instanceManager =
InstanceManager(onWeakReferenceRemoved: (_) {});
instanceManager.addHostCreatedInstance(object, 0);
instanceManager.removeWeakReference(object);
expect(instanceManager.remove(0), isA<CopyableObject>());
expect(instanceManager.containsIdentifier(0), isFalse);
});
test('removeStrongReference removes only strong reference', () {
final CopyableObject object = CopyableObject();
final InstanceManager instanceManager =
InstanceManager(onWeakReferenceRemoved: (_) {});
instanceManager.addHostCreatedInstance(object, 0);
expect(instanceManager.remove(0), isA<CopyableObject>());
expect(
instanceManager.getInstanceWithWeakReference(0),
object,
);
});
test('getInstance can add a new weak reference', () {
final CopyableObject object = CopyableObject();
final InstanceManager instanceManager =
InstanceManager(onWeakReferenceRemoved: (_) {});
instanceManager.addHostCreatedInstance(object, 0);
instanceManager.removeWeakReference(object);
final CopyableObject newWeakCopy =
instanceManager.getInstanceWithWeakReference(
0,
)!;
expect(identical(object, newWeakCopy), isFalse);
});
test('globalInstanceManager clears native `InstanceManager`', () {
final MockTestInstanceManagerHostApi mockApi =
MockTestInstanceManagerHostApi();
TestInstanceManagerHostApi.setup(mockApi);
// Calls method to clear the native InstanceManager.
// ignore: unnecessary_statements
JavaObject.globalInstanceManager;
verify(mockApi.clear());
TestInstanceManagerHostApi.setup(null);
});
});
}
class CopyableObject with Copyable {
@override
Copyable copy() {
return CopyableObject();
}
}
| packages/packages/webview_flutter/webview_flutter_android/test/instance_manager_test.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/test/instance_manager_test.dart",
"repo_id": "packages",
"token_count": 1785
} | 1,318 |
// 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 '../types/types.dart';
/// Interface for callbacks made by [WebViewPlatformController].
///
/// The webview plugin implements this class, and passes an instance to the [WebViewPlatformController].
/// [WebViewPlatformController] is notifying this handler on events that happened on the platform's webview.
abstract class WebViewPlatformCallbacksHandler {
/// Invoked by [WebViewPlatformController] when a navigation request is pending.
///
/// If true is returned the navigation is allowed, otherwise it is blocked.
FutureOr<bool> onNavigationRequest(
{required String url, required bool isForMainFrame});
/// Invoked by [WebViewPlatformController] when a page has started loading.
void onPageStarted(String url);
/// Invoked by [WebViewPlatformController] when a page has finished loading.
void onPageFinished(String url);
/// Invoked by [WebViewPlatformController] when a page is loading.
/// /// Only works when [WebSettings.hasProgressTracking] is set to `true`.
void onProgress(int progress);
/// Report web resource loading error to the host application.
void onWebResourceError(WebResourceError error);
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform_callbacks_handler.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform_callbacks_handler.dart",
"repo_id": "packages",
"token_count": 343
} | 1,319 |
// 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:plugin_platform_interface/plugin_platform_interface.dart';
import 'types/types.dart';
import 'webview_platform.dart' show WebViewPlatform;
/// Interface for a platform implementation of a web view widget.
abstract class PlatformWebViewWidget extends PlatformInterface {
/// Creates a new [PlatformWebViewWidget]
factory PlatformWebViewWidget(PlatformWebViewWidgetCreationParams params) {
assert(
WebViewPlatform.instance != null,
'A platform implementation for `webview_flutter` has not been set. Please '
'ensure that an implementation of `WebViewPlatform` has been set to '
'`WebViewPlatform.instance` before use. For unit testing, '
'`WebViewPlatform.instance` can be set with your own test implementation.',
);
final PlatformWebViewWidget webViewWidgetDelegate =
WebViewPlatform.instance!.createPlatformWebViewWidget(params);
PlatformInterface.verify(webViewWidgetDelegate, _token);
return webViewWidgetDelegate;
}
/// Used by the platform implementation to create a new
/// [PlatformWebViewWidget].
///
/// Should only be used by platform implementations because they can't extend
/// a class that only contains a factory constructor.
@protected
PlatformWebViewWidget.implementation(this.params) : super(token: _token);
static final Object _token = Object();
/// The parameters used to initialize the [PlatformWebViewWidget].
final PlatformWebViewWidgetCreationParams params;
/// Builds a new WebView.
///
/// Returns a Widget tree that embeds the created web view.
Widget build(BuildContext context);
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_widget.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/platform_webview_widget.dart",
"repo_id": "packages",
"token_count": 506
} | 1,320 |
// 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.
/// Defines the parameters of the scroll position change callback.
class ScrollPositionChange {
/// Creates a [ScrollPositionChange].
const ScrollPositionChange(this.x, this.y);
/// The value of the horizontal offset with the origin being at the leftmost
/// of the `WebView`.
final double x;
/// The value of the vertical offset with the origin being at the topmost of
/// the `WebView`.
final double y;
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/scroll_position_change.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/scroll_position_change.dart",
"repo_id": "packages",
"token_count": 153
} | 1,321 |
// 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:flutter_test/flutter_test.dart';
import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart';
void main() {
test('WebViewRequestMethod should serialize correctly', () {
expect(WebViewRequestMethod.get.serialize(), 'get');
expect(WebViewRequestMethod.post.serialize(), 'post');
});
test('WebViewRequest should serialize correctly', () {
WebViewRequest request;
Map<String, dynamic> serializedRequest;
// Test serialization without headers or a body
request = WebViewRequest(
uri: Uri.parse('https://flutter.dev'),
method: WebViewRequestMethod.get,
);
serializedRequest = request.toJson();
expect(serializedRequest['uri'], 'https://flutter.dev');
expect(serializedRequest['method'], 'get');
expect(serializedRequest['headers'], <String, String>{});
expect(serializedRequest['body'], null);
// Test serialization of headers and body
request = WebViewRequest(
uri: Uri.parse('https://flutter.dev'),
method: WebViewRequestMethod.get,
headers: <String, String>{'foo': 'bar'},
body: Uint8List.fromList('Example Body'.codeUnits),
);
serializedRequest = request.toJson();
expect(serializedRequest['headers'], <String, String>{'foo': 'bar'});
expect(serializedRequest['body'], 'Example Body'.codeUnits);
});
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/types/webview_request_test.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/types/webview_request_test.dart",
"repo_id": "packages",
"token_count": 524
} | 1,322 |
// 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:io';
// FIX (dit): Remove these integration tests, or make them run. They currently never fail.
// (They won't run because they use `dart:io`. If you remove all `dart:io` bits from
// this file, they start failing with `fail()`, for example.)
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'package:webview_flutter_web/webview_flutter_web.dart';
Future<void> main() async {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
final HttpServer server = await HttpServer.bind(InternetAddress.anyIPv4, 0);
unawaited(server.forEach((HttpRequest request) {
if (request.uri.path == '/hello.txt') {
request.response.writeln('Hello, world.');
} else {
fail('unexpected request: ${request.method} ${request.uri}');
}
request.response.close();
}));
final String prefixUrl = 'http://${server.address.address}:${server.port}';
final String primaryUrl = '$prefixUrl/hello.txt';
testWidgets('loadRequest', (WidgetTester tester) async {
final WebWebViewController controller =
WebWebViewController(const PlatformWebViewControllerCreationParams());
await controller.loadRequest(
LoadRequestParams(uri: Uri.parse(primaryUrl)),
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Builder(builder: (BuildContext context) {
return WebWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
}),
),
);
// Assert an iframe has been rendered to the DOM with the correct src attribute.
final html.IFrameElement? element =
html.document.querySelector('iframe') as html.IFrameElement?;
expect(element, isNotNull);
expect(element!.src, primaryUrl);
});
testWidgets('loadHtmlString', (WidgetTester tester) async {
final WebWebViewController controller =
WebWebViewController(const PlatformWebViewControllerCreationParams());
await controller.loadHtmlString(
'data:text/html;charset=utf-8,${Uri.encodeFull('test html')}',
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Builder(builder: (BuildContext context) {
return WebWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: controller),
).build(context);
}),
),
);
// Assert an iframe has been rendered to the DOM with the correct src attribute.
final html.IFrameElement? element =
html.document.querySelector('iframe') as html.IFrameElement?;
expect(element, isNotNull);
expect(
element!.src,
'data:text/html;charset=utf-8,data:text/html;charset=utf-8,test%2520html',
);
});
}
| packages/packages/webview_flutter/webview_flutter_web/example/integration_test/webview_flutter_test.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_web/example/integration_test/webview_flutter_test.dart",
"repo_id": "packages",
"token_count": 1141
} | 1,323 |
// 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:convert';
import 'dart:html';
import 'dart:ui_web' as ui_web;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
// ignore: implementation_imports
import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart';
import 'http_request_factory.dart';
/// Builds an iframe based WebView.
///
/// This is used as the default implementation for [WebView.platform] on web.
class WebWebViewPlatform implements WebViewPlatform {
/// Constructs a new instance of [WebWebViewPlatform].
WebWebViewPlatform() {
ui_web.platformViewRegistry.registerViewFactory(
'webview-iframe',
(int viewId) => IFrameElement()
..id = 'webview-$viewId'
..width = '100%'
..height = '100%'
..style.border = 'none');
}
@override
Widget build({
required BuildContext context,
required CreationParams creationParams,
required WebViewPlatformCallbacksHandler webViewPlatformCallbacksHandler,
required JavascriptChannelRegistry? javascriptChannelRegistry,
WebViewPlatformCreatedCallback? onWebViewPlatformCreated,
Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers,
}) {
return HtmlElementView(
viewType: 'webview-iframe',
onPlatformViewCreated: (int viewId) {
if (onWebViewPlatformCreated == null) {
return;
}
final IFrameElement element =
document.getElementById('webview-$viewId')! as IFrameElement;
if (creationParams.initialUrl != null) {
// ignore: unsafe_html
element.src = creationParams.initialUrl;
}
onWebViewPlatformCreated(WebWebViewPlatformController(
element,
));
},
);
}
@override
Future<bool> clearCookies() async => false;
/// Gets called when the plugin is registered.
static void registerWith(Registrar registrar) {}
}
/// Implementation of [WebViewPlatformController] for web.
class WebWebViewPlatformController implements WebViewPlatformController {
/// Constructs a [WebWebViewPlatformController].
WebWebViewPlatformController(this._element);
final IFrameElement _element;
HttpRequestFactory _httpRequestFactory = const HttpRequestFactory();
/// Setter for setting the HttpRequestFactory, for testing purposes.
@visibleForTesting
// ignore: avoid_setters_without_getters
set httpRequestFactory(HttpRequestFactory factory) {
_httpRequestFactory = factory;
}
@override
Future<void> addJavascriptChannels(Set<String> javascriptChannelNames) {
throw UnimplementedError();
}
@override
Future<bool> canGoBack() {
throw UnimplementedError();
}
@override
Future<bool> canGoForward() {
throw UnimplementedError();
}
@override
Future<void> clearCache() {
throw UnimplementedError();
}
@override
Future<String?> currentUrl() {
throw UnimplementedError();
}
@override
Future<String> evaluateJavascript(String javascript) {
throw UnimplementedError();
}
@override
Future<int> getScrollX() {
throw UnimplementedError();
}
@override
Future<int> getScrollY() {
throw UnimplementedError();
}
@override
Future<String?> getTitle() {
throw UnimplementedError();
}
@override
Future<void> goBack() {
throw UnimplementedError();
}
@override
Future<void> goForward() {
throw UnimplementedError();
}
@override
Future<void> loadUrl(String url, Map<String, String>? headers) async {
// ignore: unsafe_html
_element.src = url;
}
@override
Future<void> reload() {
throw UnimplementedError();
}
@override
Future<void> removeJavascriptChannels(Set<String> javascriptChannelNames) {
throw UnimplementedError();
}
@override
Future<void> runJavascript(String javascript) {
throw UnimplementedError();
}
@override
Future<String> runJavascriptReturningResult(String javascript) {
throw UnimplementedError();
}
@override
Future<void> scrollBy(int x, int y) {
throw UnimplementedError();
}
@override
Future<void> scrollTo(int x, int y) {
throw UnimplementedError();
}
@override
Future<void> updateSettings(WebSettings setting) {
throw UnimplementedError();
}
@override
Future<void> loadFile(String absoluteFilePath) {
throw UnimplementedError();
}
@override
Future<void> loadHtmlString(
String html, {
String? baseUrl,
}) async {
// ignore: unsafe_html
_element.src = Uri.dataFromString(
html,
mimeType: 'text/html',
encoding: utf8,
).toString();
}
@override
Future<void> loadRequest(WebViewRequest request) async {
if (!request.uri.hasScheme) {
throw ArgumentError('WebViewRequest#uri is required to have a scheme.');
}
final HttpRequest httpReq = await _httpRequestFactory.request(
request.uri.toString(),
method: request.method.serialize(),
requestHeaders: request.headers,
sendData: request.body);
final String contentType =
httpReq.getResponseHeader('content-type') ?? 'text/html';
// ignore: unsafe_html
_element.src = Uri.dataFromString(
httpReq.responseText ?? '',
mimeType: contentType,
encoding: utf8,
).toString();
}
@override
Future<void> loadFlutterAsset(String key) {
throw UnimplementedError();
}
}
| packages/packages/webview_flutter/webview_flutter_web/lib/src/webview_flutter_web_legacy.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_web/lib/src/webview_flutter_web_legacy.dart",
"repo_id": "packages",
"token_count": 2008
} | 1,324 |
// 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;
@import XCTest;
@import webview_flutter_wkwebview;
#import <OCMock/OCMock.h>
@interface FWFPreferencesHostApiTests : XCTestCase
@end
@implementation FWFPreferencesHostApiTests
- (void)testCreateFromWebViewConfigurationWithIdentifier {
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
FWFPreferencesHostApiImpl *hostAPI =
[[FWFPreferencesHostApiImpl alloc] initWithInstanceManager:instanceManager];
[instanceManager addDartCreatedInstance:[[WKWebViewConfiguration alloc] init] withIdentifier:0];
FlutterError *error;
[hostAPI createFromWebViewConfigurationWithIdentifier:1 configurationIdentifier:0 error:&error];
WKPreferences *preferences = (WKPreferences *)[instanceManager instanceForIdentifier:1];
XCTAssertTrue([preferences isKindOfClass:[WKPreferences class]]);
XCTAssertNil(error);
}
- (void)testSetJavaScriptEnabled {
WKPreferences *mockPreferences = OCMClassMock([WKPreferences class]);
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
[instanceManager addDartCreatedInstance:mockPreferences withIdentifier:0];
FWFPreferencesHostApiImpl *hostAPI =
[[FWFPreferencesHostApiImpl alloc] initWithInstanceManager:instanceManager];
FlutterError *error;
[hostAPI setJavaScriptEnabledForPreferencesWithIdentifier:0 isEnabled:YES error:&error];
OCMVerify([mockPreferences setJavaScriptEnabled:YES]);
XCTAssertNil(error);
}
@end
| packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFPreferencesHostApiTests.m/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFPreferencesHostApiTests.m",
"repo_id": "packages",
"token_count": 496
} | 1,325 |
// 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 XCTest;
@import os.log;
static UIColor *getPixelColorInImage(CGImageRef image, size_t x, size_t y) {
CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image));
const UInt8 *data = CFDataGetBytePtr(pixelData);
size_t bytesPerRow = CGImageGetBytesPerRow(image);
size_t pixelInfo = (bytesPerRow * y) + (x * 4); // 4 bytes per pixel
UInt8 red = data[pixelInfo + 0];
UInt8 green = data[pixelInfo + 1];
UInt8 blue = data[pixelInfo + 2];
UInt8 alpha = data[pixelInfo + 3];
CFRelease(pixelData);
return [UIColor colorWithRed:red / 255.0f
green:green / 255.0f
blue:blue / 255.0f
alpha:alpha / 255.0f];
}
@interface FLTWebViewUITests : XCTestCase
@property(nonatomic, strong) XCUIApplication *app;
@end
@implementation FLTWebViewUITests
- (void)setUp {
self.continueAfterFailure = NO;
self.app = [[XCUIApplication alloc] init];
[self.app launch];
}
- (void)testTransparentBackground {
XCTSkip(@"Test is flaky. See https://github.com/flutter/flutter/issues/124156");
XCUIApplication *app = self.app;
XCUIElement *menu = app.buttons[@"Show menu"];
if (![menu waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find menu");
}
[menu tap];
XCUIElement *transparentBackground = app.buttons[@"Transparent background example"];
if (![transparentBackground waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find Transparent background example");
}
[transparentBackground tap];
XCUIElement *transparentBackgroundLoaded =
app.webViews.staticTexts[@"Transparent background test"];
if (![transparentBackgroundLoaded waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find Transparent background test");
}
XCUIScreenshot *screenshot = [[XCUIScreen mainScreen] screenshot];
UIImage *screenshotImage = screenshot.image;
CGImageRef screenshotCGImage = screenshotImage.CGImage;
UIColor *centerLeftColor =
getPixelColorInImage(screenshotCGImage, 0, CGImageGetHeight(screenshotCGImage) / 2);
UIColor *centerColor =
getPixelColorInImage(screenshotCGImage, CGImageGetWidth(screenshotCGImage) / 2,
CGImageGetHeight(screenshotCGImage) / 2);
CGColorSpaceRef centerLeftColorSpace = CGColorGetColorSpace(centerLeftColor.CGColor);
// Flutter Colors.green color : 0xFF4CAF50 -> rgba(76, 175, 80, 1)
// https://github.com/flutter/flutter/blob/f4abaa0735eba4dfd8f33f73363911d63931fe03/packages/flutter/lib/src/material/colors.dart#L1208
// The background color of the webview is : rgba(0, 0, 0, 0.5)
// The expected color is : rgba(38, 87, 40, 1)
CGFloat flutterGreenColorComponents[] = {38.0f / 255.0f, 87.0f / 255.0f, 40.0f / 255.0f, 1.0f};
CGColorRef flutterGreenColor = CGColorCreate(centerLeftColorSpace, flutterGreenColorComponents);
CGFloat redColorComponents[] = {1.0f, 0.0f, 0.0f, 1.0f};
CGColorRef redColor = CGColorCreate(centerLeftColorSpace, redColorComponents);
CGColorSpaceRelease(centerLeftColorSpace);
XCTAssertTrue(CGColorEqualToColor(flutterGreenColor, centerLeftColor.CGColor));
XCTAssertTrue(CGColorEqualToColor(redColor, centerColor.CGColor));
}
@end
| packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerUITests/FLTWebViewUITests.m/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerUITests/FLTWebViewUITests.m",
"repo_id": "packages",
"token_count": 1338
} | 1,326 |
// 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 "FWFHTTPCookieStoreHostApi.h"
#import "FWFDataConverters.h"
#import "FWFWebsiteDataStoreHostApi.h"
@interface FWFHTTPCookieStoreHostApiImpl ()
// InstanceManager must be weak to prevent a circular reference with the object it stores.
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
@end
@implementation FWFHTTPCookieStoreHostApiImpl
- (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager {
self = [self init];
if (self) {
_instanceManager = instanceManager;
}
return self;
}
- (WKHTTPCookieStore *)HTTPCookieStoreForIdentifier:(NSInteger)identifier {
return (WKHTTPCookieStore *)[self.instanceManager instanceForIdentifier:identifier];
}
- (void)createFromWebsiteDataStoreWithIdentifier:(NSInteger)identifier
dataStoreIdentifier:(NSInteger)websiteDataStoreIdentifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)
error {
WKWebsiteDataStore *dataStore =
(WKWebsiteDataStore *)[self.instanceManager instanceForIdentifier:websiteDataStoreIdentifier];
[self.instanceManager addDartCreatedInstance:dataStore.httpCookieStore withIdentifier:identifier];
}
- (void)setCookieForStoreWithIdentifier:(NSInteger)identifier
cookie:(nonnull FWFNSHttpCookieData *)cookie
completion:(nonnull void (^)(FlutterError *_Nullable))completion {
NSHTTPCookie *nsCookie = FWFNativeNSHTTPCookieFromCookieData(cookie);
[[self HTTPCookieStoreForIdentifier:identifier] setCookie:nsCookie
completionHandler:^{
completion(nil);
}];
}
@end
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFHTTPCookieStoreHostApi.m/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFHTTPCookieStoreHostApi.m",
"repo_id": "packages",
"token_count": 825
} | 1,327 |
// 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 <WebKit/WebKit.h>
#import "FWFGeneratedWebKitApis.h"
#import "FWFInstanceManager.h"
#import "FWFObjectHostApi.h"
#import "FWFWebViewConfigurationHostApi.h"
NS_ASSUME_NONNULL_BEGIN
/// Flutter api implementation for WKUIDelegate.
///
/// Handles making callbacks to Dart for a WKUIDelegate.
@interface FWFUIDelegateFlutterApiImpl : FWFWKUIDelegateFlutterApi
@property(readonly, nonatomic)
FWFWebViewConfigurationFlutterApiImpl *webViewConfigurationFlutterApi;
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager;
@end
/// Implementation of WKUIDelegate for FWFUIDelegateHostApiImpl.
@interface FWFUIDelegate : FWFObject <WKUIDelegate>
@property(readonly, nonnull, nonatomic) FWFUIDelegateFlutterApiImpl *UIDelegateAPI;
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager;
@end
/// Host api implementation for WKUIDelegate.
///
/// Handles creating WKUIDelegate that intercommunicate with a paired Dart object.
@interface FWFUIDelegateHostApiImpl : NSObject <FWFWKUIDelegateHostApi>
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager;
@end
NS_ASSUME_NONNULL_END
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUIDelegateHostApi.h/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUIDelegateHostApi.h",
"repo_id": "packages",
"token_count": 563
} | 1,328 |
// 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 <Foundation/Foundation.h>
#import <WebKit/WebKit.h>
NS_ASSUME_NONNULL_BEGIN
/// App and package facing native API provided by the `webview_flutter_wkwebview` plugin.
///
/// This class follows the convention of breaking changes of the Dart API, which means that any
/// changes to the class that are not backwards compatible will only be made with a major version
/// change of the plugin. Native code other than this external API does not follow breaking change
/// conventions, so app or plugin clients should not use any other native APIs.
@interface FWFWebViewFlutterWKWebViewExternalAPI : NSObject
/// Retrieves the `WKWebView` that is associated with `identifier`.
///
/// See the Dart method `WebKitWebViewController.webViewIdentifier` to get the identifier of an
/// underlying `WKWebView`.
///
/// @param identifier The associated identifier of the `WebView`.
/// @param registry The plugin registry the `FLTWebViewFlutterPlugin` should belong to. If
/// the registry doesn't contain an attached instance of `FLTWebViewFlutterPlugin`,
/// this method returns nil.
/// @return The `WKWebView` associated with `identifier` or nil if a `WKWebView` instance associated
/// with `identifier` could not be found.
+ (nullable WKWebView *)webViewForIdentifier:(long)identifier
withPluginRegistry:(id<FlutterPluginRegistry>)registry;
@end
NS_ASSUME_NONNULL_END
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebViewFlutterWKWebViewExternalAPI.h/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebViewFlutterWKWebViewExternalAPI.h",
"repo_id": "packages",
"token_count": 463
} | 1,329 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
// ignore: implementation_imports
import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart';
import '../foundation/foundation.dart';
import 'web_kit_webview_widget.dart';
/// Builds an iOS webview.
///
/// This is used as the default implementation for [WebView.platform] on iOS. It uses
/// a [UiKitView] to embed the webview in the widget hierarchy, and uses a method channel to
/// communicate with the platform code.
class CupertinoWebView implements WebViewPlatform {
@override
Widget build({
required BuildContext context,
required CreationParams creationParams,
required WebViewPlatformCallbacksHandler webViewPlatformCallbacksHandler,
required JavascriptChannelRegistry javascriptChannelRegistry,
WebViewPlatformCreatedCallback? onWebViewPlatformCreated,
Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers,
}) {
return WebKitWebViewWidget(
creationParams: creationParams,
callbacksHandler: webViewPlatformCallbacksHandler,
javascriptChannelRegistry: javascriptChannelRegistry,
onBuildWidget: (WebKitWebViewPlatformController controller) {
return UiKitView(
viewType: 'plugins.flutter.io/webview',
onPlatformViewCreated: (int id) {
if (onWebViewPlatformCreated != null) {
onWebViewPlatformCreated(controller);
}
},
gestureRecognizers: gestureRecognizers,
creationParams:
NSObject.globalInstanceManager.getIdentifier(controller.webView),
creationParamsCodec: const StandardMessageCodec(),
);
},
);
}
@override
Future<bool> clearCookies() {
if (WebViewCookieManagerPlatform.instance == null) {
throw Exception(
'Could not clear cookies as no implementation for WebViewCookieManagerPlatform has been registered.');
}
return WebViewCookieManagerPlatform.instance!.clearCookies();
}
}
| packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/legacy/webview_cupertino.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/legacy/webview_cupertino.dart",
"repo_id": "packages",
"token_count": 776
} | 1,330 |
// Mocks generated by Mockito 5.4.4 from annotations
// in webview_flutter_wkwebview/test/legacy/web_kit_cookie_manager_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart'
as _i4;
import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.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: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeWKHttpCookieStore_0 extends _i1.SmartFake
implements _i2.WKHttpCookieStore {
_FakeWKHttpCookieStore_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeWKWebsiteDataStore_1 extends _i1.SmartFake
implements _i2.WKWebsiteDataStore {
_FakeWKWebsiteDataStore_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [WKHttpCookieStore].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockWKHttpCookieStore extends _i1.Mock implements _i2.WKHttpCookieStore {
MockWKHttpCookieStore() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<void> setCookie(_i4.NSHttpCookie? cookie) => (super.noSuchMethod(
Invocation.method(
#setCookie,
[cookie],
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
@override
_i2.WKHttpCookieStore copy() => (super.noSuchMethod(
Invocation.method(
#copy,
[],
),
returnValue: _FakeWKHttpCookieStore_0(
this,
Invocation.method(
#copy,
[],
),
),
) as _i2.WKHttpCookieStore);
@override
_i3.Future<void> addObserver(
_i4.NSObject? observer, {
required String? keyPath,
required Set<_i4.NSKeyValueObservingOptions>? options,
}) =>
(super.noSuchMethod(
Invocation.method(
#addObserver,
[observer],
{
#keyPath: keyPath,
#options: options,
},
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
@override
_i3.Future<void> removeObserver(
_i4.NSObject? observer, {
required String? keyPath,
}) =>
(super.noSuchMethod(
Invocation.method(
#removeObserver,
[observer],
{#keyPath: keyPath},
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
}
/// A class which mocks [WKWebsiteDataStore].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockWKWebsiteDataStore extends _i1.Mock
implements _i2.WKWebsiteDataStore {
MockWKWebsiteDataStore() {
_i1.throwOnMissingStub(this);
}
@override
_i2.WKHttpCookieStore get httpCookieStore => (super.noSuchMethod(
Invocation.getter(#httpCookieStore),
returnValue: _FakeWKHttpCookieStore_0(
this,
Invocation.getter(#httpCookieStore),
),
) as _i2.WKHttpCookieStore);
@override
_i3.Future<bool> removeDataOfTypes(
Set<_i2.WKWebsiteDataType>? dataTypes,
DateTime? since,
) =>
(super.noSuchMethod(
Invocation.method(
#removeDataOfTypes,
[
dataTypes,
since,
],
),
returnValue: _i3.Future<bool>.value(false),
) as _i3.Future<bool>);
@override
_i2.WKWebsiteDataStore copy() => (super.noSuchMethod(
Invocation.method(
#copy,
[],
),
returnValue: _FakeWKWebsiteDataStore_1(
this,
Invocation.method(
#copy,
[],
),
),
) as _i2.WKWebsiteDataStore);
@override
_i3.Future<void> addObserver(
_i4.NSObject? observer, {
required String? keyPath,
required Set<_i4.NSKeyValueObservingOptions>? options,
}) =>
(super.noSuchMethod(
Invocation.method(
#addObserver,
[observer],
{
#keyPath: keyPath,
#options: options,
},
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
@override
_i3.Future<void> removeObserver(
_i4.NSObject? observer, {
required String? keyPath,
}) =>
(super.noSuchMethod(
Invocation.method(
#removeObserver,
[observer],
{#keyPath: keyPath},
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
}
| packages/packages/webview_flutter/webview_flutter_wkwebview/test/legacy/web_kit_cookie_manager_test.mocks.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/test/legacy/web_kit_cookie_manager_test.mocks.dart",
"repo_id": "packages",
"token_count": 2529
} | 1,331 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:webview_flutter_wkwebview/src/common/instance_manager.dart';
import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart';
import 'package:webview_flutter_wkwebview/src/ui_kit/ui_kit.dart';
import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart';
import 'package:webview_flutter_wkwebview/src/webkit_proxy.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
import 'webkit_webview_controller_test.mocks.dart'
show MockUIScrollViewDelegate;
import 'webkit_webview_widget_test.mocks.dart';
@GenerateMocks(<Type>[WKUIDelegate, WKWebViewConfiguration])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('WebKitWebViewWidget', () {
testWidgets('build', (WidgetTester tester) async {
final InstanceManager testInstanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final WebKitWebViewController controller =
createTestWebViewController(testInstanceManager);
final WebKitWebViewWidget widget = WebKitWebViewWidget(
WebKitWebViewWidgetCreationParams(
key: const Key('keyValue'),
controller: controller,
instanceManager: testInstanceManager,
),
);
await tester.pumpWidget(
Builder(builder: (BuildContext context) => widget.build(context)),
);
expect(find.byType(UiKitView), findsOneWidget);
expect(find.byKey(const Key('keyValue')), findsOneWidget);
});
testWidgets('Key of the PlatformView changes when the controller changes',
(WidgetTester tester) async {
final InstanceManager testInstanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
// Pump WebViewWidget with first controller.
final WebKitWebViewController controller1 =
createTestWebViewController(testInstanceManager);
final WebKitWebViewWidget webViewWidget = WebKitWebViewWidget(
WebKitWebViewWidgetCreationParams(
controller: controller1,
instanceManager: testInstanceManager,
),
);
await tester.pumpWidget(
Builder(
builder: (BuildContext context) => webViewWidget.build(context),
),
);
await tester.pumpAndSettle();
expect(
find.byKey(
ValueKey<WebKitWebViewWidgetCreationParams>(
webViewWidget.params as WebKitWebViewWidgetCreationParams,
),
),
findsOneWidget,
);
// Pump WebViewWidget with second controller.
final WebKitWebViewController controller2 =
createTestWebViewController(testInstanceManager);
final WebKitWebViewWidget webViewWidget2 = WebKitWebViewWidget(
WebKitWebViewWidgetCreationParams(
controller: controller2,
instanceManager: testInstanceManager,
),
);
await tester.pumpWidget(
Builder(
builder: (BuildContext context) => webViewWidget2.build(context),
),
);
await tester.pumpAndSettle();
expect(webViewWidget.params != webViewWidget2.params, isTrue);
expect(
find.byKey(
ValueKey<WebKitWebViewWidgetCreationParams>(
webViewWidget.params as WebKitWebViewWidgetCreationParams,
),
),
findsNothing,
);
expect(
find.byKey(
ValueKey<WebKitWebViewWidgetCreationParams>(
webViewWidget2.params as WebKitWebViewWidgetCreationParams,
),
),
findsOneWidget,
);
});
testWidgets(
'Key of the PlatformView is the same when the creation params are equal',
(WidgetTester tester) async {
final InstanceManager testInstanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final WebKitWebViewController controller =
createTestWebViewController(testInstanceManager);
final WebKitWebViewWidget webViewWidget = WebKitWebViewWidget(
WebKitWebViewWidgetCreationParams(
controller: controller,
instanceManager: testInstanceManager,
),
);
await tester.pumpWidget(
Builder(
builder: (BuildContext context) => webViewWidget.build(context),
),
);
await tester.pumpAndSettle();
expect(
find.byKey(
ValueKey<WebKitWebViewWidgetCreationParams>(
webViewWidget.params as WebKitWebViewWidgetCreationParams,
),
),
findsOneWidget,
);
final WebKitWebViewWidget webViewWidget2 = WebKitWebViewWidget(
WebKitWebViewWidgetCreationParams(
controller: controller,
instanceManager: testInstanceManager,
),
);
await tester.pumpWidget(
Builder(
builder: (BuildContext context) => webViewWidget2.build(context),
),
);
await tester.pumpAndSettle();
// Can find the new widget with the key of the first widget.
expect(
find.byKey(
ValueKey<WebKitWebViewWidgetCreationParams>(
webViewWidget.params as WebKitWebViewWidgetCreationParams,
),
),
findsOneWidget,
);
});
});
}
WebKitWebViewController createTestWebViewController(
InstanceManager testInstanceManager,
) {
return WebKitWebViewController(
WebKitWebViewControllerCreationParams(
webKitProxy: WebKitProxy(createWebView: (
WKWebViewConfiguration configuration, {
void Function(
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
)? observeValue,
InstanceManager? instanceManager,
}) {
final WKWebView webView = WKWebView.detached(
instanceManager: testInstanceManager,
);
testInstanceManager.addDartCreatedInstance(webView);
return webView;
}, createWebViewConfiguration: ({InstanceManager? instanceManager}) {
return MockWKWebViewConfiguration();
}, createUIDelegate: ({
dynamic onCreateWebView,
dynamic requestMediaCapturePermission,
dynamic runJavaScriptAlertDialog,
dynamic runJavaScriptConfirmDialog,
dynamic runJavaScriptTextInputDialog,
InstanceManager? instanceManager,
}) {
final MockWKUIDelegate mockWKUIDelegate = MockWKUIDelegate();
when(mockWKUIDelegate.copy()).thenReturn(MockWKUIDelegate());
testInstanceManager.addDartCreatedInstance(mockWKUIDelegate);
return mockWKUIDelegate;
}, createUIScrollViewDelegate: ({
void Function(UIScrollView, double, double)? scrollViewDidScroll,
}) {
final MockUIScrollViewDelegate mockScrollViewDelegate =
MockUIScrollViewDelegate();
when(mockScrollViewDelegate.copy())
.thenReturn(MockUIScrollViewDelegate());
testInstanceManager.addDartCreatedInstance(mockScrollViewDelegate);
return mockScrollViewDelegate;
}),
),
);
}
| packages/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_webview_widget_test.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_webview_widget_test.dart",
"repo_id": "packages",
"token_count": 2976
} | 1,332 |
# Can't use Flutter integration tests due to native modal UI.
- file_selector
| packages/script/configs/exclude_integration_android.yaml/0 | {
"file_path": "packages/script/configs/exclude_integration_android.yaml",
"repo_id": "packages",
"token_count": 22
} | 1,333 |
// 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' as io;
import 'package:file/file.dart';
import 'package:yaml/yaml.dart';
import 'common/output_utils.dart';
import 'common/package_looping_command.dart';
import 'common/repository_package.dart';
/// A command to run Dart analysis on packages.
class AnalyzeCommand extends PackageLoopingCommand {
/// Creates a analysis command instance.
AnalyzeCommand(
super.packagesDir, {
super.processRunner,
super.platform,
}) {
argParser.addMultiOption(_customAnalysisFlag,
help:
'Directories (comma separated) that are allowed to have their own '
'analysis options.\n\n'
'Alternately, a list of one or more YAML files that contain a list '
'of allowed directories.',
defaultsTo: <String>[]);
argParser.addOption(_analysisSdk,
valueHelp: 'dart-sdk',
help: 'An optional path to a Dart SDK; this is used to override the '
'SDK used to provide analysis.');
argParser.addFlag(_downgradeFlag,
help: 'Runs "flutter pub downgrade" before analysis to verify that '
'the minimum constraints are sufficiently new for APIs used.');
argParser.addFlag(_libOnlyFlag,
help: 'Only analyze the lib/ directory of the main package, not the '
'entire package.');
argParser.addFlag(_skipIfResolvingFailsFlag,
help: 'If resolution fails, skip the package. This is only '
'intended to be used with pathified analysis, where a resolver '
'failure indicates that no out-of-band failure can result anyway.',
hide: true);
}
static const String _customAnalysisFlag = 'custom-analysis';
static const String _downgradeFlag = 'downgrade';
static const String _libOnlyFlag = 'lib-only';
static const String _analysisSdk = 'analysis-sdk';
static const String _skipIfResolvingFailsFlag = 'skip-if-resolving-fails';
late String _dartBinaryPath;
Set<String> _allowedCustomAnalysisDirectories = const <String>{};
@override
final String name = 'analyze';
@override
final String description = 'Analyzes all packages using dart analyze.\n\n'
'This command requires "dart" and "flutter" to be in your path.';
@override
final bool hasLongOutput = false;
/// Checks that there are no unexpected analysis_options.yaml files.
bool _hasUnexpecetdAnalysisOptions(RepositoryPackage package) {
final List<FileSystemEntity> files =
package.directory.listSync(recursive: true, followLinks: false);
for (final FileSystemEntity file in files) {
if (file.basename != 'analysis_options.yaml' &&
file.basename != '.analysis_options') {
continue;
}
final bool allowed = _allowedCustomAnalysisDirectories.any(
(String directory) =>
directory.isNotEmpty &&
path.isWithin(
packagesDir.childDirectory(directory).path, file.path));
if (allowed) {
continue;
}
printError(
'Found an extra analysis_options.yaml at ${file.absolute.path}.');
printError(
'If this was deliberate, pass the package to the analyze command '
'with the --$_customAnalysisFlag flag and try again.');
return true;
}
return false;
}
@override
Future<void> initializeRun() async {
_allowedCustomAnalysisDirectories =
getStringListArg(_customAnalysisFlag).expand<String>((String item) {
if (item.endsWith('.yaml')) {
final File file = packagesDir.fileSystem.file(item);
final Object? yaml = loadYaml(file.readAsStringSync());
if (yaml == null) {
return <String>[];
}
return (yaml as YamlList).toList().cast<String>();
}
return <String>[item];
}).toSet();
// Use the Dart SDK override if one was passed in.
final String? dartSdk = argResults![_analysisSdk] as String?;
_dartBinaryPath =
dartSdk == null ? 'dart' : path.join(dartSdk, 'bin', 'dart');
}
@override
Future<PackageResult> runForPackage(RepositoryPackage package) async {
final bool libOnly = getBoolArg(_libOnlyFlag);
if (libOnly && !package.libDirectory.existsSync()) {
return PackageResult.skip('No lib/ directory.');
}
if (getBoolArg(_downgradeFlag)) {
if (!await _runPubCommand(package, 'downgrade')) {
return PackageResult.fail(<String>['Unable to downgrade dependencies']);
}
}
// Analysis runs over the package and all subpackages (unless only lib/ is
// being analyzed), so all of them need `flutter pub get` run before
// analyzing. `example` packages can be skipped since 'flutter packages get'
// automatically runs `pub get` in examples as part of handling the parent
// directory.
final List<RepositoryPackage> packagesToGet = <RepositoryPackage>[
package,
if (!libOnly) ...await getSubpackages(package).toList(),
];
for (final RepositoryPackage packageToGet in packagesToGet) {
if (packageToGet.directory.basename != 'example' ||
!RepositoryPackage(packageToGet.directory.parent)
.pubspecFile
.existsSync()) {
if (!await _runPubCommand(packageToGet, 'get')) {
if (getBoolArg(_skipIfResolvingFailsFlag)) {
// Re-run, capturing output, to see if the failure was a resolver
// failure. (This is slightly inefficient, but this should be a
// very rare case.)
const String resolverFailureMessage = 'version solving failed';
final io.ProcessResult result = await processRunner.run(
flutterCommand, <String>['pub', 'get'],
workingDir: packageToGet.directory);
if ((result.stderr as String).contains(resolverFailureMessage) ||
(result.stdout as String).contains(resolverFailureMessage)) {
logWarning('Skipping package due to pub resolution failure.');
return PackageResult.skip('Resolution failed.');
}
}
return PackageResult.fail(<String>['Unable to get dependencies']);
}
}
}
if (_hasUnexpecetdAnalysisOptions(package)) {
return PackageResult.fail(<String>['Unexpected local analysis options']);
}
final int exitCode = await processRunner.runAndStream(_dartBinaryPath,
<String>['analyze', '--fatal-infos', if (libOnly) 'lib'],
workingDir: package.directory);
if (exitCode != 0) {
return PackageResult.fail();
}
return PackageResult.success();
}
Future<bool> _runPubCommand(RepositoryPackage package, String command) async {
final int exitCode = await processRunner.runAndStream(
flutterCommand, <String>['pub', command],
workingDir: package.directory);
return exitCode == 0;
}
}
| packages/script/tool/lib/src/analyze_command.dart/0 | {
"file_path": "packages/script/tool/lib/src/analyze_command.dart",
"repo_id": "packages",
"token_count": 2611
} | 1,334 |
// 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:convert';
import 'dart:io' as io;
import 'package:file/file.dart';
import 'output_utils.dart';
import 'process_runner.dart';
const String _xcodeBuildCommand = 'xcodebuild';
const String _xcRunCommand = 'xcrun';
/// A utility class for interacting with the installed version of Xcode.
class Xcode {
/// Creates an instance that runs commands with the given [processRunner].
///
/// If [log] is true, commands run by this instance will long various status
/// messages.
Xcode({
this.processRunner = const ProcessRunner(),
this.log = false,
});
/// The [ProcessRunner] used to run commands. Overridable for testing.
final ProcessRunner processRunner;
/// Whether or not to log when running commands.
final bool log;
/// Runs an `xcodebuild` in [directory] with the given parameters.
Future<int> runXcodeBuild(
Directory directory, {
List<String> actions = const <String>['build'],
required String workspace,
required String scheme,
String? configuration,
List<String> extraFlags = const <String>[],
}) {
final List<String> args = <String>[
_xcodeBuildCommand,
...actions,
...<String>['-workspace', workspace],
...<String>['-scheme', scheme],
if (configuration != null) ...<String>['-configuration', configuration],
...extraFlags,
];
final String completeTestCommand = '$_xcRunCommand ${args.join(' ')}';
if (log) {
print(completeTestCommand);
}
return processRunner.runAndStream(_xcRunCommand, args,
workingDir: directory);
}
/// Returns true if [project], which should be an .xcodeproj directory,
/// contains a target called [target], false if it does not, and null if the
/// check fails (e.g., if [project] is not an Xcode project).
Future<bool?> projectHasTarget(Directory project, String target) async {
final io.ProcessResult result =
await processRunner.run(_xcRunCommand, <String>[
_xcodeBuildCommand,
'-list',
'-json',
'-project',
project.path,
]);
if (result.exitCode != 0) {
return null;
}
Map<String, dynamic>? projectInfo;
try {
projectInfo = (jsonDecode(result.stdout as String)
as Map<String, dynamic>)['project'] as Map<String, dynamic>?;
} on FormatException {
return null;
}
if (projectInfo == null) {
return null;
}
final List<String>? targets =
(projectInfo['targets'] as List<dynamic>?)?.cast<String>();
return targets?.contains(target) ?? false;
}
/// Returns the newest available simulator (highest OS version, with ties
/// broken in favor of newest device), if any.
Future<String?> findBestAvailableIphoneSimulator() async {
final List<String> findSimulatorsArguments = <String>[
'simctl',
'list',
'devices',
'runtimes',
'available',
'--json',
];
final String findSimulatorCompleteCommand =
'$_xcRunCommand ${findSimulatorsArguments.join(' ')}';
if (log) {
print('Looking for available simulators...');
print(findSimulatorCompleteCommand);
}
final io.ProcessResult findSimulatorsResult =
await processRunner.run(_xcRunCommand, findSimulatorsArguments);
if (findSimulatorsResult.exitCode != 0) {
if (log) {
printError(
'Error occurred while running "$findSimulatorCompleteCommand":\n'
'${findSimulatorsResult.stderr}');
}
return null;
}
final Map<String, dynamic> simulatorListJson =
jsonDecode(findSimulatorsResult.stdout as String)
as Map<String, dynamic>;
final List<Map<String, dynamic>> runtimes =
(simulatorListJson['runtimes'] as List<dynamic>)
.cast<Map<String, dynamic>>();
final Map<String, Object> devices =
(simulatorListJson['devices'] as Map<String, dynamic>)
.cast<String, Object>();
if (runtimes.isEmpty || devices.isEmpty) {
return null;
}
String? id;
// Looking for runtimes, trying to find one with highest OS version.
for (final Map<String, dynamic> rawRuntimeMap in runtimes.reversed) {
final Map<String, Object> runtimeMap =
rawRuntimeMap.cast<String, Object>();
if ((runtimeMap['name'] as String?)?.contains('iOS') != true) {
continue;
}
final String? runtimeID = runtimeMap['identifier'] as String?;
if (runtimeID == null) {
continue;
}
final List<Map<String, dynamic>>? devicesForRuntime =
(devices[runtimeID] as List<dynamic>?)?.cast<Map<String, dynamic>>();
if (devicesForRuntime == null || devicesForRuntime.isEmpty) {
continue;
}
// Looking for runtimes, trying to find latest version of device.
for (final Map<String, dynamic> rawDevice in devicesForRuntime.reversed) {
final Map<String, Object> device = rawDevice.cast<String, Object>();
id = device['udid'] as String?;
if (id == null) {
continue;
}
if (log) {
print('device selected: $device');
}
return id;
}
}
return null;
}
}
| packages/script/tool/lib/src/common/xcode.dart/0 | {
"file_path": "packages/script/tool/lib/src/common/xcode.dart",
"repo_id": "packages",
"token_count": 1985
} | 1,335 |
// 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/file.dart';
import 'package:path/path.dart' as p;
import 'package:pub_semver/pub_semver.dart';
import 'package:pubspec_parse/pubspec_parse.dart';
import 'package:yaml/yaml.dart';
import 'package:yaml_edit/yaml_edit.dart';
import 'common/core.dart';
import 'common/git_version_finder.dart';
import 'common/output_utils.dart';
import 'common/package_command.dart';
import 'common/repository_package.dart';
const int _exitPackageNotFound = 3;
/// Converts all dependencies on target packages to path-based dependencies.
///
/// This is to allow for pre-publish testing of changes that could affect other
/// packages in the repository. For instance, this allows for catching cases
/// where a non-breaking change to a platform interface package of a federated
/// plugin would cause post-publish analyzer failures in another package of that
/// plugin.
class MakeDepsPathBasedCommand extends PackageCommand {
/// Creates an instance of the command to convert selected dependencies to
/// path-based.
MakeDepsPathBasedCommand(
super.packagesDir, {
super.gitDir,
}) {
argParser.addMultiOption(_targetDependenciesArg,
help:
'The names of the packages to convert to path-based dependencies.\n'
'Ignored if --$_targetDependenciesWithNonBreakingUpdatesArg is '
'passed.',
valueHelp: 'some_package');
argParser.addFlag(
_targetDependenciesWithNonBreakingUpdatesArg,
help: 'Causes all packages that have non-breaking version changes '
'when compared against the git base to be treated as target '
'packages.\n\nOnly packages with dependency constraints that allow '
'the new version of a given target package will be updated. E.g., '
'if package A depends on B: ^1.0.0, and B is updated from 2.0.0 to '
'2.0.1, the dependency on B in A will not become path based.',
);
}
static const String _targetDependenciesArg = 'target-dependencies';
static const String _targetDependenciesWithNonBreakingUpdatesArg =
'target-dependencies-with-non-breaking-updates';
// The comment to add to temporary dependency overrides.
//
// Includes a reference to the docs so that reviewers who aren't familiar with
// the federated plugin change process don't think it's a mistake.
static const String _dependencyOverrideWarningComment =
'# FOR TESTING AND INITIAL REVIEW ONLY. DO NOT MERGE.\n'
'# See https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#changing-federated-plugins';
@override
final String name = 'make-deps-path-based';
@override
final String description =
'Converts package dependencies to path-based references.';
@override
Future<void> run() async {
final bool targetByVersion =
getBoolArg(_targetDependenciesWithNonBreakingUpdatesArg);
final Set<String> targetDependencies = targetByVersion
? await _getNonBreakingUpdatePackages()
: getStringListArg(_targetDependenciesArg).toSet();
if (targetDependencies.isEmpty) {
print('No target dependencies; nothing to do.');
return;
}
print('Rewriting references to: ${targetDependencies.join(', ')}...');
final Map<String, RepositoryPackage> localDependencyPackages =
_findLocalPackages(targetDependencies);
// For targeting by version change, find the versions of the target
// dependencies.
final Map<String, Version?> localPackageVersions = targetByVersion
? <String, Version?>{
for (final RepositoryPackage package
in localDependencyPackages.values)
package.directory.basename: package.parsePubspec().version
}
: <String, Version>{};
final String repoRootPath = (await gitDir).path;
for (final File pubspec in await _getAllPubspecs()) {
final String displayPath = p.posix.joinAll(
path.split(path.relative(pubspec.absolute.path, from: repoRootPath)));
final bool changed = await _addDependencyOverridesIfNecessary(
RepositoryPackage(pubspec.parent),
localDependencyPackages,
localPackageVersions);
if (changed) {
print(' Modified $displayPath');
}
}
}
Map<String, RepositoryPackage> _findLocalPackages(Set<String> packageNames) {
final Map<String, RepositoryPackage> targets =
<String, RepositoryPackage>{};
for (final String packageName in packageNames) {
final Directory topLevelCandidate =
packagesDir.childDirectory(packageName);
// If packages/<packageName>/ exists, then either that directory is the
// package, or packages/<packageName>/<packageName>/ exists and is the
// package (in the case of a federated plugin).
if (topLevelCandidate.existsSync()) {
final Directory appFacingCandidate =
topLevelCandidate.childDirectory(packageName);
targets[packageName] = RepositoryPackage(appFacingCandidate.existsSync()
? appFacingCandidate
: topLevelCandidate);
continue;
}
// Check for a match in the third-party packages directory.
final Directory thirdPartyCandidate =
thirdPartyPackagesDir.childDirectory(packageName);
if (thirdPartyCandidate.existsSync()) {
targets[packageName] = RepositoryPackage(thirdPartyCandidate);
continue;
}
// If there is no packages/<packageName> directory, then either the
// packages doesn't exist, or it is a sub-package of a federated plugin.
// If it's the latter, it will be a directory whose name is a prefix.
for (final FileSystemEntity entity in packagesDir.listSync()) {
if (entity is Directory && packageName.startsWith(entity.basename)) {
final Directory subPackageCandidate =
entity.childDirectory(packageName);
if (subPackageCandidate.existsSync()) {
targets[packageName] = RepositoryPackage(subPackageCandidate);
break;
}
}
}
if (!targets.containsKey(packageName)) {
printError('Unable to find package "$packageName"');
throw ToolExit(_exitPackageNotFound);
}
}
return targets;
}
/// If [pubspecFile] has any dependencies on packages in [localDependencies],
/// adds dependency_overrides entries to redirect them to the local version
/// using path-based dependencies.
///
/// Returns true if any overrides were added.
///
/// If [additionalPackagesToOverride] are provided, they will get
/// dependency_overrides even if there is no direct dependency. This is
/// useful for overriding transitive dependencies.
Future<bool> _addDependencyOverridesIfNecessary(
RepositoryPackage package,
Map<String, RepositoryPackage> localDependencies,
Map<String, Version?> versions, {
Iterable<String> additionalPackagesToOverride = const <String>{},
}) async {
final String pubspecContents = package.pubspecFile.readAsStringSync();
// Returns true if [dependency] allows a dependency on [version]. Always
// returns true if [version] is null, to err on the side of assuming it
// will apply in cases where we don't have a target version.
bool allowsVersion(Dependency dependency, Version? version) {
return version == null ||
dependency is! HostedDependency ||
dependency.version.allows(version);
}
// Determine the dependencies to be overridden.
final Pubspec pubspec = Pubspec.parse(pubspecContents);
final Iterable<String> combinedDependencies = <String>[
// Filter out any dependencies with version constraint that wouldn't allow
// the target if published.
...<MapEntry<String, Dependency>>[
...pubspec.dependencies.entries,
...pubspec.devDependencies.entries,
]
.where((MapEntry<String, Dependency> element) =>
allowsVersion(element.value, versions[element.key]))
.map((MapEntry<String, Dependency> entry) => entry.key),
...additionalPackagesToOverride,
];
final List<String> packagesToOverride = combinedDependencies
.where(
(String packageName) => localDependencies.containsKey(packageName))
.toList();
// Sort the combined list to avoid sort_pub_dependencies lint violations.
packagesToOverride.sort();
if (packagesToOverride.isEmpty) {
return false;
}
// Find the relative path to the common base.
final String commonBasePath = packagesDir.path;
final int packageDepth = path
.split(path.relative(package.directory.absolute.path,
from: commonBasePath))
.length;
final List<String> relativeBasePathComponents =
List<String>.filled(packageDepth, '..');
// Add the overrides.
final YamlEditor editablePubspec = YamlEditor(pubspecContents);
final YamlNode root = editablePubspec.parseAt(<String>[]);
const String dependencyOverridesKey = 'dependency_overrides';
// Ensure that there's a `dependencyOverridesKey` entry to update.
if ((root as YamlMap)[dependencyOverridesKey] == null) {
editablePubspec.update(<String>[dependencyOverridesKey], YamlMap());
}
for (final String packageName in packagesToOverride) {
// Find the relative path from the common base to the local package.
final List<String> repoRelativePathComponents = path.split(path.relative(
localDependencies[packageName]!.path,
from: commonBasePath));
editablePubspec.update(<String>[
dependencyOverridesKey,
packageName
], <String, String>{
'path': p.posix.joinAll(<String>[
...relativeBasePathComponents,
...repoRelativePathComponents,
])
});
}
// Add the warning if it's not already there.
String newContent = editablePubspec.toString();
if (!newContent.contains(_dependencyOverrideWarningComment)) {
newContent = newContent.replaceFirst('$dependencyOverridesKey:', '''
$_dependencyOverrideWarningComment
$dependencyOverridesKey:
''');
}
// Write the new pubspec.
package.pubspecFile.writeAsStringSync(newContent);
// Update any examples. This is important for cases like integration tests
// of app-facing packages in federated plugins, where the app-facing
// package depends directly on the implementation packages, but the
// example app doesn't. Since integration tests are run in the example app,
// it needs the overrides in order for tests to pass.
for (final RepositoryPackage example in package.getExamples()) {
await _addDependencyOverridesIfNecessary(
example, localDependencies, versions,
additionalPackagesToOverride: packagesToOverride);
}
return true;
}
/// Returns all pubspecs anywhere under the packages directory.
Future<List<File>> _getAllPubspecs() => packagesDir.parent
.list(recursive: true, followLinks: false)
.where((FileSystemEntity entity) =>
entity is File && p.basename(entity.path) == 'pubspec.yaml')
.map((FileSystemEntity file) => file as File)
.toList();
/// Returns all packages that have non-breaking published changes (i.e., a
/// minor or bugfix version change) relative to the git comparison base.
///
/// Prints status information about what was checked for ease of auditing logs
/// in CI.
Future<Set<String>> _getNonBreakingUpdatePackages() async {
final GitVersionFinder gitVersionFinder = await retrieveVersionFinder();
final String baseSha = await gitVersionFinder.getBaseSha();
print('Finding changed packages relative to "$baseSha"...');
final Set<String> changedPackages = <String>{};
for (final String changedPath in await gitVersionFinder.getChangedFiles()) {
// Git output always uses Posix paths.
final List<String> allComponents = p.posix.split(changedPath);
// Only pubspec changes are potential publishing events.
if (allComponents.last != 'pubspec.yaml' ||
allComponents.contains('example')) {
continue;
}
if (!allComponents.contains(packagesDir.basename)) {
print(' Skipping $changedPath; not in packages directory.');
continue;
}
final RepositoryPackage package =
RepositoryPackage(packagesDir.fileSystem.file(changedPath).parent);
// Ignored deleted packages, as they won't be published.
if (!package.pubspecFile.existsSync()) {
final String directoryName = p.posix.joinAll(path.split(path.relative(
package.directory.absolute.path,
from: packagesDir.path)));
print(' Skipping $directoryName; deleted.');
continue;
}
final String packageName = package.parsePubspec().name;
if (!await _hasNonBreakingVersionChange(package)) {
// Log packages that had pubspec changes but weren't included for ease
// of auditing CI.
print(' Skipping $packageName; no non-breaking version change.');
continue;
}
changedPackages.add(packageName);
}
return changedPackages;
}
Future<bool> _hasNonBreakingVersionChange(RepositoryPackage package) async {
final Pubspec pubspec = package.parsePubspec();
if (pubspec.publishTo == 'none') {
return false;
}
final String pubspecGitPath = p.posix.joinAll(path.split(path.relative(
package.pubspecFile.absolute.path,
from: (await gitDir).path)));
final GitVersionFinder gitVersionFinder = await retrieveVersionFinder();
final Version? previousVersion =
await gitVersionFinder.getPackageVersion(pubspecGitPath);
if (previousVersion == null) {
// The plugin is new, so nothing can be depending on it yet.
return false;
}
final Version newVersion = pubspec.version!;
if ((newVersion.major > 0 && newVersion.major != previousVersion.major) ||
(newVersion.major == 0 && newVersion.minor != previousVersion.minor)) {
// Breaking changes aren't targeted since they won't be picked up
// automatically.
return false;
}
return newVersion != previousVersion;
}
}
| packages/script/tool/lib/src/make_deps_path_based_command.dart/0 | {
"file_path": "packages/script/tool/lib/src/make_deps_path_based_command.dart",
"repo_id": "packages",
"token_count": 4972
} | 1,336 |
// 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:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_plugin_tools/src/analyze_command.dart';
import 'package:flutter_plugin_tools/src/common/core.dart';
import 'package:test/test.dart';
import 'mocks.dart';
import 'util.dart';
void main() {
late FileSystem fileSystem;
late MockPlatform mockPlatform;
late Directory packagesDir;
late RecordingProcessRunner processRunner;
late CommandRunner<void> runner;
setUp(() {
fileSystem = MemoryFileSystem();
mockPlatform = MockPlatform();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
processRunner = RecordingProcessRunner();
final AnalyzeCommand analyzeCommand = AnalyzeCommand(
packagesDir,
processRunner: processRunner,
platform: mockPlatform,
);
runner = CommandRunner<void>('analyze_command', 'Test for analyze_command');
runner.addCommand(analyzeCommand);
});
test('analyzes all packages', () async {
final RepositoryPackage package1 = createFakePackage('a', packagesDir);
final RepositoryPackage plugin2 = createFakePlugin('b', packagesDir);
await runCapturingPrint(runner, <String>['analyze']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall('flutter', const <String>['pub', 'get'], package1.path),
ProcessCall('dart', const <String>['analyze', '--fatal-infos'],
package1.path),
ProcessCall('flutter', const <String>['pub', 'get'], plugin2.path),
ProcessCall(
'dart', const <String>['analyze', '--fatal-infos'], plugin2.path),
]));
});
test('skips flutter pub get for examples', () async {
final RepositoryPackage plugin1 = createFakePlugin('a', packagesDir);
await runCapturingPrint(runner, <String>['analyze']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall('flutter', const <String>['pub', 'get'], plugin1.path),
ProcessCall(
'dart', const <String>['analyze', '--fatal-infos'], plugin1.path),
]));
});
test('runs flutter pub get for non-example subpackages', () async {
final RepositoryPackage mainPackage = createFakePackage('a', packagesDir);
final Directory otherPackagesDir =
mainPackage.directory.childDirectory('other_packages');
final RepositoryPackage subpackage1 =
createFakePackage('subpackage1', otherPackagesDir);
final RepositoryPackage subpackage2 =
createFakePackage('subpackage2', otherPackagesDir);
await runCapturingPrint(runner, <String>['analyze']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'flutter', const <String>['pub', 'get'], mainPackage.path),
ProcessCall(
'flutter', const <String>['pub', 'get'], subpackage1.path),
ProcessCall(
'flutter', const <String>['pub', 'get'], subpackage2.path),
ProcessCall('dart', const <String>['analyze', '--fatal-infos'],
mainPackage.path),
]));
});
test('passes lib/ directory with --lib-only', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
await runCapturingPrint(runner, <String>['analyze', '--lib-only']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall('flutter', const <String>['pub', 'get'], package.path),
ProcessCall('dart', const <String>['analyze', '--fatal-infos', 'lib'],
package.path),
]));
});
test('skips when missing lib/ directory with --lib-only', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.libDirectory.deleteSync();
final List<String> output =
await runCapturingPrint(runner, <String>['analyze', '--lib-only']);
expect(processRunner.recordedCalls, isEmpty);
expect(
output,
containsAllInOrder(<Matcher>[
contains('SKIPPING: No lib/ directory'),
]),
);
});
test(
'does not run flutter pub get for non-example subpackages with --lib-only',
() async {
final RepositoryPackage mainPackage = createFakePackage('a', packagesDir);
final Directory otherPackagesDir =
mainPackage.directory.childDirectory('other_packages');
createFakePackage('subpackage1', otherPackagesDir);
createFakePackage('subpackage2', otherPackagesDir);
await runCapturingPrint(runner, <String>['analyze', '--lib-only']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'flutter', const <String>['pub', 'get'], mainPackage.path),
ProcessCall('dart', const <String>['analyze', '--fatal-infos', 'lib'],
mainPackage.path),
]));
});
test("don't elide a non-contained example package", () async {
final RepositoryPackage plugin1 = createFakePlugin('a', packagesDir);
final RepositoryPackage plugin2 = createFakePlugin('example', packagesDir);
await runCapturingPrint(runner, <String>['analyze']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall('flutter', const <String>['pub', 'get'], plugin1.path),
ProcessCall(
'dart', const <String>['analyze', '--fatal-infos'], plugin1.path),
ProcessCall('flutter', const <String>['pub', 'get'], plugin2.path),
ProcessCall(
'dart', const <String>['analyze', '--fatal-infos'], plugin2.path),
]));
});
test('uses a separate analysis sdk', () async {
final RepositoryPackage plugin = createFakePlugin('a', packagesDir);
await runCapturingPrint(
runner, <String>['analyze', '--analysis-sdk', 'foo/bar/baz']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'flutter',
const <String>['pub', 'get'],
plugin.path,
),
ProcessCall(
'foo/bar/baz/bin/dart',
const <String>['analyze', '--fatal-infos'],
plugin.path,
),
]),
);
});
test('downgrades first when requested', () async {
final RepositoryPackage plugin = createFakePlugin('a', packagesDir);
await runCapturingPrint(runner, <String>['analyze', '--downgrade']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'flutter',
const <String>['pub', 'downgrade'],
plugin.path,
),
ProcessCall(
'flutter',
const <String>['pub', 'get'],
plugin.path,
),
ProcessCall(
'dart',
const <String>['analyze', '--fatal-infos'],
plugin.path,
),
]),
);
});
group('verifies analysis settings', () {
test('fails analysis_options.yaml', () async {
createFakePlugin('foo', packagesDir,
extraFiles: <String>['analysis_options.yaml']);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['analyze'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Found an extra analysis_options.yaml at /packages/foo/analysis_options.yaml'),
contains(' foo:\n'
' Unexpected local analysis options'),
]),
);
});
test('fails .analysis_options', () async {
createFakePlugin('foo', packagesDir,
extraFiles: <String>['.analysis_options']);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['analyze'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Found an extra analysis_options.yaml at /packages/foo/.analysis_options'),
contains(' foo:\n'
' Unexpected local analysis options'),
]),
);
});
test('takes an allow list', () async {
final RepositoryPackage plugin = createFakePlugin('foo', packagesDir,
extraFiles: <String>['analysis_options.yaml']);
await runCapturingPrint(
runner, <String>['analyze', '--custom-analysis', 'foo']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall('flutter', const <String>['pub', 'get'], plugin.path),
ProcessCall('dart', const <String>['analyze', '--fatal-infos'],
plugin.path),
]));
});
test('ignores analysis options in the plugin .symlinks directory',
() async {
final RepositoryPackage plugin = createFakePlugin('foo', packagesDir,
extraFiles: <String>['analysis_options.yaml']);
final RepositoryPackage includingPackage =
createFakePlugin('bar', packagesDir);
// Simulate the local state of having built 'bar' if it includes 'foo'.
includingPackage.directory
.childDirectory('example')
.childDirectory('ios')
.childLink('.symlinks')
.createSync(plugin.directory.path, recursive: true);
await runCapturingPrint(
runner, <String>['analyze', '--custom-analysis', 'foo']);
});
test('takes an allow config file', () async {
final RepositoryPackage plugin = createFakePlugin('foo', packagesDir,
extraFiles: <String>['analysis_options.yaml']);
final File allowFile = packagesDir.childFile('custom.yaml');
allowFile.writeAsStringSync('- foo');
await runCapturingPrint(
runner, <String>['analyze', '--custom-analysis', allowFile.path]);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall('flutter', const <String>['pub', 'get'], plugin.path),
ProcessCall('dart', const <String>['analyze', '--fatal-infos'],
plugin.path),
]));
});
test('allows an empty config file', () async {
createFakePlugin('foo', packagesDir,
extraFiles: <String>['analysis_options.yaml']);
final File allowFile = packagesDir.childFile('custom.yaml');
allowFile.createSync();
await expectLater(
() => runCapturingPrint(
runner, <String>['analyze', '--custom-analysis', allowFile.path]),
throwsA(isA<ToolExit>()));
});
// See: https://github.com/flutter/flutter/issues/78994
test('takes an empty allow list', () async {
createFakePlugin('foo', packagesDir,
extraFiles: <String>['analysis_options.yaml']);
await expectLater(
() => runCapturingPrint(
runner, <String>['analyze', '--custom-analysis', '']),
throwsA(isA<ToolExit>()));
});
});
test('skips if requested if "pub get" fails in the resolver', () async {
final RepositoryPackage plugin = createFakePlugin('foo', packagesDir);
final FakeProcessInfo failingPubGet = FakeProcessInfo(
MockProcess(
exitCode: 1,
stderr: 'So, because foo depends on both thing_one ^1.0.0 and '
'thing_two from path, version solving failed.'),
<String>['pub', 'get']);
processRunner.mockProcessesForExecutable['flutter'] = <FakeProcessInfo>[
failingPubGet,
// The command re-runs failures when --skip-if-resolver-fails is passed
// to check the output, so provide the same failing outcome.
failingPubGet,
];
final List<String> output = await runCapturingPrint(
runner, <String>['analyze', '--skip-if-resolving-fails']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Skipping package due to pub resolution failure.'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall('flutter', const <String>['pub', 'get'], plugin.path),
ProcessCall('flutter', const <String>['pub', 'get'], plugin.path),
]));
});
test('fails if "pub get" fails', () async {
createFakePlugin('foo', packagesDir);
processRunner.mockProcessesForExecutable['flutter'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['pub', 'get'])
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['analyze'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Unable to get dependencies'),
]),
);
});
test('fails if "pub downgrade" fails', () async {
createFakePlugin('foo', packagesDir);
processRunner.mockProcessesForExecutable['flutter'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['pub', 'downgrade'])
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['analyze', '--downgrade'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Unable to downgrade dependencies'),
]),
);
});
test('fails if "analyze" fails', () async {
createFakePlugin('foo', packagesDir);
processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['analyze'])
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['analyze'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The following packages had errors:'),
contains(' foo'),
]),
);
});
// Ensure that the command used to analyze flutter/plugins in the Dart repo:
// https://github.com/dart-lang/sdk/blob/main/tools/bots/flutter/analyze_flutter_plugins.sh
// continues to work.
//
// DO NOT remove or modify this test without a coordination plan in place to
// modify the script above, as it is run from source, but out-of-repo.
// Contact stuartmorgan or devoncarew for assistance.
test('Dart repo analyze command works', () async {
final RepositoryPackage plugin = createFakePlugin('foo', packagesDir,
extraFiles: <String>['analysis_options.yaml']);
final File allowFile = packagesDir.childFile('custom.yaml');
allowFile.writeAsStringSync('- foo');
await runCapturingPrint(runner, <String>[
// DO NOT change this call; see comment above.
'analyze',
'--analysis-sdk',
'foo/bar/baz',
'--custom-analysis',
allowFile.path
]);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'flutter',
const <String>['pub', 'get'],
plugin.path,
),
ProcessCall(
'foo/bar/baz/bin/dart',
const <String>['analyze', '--fatal-infos'],
plugin.path,
),
]),
);
});
}
| packages/script/tool/test/analyze_command_test.dart/0 | {
"file_path": "packages/script/tool/test/analyze_command_test.dart",
"repo_id": "packages",
"token_count": 6281
} | 1,337 |
// 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:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_plugin_tools/src/common/core.dart';
import 'package:flutter_plugin_tools/src/custom_test_command.dart';
import 'package:test/test.dart';
import 'mocks.dart';
import 'util.dart';
void main() {
late FileSystem fileSystem;
late MockPlatform mockPlatform;
late Directory packagesDir;
late RecordingProcessRunner processRunner;
late CommandRunner<void> runner;
group('posix', () {
setUp(() {
fileSystem = MemoryFileSystem();
mockPlatform = MockPlatform();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
processRunner = RecordingProcessRunner();
final CustomTestCommand analyzeCommand = CustomTestCommand(
packagesDir,
processRunner: processRunner,
platform: mockPlatform,
);
runner = CommandRunner<void>(
'custom_test_command', 'Test for custom_test_command');
runner.addCommand(analyzeCommand);
});
test('runs both new and legacy when both are present', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, extraFiles: <String>[
'tool/run_tests.dart',
'run_tests.sh',
]);
final List<String> output =
await runCapturingPrint(runner, <String>['custom-test']);
expect(
processRunner.recordedCalls,
containsAll(<ProcessCall>[
ProcessCall(package.directory.childFile('run_tests.sh').path,
const <String>[], package.path),
ProcessCall('dart', const <String>['run', 'tool/run_tests.dart'],
package.path),
]));
expect(
output,
containsAllInOrder(<Matcher>[
contains('Ran for 1 package(s)'),
]));
});
test('runs when only new is present', () async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
extraFiles: <String>['tool/run_tests.dart']);
final List<String> output =
await runCapturingPrint(runner, <String>['custom-test']);
expect(
processRunner.recordedCalls,
containsAll(<ProcessCall>[
ProcessCall('dart', const <String>['run', 'tool/run_tests.dart'],
package.path),
]));
expect(
output,
containsAllInOrder(<Matcher>[
contains('Ran for 1 package(s)'),
]));
});
test('runs pub get before running Dart test script', () async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
extraFiles: <String>['tool/run_tests.dart']);
await runCapturingPrint(runner, <String>['custom-test']);
expect(
processRunner.recordedCalls,
containsAll(<ProcessCall>[
ProcessCall('dart', const <String>['pub', 'get'], package.path),
ProcessCall('dart', const <String>['run', 'tool/run_tests.dart'],
package.path),
]));
});
test('runs when only legacy is present', () async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
extraFiles: <String>['run_tests.sh']);
final List<String> output =
await runCapturingPrint(runner, <String>['custom-test']);
expect(
processRunner.recordedCalls,
containsAll(<ProcessCall>[
ProcessCall(package.directory.childFile('run_tests.sh').path,
const <String>[], package.path),
]));
expect(
output,
containsAllInOrder(<Matcher>[
contains('Ran for 1 package(s)'),
]));
});
test('skips when neither is present', () async {
createFakePackage('a_package', packagesDir);
final List<String> output =
await runCapturingPrint(runner, <String>['custom-test']);
expect(processRunner.recordedCalls, isEmpty);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Skipped 1 package(s)'),
]));
});
test('fails if new fails', () async {
createFakePackage('a_package', packagesDir, extraFiles: <String>[
'tool/run_tests.dart',
'run_tests.sh',
]);
processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(), <String>['pub', 'get']),
FakeProcessInfo(MockProcess(exitCode: 1), <String>['test']),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['custom-test'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The following packages had errors:'),
contains('a_package')
]));
});
test('fails if pub get fails', () async {
createFakePackage('a_package', packagesDir, extraFiles: <String>[
'tool/run_tests.dart',
'run_tests.sh',
]);
processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['pub', 'get']),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['custom-test'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The following packages had errors:'),
contains('a_package:\n'
' Unable to get script dependencies')
]));
});
test('fails if legacy fails', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, extraFiles: <String>[
'tool/run_tests.dart',
'run_tests.sh',
]);
processRunner.mockProcessesForExecutable[
package.directory.childFile('run_tests.sh').path] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1)),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['custom-test'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The following packages had errors:'),
contains('a_package')
]));
});
});
group('Windows', () {
setUp(() {
fileSystem = MemoryFileSystem(style: FileSystemStyle.windows);
mockPlatform = MockPlatform(isWindows: true);
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
processRunner = RecordingProcessRunner();
final CustomTestCommand analyzeCommand = CustomTestCommand(
packagesDir,
processRunner: processRunner,
platform: mockPlatform,
);
runner = CommandRunner<void>(
'custom_test_command', 'Test for custom_test_command');
runner.addCommand(analyzeCommand);
});
test('runs new and skips old when both are present', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, extraFiles: <String>[
'tool/run_tests.dart',
'run_tests.sh',
]);
final List<String> output =
await runCapturingPrint(runner, <String>['custom-test']);
expect(
processRunner.recordedCalls,
containsAll(<ProcessCall>[
ProcessCall('dart', const <String>['run', 'tool/run_tests.dart'],
package.path),
]));
expect(
output,
containsAllInOrder(<Matcher>[
contains('Ran for 1 package(s)'),
]));
});
test('runs when only new is present', () async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
extraFiles: <String>['tool/run_tests.dart']);
final List<String> output =
await runCapturingPrint(runner, <String>['custom-test']);
expect(
processRunner.recordedCalls,
containsAll(<ProcessCall>[
ProcessCall('dart', const <String>['run', 'tool/run_tests.dart'],
package.path),
]));
expect(
output,
containsAllInOrder(<Matcher>[
contains('Ran for 1 package(s)'),
]));
});
test('skips package when only legacy is present', () async {
createFakePackage('a_package', packagesDir,
extraFiles: <String>['run_tests.sh']);
final List<String> output =
await runCapturingPrint(runner, <String>['custom-test']);
expect(processRunner.recordedCalls, isEmpty);
expect(
output,
containsAllInOrder(<Matcher>[
contains('run_tests.sh is not supported on Windows'),
contains('Skipped 1 package(s)'),
]));
});
test('fails if new fails', () async {
createFakePackage('a_package', packagesDir, extraFiles: <String>[
'tool/run_tests.dart',
'run_tests.sh',
]);
processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(), <String>['pub', 'get']),
FakeProcessInfo(MockProcess(exitCode: 1), <String>['test']),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['custom-test'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The following packages had errors:'),
contains('a_package')
]));
});
});
}
| packages/script/tool/test/custom_test_command_test.dart/0 | {
"file_path": "packages/script/tool/test/custom_test_command_test.dart",
"repo_id": "packages",
"token_count": 4324
} | 1,338 |
// 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:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_plugin_tools/src/common/core.dart';
import 'package:flutter_plugin_tools/src/common/plugin_utils.dart';
import 'package:flutter_plugin_tools/src/podspec_check_command.dart';
import 'package:platform/platform.dart';
import 'package:test/test.dart';
import 'mocks.dart';
import 'util.dart';
/// Adds a fake podspec to [plugin]'s [platform] directory.
///
/// If [includeSwiftWorkaround] is set, the xcconfig additions to make Swift
/// libraries work in apps that have no Swift will be included. If
/// [scopeSwiftWorkaround] is set, it will be specific to the iOS configuration.
void _writeFakePodspec(
RepositoryPackage plugin,
String platform, {
bool includeSwiftWorkaround = false,
bool scopeSwiftWorkaround = false,
bool includePrivacyManifest = false,
}) {
final String pluginName = plugin.directory.basename;
final File file = plugin.directory
.childDirectory(platform)
.childFile('$pluginName.podspec');
final String swiftWorkaround = includeSwiftWorkaround
? '''
s.${scopeSwiftWorkaround ? 'ios.' : ''}xcconfig = {
'LIBRARY_SEARCH_PATHS' => '\$(TOOLCHAIN_DIR)/usr/lib/swift/\$(PLATFORM_NAME)/ \$(SDKROOT)/usr/lib/swift',
'LD_RUNPATH_SEARCH_PATHS' => '/usr/lib/swift',
}
'''
: '';
final String privacyManifest = includePrivacyManifest
? '''
s.resource_bundles = {'$pluginName' => ['Resources/PrivacyInfo.xcprivacy']}
'''
: '';
file.createSync(recursive: true);
file.writeAsStringSync('''
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'shared_preferences_foundation'
s.version = '0.0.1'
s.summary = 'iOS and macOS implementation of the shared_preferences plugin.'
s.description = <<-DESC
Wraps NSUserDefaults, providing a persistent store for simple key-value pairs.
DESC
s.homepage = 'https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences_foundation'
s.license = { :type => 'BSD', :file => '../LICENSE' }
s.author = { 'Flutter Team' => '[email protected]' }
s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences_foundation' }
s.source_files = 'Classes/**/*'
s.ios.dependency 'Flutter'
s.osx.dependency 'FlutterMacOS'
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.11'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
$swiftWorkaround
s.swift_version = '5.0'
$privacyManifest
end
''');
}
void main() {
group('PodspecCheckCommand', () {
FileSystem fileSystem;
late Directory packagesDir;
late CommandRunner<void> runner;
late MockPlatform mockPlatform;
late RecordingProcessRunner processRunner;
setUp(() {
fileSystem = MemoryFileSystem();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
mockPlatform = MockPlatform(isMacOS: true);
processRunner = RecordingProcessRunner();
final PodspecCheckCommand command = PodspecCheckCommand(
packagesDir,
processRunner: processRunner,
platform: mockPlatform,
);
runner =
CommandRunner<void>('podspec_test', 'Test for $PodspecCheckCommand');
runner.addCommand(command);
});
test('only runs on macOS', () async {
createFakePlugin('plugin1', packagesDir,
extraFiles: <String>['plugin1.podspec']);
mockPlatform.isMacOS = false;
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['podspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
processRunner.recordedCalls,
equals(<ProcessCall>[]),
);
expect(
output,
containsAllInOrder(
<Matcher>[contains('only supported on macOS')],
));
});
test('runs pod lib lint on a podspec', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin1',
packagesDir,
extraFiles: <String>[
'bogus.dart', // Ignore non-podspecs.
],
);
_writeFakePodspec(plugin, 'ios');
processRunner.mockProcessesForExecutable['pod'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'Foo', stderr: 'Bar')),
FakeProcessInfo(MockProcess()),
];
final List<String> output =
await runCapturingPrint(runner, <String>['podspec-check']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall('which', const <String>['pod'], packagesDir.path),
ProcessCall(
'pod',
<String>[
'lib',
'lint',
plugin
.platformDirectory(FlutterPlatform.ios)
.childFile('plugin1.podspec')
.path,
'--configuration=Debug',
'--skip-tests',
'--use-modular-headers',
'--use-libraries'
],
packagesDir.path),
ProcessCall(
'pod',
<String>[
'lib',
'lint',
plugin
.platformDirectory(FlutterPlatform.ios)
.childFile('plugin1.podspec')
.path,
'--configuration=Debug',
'--skip-tests',
'--use-modular-headers',
],
packagesDir.path),
]),
);
expect(output, contains('Linting plugin1.podspec'));
expect(output, contains('Foo'));
expect(output, contains('Bar'));
});
test('skips shim podspecs for the Flutter framework', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin1',
packagesDir,
extraFiles: <String>[
'example/ios/Flutter/Flutter.podspec',
'example/macos/Flutter/ephemeral/FlutterMacOS.podspec',
],
);
_writeFakePodspec(plugin, 'macos');
final List<String> output =
await runCapturingPrint(runner, <String>['podspec-check']);
expect(output, isNot(contains('FlutterMacOS.podspec')));
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall('which', const <String>['pod'], packagesDir.path),
ProcessCall(
'pod',
<String>[
'lib',
'lint',
plugin
.platformDirectory(FlutterPlatform.macos)
.childFile('plugin1.podspec')
.path,
'--configuration=Debug',
'--skip-tests',
'--use-modular-headers',
'--use-libraries'
],
packagesDir.path),
ProcessCall(
'pod',
<String>[
'lib',
'lint',
plugin
.platformDirectory(FlutterPlatform.macos)
.childFile('plugin1.podspec')
.path,
'--configuration=Debug',
'--skip-tests',
'--use-modular-headers',
],
packagesDir.path),
]),
);
});
test('fails if pod is missing', () async {
final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir);
_writeFakePodspec(plugin, 'ios');
// Simulate failure from `which pod`.
processRunner.mockProcessesForExecutable['which'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['pod']),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['podspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(
<Matcher>[
contains('Unable to find "pod". Make sure it is in your path.'),
],
));
});
test('fails if linting as a framework fails', () async {
final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir);
_writeFakePodspec(plugin, 'ios');
// Simulate failure from `pod`.
processRunner.mockProcessesForExecutable['pod'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1)),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['podspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(
<Matcher>[
contains('The following packages had errors:'),
contains('plugin1:\n'
' plugin1.podspec')
],
));
});
test('fails if linting as a static library fails', () async {
final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir);
_writeFakePodspec(plugin, 'ios');
// Simulate failure from the second call to `pod`.
processRunner.mockProcessesForExecutable['pod'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess()),
FakeProcessInfo(MockProcess(exitCode: 1)),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['podspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(
<Matcher>[
contains('The following packages had errors:'),
contains('plugin1:\n'
' plugin1.podspec')
],
));
});
test('fails if an iOS Swift plugin is missing the search paths workaround',
() async {
final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir,
extraFiles: <String>['ios/Classes/SomeSwift.swift']);
_writeFakePodspec(plugin, 'ios');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['podspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(
<Matcher>[
contains(r'''
s.xcconfig = {
'LIBRARY_SEARCH_PATHS' => '$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)/ $(SDKROOT)/usr/lib/swift',
'LD_RUNPATH_SEARCH_PATHS' => '/usr/lib/swift',
}'''),
contains('The following packages had errors:'),
contains('plugin1:\n'
' plugin1.podspec')
],
));
});
test(
'fails if a shared-source Swift plugin is missing the search paths workaround',
() async {
final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir,
extraFiles: <String>['darwin/Classes/SomeSwift.swift']);
_writeFakePodspec(plugin, 'darwin');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['podspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(
<Matcher>[
contains(r'''
s.xcconfig = {
'LIBRARY_SEARCH_PATHS' => '$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)/ $(SDKROOT)/usr/lib/swift',
'LD_RUNPATH_SEARCH_PATHS' => '/usr/lib/swift',
}'''),
contains('The following packages had errors:'),
contains('plugin1:\n'
' plugin1.podspec')
],
));
});
test('does not require the search paths workaround for macOS plugins',
() async {
final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir,
extraFiles: <String>['macos/Classes/SomeSwift.swift']);
_writeFakePodspec(plugin, 'macos');
final List<String> output =
await runCapturingPrint(runner, <String>['podspec-check']);
expect(
output,
containsAllInOrder(
<Matcher>[
contains('Ran for 1 package(s)'),
],
));
});
test('does not require the search paths workaround for ObjC iOS plugins',
() async {
final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir,
extraFiles: <String>[
'ios/Classes/SomeObjC.h',
'ios/Classes/SomeObjC.m'
]);
_writeFakePodspec(plugin, 'ios');
final List<String> output =
await runCapturingPrint(runner, <String>['podspec-check']);
expect(
output,
containsAllInOrder(
<Matcher>[
contains('Ran for 1 package(s)'),
],
));
});
test('passes if the search paths workaround is present', () async {
final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir,
extraFiles: <String>['ios/Classes/SomeSwift.swift']);
_writeFakePodspec(plugin, 'ios', includeSwiftWorkaround: true);
final List<String> output =
await runCapturingPrint(runner, <String>['podspec-check']);
expect(
output,
containsAllInOrder(
<Matcher>[
contains('Ran for 1 package(s)'),
],
));
});
test('passes if the search paths workaround is present for iOS only',
() async {
final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir,
extraFiles: <String>['ios/Classes/SomeSwift.swift']);
_writeFakePodspec(plugin, 'ios',
includeSwiftWorkaround: true, scopeSwiftWorkaround: true);
final List<String> output =
await runCapturingPrint(runner, <String>['podspec-check']);
expect(
output,
containsAllInOrder(
<Matcher>[
contains('Ran for 1 package(s)'),
],
));
});
test('does not require the search paths workaround for Swift example code',
() async {
final RepositoryPackage plugin =
createFakePlugin('plugin1', packagesDir, extraFiles: <String>[
'ios/Classes/SomeObjC.h',
'ios/Classes/SomeObjC.m',
'example/ios/Runner/AppDelegate.swift',
]);
_writeFakePodspec(plugin, 'ios');
final List<String> output =
await runCapturingPrint(runner, <String>['podspec-check']);
expect(
output,
containsAllInOrder(
<Matcher>[
contains('Ran for 1 package(s)'),
],
));
});
test('skips when there are no podspecs', () async {
createFakePlugin('plugin1', packagesDir);
final List<String> output =
await runCapturingPrint(runner, <String>['podspec-check']);
expect(
output,
containsAllInOrder(
<Matcher>[contains('SKIPPING: No podspecs.')],
));
});
test('fails when an iOS plugin is missing a privacy manifest', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin1',
packagesDir,
platformSupport: <String, PlatformDetails>{
Platform.iOS: const PlatformDetails(PlatformSupport.inline),
},
);
_writeFakePodspec(plugin, 'ios');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['podspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(
<Matcher>[contains('No PrivacyInfo.xcprivacy file specified.')],
));
});
test('passes when an iOS plugin has a privacy manifest', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin1',
packagesDir,
platformSupport: <String, PlatformDetails>{
Platform.iOS: const PlatformDetails(PlatformSupport.inline),
},
);
_writeFakePodspec(plugin, 'ios', includePrivacyManifest: true);
final List<String> output =
await runCapturingPrint(runner, <String>['podspec-check']);
expect(
output,
containsAllInOrder(
<Matcher>[contains('Ran for 1 package(s)')],
));
});
});
}
| packages/script/tool/test/podspec_check_command_test.dart/0 | {
"file_path": "packages/script/tool/test/podspec_check_command_test.dart",
"repo_id": "packages",
"token_count": 7710
} | 1,339 |
The MIT License (MIT)
Copyright (c) 2016 Vladimir Kharlampidi
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | packages/third_party/packages/cupertino_icons/LICENSE/0 | {
"file_path": "packages/third_party/packages/cupertino_icons/LICENSE",
"repo_id": "packages",
"token_count": 273
} | 1,340 |
export default `
<footer>
<div class="left">
<span>Made with
<a href="https://flutter.dev">Flutter</a> &
<a href="https://firebase.google.com">Firebase</a>
</ul>
</div>
<div class="right">
<ul>
<li><a href="https://events.google.com/io/">Google I/O</a></li>
<li><a href="https://flutter.dev/docs/codelabs">Codelab</a></li>
<li><a href="https://medium.com/flutter/how-its-made-i-o-photo-booth-3b8355d35883">How It's Made</a></li>
<li><a href="https://policies.google.com/terms">Terms of Service</a></li>
<li><a href="https://policies.google.com/privacy">Privacy Policy</a></li>
</ul>
</div>
</footer>
`;
| photobooth/functions/src/share/templates/footer.ts/0 | {
"file_path": "photobooth/functions/src/share/templates/footer.ts",
"repo_id": "photobooth",
"token_count": 305
} | 1,341 |
import 'package:flutter/material.dart';
import 'package:io_photobooth/external_links/external_links.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class IconLink extends StatelessWidget {
const IconLink({
required this.icon,
required this.link,
super.key,
});
final Widget icon;
final String link;
@override
Widget build(BuildContext context) {
return Clickable(
onPressed: () => openLink(link),
child: SizedBox(height: 30, width: 30, child: icon),
);
}
}
class FlutterIconLink extends StatelessWidget {
const FlutterIconLink({
super.key,
});
@override
Widget build(BuildContext context) {
return IconLink(
icon: Image.asset('assets/icons/flutter_icon.png'),
link: flutterDevExternalLink,
);
}
}
class FirebaseIconLink extends StatelessWidget {
const FirebaseIconLink({
super.key,
});
@override
Widget build(BuildContext context) {
return IconLink(
icon: Image.asset('assets/icons/firebase_icon.png'),
link: firebaseExternalLink,
);
}
}
class MadeWithIconLinks extends StatelessWidget {
const MadeWithIconLinks({super.key});
@override
Widget build(BuildContext context) {
return const Row(
mainAxisSize: MainAxisSize.min,
children: [
FlutterIconLink(),
SizedBox(width: 8),
FirebaseIconLink(),
],
);
}
}
| photobooth/lib/footer/widgets/icon_link.dart/0 | {
"file_path": "photobooth/lib/footer/widgets/icon_link.dart",
"repo_id": "photobooth",
"token_count": 527
} | 1,342 |
// ignore: avoid_web_libraries_in_flutter
import 'dart:html' as html;
/// Removes the handed-coded piece of HTML used as the app loading
/// indicator/splash screen.
void removeLoadingIndicator() {
html.document.querySelector('#loading-indicator')?.remove();
}
| photobooth/lib/landing/loading_indicator_web.dart/0 | {
"file_path": "photobooth/lib/landing/loading_indicator_web.dart",
"repo_id": "photobooth",
"token_count": 81
} | 1,343 |
import 'package:flutter/material.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class AnimatedSparky extends AnimatedSprite {
const AnimatedSparky({super.key})
: super(
loadingIndicatorColor: PhotoboothColors.red,
sprites: const Sprites(
asset: 'sparky_spritesheet.png',
size: Size(730, 588),
frames: 25,
stepTime: 2 / 25,
),
);
}
| photobooth/lib/photobooth/widgets/animated_characters/animated_sparky.dart/0 | {
"file_path": "photobooth/lib/photobooth/widgets/animated_characters/animated_sparky.dart",
"repo_id": "photobooth",
"token_count": 208
} | 1,344 |
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:io_photobooth/share/share.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class ShareDialog extends StatelessWidget {
const ShareDialog({required this.image, super.key});
final Uint8List image;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = context.l10n;
return DecoratedBox(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
PhotoboothColors.whiteBackground,
PhotoboothColors.white,
],
),
),
child: Stack(
children: [
SingleChildScrollView(
child: SizedBox(
width: 900,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 30,
vertical: 60,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SharePreviewPhoto(image: image),
const SizedBox(height: 60),
SelectableText(
l10n.shareDialogHeading,
key: const Key('shareDialog_heading'),
style: theme.textTheme.displayLarge,
textAlign: TextAlign.center,
),
const SizedBox(height: 24),
SelectableText(
l10n.shareDialogSubheading,
key: const Key('shareDialog_subheading'),
style: theme.textTheme.displaySmall,
textAlign: TextAlign.center,
),
const SizedBox(height: 30),
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TwitterButton(),
SizedBox(width: 36),
FacebookButton(),
],
),
const SizedBox(height: 30),
const SocialMediaShareClarificationNote(),
],
),
),
),
),
Positioned(
left: 24,
top: 24,
child: IconButton(
icon: const Icon(
Icons.clear,
color: PhotoboothColors.black54,
),
onPressed: () => Navigator.of(context).pop(),
),
),
],
),
);
}
}
| photobooth/lib/share/view/share_dialog.dart/0 | {
"file_path": "photobooth/lib/share/view/share_dialog.dart",
"repo_id": "photobooth",
"token_count": 1596
} | 1,345 |
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:io_photobooth/external_links/external_links.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class SocialMediaShareClarificationNote extends StatelessWidget {
const SocialMediaShareClarificationNote({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = context.l10n;
return SelectableText.rich(
TextSpan(
style: theme.textTheme.bodySmall?.copyWith(
color: PhotoboothColors.black,
fontWeight: PhotoboothFontWeight.regular,
),
children: <TextSpan>[
TextSpan(
text: l10n.sharePageSocialMediaShareClarification1,
),
TextSpan(
text: l10n.sharePageSocialMediaShareClarification2,
recognizer: TapGestureRecognizer()..onTap = launchPhotoboothEmail,
style: const TextStyle(
decoration: TextDecoration.underline,
),
),
TextSpan(
text: l10n.sharePageSocialMediaShareClarification3,
),
],
),
textAlign: TextAlign.center,
);
}
}
| photobooth/lib/share/widgets/share_social_media_clarification.dart/0 | {
"file_path": "photobooth/lib/share/widgets/share_social_media_clarification.dart",
"repo_id": "photobooth",
"token_count": 556
} | 1,346 |
import 'package:flutter/material.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:io_photobooth/stickers/stickers.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class DesktopStickersDrawer extends StatelessWidget {
const DesktopStickersDrawer({
required this.initialIndex,
required this.onStickerSelected,
required this.onTabChanged,
required this.onCloseTapped,
required this.bucket,
super.key,
});
final int initialIndex;
final ValueSetter<Asset> onStickerSelected;
final ValueSetter<int> onTabChanged;
final VoidCallback onCloseTapped;
final PageStorageBucket bucket;
@override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
final l10n = context.l10n;
return PageStorage(
bucket: bucket,
child: Container(
width: width * 0.35,
color: PhotoboothColors.white,
padding: const EdgeInsets.only(top: 30),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: Text(
l10n.stickersDrawerTitle,
style: Theme.of(context).textTheme.displayMedium,
),
),
IconButton(
key: const Key('stickersDrawer_close_iconButton'),
onPressed: onCloseTapped,
icon: const Icon(Icons.clear),
),
],
),
),
const SizedBox(height: 15),
Flexible(
child: StickersTabs(
initialIndex: initialIndex,
onTabChanged: onTabChanged,
onStickerSelected: onStickerSelected,
),
),
],
),
),
);
}
}
| photobooth/lib/stickers/widgets/stickers_drawer_layer/desktop_stickers_drawer.dart/0 | {
"file_path": "photobooth/lib/stickers/widgets/stickers_drawer_layer/desktop_stickers_drawer.dart",
"repo_id": "photobooth",
"token_count": 1038
} | 1,347 |
/// A library which manages user authentication using Firebase Authentication.
library authentication_repository;
export 'src/authentication_repository.dart';
| photobooth/packages/authentication_repository/lib/authentication_repository.dart/0 | {
"file_path": "photobooth/packages/authentication_repository/lib/authentication_repository.dart",
"repo_id": "photobooth",
"token_count": 37
} | 1,348 |
library camera;
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/widgets.dart';
export 'package:camera_platform_interface/camera_platform_interface.dart';
part 'src/camera.dart';
part 'src/controller.dart';
| photobooth/packages/camera/camera/lib/camera.dart/0 | {
"file_path": "photobooth/packages/camera/camera/lib/camera.dart",
"repo_id": "photobooth",
"token_count": 81
} | 1,349 |
/// A library for the web platform implementation of camera.
library camera_web;
export 'src/browser_detection.dart';
export 'src/camera_web.dart' show CameraPlugin;
| photobooth/packages/camera/camera_web/lib/camera_web.dart/0 | {
"file_path": "photobooth/packages/camera/camera_web/lib/camera_web.dart",
"repo_id": "photobooth",
"token_count": 48
} | 1,350 |
@TestOn('chrome')
library;
import 'package:image_compositor/src/web.dart';
import 'package:test/test.dart';
void main() {
group('ImageCompositor', () {
test('can be instantiated', () {
expect(ImageCompositor(), isNotNull);
});
});
}
| photobooth/packages/image_compositor/test/web_image_compositor_test.dart/0 | {
"file_path": "photobooth/packages/image_compositor/test/web_image_compositor_test.dart",
"repo_id": "photobooth",
"token_count": 98
} | 1,351 |
export 'aspect_ratio.dart';
export 'breakpoints.dart';
| photobooth/packages/photobooth_ui/lib/src/layout/layout.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/layout/layout.dart",
"repo_id": "photobooth",
"token_count": 21
} | 1,352 |
import 'package:flutter/material.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
/// Displays a dialog above the current contents of the app.
Future<T?> showAppDialog<T>({
required BuildContext context,
required Widget child,
bool barrierDismissible = true,
}) =>
showDialog<T>(
context: context,
barrierColor: PhotoboothColors.charcoal,
barrierDismissible: barrierDismissible,
builder: (context) => _AppDialog(child: child),
);
class _AppDialog extends StatelessWidget {
const _AppDialog({required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return Dialog(
clipBehavior: Clip.hardEdge,
child: Container(
width: 900,
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
PhotoboothColors.whiteBackground,
PhotoboothColors.white,
],
),
),
child: child,
),
);
}
}
| photobooth/packages/photobooth_ui/lib/src/widgets/app_dialog.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/widgets/app_dialog.dart",
"repo_id": "photobooth",
"token_count": 453
} | 1,353 |
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
extension PhotoboothWidgetTester on WidgetTester {
void setDisplaySize(Size size) {
binding.window.physicalSizeTestValue = size;
binding.window.devicePixelRatioTestValue = 1.0;
addTearDown(() {
binding.window.clearPhysicalSizeTestValue();
binding.window.clearDevicePixelRatioTestValue();
});
}
void setLandscapeDisplaySize() {
setDisplaySize(const Size(PhotoboothBreakpoints.large, 1000));
}
void setPortraitDisplaySize() {
setDisplaySize(const Size(PhotoboothBreakpoints.small, 1000));
}
}
| photobooth/packages/photobooth_ui/test/src/helpers/set_display_size.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/test/src/helpers/set_display_size.dart",
"repo_id": "photobooth",
"token_count": 236
} | 1,354 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
import 'package:platform_helper/platform_helper.dart';
class MockPlatformHelper extends Mock implements PlatformHelper {}
void main() {
group('PlatformBuilder', () {
late PlatformHelper platformHelper;
setUp(() {
platformHelper = MockPlatformHelper();
});
testWidgets('renders without platform helper parameter', (tester) async {
await tester.pumpWidget(
PlatformBuilder(
mobile: const SizedBox(),
desktop: const SizedBox(),
),
);
expect(find.byType(PlatformBuilder), findsOneWidget);
});
testWidgets('renders mobile when isMobile: true', (tester) async {
const mobileKey = Key('__mobile__');
const desktopKey = Key('__desktop__');
when(() => platformHelper.isMobile).thenReturn(true);
await tester.pumpWidget(
PlatformBuilder(
mobile: const SizedBox(key: mobileKey),
desktop: const SizedBox(key: desktopKey),
platformHelper: platformHelper,
),
);
expect(find.byKey(mobileKey), findsOneWidget);
expect(find.byKey(desktopKey), findsNothing);
});
testWidgets('renders desktop when isMobile: false', (tester) async {
const mobileKey = Key('__mobile__');
const desktopKey = Key('__desktop__');
when(() => platformHelper.isMobile).thenReturn(false);
await tester.pumpWidget(
PlatformBuilder(
mobile: const SizedBox(key: mobileKey),
desktop: const SizedBox(key: desktopKey),
platformHelper: platformHelper,
),
);
expect(find.byKey(mobileKey), findsNothing);
expect(find.byKey(desktopKey), findsOneWidget);
});
});
}
| photobooth/packages/photobooth_ui/test/src/widgets/platform_builder_test.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/test/src/widgets/platform_builder_test.dart",
"repo_id": "photobooth",
"token_count": 720
} | 1,355 |
/// Unsupported Implementation of [PlatformHelper]
class PlatformHelper {
/// Throws [UnsupportedError].
bool get isMobile {
throw UnsupportedError('isMobile is not supported on the current platform');
}
}
| photobooth/packages/platform_helper/lib/src/unsupported.dart/0 | {
"file_path": "photobooth/packages/platform_helper/lib/src/unsupported.dart",
"repo_id": "photobooth",
"token_count": 56
} | 1,356 |
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
const landscapeDisplaySize = Size(1920, 1080);
const portraitDisplaySize = Size(1080, 1920);
extension PhotoboothWidgetTester on WidgetTester {
void setDisplaySize(Size size) {
binding.window.physicalSizeTestValue = size;
binding.window.devicePixelRatioTestValue = 1.0;
addTearDown(() {
binding.window.clearPhysicalSizeTestValue();
binding.window.clearDevicePixelRatioTestValue();
});
}
void setLandscapeDisplaySize() {
setDisplaySize(const Size(PhotoboothBreakpoints.large, 1000));
}
void setPortraitDisplaySize() {
setDisplaySize(const Size(PhotoboothBreakpoints.small, 1000));
}
void setSmallDisplaySize() {
setDisplaySize(const Size(PhotoboothBreakpoints.small - 1, 1000));
}
}
| photobooth/test/helpers/set_display_size.dart/0 | {
"file_path": "photobooth/test/helpers/set_display_size.dart",
"repo_id": "photobooth",
"token_count": 296
} | 1,357 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/share/share.dart';
import '../../helpers/helpers.dart';
void main() {
group('ShareErrorBottomSheet', () {
testWidgets('displays heading', (tester) async {
await tester.pumpApp(Scaffold(body: ShareErrorBottomSheet()));
expect(find.byKey(Key('shareErrorBottomSheet_heading')), findsOneWidget);
});
testWidgets('displays subheading', (tester) async {
await tester.pumpApp(Scaffold(body: ShareErrorBottomSheet()));
expect(
find.byKey(Key('shareErrorBottomSheet_subheading')),
findsOneWidget,
);
});
testWidgets('displays a ShareTryAgainButton button', (tester) async {
await tester.pumpApp(Scaffold(body: ShareErrorBottomSheet()));
expect(find.byType(ShareTryAgainButton), findsOneWidget);
});
testWidgets('pops when tapped on ShareTryAgainButton button',
(tester) async {
await tester.pumpApp(Scaffold(body: ShareErrorBottomSheet()));
await tester.ensureVisible(find.byType(ShareTryAgainButton));
await tester.tap(find.byType(ShareTryAgainButton));
await tester.pumpAndSettle();
expect(find.byType(ShareErrorBottomSheet), findsNothing);
});
testWidgets('pops when tapped on close button', (tester) async {
await tester.pumpApp(Scaffold(body: ShareErrorBottomSheet()));
await tester.tap(find.byIcon(Icons.clear));
await tester.pumpAndSettle();
expect(find.byType(ShareErrorBottomSheet), findsNothing);
});
});
}
| photobooth/test/share/view/share_error_bottom_sheet_test.dart/0 | {
"file_path": "photobooth/test/share/view/share_error_bottom_sheet_test.dart",
"repo_id": "photobooth",
"token_count": 629
} | 1,358 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/assets.g.dart';
import 'package:io_photobooth/stickers/stickers.dart';
import '../../helpers/helpers.dart';
void main() {
const googleTabAssetPath = 'assets/icons/google_icon.png';
const hatsTabAssetPath = 'assets/icons/hats_icon.png';
const eyewearTabAssetPath = 'assets/icons/eyewear_icon.png';
const foodTabAssetPath = 'assets/icons/food_icon.png';
const shapesTabAssetPath = 'assets/icons/shapes_icon.png';
group('StickersTabs', () {
testWidgets('onTabChanged is called with correct index', (tester) async {
final onTabChangedCalls = <int>[];
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: onTabChangedCalls.add,
),
),
);
await tester.tap(find.byKey(Key('stickersTabs_hatsTab')));
await tester.pump();
expect(onTabChangedCalls, equals([1]));
});
group('TabBar', () {
group('google', () {
testWidgets('renders as first tab', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tabBar = tester.widget<TabBar>(find.byType(TabBar));
expect(tabBar.tabs[0].key, equals(Key('stickersTabs_googleTab')));
});
testWidgets('has correct correct asset path', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tab = tester.widget<StickersTab>(
find.byKey(Key('stickersTabs_googleTab')),
);
expect(tab.assetPath, equals(googleTabAssetPath));
});
});
group('hats', () {
testWidgets('renders as second tab', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tabBar = tester.widget<TabBar>(find.byType(TabBar));
expect(tabBar.tabs[1].key, equals(Key('stickersTabs_hatsTab')));
});
testWidgets('has correct correct asset path', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tab = tester.widget<StickersTab>(
find.byKey(Key('stickersTabs_hatsTab')),
);
expect(tab.assetPath, equals(hatsTabAssetPath));
});
});
group('eyewear', () {
testWidgets('renders as third tab', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tabBar = tester.widget<TabBar>(find.byType(TabBar));
expect(tabBar.tabs[2].key, equals(Key('stickersTabs_eyewearTab')));
});
testWidgets('has correct correct asset path', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tab = tester
.widget<StickersTab>(find.byKey(Key('stickersTabs_eyewearTab')));
expect(tab.assetPath, equals(eyewearTabAssetPath));
});
});
group('food', () {
testWidgets('renders as fourth tab', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tabBar = tester.widget<TabBar>(find.byType(TabBar));
expect(tabBar.tabs[3].key, equals(Key('stickersTabs_foodTab')));
});
testWidgets('has correct correct asset path', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tab = tester
.widget<StickersTab>(find.byKey(Key('stickersTabs_foodTab')));
expect(tab.assetPath, equals(foodTabAssetPath));
});
});
group('shapes', () {
testWidgets('renders as fifth tab', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tabBar = tester.widget<TabBar>(find.byType(TabBar));
expect(tabBar.tabs[4].key, equals(Key('stickersTabs_shapesTab')));
});
testWidgets('has correct correct asset path', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tab = tester
.widget<StickersTab>(find.byKey(Key('stickersTabs_shapesTab')));
expect(tab.assetPath, equals(shapesTabAssetPath));
});
});
});
group('TabBarView', () {
group('google', () {
testWidgets('renders as first tab bar view', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tabBar = tester.widget<TabBarView>(find.byType(TabBarView));
expect(
tabBar.children[0].key,
equals(Key('stickersTabs_googleTabBarView')),
);
});
testWidgets('has correct stickers', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tabBarView = tester.widget<StickersTabBarView>(
find.byKey(Key('stickersTabs_googleTabBarView')),
);
expect(tabBarView.stickers, equals(Assets.googleProps));
});
});
group('hats', () {
testWidgets('renders as second tab bar view', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tabBar = tester.widget<TabBarView>(find.byType(TabBarView));
expect(
tabBar.children[1].key,
equals(Key('stickersTabs_hatsTabBarView')),
);
});
testWidgets('has correct stickers', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
/// Swipe to the second page.
await tester.fling(
find.byType(StickersTabs),
const Offset(-200, 0),
1000,
);
await tester.pump();
await tester.pump(kThemeAnimationDuration);
final tabBarView = tester.widget<StickersTabBarView>(
find.byKey(Key('stickersTabs_hatsTabBarView')),
);
expect(tabBarView.stickers, equals(Assets.hatProps));
});
});
group('eyewear', () {
testWidgets('renders as third tab bar view', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tabBar = tester.widget<TabBarView>(find.byType(TabBarView));
expect(
tabBar.children[2].key,
equals(Key('stickersTabs_eyewearTabBarView')),
);
});
testWidgets('has correct stickers', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
/// Swipe to the second page.
await tester.fling(
find.byType(StickersTabs),
const Offset(-200, 0),
1000,
);
await tester.pump();
await tester.pump(kThemeAnimationDuration);
/// Swipe to the third page.
await tester.fling(
find.byType(StickersTabs),
const Offset(-200, 0),
1000,
);
await tester.pump();
await tester.pump(kThemeAnimationDuration);
final tabBarView = tester.widget<StickersTabBarView>(
find.byKey(Key('stickersTabs_eyewearTabBarView')),
);
expect(tabBarView.stickers, equals(Assets.eyewearProps));
});
});
group('food', () {
testWidgets('renders as fourth tab bar view', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tabBar = tester.widget<TabBarView>(find.byType(TabBarView));
expect(
tabBar.children[3].key,
equals(Key('stickersTabs_foodTabBarView')),
);
});
testWidgets('has correct stickers', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
/// Swipe to the second page.
await tester.fling(
find.byType(StickersTabs),
const Offset(-200, 0),
1000,
);
await tester.pump();
await tester.pump(kThemeAnimationDuration);
/// Swipe to the third page.
await tester.fling(
find.byType(StickersTabs),
const Offset(-200, 0),
1000,
);
await tester.pump();
await tester.pump(kThemeAnimationDuration);
/// Swipe to the fourth page.
await tester.fling(
find.byType(StickersTabs),
const Offset(-200, 0),
1000,
);
await tester.pump();
await tester.pump(kThemeAnimationDuration);
final tabBarView = tester.widget<StickersTabBarView>(
find.byKey(Key('stickersTabs_foodTabBarView')),
);
expect(tabBarView.stickers, equals(Assets.foodProps));
});
});
group('shapes', () {
testWidgets('renders as fourth tab bar view', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
final tabBar = tester.widget<TabBarView>(find.byType(TabBarView));
expect(
tabBar.children[4].key,
equals(Key('stickersTabs_shapesTabBarView')),
);
});
testWidgets('has correct stickers', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTabs(
onStickerSelected: (_) {},
onTabChanged: (_) {},
),
),
);
/// Swipe to the second page.
await tester.fling(
find.byType(StickersTabs),
const Offset(-200, 0),
1000,
);
await tester.pump();
await tester.pump(kThemeAnimationDuration);
/// Swipe to the third page.
await tester.fling(
find.byType(StickersTabs),
const Offset(-200, 0),
1000,
);
await tester.pump();
await tester.pump(kThemeAnimationDuration);
/// Swipe to the fourth page.
await tester.fling(
find.byType(StickersTabs),
const Offset(-200, 0),
1000,
);
await tester.pump();
await tester.pump(kThemeAnimationDuration);
/// Swipe to the fifth page.
await tester.fling(
find.byType(StickersTabs),
const Offset(-200, 0),
1000,
);
await tester.pump();
await tester.pump(kThemeAnimationDuration);
final tabBarView = tester.widget<StickersTabBarView>(
find.byKey(Key('stickersTabs_shapesTabBarView')),
);
expect(tabBarView.stickers, equals(Assets.shapeProps));
});
});
});
});
group('StickersTab', () {
testWidgets('renders', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTab(assetPath: googleTabAssetPath),
),
);
expect(find.byType(StickersTab), findsOneWidget);
});
testWidgets('renders tab widget', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTab(assetPath: googleTabAssetPath),
),
);
expect(find.byType(Tab), findsOneWidget);
});
testWidgets('renders image widget', (tester) async {
await tester.pumpApp(
Scaffold(
body: StickersTab(assetPath: googleTabAssetPath),
),
);
expect(find.byType(Image), findsOneWidget);
});
});
}
| photobooth/test/stickers/widgets/stickers_tabs_test.dart/0 | {
"file_path": "photobooth/test/stickers/widgets/stickers_tabs_test.dart",
"repo_id": "photobooth",
"token_count": 7740
} | 1,359 |
export 'view/app.dart';
| pinball/lib/app/app.dart/0 | {
"file_path": "pinball/lib/app/app.dart",
"repo_id": "pinball",
"token_count": 10
} | 1,360 |
// ignore_for_file: public_member_api_docs
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_audio/pinball_audio.dart';
import 'package:pinball_flame/pinball_flame.dart';
class CowBumperNoiseBehavior extends ContactBehavior {
@override
void beginContact(Object other, Contact contact) {
super.beginContact(other, contact);
readProvider<PinballAudioPlayer>().play(PinballAudio.cowMoo);
}
}
| pinball/lib/game/behaviors/cow_bumper_noise_behavior.dart/0 | {
"file_path": "pinball/lib/game/behaviors/cow_bumper_noise_behavior.dart",
"repo_id": "pinball",
"token_count": 146
} | 1,361 |
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart';
import 'package:pinball/leaderboard/models/leader_board_entry.dart';
import 'package:pinball_theme/pinball_theme.dart';
part 'backbox_event.dart';
part 'backbox_state.dart';
/// {@template backbox_bloc}
/// Bloc which manages the Backbox display.
/// {@endtemplate}
class BackboxBloc extends Bloc<BackboxEvent, BackboxState> {
/// {@macro backbox_bloc}
BackboxBloc({
required LeaderboardRepository leaderboardRepository,
required List<LeaderboardEntryData>? initialEntries,
}) : _leaderboardRepository = leaderboardRepository,
super(
initialEntries != null
? LeaderboardSuccessState(entries: initialEntries)
: LeaderboardFailureState(),
) {
on<PlayerInitialsRequested>(_onPlayerInitialsRequested);
on<PlayerInitialsSubmitted>(_onPlayerInitialsSubmitted);
on<ShareScoreRequested>(_onScoreShareRequested);
on<LeaderboardRequested>(_onLeaderboardRequested);
}
final LeaderboardRepository _leaderboardRepository;
void _onPlayerInitialsRequested(
PlayerInitialsRequested event,
Emitter<BackboxState> emit,
) {
emit(
InitialsFormState(
score: event.score,
character: event.character,
),
);
}
Future<void> _onPlayerInitialsSubmitted(
PlayerInitialsSubmitted event,
Emitter<BackboxState> emit,
) async {
try {
emit(LoadingState());
await _leaderboardRepository.addLeaderboardEntry(
LeaderboardEntryData(
playerInitials: event.initials,
score: event.score,
character: event.character.toType,
),
);
emit(
InitialsSuccessState(
score: event.score,
),
);
} catch (error, stackTrace) {
addError(error, stackTrace);
emit(
InitialsFailureState(
score: event.score,
character: event.character,
),
);
}
}
Future<void> _onScoreShareRequested(
ShareScoreRequested event,
Emitter<BackboxState> emit,
) async {
emit(
ShareState(score: event.score),
);
}
Future<void> _onLeaderboardRequested(
LeaderboardRequested event,
Emitter<BackboxState> emit,
) async {
try {
emit(LoadingState());
final entries = await _leaderboardRepository.fetchTop10Leaderboard();
emit(LeaderboardSuccessState(entries: entries));
} catch (error, stackTrace) {
addError(error, stackTrace);
emit(LeaderboardFailureState());
}
}
}
| pinball/lib/game/components/backbox/bloc/backbox_bloc.dart/0 | {
"file_path": "pinball/lib/game/components/backbox/bloc/backbox_bloc.dart",
"repo_id": "pinball",
"token_count": 1043
} | 1,362 |
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball/game/components/dino_desert/behaviors/behaviors.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
/// {@template dino_desert}
/// Area located next to the [Launcher] containing the [ChromeDino],
/// [DinoWalls], and the [Slingshots].
/// {@endtemplate}
class DinoDesert extends Component {
/// {@macro dino_desert}
DinoDesert()
: super(
children: [
ChromeDino(
children: [
ScoringContactBehavior(points: Points.twoHundredThousand)
..applyTo(['inside_mouth']),
],
)..initialPosition = Vector2(12.2, -6.9),
_BarrierBehindDino(),
DinoWalls(),
Slingshots(),
ChromeDinoBonusBehavior(),
],
);
/// Creates [DinoDesert] without any children.
///
/// This can be used for testing [DinoDesert]'s behaviors in isolation.
@visibleForTesting
DinoDesert.test();
}
class _BarrierBehindDino extends BodyComponent {
_BarrierBehindDino() : super(renderBody: false);
@override
Body createBody() {
final shape = EdgeShape()
..set(
Vector2(24.2, -14.8),
Vector2(25.3, -7.7),
);
return world.createBody(BodyDef())..createFixtureFromShape(shape);
}
}
| pinball/lib/game/components/dino_desert/dino_desert.dart/0 | {
"file_path": "pinball/lib/game/components/dino_desert/dino_desert.dart",
"repo_id": "pinball",
"token_count": 650
} | 1,363 |
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// Toggle each [Multiplier] when GameState.multiplier changes.
class MultipliersBehavior extends Component
with ParentIsA<Multipliers>, FlameBlocListenable<GameBloc, GameState> {
@override
bool listenWhen(GameState? previousState, GameState newState) {
return previousState?.multiplier != newState.multiplier;
}
@override
void onNewState(GameState state) {
final multipliers = parent.children.whereType<Multiplier>();
for (final multiplier in multipliers) {
multiplier.bloc.next(state.multiplier);
}
}
}
| pinball/lib/game/components/multipliers/behaviors/multipliers_behavior.dart/0 | {
"file_path": "pinball/lib/game/components/multipliers/behaviors/multipliers_behavior.dart",
"repo_id": "pinball",
"token_count": 260
} | 1,364 |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball_ui/pinball_ui.dart';
/// {@template round_count_display}
/// Colored square indicating if a round is available.
/// {@endtemplate}
class RoundCountDisplay extends StatelessWidget {
/// {@macro round_count_display}
const RoundCountDisplay({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final rounds = context.select((GameBloc bloc) => bloc.state.rounds);
return Row(
children: [
Text(
l10n.rounds,
style: Theme.of(context).textTheme.subtitle1,
),
const SizedBox(width: 8),
Row(
children: [
RoundIndicator(isActive: rounds >= 1),
RoundIndicator(isActive: rounds >= 2),
RoundIndicator(isActive: rounds >= 3),
],
),
],
);
}
}
/// {@template round_indicator}
/// [Widget] that displays the round indicator.
/// {@endtemplate}
@visibleForTesting
class RoundIndicator extends StatelessWidget {
/// {@macro round_indicator}
const RoundIndicator({
Key? key,
required this.isActive,
}) : super(key: key);
/// A value that describes whether the indicator is active.
final bool isActive;
@override
Widget build(BuildContext context) {
final color =
isActive ? PinballColors.yellow : PinballColors.yellow.withAlpha(128);
const size = 8.0;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Container(
color: color,
height: size,
width: size,
),
);
}
}
| pinball/lib/game/view/widgets/round_count_display.dart/0 | {
"file_path": "pinball/lib/game/view/widgets/round_count_display.dart",
"repo_id": "pinball",
"token_count": 701
} | 1,365 |
export 'cubit/character_theme_cubit.dart';
export 'view/view.dart';
| pinball/lib/select_character/select_character.dart/0 | {
"file_path": "pinball/lib/select_character/select_character.dart",
"repo_id": "pinball",
"token_count": 28
} | 1,366 |
name: leaderboard_repository
description: Repository to access leaderboard data in Firebase Cloud Firestore.
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.16.0 <3.0.0"
dependencies:
cloud_firestore: ^3.1.10
equatable: ^2.0.3
flutter:
sdk: flutter
json_annotation: ^4.4.0
dev_dependencies:
build_runner: ^2.1.8
flutter_test:
sdk: flutter
json_serializable: ^6.1.5
mocktail: ^0.2.0
test: ^1.19.2
very_good_analysis: ^2.4.0 | pinball/packages/leaderboard_repository/pubspec.yaml/0 | {
"file_path": "pinball/packages/leaderboard_repository/pubspec.yaml",
"repo_id": "pinball",
"token_count": 205
} | 1,367 |
part of 'android_bumper_cubit.dart';
enum AndroidBumperState {
lit,
dimmed,
}
| pinball/packages/pinball_components/lib/src/components/android_bumper/cubit/android_bumper_state.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/android_bumper/cubit/android_bumper_state.dart",
"repo_id": "pinball",
"token_count": 35
} | 1,368 |
import 'dart:math' as math;
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template baseboard}
/// Wing-shaped board piece to corral the [Ball] towards the [Flipper]s.
/// {@endtemplate}
class Baseboard extends BodyComponent with InitialPosition {
/// {@macro baseboard}
Baseboard({
required BoardSide side,
}) : _side = side,
super(
renderBody: false,
children: [_BaseboardSpriteComponent(side: side)],
);
/// Whether the [Baseboard] is on the left or right side of the board.
final BoardSide _side;
List<FixtureDef> _createFixtureDefs() {
final direction = _side.direction;
const arcsAngle = 1.11;
final arcsRotation = (_side.isLeft) ? -2.7 : -1.6;
final pegBumperShape = CircleShape()..radius = 0.7;
pegBumperShape.position.setValues(11.11 * direction, -7.15);
final pegBumperFixtureDef = FixtureDef(pegBumperShape);
final topCircleShape = CircleShape()..radius = 0.7;
topCircleShape.position.setValues(9.71 * direction, -4.95);
final topCircleFixtureDef = FixtureDef(topCircleShape);
final innerEdgeShape = EdgeShape()
..set(
Vector2(9.01 * direction, -5.35),
Vector2(5.29 * direction, 0.95),
);
final innerEdgeShapeFixtureDef = FixtureDef(innerEdgeShape);
final outerEdgeShape = EdgeShape()
..set(
Vector2(10.41 * direction, -4.75),
Vector2(3.79 * direction, 5.95),
);
final outerEdgeShapeFixtureDef = FixtureDef(outerEdgeShape);
final upperArcShape = ArcShape(
center: Vector2(0.09 * direction, -2.15),
arcRadius: 6.1,
angle: arcsAngle,
rotation: arcsRotation,
);
final upperArcFixtureDef = FixtureDef(upperArcShape);
final lowerArcShape = ArcShape(
center: Vector2(0.09 * direction, 3.35),
arcRadius: 4.5,
angle: arcsAngle,
rotation: arcsRotation,
);
final lowerArcFixtureDef = FixtureDef(lowerArcShape);
final bottomRectangle = PolygonShape()
..setAsBox(
6.8,
2,
Vector2(-6.3 * direction, 5.85),
0,
);
final bottomRectangleFixtureDef = FixtureDef(bottomRectangle);
return [
pegBumperFixtureDef,
topCircleFixtureDef,
innerEdgeShapeFixtureDef,
outerEdgeShapeFixtureDef,
upperArcFixtureDef,
lowerArcFixtureDef,
bottomRectangleFixtureDef,
];
}
@override
Body createBody() {
const angle = 37.1 * (math.pi / 180);
final bodyDef = BodyDef(
position: initialPosition,
angle: -angle * _side.direction,
);
final body = world.createBody(bodyDef);
_createFixtureDefs().forEach(body.createFixture);
return body;
}
}
class _BaseboardSpriteComponent extends SpriteComponent with HasGameRef {
_BaseboardSpriteComponent({required BoardSide side})
: _side = side,
super(
anchor: Anchor.center,
position: Vector2(0.4 * -side.direction, 0),
);
final BoardSide _side;
@override
Future<void> onLoad() async {
await super.onLoad();
final sprite = Sprite(
gameRef.images.fromCache(
(_side.isLeft)
? Assets.images.baseboard.left.keyName
: Assets.images.baseboard.right.keyName,
),
);
this.sprite = sprite;
size = sprite.originalSize / 10;
}
}
| pinball/packages/pinball_components/lib/src/components/baseboard.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/baseboard.dart",
"repo_id": "pinball",
"token_count": 1419
} | 1,369 |
import 'package:flame/components.dart';
import 'package:pinball_components/pinball_components.dart';
/// {@template dash_animatronic}
/// Animated Dash that sits on top of the [DashBumper.main].
/// {@endtemplate}
class DashAnimatronic extends SpriteAnimationComponent with HasGameRef {
/// {@macro dash_animatronic}
DashAnimatronic({Iterable<Component>? children})
: super(
anchor: Anchor.center,
playing: false,
children: children,
);
@override
Future<void> onLoad() async {
await super.onLoad();
final spriteSheet = gameRef.images.fromCache(
Assets.images.dash.animatronic.keyName,
);
const amountPerRow = 13;
const amountPerColumn = 6;
final textureSize = Vector2(
spriteSheet.width / amountPerRow,
spriteSheet.height / amountPerColumn,
);
size = textureSize / 10;
animation = SpriteAnimation.fromFrameData(
spriteSheet,
SpriteAnimationData.sequenced(
amount: amountPerRow * amountPerColumn,
amountPerRow: amountPerRow,
stepTime: 1 / 24,
textureSize: textureSize,
loop: false,
),
);
}
}
| pinball/packages/pinball_components/lib/src/components/dash_animatronic.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/dash_animatronic.dart",
"repo_id": "pinball",
"token_count": 451
} | 1,370 |
import 'package:bloc/bloc.dart';
part 'flipper_state.dart';
class FlipperCubit extends Cubit<FlipperState> {
FlipperCubit() : super(FlipperState.movingDown);
void moveUp() => emit(FlipperState.movingUp);
void moveDown() => emit(FlipperState.movingDown);
}
| pinball/packages/pinball_components/lib/src/components/flipper/cubit/flipper_cubit.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/flipper/cubit/flipper_cubit.dart",
"repo_id": "pinball",
"token_count": 97
} | 1,371 |
import 'package:flame/components.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template kicker_blinking_behavior}
/// Makes a [Kicker] blink back to [KickerState.lit] when [KickerState.dimmed].
/// {@endtemplate}
class KickerBlinkingBehavior extends TimerComponent with ParentIsA<Kicker> {
/// {@macro kicker_blinking_behavior}
KickerBlinkingBehavior() : super(period: 0.05);
void _onNewState(KickerState state) {
switch (state) {
case KickerState.lit:
break;
case KickerState.dimmed:
timer
..reset()
..start();
break;
}
}
@override
Future<void> onLoad() async {
await super.onLoad();
timer.stop();
parent.bloc.stream.listen(_onNewState);
}
@override
void onTick() {
super.onTick();
timer.stop();
parent.bloc.onBlinked();
}
}
| pinball/packages/pinball_components/lib/src/components/kicker/behaviors/kicker_blinking_behavior.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/kicker/behaviors/kicker_blinking_behavior.dart",
"repo_id": "pinball",
"token_count": 369
} | 1,372 |
export 'plunger_jointing_behavior.dart';
export 'plunger_key_controlling_behavior.dart';
export 'plunger_noise_behavior.dart';
export 'plunger_pulling_behavior.dart';
export 'plunger_releasing_behavior.dart';
| pinball/packages/pinball_components/lib/src/components/plunger/behaviors/behaviors.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/plunger/behaviors/behaviors.dart",
"repo_id": "pinball",
"token_count": 78
} | 1,373 |
export 'skill_shot_ball_contact_behavior.dart';
export 'skill_shot_blinking_behavior.dart';
| pinball/packages/pinball_components/lib/src/components/skill_shot/behaviors/behaviors.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/skill_shot/behaviors/behaviors.dart",
"repo_id": "pinball",
"token_count": 31
} | 1,374 |
import 'package:flame/components.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template sparky_bumper_blinking_behavior}
/// Makes a [SparkyBumper] blink back to [SparkyBumperState.lit] when
/// [SparkyBumperState.dimmed].
/// {@endtemplate}
class SparkyBumperBlinkingBehavior extends TimerComponent
with ParentIsA<SparkyBumper> {
/// {@macro sparky_bumper_blinking_behavior}
SparkyBumperBlinkingBehavior() : super(period: 0.05);
void _onNewState(SparkyBumperState state) {
switch (state) {
case SparkyBumperState.lit:
break;
case SparkyBumperState.dimmed:
timer
..reset()
..start();
break;
}
}
@override
Future<void> onLoad() async {
await super.onLoad();
timer.stop();
parent.bloc.stream.listen(_onNewState);
}
@override
void onTick() {
super.onTick();
timer.stop();
parent.bloc.onBlinked();
}
}
| pinball/packages/pinball_components/lib/src/components/sparky_bumper/behaviors/sparky_bumper_blinking_behavior.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/sparky_bumper/behaviors/sparky_bumper_blinking_behavior.dart",
"repo_id": "pinball",
"token_count": 406
} | 1,375 |
import 'package:flame/game.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:sandbox/common/games.dart';
class ArrowIconGame extends AssetsGame with HasTappables {
ArrowIconGame()
: super(
imagesFileNames: [
Assets.images.displayArrows.arrowLeft.keyName,
Assets.images.displayArrows.arrowRight.keyName,
],
);
static const description = 'Shows how ArrowIcons are rendered.';
@override
Future<void> onLoad() async {
await super.onLoad();
camera.followVector2(Vector2.zero());
await add(
ArrowIcon(
position: Vector2.zero(),
direction: ArrowIconDirection.left,
onTap: () {},
),
);
await add(
ArrowIcon(
position: Vector2(0, 20),
direction: ArrowIconDirection.right,
onTap: () {},
),
);
}
}
| pinball/packages/pinball_components/sandbox/lib/stories/arrow_icon/arrow_icon_game.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/arrow_icon/arrow_icon_game.dart",
"repo_id": "pinball",
"token_count": 377
} | 1,376 |
import 'package:flame/components.dart';
import 'package:flame/input.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:sandbox/common/common.dart';
class CameraZoomGame extends AssetsGame with TapDetector {
static const description = '''
Shows how CameraZoom can be used.
- Tap to zoom in/out.
''';
bool zoomApplied = false;
@override
Future<void> onLoad() async {
final sprite = await loadSprite(Assets.images.signpost.inactive.keyName);
await add(
SpriteComponent(
sprite: sprite,
size: Vector2(4, 8),
anchor: Anchor.center,
),
);
camera.followVector2(Vector2.zero());
}
@override
void onTap() {
if (firstChild<CameraZoom>() == null) {
final zoom = CameraZoom(value: zoomApplied ? 30 : 10);
add(zoom);
zoomApplied = !zoomApplied;
}
}
}
| pinball/packages/pinball_components/sandbox/lib/stories/effects/camera_zoom_game.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/effects/camera_zoom_game.dart",
"repo_id": "pinball",
"token_count": 350
} | 1,377 |
import 'package:dashbook/dashbook.dart';
import 'package:sandbox/common/common.dart';
import 'package:sandbox/stories/multiball/multiball_game.dart';
void addMultiballStories(Dashbook dashbook) {
dashbook.storiesOf('Multiball').addGame(
title: 'Assets',
description: MultiballGame.description,
gameBuilder: (_) => MultiballGame(),
);
}
| pinball/packages/pinball_components/sandbox/lib/stories/multiball/stories.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/multiball/stories.dart",
"repo_id": "pinball",
"token_count": 142
} | 1,378 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_theme/pinball_theme.dart';
void main() {
group('ArcadeBackgroundState', () {
test('supports value equality', () {
expect(
ArcadeBackgroundState(characterTheme: DashTheme()),
equals(ArcadeBackgroundState(characterTheme: DashTheme())),
);
});
group('constructor', () {
test('can be instantiated', () {
expect(
ArcadeBackgroundState(characterTheme: DashTheme()),
isNotNull,
);
});
test('initial contains DashTheme', () {
expect(
ArcadeBackgroundState.initial().characterTheme,
DashTheme(),
);
});
});
});
}
| pinball/packages/pinball_components/test/src/components/arcade_background/cubit/arcade_background_state_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/arcade_background/cubit/arcade_background_state_test.dart",
"repo_id": "pinball",
"token_count": 330
} | 1,379 |
// ignore_for_file: cascade_invocations
import 'package:bloc_test/bloc_test.dart';
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/chrome_dino/behaviors/behaviors.dart';
import 'package:pinball_theme/pinball_theme.dart' as theme;
import '../../../../helpers/helpers.dart';
class _MockChromeDinoCubit extends Mock implements ChromeDinoCubit {}
class _MockContact extends Mock implements Contact {}
class _MockFixture extends Mock implements Fixture {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
theme.Assets.images.dash.ball.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));
group(
'ChromeDinoChompingBehavior',
() {
test('can be instantiated', () {
expect(
ChromeDinoChompingBehavior(),
isA<ChromeDinoChompingBehavior>(),
);
});
flameTester.test(
'beginContact sets ball sprite to be invisible and calls onChomp',
(game) async {
final ball = Ball();
final behavior = ChromeDinoChompingBehavior();
final bloc = _MockChromeDinoCubit();
whenListen(
bloc,
const Stream<ChromeDinoState>.empty(),
initialState: const ChromeDinoState(
status: ChromeDinoStatus.idle,
isMouthOpen: true,
),
);
final chromeDino = ChromeDino.test(bloc: bloc);
await chromeDino.add(behavior);
await game.ensureAddAll([chromeDino, ball]);
final contact = _MockContact();
final fixture = _MockFixture();
when(() => contact.fixtureA).thenReturn(fixture);
when(() => fixture.userData).thenReturn('inside_mouth');
behavior.beginContact(ball, contact);
expect(
ball.descendants().whereType<SpriteComponent>().single.getOpacity(),
isZero,
);
verify(() => bloc.onChomp(ball)).called(1);
},
);
},
);
}
| pinball/packages/pinball_components/test/src/components/chrome_dino/behaviors/chrome_dino_chomping_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/chrome_dino/behaviors/chrome_dino_chomping_behavior_test.dart",
"repo_id": "pinball",
"token_count": 972
} | 1,380 |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
import '../../helpers/helpers.dart';
extension _IterableX on Iterable<Component> {
int countTexts(String value) {
return where(
(component) => component is TextComponent && component.text == value,
).length;
}
}
void main() {
group('ErrorComponent', () {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
Assets.images.errorBackground.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));
flameTester.test('renders correctly', (game) async {
await game.ensureAdd(ErrorComponent(label: 'Error Message'));
final count = game.descendants().countTexts('Error Message');
expect(count, equals(1));
});
group('when the text is longer than one line', () {
flameTester.test('renders correctly', (game) async {
await game.ensureAdd(
ErrorComponent(
label: 'Error With A Longer Message',
),
);
final count1 = game.descendants().countTexts('Error With A');
final count2 = game.descendants().countTexts('Longer Message');
expect(count1, equals(1));
expect(count2, equals(1));
});
});
group('when using the bold font', () {
flameTester.test('renders correctly', (game) async {
await game.ensureAdd(ErrorComponent.bold(label: 'Error Message'));
final count = game.descendants().countTexts('Error Message');
expect(count, equals(1));
});
});
});
}
| pinball/packages/pinball_components/test/src/components/error_component_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/error_component_test.dart",
"repo_id": "pinball",
"token_count": 646
} | 1,381 |
// ignore_for_file: cascade_invocations
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
class TestBodyComponent extends BodyComponent with InitialPosition {
@override
Body createBody() {
return world.createBody(BodyDef());
}
}
class TestPositionedBodyComponent extends BodyComponent with InitialPosition {
@override
Body createBody() {
return world.createBody(BodyDef()..position = initialPosition);
}
}
void main() {
final flameTester = FlameTester(Forge2DGame.new);
group('InitialPosition', () {
test('correctly sets and gets', () {
final component = TestBodyComponent()..initialPosition = Vector2(1, 2);
expect(component.initialPosition, Vector2(1, 2));
});
flameTester.test(
'throws AssertionError '
'when BodyDef is not positioned with initialPosition',
(game) async {
final component = TestBodyComponent()
..initialPosition = Vector2.all(
10,
);
await expectLater(
() => game.ensureAdd(component),
throwsAssertionError,
);
},
);
flameTester.test(
'positions correctly',
(game) async {
final position = Vector2.all(10);
final component = TestPositionedBodyComponent()
..initialPosition = position;
await game.ensureAdd(component);
expect(component.body.position, equals(position));
},
);
flameTester.test(
'defaults to zero '
'when no initialPosition is given',
(game) async {
final component = TestBodyComponent();
await game.ensureAdd(component);
expect(component.body.position, equals(Vector2.zero()));
},
);
flameTester.test(
'setting throws AssertionError '
'when component has loaded',
(game) async {
final component = TestBodyComponent();
await game.ensureAdd(component);
expect(component.isLoaded, isTrue);
expect(
() => component.initialPosition = Vector2.all(4),
throwsAssertionError,
);
},
);
});
}
| pinball/packages/pinball_components/test/src/components/initial_position_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/initial_position_test.dart",
"repo_id": "pinball",
"token_count": 878
} | 1,382 |
// ignore_for_file: cascade_invocations
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(Forge2DGame.new);
group('PlungerJointingBehavior', () {
test('can be instantiated', () {
expect(
PlungerJointingBehavior(compressionDistance: 0),
isA<PlungerJointingBehavior>(),
);
});
flameTester.test('can be loaded', (game) async {
final parent = Plunger.test();
final behavior = PlungerJointingBehavior(compressionDistance: 0);
await game.ensureAdd(parent);
await parent.ensureAdd(behavior);
expect(parent.children, contains(behavior));
});
flameTester.test('creates a joint', (game) async {
final behavior = PlungerJointingBehavior(compressionDistance: 0);
final parent = Plunger.test();
await game.ensureAdd(parent);
await parent.ensureAdd(behavior);
expect(parent.body.joints, isNotEmpty);
});
});
}
| pinball/packages/pinball_components/test/src/components/plunger/behaviors/plunger_jointing_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/plunger/behaviors/plunger_jointing_behavior_test.dart",
"repo_id": "pinball",
"token_count": 446
} | 1,383 |
// ignore_for_file: cascade_invocations
import 'package:bloc_test/bloc_test.dart';
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/skill_shot/behaviors/behaviors.dart';
import '../../../helpers/helpers.dart';
class _MockSkillShotCubit extends Mock implements SkillShotCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
Assets.images.skillShot.decal.keyName,
Assets.images.skillShot.pin.keyName,
Assets.images.skillShot.lit.keyName,
Assets.images.skillShot.dimmed.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));
group('SkillShot', () {
flameTester.test('loads correctly', (game) async {
final skillShot = SkillShot();
await game.ensureAdd(skillShot);
expect(game.contains(skillShot), isTrue);
});
flameTester.test('closes bloc when removed', (game) async {
final bloc = _MockSkillShotCubit();
whenListen(
bloc,
const Stream<SkillShotState>.empty(),
initialState: const SkillShotState.initial(),
);
when(bloc.close).thenAnswer((_) async {});
final skillShot = SkillShot.test(bloc: bloc);
await game.ensureAdd(skillShot);
game.remove(skillShot);
await game.ready();
verify(bloc.close).called(1);
});
group('adds', () {
flameTester.test('new children', (game) async {
final component = Component();
final skillShot = SkillShot(
children: [component],
);
await game.ensureAdd(skillShot);
expect(skillShot.children, contains(component));
});
flameTester.test('a SkillShotBallContactBehavior', (game) async {
final skillShot = SkillShot();
await game.ensureAdd(skillShot);
expect(
skillShot.children.whereType<SkillShotBallContactBehavior>().single,
isNotNull,
);
});
flameTester.test('a SkillShotBlinkingBehavior', (game) async {
final skillShot = SkillShot();
await game.ensureAdd(skillShot);
expect(
skillShot.children.whereType<SkillShotBlinkingBehavior>().single,
isNotNull,
);
});
});
flameTester.test(
'pin stops animating after animation completes',
(game) async {
final skillShot = SkillShot();
await game.ensureAdd(skillShot);
final pinSpriteAnimationComponent =
skillShot.firstChild<PinSpriteAnimationComponent>()!;
pinSpriteAnimationComponent.playing = true;
game.update(
pinSpriteAnimationComponent.animation!.totalDuration() + 0.1,
);
expect(pinSpriteAnimationComponent.playing, isFalse);
},
);
});
}
| pinball/packages/pinball_components/test/src/components/skill_shot/skill_shot_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/skill_shot/skill_shot_test.dart",
"repo_id": "pinball",
"token_count": 1174
} | 1,384 |
import 'dart:math';
import 'package:flame/game.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_forge2d/world_contact_listener.dart';
// NOTE: This should be removed when https://github.com/flame-engine/flame/pull/1597 is solved.
/// {@template pinball_forge2d_game}
/// A [Game] that uses the Forge2D physics engine.
/// {@endtemplate}
class PinballForge2DGame extends FlameGame implements Forge2DGame {
/// {@macro pinball_forge2d_game}
PinballForge2DGame({
required Vector2 gravity,
}) : world = World(gravity),
super(camera: Camera()) {
camera.zoom = Forge2DGame.defaultZoom;
world.setContactListener(WorldContactListener());
}
@override
final World world;
@override
void update(double dt) {
super.update(dt);
world.stepDt(clampDt(dt));
}
@override
Vector2 screenToFlameWorld(Vector2 position) {
throw UnimplementedError();
}
@override
Vector2 screenToWorld(Vector2 position) {
throw UnimplementedError();
}
@override
Vector2 worldToScreen(Vector2 position) {
throw UnimplementedError();
}
/// Clamp the [dt] in such a way that it would never exceed the minimal of
/// 1/60th of a second.
///
/// Note: this is a static method because composing this class as a generic
/// on `BodyComponent` and mixins for that class will crash the Dart analyzer
/// server.
static double clampDt(double dt) {
return min(dt, 1 / 60);
}
}
| pinball/packages/pinball_flame/lib/src/pinball_forge2d_game.dart/0 | {
"file_path": "pinball/packages/pinball_flame/lib/src/pinball_forge2d_game.dart",
"repo_id": "pinball",
"token_count": 499
} | 1,385 |
export 'pinball_dialog.dart';
export 'pixelated_decoration.dart';
| pinball/packages/pinball_ui/lib/src/dialog/dialog.dart/0 | {
"file_path": "pinball/packages/pinball_ui/lib/src/dialog/dialog.dart",
"repo_id": "pinball",
"token_count": 24
} | 1,386 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_ui/pinball_ui.dart';
void main() {
group('PixelatedDecoration', () {
testWidgets('renders header and body', (tester) async {
const headerText = 'header';
const bodyText = 'body';
await tester.pumpWidget(
MaterialApp(
home: PixelatedDecoration(
header: Text(headerText),
body: Text(bodyText),
),
),
);
expect(find.text(headerText), findsOneWidget);
expect(find.text(bodyText), findsOneWidget);
});
});
}
| pinball/packages/pinball_ui/test/src/dialog/pixelated_decoration_test.dart/0 | {
"file_path": "pinball/packages/pinball_ui/test/src/dialog/pixelated_decoration_test.dart",
"repo_id": "pinball",
"token_count": 283
} | 1,387 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:platform_helper/platform_helper.dart';
void main() {
group('PlatformHelper', () {
test('can be instantiated', () {
expect(PlatformHelper(), isNotNull);
});
group('isMobile', () {
tearDown(() async {
debugDefaultTargetPlatformOverride = null;
});
test('returns true when defaultTargetPlatform is iOS', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
expect(PlatformHelper().isMobile, isTrue);
debugDefaultTargetPlatformOverride = null;
});
test('returns true when defaultTargetPlatform is android', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
expect(PlatformHelper().isMobile, isTrue);
debugDefaultTargetPlatformOverride = null;
});
test(
'returns false when defaultTargetPlatform is neither iOS nor android',
() async {
debugDefaultTargetPlatformOverride = TargetPlatform.macOS;
expect(PlatformHelper().isMobile, isFalse);
debugDefaultTargetPlatformOverride = null;
},
);
});
});
}
| pinball/packages/platform_helper/test/src/platform_helper_test.dart/0 | {
"file_path": "pinball/packages/platform_helper/test/src/platform_helper_test.dart",
"repo_id": "pinball",
"token_count": 449
} | 1,388 |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball_components/pinball_components.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.load(Assets.images.dash.animatronic.keyName);
}
}
class _TestSpriteAnimationComponent extends SpriteAnimationComponent {}
class _MockSpriteAnimation extends Mock implements SpriteAnimation {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
group('AnimatronicLoopingBehavior', () {
test('can be instantiated', () {
expect(
AnimatronicLoopingBehavior(animationCoolDown: 1),
isA<AnimatronicLoopingBehavior>(),
);
});
flameTester.test(
'can be added',
(game) async {
final behavior = AnimatronicLoopingBehavior(animationCoolDown: 1);
final animation = _MockSpriteAnimation();
final spriteAnimationComponent = _TestSpriteAnimationComponent()
..animation = animation;
await game.ensureAdd(spriteAnimationComponent);
await spriteAnimationComponent.add(behavior);
await game.ready();
expect(game.contains(spriteAnimationComponent), isTrue);
expect(spriteAnimationComponent.contains(behavior), isTrue);
},
);
flameTester.test(
'onTick starts playing the animation',
(game) async {
final behavior = AnimatronicLoopingBehavior(animationCoolDown: 1);
final spriteAnimationComponent = _TestSpriteAnimationComponent();
await game.ensureAdd(spriteAnimationComponent);
await spriteAnimationComponent.add(behavior);
spriteAnimationComponent.playing = false;
game.update(behavior.timer.limit);
expect(spriteAnimationComponent.playing, isTrue);
},
);
flameTester.test(
'animation onComplete resets and stops playing the animation',
(game) async {
final behavior = AnimatronicLoopingBehavior(animationCoolDown: 1);
final spriteAnimationComponent = DashAnimatronic();
await game.ensureAdd(spriteAnimationComponent);
await spriteAnimationComponent.add(behavior);
game.update(1);
expect(spriteAnimationComponent.playing, isTrue);
spriteAnimationComponent.animation!.onComplete!.call();
expect(spriteAnimationComponent.playing, isFalse);
expect(spriteAnimationComponent.animation!.currentIndex, equals(0));
},
);
flameTester.test(
'animation onComplete resets and starts the timer',
(game) async {
final behavior = AnimatronicLoopingBehavior(animationCoolDown: 1);
final spriteAnimationComponent = DashAnimatronic();
await game.ensureAdd(spriteAnimationComponent);
await spriteAnimationComponent.add(behavior);
game.update(0.5);
expect(behavior.timer.current, equals(0.5));
spriteAnimationComponent.animation!.onComplete!.call();
expect(behavior.timer.current, equals(0));
expect(behavior.timer.isRunning(), isTrue);
},
);
});
}
| pinball/test/game/behaviors/animatronic_looping_behavior_test.dart/0 | {
"file_path": "pinball/test/game/behaviors/animatronic_looping_behavior_test.dart",
"repo_id": "pinball",
"token_count": 1231
} | 1,389 |
// ignore_for_file: cascade_invocations, prefer_const_constructors
import 'dart:async';
import 'package:bloc_test/bloc_test.dart';
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball/game/components/android_acres/behaviors/behaviors.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.android.ramp.boardOpening.keyName,
Assets.images.android.ramp.railingForeground.keyName,
Assets.images.android.ramp.railingBackground.keyName,
Assets.images.android.ramp.main.keyName,
Assets.images.android.ramp.arrow.inactive.keyName,
Assets.images.android.ramp.arrow.active1.keyName,
Assets.images.android.ramp.arrow.active2.keyName,
Assets.images.android.ramp.arrow.active3.keyName,
Assets.images.android.ramp.arrow.active4.keyName,
Assets.images.android.ramp.arrow.active5.keyName,
Assets.images.android.rail.main.keyName,
Assets.images.android.rail.exit.keyName,
Assets.images.score.oneMillion.keyName,
]);
}
Future<void> pump(
List<Component> children, {
required SpaceshipRampCubit bloc,
required GameBloc gameBloc,
}) async {
await ensureAdd(
FlameMultiBlocProvider(
providers: [
FlameBlocProvider<GameBloc, GameState>.value(
value: gameBloc,
),
FlameBlocProvider<SpaceshipRampCubit, SpaceshipRampState>.value(
value: bloc,
),
],
children: [
ZCanvasComponent(children: children),
],
),
);
}
}
class _MockGameBloc extends Mock implements GameBloc {}
class _MockSpaceshipRampCubit extends Mock implements SpaceshipRampCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late GameBloc gameBloc;
setUp(() {
gameBloc = _MockGameBloc();
});
group('RampBonusBehavior', () {
const shotPoints = Points.oneMillion;
final flameTester = FlameTester(_TestGame.new);
flameTester.test(
'when hits are multiples of 10 times adds a ScoringBehavior',
(game) async {
final bloc = _MockSpaceshipRampCubit();
final state = SpaceshipRampState.initial();
final streamController = StreamController<SpaceshipRampState>();
whenListen(
bloc,
streamController.stream,
initialState: state,
);
final behavior = RampBonusBehavior(points: shotPoints);
final parent = SpaceshipRamp.test(children: [behavior]);
await game.pump(
[parent],
bloc: bloc,
gameBloc: gameBloc,
);
streamController.add(state.copyWith(hits: 10));
final scores = game.descendants().whereType<ScoringBehavior>();
await game.ready();
expect(scores.length, 1);
},
);
flameTester.test(
"when hits are not multiple of 10 times doesn't add any ScoringBehavior",
(game) async {
final bloc = _MockSpaceshipRampCubit();
final state = SpaceshipRampState.initial();
final streamController = StreamController<SpaceshipRampState>();
whenListen(
bloc,
streamController.stream,
initialState: state,
);
final behavior = RampBonusBehavior(points: shotPoints);
final parent = SpaceshipRamp.test(children: [behavior]);
await game.pump(
[parent],
bloc: bloc,
gameBloc: gameBloc,
);
streamController.add(state.copyWith(hits: 9));
final scores = game.descendants().whereType<ScoringBehavior>();
await game.ready();
expect(scores.length, 0);
},
);
});
}
| pinball/test/game/components/android_acres/behaviors/ramp_bonus_behavior_test.dart/0 | {
"file_path": "pinball/test/game/components/android_acres/behaviors/ramp_bonus_behavior_test.dart",
"repo_id": "pinball",
"token_count": 1734
} | 1,390 |
// ignore_for_file: cascade_invocations
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/bloc/game_bloc.dart';
import 'package:pinball/game/components/backbox/displays/share_display.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
class _TestGame extends Forge2DGame with HasTappables {
@override
Future<void> onLoad() async {
await super.onLoad();
images.prefix = '';
await images.loadAll(
[
Assets.images.backbox.button.facebook.keyName,
Assets.images.backbox.button.twitter.keyName,
],
);
}
Future<void> pump(ShareDisplay component) {
return ensureAdd(
FlameBlocProvider<GameBloc, GameState>.value(
value: GameBloc(),
children: [
FlameProvider.value(
_MockAppLocalizations(),
children: [component],
),
],
),
);
}
}
class _MockAppLocalizations extends Mock implements AppLocalizations {
@override
String get letEveryone => '';
@override
String get bySharingYourScore => '';
@override
String get socialMediaAccount => '';
}
class _MockTapUpInfo extends Mock implements TapUpInfo {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
group('ShareDisplay', () {
flameTester.test(
'loads correctly',
(game) async {
final component = ShareDisplay();
await game.pump(component);
expect(game.descendants(), contains(component));
},
);
flameTester.test(
'calls onShare when Facebook button is tapped',
(game) async {
var tapped = false;
final tapUpInfo = _MockTapUpInfo();
final component = ShareDisplay(
onShare: (_) => tapped = true,
);
await game.pump(component);
final facebookButton =
component.descendants().whereType<FacebookButtonComponent>().first;
facebookButton.onTapUp(tapUpInfo);
expect(tapped, isTrue);
},
);
flameTester.test(
'calls onShare when Twitter button is tapped',
(game) async {
var tapped = false;
final tapUpInfo = _MockTapUpInfo();
final component = ShareDisplay(
onShare: (_) => tapped = true,
);
await game.pump(component);
final twitterButton =
component.descendants().whereType<TwitterButtonComponent>().first;
twitterButton.onTapUp(tapUpInfo);
expect(tapped, isTrue);
},
);
});
}
| pinball/test/game/components/backbox/displays/share_display_test.dart/0 | {
"file_path": "pinball/test/game/components/backbox/displays/share_display_test.dart",
"repo_id": "pinball",
"token_count": 1167
} | 1,391 |
// ignore_for_file: cascade_invocations
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.multiplier.x2.lit.keyName,
Assets.images.multiplier.x2.dimmed.keyName,
Assets.images.multiplier.x3.lit.keyName,
Assets.images.multiplier.x3.dimmed.keyName,
Assets.images.multiplier.x4.lit.keyName,
Assets.images.multiplier.x4.dimmed.keyName,
Assets.images.multiplier.x5.lit.keyName,
Assets.images.multiplier.x5.dimmed.keyName,
Assets.images.multiplier.x6.lit.keyName,
Assets.images.multiplier.x6.dimmed.keyName,
]);
}
Future<void> pump(Multipliers child) async {
await ensureAdd(
FlameBlocProvider<GameBloc, GameState>.value(
value: GameBloc(),
children: [child],
),
);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
group('Multipliers', () {
flameTester.test(
'loads correctly',
(game) async {
final component = Multipliers();
await game.pump(component);
expect(game.descendants(), contains(component));
},
);
flameTester.test(
'loads five Multiplier',
(game) async {
final multipliersGroup = Multipliers();
await game.pump(multipliersGroup);
expect(
multipliersGroup.descendants().whereType<Multiplier>().length,
equals(5),
);
},
);
});
}
| pinball/test/game/components/multipliers/multipliers_test.dart/0 | {
"file_path": "pinball/test/game/components/multipliers/multipliers_test.dart",
"repo_id": "pinball",
"token_count": 765
} | 1,392 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/how_to_play/how_to_play.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:platform_helper/platform_helper.dart';
import '../helpers/helpers.dart';
class _MockPlatformHelper extends Mock implements PlatformHelper {}
void main() {
group('HowToPlayDialog', () {
late AppLocalizations l10n;
late PlatformHelper platformHelper;
setUp(() async {
l10n = await AppLocalizations.delegate.load(const Locale('en'));
platformHelper = _MockPlatformHelper();
when(() => platformHelper.isMobile).thenAnswer((_) => false);
});
test('can be instantiated', () {
expect(
HowToPlayDialog(onDismissCallback: () {}),
isA<HowToPlayDialog>(),
);
});
testWidgets('displays content for desktop', (tester) async {
when(() => platformHelper.isMobile).thenAnswer((_) => false);
await tester.pumpApp(
HowToPlayDialog(
onDismissCallback: () {},
),
platformHelper: platformHelper,
);
expect(find.text(l10n.howToPlay), findsOneWidget);
expect(find.text(l10n.tipsForFlips), findsOneWidget);
expect(find.text(l10n.launchControls), findsOneWidget);
expect(find.text(l10n.flipperControls), findsOneWidget);
expect(find.byType(RotatedBox), findsNWidgets(7)); // controls
});
testWidgets('displays content for mobile', (tester) async {
when(() => platformHelper.isMobile).thenAnswer((_) => true);
await tester.pumpApp(
HowToPlayDialog(
onDismissCallback: () {},
),
platformHelper: platformHelper,
);
expect(find.text(l10n.howToPlay), findsOneWidget);
expect(find.text(l10n.tipsForFlips), findsOneWidget);
expect(find.text(l10n.tapAndHoldRocket), findsOneWidget);
expect(find.text(l10n.tapLeftRightScreen), findsOneWidget);
});
testWidgets('disappears after 3 seconds', (tester) async {
await tester.pumpApp(
Builder(
builder: (context) {
return TextButton(
onPressed: () => showDialog<void>(
context: context,
builder: (_) => HowToPlayDialog(
onDismissCallback: () {},
),
),
child: const Text('test'),
);
},
),
platformHelper: platformHelper,
);
expect(find.byType(HowToPlayDialog), findsNothing);
await tester.tap(find.text('test'));
await tester.pumpAndSettle();
expect(find.byType(HowToPlayDialog), findsOneWidget);
await tester.pump(const Duration(seconds: 4));
await tester.pumpAndSettle();
expect(find.byType(HowToPlayDialog), findsNothing);
});
testWidgets('can be dismissed', (tester) async {
await tester.pumpApp(
Builder(
builder: (context) {
return TextButton(
onPressed: () => showDialog<void>(
context: context,
builder: (_) => HowToPlayDialog(
onDismissCallback: () {},
),
),
child: const Text('test'),
);
},
),
platformHelper: platformHelper,
);
expect(find.byType(HowToPlayDialog), findsNothing);
await tester.tap(find.text('test'));
await tester.pumpAndSettle();
await tester.tapAt(Offset.zero);
await tester.pumpAndSettle();
expect(find.byType(HowToPlayDialog), findsNothing);
});
});
}
| pinball/test/how_to_play/how_to_play_dialog_test.dart/0 | {
"file_path": "pinball/test/how_to_play/how_to_play_dialog_test.dart",
"repo_id": "pinball",
"token_count": 1625
} | 1,393 |
tasks:
- name: prepare tool
script: .ci/scripts/prepare_tool.sh
- name: create simulator
script: .ci/scripts/create_simulator.sh
- name: build examples
script: script/tool_runner.sh
args: ["build-examples", "--ios"]
- name: xcode analyze
script: script/tool_runner.sh
args: ["xcode-analyze", "--ios"]
- name: xcode analyze deprecation
# Ensure we don't accidentally introduce deprecated code.
script: script/tool_runner.sh
args: ["xcode-analyze", "--ios", "--ios-min-version=13.0"]
- name: native test
script: script/tool_runner.sh
args: ["native-test", "--ios", "--ios-destination", "platform=iOS Simulator,name=iPhone 13,OS=latest"]
- name: drive examples
# `drive-examples` contains integration tests, which changes the UI of the application.
# This UI change sometimes affects `xctest`.
# So we run `drive-examples` after `native-test`; changing the order will result ci failure.
script: script/tool_runner.sh
args: ["drive-examples", "--ios", "--exclude=script/configs/exclude_integration_ios.yaml"]
| plugins/.ci/targets/ios_platform_tests.yaml/0 | {
"file_path": "plugins/.ci/targets/ios_platform_tests.yaml",
"repo_id": "plugins",
"token_count": 375
} | 1,394 |
# FlutterFire - MOVED
The FlutterFire family of plugins has moved to the Firebase organization on GitHub. This makes it easier for us to collaborate with the Firebase team. We want to build the best integration we can!
Visit FlutterFire at its new home:
https://github.com/firebase/flutterfire
| plugins/FlutterFire.md/0 | {
"file_path": "plugins/FlutterFire.md",
"repo_id": "plugins",
"token_count": 75
} | 1,395 |
// 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_example/main.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Test snackbar', (WidgetTester tester) async {
WidgetsFlutterBinding.ensureInitialized();
await tester.pumpWidget(const CameraApp());
await tester.pumpAndSettle();
expect(find.byType(SnackBar), findsOneWidget);
});
}
| plugins/packages/camera/camera/example/test/main_test.dart/0 | {
"file_path": "plugins/packages/camera/camera/example/test/main_test.dart",
"repo_id": "plugins",
"token_count": 182
} | 1,396 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#106316)
// ignore: unnecessary_import
import 'dart:ui';
import 'package:camera/camera.dart';
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#106316)
// ignore: unnecessary_import
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('camera_value', () {
test('Can be created', () {
const CameraValue cameraValue = CameraValue(
isInitialized: false,
previewSize: Size(10, 10),
isRecordingPaused: false,
isRecordingVideo: false,
isTakingPicture: false,
isStreamingImages: false,
flashMode: FlashMode.auto,
exposureMode: ExposureMode.auto,
exposurePointSupported: true,
focusMode: FocusMode.auto,
deviceOrientation: DeviceOrientation.portraitUp,
lockedCaptureOrientation: DeviceOrientation.portraitUp,
recordingOrientation: DeviceOrientation.portraitUp,
focusPointSupported: true,
previewPauseOrientation: DeviceOrientation.portraitUp,
);
expect(cameraValue, isA<CameraValue>());
expect(cameraValue.isInitialized, isFalse);
expect(cameraValue.errorDescription, null);
expect(cameraValue.previewSize, const Size(10, 10));
expect(cameraValue.isRecordingPaused, isFalse);
expect(cameraValue.isRecordingVideo, isFalse);
expect(cameraValue.isTakingPicture, isFalse);
expect(cameraValue.isStreamingImages, isFalse);
expect(cameraValue.flashMode, FlashMode.auto);
expect(cameraValue.exposureMode, ExposureMode.auto);
expect(cameraValue.exposurePointSupported, true);
expect(cameraValue.deviceOrientation, DeviceOrientation.portraitUp);
expect(
cameraValue.lockedCaptureOrientation, DeviceOrientation.portraitUp);
expect(cameraValue.recordingOrientation, DeviceOrientation.portraitUp);
expect(cameraValue.isPreviewPaused, false);
expect(cameraValue.previewPauseOrientation, DeviceOrientation.portraitUp);
});
test('Can be created as uninitialized', () {
const CameraValue cameraValue = CameraValue.uninitialized();
expect(cameraValue, isA<CameraValue>());
expect(cameraValue.isInitialized, isFalse);
expect(cameraValue.errorDescription, null);
expect(cameraValue.previewSize, null);
expect(cameraValue.isRecordingPaused, isFalse);
expect(cameraValue.isRecordingVideo, isFalse);
expect(cameraValue.isTakingPicture, isFalse);
expect(cameraValue.isStreamingImages, isFalse);
expect(cameraValue.flashMode, FlashMode.auto);
expect(cameraValue.exposureMode, ExposureMode.auto);
expect(cameraValue.exposurePointSupported, false);
expect(cameraValue.focusMode, FocusMode.auto);
expect(cameraValue.deviceOrientation, DeviceOrientation.portraitUp);
expect(cameraValue.lockedCaptureOrientation, null);
expect(cameraValue.recordingOrientation, null);
expect(cameraValue.isPreviewPaused, isFalse);
expect(cameraValue.previewPauseOrientation, null);
});
test('Can be copied with isInitialized', () {
const CameraValue cv = CameraValue.uninitialized();
final CameraValue cameraValue = cv.copyWith(isInitialized: true);
expect(cameraValue, isA<CameraValue>());
expect(cameraValue.isInitialized, isTrue);
expect(cameraValue.errorDescription, null);
expect(cameraValue.previewSize, null);
expect(cameraValue.isRecordingPaused, isFalse);
expect(cameraValue.isRecordingVideo, isFalse);
expect(cameraValue.isTakingPicture, isFalse);
expect(cameraValue.isStreamingImages, isFalse);
expect(cameraValue.flashMode, FlashMode.auto);
expect(cameraValue.focusMode, FocusMode.auto);
expect(cameraValue.exposureMode, ExposureMode.auto);
expect(cameraValue.exposurePointSupported, false);
expect(cameraValue.deviceOrientation, DeviceOrientation.portraitUp);
expect(cameraValue.lockedCaptureOrientation, null);
expect(cameraValue.recordingOrientation, null);
expect(cameraValue.isPreviewPaused, isFalse);
expect(cameraValue.previewPauseOrientation, null);
});
test('Has aspectRatio after setting size', () {
const CameraValue cv = CameraValue.uninitialized();
final CameraValue cameraValue =
cv.copyWith(isInitialized: true, previewSize: const Size(20, 10));
expect(cameraValue.aspectRatio, 2.0);
});
test('hasError is true after setting errorDescription', () {
const CameraValue cv = CameraValue.uninitialized();
final CameraValue cameraValue = cv.copyWith(errorDescription: 'error');
expect(cameraValue.hasError, isTrue);
expect(cameraValue.errorDescription, 'error');
});
test('Recording paused is false when not recording', () {
const CameraValue cv = CameraValue.uninitialized();
final CameraValue cameraValue = cv.copyWith(
isInitialized: true,
isRecordingVideo: false,
isRecordingPaused: true);
expect(cameraValue.isRecordingPaused, isFalse);
});
test('toString() works as expected', () {
const CameraValue cameraValue = CameraValue(
isInitialized: false,
previewSize: Size(10, 10),
isRecordingPaused: false,
isRecordingVideo: false,
isTakingPicture: false,
isStreamingImages: false,
flashMode: FlashMode.auto,
exposureMode: ExposureMode.auto,
focusMode: FocusMode.auto,
exposurePointSupported: true,
focusPointSupported: true,
deviceOrientation: DeviceOrientation.portraitUp,
lockedCaptureOrientation: DeviceOrientation.portraitUp,
recordingOrientation: DeviceOrientation.portraitUp,
isPreviewPaused: true,
previewPauseOrientation: DeviceOrientation.portraitUp);
expect(cameraValue.toString(),
'CameraValue(isRecordingVideo: false, isInitialized: false, errorDescription: null, previewSize: Size(10.0, 10.0), isStreamingImages: false, flashMode: FlashMode.auto, exposureMode: ExposureMode.auto, focusMode: FocusMode.auto, exposurePointSupported: true, focusPointSupported: true, deviceOrientation: DeviceOrientation.portraitUp, lockedCaptureOrientation: DeviceOrientation.portraitUp, recordingOrientation: DeviceOrientation.portraitUp, isPreviewPaused: true, previewPausedOrientation: DeviceOrientation.portraitUp)');
});
});
}
| plugins/packages/camera/camera/test/camera_value_test.dart/0 | {
"file_path": "plugins/packages/camera/camera/test/camera_value_test.dart",
"repo_id": "plugins",
"token_count": 2422
} | 1,397 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera;
import android.app.Activity;
import android.content.Context;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Provides various utilities for camera. */
public final class CameraUtils {
private CameraUtils() {}
/**
* Gets the {@link CameraManager} singleton.
*
* @param context The context to get the {@link CameraManager} singleton from.
* @return The {@link CameraManager} singleton.
*/
static CameraManager getCameraManager(Context context) {
return (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
}
/**
* Serializes the {@link PlatformChannel.DeviceOrientation} to a string value.
*
* @param orientation The orientation to serialize.
* @return The serialized orientation.
* @throws UnsupportedOperationException when the provided orientation not have a corresponding
* string value.
*/
static String serializeDeviceOrientation(PlatformChannel.DeviceOrientation orientation) {
if (orientation == null)
throw new UnsupportedOperationException("Could not serialize null device orientation.");
switch (orientation) {
case PORTRAIT_UP:
return "portraitUp";
case PORTRAIT_DOWN:
return "portraitDown";
case LANDSCAPE_LEFT:
return "landscapeLeft";
case LANDSCAPE_RIGHT:
return "landscapeRight";
default:
throw new UnsupportedOperationException(
"Could not serialize device orientation: " + orientation.toString());
}
}
/**
* Deserializes a string value to its corresponding {@link PlatformChannel.DeviceOrientation}
* value.
*
* @param orientation The string value to deserialize.
* @return The deserialized orientation.
* @throws UnsupportedOperationException when the provided string value does not have a
* corresponding {@link PlatformChannel.DeviceOrientation}.
*/
static PlatformChannel.DeviceOrientation deserializeDeviceOrientation(String orientation) {
if (orientation == null)
throw new UnsupportedOperationException("Could not deserialize null device orientation.");
switch (orientation) {
case "portraitUp":
return PlatformChannel.DeviceOrientation.PORTRAIT_UP;
case "portraitDown":
return PlatformChannel.DeviceOrientation.PORTRAIT_DOWN;
case "landscapeLeft":
return PlatformChannel.DeviceOrientation.LANDSCAPE_LEFT;
case "landscapeRight":
return PlatformChannel.DeviceOrientation.LANDSCAPE_RIGHT;
default:
throw new UnsupportedOperationException(
"Could not deserialize device orientation: " + orientation);
}
}
/**
* Gets all the available cameras for the device.
*
* @param activity The current Android activity.
* @return A map of all the available cameras, with their name as their key.
* @throws CameraAccessException when the camera could not be accessed.
*/
public static List<Map<String, Object>> getAvailableCameras(Activity activity)
throws CameraAccessException {
CameraManager cameraManager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
String[] cameraNames = cameraManager.getCameraIdList();
List<Map<String, Object>> cameras = new ArrayList<>();
for (String cameraName : cameraNames) {
int cameraId;
try {
cameraId = Integer.parseInt(cameraName, 10);
} catch (NumberFormatException e) {
cameraId = -1;
}
if (cameraId < 0) {
continue;
}
HashMap<String, Object> details = new HashMap<>();
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraName);
details.put("name", cameraName);
int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
details.put("sensorOrientation", sensorOrientation);
int lensFacing = characteristics.get(CameraCharacteristics.LENS_FACING);
switch (lensFacing) {
case CameraMetadata.LENS_FACING_FRONT:
details.put("lensFacing", "front");
break;
case CameraMetadata.LENS_FACING_BACK:
details.put("lensFacing", "back");
break;
case CameraMetadata.LENS_FACING_EXTERNAL:
details.put("lensFacing", "external");
break;
}
cameras.add(details);
}
return cameras;
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/CameraUtils.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/CameraUtils.java",
"repo_id": "plugins",
"token_count": 1652
} | 1,398 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.flash;
// Mirrors flash_mode.dart
public enum FlashMode {
off("off"),
auto("auto"),
always("always"),
torch("torch");
private final String strValue;
FlashMode(String strValue) {
this.strValue = strValue;
}
/**
* Tries to convert the supplied string into a {@see FlashMode} enum value.
*
* <p>When the supplied string doesn't match a valid {@see FlashMode} enum value, null is
* returned.
*
* @param modeStr String value to convert into an {@see FlashMode} enum value.
* @return Matching {@see FlashMode} enum value, or null if no match is found.
*/
public static FlashMode getValueForString(String modeStr) {
for (FlashMode 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/features/flash/FlashMode.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/flash/FlashMode.java",
"repo_id": "plugins",
"token_count": 341
} | 1,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.