text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.flutter.plugins.quickactionsexample"> <!-- Flutter needs internet permission to communicate with the running application to allow setting breakpoints, to provide hot reload, etc. --> <uses-permission android:name="android.permission.INTERNET"/> <application android:usesCleartextTraffic="true"> <activity android:name=".QuickActionsTestActivity" android:launchMode="singleTop" android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize"> </activity> </application> </manifest>
packages/packages/quick_actions/quick_actions_android/example/android/app/src/debug/AndroidManifest.xml/0
{ "file_path": "packages/packages/quick_actions/quick_actions_android/example/android/app/src/debug/AndroidManifest.xml", "repo_id": "packages", "token_count": 321 }
1,122
// 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 private let elementWaitingTime: TimeInterval = 30 // The duration in when pressing the app icon to open the // quick action menu. This duration is undocumented by Apple. // The duration will be adjusted with `pressDurationRetryAdjustment` if // this duration does not result in the quick action menu opened. private let quickActionPressDuration: TimeInterval = 1.5 // If the previous try to open quick action menu did not work, // a new try with adjust the press time by this value. // The adjusment could be + or - depends on the result of the previous try. private let pressDurationRetryAdjustment: TimeInterval = 0.2 // Max number of tries to open the quick action menu if failed. // This is to deflake a situation where the quick action menu is not present after // the long press. // See: https://github.com/flutter/flutter/issues/125509 private let quickActionMaxRetries: Int = 4 class RunnerUITests: XCTestCase { private var exampleApp: XCUIApplication! override func setUp() { super.setUp() self.continueAfterFailure = false exampleApp = XCUIApplication() } override func tearDown() { super.tearDown() exampleApp.terminate() exampleApp = nil } func testQuickActionWithFreshStart() { let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard") let quickActionsAppIcon = springboard.icons["quick_actions_example"] findAndTapQuickActionButton( buttonName: "Action two", quickActionsAppIcon: quickActionsAppIcon, springboard: springboard) let actionTwoConfirmation = exampleApp.otherElements["action_two"] if !actionTwoConfirmation.waitForExistence(timeout: elementWaitingTime) { XCTFail( "Failed due to not able to find the actionTwoConfirmation in the app with \(elementWaitingTime) seconds. Springboard debug description: \(springboard.debugDescription)" ) } XCTAssert(actionTwoConfirmation.exists) } func testQuickActionWhenAppIsInBackground() { exampleApp.launch() let actionsReady = exampleApp.otherElements["actions ready"] if !actionsReady.waitForExistence(timeout: elementWaitingTime) { XCTFail( "Failed due to not able to find the actionsReady in the app with \(elementWaitingTime) seconds. App debug description: \(exampleApp.debugDescription)" ) } XCUIDevice.shared.press(.home) let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard") let quickActionsAppIcon = springboard.icons["quick_actions_example"] if !quickActionsAppIcon.waitForExistence(timeout: elementWaitingTime) { XCTFail( "Failed due to not able to find the example app from springboard with \(elementWaitingTime) seconds. Springboard debug description: \(springboard.debugDescription)" ) } findAndTapQuickActionButton( buttonName: "Action one", quickActionsAppIcon: quickActionsAppIcon, springboard: springboard) let actionOneConfirmation = exampleApp.otherElements["action_one"] if !actionOneConfirmation.waitForExistence(timeout: elementWaitingTime) { XCTFail( "Failed due to not able to find the actionOneConfirmation in the app with \(elementWaitingTime) seconds. Springboard debug description: \(springboard.debugDescription)" ) } XCTAssert(actionOneConfirmation.exists) } private func findAndTapQuickActionButton( buttonName: String, quickActionsAppIcon: XCUIElement, springboard: XCUIElement ) { var actionButton: XCUIElement? var pressDuration = quickActionPressDuration for _ in 1...quickActionMaxRetries { if !quickActionsAppIcon.waitForExistence(timeout: elementWaitingTime) { XCTFail( "Failed due to not able to find the example app from springboard with \(elementWaitingTime) seconds. Springboard debug description: \(springboard.debugDescription)" ) } quickActionsAppIcon.press(forDuration: pressDuration) actionButton = springboard.buttons[buttonName] if actionButton!.waitForExistence(timeout: elementWaitingTime) { // find the button, exit the retry loop. break } let deleteButton = springboard.buttons["DeleteButton"] if deleteButton.waitForExistence(timeout: elementWaitingTime) { // Found delete button instead, we pressed too long, reduce the press time. pressDuration -= pressDurationRetryAdjustment } else { // Neither action button nor delete button was found, we need a longer press. pressDuration += pressDurationRetryAdjustment } // Reset to previous state. XCUIDevice.shared.press(XCUIDevice.Button.home) } if !actionButton!.exists { XCTFail( "Failed due to not able to find the \(buttonName) button from springboard with \(elementWaitingTime) seconds. Springboard debug description: \(springboard.debugDescription)" ) } actionButton!.tap() } }
packages/packages/quick_actions/quick_actions_ios/example/ios/RunnerUITests/RunnerUITests.swift/0
{ "file_path": "packages/packages/quick_actions/quick_actions_ios/example/ios/RunnerUITests/RunnerUITests.swift", "repo_id": "packages", "token_count": 1630 }
1,123
## 1.0.26 * Supports overriding the error widget builder. ## 1.0.25 * Adds support for wildget builders. ## 1.0.24 * Adds `InkResponse` material widget. * Adds `Material` material widget. * Adds the `child` to `Opacity` core widget. * Implements more `InkWell` parameters. ## 1.0.23 * Replaces usage of deprecated Flutter APIs. ## 1.0.22 * Adds more testing to restore coverage to 100%. * Format documentation. ## 1.0.21 * Adds support for subscribing to the root of a `DynamicContent` object. ## 1.0.20 * Adds `OverflowBox` material widget. * Updates `ButtonBar` material widget implementation. ## 1.0.19 * Add `DropdownButton` and `ClipRRect` widgets to rfw widget library. ## 1.0.18 * Exposes `WidgetLibrary`s registered in `Runtime`. * Exposes widgets map in `LocalWidgetLibrary`. ## 1.0.17 * Adds support for tracking source locations of `BlobNode`s and finding `BlobNode`s from the widget tree (`BlobNode.source` and `Runtime.blobNodeFor` respectively). ## 1.0.16 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Fixes lint warnings. ## 1.0.15 * Updates README.md to point to the CONTRIBUTING.md file. * Introduces CONTRIBUTING.md, and adds more information about golden testing. ## 1.0.14 * Adds pub topics to package metadata. ## 1.0.13 * Block comments in RFW's text format. (`/*...*/`) ## 1.0.12 * Improves web compatibility. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. * Adds more testing to restore coverage to 100%. * Removes some dead code. ## 1.0.11 * Adds more documentation in the README.md file! * Adds automated verification of the sample code in the README. ## 1.0.10 * Fixes stale ignore: `prefer_const_constructors`. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Changes package internals to avoid explicit `as Uint8List` downcast. ## 1.0.9 * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. * Aligns Dart and Flutter SDK constraints. * Fixes a typo in the API documentation that broke the formatting. ## 1.0.8 * Removes use of `runtimeType.toString()`. * Updates code to fix strict-cast violations. ## 1.0.7 * Updates README. ## 1.0.6 * Temporarily lowers test coverage minimum to fix flutter roll. * Disables golden testing due to https://github.com/flutter/flutter/issues/106205. * Fixes lint warnings. ## 1.0.5 * Fixes URL in document. ## 1.0.4 * Migrates from `ui.hash*` to `Object.hash*`. ## 1.0.3 * Transitions internal testing from a command line lcov tool to a Dart tool. No effect on consumers. * Removes unsupported platforms from the wasm example. * Updates for non-nullable bindings. ## 1.0.2 * Mentions FractionallySizedBox in documentation. ## 1.0.1 * Improves documentation. * Provides constants for the file signatures. * Minor efficiency improvements. * Fixes `unnecessary_import` lint errors. * Adds one more core widget, FractionallySizedBox. ## 1.0.0 * Initial release.
packages/packages/rfw/CHANGELOG.md/0
{ "file_path": "packages/packages/rfw/CHANGELOG.md", "repo_id": "packages", "token_count": 954 }
1,124
// 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. // This file is hand-formatted. import 'dart:io'; import 'package:flutter/material.dart'; import 'package:path/path.dart' as path; import 'package:path_provider/path_provider.dart'; import 'package:rfw/rfw.dart'; const String urlPrefix = 'https://raw.githubusercontent.com/flutter/packages/main/packages/rfw/example/remote/remote_widget_libraries'; void main() { runApp(const MaterialApp(home: Example())); } class Example extends StatefulWidget { const Example({super.key}); @override State<Example> createState() => _ExampleState(); } class _ExampleState extends State<Example> { final Runtime _runtime = Runtime(); final DynamicContent _data = DynamicContent(); bool _ready = false; int _counter = 0; @override void initState() { super.initState(); _runtime.update(const LibraryName(<String>['core', 'widgets']), createCoreWidgets()); _runtime.update(const LibraryName(<String>['core', 'material']), createMaterialWidgets()); _updateData(); _updateWidgets(); } void _updateData() { _data.update('counter', _counter.toString()); } Future<void> _updateWidgets() async { final Directory home = await getApplicationSupportDirectory(); final File settingsFile = File(path.join(home.path, 'settings.txt')); String nextFile = 'counter_app1.rfw'; if (settingsFile.existsSync()) { final String settings = await settingsFile.readAsString(); if (settings == nextFile) { nextFile = 'counter_app2.rfw'; } } final File currentFile = File(path.join(home.path, 'current.rfw')); if (currentFile.existsSync()) { try { _runtime.update(const LibraryName(<String>['main']), decodeLibraryBlob(await currentFile.readAsBytes())); setState(() { _ready = true; }); } catch (e, stack) { FlutterError.reportError(FlutterErrorDetails(exception: e, stack: stack)); } } print('Fetching: $urlPrefix/$nextFile'); // ignore: avoid_print final HttpClientResponse client = await (await HttpClient().getUrl(Uri.parse('$urlPrefix/$nextFile'))).close(); await currentFile.writeAsBytes(await client.expand((List<int> chunk) => chunk).toList()); await settingsFile.writeAsString(nextFile); } @override Widget build(BuildContext context) { final Widget result; if (_ready) { result = RemoteWidget( runtime: _runtime, data: _data, widget: const FullyQualifiedWidgetName(LibraryName(<String>['main']), 'Counter'), onEvent: (String name, DynamicMap arguments) { if (name == 'increment') { _counter += 1; _updateData(); } }, ); } else { result = const Material( child: SafeArea( child: Padding( padding: EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Padding(padding: EdgeInsets.only(right: 100.0), child: Text('REMOTE', textAlign: TextAlign.center, style: TextStyle(letterSpacing: 12.0))), Expanded(child: DecoratedBox(decoration: FlutterLogoDecoration(style: FlutterLogoStyle.horizontal))), Padding(padding: EdgeInsets.only(left: 100.0), child: Text('WIDGETS', textAlign: TextAlign.center, style: TextStyle(letterSpacing: 12.0))), Spacer(), Expanded(child: Text('Every time this program is run, it fetches a new remote widgets library.', textAlign: TextAlign.center)), Expanded(child: Text('The interface that it shows is whatever library was last fetched.', textAlign: TextAlign.center)), Expanded(child: Text('Restart this application to see the new interface!', textAlign: TextAlign.center)), ], ), ), ), ); } return AnimatedSwitcher(duration: const Duration(milliseconds: 1250), switchOutCurve: Curves.easeOut, switchInCurve: Curves.easeOut, child: result); } }
packages/packages/rfw/example/remote/lib/main.dart/0
{ "file_path": "packages/packages/rfw/example/remote/lib/main.dart", "repo_id": "packages", "token_count": 1626 }
1,125
{ "name": "remote", "short_name": "remote", "start_url": ".", "display": "standalone", "background_color": "#0175C2", "theme_color": "#0175C2", "description": "Example of fetching remote widgets for RFW", "orientation": "portrait-primary", "prefer_related_applications": false, "icons": [ { "src": "icons/Icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icons/Icon-512.png", "sizes": "512x512", "type": "image/png" }, { "src": "icons/Icon-maskable-192.png", "sizes": "192x192", "type": "image/png", "purpose": "maskable" }, { "src": "icons/Icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" } ] }
packages/packages/rfw/example/remote/web/manifest.json/0
{ "file_path": "packages/packages/rfw/example/remote/web/manifest.json", "repo_id": "packages", "token_count": 515 }
1,126
// 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. // This file is hand-formatted. import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:rfw/formats.dart' show parseLibraryFile; import 'package:rfw/rfw.dart'; void main() { testWidgets('Core widgets', (WidgetTester tester) async { final Runtime runtime = Runtime() ..update(const LibraryName(<String>['core']), createCoreWidgets()); final DynamicContent data = DynamicContent(); final List<String> eventLog = <String>[]; await tester.pumpWidget( RemoteWidget( runtime: runtime, data: data, widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'), onEvent: (String eventName, DynamicMap eventArguments) { eventLog.add('$eventName $eventArguments'); }, ), ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = GestureDetector( onTapDown: event 'tapdown' { }, onTapUp: event 'tapup' { }, onTap: event 'tap' { }, child: ColoredBox(), ); ''')); await tester.pump(); await tester.tap(find.byType(ColoredBox)); expect(eventLog, <String>['tapdown {}', 'tapup {}', 'tap {}']); eventLog.clear(); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = IntrinsicHeight(); ''')); await tester.pump(); expect(find.byType(IntrinsicHeight), findsOneWidget); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = IntrinsicWidth(); ''')); await tester.pump(); expect(find.byType(IntrinsicWidth), findsOneWidget); ArgumentDecoders.imageProviderDecoders['beepboop'] = (DataSource source, List<Object> key) { return MemoryImage(Uint8List.fromList(<int>[ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0xff, 0x00, 0xc0, 0xc0, 0xc0, 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3b, ])); }; runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Image(source: 'beepboop'); ''')); await tester.pump(); expect(find.byType(Image), findsOneWidget); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = SingleChildScrollView(child: ListBody()); ''')); await tester.pump(); expect(find.byType(SingleChildScrollView), findsOneWidget); expect(find.byType(ListBody), findsOneWidget); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Directionality( textDirection: "rtl", child: ListView( children: [ Container(height: 67.0), Container(height: 67.0), Container(height: 67.0), Container(height: 67.0), Container(height: 67.0), Container(height: 67.0), Container(height: 67.0), Container(height: 67.0), Container(height: 67.0), Container(height: 67.0), // number 10 is not visible ], ), ); ''')); await tester.pump(); expect(find.byType(ListView), findsOneWidget); expect(find.byType(Container), findsNWidgets(9)); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Opacity( onEnd: event 'end' {}, child: Placeholder(), ); ''')); await tester.pump(); expect(tester.widget<AnimatedOpacity>(find.byType(AnimatedOpacity)).onEnd, isNot(isNull)); expect(eventLog, isEmpty); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Directionality(textDirection: "ltr", child: Padding(padding: [12.0])); ''')); await tester.pump(); expect(tester.widget<Padding>(find.byType(Padding)).padding.resolve(TextDirection.ltr), const EdgeInsets.all(12.0)); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Directionality(textDirection: "ltr", child: Padding(padding: [24.0])); ''')); await tester.pump(); expect(tester.widget<Padding>(find.byType(Padding)).padding.resolve(TextDirection.ltr), const EdgeInsets.all(12.0)); await tester.pump(const Duration(seconds: 4)); expect(tester.widget<Padding>(find.byType(Padding)).padding.resolve(TextDirection.ltr), const EdgeInsets.all(24.0)); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Placeholder(); ''')); await tester.pump(); expect(find.byType(Placeholder), findsOneWidget); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Directionality( textDirection: "ltr", child: Stack( children: [ Positioned( start: 0.0, top: 0.0, width: 10.0, height: 10.0, child: ColoredBox(), ), ], ), ); ''')); await tester.pump(); expect(find.byType(Stack), findsOneWidget); expect(find.byType(Positioned), findsOneWidget); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Directionality( textDirection: "rtl", child: Rotation(turns: 0.0), ); ''')); await tester.pump(); expect(find.byType(AnimatedRotation), findsOneWidget); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Directionality( textDirection: "rtl", child: Rotation(turns: 1.0, onEnd: event 'end' { from: "rotation" }), ); ''')); await tester.pump(); expect(find.byType(AnimatedRotation), findsOneWidget); expect(eventLog, isEmpty); await tester.pump(const Duration(seconds: 1)); expect(eventLog, <String>['end {from: rotation}']); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Directionality( textDirection: "rtl", child: Row( crossAxisAlignment: "start", children: [SizedBox(width: 10.0)] ), ); ''')); await tester.pump(); expect(tester.getTopLeft(find.byType(SizedBox)), const Offset(790.0, 0.0)); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Directionality( textDirection: "rtl", child: Row( crossAxisAlignment: "start", children: [Spacer()] ), ); ''')); await tester.pump(); expect(tester.getTopLeft(find.byType(SizedBox)), Offset.zero); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = SizedBoxExpand(); ''')); await tester.pump(); expect(find.byType(SizedBox), findsOneWidget); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = SizedBoxShrink(); ''')); await tester.pump(); expect(find.byType(SizedBox), findsOneWidget); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Directionality( textDirection: "ltr", child: FractionallySizedBox( widthFactor: 0.5, heightFactor: 0.8, child: Text( text: "test", textScaleFactor: 3.0, ), ), ); ''')); await tester.pump(); final Size fractionallySizedBoxSize = tester.getSize(find.byType(FractionallySizedBox)); final Size childSize = tester.getSize(find.text('test')); expect(childSize.width, fractionallySizedBoxSize.width * 0.5); expect(childSize.height, fractionallySizedBoxSize.height * 0.8); expect(tester.widget<Text>(find.text('test')).textScaler, const TextScaler.linear(3)); expect(tester.widget<FractionallySizedBox>(find.byType(FractionallySizedBox)).alignment, Alignment.center); }); testWidgets('More core widgets', (WidgetTester tester) async { final Runtime runtime = Runtime() ..update(const LibraryName(<String>['core']), createCoreWidgets()); final DynamicContent data = DynamicContent(); final List<String> eventLog = <String>[]; await tester.pumpWidget( MaterialApp( home: RemoteWidget( runtime: runtime, data: data, widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'), onEvent: (String eventName, DynamicMap eventArguments) { eventLog.add('$eventName $eventArguments'); }, ), ), ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = SafeArea( child: SizedBoxShrink(), ); ''')); await tester.pump(); expect(find.byType(SafeArea), findsOneWidget); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Scale(); ''')); await tester.pump(); expect(find.byType(AnimatedScale), findsOneWidget); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Wrap(); ''')); await tester.pump(); expect(find.byType(Wrap), findsOneWidget); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = ClipRRect(); ''')); await tester.pump(); expect(find.byType(ClipRRect), findsOneWidget); final RenderClipRRect renderClip = tester.allRenderObjects.whereType<RenderClipRRect>().first; expect(renderClip.clipBehavior, equals(Clip.antiAlias)); expect(renderClip.borderRadius, equals(BorderRadius.zero)); }); }
packages/packages/rfw/test/core_widgets_test.dart/0
{ "file_path": "packages/packages/rfw/test/core_widgets_test.dart", "repo_id": "packages", "token_count": 4416 }
1,127
name: shared_preferences_android description: Android implementation of the shared_preferences plugin repository: https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22 version: 2.2.1 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: shared_preferences platforms: android: package: io.flutter.plugins.sharedpreferences pluginClass: SharedPreferencesPlugin dartPluginClass: SharedPreferencesAndroid dependencies: flutter: sdk: flutter shared_preferences_platform_interface: ^2.3.0 dev_dependencies: flutter_test: sdk: flutter pigeon: ^9.2.3 topics: - persistence - shared-preferences - storage
packages/packages/shared_preferences/shared_preferences_android/pubspec.yaml/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_android/pubspec.yaml", "repo_id": "packages", "token_count": 324 }
1,128
name: shared_preferences_example description: Testbed for the shared_preferences_foundation implementation. publish_to: none environment: sdk: ^3.2.3 flutter: ">=3.16.6" dependencies: flutter: sdk: flutter shared_preferences_foundation: # When depending on this package from a real application you should use: # shared_preferences_foundation: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ shared_preferences_platform_interface: ^2.3.0 dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true
packages/packages/shared_preferences/shared_preferences_foundation/example/pubspec.yaml/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_foundation/example/pubspec.yaml", "repo_id": "packages", "token_count": 269 }
1,129
<?code-excerpt path-base="example/lib"?> An efficient and schemaless binary format used by the Flutter SDK. ## Features ### Efficiency The standard message codec is a binary format, as opposed to text based formats like JSON. Consider the following snippet of JSON: ```json { "data": [1, 2, 3, 4], } ``` In order for this message to be decoded into a Dart map, a utf8 binary file must first be parsed and validated into a Dart string. Then a second pass is performed which looks for specific characters that indicate JSON structures - for example "{" and "}". No sizes or lengths are known ahead of time while, parsing, so the resulting Dart list created for the "data" key is append to as decoding happens. In contrast, decoding the standard message codec version of this message avoids utf8 decoding, instead operating on the bytes themselves. The only string constructed will be for the "data" key. The length of the list in the data field is encoded in the structure, meaning the correct length object can be allocated and filled in as decoding happens. ### Schemaless Using standard message codec does not require a schema (like protobuf) or any generated code. This makes it easy to use for dynamic messages and simplifies the integration into existing codebases. The tradeoff for this ease of use is that it becomes the application's responsibility to verify the structure of messages sent/received. There is also no automatic backwards compatibility like protobuf. ## Getting started standard_message_codec can be used to encode and decode messages in either Flutter or pure Dart applications. <?code-excerpt "readme_excerpts.dart (Encoding)"?> ```dart void main() { final ByteData? data = const StandardMessageCodec().encodeMessage(<Object, Object>{ 'foo': true, 3: 'fizz', }); print('The encoded message is $data'); } ```
packages/packages/standard_message_codec/README.md/0
{ "file_path": "packages/packages/standard_message_codec/README.md", "repo_id": "packages", "token_count": 489 }
1,130
# TableView Example A sample application that utilizes the TableView API.
packages/packages/two_dimensional_scrollables/example/README.md/0
{ "file_path": "packages/packages/two_dimensional_scrollables/example/README.md", "repo_id": "packages", "token_count": 17 }
1,131
// 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/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:two_dimensional_scrollables/two_dimensional_scrollables.dart'; const TableSpan span = TableSpan(extent: FixedTableSpanExtent(100)); const TableViewCell cell = TableViewCell(child: SizedBox.shrink()); TableSpan getTappableSpan(int index, VoidCallback callback) { return TableSpan( extent: const FixedTableSpanExtent(100), recognizerFactories: <Type, GestureRecognizerFactory>{ TapGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>( () => TapGestureRecognizer(), (TapGestureRecognizer t) => t.onTap = () => callback(), ), }, ); } TableSpan getMouseTrackingSpan( int index, { PointerEnterEventListener? onEnter, PointerExitEventListener? onExit, }) { return TableSpan( extent: const FixedTableSpanExtent(100), onEnter: onEnter, onExit: onExit, cursor: SystemMouseCursors.cell, ); } void main() { group('TableView.builder', () { test('creates correct delegate', () { final TableView tableView = TableView.builder( columnCount: 3, rowCount: 2, rowBuilder: (_) => span, columnBuilder: (_) => span, cellBuilder: (_, __) => cell, ); final TableCellBuilderDelegate delegate = tableView.delegate as TableCellBuilderDelegate; expect(delegate.pinnedRowCount, 0); expect(delegate.pinnedRowCount, 0); expect(delegate.rowCount, 2); expect(delegate.columnCount, 3); expect(delegate.buildColumn(0), span); expect(delegate.buildRow(0), span); expect( delegate.builder( _NullBuildContext(), TableVicinity.zero, ), cell, ); }); test('asserts correct counts', () { TableView? tableView; expect( () { tableView = TableView.builder( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 1, rowCount: 1, pinnedColumnCount: -1, // asserts ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('pinnedColumnCount >= 0'), ), ), ); expect( () { tableView = TableView.builder( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 1, rowCount: 1, pinnedRowCount: -1, // asserts ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('pinnedRowCount >= 0'), ), ), ); expect( () { tableView = TableView.builder( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 1, rowCount: -1, // asserts ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('rowCount >= 0'), ), ), ); expect( () { tableView = TableView.builder( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: -1, // asserts rowCount: 1, ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('columnCount >= 0'), ), ), ); expect( () { tableView = TableView.builder( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 1, pinnedColumnCount: 2, // asserts rowCount: 1, ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('columnCount >= pinnedColumnCount'), ), ), ); expect( () { tableView = TableView.builder( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 1, pinnedRowCount: 2, // asserts rowCount: 1, ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('rowCount >= pinnedRowCount'), ), ), ); expect(tableView, isNull); }); }); group('TableView.list', () { test('creates correct delegate', () { final TableView tableView = TableView.list( rowBuilder: (_) => span, columnBuilder: (_) => span, cells: const <List<TableViewCell>>[ <TableViewCell>[cell, cell, cell], <TableViewCell>[cell, cell, cell] ], ); final TableCellListDelegate delegate = tableView.delegate as TableCellListDelegate; expect(delegate.pinnedRowCount, 0); expect(delegate.pinnedRowCount, 0); expect(delegate.rowCount, 2); expect(delegate.columnCount, 3); expect(delegate.buildColumn(0), span); expect(delegate.buildRow(0), span); expect(delegate.children[0][0], cell); }); test('asserts correct counts', () { TableView? tableView; expect( () { tableView = TableView.list( cells: const <List<TableViewCell>>[ <TableViewCell>[cell] ], columnBuilder: (_) => span, rowBuilder: (_) => span, pinnedColumnCount: -1, // asserts ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('pinnedColumnCount >= 0'), ), ), ); expect( () { tableView = TableView.list( cells: const <List<TableViewCell>>[ <TableViewCell>[cell] ], columnBuilder: (_) => span, rowBuilder: (_) => span, pinnedRowCount: -1, // asserts ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('pinnedRowCount >= 0'), ), ), ); expect(tableView, isNull); }); }); group('RenderTableViewport', () { testWidgets('parent data and table vicinities', (WidgetTester tester) async { final Map<TableVicinity, UniqueKey> childKeys = <TableVicinity, UniqueKey>{}; const TableSpan span = TableSpan(extent: FixedTableSpanExtent(200)); final TableView tableView = TableView.builder( rowCount: 5, columnCount: 5, columnBuilder: (_) => span, rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return TableViewCell( child: SizedBox.square( key: childKeys[vicinity], dimension: 200, ), ); }, ); TableViewParentData parentDataOf(RenderBox child) { return child.parentData! as TableViewParentData; } await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); final RenderTwoDimensionalViewport viewport = getViewport( tester, childKeys.values.first, ); expect(viewport.mainAxis, Axis.vertical); // first child TableVicinity vicinity = TableVicinity.zero; TableViewParentData parentData = parentDataOf( viewport.firstChild!, ); expect(parentData.vicinity, vicinity); expect(parentData.layoutOffset, Offset.zero); expect(parentData.isVisible, isTrue); // after first child vicinity = const TableVicinity(column: 1, row: 0); parentData = parentDataOf( viewport.childAfter(viewport.firstChild!)!, ); expect(parentData.vicinity, vicinity); expect(parentData.layoutOffset, const Offset(200, 0.0)); expect(parentData.isVisible, isTrue); // before first child (none) expect( viewport.childBefore(viewport.firstChild!), isNull, ); // last child vicinity = const TableVicinity(column: 4, row: 4); parentData = parentDataOf(viewport.lastChild!); expect(parentData.vicinity, vicinity); expect(parentData.layoutOffset, const Offset(800.0, 800.0)); expect(parentData.isVisible, isFalse); // after last child (none) expect( viewport.childAfter(viewport.lastChild!), isNull, ); // before last child vicinity = const TableVicinity(column: 3, row: 4); parentData = parentDataOf( viewport.childBefore(viewport.lastChild!)!, ); expect(parentData.vicinity, vicinity); expect(parentData.layoutOffset, const Offset(600.0, 800.0)); expect(parentData.isVisible, isFalse); }); testWidgets('TableSpanPadding', (WidgetTester tester) async { final Map<TableVicinity, UniqueKey> childKeys = <TableVicinity, UniqueKey>{}; const TableSpan columnSpan = TableSpan( extent: FixedTableSpanExtent(200), padding: TableSpanPadding( leading: 10.0, trailing: 20.0, ), ); const TableSpan rowSpan = TableSpan( extent: FixedTableSpanExtent(200), padding: TableSpanPadding( leading: 30.0, trailing: 40.0, ), ); TableView tableView = TableView.builder( rowCount: 2, columnCount: 2, columnBuilder: (_) => columnSpan, rowBuilder: (_) => rowSpan, cellBuilder: (_, TableVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return TableViewCell( child: SizedBox.square( key: childKeys[vicinity], dimension: 200, ), ); }, ); TableViewParentData parentDataOf(RenderBox child) { return child.parentData! as TableViewParentData; } await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); RenderTwoDimensionalViewport viewport = getViewport( tester, childKeys.values.first, ); // first child TableVicinity vicinity = TableVicinity.zero; TableViewParentData parentData = parentDataOf( viewport.firstChild!, ); expect(parentData.vicinity, vicinity); expect( parentData.layoutOffset, const Offset( 10.0, // Leading 10 pixels before first column 30.0, // leading 30 pixels before first row ), ); // after first child vicinity = const TableVicinity(column: 1, row: 0); parentData = parentDataOf( viewport.childAfter(viewport.firstChild!)!, ); expect(parentData.vicinity, vicinity); expect( parentData.layoutOffset, const Offset( 240, // 10 leading + 200 first column + 20 trailing + 10 leading 30.0, // leading 30 pixels before first row ), ); // last child vicinity = const TableVicinity(column: 1, row: 1); parentData = parentDataOf(viewport.lastChild!); expect(parentData.vicinity, vicinity); expect( parentData.layoutOffset, const Offset( 240.0, // 10 leading + 200 first column + 20 trailing + 10 leading 300.0, // 30 leading + 200 first row + 40 trailing + 30 leading ), ); // reverse tableView = TableView.builder( rowCount: 2, columnCount: 2, verticalDetails: const ScrollableDetails.vertical(reverse: true), horizontalDetails: const ScrollableDetails.horizontal(reverse: true), columnBuilder: (_) => columnSpan, rowBuilder: (_) => rowSpan, cellBuilder: (_, TableVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return TableViewCell( child: SizedBox.square( key: childKeys[vicinity], dimension: 200, ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); viewport = getViewport( tester, childKeys.values.first, ); // first child vicinity = TableVicinity.zero; parentData = parentDataOf( viewport.firstChild!, ); expect(parentData.vicinity, vicinity); // layoutOffset is later corrected for reverse in the paintOffset expect(parentData.paintOffset, const Offset(590.0, 370.0)); // after first child vicinity = const TableVicinity(column: 1, row: 0); parentData = parentDataOf( viewport.childAfter(viewport.firstChild!)!, ); expect(parentData.vicinity, vicinity); expect(parentData.paintOffset, const Offset(360.0, 370.0)); // last child vicinity = const TableVicinity(column: 1, row: 1); parentData = parentDataOf(viewport.lastChild!); expect(parentData.vicinity, vicinity); expect(parentData.paintOffset, const Offset(360.0, 100.0)); }); testWidgets('TableSpan gesture hit testing', (WidgetTester tester) async { int tapCounter = 0; // Rows TableView tableView = TableView.builder( rowCount: 50, columnCount: 50, columnBuilder: (_) => span, rowBuilder: (int index) => index.isEven ? getTappableSpan( index, () => tapCounter++, ) : span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 100, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); // Even rows are set up for taps. expect(tapCounter, 0); // Tap along along a row await tester.tap(find.text('Row: 0 Column: 0')); await tester.tap(find.text('Row: 0 Column: 1')); await tester.tap(find.text('Row: 0 Column: 2')); await tester.tap(find.text('Row: 0 Column: 3')); expect(tapCounter, 4); // Tap along some odd rows await tester.tap(find.text('Row: 1 Column: 0')); await tester.tap(find.text('Row: 1 Column: 1')); await tester.tap(find.text('Row: 3 Column: 2')); await tester.tap(find.text('Row: 5 Column: 3')); expect(tapCounter, 4); // Check other even rows await tester.tap(find.text('Row: 2 Column: 1')); await tester.tap(find.text('Row: 2 Column: 2')); await tester.tap(find.text('Row: 4 Column: 4')); await tester.tap(find.text('Row: 4 Column: 5')); expect(tapCounter, 8); // Columns tapCounter = 0; tableView = TableView.builder( rowCount: 50, columnCount: 50, rowBuilder: (_) => span, columnBuilder: (int index) => index.isEven ? getTappableSpan( index, () => tapCounter++, ) : span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 100, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); // Even columns are set up for taps. expect(tapCounter, 0); // Tap along along a column await tester.tap(find.text('Row: 1 Column: 0')); await tester.tap(find.text('Row: 2 Column: 0')); await tester.tap(find.text('Row: 3 Column: 0')); await tester.tap(find.text('Row: 4 Column: 0')); expect(tapCounter, 4); // Tap along some odd columns await tester.tap(find.text('Row: 1 Column: 1')); await tester.tap(find.text('Row: 2 Column: 1')); await tester.tap(find.text('Row: 3 Column: 3')); await tester.tap(find.text('Row: 4 Column: 3')); expect(tapCounter, 4); // Check other even columns await tester.tap(find.text('Row: 2 Column: 2')); await tester.tap(find.text('Row: 3 Column: 2')); await tester.tap(find.text('Row: 4 Column: 4')); await tester.tap(find.text('Row: 5 Column: 4')); expect(tapCounter, 8); // Intersecting - main axis sets precedence int rowTapCounter = 0; int columnTapCounter = 0; tableView = TableView.builder( rowCount: 50, columnCount: 50, rowBuilder: (int index) => index.isEven ? getTappableSpan( index, () => rowTapCounter++, ) : span, columnBuilder: (int index) => index.isEven ? getTappableSpan( index, () => columnTapCounter++, ) : span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 100, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); // Even columns and rows are set up for taps, mainAxis is vertical by // default, mening row major order. Rows should take precedence where they // intersect at even indices. expect(columnTapCounter, 0); expect(rowTapCounter, 0); // Tap where non intersecting, but even. await tester.tap(find.text('Row: 2 Column: 3')); // Row await tester.tap(find.text('Row: 4 Column: 5')); // Row await tester.tap(find.text('Row: 3 Column: 2')); // Column await tester.tap(find.text('Row: 1 Column: 6')); // Column expect(columnTapCounter, 2); expect(rowTapCounter, 2); // Tap where both are odd and nothing should receive a tap. await tester.tap(find.text('Row: 1 Column: 1')); await tester.tap(find.text('Row: 3 Column: 1')); await tester.tap(find.text('Row: 3 Column: 3')); await tester.tap(find.text('Row: 5 Column: 3')); expect(columnTapCounter, 2); expect(rowTapCounter, 2); // Check intersections. await tester.tap(find.text('Row: 2 Column: 2')); await tester.tap(find.text('Row: 4 Column: 2')); await tester.tap(find.text('Row: 2 Column: 4')); await tester.tap(find.text('Row: 4 Column: 4')); expect(columnTapCounter, 2); expect(rowTapCounter, 6); // Rows took precedence // Change mainAxis rowTapCounter = 0; columnTapCounter = 0; tableView = TableView.builder( mainAxis: Axis.horizontal, rowCount: 50, columnCount: 50, rowBuilder: (int index) => index.isEven ? getTappableSpan( index, () => rowTapCounter++, ) : span, columnBuilder: (int index) => index.isEven ? getTappableSpan( index, () => columnTapCounter++, ) : span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 100, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); expect(rowTapCounter, 0); expect(columnTapCounter, 0); // Check intersections. await tester.tap(find.text('Row: 2 Column: 2')); await tester.tap(find.text('Row: 4 Column: 2')); await tester.tap(find.text('Row: 2 Column: 4')); await tester.tap(find.text('Row: 4 Column: 4')); expect(columnTapCounter, 4); // Columns took precedence expect(rowTapCounter, 0); }); testWidgets('provides correct details in TableSpanExtentDelegate', (WidgetTester tester) async { final TestTableSpanExtent columnExtent = TestTableSpanExtent(); final TestTableSpanExtent rowExtent = TestTableSpanExtent(); final ScrollController verticalController = ScrollController(); final ScrollController horizontalController = ScrollController(); final TableView tableView = TableView.builder( rowCount: 10, columnCount: 10, columnBuilder: (_) => TableSpan(extent: columnExtent), rowBuilder: (_) => TableSpan(extent: rowExtent), cellBuilder: (_, TableVicinity vicinity) { return const TableViewCell( child: SizedBox.square(dimension: 100), ); }, verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); // Represents the last delegate provided to the last row and column expect(columnExtent.delegate.precedingExtent, 900.0); expect(columnExtent.delegate.viewportExtent, 800.0); expect(rowExtent.delegate.precedingExtent, 900.0); expect(rowExtent.delegate.viewportExtent, 600.0); verticalController.jumpTo(10.0); await tester.pump(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 0.0); // Represents the last delegate provided to the last row and column expect(columnExtent.delegate.precedingExtent, 900.0); expect(columnExtent.delegate.viewportExtent, 800.0); expect(rowExtent.delegate.precedingExtent, 900.0); expect(rowExtent.delegate.viewportExtent, 600.0); horizontalController.jumpTo(10.0); await tester.pump(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 10.0); // Represents the last delegate provided to the last row and column expect(columnExtent.delegate.precedingExtent, 900.0); expect(columnExtent.delegate.viewportExtent, 800.0); expect(rowExtent.delegate.precedingExtent, 900.0); expect(rowExtent.delegate.viewportExtent, 600.0); }); testWidgets('First row/column layout based on padding', (WidgetTester tester) async { // Huge padding, first span layout // Column-wise TableView tableView = TableView.builder( rowCount: 50, columnCount: 50, columnBuilder: (_) => const TableSpan( extent: FixedTableSpanExtent(100), // This padding is so high, only the first column should be laid out. padding: TableSpanPadding(leading: 2000), ), rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 100, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); // All of these children are so offset by the column padding that they are // outside of the viewport and cache extent, so all but the very // first column is laid out. This is so that the ability to scroll the // table through means such as focus traversal are still accessible. expect(find.text('Row: 0 Column: 0'), findsOneWidget); expect(find.text('Row: 1 Column: 0'), findsOneWidget); expect(find.text('Row: 0 Column: 1'), findsNothing); expect(find.text('Row: 1 Column: 1'), findsNothing); expect(find.text('Row: 0 Column: 2'), findsNothing); expect(find.text('Row: 1 Column: 2'), findsNothing); // Row-wise tableView = TableView.builder( rowCount: 50, columnCount: 50, // This padding is so high, no children should be laid out. rowBuilder: (_) => const TableSpan( extent: FixedTableSpanExtent(100), padding: TableSpanPadding(leading: 2000), ), columnBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 100, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); // All of these children are so offset by the row padding that they are // outside of the viewport and cache extent, so all but the very // first row is laid out. This is so that the ability to scroll the // table through means such as focus traversal are still accessible. expect(find.text('Row: 0 Column: 0'), findsOneWidget); expect(find.text('Row: 0 Column: 1'), findsOneWidget); expect(find.text('Row: 1 Column: 0'), findsNothing); expect(find.text('Row: 1 Column: 1'), findsNothing); expect(find.text('Row: 2 Column: 0'), findsNothing); expect(find.text('Row: 2 Column: 1'), findsNothing); }); testWidgets('lazy layout accounts for gradually accrued padding', (WidgetTester tester) async { // Check with gradually accrued paddings // Column-wise TableView tableView = TableView.builder( rowCount: 50, columnCount: 50, columnBuilder: (_) => const TableSpan( extent: FixedTableSpanExtent(200), ), rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 200, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); // No padding here, check all lazily laid out columns in one row. expect(find.text('Row: 0 Column: 0'), findsOneWidget); expect(find.text('Row: 0 Column: 1'), findsOneWidget); expect(find.text('Row: 0 Column: 2'), findsOneWidget); expect(find.text('Row: 0 Column: 3'), findsOneWidget); expect(find.text('Row: 0 Column: 4'), findsOneWidget); expect(find.text('Row: 0 Column: 5'), findsOneWidget); expect(find.text('Row: 0 Column: 6'), findsNothing); tableView = TableView.builder( rowCount: 50, columnCount: 50, columnBuilder: (_) => const TableSpan( extent: FixedTableSpanExtent(200), padding: TableSpanPadding(trailing: 200), ), rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 200, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); // Fewer children laid out. expect(find.text('Row: 0 Column: 0'), findsOneWidget); expect(find.text('Row: 0 Column: 1'), findsOneWidget); expect(find.text('Row: 0 Column: 2'), findsOneWidget); expect(find.text('Row: 0 Column: 3'), findsNothing); expect(find.text('Row: 0 Column: 4'), findsNothing); expect(find.text('Row: 0 Column: 5'), findsNothing); expect(find.text('Row: 0 Column: 6'), findsNothing); // Row-wise tableView = TableView.builder( rowCount: 50, columnCount: 50, rowBuilder: (_) => const TableSpan( extent: FixedTableSpanExtent(200), ), columnBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 200, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); // No padding here, check all lazily laid out rows in one column. expect(find.text('Row: 0 Column: 0'), findsOneWidget); expect(find.text('Row: 1 Column: 0'), findsOneWidget); expect(find.text('Row: 2 Column: 0'), findsOneWidget); expect(find.text('Row: 3 Column: 0'), findsOneWidget); expect(find.text('Row: 4 Column: 0'), findsOneWidget); expect(find.text('Row: 5 Column: 0'), findsNothing); tableView = TableView.builder( rowCount: 50, columnCount: 50, rowBuilder: (_) => const TableSpan( extent: FixedTableSpanExtent(200), padding: TableSpanPadding(trailing: 200), ), columnBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 200, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); // Fewer children laid out. expect(find.text('Row: 0 Column: 0'), findsOneWidget); expect(find.text('Row: 1 Column: 0'), findsOneWidget); expect(find.text('Row: 2 Column: 0'), findsOneWidget); expect(find.text('Row: 3 Column: 0'), findsNothing); expect(find.text('Row: 4 Column: 0'), findsNothing); expect(find.text('Row: 5 Column: 0'), findsNothing); // Check padding with pinned rows and columns // TODO(Piinks): Pinned rows/columns are not lazily laid out, should check // for assertions in this case. Will add in https://github.com/flutter/flutter/issues/136833 }); testWidgets('regular layout - no pinning', (WidgetTester tester) async { final ScrollController verticalController = ScrollController(); final ScrollController horizontalController = ScrollController(); final TableView tableView = TableView.builder( rowCount: 50, columnCount: 50, columnBuilder: (_) => span, rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 100, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); expect(find.text('Row: 0 Column: 0'), findsOneWidget); expect(find.text('Row: 1 Column: 0'), findsOneWidget); expect(find.text('Row: 0 Column: 1'), findsOneWidget); expect(find.text('Row: 1 Column: 1'), findsOneWidget); // Within the cacheExtent expect(find.text('Row: 3 Column: 0'), findsOneWidget); expect(find.text('Row: 4 Column: 0'), findsOneWidget); expect(find.text('Row: 0 Column: 4'), findsOneWidget); expect(find.text('Row: 1 Column: 5'), findsOneWidget); // Outside of the cacheExtent expect(find.text('Row: 10 Column: 10'), findsNothing); expect(find.text('Row: 11 Column: 10'), findsNothing); expect(find.text('Row: 10 Column: 11'), findsNothing); expect(find.text('Row: 11 Column: 11'), findsNothing); // Let's scroll! verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 4400.0); expect(horizontalController.position.pixels, 0.0); expect(find.text('Row: 49 Column: 0'), findsOneWidget); expect(find.text('Row: 48 Column: 0'), findsOneWidget); expect(find.text('Row: 49 Column: 1'), findsOneWidget); expect(find.text('Row: 48 Column: 1'), findsOneWidget); // Within the CacheExtent expect(find.text('Row: 49 Column: 4'), findsOneWidget); expect(find.text('Row: 48 Column: 5'), findsOneWidget); // Not around. expect(find.text('Row: 0 Column: 0'), findsNothing); expect(find.text('Row: 1 Column: 0'), findsNothing); expect(find.text('Row: 0 Column: 1'), findsNothing); expect(find.text('Row: 1 Column: 1'), findsNothing); // Let's scroll some more! horizontalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 4400.0); expect(horizontalController.position.pixels, 4400.0); expect(find.text('Row: 49 Column: 49'), findsOneWidget); expect(find.text('Row: 48 Column: 49'), findsOneWidget); expect(find.text('Row: 49 Column: 48'), findsOneWidget); expect(find.text('Row: 48 Column: 48'), findsOneWidget); // Nothing within the CacheExtent expect(find.text('Row: 50 Column: 50'), findsNothing); expect(find.text('Row: 51 Column: 51'), findsNothing); // Not around. expect(find.text('Row: 0 Column: 0'), findsNothing); expect(find.text('Row: 1 Column: 0'), findsNothing); expect(find.text('Row: 0 Column: 1'), findsNothing); expect(find.text('Row: 1 Column: 1'), findsNothing); }); testWidgets('pinned rows and columns', (WidgetTester tester) async { // Just pinned rows final ScrollController verticalController = ScrollController(); final ScrollController horizontalController = ScrollController(); TableView tableView = TableView.builder( rowCount: 50, pinnedRowCount: 1, columnCount: 50, columnBuilder: (_) => span, rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 100, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect(find.text('Row: 0 Column: 0'), findsOneWidget); expect(find.text('Row: 1 Column: 0'), findsOneWidget); expect(find.text('Row: 0 Column: 1'), findsOneWidget); expect(find.text('Row: 1 Column: 1'), findsOneWidget); // Within the cacheExtent expect(find.text('Row: 6 Column: 0'), findsOneWidget); expect(find.text('Row: 7 Column: 0'), findsOneWidget); expect(find.text('Row: 0 Column: 8'), findsOneWidget); expect(find.text('Row: 1 Column: 8'), findsOneWidget); // Outside of the cacheExtent expect(find.text('Row: 10 Column: 10'), findsNothing); expect(find.text('Row: 11 Column: 10'), findsNothing); expect(find.text('Row: 10 Column: 11'), findsNothing); expect(find.text('Row: 11 Column: 11'), findsNothing); // Let's scroll! verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 4400.0); expect(horizontalController.position.pixels, 0.0); expect(find.text('Row: 49 Column: 0'), findsOneWidget); expect(find.text('Row: 48 Column: 0'), findsOneWidget); expect(find.text('Row: 49 Column: 1'), findsOneWidget); expect(find.text('Row: 48 Column: 1'), findsOneWidget); // Within the CacheExtent expect(find.text('Row: 49 Column: 8'), findsOneWidget); expect(find.text('Row: 48 Column: 9'), findsOneWidget); // Not around unless pinned. expect(find.text('Row: 0 Column: 0'), findsOneWidget); // Pinned row expect(find.text('Row: 1 Column: 0'), findsNothing); expect(find.text('Row: 0 Column: 1'), findsOneWidget); // Pinned row expect(find.text('Row: 1 Column: 1'), findsNothing); // Let's scroll some more! horizontalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 4400.0); expect(horizontalController.position.pixels, 4400.0); expect(find.text('Row: 49 Column: 49'), findsOneWidget); expect(find.text('Row: 48 Column: 49'), findsOneWidget); expect(find.text('Row: 49 Column: 48'), findsOneWidget); expect(find.text('Row: 48 Column: 48'), findsOneWidget); // Nothing within the CacheExtent expect(find.text('Row: 50 Column: 50'), findsNothing); expect(find.text('Row: 51 Column: 51'), findsNothing); // Not around unless pinned. expect(find.text('Row: 0 Column: 49'), findsOneWidget); // Pinned row expect(find.text('Row: 1 Column: 49'), findsNothing); expect(find.text('Row: 0 Column: 48'), findsOneWidget); // Pinned row expect(find.text('Row: 1 Column: 48'), findsNothing); // Just pinned columns verticalController.jumpTo(0.0); horizontalController.jumpTo(0.0); tableView = TableView.builder( rowCount: 50, pinnedColumnCount: 1, columnCount: 50, columnBuilder: (_) => span, rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 100, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect(find.text('Row: 0 Column: 0'), findsOneWidget); expect(find.text('Row: 1 Column: 0'), findsOneWidget); expect(find.text('Row: 0 Column: 1'), findsOneWidget); expect(find.text('Row: 1 Column: 1'), findsOneWidget); // Within the cacheExtent expect(find.text('Row: 6 Column: 0'), findsOneWidget); expect(find.text('Row: 7 Column: 0'), findsOneWidget); expect(find.text('Row: 0 Column: 8'), findsOneWidget); expect(find.text('Row: 1 Column: 9'), findsOneWidget); // Outside of the cacheExtent expect(find.text('Row: 10 Column: 10'), findsNothing); expect(find.text('Row: 11 Column: 10'), findsNothing); expect(find.text('Row: 10 Column: 11'), findsNothing); expect(find.text('Row: 11 Column: 11'), findsNothing); // Let's scroll! verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 4400.0); expect(horizontalController.position.pixels, 0.0); expect(find.text('Row: 49 Column: 0'), findsOneWidget); expect(find.text('Row: 48 Column: 0'), findsOneWidget); expect(find.text('Row: 49 Column: 1'), findsOneWidget); expect(find.text('Row: 48 Column: 1'), findsOneWidget); // Within the CacheExtent expect(find.text('Row: 49 Column: 8'), findsOneWidget); expect(find.text('Row: 48 Column: 9'), findsOneWidget); // Not around unless pinned. expect(find.text('Row: 49 Column: 0'), findsOneWidget); // Pinned column expect(find.text('Row: 48 Column: 0'), findsOneWidget); // Pinned column expect(find.text('Row: 0 Column: 1'), findsNothing); expect(find.text('Row: 1 Column: 1'), findsNothing); // Let's scroll some more! horizontalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 4400.0); expect(horizontalController.position.pixels, 4400.0); expect(find.text('Row: 49 Column: 49'), findsOneWidget); expect(find.text('Row: 48 Column: 49'), findsOneWidget); expect(find.text('Row: 49 Column: 48'), findsOneWidget); expect(find.text('Row: 48 Column: 48'), findsOneWidget); // Nothing within the CacheExtent expect(find.text('Row: 50 Column: 50'), findsNothing); expect(find.text('Row: 51 Column: 51'), findsNothing); // Not around. expect(find.text('Row: 49 Column: 0'), findsOneWidget); // Pinned column expect(find.text('Row: 48 Column: 0'), findsOneWidget); // Pinned column expect(find.text('Row: 0 Column: 1'), findsNothing); expect(find.text('Row: 1 Column: 1'), findsNothing); // Both verticalController.jumpTo(0.0); horizontalController.jumpTo(0.0); tableView = TableView.builder( rowCount: 50, pinnedColumnCount: 1, pinnedRowCount: 1, columnCount: 50, columnBuilder: (_) => span, rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 100, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect(find.text('Row: 0 Column: 0'), findsOneWidget); expect(find.text('Row: 1 Column: 0'), findsOneWidget); expect(find.text('Row: 0 Column: 1'), findsOneWidget); expect(find.text('Row: 1 Column: 1'), findsOneWidget); // Within the cacheExtent expect(find.text('Row: 7 Column: 0'), findsOneWidget); expect(find.text('Row: 6 Column: 0'), findsOneWidget); expect(find.text('Row: 0 Column: 8'), findsOneWidget); expect(find.text('Row: 1 Column: 9'), findsOneWidget); // Outside of the cacheExtent expect(find.text('Row: 10 Column: 10'), findsNothing); expect(find.text('Row: 11 Column: 10'), findsNothing); expect(find.text('Row: 10 Column: 11'), findsNothing); expect(find.text('Row: 11 Column: 11'), findsNothing); // Let's scroll! verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 4400.0); expect(horizontalController.position.pixels, 0.0); expect(find.text('Row: 49 Column: 0'), findsOneWidget); expect(find.text('Row: 48 Column: 0'), findsOneWidget); expect(find.text('Row: 49 Column: 1'), findsOneWidget); expect(find.text('Row: 48 Column: 1'), findsOneWidget); // Within the CacheExtent expect(find.text('Row: 49 Column: 8'), findsOneWidget); expect(find.text('Row: 48 Column: 9'), findsOneWidget); // Not around unless pinned. expect(find.text('Row: 0 Column: 0'), findsOneWidget); // Pinned expect(find.text('Row: 48 Column: 0'), findsOneWidget); // Pinned expect(find.text('Row: 0 Column: 1'), findsOneWidget); // Pinned expect(find.text('Row: 1 Column: 1'), findsNothing); // Let's scroll some more! horizontalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 4400.0); expect(horizontalController.position.pixels, 4400.0); expect(find.text('Row: 49 Column: 49'), findsOneWidget); expect(find.text('Row: 48 Column: 49'), findsOneWidget); expect(find.text('Row: 49 Column: 48'), findsOneWidget); expect(find.text('Row: 48 Column: 48'), findsOneWidget); // Nothing within the CacheExtent expect(find.text('Row: 50 Column: 50'), findsNothing); expect(find.text('Row: 51 Column: 51'), findsNothing); // Not around unless pinned. expect(find.text('Row: 0 Column: 0'), findsOneWidget); // Pinned expect(find.text('Row: 49 Column: 0'), findsOneWidget); // Pinned expect(find.text('Row: 0 Column: 49'), findsOneWidget); // Pinned expect(find.text('Row: 1 Column: 1'), findsNothing); }); testWidgets('only paints visible cells', (WidgetTester tester) async { final ScrollController verticalController = ScrollController(); final ScrollController horizontalController = ScrollController(); final TableView tableView = TableView.builder( rowCount: 50, columnCount: 50, columnBuilder: (_) => span, rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 100, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); bool cellNeedsPaint(String cell) { return find.text(cell).evaluate().first.renderObject!.debugNeedsPaint; } expect(cellNeedsPaint('Row: 0 Column: 0'), isFalse); expect(cellNeedsPaint('Row: 0 Column: 1'), isFalse); expect(cellNeedsPaint('Row: 0 Column: 2'), isFalse); expect(cellNeedsPaint('Row: 0 Column: 3'), isFalse); expect(cellNeedsPaint('Row: 0 Column: 4'), isFalse); expect(cellNeedsPaint('Row: 0 Column: 5'), isFalse); expect(cellNeedsPaint('Row: 0 Column: 6'), isFalse); expect(cellNeedsPaint('Row: 0 Column: 7'), isFalse); expect(cellNeedsPaint('Row: 0 Column: 8'), isTrue); // cacheExtent expect(cellNeedsPaint('Row: 0 Column: 9'), isTrue); // cacheExtent expect(cellNeedsPaint('Row: 0 Column: 10'), isTrue); // cacheExtent expect( find.text('Row: 0 Column: 11'), findsNothing, ); // outside of cacheExtent expect(cellNeedsPaint('Row: 1 Column: 0'), isFalse); expect(cellNeedsPaint('Row: 2 Column: 0'), isFalse); expect(cellNeedsPaint('Row: 3 Column: 0'), isFalse); expect(cellNeedsPaint('Row: 4 Column: 0'), isFalse); expect(cellNeedsPaint('Row: 5 Column: 0'), isFalse); expect(cellNeedsPaint('Row: 6 Column: 0'), isTrue); // cacheExtent expect(cellNeedsPaint('Row: 7 Column: 0'), isTrue); // cacheExtent expect(cellNeedsPaint('Row: 8 Column: 0'), isTrue); // cacheExtent expect( find.text('Row: 9 Column: 0'), findsNothing, ); // outside of cacheExtent // Check a couple other cells expect(cellNeedsPaint('Row: 5 Column: 7'), isFalse); // last visible cell expect(cellNeedsPaint('Row: 6 Column: 7'), isTrue); // also in cacheExtent expect(cellNeedsPaint('Row: 5 Column: 8'), isTrue); // also in cacheExtent expect(cellNeedsPaint('Row: 6 Column: 8'), isTrue); // also in cacheExtent }); testWidgets('paints decorations in correct order', (WidgetTester tester) async { TableView tableView = TableView.builder( rowCount: 2, columnCount: 2, columnBuilder: (int index) => TableSpan( extent: const FixedTableSpanExtent(200.0), padding: index == 0 ? const TableSpanPadding(trailing: 10) : null, foregroundDecoration: TableSpanDecoration( consumeSpanPadding: false, borderRadius: BorderRadius.circular(10.0), border: const TableSpanBorder( trailing: BorderSide( color: Colors.orange, width: 3, ), ), ), backgroundDecoration: TableSpanDecoration( // consumePadding true by default color: index.isEven ? Colors.red : null, borderRadius: BorderRadius.circular(30.0), ), ), rowBuilder: (int index) => TableSpan( extent: const FixedTableSpanExtent(200.0), padding: index == 1 ? const TableSpanPadding(leading: 10) : null, foregroundDecoration: TableSpanDecoration( // consumePadding true by default borderRadius: BorderRadius.circular(30.0), border: const TableSpanBorder( leading: BorderSide( color: Colors.green, width: 3, ), ), ), backgroundDecoration: TableSpanDecoration( color: index.isOdd ? Colors.blue : null, borderRadius: BorderRadius.circular(30.0), consumeSpanPadding: false, ), ), cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: Container( height: 200, width: 200, color: Colors.grey.withOpacity(0.5), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); expect( find.byType(TableViewport), paints // background row ..rrect( rrect: RRect.fromRectAndRadius( const Rect.fromLTRB(0.0, 210.0, 410.0, 410.0), const Radius.circular(30.0), ), color: const Color(0xff2196f3), ) // background column ..rrect( rrect: RRect.fromRectAndRadius( const Rect.fromLTRB(0.0, 0.0, 210.0, 410.0), const Radius.circular(30.0), ), color: const Color(0xfff44336), ) // child at 0,0 ..rect( rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), color: const Color(0x809e9e9e), ) // child at 0,1 ..rect( rect: const Rect.fromLTRB(0.0, 210.0, 200.0, 410.0), color: const Color(0x809e9e9e), ) // child at 1,0 ..rect( rect: const Rect.fromLTRB(210.0, 0.0, 410.0, 200.0), color: const Color(0x809e9e9e), ) // child at 1,1 ..rect( rect: const Rect.fromLTRB(210.0, 210.0, 410.0, 410.0), color: const Color(0x809e9e9e), ) // foreground row border (1) ..drrect( outer: RRect.fromRectAndRadius( const Rect.fromLTRB(0.0, 0.0, 410.0, 200.0), const Radius.circular(30.0), ), inner: RRect.fromLTRBAndCorners( 0.0, 3.0, 410.0, 200.0, topLeft: const Radius.elliptical(30.0, 27.0), topRight: const Radius.elliptical(30.0, 27.0), bottomRight: const Radius.circular(30.0), bottomLeft: const Radius.circular(30.0), ), color: const Color(0xff4caf50), ) // foreground row border (2) ..drrect( outer: RRect.fromRectAndRadius( const Rect.fromLTRB(0.0, 200.0, 410.0, 410.0), const Radius.circular(30.0), ), inner: RRect.fromLTRBAndCorners( 0.0, 203.0, 410.0, 410.0, topLeft: const Radius.elliptical(30.0, 27.0), topRight: const Radius.elliptical(30.0, 27.0), bottomRight: const Radius.circular(30.0), bottomLeft: const Radius.circular(30.0), ), color: const Color(0xff4caf50), ) // foreground column border (1) ..drrect( outer: RRect.fromRectAndRadius( const Rect.fromLTRB(0.0, 0.0, 200.0, 410.0), const Radius.circular(10.0), ), inner: RRect.fromLTRBAndCorners( 0.0, 0.0, 197.0, 410.0, topLeft: const Radius.circular(10.0), topRight: const Radius.elliptical(7.0, 10.0), bottomRight: const Radius.elliptical(7.0, 10.0), bottomLeft: const Radius.circular(10.0), ), color: const Color(0xffff9800), ) // foreground column border (2) ..drrect( outer: RRect.fromRectAndRadius( const Rect.fromLTRB(210.0, 0.0, 410.0, 410.0), const Radius.circular(10.0), ), inner: RRect.fromLTRBAndCorners( 210.0, 0.0, 407.0, 410.0, topLeft: const Radius.circular(10.0), topRight: const Radius.elliptical(7.0, 10.0), bottomRight: const Radius.elliptical(7.0, 10.0), bottomLeft: const Radius.circular(10.0), ), color: const Color(0xffff9800), ), ); // Switch main axis tableView = TableView.builder( mainAxis: Axis.horizontal, rowCount: 2, columnCount: 2, columnBuilder: (int index) => TableSpan( extent: const FixedTableSpanExtent(200.0), foregroundDecoration: const TableSpanDecoration( border: TableSpanBorder( trailing: BorderSide( color: Colors.orange, width: 3, ), ), ), backgroundDecoration: TableSpanDecoration( color: index.isEven ? Colors.red : null, ), ), rowBuilder: (int index) => TableSpan( extent: const FixedTableSpanExtent(200.0), foregroundDecoration: const TableSpanDecoration( border: TableSpanBorder( leading: BorderSide( color: Colors.green, width: 3, ), ), ), backgroundDecoration: TableSpanDecoration( color: index.isOdd ? Colors.blue : null, ), ), cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: Container( height: 200, width: 200, color: Colors.grey.withOpacity(0.5), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); expect( find.byType(TableViewport), paints // background column goes first this time ..rect( rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 400.0), color: const Color(0xfff44336), ) // background row ..rect( rect: const Rect.fromLTRB(0.0, 200.0, 400.0, 400.0), color: const Color(0xff2196f3), ) // child at 0,0 ..rect( rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), color: const Color(0x809e9e9e), ) // child at 1,0 ..rect( rect: const Rect.fromLTRB(0.0, 200.0, 200.0, 400.0), color: const Color(0x809e9e9e), ) // child at 0,1 ..rect( rect: const Rect.fromLTRB(200.0, 0.0, 400.0, 200.0), color: const Color(0x809e9e9e), ) // child at 1,1 ..rect( rect: const Rect.fromLTRB(200.0, 200.0, 400.0, 400.0), color: const Color(0x809e9e9e), ) // foreground column border (1) ..path( includes: <Offset>[ const Offset(200.0, 0.0), const Offset(200.0, 200.0), const Offset(200.0, 400.0), ], color: const Color(0xffff9800), ) // foreground column border (2) ..path( includes: <Offset>[ const Offset(400.0, 0.0), const Offset(400.0, 200.0), const Offset(400.0, 400.0), ], color: const Color(0xffff9800), ) // foreground row border ..path( includes: <Offset>[ Offset.zero, const Offset(200.0, 0.0), const Offset(400.0, 0.0), ], color: const Color(0xff4caf50), ) // foreground row border(2) ..path( includes: <Offset>[ const Offset(0.0, 200.0), const Offset(200.0, 200.0), const Offset(400.0, 200.0), ], color: const Color(0xff4caf50), ), ); }); testWidgets('child paint rects are correct when reversed and pinned', (WidgetTester tester) async { // Both reversed - Regression test for https://github.com/flutter/flutter/issues/135386 TableView tableView = TableView.builder( verticalDetails: const ScrollableDetails.vertical(reverse: true), horizontalDetails: const ScrollableDetails.horizontal(reverse: true), rowCount: 2, pinnedRowCount: 1, columnCount: 2, pinnedColumnCount: 1, columnBuilder: (int index) => const TableSpan( extent: FixedTableSpanExtent(200.0), ), rowBuilder: (int index) => const TableSpan( extent: FixedTableSpanExtent(200.0), ), cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: Container( height: 200, width: 200, color: Colors.grey.withOpacity(0.5), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); // All children are painted in the right place expect( find.byType(TableViewport), paints ..rect( rect: const Rect.fromLTRB(400.0, 200.0, 600.0, 400.0), color: const Color(0x809e9e9e), ) ..rect( rect: const Rect.fromLTRB(600.0, 200.0, 800.0, 400.0), color: const Color(0x809e9e9e), ) ..rect( rect: const Rect.fromLTRB(400.0, 400.0, 600.0, 600.0), color: const Color(0x809e9e9e), ) ..rect( rect: const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0), color: const Color(0x809e9e9e), ), ); // Only one axis reversed - Regression test for https://github.com/flutter/flutter/issues/136897 tableView = TableView.builder( horizontalDetails: const ScrollableDetails.horizontal(reverse: true), rowCount: 2, pinnedRowCount: 1, columnCount: 2, pinnedColumnCount: 1, columnBuilder: (int index) => const TableSpan( extent: FixedTableSpanExtent(200.0), ), rowBuilder: (int index) => const TableSpan( extent: FixedTableSpanExtent(200.0), ), cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: Container( height: 200, width: 200, color: Colors.grey.withOpacity(0.5), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); expect( find.byType(TableViewport), paints ..rect( rect: const Rect.fromLTRB(400.0, 200.0, 600.0, 400.0), color: const Color(0x809e9e9e), ) ..rect( rect: const Rect.fromLTRB(600.0, 200.0, 800.0, 400.0), color: const Color(0x809e9e9e), ) ..rect( rect: const Rect.fromLTRB(400.0, 0.0, 600.0, 200.0), color: const Color(0x809e9e9e), ) ..rect( rect: const Rect.fromLTRB(600.0, 0.0, 800.0, 200.0), color: const Color(0x809e9e9e), ), ); }); testWidgets('mouse handling', (WidgetTester tester) async { int enterCounter = 0; int exitCounter = 0; final TableView tableView = TableView.builder( rowCount: 50, columnCount: 50, columnBuilder: (_) => span, rowBuilder: (int index) => index.isEven ? getMouseTrackingSpan( index, onEnter: (_) => enterCounter++, onExit: (_) => exitCounter++, ) : span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( dimension: 100, child: Text('Row: ${vicinity.row} Column: ${vicinity.column}'), ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); // Even rows will respond to mouse, odd will not final Offset evenRow = tester.getCenter(find.text('Row: 2 Column: 2')); final Offset oddRow = tester.getCenter(find.text('Row: 3 Column: 2')); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(location: oddRow); expect(enterCounter, 0); expect(exitCounter, 0); expect( RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic, ); await gesture.moveTo(evenRow); await tester.pumpAndSettle(); expect(enterCounter, 1); expect(exitCounter, 0); expect( RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.cell, ); await gesture.moveTo(oddRow); await tester.pumpAndSettle(); expect(enterCounter, 1); expect(exitCounter, 1); expect( RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic, ); }); group('Merged pinned cells layout', () { // Regression tests for https://github.com/flutter/flutter/issues/143526 // These tests all use the same collection of merged pinned cells in a // variety of combinations. final Map<TableVicinity, ({int start, int span})> bothMerged = <TableVicinity, ({int start, int span})>{ TableVicinity.zero: (start: 0, span: 2), const TableVicinity(row: 1, column: 0): (start: 0, span: 2), const TableVicinity(row: 0, column: 1): (start: 0, span: 2), const TableVicinity(row: 1, column: 1): (start: 0, span: 2), }; final Map<TableVicinity, ({int start, int span})> rowMerged = <TableVicinity, ({int start, int span})>{ const TableVicinity(row: 2, column: 0): (start: 2, span: 2), const TableVicinity(row: 3, column: 0): (start: 2, span: 2), const TableVicinity(row: 4, column: 1): (start: 4, span: 3), const TableVicinity(row: 5, column: 1): (start: 4, span: 3), const TableVicinity(row: 6, column: 1): (start: 4, span: 3), }; final Map<TableVicinity, ({int start, int span})> columnMerged = <TableVicinity, ({int start, int span})>{ const TableVicinity(row: 0, column: 2): (start: 2, span: 2), const TableVicinity(row: 0, column: 3): (start: 2, span: 2), const TableVicinity(row: 1, column: 4): (start: 4, span: 3), const TableVicinity(row: 1, column: 5): (start: 4, span: 3), const TableVicinity(row: 1, column: 6): (start: 4, span: 3), }; const TableSpan span = TableSpan(extent: FixedTableSpanExtent(75)); testWidgets('Normal axes', (WidgetTester tester) async { final ScrollController verticalController = ScrollController(); final ScrollController horizontalController = ScrollController(); final TableView tableView = TableView.builder( verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), columnCount: 20, rowCount: 20, pinnedRowCount: 2, pinnedColumnCount: 2, columnBuilder: (_) => span, rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( columnMergeStart: bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start, columnMergeSpan: bothMerged[vicinity]?.span ?? columnMerged[vicinity]?.span, rowMergeStart: bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start, rowMergeSpan: bothMerged[vicinity]?.span ?? rowMerged[vicinity]?.span, child: Text( 'R${bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start ?? vicinity.row}:' 'C${bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start ?? vicinity.column}', ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect( tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(0.0, 0.0, 150.0, 150.0), ); expect( tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(150.0, 0.0, 150.0, 75.0), ); expect( tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(300.0, 75.0, 225.0, 75.0), ); expect( tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(0.0, 150.0, 75.0, 150.0), ); expect( tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(75.0, 300.0, 75.0, 225.0), ); verticalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 0.0); expect( tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(0.0, 0.0, 150.0, 150.0), ); expect( tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(150.0, 0.0, 150.0, 75.0), ); expect( tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(300.0, 75.0, 225.0, 75.0), ); expect( tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(0.0, 140.0, 75.0, 150.0), ); expect( tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(75.0, 290.0, 75.0, 225.0), ); horizontalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 10.0); expect( tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(0.0, 0.0, 150.0, 150.0), ); expect( tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(140.0, 0.0, 150.0, 75.0), ); expect( tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(290.0, 75.0, 225.0, 75.0), ); expect( tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(0.0, 140.0, 75.0, 150.0), ); expect( tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(75.0, 290.0, 75.0, 225.0), ); }); testWidgets('Vertical reversed', (WidgetTester tester) async { final ScrollController verticalController = ScrollController(); final ScrollController horizontalController = ScrollController(); final TableView tableView = TableView.builder( verticalDetails: ScrollableDetails.vertical( reverse: true, controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), columnCount: 20, rowCount: 20, pinnedRowCount: 2, pinnedColumnCount: 2, columnBuilder: (_) => span, rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( columnMergeStart: bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start, columnMergeSpan: bothMerged[vicinity]?.span ?? columnMerged[vicinity]?.span, rowMergeStart: bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start, rowMergeSpan: bothMerged[vicinity]?.span ?? rowMerged[vicinity]?.span, child: Text( 'R${bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start ?? vicinity.row}:' 'C${bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start ?? vicinity.column}', ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect( tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(0.0, 450.0, 150.0, 150.0), ); expect( tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(150.0, 525.0, 150.0, 75.0), ); expect( tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(300.0, 450.0, 225.0, 75.0), ); expect( tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(0.0, 300.0, 75.0, 150.0), ); expect( tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(75.0, 75.0, 75.0, 225.0), ); verticalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 0.0); expect( tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(0.0, 450.0, 150.0, 150.0), ); expect( tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(150.0, 525.0, 150.0, 75.0), ); expect( tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(300.0, 450.0, 225.0, 75.0), ); expect( tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(0.0, 310.0, 75.0, 150.0), ); expect( tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(75.0, 85.0, 75.0, 225.0), ); horizontalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 10.0); expect( tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(0.0, 450.0, 150.0, 150.0), ); expect( tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(140.0, 525.0, 150.0, 75.0), ); expect( tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(290.0, 450.0, 225.0, 75.0), ); expect( tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(0.0, 310.0, 75.0, 150.0), ); expect( tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(75.0, 85.0, 75.0, 225.0), ); }); testWidgets('Horizontal reversed', (WidgetTester tester) async { final ScrollController verticalController = ScrollController(); final ScrollController horizontalController = ScrollController(); final TableView tableView = TableView.builder( verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( reverse: true, controller: horizontalController, ), columnCount: 20, rowCount: 20, pinnedRowCount: 2, pinnedColumnCount: 2, columnBuilder: (_) => span, rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( columnMergeStart: bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start, columnMergeSpan: bothMerged[vicinity]?.span ?? columnMerged[vicinity]?.span, rowMergeStart: bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start, rowMergeSpan: bothMerged[vicinity]?.span ?? rowMerged[vicinity]?.span, child: Text( 'R${bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start ?? vicinity.row}:' 'C${bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start ?? vicinity.column}', ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect( tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(650.0, 0.0, 150.0, 150.0), ); expect( tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(500.0, 0.0, 150.0, 75.0), ); expect( tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(275.0, 75.0, 225.0, 75.0), ); expect( tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(725.0, 150.0, 75.0, 150.0), ); expect( tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(650.0, 300.0, 75.0, 225.0), ); verticalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 0.0); expect( tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(650.0, 0.0, 150.0, 150.0), ); expect( tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(500.0, 0.0, 150.0, 75.0), ); expect( tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(275.0, 75.0, 225.0, 75.0), ); expect( tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(725.0, 140.0, 75.0, 150.0), ); expect( tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(650.0, 290.0, 75.0, 225.0), ); horizontalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 10.0); expect( tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(650.0, 0.0, 150.0, 150.0), ); expect( tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(510.0, 0.0, 150.0, 75.0), ); expect( tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(285.0, 75.0, 225.0, 75.0), ); expect( tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(725.0, 140.0, 75.0, 150.0), ); expect( tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(650.0, 290.0, 75.0, 225.0), ); }); testWidgets('Both reversed', (WidgetTester tester) async { final ScrollController verticalController = ScrollController(); final ScrollController horizontalController = ScrollController(); final TableView tableView = TableView.builder( verticalDetails: ScrollableDetails.vertical( reverse: true, controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( reverse: true, controller: horizontalController, ), columnCount: 20, rowCount: 20, pinnedRowCount: 2, pinnedColumnCount: 2, columnBuilder: (_) => span, rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( columnMergeStart: bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start, columnMergeSpan: bothMerged[vicinity]?.span ?? columnMerged[vicinity]?.span, rowMergeStart: bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start, rowMergeSpan: bothMerged[vicinity]?.span ?? rowMerged[vicinity]?.span, child: Text( 'R${bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start ?? vicinity.row}:' 'C${bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start ?? vicinity.column}', ), ); }, ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect( tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(650.0, 450.0, 150.0, 150.0), ); expect( tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(500.0, 525.0, 150.0, 75.0), ); expect( tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(275.0, 450.0, 225.0, 75.0), ); expect( tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(725.0, 300.0, 75.0, 150.0), ); expect( tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(650.0, 75.0, 75.0, 225.0), ); verticalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 0.0); expect( tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(650.0, 450.0, 150.0, 150.0), ); expect( tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(500.0, 525.0, 150.0, 75.0), ); expect( tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(275.0, 450.0, 225.0, 75.0), ); expect( tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(725.0, 310.0, 75.0, 150.0), ); expect( tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(650.0, 85.0, 75.0, 225.0), ); horizontalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 10.0); expect( tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(650.0, 450.0, 150.0, 150.0), ); expect( tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(510.0, 525.0, 150.0, 75.0), ); expect( tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(285.0, 450.0, 225.0, 75.0), ); expect( tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(725.0, 310.0, 75.0, 150.0), ); expect( tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(650.0, 85.0, 75.0, 225.0), ); }); }); }); testWidgets( 'Merged unpinned cells following pinned cells are laid out correctly', (WidgetTester tester) async { final ScrollController verticalController = ScrollController(); final ScrollController horizontalController = ScrollController(); final Set<TableVicinity> mergedCell = <TableVicinity>{ const TableVicinity(row: 2, column: 2), const TableVicinity(row: 3, column: 2), const TableVicinity(row: 2, column: 3), const TableVicinity(row: 3, column: 3), }; final TableView tableView = TableView.builder( columnCount: 10, rowCount: 10, columnBuilder: (_) => const TableSpan(extent: FixedTableSpanExtent(100)), rowBuilder: (_) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (BuildContext context, TableVicinity vicinity) { if (mergedCell.contains(vicinity)) { return const TableViewCell( rowMergeStart: 2, rowMergeSpan: 2, columnMergeStart: 2, columnMergeSpan: 2, child: Text('Tile c: 2, r: 2'), ); } return TableViewCell( child: Text('Tile c: ${vicinity.column}, r: ${vicinity.row}'), ); }, pinnedRowCount: 1, pinnedColumnCount: 1, verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), ); await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect( tester.getRect(find.text('Tile c: 2, r: 2')), const Rect.fromLTWH(200.0, 200.0, 200.0, 200.0), ); verticalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 0.0); expect( tester.getRect(find.text('Tile c: 2, r: 2')), const Rect.fromLTWH(200.0, 190.0, 200.0, 200.0), ); horizontalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 10.0); expect( tester.getRect(find.text('Tile c: 2, r: 2')), const Rect.fromLTWH(190.0, 190.0, 200.0, 200.0), ); }); } class _NullBuildContext implements BuildContext, TwoDimensionalChildManager { @override dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError(); } RenderTableViewport getViewport(WidgetTester tester, Key childKey) { return RenderAbstractViewport.of(tester.renderObject(find.byKey(childKey))) as RenderTableViewport; } class TestTableSpanExtent extends TableSpanExtent { late TableSpanExtentDelegate delegate; @override double calculateExtent(TableSpanExtentDelegate delegate) { this.delegate = delegate; return 100; } }
packages/packages/two_dimensional_scrollables/test/table_view/table_test.dart/0
{ "file_path": "packages/packages/two_dimensional_scrollables/test/table_view/table_test.dart", "repo_id": "packages", "token_count": 39449 }
1,132
name: url_launcher_example description: Demonstrates how to use the url_launcher plugin. publish_to: none environment: sdk: ^3.2.3 flutter: ">=3.16.6" dependencies: flutter: sdk: flutter url_launcher_ios: # When depending on this package from a real application you should use: # url_launcher_ios: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ url_launcher_platform_interface: ^2.2.0 dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter plugin_platform_interface: ^2.1.7 flutter: uses-material-design: true
packages/packages/url_launcher/url_launcher_ios/example/pubspec.yaml/0
{ "file_path": "packages/packages/url_launcher/url_launcher_ios/example/pubspec.yaml", "repo_id": "packages", "token_count": 279 }
1,133
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v10.1.3), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; /// Possible error conditions for [UrlLauncherApi] calls. enum UrlLauncherError { /// The URL could not be parsed as an NSURL. invalidUrl, } /// Possible results for a [UrlLauncherApi] call with a boolean outcome. class UrlLauncherBoolResult { UrlLauncherBoolResult({ required this.value, this.error, }); bool value; UrlLauncherError? error; Object encode() { return <Object?>[ value, error?.index, ]; } static UrlLauncherBoolResult decode(Object result) { result as List<Object?>; return UrlLauncherBoolResult( value: result[0]! as bool, error: result[1] != null ? UrlLauncherError.values[result[1]! as int] : null, ); } } class _UrlLauncherApiCodec extends StandardMessageCodec { const _UrlLauncherApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is UrlLauncherBoolResult) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return UrlLauncherBoolResult.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class UrlLauncherApi { /// Constructor for [UrlLauncherApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. UrlLauncherApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = _UrlLauncherApiCodec(); /// Returns a true result if the URL can definitely be launched. Future<UrlLauncherBoolResult> canLaunchUrl(String arg_url) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.UrlLauncherApi.canLaunchUrl', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_url]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as UrlLauncherBoolResult?)!; } } /// Opens the URL externally, returning a true result if successful. Future<UrlLauncherBoolResult> launchUrl(String arg_url) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.UrlLauncherApi.launchUrl', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_url]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as UrlLauncherBoolResult?)!; } } }
packages/packages/url_launcher/url_launcher_macos/lib/src/messages.g.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_macos/lib/src/messages.g.dart", "repo_id": "packages", "token_count": 1675 }
1,134
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import '../link.dart'; import '../method_channel_url_launcher.dart'; import '../url_launcher_platform_interface.dart'; import 'types.dart'; /// The interface that implementations of url_launcher must implement. /// /// Platform implementations should extend this class rather than implement it as `url_launcher` /// does not consider newly added methods to be breaking changes. Extending this class /// (using `extends`) ensures that the subclass will get the default implementation, while /// platform implementations that `implements` this interface will be broken by newly added /// [UrlLauncherPlatform] methods. abstract class UrlLauncherPlatform extends PlatformInterface { /// Constructs a UrlLauncherPlatform. UrlLauncherPlatform() : super(token: _token); static final Object _token = Object(); static UrlLauncherPlatform _instance = MethodChannelUrlLauncher(); /// The default instance of [UrlLauncherPlatform] to use. /// /// Defaults to [MethodChannelUrlLauncher]. static UrlLauncherPlatform get instance => _instance; /// Platform-specific plugins should set this with their own platform-specific /// class that extends [UrlLauncherPlatform] when they register themselves. // TODO(amirh): Extract common platform interface logic. // https://github.com/flutter/flutter/issues/43368 static set instance(UrlLauncherPlatform instance) { PlatformInterface.verify(instance, _token); _instance = instance; } /// The delegate used by the Link widget to build itself. LinkDelegate? get linkDelegate; /// Returns `true` if this platform is able to launch [url]. Future<bool> canLaunch(String url) { throw UnimplementedError('canLaunch() has not been implemented.'); } /// Passes [url] to the underlying platform for handling. /// /// Returns `true` if the given [url] was successfully launched. /// /// For documentation on the other arguments, see the `launch` documentation /// in `package:url_launcher/url_launcher.dart`. Future<bool> launch( String url, { required bool useSafariVC, required bool useWebView, required bool enableJavaScript, required bool enableDomStorage, required bool universalLinksOnly, required Map<String, String> headers, String? webOnlyWindowName, }) { throw UnimplementedError('launch() has not been implemented.'); } /// Passes [url] to the underlying platform for handling. /// /// Returns `true` if the given [url] was successfully launched. Future<bool> launchUrl(String url, LaunchOptions options) { final bool isWebURL = url.startsWith('http:') || url.startsWith('https:'); final bool useWebView = options.mode == PreferredLaunchMode.inAppWebView || options.mode == PreferredLaunchMode.inAppBrowserView || (isWebURL && options.mode == PreferredLaunchMode.platformDefault); return launch( url, useSafariVC: useWebView, useWebView: useWebView, enableJavaScript: options.webViewConfiguration.enableJavaScript, enableDomStorage: options.webViewConfiguration.enableDomStorage, universalLinksOnly: options.mode == PreferredLaunchMode.externalNonBrowserApplication, headers: options.webViewConfiguration.headers, webOnlyWindowName: options.webOnlyWindowName, ); } /// Closes the web view, if one was opened earlier by [launchUrl]. /// /// This will only work if the launch mode (the actual launch mode used, /// not the requested launch mode, which may not match if [supportsMode] is /// false for the requested mode) was one for which [supportsCloseForMode] /// returns true. Future<void> closeWebView() { throw UnimplementedError('closeWebView() has not been implemented.'); } /// Returns true if the given launch mode is supported by the current /// implementation. /// /// Clients are not required to query this, as implementations are strongly /// encouraged to automatically fall back to other modes if a launch is /// requested using an unsupported mode (matching historical behavior of the /// plugin, and thus maximizing compatibility with existing code). Future<bool> supportsMode(PreferredLaunchMode mode) { return Future<bool>.value(mode == PreferredLaunchMode.platformDefault); } /// Returns true if the given launch mode can be closed with [closeWebView]. Future<bool> supportsCloseForMode(PreferredLaunchMode mode) { // This is the historical documented behavior, so default to that for // compatibility. return Future<bool>.value(mode == PreferredLaunchMode.inAppWebView); } }
packages/packages/url_launcher/url_launcher_platform_interface/lib/src/url_launcher_platform.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_platform_interface/lib/src/url_launcher_platform.dart", "repo_id": "packages", "token_count": 1354 }
1,135
name: regular_integration_tests publish_to: none environment: sdk: ^3.3.0 flutter: ">=3.19.0" dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter mockito: 5.4.4 url_launcher_platform_interface: ^2.2.0 url_launcher_web: path: ../ web: ^0.5.0
packages/packages/url_launcher/url_launcher_web/example/pubspec.yaml/0
{ "file_path": "packages/packages/url_launcher/url_launcher_web/example/pubspec.yaml", "repo_id": "packages", "token_count": 156 }
1,136
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "run_loop.h" #include <windows.h> #include <algorithm> RunLoop::RunLoop() {} RunLoop::~RunLoop() {} void RunLoop::Run() { bool keep_running = true; TimePoint next_flutter_event_time = TimePoint::clock::now(); while (keep_running) { std::chrono::nanoseconds wait_duration = std::max(std::chrono::nanoseconds(0), next_flutter_event_time - TimePoint::clock::now()); ::MsgWaitForMultipleObjects( 0, nullptr, FALSE, static_cast<DWORD>(wait_duration.count() / 1000), QS_ALLINPUT); bool processed_events = false; MSG message; // All pending Windows messages must be processed; MsgWaitForMultipleObjects // won't return again for items left in the queue after PeekMessage. while (::PeekMessage(&message, nullptr, 0, 0, PM_REMOVE)) { processed_events = true; if (message.message == WM_QUIT) { keep_running = false; break; } ::TranslateMessage(&message); ::DispatchMessage(&message); // Allow Flutter to process messages each time a Windows message is // processed, to prevent starvation. next_flutter_event_time = std::min(next_flutter_event_time, ProcessFlutterMessages()); } // If the PeekMessage loop didn't run, process Flutter messages. if (!processed_events) { next_flutter_event_time = std::min(next_flutter_event_time, ProcessFlutterMessages()); } } } void RunLoop::RegisterFlutterInstance( flutter::FlutterEngine* flutter_instance) { flutter_instances_.insert(flutter_instance); } void RunLoop::UnregisterFlutterInstance( flutter::FlutterEngine* flutter_instance) { flutter_instances_.erase(flutter_instance); } RunLoop::TimePoint RunLoop::ProcessFlutterMessages() { TimePoint next_event_time = TimePoint::max(); for (auto instance : flutter_instances_) { std::chrono::nanoseconds wait_duration = instance->ProcessMessages(); if (wait_duration != std::chrono::nanoseconds::max()) { next_event_time = std::min(next_event_time, TimePoint::clock::now() + wait_duration); } } return next_event_time; }
packages/packages/url_launcher/url_launcher_windows/example/windows/runner/run_loop.cpp/0
{ "file_path": "packages/packages/url_launcher/url_launcher_windows/example/windows/runner/run_loop.cpp", "repo_id": "packages", "token_count": 853 }
1,137
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v13.0.0), do not edit directly. // See also: https://pub.dev/packages/pigeon #undef _HAS_EXCEPTIONS #include "messages.g.h" #include <flutter/basic_message_channel.h> #include <flutter/binary_messenger.h> #include <flutter/encodable_value.h> #include <flutter/standard_message_codec.h> #include <map> #include <optional> #include <string> namespace url_launcher_windows { using flutter::BasicMessageChannel; using flutter::CustomEncodableValue; using flutter::EncodableList; using flutter::EncodableMap; using flutter::EncodableValue; /// The codec used by UrlLauncherApi. const flutter::StandardMessageCodec& UrlLauncherApi::GetCodec() { return flutter::StandardMessageCodec::GetInstance( &flutter::StandardCodecSerializer::GetInstance()); } // Sets up an instance of `UrlLauncherApi` to handle messages through the // `binary_messenger`. void UrlLauncherApi::SetUp(flutter::BinaryMessenger* binary_messenger, UrlLauncherApi* api) { { auto channel = std::make_unique<BasicMessageChannel<>>( binary_messenger, "dev.flutter.pigeon.url_launcher_windows.UrlLauncherApi.canLaunchUrl", &GetCodec()); if (api != nullptr) { channel->SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_url_arg = args.at(0); if (encodable_url_arg.IsNull()) { reply(WrapError("url_arg unexpectedly null.")); return; } const auto& url_arg = std::get<std::string>(encodable_url_arg); ErrorOr<bool> output = api->CanLaunchUrl(url_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel->SetMessageHandler(nullptr); } } { auto channel = std::make_unique<BasicMessageChannel<>>( binary_messenger, "dev.flutter.pigeon.url_launcher_windows.UrlLauncherApi.launchUrl", &GetCodec()); if (api != nullptr) { channel->SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_url_arg = args.at(0); if (encodable_url_arg.IsNull()) { reply(WrapError("url_arg unexpectedly null.")); return; } const auto& url_arg = std::get<std::string>(encodable_url_arg); ErrorOr<bool> output = api->LaunchUrl(url_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel->SetMessageHandler(nullptr); } } } EncodableValue UrlLauncherApi::WrapError(std::string_view error_message) { return EncodableValue( EncodableList{EncodableValue(std::string(error_message)), EncodableValue("Error"), EncodableValue()}); } EncodableValue UrlLauncherApi::WrapError(const FlutterError& error) { return EncodableValue(EncodableList{EncodableValue(error.code()), EncodableValue(error.message()), error.details()}); } } // namespace url_launcher_windows
packages/packages/url_launcher/url_launcher_windows/windows/messages.g.cpp/0
{ "file_path": "packages/packages/url_launcher/url_launcher_windows/windows/messages.g.cpp", "repo_id": "packages", "token_count": 1981 }
1,138
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:video_player_platform_interface/video_player_platform_interface.dart'; import 'src/closed_caption_file.dart'; export 'package:video_player_platform_interface/video_player_platform_interface.dart' show DataSourceType, DurationRange, VideoFormat, VideoPlayerOptions; export 'src/closed_caption_file.dart'; VideoPlayerPlatform? _lastVideoPlayerPlatform; VideoPlayerPlatform get _videoPlayerPlatform { final VideoPlayerPlatform currentInstance = VideoPlayerPlatform.instance; if (_lastVideoPlayerPlatform != currentInstance) { // This will clear all open videos on the platform when a full restart is // performed. currentInstance.init(); _lastVideoPlayerPlatform = currentInstance; } return currentInstance; } /// The duration, current position, buffering state, error state and settings /// of a [VideoPlayerController]. @immutable class VideoPlayerValue { /// Constructs a video with the given values. Only [duration] is required. The /// rest will initialize with default values when unset. const VideoPlayerValue({ required this.duration, this.size = Size.zero, this.position = Duration.zero, this.caption = Caption.none, this.captionOffset = Duration.zero, this.buffered = const <DurationRange>[], this.isInitialized = false, this.isPlaying = false, this.isLooping = false, this.isBuffering = false, this.volume = 1.0, this.playbackSpeed = 1.0, this.rotationCorrection = 0, this.errorDescription, this.isCompleted = false, }); /// Returns an instance for a video that hasn't been loaded. const VideoPlayerValue.uninitialized() : this(duration: Duration.zero, isInitialized: false); /// Returns an instance with the given [errorDescription]. const VideoPlayerValue.erroneous(String errorDescription) : this( duration: Duration.zero, isInitialized: false, errorDescription: errorDescription); /// This constant is just to indicate that parameter is not passed to [copyWith] /// workaround for this issue https://github.com/dart-lang/language/issues/2009 static const String _defaultErrorDescription = 'defaultErrorDescription'; /// The total duration of the video. /// /// The duration is [Duration.zero] if the video hasn't been initialized. final Duration duration; /// The current playback position. final Duration position; /// The [Caption] that should be displayed based on the current [position]. /// /// This field will never be null. If there is no caption for the current /// [position], this will be a [Caption.none] object. final Caption caption; /// The [Duration] that should be used to offset the current [position] to get the correct [Caption]. /// /// Defaults to Duration.zero. final Duration captionOffset; /// The currently buffered ranges. final List<DurationRange> buffered; /// True if the video is playing. False if it's paused. final bool isPlaying; /// True if the video is looping. final bool isLooping; /// True if the video is currently buffering. final bool isBuffering; /// The current volume of the playback. final double volume; /// The current speed of the playback. final double playbackSpeed; /// A description of the error if present. /// /// If [hasError] is false this is `null`. final String? errorDescription; /// True if video has finished playing to end. /// /// Reverts to false if video position changes, or video begins playing. /// Does not update if video is looping. final bool isCompleted; /// The [size] of the currently loaded video. final Size size; /// Degrees to rotate the video (clockwise) so it is displayed correctly. final int rotationCorrection; /// Indicates whether or not the video has been loaded and is ready to play. final bool isInitialized; /// Indicates whether or not the video is in an error state. If this is true /// [errorDescription] should have information about the problem. bool get hasError => errorDescription != null; /// Returns [size.width] / [size.height]. /// /// Will return `1.0` if: /// * [isInitialized] is `false` /// * [size.width], or [size.height] is equal to `0.0` /// * aspect ratio would be less than or equal to `0.0` double get aspectRatio { if (!isInitialized || size.width == 0 || size.height == 0) { return 1.0; } final double aspectRatio = size.width / size.height; if (aspectRatio <= 0) { return 1.0; } return aspectRatio; } /// Returns a new instance that has the same values as this current instance, /// except for any overrides passed in as arguments to [copyWith]. VideoPlayerValue copyWith({ Duration? duration, Size? size, Duration? position, Caption? caption, Duration? captionOffset, List<DurationRange>? buffered, bool? isInitialized, bool? isPlaying, bool? isLooping, bool? isBuffering, double? volume, double? playbackSpeed, int? rotationCorrection, String? errorDescription = _defaultErrorDescription, bool? isCompleted, }) { return VideoPlayerValue( duration: duration ?? this.duration, size: size ?? this.size, position: position ?? this.position, caption: caption ?? this.caption, captionOffset: captionOffset ?? this.captionOffset, buffered: buffered ?? this.buffered, isInitialized: isInitialized ?? this.isInitialized, isPlaying: isPlaying ?? this.isPlaying, isLooping: isLooping ?? this.isLooping, isBuffering: isBuffering ?? this.isBuffering, volume: volume ?? this.volume, playbackSpeed: playbackSpeed ?? this.playbackSpeed, rotationCorrection: rotationCorrection ?? this.rotationCorrection, errorDescription: errorDescription != _defaultErrorDescription ? errorDescription : this.errorDescription, isCompleted: isCompleted ?? this.isCompleted, ); } @override String toString() { return '${objectRuntimeType(this, 'VideoPlayerValue')}(' 'duration: $duration, ' 'size: $size, ' 'position: $position, ' 'caption: $caption, ' 'captionOffset: $captionOffset, ' 'buffered: [${buffered.join(', ')}], ' 'isInitialized: $isInitialized, ' 'isPlaying: $isPlaying, ' 'isLooping: $isLooping, ' 'isBuffering: $isBuffering, ' 'volume: $volume, ' 'playbackSpeed: $playbackSpeed, ' 'errorDescription: $errorDescription, ' 'isCompleted: $isCompleted),'; } @override bool operator ==(Object other) => identical(this, other) || other is VideoPlayerValue && runtimeType == other.runtimeType && duration == other.duration && position == other.position && caption == other.caption && captionOffset == other.captionOffset && listEquals(buffered, other.buffered) && isPlaying == other.isPlaying && isLooping == other.isLooping && isBuffering == other.isBuffering && volume == other.volume && playbackSpeed == other.playbackSpeed && errorDescription == other.errorDescription && size == other.size && rotationCorrection == other.rotationCorrection && isInitialized == other.isInitialized && isCompleted == other.isCompleted; @override int get hashCode => Object.hash( duration, position, caption, captionOffset, buffered, isPlaying, isLooping, isBuffering, volume, playbackSpeed, errorDescription, size, rotationCorrection, isInitialized, isCompleted, ); } /// Controls a platform video player, and provides updates when the state is /// changing. /// /// Instances must be initialized with initialize. /// /// The video is displayed in a Flutter app by creating a [VideoPlayer] widget. /// /// To reclaim the resources used by the player call [dispose]. /// /// After [dispose] all further calls are ignored. class VideoPlayerController extends ValueNotifier<VideoPlayerValue> { /// Constructs a [VideoPlayerController] playing a video from an asset. /// /// The name of the asset is given by the [dataSource] argument and must not be /// null. The [package] argument must be non-null when the asset comes from a /// package and null otherwise. VideoPlayerController.asset(this.dataSource, {this.package, Future<ClosedCaptionFile>? closedCaptionFile, this.videoPlayerOptions}) : _closedCaptionFileFuture = closedCaptionFile, dataSourceType = DataSourceType.asset, formatHint = null, httpHeaders = const <String, String>{}, super(const VideoPlayerValue(duration: Duration.zero)); /// Constructs a [VideoPlayerController] playing a network video. /// /// The URI for the video is given by the [dataSource] argument. /// /// **Android only**: The [formatHint] option allows the caller to override /// the video format detection code. /// /// [httpHeaders] option allows to specify HTTP headers /// for the request to the [dataSource]. @Deprecated('Use VideoPlayerController.networkUrl instead') VideoPlayerController.network( this.dataSource, { this.formatHint, Future<ClosedCaptionFile>? closedCaptionFile, this.videoPlayerOptions, this.httpHeaders = const <String, String>{}, }) : _closedCaptionFileFuture = closedCaptionFile, dataSourceType = DataSourceType.network, package = null, super(const VideoPlayerValue(duration: Duration.zero)); /// Constructs a [VideoPlayerController] playing a network video. /// /// The URI for the video is given by the [dataSource] argument. /// /// **Android only**: The [formatHint] option allows the caller to override /// the video format detection code. /// /// [httpHeaders] option allows to specify HTTP headers /// for the request to the [dataSource]. VideoPlayerController.networkUrl( Uri url, { this.formatHint, Future<ClosedCaptionFile>? closedCaptionFile, this.videoPlayerOptions, this.httpHeaders = const <String, String>{}, }) : _closedCaptionFileFuture = closedCaptionFile, dataSource = url.toString(), dataSourceType = DataSourceType.network, package = null, super(const VideoPlayerValue(duration: Duration.zero)); /// Constructs a [VideoPlayerController] playing a video from a file. /// /// This will load the file from a file:// URI constructed from [file]'s path. /// [httpHeaders] option allows to specify HTTP headers, mainly used for hls files like (m3u8). VideoPlayerController.file(File file, {Future<ClosedCaptionFile>? closedCaptionFile, this.videoPlayerOptions, this.httpHeaders = const <String, String>{}}) : _closedCaptionFileFuture = closedCaptionFile, dataSource = Uri.file(file.absolute.path).toString(), dataSourceType = DataSourceType.file, package = null, formatHint = null, super(const VideoPlayerValue(duration: Duration.zero)); /// Constructs a [VideoPlayerController] playing a video from a contentUri. /// /// This will load the video from the input content-URI. /// This is supported on Android only. VideoPlayerController.contentUri(Uri contentUri, {Future<ClosedCaptionFile>? closedCaptionFile, this.videoPlayerOptions}) : assert(defaultTargetPlatform == TargetPlatform.android, 'VideoPlayerController.contentUri is only supported on Android.'), _closedCaptionFileFuture = closedCaptionFile, dataSource = contentUri.toString(), dataSourceType = DataSourceType.contentUri, package = null, formatHint = null, httpHeaders = const <String, String>{}, super(const VideoPlayerValue(duration: Duration.zero)); /// The URI to the video file. This will be in different formats depending on /// the [DataSourceType] of the original video. final String dataSource; /// HTTP headers used for the request to the [dataSource]. /// Only for [VideoPlayerController.network]. /// Always empty for other video types. final Map<String, String> httpHeaders; /// **Android only**. Will override the platform's generic file format /// detection with whatever is set here. final VideoFormat? formatHint; /// Describes the type of data source this [VideoPlayerController] /// is constructed with. final DataSourceType dataSourceType; /// Provide additional configuration options (optional). Like setting the audio mode to mix final VideoPlayerOptions? videoPlayerOptions; /// Only set for [asset] videos. The package that the asset was loaded from. final String? package; Future<ClosedCaptionFile>? _closedCaptionFileFuture; ClosedCaptionFile? _closedCaptionFile; Timer? _timer; bool _isDisposed = false; Completer<void>? _creatingCompleter; StreamSubscription<dynamic>? _eventSubscription; _VideoAppLifeCycleObserver? _lifeCycleObserver; /// The id of a texture that hasn't been initialized. @visibleForTesting static const int kUninitializedTextureId = -1; int _textureId = kUninitializedTextureId; /// This is just exposed for testing. It shouldn't be used by anyone depending /// on the plugin. @visibleForTesting int get textureId => _textureId; /// Attempts to open the given [dataSource] and load metadata about the video. Future<void> initialize() async { final bool allowBackgroundPlayback = videoPlayerOptions?.allowBackgroundPlayback ?? false; if (!allowBackgroundPlayback) { _lifeCycleObserver = _VideoAppLifeCycleObserver(this); } _lifeCycleObserver?.initialize(); _creatingCompleter = Completer<void>(); late DataSource dataSourceDescription; switch (dataSourceType) { case DataSourceType.asset: dataSourceDescription = DataSource( sourceType: DataSourceType.asset, asset: dataSource, package: package, ); case DataSourceType.network: dataSourceDescription = DataSource( sourceType: DataSourceType.network, uri: dataSource, formatHint: formatHint, httpHeaders: httpHeaders, ); case DataSourceType.file: dataSourceDescription = DataSource( sourceType: DataSourceType.file, uri: dataSource, httpHeaders: httpHeaders, ); case DataSourceType.contentUri: dataSourceDescription = DataSource( sourceType: DataSourceType.contentUri, uri: dataSource, ); } if (videoPlayerOptions?.mixWithOthers != null) { await _videoPlayerPlatform .setMixWithOthers(videoPlayerOptions!.mixWithOthers); } _textureId = (await _videoPlayerPlatform.create(dataSourceDescription)) ?? kUninitializedTextureId; _creatingCompleter!.complete(null); final Completer<void> initializingCompleter = Completer<void>(); void eventListener(VideoEvent event) { if (_isDisposed) { return; } switch (event.eventType) { case VideoEventType.initialized: value = value.copyWith( duration: event.duration, size: event.size, rotationCorrection: event.rotationCorrection, isInitialized: event.duration != null, errorDescription: null, isCompleted: false, ); initializingCompleter.complete(null); _applyLooping(); _applyVolume(); _applyPlayPause(); case VideoEventType.completed: // In this case we need to stop _timer, set isPlaying=false, and // position=value.duration. Instead of setting the values directly, // we use pause() and seekTo() to ensure the platform stops playing // and seeks to the last frame of the video. pause().then((void pauseResult) => seekTo(value.duration)); value = value.copyWith(isCompleted: true); case VideoEventType.bufferingUpdate: value = value.copyWith(buffered: event.buffered); case VideoEventType.bufferingStart: value = value.copyWith(isBuffering: true); case VideoEventType.bufferingEnd: value = value.copyWith(isBuffering: false); case VideoEventType.isPlayingStateUpdate: if (event.isPlaying ?? false) { value = value.copyWith(isPlaying: event.isPlaying, isCompleted: false); } else { value = value.copyWith(isPlaying: event.isPlaying); } case VideoEventType.unknown: break; } } if (_closedCaptionFileFuture != null) { await _updateClosedCaptionWithFuture(_closedCaptionFileFuture); } void errorListener(Object obj) { final PlatformException e = obj as PlatformException; value = VideoPlayerValue.erroneous(e.message!); _timer?.cancel(); if (!initializingCompleter.isCompleted) { initializingCompleter.completeError(obj); } } _eventSubscription = _videoPlayerPlatform .videoEventsFor(_textureId) .listen(eventListener, onError: errorListener); return initializingCompleter.future; } @override Future<void> dispose() async { if (_isDisposed) { return; } if (_creatingCompleter != null) { await _creatingCompleter!.future; if (!_isDisposed) { _isDisposed = true; _timer?.cancel(); await _eventSubscription?.cancel(); await _videoPlayerPlatform.dispose(_textureId); } _lifeCycleObserver?.dispose(); } _isDisposed = true; super.dispose(); } /// Starts playing the video. /// /// If the video is at the end, this method starts playing from the beginning. /// /// This method returns a future that completes as soon as the "play" command /// has been sent to the platform, not when playback itself is totally /// finished. Future<void> play() async { if (value.position == value.duration) { await seekTo(Duration.zero); } value = value.copyWith(isPlaying: true); await _applyPlayPause(); } /// Sets whether or not the video should loop after playing once. See also /// [VideoPlayerValue.isLooping]. Future<void> setLooping(bool looping) async { value = value.copyWith(isLooping: looping); await _applyLooping(); } /// Pauses the video. Future<void> pause() async { value = value.copyWith(isPlaying: false); await _applyPlayPause(); } Future<void> _applyLooping() async { if (_isDisposedOrNotInitialized) { return; } await _videoPlayerPlatform.setLooping(_textureId, value.isLooping); } Future<void> _applyPlayPause() async { if (_isDisposedOrNotInitialized) { return; } if (value.isPlaying) { await _videoPlayerPlatform.play(_textureId); // Cancel previous timer. _timer?.cancel(); _timer = Timer.periodic( const Duration(milliseconds: 500), (Timer timer) async { if (_isDisposed) { return; } final Duration? newPosition = await position; if (newPosition == null) { return; } _updatePosition(newPosition); }, ); // This ensures that the correct playback speed is always applied when // playing back. This is necessary because we do not set playback speed // when paused. await _applyPlaybackSpeed(); } else { _timer?.cancel(); await _videoPlayerPlatform.pause(_textureId); } } Future<void> _applyVolume() async { if (_isDisposedOrNotInitialized) { return; } await _videoPlayerPlatform.setVolume(_textureId, value.volume); } Future<void> _applyPlaybackSpeed() async { if (_isDisposedOrNotInitialized) { return; } // Setting the playback speed on iOS will trigger the video to play. We // prevent this from happening by not applying the playback speed until // the video is manually played from Flutter. if (!value.isPlaying) { return; } await _videoPlayerPlatform.setPlaybackSpeed( _textureId, value.playbackSpeed, ); } /// The position in the current video. Future<Duration?> get position async { if (_isDisposed) { return null; } return _videoPlayerPlatform.getPosition(_textureId); } /// Sets the video's current timestamp to be at [moment]. The next /// time the video is played it will resume from the given [moment]. /// /// If [moment] is outside of the video's full range it will be automatically /// and silently clamped. Future<void> seekTo(Duration position) async { if (_isDisposedOrNotInitialized) { return; } if (position > value.duration) { position = value.duration; } else if (position < Duration.zero) { position = Duration.zero; } await _videoPlayerPlatform.seekTo(_textureId, position); _updatePosition(position); } /// Sets the audio volume of [this]. /// /// [volume] indicates a value between 0.0 (silent) and 1.0 (full volume) on a /// linear scale. Future<void> setVolume(double volume) async { value = value.copyWith(volume: volume.clamp(0.0, 1.0)); await _applyVolume(); } /// Sets the playback speed of [this]. /// /// [speed] indicates a speed value with different platforms accepting /// different ranges for speed values. The [speed] must be greater than 0. /// /// The values will be handled as follows: /// * On web, the audio will be muted at some speed when the browser /// determines that the sound would not be useful anymore. For example, /// "Gecko mutes the sound outside the range `0.25` to `5.0`" (see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/playbackRate). /// * On Android, some very extreme speeds will not be played back accurately. /// Instead, your video will still be played back, but the speed will be /// clamped by ExoPlayer (but the values are allowed by the player, like on /// web). /// * On iOS, you can sometimes not go above `2.0` playback speed on a video. /// An error will be thrown for if the option is unsupported. It is also /// possible that your specific video cannot be slowed down, in which case /// the plugin also reports errors. Future<void> setPlaybackSpeed(double speed) async { if (speed < 0) { throw ArgumentError.value( speed, 'Negative playback speeds are generally unsupported.', ); } else if (speed == 0) { throw ArgumentError.value( speed, 'Zero playback speed is generally unsupported. Consider using [pause].', ); } value = value.copyWith(playbackSpeed: speed); await _applyPlaybackSpeed(); } /// Sets the caption offset. /// /// The [offset] will be used when getting the correct caption for a specific position. /// The [offset] can be positive or negative. /// /// The values will be handled as follows: /// * 0: This is the default behaviour. No offset will be applied. /// * >0: The caption will have a negative offset. So you will get caption text from the past. /// * <0: The caption will have a positive offset. So you will get caption text from the future. void setCaptionOffset(Duration offset) { value = value.copyWith( captionOffset: offset, caption: _getCaptionAt(value.position), ); } /// The closed caption based on the current [position] in the video. /// /// If there are no closed captions at the current [position], this will /// return an empty [Caption]. /// /// If no [closedCaptionFile] was specified, this will always return an empty /// [Caption]. Caption _getCaptionAt(Duration position) { if (_closedCaptionFile == null) { return Caption.none; } final Duration delayedPosition = position + value.captionOffset; // TODO(johnsonmh): This would be more efficient as a binary search. for (final Caption caption in _closedCaptionFile!.captions) { if (caption.start <= delayedPosition && caption.end >= delayedPosition) { return caption; } } return Caption.none; } /// Returns the file containing closed captions for the video, if any. Future<ClosedCaptionFile>? get closedCaptionFile { return _closedCaptionFileFuture; } /// Sets a closed caption file. /// /// If [closedCaptionFile] is null, closed captions will be removed. Future<void> setClosedCaptionFile( Future<ClosedCaptionFile>? closedCaptionFile, ) async { await _updateClosedCaptionWithFuture(closedCaptionFile); _closedCaptionFileFuture = closedCaptionFile; } Future<void> _updateClosedCaptionWithFuture( Future<ClosedCaptionFile>? closedCaptionFile, ) async { _closedCaptionFile = await closedCaptionFile; value = value.copyWith(caption: _getCaptionAt(value.position)); } void _updatePosition(Duration position) { value = value.copyWith( position: position, caption: _getCaptionAt(position), isCompleted: position == value.duration, ); } @override void removeListener(VoidCallback listener) { // Prevent VideoPlayer from causing an exception to be thrown when attempting to // remove its own listener after the controller has already been disposed. if (!_isDisposed) { super.removeListener(listener); } } bool get _isDisposedOrNotInitialized => _isDisposed || !value.isInitialized; } class _VideoAppLifeCycleObserver extends Object with WidgetsBindingObserver { _VideoAppLifeCycleObserver(this._controller); bool _wasPlayingBeforePause = false; final VideoPlayerController _controller; void initialize() { _ambiguate(WidgetsBinding.instance)!.addObserver(this); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.paused) { _wasPlayingBeforePause = _controller.value.isPlaying; _controller.pause(); } else if (state == AppLifecycleState.resumed) { if (_wasPlayingBeforePause) { _controller.play(); } } } void dispose() { _ambiguate(WidgetsBinding.instance)!.removeObserver(this); } } /// Widget that displays the video controlled by [controller]. class VideoPlayer extends StatefulWidget { /// Uses the given [controller] for all video rendered in this widget. const VideoPlayer(this.controller, {super.key}); /// The [VideoPlayerController] responsible for the video being rendered in /// this widget. final VideoPlayerController controller; @override State<VideoPlayer> createState() => _VideoPlayerState(); } class _VideoPlayerState extends State<VideoPlayer> { _VideoPlayerState() { _listener = () { final int newTextureId = widget.controller.textureId; if (newTextureId != _textureId) { setState(() { _textureId = newTextureId; }); } }; } late VoidCallback _listener; late int _textureId; @override void initState() { super.initState(); _textureId = widget.controller.textureId; // Need to listen for initialization events since the actual texture ID // becomes available after asynchronous initialization finishes. widget.controller.addListener(_listener); } @override void didUpdateWidget(VideoPlayer oldWidget) { super.didUpdateWidget(oldWidget); oldWidget.controller.removeListener(_listener); _textureId = widget.controller.textureId; widget.controller.addListener(_listener); } @override void deactivate() { super.deactivate(); widget.controller.removeListener(_listener); } @override Widget build(BuildContext context) { return _textureId == VideoPlayerController.kUninitializedTextureId ? Container() : _VideoPlayerWithRotation( rotation: widget.controller.value.rotationCorrection, child: _videoPlayerPlatform.buildView(_textureId), ); } } class _VideoPlayerWithRotation extends StatelessWidget { const _VideoPlayerWithRotation({required this.rotation, required this.child}); final int rotation; final Widget child; @override Widget build(BuildContext context) => rotation == 0 ? child : Transform.rotate( angle: rotation * math.pi / 180, child: child, ); } /// Used to configure the [VideoProgressIndicator] widget's colors for how it /// describes the video's status. /// /// The widget uses default colors that are customizable through this class. class VideoProgressColors { /// Any property can be set to any color. They each have defaults. /// /// [playedColor] defaults to red at 70% opacity. This fills up a portion of /// the [VideoProgressIndicator] to represent how much of the video has played /// so far. /// /// [bufferedColor] defaults to blue at 20% opacity. This fills up a portion /// of [VideoProgressIndicator] to represent how much of the video has /// buffered so far. /// /// [backgroundColor] defaults to gray at 50% opacity. This is the background /// color behind both [playedColor] and [bufferedColor] to denote the total /// size of the video compared to either of those values. const VideoProgressColors({ this.playedColor = const Color.fromRGBO(255, 0, 0, 0.7), this.bufferedColor = const Color.fromRGBO(50, 50, 200, 0.2), this.backgroundColor = const Color.fromRGBO(200, 200, 200, 0.5), }); /// [playedColor] defaults to red at 70% opacity. This fills up a portion of /// the [VideoProgressIndicator] to represent how much of the video has played /// so far. final Color playedColor; /// [bufferedColor] defaults to blue at 20% opacity. This fills up a portion /// of [VideoProgressIndicator] to represent how much of the video has /// buffered so far. final Color bufferedColor; /// [backgroundColor] defaults to gray at 50% opacity. This is the background /// color behind both [playedColor] and [bufferedColor] to denote the total /// size of the video compared to either of those values. final Color backgroundColor; } /// A scrubber to control [VideoPlayerController]s class VideoScrubber extends StatefulWidget { /// Create a [VideoScrubber] handler with the given [child]. /// /// [controller] is the [VideoPlayerController] that will be controlled by /// this scrubber. const VideoScrubber({ super.key, required this.child, required this.controller, }); /// The widget that will be displayed inside the gesture detector. final Widget child; /// The [VideoPlayerController] that will be controlled by this scrubber. final VideoPlayerController controller; @override State<VideoScrubber> createState() => _VideoScrubberState(); } class _VideoScrubberState extends State<VideoScrubber> { bool _controllerWasPlaying = false; VideoPlayerController get controller => widget.controller; @override Widget build(BuildContext context) { void seekToRelativePosition(Offset globalPosition) { final RenderBox box = context.findRenderObject()! as RenderBox; final Offset tapPos = box.globalToLocal(globalPosition); final double relative = tapPos.dx / box.size.width; final Duration position = controller.value.duration * relative; controller.seekTo(position); } return GestureDetector( behavior: HitTestBehavior.opaque, child: widget.child, onHorizontalDragStart: (DragStartDetails details) { if (!controller.value.isInitialized) { return; } _controllerWasPlaying = controller.value.isPlaying; if (_controllerWasPlaying) { controller.pause(); } }, onHorizontalDragUpdate: (DragUpdateDetails details) { if (!controller.value.isInitialized) { return; } seekToRelativePosition(details.globalPosition); }, onHorizontalDragEnd: (DragEndDetails details) { if (_controllerWasPlaying && controller.value.position != controller.value.duration) { controller.play(); } }, onTapDown: (TapDownDetails details) { if (!controller.value.isInitialized) { return; } seekToRelativePosition(details.globalPosition); }, ); } } /// Displays the play/buffering status of the video controlled by [controller]. /// /// If [allowScrubbing] is true, this widget will detect taps and drags and /// seek the video accordingly. /// /// [padding] allows to specify some extra padding around the progress indicator /// that will also detect the gestures. class VideoProgressIndicator extends StatefulWidget { /// Construct an instance that displays the play/buffering status of the video /// controlled by [controller]. /// /// Defaults will be used for everything except [controller] if they're not /// provided. [allowScrubbing] defaults to false, and [padding] will default /// to `top: 5.0`. const VideoProgressIndicator( this.controller, { super.key, this.colors = const VideoProgressColors(), required this.allowScrubbing, this.padding = const EdgeInsets.only(top: 5.0), }); /// The [VideoPlayerController] that actually associates a video with this /// widget. final VideoPlayerController controller; /// The default colors used throughout the indicator. /// /// See [VideoProgressColors] for default values. final VideoProgressColors colors; /// When true, the widget will detect touch input and try to seek the video /// accordingly. The widget ignores such input when false. /// /// Defaults to false. final bool allowScrubbing; /// This allows for visual padding around the progress indicator that can /// still detect gestures via [allowScrubbing]. /// /// Defaults to `top: 5.0`. final EdgeInsets padding; @override State<VideoProgressIndicator> createState() => _VideoProgressIndicatorState(); } class _VideoProgressIndicatorState extends State<VideoProgressIndicator> { _VideoProgressIndicatorState() { listener = () { if (!mounted) { return; } setState(() {}); }; } late VoidCallback listener; VideoPlayerController get controller => widget.controller; VideoProgressColors get colors => widget.colors; @override void initState() { super.initState(); controller.addListener(listener); } @override void deactivate() { controller.removeListener(listener); super.deactivate(); } @override Widget build(BuildContext context) { Widget progressIndicator; if (controller.value.isInitialized) { final int duration = controller.value.duration.inMilliseconds; final int position = controller.value.position.inMilliseconds; int maxBuffering = 0; for (final DurationRange range in controller.value.buffered) { final int end = range.end.inMilliseconds; if (end > maxBuffering) { maxBuffering = end; } } progressIndicator = Stack( fit: StackFit.passthrough, children: <Widget>[ LinearProgressIndicator( value: maxBuffering / duration, valueColor: AlwaysStoppedAnimation<Color>(colors.bufferedColor), backgroundColor: colors.backgroundColor, ), LinearProgressIndicator( value: position / duration, valueColor: AlwaysStoppedAnimation<Color>(colors.playedColor), backgroundColor: Colors.transparent, ), ], ); } else { progressIndicator = LinearProgressIndicator( valueColor: AlwaysStoppedAnimation<Color>(colors.playedColor), backgroundColor: colors.backgroundColor, ); } final Widget paddedProgressIndicator = Padding( padding: widget.padding, child: progressIndicator, ); if (widget.allowScrubbing) { return VideoScrubber( controller: controller, child: paddedProgressIndicator, ); } else { return paddedProgressIndicator; } } } /// Widget for displaying closed captions on top of a video. /// /// If [text] is null, this widget will not display anything. /// /// If [textStyle] is supplied, it will be used to style the text in the closed /// caption. /// /// Note: in order to have closed captions, you need to specify a /// [VideoPlayerController.closedCaptionFile]. /// /// Usage: /// /// ```dart /// Stack(children: <Widget>[ /// VideoPlayer(_controller), /// ClosedCaption(text: _controller.value.caption.text), /// ]), /// ``` class ClosedCaption extends StatelessWidget { /// Creates a a new closed caption, designed to be used with /// [VideoPlayerValue.caption]. /// /// If [text] is null or empty, nothing will be displayed. const ClosedCaption({super.key, this.text, this.textStyle}); /// The text that will be shown in the closed caption, or null if no caption /// should be shown. /// If the text is empty the caption will not be shown. final String? text; /// Specifies how the text in the closed caption should look. /// /// If null, defaults to [DefaultTextStyle.of(context).style] with size 36 /// font colored white. final TextStyle? textStyle; @override Widget build(BuildContext context) { final String? text = this.text; if (text == null || text.isEmpty) { return const SizedBox.shrink(); } final TextStyle effectiveTextStyle = textStyle ?? DefaultTextStyle.of(context).style.copyWith( fontSize: 36.0, color: Colors.white, ); return Align( alignment: Alignment.bottomCenter, child: Padding( padding: const EdgeInsets.only(bottom: 24.0), child: DecoratedBox( decoration: BoxDecoration( color: const Color(0xB8000000), borderRadius: BorderRadius.circular(2.0), ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 2.0), child: Text(text, style: effectiveTextStyle), ), ), ), ); } } /// This allows a value of type T or T? to be treated as a value of type T?. /// /// We use this so that APIs that have become non-nullable can still be used /// with `!` and `?` on the stable branch. T? _ambiguate<T>(T? value) => value;
packages/packages/video_player/video_player/lib/video_player.dart/0
{ "file_path": "packages/packages/video_player/video_player/lib/video_player.dart", "repo_id": "packages", "token_count": 13190 }
1,139
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v9.2.5), do not edit directly. // See also: https://pub.dev/packages/pigeon package io.flutter.plugins.videoplayer; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MessageCodec; import io.flutter.plugin.common.StandardMessageCodec; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Map; /** Generated class from Pigeon. */ @SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"}) public class Messages { /** Error class for passing custom error details to Flutter via a thrown PlatformException. */ public static class FlutterError extends RuntimeException { /** The error code. */ public final String code; /** The error details. Must be a datatype supported by the api codec. */ public final Object details; public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) { super(message); this.code = code; this.details = details; } } @NonNull protected static ArrayList<Object> wrapError(@NonNull Throwable exception) { ArrayList<Object> errorList = new ArrayList<Object>(3); if (exception instanceof FlutterError) { FlutterError error = (FlutterError) exception; errorList.add(error.code); errorList.add(error.getMessage()); errorList.add(error.details); } else { errorList.add(exception.toString()); errorList.add(exception.getClass().getSimpleName()); errorList.add( "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); } return errorList; } /** Generated class from Pigeon that represents data sent in messages. */ public static final class TextureMessage { private @NonNull Long textureId; public @NonNull Long getTextureId() { return textureId; } public void setTextureId(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"textureId\" is null."); } this.textureId = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ TextureMessage() {} public static final class Builder { private @Nullable Long textureId; public @NonNull Builder setTextureId(@NonNull Long setterArg) { this.textureId = setterArg; return this; } public @NonNull TextureMessage build() { TextureMessage pigeonReturn = new TextureMessage(); pigeonReturn.setTextureId(textureId); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(1); toListResult.add(textureId); return toListResult; } static @NonNull TextureMessage fromList(@NonNull ArrayList<Object> list) { TextureMessage pigeonResult = new TextureMessage(); Object textureId = list.get(0); pigeonResult.setTextureId( (textureId == null) ? null : ((textureId instanceof Integer) ? (Integer) textureId : (Long) textureId)); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class LoopingMessage { private @NonNull Long textureId; public @NonNull Long getTextureId() { return textureId; } public void setTextureId(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"textureId\" is null."); } this.textureId = setterArg; } private @NonNull Boolean isLooping; public @NonNull Boolean getIsLooping() { return isLooping; } public void setIsLooping(@NonNull Boolean setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"isLooping\" is null."); } this.isLooping = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ LoopingMessage() {} public static final class Builder { private @Nullable Long textureId; public @NonNull Builder setTextureId(@NonNull Long setterArg) { this.textureId = setterArg; return this; } private @Nullable Boolean isLooping; public @NonNull Builder setIsLooping(@NonNull Boolean setterArg) { this.isLooping = setterArg; return this; } public @NonNull LoopingMessage build() { LoopingMessage pigeonReturn = new LoopingMessage(); pigeonReturn.setTextureId(textureId); pigeonReturn.setIsLooping(isLooping); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(2); toListResult.add(textureId); toListResult.add(isLooping); return toListResult; } static @NonNull LoopingMessage fromList(@NonNull ArrayList<Object> list) { LoopingMessage pigeonResult = new LoopingMessage(); Object textureId = list.get(0); pigeonResult.setTextureId( (textureId == null) ? null : ((textureId instanceof Integer) ? (Integer) textureId : (Long) textureId)); Object isLooping = list.get(1); pigeonResult.setIsLooping((Boolean) isLooping); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class VolumeMessage { private @NonNull Long textureId; public @NonNull Long getTextureId() { return textureId; } public void setTextureId(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"textureId\" is null."); } this.textureId = setterArg; } private @NonNull Double volume; public @NonNull Double getVolume() { return volume; } public void setVolume(@NonNull Double setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"volume\" is null."); } this.volume = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ VolumeMessage() {} public static final class Builder { private @Nullable Long textureId; public @NonNull Builder setTextureId(@NonNull Long setterArg) { this.textureId = setterArg; return this; } private @Nullable Double volume; public @NonNull Builder setVolume(@NonNull Double setterArg) { this.volume = setterArg; return this; } public @NonNull VolumeMessage build() { VolumeMessage pigeonReturn = new VolumeMessage(); pigeonReturn.setTextureId(textureId); pigeonReturn.setVolume(volume); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(2); toListResult.add(textureId); toListResult.add(volume); return toListResult; } static @NonNull VolumeMessage fromList(@NonNull ArrayList<Object> list) { VolumeMessage pigeonResult = new VolumeMessage(); Object textureId = list.get(0); pigeonResult.setTextureId( (textureId == null) ? null : ((textureId instanceof Integer) ? (Integer) textureId : (Long) textureId)); Object volume = list.get(1); pigeonResult.setVolume((Double) volume); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class PlaybackSpeedMessage { private @NonNull Long textureId; public @NonNull Long getTextureId() { return textureId; } public void setTextureId(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"textureId\" is null."); } this.textureId = setterArg; } private @NonNull Double speed; public @NonNull Double getSpeed() { return speed; } public void setSpeed(@NonNull Double setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"speed\" is null."); } this.speed = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ PlaybackSpeedMessage() {} public static final class Builder { private @Nullable Long textureId; public @NonNull Builder setTextureId(@NonNull Long setterArg) { this.textureId = setterArg; return this; } private @Nullable Double speed; public @NonNull Builder setSpeed(@NonNull Double setterArg) { this.speed = setterArg; return this; } public @NonNull PlaybackSpeedMessage build() { PlaybackSpeedMessage pigeonReturn = new PlaybackSpeedMessage(); pigeonReturn.setTextureId(textureId); pigeonReturn.setSpeed(speed); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(2); toListResult.add(textureId); toListResult.add(speed); return toListResult; } static @NonNull PlaybackSpeedMessage fromList(@NonNull ArrayList<Object> list) { PlaybackSpeedMessage pigeonResult = new PlaybackSpeedMessage(); Object textureId = list.get(0); pigeonResult.setTextureId( (textureId == null) ? null : ((textureId instanceof Integer) ? (Integer) textureId : (Long) textureId)); Object speed = list.get(1); pigeonResult.setSpeed((Double) speed); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class PositionMessage { private @NonNull Long textureId; public @NonNull Long getTextureId() { return textureId; } public void setTextureId(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"textureId\" is null."); } this.textureId = setterArg; } private @NonNull Long position; public @NonNull Long getPosition() { return position; } public void setPosition(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"position\" is null."); } this.position = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ PositionMessage() {} public static final class Builder { private @Nullable Long textureId; public @NonNull Builder setTextureId(@NonNull Long setterArg) { this.textureId = setterArg; return this; } private @Nullable Long position; public @NonNull Builder setPosition(@NonNull Long setterArg) { this.position = setterArg; return this; } public @NonNull PositionMessage build() { PositionMessage pigeonReturn = new PositionMessage(); pigeonReturn.setTextureId(textureId); pigeonReturn.setPosition(position); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(2); toListResult.add(textureId); toListResult.add(position); return toListResult; } static @NonNull PositionMessage fromList(@NonNull ArrayList<Object> list) { PositionMessage pigeonResult = new PositionMessage(); Object textureId = list.get(0); pigeonResult.setTextureId( (textureId == null) ? null : ((textureId instanceof Integer) ? (Integer) textureId : (Long) textureId)); Object position = list.get(1); pigeonResult.setPosition( (position == null) ? null : ((position instanceof Integer) ? (Integer) position : (Long) position)); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class CreateMessage { private @Nullable String asset; public @Nullable String getAsset() { return asset; } public void setAsset(@Nullable String setterArg) { this.asset = setterArg; } private @Nullable String uri; public @Nullable String getUri() { return uri; } public void setUri(@Nullable String setterArg) { this.uri = setterArg; } private @Nullable String packageName; public @Nullable String getPackageName() { return packageName; } public void setPackageName(@Nullable String setterArg) { this.packageName = setterArg; } private @Nullable String formatHint; public @Nullable String getFormatHint() { return formatHint; } public void setFormatHint(@Nullable String setterArg) { this.formatHint = setterArg; } private @NonNull Map<String, String> httpHeaders; public @NonNull Map<String, String> getHttpHeaders() { return httpHeaders; } public void setHttpHeaders(@NonNull Map<String, String> setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"httpHeaders\" is null."); } this.httpHeaders = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ CreateMessage() {} public static final class Builder { private @Nullable String asset; public @NonNull Builder setAsset(@Nullable String setterArg) { this.asset = setterArg; return this; } private @Nullable String uri; public @NonNull Builder setUri(@Nullable String setterArg) { this.uri = setterArg; return this; } private @Nullable String packageName; public @NonNull Builder setPackageName(@Nullable String setterArg) { this.packageName = setterArg; return this; } private @Nullable String formatHint; public @NonNull Builder setFormatHint(@Nullable String setterArg) { this.formatHint = setterArg; return this; } private @Nullable Map<String, String> httpHeaders; public @NonNull Builder setHttpHeaders(@NonNull Map<String, String> setterArg) { this.httpHeaders = setterArg; return this; } public @NonNull CreateMessage build() { CreateMessage pigeonReturn = new CreateMessage(); pigeonReturn.setAsset(asset); pigeonReturn.setUri(uri); pigeonReturn.setPackageName(packageName); pigeonReturn.setFormatHint(formatHint); pigeonReturn.setHttpHeaders(httpHeaders); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(5); toListResult.add(asset); toListResult.add(uri); toListResult.add(packageName); toListResult.add(formatHint); toListResult.add(httpHeaders); return toListResult; } static @NonNull CreateMessage fromList(@NonNull ArrayList<Object> list) { CreateMessage pigeonResult = new CreateMessage(); Object asset = list.get(0); pigeonResult.setAsset((String) asset); Object uri = list.get(1); pigeonResult.setUri((String) uri); Object packageName = list.get(2); pigeonResult.setPackageName((String) packageName); Object formatHint = list.get(3); pigeonResult.setFormatHint((String) formatHint); Object httpHeaders = list.get(4); pigeonResult.setHttpHeaders((Map<String, String>) httpHeaders); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class MixWithOthersMessage { private @NonNull Boolean mixWithOthers; public @NonNull Boolean getMixWithOthers() { return mixWithOthers; } public void setMixWithOthers(@NonNull Boolean setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"mixWithOthers\" is null."); } this.mixWithOthers = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ MixWithOthersMessage() {} public static final class Builder { private @Nullable Boolean mixWithOthers; public @NonNull Builder setMixWithOthers(@NonNull Boolean setterArg) { this.mixWithOthers = setterArg; return this; } public @NonNull MixWithOthersMessage build() { MixWithOthersMessage pigeonReturn = new MixWithOthersMessage(); pigeonReturn.setMixWithOthers(mixWithOthers); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(1); toListResult.add(mixWithOthers); return toListResult; } static @NonNull MixWithOthersMessage fromList(@NonNull ArrayList<Object> list) { MixWithOthersMessage pigeonResult = new MixWithOthersMessage(); Object mixWithOthers = list.get(0); pigeonResult.setMixWithOthers((Boolean) mixWithOthers); return pigeonResult; } } private static class AndroidVideoPlayerApiCodec extends StandardMessageCodec { public static final AndroidVideoPlayerApiCodec INSTANCE = new AndroidVideoPlayerApiCodec(); private AndroidVideoPlayerApiCodec() {} @Override protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { switch (type) { case (byte) 128: return CreateMessage.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 129: return LoopingMessage.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 130: return MixWithOthersMessage.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 131: return PlaybackSpeedMessage.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 132: return PositionMessage.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 133: return TextureMessage.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 134: return VolumeMessage.fromList((ArrayList<Object>) readValue(buffer)); default: return super.readValueOfType(type, buffer); } } @Override protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { if (value instanceof CreateMessage) { stream.write(128); writeValue(stream, ((CreateMessage) value).toList()); } else if (value instanceof LoopingMessage) { stream.write(129); writeValue(stream, ((LoopingMessage) value).toList()); } else if (value instanceof MixWithOthersMessage) { stream.write(130); writeValue(stream, ((MixWithOthersMessage) value).toList()); } else if (value instanceof PlaybackSpeedMessage) { stream.write(131); writeValue(stream, ((PlaybackSpeedMessage) value).toList()); } else if (value instanceof PositionMessage) { stream.write(132); writeValue(stream, ((PositionMessage) value).toList()); } else if (value instanceof TextureMessage) { stream.write(133); writeValue(stream, ((TextureMessage) value).toList()); } else if (value instanceof VolumeMessage) { stream.write(134); writeValue(stream, ((VolumeMessage) value).toList()); } else { super.writeValue(stream, value); } } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface AndroidVideoPlayerApi { void initialize(); @NonNull TextureMessage create(@NonNull CreateMessage msg); void dispose(@NonNull TextureMessage msg); void setLooping(@NonNull LoopingMessage msg); void setVolume(@NonNull VolumeMessage msg); void setPlaybackSpeed(@NonNull PlaybackSpeedMessage msg); void play(@NonNull TextureMessage msg); @NonNull PositionMessage position(@NonNull TextureMessage msg); void seekTo(@NonNull PositionMessage msg); void pause(@NonNull TextureMessage msg); void setMixWithOthers(@NonNull MixWithOthersMessage msg); /** The codec used by AndroidVideoPlayerApi. */ static @NonNull MessageCodec<Object> getCodec() { return AndroidVideoPlayerApiCodec.INSTANCE; } /** * Sets up an instance of `AndroidVideoPlayerApi` to handle messages through the * `binaryMessenger`. */ static void setup( @NonNull BinaryMessenger binaryMessenger, @Nullable AndroidVideoPlayerApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.AndroidVideoPlayerApi.initialize", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); try { api.initialize(); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.AndroidVideoPlayerApi.create", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; CreateMessage msgArg = (CreateMessage) args.get(0); try { TextureMessage output = api.create(msgArg); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.AndroidVideoPlayerApi.dispose", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; TextureMessage msgArg = (TextureMessage) args.get(0); try { api.dispose(msgArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.AndroidVideoPlayerApi.setLooping", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; LoopingMessage msgArg = (LoopingMessage) args.get(0); try { api.setLooping(msgArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.AndroidVideoPlayerApi.setVolume", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; VolumeMessage msgArg = (VolumeMessage) args.get(0); try { api.setVolume(msgArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.AndroidVideoPlayerApi.setPlaybackSpeed", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; PlaybackSpeedMessage msgArg = (PlaybackSpeedMessage) args.get(0); try { api.setPlaybackSpeed(msgArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.AndroidVideoPlayerApi.play", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; TextureMessage msgArg = (TextureMessage) args.get(0); try { api.play(msgArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.AndroidVideoPlayerApi.position", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; TextureMessage msgArg = (TextureMessage) args.get(0); try { PositionMessage output = api.position(msgArg); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.AndroidVideoPlayerApi.seekTo", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; PositionMessage msgArg = (PositionMessage) args.get(0); try { api.seekTo(msgArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.AndroidVideoPlayerApi.pause", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; TextureMessage msgArg = (TextureMessage) args.get(0); try { api.pause(msgArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.AndroidVideoPlayerApi.setMixWithOthers", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; MixWithOthersMessage msgArg = (MixWithOthersMessage) args.get(0); try { api.setMixWithOthers(msgArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } }
packages/packages/video_player/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/Messages.java/0
{ "file_path": "packages/packages/video_player/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/Messages.java", "repo_id": "packages", "token_count": 13085 }
1,140
// 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(stuartmorgan): Consider extracting this to a shared local (path-based) // package for use in all implementation packages. import 'dart:async'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:video_player_platform_interface/video_player_platform_interface.dart'; VideoPlayerPlatform? _cachedPlatform; VideoPlayerPlatform get _platform { if (_cachedPlatform == null) { _cachedPlatform = VideoPlayerPlatform.instance; _cachedPlatform!.init(); } return _cachedPlatform!; } /// The duration, current position, buffering state, error state and settings /// of a [MiniController]. @immutable class VideoPlayerValue { /// Constructs a video with the given values. Only [duration] is required. The /// rest will initialize with default values when unset. const VideoPlayerValue({ required this.duration, this.size = Size.zero, this.position = Duration.zero, this.buffered = const <DurationRange>[], this.isInitialized = false, this.isPlaying = false, this.isBuffering = false, this.playbackSpeed = 1.0, this.errorDescription, }); /// Returns an instance for a video that hasn't been loaded. const VideoPlayerValue.uninitialized() : this(duration: Duration.zero, isInitialized: false); /// Returns an instance with the given [errorDescription]. const VideoPlayerValue.erroneous(String errorDescription) : this( duration: Duration.zero, isInitialized: false, errorDescription: errorDescription); /// The total duration of the video. /// /// The duration is [Duration.zero] if the video hasn't been initialized. final Duration duration; /// The current playback position. final Duration position; /// The currently buffered ranges. final List<DurationRange> buffered; /// True if the video is playing. False if it's paused. final bool isPlaying; /// True if the video is currently buffering. final bool isBuffering; /// The current speed of the playback. final double playbackSpeed; /// A description of the error if present. /// /// If [hasError] is false this is `null`. final String? errorDescription; /// The [size] of the currently loaded video. final Size size; /// Indicates whether or not the video has been loaded and is ready to play. final bool isInitialized; /// Indicates whether or not the video is in an error state. If this is true /// [errorDescription] should have information about the problem. bool get hasError => errorDescription != null; /// Returns [size.width] / [size.height]. /// /// Will return `1.0` if: /// * [isInitialized] is `false` /// * [size.width], or [size.height] is equal to `0.0` /// * aspect ratio would be less than or equal to `0.0` double get aspectRatio { if (!isInitialized || size.width == 0 || size.height == 0) { return 1.0; } final double aspectRatio = size.width / size.height; if (aspectRatio <= 0) { return 1.0; } return aspectRatio; } /// Returns a new instance that has the same values as this current instance, /// except for any overrides passed in as arguments to [copyWidth]. VideoPlayerValue copyWith({ Duration? duration, Size? size, Duration? position, List<DurationRange>? buffered, bool? isInitialized, bool? isPlaying, bool? isBuffering, double? playbackSpeed, String? errorDescription, }) { return VideoPlayerValue( duration: duration ?? this.duration, size: size ?? this.size, position: position ?? this.position, buffered: buffered ?? this.buffered, isInitialized: isInitialized ?? this.isInitialized, isPlaying: isPlaying ?? this.isPlaying, isBuffering: isBuffering ?? this.isBuffering, playbackSpeed: playbackSpeed ?? this.playbackSpeed, errorDescription: errorDescription ?? this.errorDescription, ); } @override bool operator ==(Object other) => identical(this, other) || other is VideoPlayerValue && runtimeType == other.runtimeType && duration == other.duration && position == other.position && listEquals(buffered, other.buffered) && isPlaying == other.isPlaying && isBuffering == other.isBuffering && playbackSpeed == other.playbackSpeed && errorDescription == other.errorDescription && size == other.size && isInitialized == other.isInitialized; @override int get hashCode => Object.hash( duration, position, buffered, isPlaying, isBuffering, playbackSpeed, errorDescription, size, isInitialized, ); } /// A very minimal version of `VideoPlayerController` for running the example /// without relying on `video_player`. class MiniController extends ValueNotifier<VideoPlayerValue> { /// Constructs a [MiniController] playing a video from an asset. /// /// The name of the asset is given by the [dataSource] argument and must not be /// null. The [package] argument must be non-null when the asset comes from a /// package and null otherwise. MiniController.asset(this.dataSource, {this.package}) : dataSourceType = DataSourceType.asset, super(const VideoPlayerValue(duration: Duration.zero)); /// Constructs a [MiniController] playing a video from obtained from /// the network. MiniController.network(this.dataSource) : dataSourceType = DataSourceType.network, package = null, super(const VideoPlayerValue(duration: Duration.zero)); /// Constructs a [MiniController] playing a video from obtained from a file. MiniController.file(File file) : dataSource = Uri.file(file.absolute.path).toString(), dataSourceType = DataSourceType.file, package = null, super(const VideoPlayerValue(duration: Duration.zero)); /// The URI to the video file. This will be in different formats depending on /// the [DataSourceType] of the original video. final String dataSource; /// Describes the type of data source this [MiniController] /// is constructed with. final DataSourceType dataSourceType; /// Only set for [asset] videos. The package that the asset was loaded from. final String? package; Timer? _timer; Completer<void>? _creatingCompleter; StreamSubscription<dynamic>? _eventSubscription; /// The id of a texture that hasn't been initialized. @visibleForTesting static const int kUninitializedTextureId = -1; int _textureId = kUninitializedTextureId; /// This is just exposed for testing. It shouldn't be used by anyone depending /// on the plugin. @visibleForTesting int get textureId => _textureId; /// Attempts to open the given [dataSource] and load metadata about the video. Future<void> initialize() async { _creatingCompleter = Completer<void>(); late DataSource dataSourceDescription; switch (dataSourceType) { case DataSourceType.asset: dataSourceDescription = DataSource( sourceType: DataSourceType.asset, asset: dataSource, package: package, ); case DataSourceType.network: dataSourceDescription = DataSource( sourceType: DataSourceType.network, uri: dataSource, ); case DataSourceType.file: dataSourceDescription = DataSource( sourceType: DataSourceType.file, uri: dataSource, ); case DataSourceType.contentUri: dataSourceDescription = DataSource( sourceType: DataSourceType.contentUri, uri: dataSource, ); } _textureId = (await _platform.create(dataSourceDescription)) ?? kUninitializedTextureId; _creatingCompleter!.complete(null); final Completer<void> initializingCompleter = Completer<void>(); void eventListener(VideoEvent event) { switch (event.eventType) { case VideoEventType.initialized: value = value.copyWith( duration: event.duration, size: event.size, isInitialized: event.duration != null, ); initializingCompleter.complete(null); _platform.setVolume(_textureId, 1.0); _platform.setLooping(_textureId, true); _applyPlayPause(); case VideoEventType.completed: pause().then((void pauseResult) => seekTo(value.duration)); case VideoEventType.bufferingUpdate: value = value.copyWith(buffered: event.buffered); case VideoEventType.bufferingStart: value = value.copyWith(isBuffering: true); case VideoEventType.bufferingEnd: value = value.copyWith(isBuffering: false); case VideoEventType.isPlayingStateUpdate: value = value.copyWith(isPlaying: event.isPlaying); case VideoEventType.unknown: break; } } void errorListener(Object obj) { final PlatformException e = obj as PlatformException; value = VideoPlayerValue.erroneous(e.message!); _timer?.cancel(); if (!initializingCompleter.isCompleted) { initializingCompleter.completeError(obj); } } _eventSubscription = _platform .videoEventsFor(_textureId) .listen(eventListener, onError: errorListener); return initializingCompleter.future; } @override Future<void> dispose() async { if (_creatingCompleter != null) { await _creatingCompleter!.future; _timer?.cancel(); await _eventSubscription?.cancel(); await _platform.dispose(_textureId); } super.dispose(); } /// Starts playing the video. Future<void> play() async { value = value.copyWith(isPlaying: true); await _applyPlayPause(); } /// Pauses the video. Future<void> pause() async { value = value.copyWith(isPlaying: false); await _applyPlayPause(); } Future<void> _applyPlayPause() async { _timer?.cancel(); if (value.isPlaying) { await _platform.play(_textureId); _timer = Timer.periodic( const Duration(milliseconds: 500), (Timer timer) async { final Duration? newPosition = await position; if (newPosition == null) { return; } _updatePosition(newPosition); }, ); await _applyPlaybackSpeed(); } else { await _platform.pause(_textureId); } } Future<void> _applyPlaybackSpeed() async { if (value.isPlaying) { await _platform.setPlaybackSpeed( _textureId, value.playbackSpeed, ); } } /// The position in the current video. Future<Duration?> get position async { return _platform.getPosition(_textureId); } /// Sets the video's current timestamp to be at [position]. Future<void> seekTo(Duration position) async { if (position > value.duration) { position = value.duration; } else if (position < Duration.zero) { position = Duration.zero; } await _platform.seekTo(_textureId, position); _updatePosition(position); } /// Sets the playback speed. Future<void> setPlaybackSpeed(double speed) async { value = value.copyWith(playbackSpeed: speed); await _applyPlaybackSpeed(); } void _updatePosition(Duration position) { value = value.copyWith(position: position); } } /// Widget that displays the video controlled by [controller]. class VideoPlayer extends StatefulWidget { /// Uses the given [controller] for all video rendered in this widget. const VideoPlayer(this.controller, {super.key}); /// The [MiniController] responsible for the video being rendered in /// this widget. final MiniController controller; @override State<VideoPlayer> createState() => _VideoPlayerState(); } class _VideoPlayerState extends State<VideoPlayer> { _VideoPlayerState() { _listener = () { final int newTextureId = widget.controller.textureId; if (newTextureId != _textureId) { setState(() { _textureId = newTextureId; }); } }; } late VoidCallback _listener; late int _textureId; @override void initState() { super.initState(); _textureId = widget.controller.textureId; // Need to listen for initialization events since the actual texture ID // becomes available after asynchronous initialization finishes. widget.controller.addListener(_listener); } @override void didUpdateWidget(VideoPlayer oldWidget) { super.didUpdateWidget(oldWidget); oldWidget.controller.removeListener(_listener); _textureId = widget.controller.textureId; widget.controller.addListener(_listener); } @override void deactivate() { super.deactivate(); widget.controller.removeListener(_listener); } @override Widget build(BuildContext context) { return _textureId == MiniController.kUninitializedTextureId ? Container() : _platform.buildView(_textureId); } } class _VideoScrubber extends StatefulWidget { const _VideoScrubber({ required this.child, required this.controller, }); final Widget child; final MiniController controller; @override _VideoScrubberState createState() => _VideoScrubberState(); } class _VideoScrubberState extends State<_VideoScrubber> { MiniController get controller => widget.controller; @override Widget build(BuildContext context) { void seekToRelativePosition(Offset globalPosition) { final RenderBox box = context.findRenderObject()! as RenderBox; final Offset tapPos = box.globalToLocal(globalPosition); final double relative = tapPos.dx / box.size.width; final Duration position = controller.value.duration * relative; controller.seekTo(position); } return GestureDetector( behavior: HitTestBehavior.opaque, child: widget.child, onTapDown: (TapDownDetails details) { if (controller.value.isInitialized) { seekToRelativePosition(details.globalPosition); } }, ); } } /// Displays the play/buffering status of the video controlled by [controller]. class VideoProgressIndicator extends StatefulWidget { /// Construct an instance that displays the play/buffering status of the video /// controlled by [controller]. const VideoProgressIndicator(this.controller, {super.key}); /// The [MiniController] that actually associates a video with this /// widget. final MiniController controller; @override State<VideoProgressIndicator> createState() => _VideoProgressIndicatorState(); } class _VideoProgressIndicatorState extends State<VideoProgressIndicator> { _VideoProgressIndicatorState() { listener = () { if (mounted) { setState(() {}); } }; } late VoidCallback listener; MiniController get controller => widget.controller; @override void initState() { super.initState(); controller.addListener(listener); } @override void deactivate() { controller.removeListener(listener); super.deactivate(); } @override Widget build(BuildContext context) { const Color playedColor = Color.fromRGBO(255, 0, 0, 0.7); const Color bufferedColor = Color.fromRGBO(50, 50, 200, 0.2); const Color backgroundColor = Color.fromRGBO(200, 200, 200, 0.5); Widget progressIndicator; if (controller.value.isInitialized) { final int duration = controller.value.duration.inMilliseconds; final int position = controller.value.position.inMilliseconds; int maxBuffering = 0; for (final DurationRange range in controller.value.buffered) { final int end = range.end.inMilliseconds; if (end > maxBuffering) { maxBuffering = end; } } progressIndicator = Stack( fit: StackFit.passthrough, children: <Widget>[ LinearProgressIndicator( value: maxBuffering / duration, valueColor: const AlwaysStoppedAnimation<Color>(bufferedColor), backgroundColor: backgroundColor, ), LinearProgressIndicator( value: position / duration, valueColor: const AlwaysStoppedAnimation<Color>(playedColor), backgroundColor: Colors.transparent, ), ], ); } else { progressIndicator = const LinearProgressIndicator( valueColor: AlwaysStoppedAnimation<Color>(playedColor), backgroundColor: backgroundColor, ); } return _VideoScrubber( controller: controller, child: Padding( padding: const EdgeInsets.only(top: 5.0), child: progressIndicator, ), ); } }
packages/packages/video_player/video_player_android/example/lib/mini_controller.dart/0
{ "file_path": "packages/packages/video_player/video_player_android/example/lib/mini_controller.dart", "repo_id": "packages", "token_count": 5880 }
1,141
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/video_player/video_player_avfoundation/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/video_player/video_player_avfoundation/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
1,142
// 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. @JS() library video_player_web_integration_test_pkg_web_tweaks; import 'dart:js_interop'; import 'package:web/web.dart' as web; /// Adds a `controlsList` and `disablePictureInPicture` getters. extension NonStandardGettersOnVideoElement on web.HTMLVideoElement { external web.DOMTokenList? get controlsList; external JSBoolean get disablePictureInPicture; } /// Adds a `disableRemotePlayback` getter. extension NonStandardGettersOnMediaElement on web.HTMLMediaElement { external JSBoolean get disableRemotePlayback; } /// Defines JS interop to access static methods from `Object`. @JS('Object') extension type DomObject._(JSAny _) { @JS('defineProperty') external static void _defineProperty( JSAny? object, JSString property, Descriptor value); /// `Object.defineProperty`. /// /// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty static void defineProperty( JSObject object, String property, Descriptor descriptor) { return _defineProperty(object, property.toJS, descriptor); } } /// The descriptor for the property being defined or modified with `defineProperty`. /// /// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description extension type Descriptor._(JSObject _) implements JSObject { /// Builds a "data descriptor". factory Descriptor.data({ bool? writable, JSAny? value, }) => Descriptor._data( writable: writable?.toJS, value: value.jsify(), ); /// Builds an "accessor descriptor". factory Descriptor.accessor({ void Function(JSAny? value)? set, JSAny? Function()? get, }) => Descriptor._accessor( set: set?.toJS, get: get?.toJS, ); external factory Descriptor._accessor({ // JSBoolean configurable, // JSBoolean enumerable, JSFunction? set, JSFunction? get, }); external factory Descriptor._data({ // JSBoolean configurable, // JSBoolean enumerable, JSBoolean? writable, JSAny? value, }); }
packages/packages/video_player/video_player_web/example/integration_test/pkg_web_tweaks.dart/0
{ "file_path": "packages/packages/video_player/video_player_web/example/integration_test/pkg_web_tweaks.dart", "repo_id": "packages", "token_count": 763 }
1,143
## 1.2.1 * Removes a few deprecated API usages. ## 1.2.0 * Updates to web code to package `web: ^0.5.0`. * Updates SDK version to Dart `^3.3.0`. Flutter `^3.19.0`. ## 1.1.1 * Fixes new lint warnings. ## 1.1.0 * Adds `computeAverage` and `computeDelta` methods to support analysis of benchmark results. ## 1.0.1 * Adds `parse` constructors for the `BenchmarkResults` and `BenchmarkScore` classes. ## 1.0.0 * **Breaking change:** replace the `useCanvasKit` parameter in the `serveWebBenchmark` method with a new parameter `compilationOptions`, which allows you to: * specify the web renderer to use for the benchmark app (html, canvaskit, or skwasm) * specify whether to use WebAssembly to build the benchmark app * **Breaking change:** `serveWebBenchmark` now uses `canvaskit` instead of `html` as the default web renderer. ## 0.1.0+11 * Migrates benchmark recorder from `dart:html` to `package:web` to support WebAssembly. ## 0.1.0+10 * Ensure the benchmark client reloads with the proper `initialPage`. * Migrates benchmark recorder away from deprecated `js_util` APIs. ## 0.1.0+9 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Adds an optional parameter `initialPage` to `serveWebBenchmark`. ## 0.1.0+8 * Adds an optional parameter `treeShakeIcons` to `serveWebBenchmark`. * Adds a required and named parameter `treeShakeIcons` to `BenchmarkServer`. ## 0.1.0+7 * Updates `package:process` version constraints. ## 0.1.0+6 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 0.1.0+5 * Fixes unawaited_futures violations. ## 0.1.0+4 * Removes obsolete null checks on non-nullable values. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 0.1.0+3 * Migrates from SingletonFlutterWindow to PlatformDispatcher API. ## 0.1.0+2 * Updates code to fix strict-cast violations. ## 0.1.0+1 * Fixes lint warnings. ## 0.1.0 * Migrates to null safety. * **BREAKING CHANGES**: * Required parameters are non-nullable. ## 0.0.7+1 * Updates text theme parameters to avoid deprecation issues. ## 0.0.7 * Updates BlinkTraceEvents to match with changes in Chromium v89+ ## 0.0.6 * Update implementation of `_RecordingWidgetsBinding` to match the [new Binding API](https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/foundation/binding.dart#L96-L128) ## 0.0.5 * Updated dependencies to allow broader versions for upstream packages. ## 0.0.4 * Updated dependencies to allow broader versions for upstream packages. ## 0.0.3 * Fixed benchmarks failing due to trace format change for begin frame. ## 0.0.2 * Improve console messages. ## 0.0.1 - Initial release. * Provide a benchmark server (host-side) and a benchmark client (browser-side).
packages/packages/web_benchmarks/CHANGELOG.md/0
{ "file_path": "packages/packages/web_benchmarks/CHANGELOG.md", "repo_id": "packages", "token_count": 930 }
1,144
// 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:web_benchmarks/server.dart'; void main() { group('can serialize and deserialize', () { test('$BenchmarkResults', () { final Map<String, Object?> data = <String, Object?>{ 'foo': <Map<String, Object?>>[ <String, Object?>{'metric': 'foo.bar', 'value': 12.34, 'delta': -0.2}, <String, Object?>{'metric': 'foo.baz', 'value': 10, 'delta': 3.3}, ], 'bar': <Map<String, Object?>>[ <String, Object?>{'metric': 'bar.foo', 'value': 1.23}, ] }; final BenchmarkResults benchmarkResults = BenchmarkResults.parse(data); expect(benchmarkResults.scores.length, 2); final List<BenchmarkScore> fooBenchmarks = benchmarkResults.scores['foo']!; final List<BenchmarkScore> barBenchmarks = benchmarkResults.scores['bar']!; expect(fooBenchmarks.length, 2); expect(fooBenchmarks[0].metric, 'foo.bar'); expect(fooBenchmarks[0].value, 12.34); expect(fooBenchmarks[0].delta, -0.2); expect(fooBenchmarks[1].metric, 'foo.baz'); expect(fooBenchmarks[1].value, 10); expect(fooBenchmarks[1].delta, 3.3); expect(barBenchmarks.length, 1); expect(barBenchmarks[0].metric, 'bar.foo'); expect(barBenchmarks[0].value, 1.23); expect(barBenchmarks[0].delta, isNull); expect(benchmarkResults.toJson(), data); }); test('$BenchmarkScore', () { final Map<String, Object?> data = <String, Object?>{ 'metric': 'foo', 'value': 1.234, 'delta': -0.4, }; final BenchmarkScore score = BenchmarkScore.parse(data); expect(score.metric, 'foo'); expect(score.value, 1.234); expect(score.delta, -0.4); expect(score.toJson(), data); }); }); }
packages/packages/web_benchmarks/test/src/benchmark_result_test.dart/0
{ "file_path": "packages/packages/web_benchmarks/test/src/benchmark_result_test.dart", "repo_id": "packages", "token_count": 854 }
1,145
// 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:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'webview_controller.dart'; /// Callbacks for accepting or rejecting navigation changes, and for tracking /// the progress of navigation requests. /// /// See [WebViewController.setNavigationDelegate]. /// /// ## Platform-Specific Features /// This class contains an underlying implementation provided by the current /// platform. Once a platform implementation is imported, the examples below /// can be followed to use features provided by a platform's implementation. /// /// {@macro webview_flutter.NavigationDelegate.fromPlatformCreationParams} /// /// Below is an example of accessing the platform-specific implementation for /// iOS and Android: /// /// ```dart /// final NavigationDelegate navigationDelegate = NavigationDelegate(); /// /// if (WebViewPlatform.instance is WebKitWebViewPlatform) { /// final WebKitNavigationDelegate webKitDelegate = /// navigationDelegate.platform as WebKitNavigationDelegate; /// } else if (WebViewPlatform.instance is AndroidWebViewPlatform) { /// final AndroidNavigationDelegate androidDelegate = /// navigationDelegate.platform as AndroidNavigationDelegate; /// } /// ``` class NavigationDelegate { /// Constructs a [NavigationDelegate]. /// /// {@template webview_fluttter.NavigationDelegate.constructor} /// `onUrlChange`: invoked when the underlying web view changes to a new url. /// `onHttpAuthRequest`: invoked when the web view is requesting authentication. /// {@endtemplate} NavigationDelegate({ FutureOr<NavigationDecision> Function(NavigationRequest request)? onNavigationRequest, void Function(String url)? onPageStarted, void Function(String url)? onPageFinished, void Function(int progress)? onProgress, void Function(WebResourceError error)? onWebResourceError, void Function(UrlChange change)? onUrlChange, void Function(HttpAuthRequest request)? onHttpAuthRequest, }) : this.fromPlatformCreationParams( const PlatformNavigationDelegateCreationParams(), onNavigationRequest: onNavigationRequest, onPageStarted: onPageStarted, onPageFinished: onPageFinished, onProgress: onProgress, onWebResourceError: onWebResourceError, onUrlChange: onUrlChange, onHttpAuthRequest: onHttpAuthRequest, ); /// Constructs a [NavigationDelegate] from creation params for a specific /// platform. /// /// {@macro webview_fluttter.NavigationDelegate.constructor} /// /// {@template webview_flutter.NavigationDelegate.fromPlatformCreationParams} /// Below is an example of setting platform-specific creation parameters for /// iOS and Android: /// /// ```dart /// PlatformNavigationDelegateCreationParams params = /// const PlatformNavigationDelegateCreationParams(); /// /// if (WebViewPlatform.instance is WebKitWebViewPlatform) { /// params = WebKitNavigationDelegateCreationParams /// .fromPlatformNavigationDelegateCreationParams( /// params, /// ); /// } else if (WebViewPlatform.instance is AndroidWebViewPlatform) { /// params = AndroidNavigationDelegateCreationParams /// .fromPlatformNavigationDelegateCreationParams( /// params, /// ); /// } /// /// final NavigationDelegate navigationDelegate = /// NavigationDelegate.fromPlatformCreationParams( /// params, /// ); /// ``` /// {@endtemplate} NavigationDelegate.fromPlatformCreationParams( PlatformNavigationDelegateCreationParams params, { FutureOr<NavigationDecision> Function(NavigationRequest request)? onNavigationRequest, void Function(String url)? onPageStarted, void Function(String url)? onPageFinished, void Function(int progress)? onProgress, void Function(WebResourceError error)? onWebResourceError, void Function(UrlChange change)? onUrlChange, void Function(HttpAuthRequest request)? onHttpAuthRequest, }) : this.fromPlatform( PlatformNavigationDelegate(params), onNavigationRequest: onNavigationRequest, onPageStarted: onPageStarted, onPageFinished: onPageFinished, onProgress: onProgress, onWebResourceError: onWebResourceError, onUrlChange: onUrlChange, onHttpAuthRequest: onHttpAuthRequest, ); /// Constructs a [NavigationDelegate] from a specific platform implementation. /// /// {@macro webview_fluttter.NavigationDelegate.constructor} NavigationDelegate.fromPlatform( this.platform, { this.onNavigationRequest, this.onPageStarted, this.onPageFinished, this.onProgress, this.onWebResourceError, void Function(UrlChange change)? onUrlChange, HttpAuthRequestCallback? onHttpAuthRequest, }) { if (onNavigationRequest != null) { platform.setOnNavigationRequest(onNavigationRequest!); } if (onPageStarted != null) { platform.setOnPageStarted(onPageStarted!); } if (onPageFinished != null) { platform.setOnPageFinished(onPageFinished!); } if (onProgress != null) { platform.setOnProgress(onProgress!); } if (onWebResourceError != null) { platform.setOnWebResourceError(onWebResourceError!); } if (onUrlChange != null) { platform.setOnUrlChange(onUrlChange); } if (onHttpAuthRequest != null) { platform.setOnHttpAuthRequest(onHttpAuthRequest); } } /// Implementation of [PlatformNavigationDelegate] for the current platform. final PlatformNavigationDelegate platform; /// Invoked when a decision for a navigation request is pending. /// /// When a navigation is initiated by the WebView (e.g when a user clicks a /// link) this delegate is called and has to decide how to proceed with the /// navigation. /// /// *Important*: Some platforms may also trigger this callback from calls to /// [WebViewController.loadRequest]. /// /// See [NavigationDecision]. final NavigationRequestCallback? onNavigationRequest; /// Invoked when a page has started loading. final PageEventCallback? onPageStarted; /// Invoked when a page has finished loading. final PageEventCallback? onPageFinished; /// Invoked when a page is loading to report the progress. final ProgressCallback? onProgress; /// Invoked when a resource loading error occurred. final WebResourceErrorCallback? onWebResourceError; }
packages/packages/webview_flutter/webview_flutter/lib/src/navigation_delegate.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter/lib/src/navigation_delegate.dart", "repo_id": "packages", "token_count": 2086 }
1,146
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:webview_flutter/webview_flutter.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'webview_widget_test.mocks.dart'; @GenerateMocks(<Type>[PlatformWebViewController, PlatformWebViewWidget]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('WebViewWidget', () { testWidgets('build', (WidgetTester tester) async { final MockPlatformWebViewWidget mockPlatformWebViewWidget = MockPlatformWebViewWidget(); when(mockPlatformWebViewWidget.build(any)).thenReturn(Container()); await tester.pumpWidget(WebViewWidget.fromPlatform( platform: mockPlatformWebViewWidget, )); expect(find.byType(Container), findsOneWidget); }); testWidgets( 'constructor parameters are correctly passed to creation params', (WidgetTester tester) async { WebViewPlatform.instance = TestWebViewPlatform(); final MockPlatformWebViewController mockPlatformWebViewController = MockPlatformWebViewController(); final WebViewController webViewController = WebViewController.fromPlatform( mockPlatformWebViewController, ); final WebViewWidget webViewWidget = WebViewWidget( key: GlobalKey(), controller: webViewController, layoutDirection: TextDirection.rtl, gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ Factory<OneSequenceGestureRecognizer>(() => EagerGestureRecognizer()), }, ); // The key passed to the default constructor is used by the super class // and not passed to the platform implementation. expect(webViewWidget.platform.params.key, isNull); expect( webViewWidget.platform.params.controller, webViewController.platform, ); expect(webViewWidget.platform.params.layoutDirection, TextDirection.rtl); expect( webViewWidget.platform.params.gestureRecognizers.isNotEmpty, isTrue, ); }); }); } class TestWebViewPlatform extends WebViewPlatform { @override PlatformWebViewWidget createPlatformWebViewWidget( PlatformWebViewWidgetCreationParams params, ) { return TestPlatformWebViewWidget(params); } } class TestPlatformWebViewWidget extends PlatformWebViewWidget { TestPlatformWebViewWidget(super.params) : super.implementation(); @override Widget build(BuildContext context) { throw UnimplementedError(); } }
packages/packages/webview_flutter/webview_flutter/test/webview_widget_test.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter/test/webview_widget_test.dart", "repo_id": "packages", "token_count": 1004 }
1,147
// 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.content.res.AssetManager; import androidx.annotation.NonNull; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.plugin.common.PluginRegistry; import java.io.IOException; /** Provides access to the assets registered as part of the App bundle. */ @SuppressWarnings({"deprecation", "DeprecatedIsStillUsed"}) abstract class FlutterAssetManager { final AssetManager assetManager; /** * Constructs a new instance of the {@link FlutterAssetManager}. * * @param assetManager Instance of Android's {@link AssetManager} used to access assets within the * App bundle. */ public FlutterAssetManager(AssetManager assetManager) { this.assetManager = assetManager; } /** * Gets the relative file path to the Flutter asset with the given name, including the file's * extension, e.g., "myImage.jpg". * * <p>The returned file path is relative to the Android app's standard asset's directory. * Therefore, the returned path is appropriate to pass to Android's AssetManager, but the path is * not appropriate to load as an absolute path. */ abstract String getAssetFilePathByName(String name); /** * Returns a String array of all the assets at the given path. * * @param path A relative path within the assets, i.e., "docs/home.html". This value cannot be * null. * @return String[] Array of strings, one for each asset. These file names are relative to 'path'. * This value may be null. * @throws IOException Throws an IOException in case I/O operations were interrupted. */ public String[] list(@NonNull String path) throws IOException { return assetManager.list(path); } /** * Provides access to assets using the {@link PluginRegistry.Registrar} for looking up file paths * to Flutter assets. * * @deprecated The {@link RegistrarFlutterAssetManager} is for Flutter's v1 embedding. For * instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration */ @Deprecated static class RegistrarFlutterAssetManager extends FlutterAssetManager { final PluginRegistry.Registrar registrar; /** * Constructs a new instance of the {@link RegistrarFlutterAssetManager}. * * @param assetManager Instance of Android's {@link AssetManager} used to access assets within * the App bundle. * @param registrar Instance of {@link io.flutter.plugin.common.PluginRegistry.Registrar} used * to look up file paths to assets registered by Flutter. */ RegistrarFlutterAssetManager(AssetManager assetManager, PluginRegistry.Registrar registrar) { super(assetManager); this.registrar = registrar; } @Override public String getAssetFilePathByName(String name) { return registrar.lookupKeyForAsset(name); } } /** * Provides access to assets using the {@link FlutterPlugin.FlutterAssets} for looking up file * paths to Flutter assets. */ static class PluginBindingFlutterAssetManager extends FlutterAssetManager { final FlutterPlugin.FlutterAssets flutterAssets; /** * Constructs a new instance of the {@link PluginBindingFlutterAssetManager}. * * @param assetManager Instance of Android's {@link AssetManager} used to access assets within * the App bundle. * @param flutterAssets Instance of {@link * io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterAssets} used to look up file * paths to assets registered by Flutter. */ PluginBindingFlutterAssetManager( AssetManager assetManager, FlutterPlugin.FlutterAssets flutterAssets) { super(assetManager); this.flutterAssets = flutterAssets; } @Override public String getAssetFilePathByName(String name) { return flutterAssets.getAssetFilePathByName(name); } } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterAssetManager.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterAssetManager.java", "repo_id": "packages", "token_count": 1317 }
1,148
// 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.view.View; import android.webkit.ConsoleMessage; import android.webkit.GeolocationPermissions; import android.webkit.PermissionRequest; import android.webkit.WebChromeClient; import android.webkit.WebView; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebChromeClientFlutterApi; import java.util.List; import java.util.Objects; /** * Flutter Api implementation for {@link WebChromeClient}. * * <p>Passes arguments of callbacks methods from a {@link WebChromeClient} to Dart. */ public class WebChromeClientFlutterApiImpl extends WebChromeClientFlutterApi { private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; private final WebViewFlutterApiImpl webViewFlutterApi; private static GeneratedAndroidWebView.ConsoleMessageLevel toConsoleMessageLevel( ConsoleMessage.MessageLevel level) { switch (level) { case TIP: return GeneratedAndroidWebView.ConsoleMessageLevel.TIP; case LOG: return GeneratedAndroidWebView.ConsoleMessageLevel.LOG; case WARNING: return GeneratedAndroidWebView.ConsoleMessageLevel.WARNING; case ERROR: return GeneratedAndroidWebView.ConsoleMessageLevel.ERROR; case DEBUG: return GeneratedAndroidWebView.ConsoleMessageLevel.DEBUG; } return GeneratedAndroidWebView.ConsoleMessageLevel.UNKNOWN; } /** * Creates a Flutter api that sends messages to Dart. * * @param binaryMessenger handles sending messages to Dart * @param instanceManager maintains instances stored to communicate with Dart objects */ public WebChromeClientFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { super(binaryMessenger); this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; webViewFlutterApi = new WebViewFlutterApiImpl(binaryMessenger, instanceManager); } /** Passes arguments from {@link WebChromeClient#onProgressChanged} to Dart. */ public void onProgressChanged( @NonNull WebChromeClient webChromeClient, @NonNull WebView webView, @NonNull Long progress, @NonNull Reply<Void> callback) { webViewFlutterApi.create(webView, reply -> {}); final Long webViewIdentifier = Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(webView)); super.onProgressChanged( getIdentifierForClient(webChromeClient), webViewIdentifier, progress, callback); } /** Passes arguments from {@link WebChromeClient#onShowFileChooser} to Dart. */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void onShowFileChooser( @NonNull WebChromeClient webChromeClient, @NonNull WebView webView, @NonNull WebChromeClient.FileChooserParams fileChooserParams, @NonNull Reply<List<String>> callback) { webViewFlutterApi.create(webView, reply -> {}); new FileChooserParamsFlutterApiImpl(binaryMessenger, instanceManager) .create(fileChooserParams, reply -> {}); onShowFileChooser( Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(webChromeClient)), Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(webView)), Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(fileChooserParams)), callback); } /** Passes arguments from {@link WebChromeClient#onGeolocationPermissionsShowPrompt} to Dart. */ public void onGeolocationPermissionsShowPrompt( @NonNull WebChromeClient webChromeClient, @NonNull String origin, @NonNull GeolocationPermissions.Callback callback, @NonNull WebChromeClientFlutterApi.Reply<Void> replyCallback) { new GeolocationPermissionsCallbackFlutterApiImpl(binaryMessenger, instanceManager) .create(callback, reply -> {}); onGeolocationPermissionsShowPrompt( Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(webChromeClient)), Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(callback)), origin, replyCallback); } /** * Sends a message to Dart to call `WebChromeClient.onGeolocationPermissionsHidePrompt` on the * Dart object representing `instance`. */ public void onGeolocationPermissionsHidePrompt( @NonNull WebChromeClient instance, @NonNull WebChromeClientFlutterApi.Reply<Void> callback) { super.onGeolocationPermissionsHidePrompt( Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(instance)), callback); } /** * Sends a message to Dart to call `WebChromeClient.onPermissionRequest` on the Dart object * representing `instance`. */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void onPermissionRequest( @NonNull WebChromeClient instance, @NonNull PermissionRequest request, @NonNull WebChromeClientFlutterApi.Reply<Void> callback) { new PermissionRequestFlutterApiImpl(binaryMessenger, instanceManager) .create(request, request.getResources(), reply -> {}); super.onPermissionRequest( Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(instance)), Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(request)), callback); } /** * Sends a message to Dart to call `WebChromeClient.onShowCustomView` on the Dart object * representing `instance`. */ public void onShowCustomView( @NonNull WebChromeClient instance, @NonNull View view, @NonNull WebChromeClient.CustomViewCallback customViewCallback, @NonNull WebChromeClientFlutterApi.Reply<Void> callback) { new ViewFlutterApiImpl(binaryMessenger, instanceManager).create(view, reply -> {}); new CustomViewCallbackFlutterApiImpl(binaryMessenger, instanceManager) .create(customViewCallback, reply -> {}); onShowCustomView( Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(instance)), Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(view)), Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(customViewCallback)), callback); } /** * Sends a message to Dart to call `WebChromeClient.onHideCustomView` on the Dart object * representing `instance`. */ public void onHideCustomView( @NonNull WebChromeClient instance, @NonNull WebChromeClientFlutterApi.Reply<Void> callback) { super.onHideCustomView( Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(instance)), callback); } /** * Sends a message to Dart to call `WebChromeClient.onConsoleMessage` on the Dart object * representing `instance`. */ public void onConsoleMessage( @NonNull WebChromeClient instance, @NonNull ConsoleMessage message, @NonNull Reply<Void> callback) { super.onConsoleMessage( Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(instance)), new GeneratedAndroidWebView.ConsoleMessage.Builder() .setLineNumber((long) message.lineNumber()) .setMessage(message.message()) .setLevel(toConsoleMessageLevel(message.messageLevel())) .setSourceId(message.sourceId()) .build(), callback); } /** * Sends a message to Dart to call `WebChromeClient.onJsAlert` on the Dart object representing * `instance`. */ public void onJsAlert( @NonNull WebChromeClient instance, @NonNull String url, @NonNull String message, @NonNull WebChromeClientFlutterApi.Reply<Void> callback) { super.onJsAlert( Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(instance)), url, message, callback); } /** * Sends a message to Dart to call `WebChromeClient.onJsConfirm` on the Dart object representing * `instance`. */ public void onJsConfirm( @NonNull WebChromeClient instance, @NonNull String url, @NonNull String message, @NonNull WebChromeClientFlutterApi.Reply<Boolean> callback) { super.onJsConfirm( Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(instance)), url, message, callback); } /** * Sends a message to Dart to call `WebChromeClient.onJsPrompt` on the Dart object representing * `instance`. */ public void onJsPrompt( @NonNull WebChromeClient instance, @NonNull String url, @NonNull String message, @NonNull String defaultValue, @NonNull WebChromeClientFlutterApi.Reply<String> callback) { super.onJsPrompt( Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(instance)), url, message, defaultValue, callback); } private long getIdentifierForClient(WebChromeClient webChromeClient) { final Long identifier = instanceManager.getIdentifierForStrongReference(webChromeClient); if (identifier == null) { throw new IllegalStateException("Could not find identifier for WebChromeClient."); } return identifier; } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebChromeClientFlutterApiImpl.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebChromeClientFlutterApiImpl.java", "repo_id": "packages", "token_count": 3219 }
1,149
// 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.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import android.webkit.GeolocationPermissions; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.GeolocationPermissionsCallbackFlutterApi; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; public class GeolocationPermissionsCallbackTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public GeolocationPermissions.Callback mockGeolocationPermissionsCallback; @Mock public BinaryMessenger mockBinaryMessenger; @Mock public GeolocationPermissionsCallbackFlutterApi mockFlutterApi; InstanceManager instanceManager; @Before public void setUp() { instanceManager = InstanceManager.create(identifier -> {}); } @After public void tearDown() { instanceManager.stopFinalizationListener(); } @Test public void invoke() { final String origin = "testString"; final boolean allow = true; final boolean retain = true; final long instanceIdentifier = 0; instanceManager.addDartCreatedInstance(mockGeolocationPermissionsCallback, instanceIdentifier); final GeolocationPermissionsCallbackHostApiImpl hostApi = new GeolocationPermissionsCallbackHostApiImpl(mockBinaryMessenger, instanceManager); hostApi.invoke(instanceIdentifier, origin, allow, retain); verify(mockGeolocationPermissionsCallback).invoke(origin, allow, retain); } @Test public void flutterApiCreate() { final GeolocationPermissionsCallbackFlutterApiImpl flutterApi = new GeolocationPermissionsCallbackFlutterApiImpl(mockBinaryMessenger, instanceManager); flutterApi.setApi(mockFlutterApi); flutterApi.create(mockGeolocationPermissionsCallback, reply -> {}); final long instanceIdentifier = Objects.requireNonNull( instanceManager.getIdentifierForStrongReference(mockGeolocationPermissionsCallback)); verify(mockFlutterApi).create(eq(instanceIdentifier), any()); } }
packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/GeolocationPermissionsCallbackTest.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/GeolocationPermissionsCallbackTest.java", "repo_id": "packages", "token_count": 781 }
1,150
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/webview_flutter/webview_flutter_android/example/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/example/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 45 }
1,151
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; // ignore: implementation_imports import 'package:webview_flutter_android/src/webview_flutter_android_legacy.dart'; // ignore: implementation_imports import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart'; import 'navigation_decision.dart'; import 'navigation_request.dart'; /// Optional callback invoked when a web view is first created. [controller] is /// the [WebViewController] for the created web view. typedef WebViewCreatedCallback = void Function(WebViewController controller); /// Decides how to handle a specific navigation request. /// /// The returned [NavigationDecision] determines how the navigation described by /// `navigation` should be handled. /// /// See also: [WebView.navigationDelegate]. typedef NavigationDelegate = FutureOr<NavigationDecision> Function( NavigationRequest navigation); /// Signature for when a [WebView] has started loading a page. typedef PageStartedCallback = void Function(String url); /// Signature for when a [WebView] has finished loading a page. typedef PageFinishedCallback = void Function(String url); /// Signature for when a [WebView] is loading a page. typedef PageLoadingCallback = void Function(int progress); /// Signature for when a [WebView] has failed to load a resource. typedef WebResourceErrorCallback = void Function(WebResourceError error); /// A web view widget for showing html content. /// /// The [WebView] widget wraps around the [AndroidWebView] or /// [SurfaceAndroidWebView] classes and acts like a facade which makes it easier /// to inject a [AndroidWebView] or [SurfaceAndroidWebView] control into the /// widget tree. /// /// The [WebView] widget is controlled using the [WebViewController] which is /// provided through the `onWebViewCreated` callback. /// /// In this example project it's main purpose is to facilitate integration /// testing of the `webview_flutter_android` package. class WebView extends StatefulWidget { /// Creates a new web view. /// /// The web view can be controlled using a `WebViewController` that is passed to the /// `onWebViewCreated` callback once the web view is created. /// /// The `javascriptMode` and `autoMediaPlaybackPolicy` parameters must not be null. const WebView({ super.key, this.onWebViewCreated, this.initialUrl, this.initialCookies = const <WebViewCookie>[], this.javascriptMode = JavascriptMode.disabled, this.javascriptChannels, this.navigationDelegate, this.gestureRecognizers, this.onPageStarted, this.onPageFinished, this.onProgress, this.onWebResourceError, this.debuggingEnabled = false, this.gestureNavigationEnabled = false, this.userAgent, this.zoomEnabled = true, this.initialMediaPlaybackPolicy = AutoMediaPlaybackPolicy.require_user_action_for_all_media_types, this.allowsInlineMediaPlayback = false, this.backgroundColor, }); /// The WebView platform that's used by this WebView. /// /// The default value is [AndroidWebView]. static WebViewPlatform platform = AndroidWebView(); /// If not null invoked once the web view is created. final WebViewCreatedCallback? onWebViewCreated; /// Which gestures should be consumed by the web view. /// /// It is possible for other gesture recognizers to be competing with the web view on pointer /// events, e.g if the web view is inside a [ListView] the [ListView] will want to handle /// vertical drags. The web view will claim gestures that are recognized by any of the /// recognizers on this list. /// /// When this set is empty or null, the web view will only handle pointer events for gestures that /// were not claimed by any other gesture recognizer. final Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers; /// The initial URL to load. final String? initialUrl; /// The initial cookies to set. final List<WebViewCookie> initialCookies; /// Whether JavaScript execution is enabled. final JavascriptMode javascriptMode; /// The set of [JavascriptChannel]s available to JavaScript code running in the web view. /// /// For each [JavascriptChannel] in the set, a channel object is made available for the /// JavaScript code in a window property named [JavascriptChannel.name]. /// The JavaScript code can then call `postMessage` on that object to send a message that will be /// passed to [JavascriptChannel.onMessageReceived]. /// /// For example for the following [JavascriptChannel]: /// /// ```dart /// JavascriptChannel(name: 'Print', onMessageReceived: (JavascriptMessage message) { print(message.message); }); /// ``` /// /// JavaScript code can call: /// /// ```javascript /// Print.postMessage('Hello'); /// ``` /// /// To asynchronously invoke the message handler which will print the message to standard output. /// /// Adding a new JavaScript channel only takes affect after the next page is loaded. /// /// Set values must not be null. A [JavascriptChannel.name] cannot be the same for multiple /// channels in the list. /// /// A null value is equivalent to an empty set. final Set<JavascriptChannel>? javascriptChannels; /// A delegate function that decides how to handle navigation actions. /// /// When a navigation is initiated by the WebView (e.g when a user clicks a link) /// this delegate is called and has to decide how to proceed with the navigation. /// /// See [NavigationDecision] for possible decisions the delegate can take. /// /// When null all navigation actions are allowed. /// /// Caveats on Android: /// /// * Navigation actions targeted to the main frame can be intercepted, /// navigation actions targeted to subframes are allowed regardless of the value /// returned by this delegate. /// * Setting a navigationDelegate makes the WebView treat all navigations as if they were /// triggered by a user gesture, this disables some of Chromium's security mechanisms. /// A navigationDelegate should only be set when loading trusted content. /// * On Android WebView versions earlier than 67(most devices running at least Android L+ should have /// a later version): /// * When a navigationDelegate is set pages with frames are not properly handled by the /// webview, and frames will be opened in the main frame. /// * When a navigationDelegate is set HTTP requests do not include the HTTP referer header. final NavigationDelegate? navigationDelegate; /// Controls whether inline playback of HTML5 videos is allowed on iOS. /// /// This field is ignored on Android because Android allows it by default. /// /// By default `allowsInlineMediaPlayback` is false. final bool allowsInlineMediaPlayback; /// Invoked when a page starts loading. final PageStartedCallback? onPageStarted; /// Invoked when a page has finished loading. /// /// This is invoked only for the main frame. /// /// When [onPageFinished] is invoked on Android, the page being rendered may /// not be updated yet. /// /// When invoked on iOS or Android, any JavaScript code that is embedded /// directly in the HTML has been loaded and code injected with /// [WebViewController.evaluateJavascript] can assume this. final PageFinishedCallback? onPageFinished; /// Invoked when a page is loading. final PageLoadingCallback? onProgress; /// Invoked when a web resource has failed to load. /// /// This callback is only called for the main page. final WebResourceErrorCallback? onWebResourceError; /// Controls whether WebView debugging is enabled. /// /// Setting this to true enables [WebView debugging on Android](https://developers.google.com/web/tools/chrome-devtools/remote-debugging/). /// /// WebView debugging is enabled by default in dev builds on iOS. /// /// To debug WebViews on iOS: /// - Enable developer options (Open Safari, go to Preferences -> Advanced and make sure "Show Develop Menu in Menubar" is on.) /// - From the Menu-bar (of Safari) select Develop -> iPhone Simulator -> <your webview page> /// /// By default `debuggingEnabled` is false. final bool debuggingEnabled; /// A Boolean value indicating whether horizontal swipe gestures will trigger back-forward list navigations. /// /// This only works on iOS. /// /// By default `gestureNavigationEnabled` is false. final bool gestureNavigationEnabled; /// A Boolean value indicating whether the WebView should support zooming using its on-screen zoom controls and gestures. /// /// By default 'zoomEnabled' is true final bool zoomEnabled; /// The value used for the HTTP User-Agent: request header. /// /// When null the platform's webview default is used for the User-Agent header. /// /// When the [WebView] is rebuilt with a different `userAgent`, the page reloads and the request uses the new User Agent. /// /// When [WebViewController.goBack] is called after changing `userAgent` the previous `userAgent` value is used until the page is reloaded. /// /// This field is ignored on iOS versions prior to 9 as the platform does not support a custom /// user agent. /// /// By default `userAgent` is null. final String? userAgent; /// Which restrictions apply on automatic media playback. /// /// This initial value is applied to the platform's webview upon creation. Any following /// changes to this parameter are ignored (as long as the state of the [WebView] is preserved). /// /// The default policy is [AutoMediaPlaybackPolicy.require_user_action_for_all_media_types]. final AutoMediaPlaybackPolicy initialMediaPlaybackPolicy; /// The background color of the [WebView]. /// /// When `null` the platform's webview default background color is used. By /// default [backgroundColor] is `null`. final Color? backgroundColor; @override State<WebView> createState() => _WebViewState(); } class _WebViewState extends State<WebView> { final Completer<WebViewController> _controller = Completer<WebViewController>(); late final JavascriptChannelRegistry _javascriptChannelRegistry; late final _PlatformCallbacksHandler _platformCallbacksHandler; @override void initState() { super.initState(); _platformCallbacksHandler = _PlatformCallbacksHandler(widget); _javascriptChannelRegistry = JavascriptChannelRegistry(widget.javascriptChannels); } @override void didUpdateWidget(WebView oldWidget) { super.didUpdateWidget(oldWidget); _controller.future.then((WebViewController controller) { controller.updateWidget(widget); }); } @override Widget build(BuildContext context) { return WebView.platform.build( context: context, onWebViewPlatformCreated: (WebViewPlatformController? webViewPlatformController) { final WebViewController controller = WebViewController( widget, webViewPlatformController!, _javascriptChannelRegistry, ); _controller.complete(controller); if (widget.onWebViewCreated != null) { widget.onWebViewCreated!(controller); } }, webViewPlatformCallbacksHandler: _platformCallbacksHandler, creationParams: CreationParams( initialUrl: widget.initialUrl, webSettings: _webSettingsFromWidget(widget), javascriptChannelNames: _javascriptChannelRegistry.channels.keys.toSet(), autoMediaPlaybackPolicy: widget.initialMediaPlaybackPolicy, userAgent: widget.userAgent, backgroundColor: widget.backgroundColor, cookies: widget.initialCookies, ), javascriptChannelRegistry: _javascriptChannelRegistry, ); } } class _PlatformCallbacksHandler implements WebViewPlatformCallbacksHandler { _PlatformCallbacksHandler(this._webView); final WebView _webView; @override FutureOr<bool> onNavigationRequest({ required String url, required bool isForMainFrame, }) async { if (url.startsWith('https://www.youtube.com/')) { debugPrint('blocking navigation to $url'); return false; } debugPrint('allowing navigation to $url'); return true; } @override void onPageStarted(String url) { if (_webView.onPageStarted != null) { _webView.onPageStarted!(url); } } @override void onPageFinished(String url) { if (_webView.onPageFinished != null) { _webView.onPageFinished!(url); } } @override void onProgress(int progress) { if (_webView.onProgress != null) { _webView.onProgress!(progress); } } @override void onWebResourceError(WebResourceError error) { if (_webView.onWebResourceError != null) { _webView.onWebResourceError!(error); } } } /// Controls a [WebView]. /// /// A [WebViewController] instance can be obtained by setting the [WebView.onWebViewCreated] /// callback for a [WebView] widget. class WebViewController { /// Creates a [WebViewController] which can be used to control the provided /// [WebView] widget. WebViewController( this._widget, this._webViewPlatformController, this._javascriptChannelRegistry, ) { _settings = _webSettingsFromWidget(_widget); } final JavascriptChannelRegistry _javascriptChannelRegistry; final WebViewPlatformController _webViewPlatformController; late WebSettings _settings; WebView _widget; /// Loads the file located on the specified [absoluteFilePath]. /// /// The [absoluteFilePath] parameter should contain the absolute path to the /// file as it is stored on the device. For example: /// `/Users/username/Documents/www/index.html`. /// /// Throws an ArgumentError if the [absoluteFilePath] does not exist. Future<void> loadFile(String absoluteFilePath) { return _webViewPlatformController.loadFile(absoluteFilePath); } /// Loads the Flutter asset specified in the pubspec.yaml file. /// /// Throws an ArgumentError if [key] is not part of the specified assets /// in the pubspec.yaml file. Future<void> loadFlutterAsset(String key) { return _webViewPlatformController.loadFlutterAsset(key); } /// Loads the supplied HTML string. /// /// The [baseUrl] parameter is used when resolving relative URLs within the /// HTML string. Future<void> loadHtmlString(String html, {String? baseUrl}) { return _webViewPlatformController.loadHtmlString( html, baseUrl: baseUrl, ); } /// Loads the specified URL. /// /// If `headers` is not null and the URL is an HTTP URL, the key value paris in `headers` will /// be added as key value pairs of HTTP headers for the request. /// /// `url` must not be null. /// /// Throws an ArgumentError if `url` is not a valid URL string. Future<void> loadUrl( String url, { Map<String, String>? headers, }) async { _validateUrlString(url); return _webViewPlatformController.loadUrl(url, headers); } /// Loads a page by making the specified request. Future<void> loadRequest(WebViewRequest request) async { return _webViewPlatformController.loadRequest(request); } /// Accessor to the current URL that the WebView is displaying. /// /// If [WebView.initialUrl] was never specified, returns `null`. /// Note that this operation is asynchronous, and it is possible that the /// current URL changes again by the time this function returns (in other /// words, by the time this future completes, the WebView may be displaying a /// different URL). Future<String?> currentUrl() { return _webViewPlatformController.currentUrl(); } /// Checks whether there's a back history item. /// /// Note that this operation is asynchronous, and it is possible that the "canGoBack" state has /// changed by the time the future completed. Future<bool> canGoBack() { return _webViewPlatformController.canGoBack(); } /// Checks whether there's a forward history item. /// /// Note that this operation is asynchronous, and it is possible that the "canGoForward" state has /// changed by the time the future completed. Future<bool> canGoForward() { return _webViewPlatformController.canGoForward(); } /// Goes back in the history of this WebView. /// /// If there is no back history item this is a no-op. Future<void> goBack() { return _webViewPlatformController.goBack(); } /// Goes forward in the history of this WebView. /// /// If there is no forward history item this is a no-op. Future<void> goForward() { return _webViewPlatformController.goForward(); } /// Reloads the current URL. Future<void> reload() { return _webViewPlatformController.reload(); } /// Clears all caches used by the [WebView]. /// /// The following caches are cleared: /// 1. Browser HTTP Cache. /// 2. [Cache API](https://developers.google.com/web/fundamentals/instant-and-offline/web-storage/cache-api) caches. /// These are not yet supported in iOS WkWebView. Service workers tend to use this cache. /// 3. Application cache. /// 4. Local Storage. /// /// Note: Calling this method also triggers a reload. Future<void> clearCache() async { await _webViewPlatformController.clearCache(); return reload(); } /// Update the widget managed by the [WebViewController]. Future<void> updateWidget(WebView widget) async { _widget = widget; await _updateSettings(_webSettingsFromWidget(widget)); await _updateJavascriptChannels( _javascriptChannelRegistry.channels.values.toSet()); } Future<void> _updateSettings(WebSettings newSettings) { final WebSettings update = _clearUnchangedWebSettings(_settings, newSettings); _settings = newSettings; return _webViewPlatformController.updateSettings(update); } Future<void> _updateJavascriptChannels( Set<JavascriptChannel>? newChannels) async { final Set<String> currentChannels = _javascriptChannelRegistry.channels.keys.toSet(); final Set<String> newChannelNames = _extractChannelNames(newChannels); final Set<String> channelsToAdd = newChannelNames.difference(currentChannels); final Set<String> channelsToRemove = currentChannels.difference(newChannelNames); if (channelsToRemove.isNotEmpty) { await _webViewPlatformController .removeJavascriptChannels(channelsToRemove); } if (channelsToAdd.isNotEmpty) { await _webViewPlatformController.addJavascriptChannels(channelsToAdd); } _javascriptChannelRegistry.updateJavascriptChannelsFromSet(newChannels); } @visibleForTesting // ignore: public_member_api_docs Future<String> evaluateJavascript(String javascriptString) { if (_settings.javascriptMode == JavascriptMode.disabled) { return Future<String>.error(FlutterError( 'JavaScript mode must be enabled/unrestricted when calling evaluateJavascript.')); } return _webViewPlatformController.evaluateJavascript(javascriptString); } /// Runs the given JavaScript in the context of the current page. /// If you are looking for the result, use [runJavascriptReturningResult] instead. /// The Future completes with an error if a JavaScript error occurred. /// /// When running JavaScript in a [WebView], it is best practice to wait for // the [WebView.onPageFinished] callback. This guarantees all the JavaScript // embedded in the main frame HTML has been loaded. Future<void> runJavascript(String javaScriptString) { if (_settings.javascriptMode == JavascriptMode.disabled) { return Future<void>.error(FlutterError( 'Javascript mode must be enabled/unrestricted when calling runJavascript.')); } return _webViewPlatformController.runJavascript(javaScriptString); } /// Runs the given JavaScript in the context of the current page, and returns the result. /// /// Returns the evaluation result as a JSON formatted string. /// The Future completes with an error if a JavaScript error occurred. /// /// When evaluating JavaScript in a [WebView], it is best practice to wait for /// the [WebView.onPageFinished] callback. This guarantees all the JavaScript /// embedded in the main frame HTML has been loaded. Future<String> runJavascriptReturningResult(String javaScriptString) { if (_settings.javascriptMode == JavascriptMode.disabled) { return Future<String>.error(FlutterError( 'Javascript mode must be enabled/unrestricted when calling runJavascriptReturningResult.')); } return _webViewPlatformController .runJavascriptReturningResult(javaScriptString); } /// Returns the title of the currently loaded page. Future<String?> getTitle() { return _webViewPlatformController.getTitle(); } /// Sets the WebView's content scroll position. /// /// The parameters `x` and `y` specify the scroll position in WebView pixels. Future<void> scrollTo(int x, int y) { return _webViewPlatformController.scrollTo(x, y); } /// Move the scrolled position of this view. /// /// The parameters `x` and `y` specify the amount of WebView pixels to scroll by horizontally and vertically respectively. Future<void> scrollBy(int x, int y) { return _webViewPlatformController.scrollBy(x, y); } /// Return the horizontal scroll position, in WebView pixels, of this view. /// /// Scroll position is measured from left. Future<int> getScrollX() { return _webViewPlatformController.getScrollX(); } /// Return the vertical scroll position, in WebView pixels, of this view. /// /// Scroll position is measured from top. Future<int> getScrollY() { return _webViewPlatformController.getScrollY(); } // This method assumes that no fields in `currentValue` are null. WebSettings _clearUnchangedWebSettings( WebSettings currentValue, WebSettings newValue) { assert(currentValue.javascriptMode != null); assert(currentValue.hasNavigationDelegate != null); assert(currentValue.hasProgressTracking != null); assert(currentValue.debuggingEnabled != null); assert(newValue.javascriptMode != null); assert(newValue.hasNavigationDelegate != null); assert(newValue.debuggingEnabled != null); assert(newValue.zoomEnabled != null); JavascriptMode? javascriptMode; bool? hasNavigationDelegate; bool? hasProgressTracking; bool? debuggingEnabled; WebSetting<String?> userAgent = const WebSetting<String?>.absent(); bool? zoomEnabled; if (currentValue.javascriptMode != newValue.javascriptMode) { javascriptMode = newValue.javascriptMode; } if (currentValue.hasNavigationDelegate != newValue.hasNavigationDelegate) { hasNavigationDelegate = newValue.hasNavigationDelegate; } if (currentValue.hasProgressTracking != newValue.hasProgressTracking) { hasProgressTracking = newValue.hasProgressTracking; } if (currentValue.debuggingEnabled != newValue.debuggingEnabled) { debuggingEnabled = newValue.debuggingEnabled; } if (currentValue.userAgent != newValue.userAgent) { userAgent = newValue.userAgent; } if (currentValue.zoomEnabled != newValue.zoomEnabled) { zoomEnabled = newValue.zoomEnabled; } return WebSettings( javascriptMode: javascriptMode, hasNavigationDelegate: hasNavigationDelegate, hasProgressTracking: hasProgressTracking, debuggingEnabled: debuggingEnabled, userAgent: userAgent, zoomEnabled: zoomEnabled, ); } Set<String> _extractChannelNames(Set<JavascriptChannel>? channels) { final Set<String> channelNames = channels == null ? <String>{} : channels.map((JavascriptChannel channel) => channel.name).toSet(); return channelNames; } // Throws an ArgumentError if `url` is not a valid URL string. void _validateUrlString(String url) { try { final Uri uri = Uri.parse(url); if (uri.scheme.isEmpty) { throw ArgumentError('Missing scheme in URL string: "$url"'); } } on FormatException catch (e) { throw ArgumentError(e); } } } WebSettings _webSettingsFromWidget(WebView widget) { return WebSettings( javascriptMode: widget.javascriptMode, hasNavigationDelegate: widget.navigationDelegate != null, hasProgressTracking: widget.onProgress != null, debuggingEnabled: widget.debuggingEnabled, gestureNavigationEnabled: widget.gestureNavigationEnabled, allowsInlineMediaPlayback: widget.allowsInlineMediaPlayback, userAgent: WebSetting<String?>.of(widget.userAgent), zoomEnabled: widget.zoomEnabled, ); } /// App-facing cookie manager that exposes the correct platform implementation. class WebViewCookieManager extends WebViewCookieManagerPlatform { WebViewCookieManager._(); /// Returns an instance of the cookie manager for the current platform. static WebViewCookieManagerPlatform get instance { if (WebViewCookieManagerPlatform.instance == null) { if (Platform.isAndroid) { WebViewCookieManagerPlatform.instance = WebViewAndroidCookieManager(); } else { throw AssertionError( 'This platform is currently unsupported for webview_flutter_android.'); } } return WebViewCookieManagerPlatform.instance!; } }
packages/packages/webview_flutter/webview_flutter_android/example/lib/legacy/web_view.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/example/lib/legacy/web_view.dart", "repo_id": "packages", "token_count": 7601 }
1,152
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; /// Proxy that provides access to the platform views service. /// /// This service allows creating and controlling platform-specific views. @immutable class PlatformViewsServiceProxy { /// Constructs a [PlatformViewsServiceProxy]. const PlatformViewsServiceProxy(); /// Proxy method for [PlatformViewsService.initExpensiveAndroidView]. ExpensiveAndroidViewController initExpensiveAndroidView({ required int id, required String viewType, required TextDirection layoutDirection, dynamic creationParams, MessageCodec<dynamic>? creationParamsCodec, VoidCallback? onFocus, }) { return PlatformViewsService.initExpensiveAndroidView( id: id, viewType: viewType, layoutDirection: layoutDirection, creationParams: creationParams, creationParamsCodec: creationParamsCodec, onFocus: onFocus, ); } /// Proxy method for [PlatformViewsService.initSurfaceAndroidView]. SurfaceAndroidViewController initSurfaceAndroidView({ required int id, required String viewType, required TextDirection layoutDirection, dynamic creationParams, MessageCodec<dynamic>? creationParamsCodec, VoidCallback? onFocus, }) { return PlatformViewsService.initSurfaceAndroidView( id: id, viewType: viewType, layoutDirection: layoutDirection, creationParams: creationParams, creationParamsCodec: creationParamsCodec, onFocus: onFocus, ); } }
packages/packages/webview_flutter/webview_flutter_android/lib/src/platform_views_service_proxy.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/lib/src/platform_views_service_proxy.dart", "repo_id": "packages", "token_count": 541 }
1,153
// 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/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:webview_flutter_android/src/legacy/webview_surface_android.dart'; import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('SurfaceAndroidWebView', () { late List<MethodCall> log; setUpAll(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler( SystemChannels.platform_views, (MethodCall call) async { log.add(call); if (call.method == 'resize') { final Map<String, Object?> arguments = (call.arguments as Map<Object?, Object?>) .cast<String, Object?>(); return <String, Object?>{ 'width': arguments['width'], 'height': arguments['height'], }; } return null; }, ); }); tearDownAll(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform_views, null); }); setUp(() { log = <MethodCall>[]; }); testWidgets( 'uses hybrid composition when background color is not 100% opaque', (WidgetTester tester) async { await tester.pumpWidget(Builder(builder: (BuildContext context) { return SurfaceAndroidWebView().build( context: context, creationParams: CreationParams( backgroundColor: Colors.transparent, webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: false, )), javascriptChannelRegistry: JavascriptChannelRegistry(null), webViewPlatformCallbacksHandler: TestWebViewPlatformCallbacksHandler(), ); })); await tester.pumpAndSettle(); final MethodCall createMethodCall = log[0]; expect(createMethodCall.method, 'create'); expect(createMethodCall.arguments, containsPair('hybrid', true)); }); testWidgets('default text direction is ltr', (WidgetTester tester) async { await tester.pumpWidget(Builder(builder: (BuildContext context) { return SurfaceAndroidWebView().build( context: context, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: false, )), javascriptChannelRegistry: JavascriptChannelRegistry(null), webViewPlatformCallbacksHandler: TestWebViewPlatformCallbacksHandler(), ); })); await tester.pumpAndSettle(); final MethodCall createMethodCall = log[0]; expect(createMethodCall.method, 'create'); expect( createMethodCall.arguments, containsPair( 'direction', AndroidViewController.kAndroidLayoutDirectionLtr, ), ); }); }); } class TestWebViewPlatformCallbacksHandler implements WebViewPlatformCallbacksHandler { @override FutureOr<bool> onNavigationRequest({ required String url, required bool isForMainFrame, }) { throw UnimplementedError(); } @override void onPageFinished(String url) {} @override void onPageStarted(String url) {} @override void onProgress(int progress) {} @override void onWebResourceError(WebResourceError error) {} }
packages/packages/webview_flutter/webview_flutter_android/test/legacy/surface_android_test.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/test/legacy/surface_android_test.dart", "repo_id": "packages", "token_count": 1545 }
1,154
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Specifies possible restrictions on automatic media playback. /// /// This is typically used in [WebView.initialMediaPlaybackPolicy]. // The method channel implementation is marshalling this enum to the value's index, so the order // is important. enum AutoMediaPlaybackPolicy { /// Starting any kind of media playback requires a user action. /// /// For example: JavaScript code cannot start playing media unless the code was executed /// as a result of a user action (like a touch event). require_user_action_for_all_media_types, /// Starting any kind of media playback is always allowed. /// /// For example: JavaScript code that's triggered when the page is loaded can start playing /// video or audio. always_allow, }
packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/auto_media_playback_policy.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/auto_media_playback_policy.dart", "repo_id": "packages", "token_count": 221 }
1,155
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'web_resource_request.dart'; import 'web_resource_response.dart'; /// Error returned in `PlatformNavigationDelegate.setOnHttpError` when an HTTP /// response error has been received. /// /// Platform specific implementations can add additional fields by extending /// this class. /// /// This example demonstrates how to extend the [HttpResponseError] to /// provide additional platform specific parameters. /// /// When extending [HttpResponseError] additional parameters should always /// accept `null` or have a default value to prevent breaking changes. /// /// ```dart /// class IOSHttpResponseError extends HttpResponseError { /// IOSHttpResponseError._(HttpResponseError error, {required this.domain}) /// : super( /// statusCode: error.statusCode, /// ); /// /// factory IOSHttpResponseError.fromHttpResponseError( /// HttpResponseError error, { /// required String? domain, /// }) { /// return IOSHttpResponseError._(error, domain: domain); /// } /// /// final String? domain; /// } /// ``` @immutable class HttpResponseError { /// Used by the platform implementation to create a new [HttpResponseError]. const HttpResponseError({ this.request, this.response, }); /// The associated request. final WebResourceRequest? request; /// The associated response. final WebResourceResponse? response; }
packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/http_response_error.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/http_response_error.dart", "repo_id": "packages", "token_count": 449 }
1,156
// 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/cupertino.dart'; /// Details of the change to a web view's url. /// /// Platform specific implementations can add additional fields by extending /// this class. /// /// This example demonstrates how to extend the [UrlChange] to provide /// additional platform specific parameters: /// /// ```dart /// class AndroidUrlChange extends UrlChange { /// const AndroidUrlChange({required super.url, required this.isReload}); /// /// final bool isReload; /// } /// ``` @immutable class UrlChange { /// Creates a new [UrlChange]. const UrlChange({required this.url}); /// The new url of the web view. final String? url; }
packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/url_change.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/url_change.dart", "repo_id": "packages", "token_count": 225 }
1,157
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs import 'dart:async'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'package:webview_flutter_web/webview_flutter_web.dart'; void main() { WebViewPlatform.instance = WebWebViewPlatform(); runApp(const MaterialApp(home: _WebViewExample())); } class _WebViewExample extends StatefulWidget { const _WebViewExample(); @override _WebViewExampleState createState() => _WebViewExampleState(); } class _WebViewExampleState extends State<_WebViewExample> { final PlatformWebViewController _controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), )..loadRequest( LoadRequestParams( uri: Uri.parse('https://flutter.dev'), ), ); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Flutter WebView example'), actions: <Widget>[ _SampleMenu(_controller), ], ), body: PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: _controller), ).build(context), ); } } enum _MenuOptions { doPostRequest, } class _SampleMenu extends StatelessWidget { const _SampleMenu(this.controller); final PlatformWebViewController controller; @override Widget build(BuildContext context) { return PopupMenuButton<_MenuOptions>( onSelected: (_MenuOptions value) { switch (value) { case _MenuOptions.doPostRequest: _onDoPostRequest(controller); } }, itemBuilder: (BuildContext context) => <PopupMenuItem<_MenuOptions>>[ const PopupMenuItem<_MenuOptions>( value: _MenuOptions.doPostRequest, child: Text('Post Request'), ), ], ); } Future<void> _onDoPostRequest(PlatformWebViewController controller) async { final LoadRequestParams params = LoadRequestParams( uri: Uri.parse('https://httpbin.org/post'), method: LoadRequestMethod.post, headers: const <String, String>{ 'foo': 'bar', 'Content-Type': 'text/plain' }, body: Uint8List.fromList('Test Body'.codeUnits), ); await controller.loadRequest(params); } }
packages/packages/webview_flutter/webview_flutter_web/example/lib/main.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_web/example/lib/main.dart", "repo_id": "packages", "token_count": 916 }
1,158
name: webview_flutter_web description: A Flutter plugin that provides a WebView widget on web. repository: https://github.com/flutter/packages/tree/main/packages/webview_flutter/webview_flutter_web issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+webview%22 version: 0.2.2+4 environment: sdk: ">=3.1.0 <4.0.0" flutter: ">=3.13.0" flutter: plugin: implements: webview_flutter platforms: web: pluginClass: WebWebViewPlatform fileName: webview_flutter_web.dart dependencies: flutter: sdk: flutter flutter_web_plugins: sdk: flutter webview_flutter_platform_interface: ^2.0.0 dev_dependencies: build_runner: ^2.1.5 flutter_test: sdk: flutter mockito: 5.4.4 topics: - html - webview - webview-flutter
packages/packages/webview_flutter/webview_flutter_web/pubspec.yaml/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_web/pubspec.yaml", "repo_id": "packages", "token_count": 350 }
1,159
<!DOCTYPE html> <!-- 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. --> <html lang="en"> <head> <title>Load file or HTML string example</title> <link rel="stylesheet" href="styles/style.css" /> </head> <body> <h1>Local demo page</h1> <p> This is an example page used to demonstrate how to load a local file or HTML string using the <a href="https://pub.dev/packages/webview_flutter">Flutter webview</a> plugin. </p> </body> </html>
packages/packages/webview_flutter/webview_flutter_wkwebview/example/assets/www/index.html/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/example/assets/www/index.html", "repo_id": "packages", "token_count": 182 }
1,160
// 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 FWFScrollViewDelegateHostApiTests : XCTestCase @end @implementation FWFScrollViewDelegateHostApiTests /** * Creates a partially mocked FWFScrollViewDelegate and adds it to instanceManager. * * @param instanceManager Instance manager to add the delegate to. * @param identifier Identifier for the delegate added to the instanceManager. * * @return A mock FWFScrollViewDelegate. */ - (id)mockDelegateWithManager:(FWFInstanceManager *)instanceManager identifier:(long)identifier { FWFScrollViewDelegate *delegate = [[FWFScrollViewDelegate alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; [instanceManager addDartCreatedInstance:delegate withIdentifier:0]; return OCMPartialMock(delegate); } /** * Creates a mock FWFUIScrollViewDelegateFlutterApiImpl with instanceManager. * * @param instanceManager Instance manager passed to the Flutter API. * * @return A mock FWFUIScrollViewDelegateFlutterApiImpl. */ - (id)mockFlutterApiWithManager:(FWFInstanceManager *)instanceManager { FWFScrollViewDelegateFlutterApiImpl *flutterAPI = [[FWFScrollViewDelegateFlutterApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; return OCMPartialMock(flutterAPI); } - (void)testCreateWithIdentifier { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFScrollViewDelegateHostApiImpl *hostAPI = [[FWFScrollViewDelegateHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI createWithIdentifier:0 error:&error]; FWFScrollViewDelegate *delegate = (FWFScrollViewDelegate *)[instanceManager instanceForIdentifier:0]; XCTAssertTrue([delegate conformsToProtocol:@protocol(UIScrollViewDelegate)]); XCTAssertNil(error); } - (void)testOnScrollViewDidScrollForDelegateWithIdentifier { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFScrollViewDelegate *mockDelegate = [self mockDelegateWithManager:instanceManager identifier:0]; FWFScrollViewDelegateFlutterApiImpl *mockFlutterAPI = [self mockFlutterApiWithManager:instanceManager]; OCMStub([mockDelegate scrollViewDelegateAPI]).andReturn(mockFlutterAPI); UIScrollView *scrollView = [[UIScrollView alloc] init]; scrollView.contentOffset = CGPointMake(1.0, 2.0); [instanceManager addDartCreatedInstance:scrollView withIdentifier:1]; [mockDelegate scrollViewDidScroll:scrollView]; OCMVerify([mockFlutterAPI scrollViewDidScrollWithIdentifier:0 UIScrollViewIdentifier:1 x:1.0 y:2.0 completion:OCMOCK_ANY]); } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFScrollViewDelegateHostApiTests.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFScrollViewDelegateHostApiTests.m", "repo_id": "packages", "token_count": 1199 }
1,161
// 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 "FWFInstanceManager.h" #import "FWFInstanceManager_Test.h" #import <objc/runtime.h> // Attaches to an object to receive a callback when the object is deallocated. @interface FWFFinalizer : NSObject @end // Attaches to an object to receive a callback when the object is deallocated. @implementation FWFFinalizer { long _identifier; // Callbacks are no longer made once FWFInstanceManager is inaccessible. FWFOnDeallocCallback __weak _callback; } - (instancetype)initWithIdentifier:(long)identifier callback:(FWFOnDeallocCallback)callback { self = [self init]; if (self) { _identifier = identifier; _callback = callback; } return self; } + (void)attachToInstance:(NSObject *)instance withIdentifier:(long)identifier callback:(FWFOnDeallocCallback)callback { FWFFinalizer *finalizer = [[FWFFinalizer alloc] initWithIdentifier:identifier callback:callback]; objc_setAssociatedObject(instance, _cmd, finalizer, OBJC_ASSOCIATION_RETAIN); } + (void)detachFromInstance:(NSObject *)instance { objc_setAssociatedObject(instance, @selector(attachToInstance:withIdentifier:callback:), nil, OBJC_ASSOCIATION_ASSIGN); } - (void)dealloc { if (_callback) { _callback(_identifier); } } @end @interface FWFInstanceManager () @property dispatch_queue_t lockQueue; @property NSMapTable<NSObject *, NSNumber *> *identifiers; @property NSMapTable<NSNumber *, NSObject *> *weakInstances; @property NSMapTable<NSNumber *, NSObject *> *strongInstances; @end @implementation FWFInstanceManager // Identifiers are locked to a specific range to avoid collisions with objects // created simultaneously from Dart. // Host uses identifiers >= 2^16 and Dart is expected to use values n where, // 0 <= n < 2^16. static long const FWFMinHostCreatedIdentifier = 65536; - (instancetype)init { self = [super init]; if (self) { _deallocCallback = _deallocCallback ? _deallocCallback : ^(long identifier) { }; _lockQueue = dispatch_queue_create("FWFInstanceManager", DISPATCH_QUEUE_SERIAL); // Pointer equality is used to prevent collisions of objects that override the `isEqualTo:` // method. _identifiers = [NSMapTable mapTableWithKeyOptions:NSMapTableWeakMemory | NSMapTableObjectPointerPersonality valueOptions:NSMapTableStrongMemory]; _weakInstances = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableWeakMemory | NSMapTableObjectPointerPersonality]; _strongInstances = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableStrongMemory | NSMapTableObjectPointerPersonality]; _nextIdentifier = FWFMinHostCreatedIdentifier; } return self; } - (instancetype)initWithDeallocCallback:(FWFOnDeallocCallback)callback { self = [self init]; if (self) { _deallocCallback = callback; } return self; } - (void)addDartCreatedInstance:(NSObject *)instance withIdentifier:(long)instanceIdentifier { NSParameterAssert(instance); NSParameterAssert(instanceIdentifier >= 0); dispatch_async(_lockQueue, ^{ [self addInstance:instance withIdentifier:instanceIdentifier]; }); } - (long)addHostCreatedInstance:(nonnull NSObject *)instance { NSParameterAssert(instance); long __block identifier = -1; dispatch_sync(_lockQueue, ^{ identifier = self.nextIdentifier++; [self addInstance:instance withIdentifier:identifier]; }); return identifier; } - (nullable NSObject *)removeInstanceWithIdentifier:(long)instanceIdentifier { NSObject *__block instance = nil; dispatch_sync(_lockQueue, ^{ instance = [self.strongInstances objectForKey:@(instanceIdentifier)]; if (instance) { [self.strongInstances removeObjectForKey:@(instanceIdentifier)]; } }); return instance; } - (nullable NSObject *)instanceForIdentifier:(long)instanceIdentifier { NSObject *__block instance = nil; dispatch_sync(_lockQueue, ^{ instance = [self.weakInstances objectForKey:@(instanceIdentifier)]; }); return instance; } - (void)addInstance:(nonnull NSObject *)instance withIdentifier:(long)instanceIdentifier { [self.identifiers setObject:@(instanceIdentifier) forKey:instance]; [self.weakInstances setObject:instance forKey:@(instanceIdentifier)]; [self.strongInstances setObject:instance forKey:@(instanceIdentifier)]; [FWFFinalizer attachToInstance:instance withIdentifier:instanceIdentifier callback:self.deallocCallback]; } - (long)identifierWithStrongReferenceForInstance:(nonnull NSObject *)instance { NSNumber *__block identifierNumber = nil; dispatch_sync(_lockQueue, ^{ identifierNumber = [self.identifiers objectForKey:instance]; if (identifierNumber) { [self.strongInstances setObject:instance forKey:identifierNumber]; } }); return identifierNumber ? identifierNumber.longValue : NSNotFound; } - (BOOL)containsInstance:(nonnull NSObject *)instance { BOOL __block containsInstance; dispatch_sync(_lockQueue, ^{ containsInstance = [self.identifiers objectForKey:instance]; }); return containsInstance; } - (NSUInteger)strongInstanceCount { NSUInteger __block count = -1; dispatch_sync(_lockQueue, ^{ count = self.strongInstances.count; }); return count; } - (NSUInteger)weakInstanceCount { NSUInteger __block count = -1; dispatch_sync(_lockQueue, ^{ count = self.weakInstances.count; }); return count; } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFInstanceManager.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFInstanceManager.m", "repo_id": "packages", "token_count": 1900 }
1,162
// 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 "FWFGeneratedWebKitApis.h" #import "FWFInstanceManager.h" NS_ASSUME_NONNULL_BEGIN /// Host api implementation for UIView. /// /// Handles creating UIView that intercommunicate with a paired Dart object. @interface FWFUIViewHostApiImpl : NSObject <FWFUIViewHostApi> - (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager; @end NS_ASSUME_NONNULL_END
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUIViewHostApi.h/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUIViewHostApi.h", "repo_id": "packages", "token_count": 184 }
1,163
// 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" NS_ASSUME_NONNULL_BEGIN /// A set of Flutter and Dart assets used by a `FlutterEngine` to initialize execution. /// /// Default implementation delegates methods to FlutterDartProject. @interface FWFAssetManager : NSObject - (NSString *)lookupKeyForAsset:(NSString *)asset; @end /// Implementation of WKWebView that can be used as a FlutterPlatformView. @interface FWFWebView : WKWebView <FlutterPlatformView> @property(readonly, nonnull, nonatomic) FWFObjectFlutterApiImpl *objectApi; - (instancetype)initWithFrame:(CGRect)frame configuration:(nonnull WKWebViewConfiguration *)configuration binaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager; @end /// Host api implementation for WKWebView. /// /// Handles creating WKWebViews that intercommunicate with a paired Dart object. @interface FWFWebViewHostApiImpl : NSObject <FWFWKWebViewHostApi> - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager; - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager bundle:(NSBundle *)bundle assetManager:(FWFAssetManager *)assetManager; @end NS_ASSUME_NONNULL_END
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebViewHostApi.h/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebViewHostApi.h", "repo_id": "packages", "token_count": 635 }
1,164
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:math'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import '../common/instance_manager.dart'; import '../foundation/foundation.dart'; import '../web_kit/web_kit.dart'; import '../web_kit/web_kit_api_impls.dart'; import 'ui_kit_api_impls.dart'; /// A view that allows the scrolling and zooming of its contained views. /// /// Wraps [UIScrollView](https://developer.apple.com/documentation/uikit/uiscrollview?language=objc). @immutable class UIScrollView extends UIView { /// Constructs a [UIScrollView] that is owned by [webView]. factory UIScrollView.fromWebView( WKWebView webView, { BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, }) { final UIScrollView scrollView = UIScrollView.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ); scrollView._scrollViewApi.createFromWebViewForInstances( scrollView, webView, ); return scrollView; } /// Constructs a [UIScrollView] without creating the associated /// Objective-C object. /// /// This should only be used by subclasses created by this library or to /// create copies. UIScrollView.detached({ super.observeValue, super.binaryMessenger, super.instanceManager, }) : _scrollViewApi = UIScrollViewHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), super.detached(); final UIScrollViewHostApiImpl _scrollViewApi; /// Point at which the origin of the content view is offset from the origin of the scroll view. /// /// Represents [WKWebView.contentOffset](https://developer.apple.com/documentation/uikit/uiscrollview/1619404-contentoffset?language=objc). Future<Point<double>> getContentOffset() { return _scrollViewApi.getContentOffsetForInstances(this); } /// Move the scrolled position of this view. /// /// This method is not a part of UIKit and is only a helper method to make /// scrollBy atomic. Future<void> scrollBy(Point<double> offset) { return _scrollViewApi.scrollByForInstances(this, offset); } /// Set point at which the origin of the content view is offset from the origin of the scroll view. /// /// The default value is `Point<double>(0.0, 0.0)`. /// /// Sets [WKWebView.contentOffset](https://developer.apple.com/documentation/uikit/uiscrollview/1619404-contentoffset?language=objc). Future<void> setContentOffset(Point<double> offset) { return _scrollViewApi.setContentOffsetForInstances(this, offset); } /// Set the delegate to this scroll view. /// /// Represents [UIScrollView.delegate](https://developer.apple.com/documentation/uikit/uiscrollview/1619430-delegate?language=objc). Future<void> setDelegate(UIScrollViewDelegate? delegate) { return _scrollViewApi.setDelegateForInstances(this, delegate); } @override UIScrollView copy() { return UIScrollView.detached( observeValue: observeValue, binaryMessenger: _viewApi.binaryMessenger, instanceManager: _viewApi.instanceManager, ); } } /// Manages the content for a rectangular area on the screen. /// /// Wraps [UIView](https://developer.apple.com/documentation/uikit/uiview?language=objc). @immutable class UIView extends NSObject { /// Constructs a [UIView] without creating the associated /// Objective-C object. /// /// This should only be used by subclasses created by this library or to /// create copies. UIView.detached({ super.observeValue, super.binaryMessenger, super.instanceManager, }) : _viewApi = UIViewHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), super.detached(); final UIViewHostApiImpl _viewApi; /// The view’s background color. /// /// The default value is null, which results in a transparent background color. /// /// Sets [UIView.backgroundColor](https://developer.apple.com/documentation/uikit/uiview/1622591-backgroundcolor?language=objc). Future<void> setBackgroundColor(Color? color) { return _viewApi.setBackgroundColorForInstances(this, color); } /// Determines whether the view is opaque. /// /// Sets [UIView.opaque](https://developer.apple.com/documentation/uikit/uiview?language=objc). Future<void> setOpaque(bool opaque) { return _viewApi.setOpaqueForInstances(this, opaque); } @override UIView copy() { return UIView.detached( observeValue: observeValue, binaryMessenger: _viewApi.binaryMessenger, instanceManager: _viewApi.instanceManager, ); } } /// Responding to scroll view interactions. /// /// Represent [UIScrollViewDelegate](https://developer.apple.com/documentation/uikit/uiscrollviewdelegate?language=objc). @immutable class UIScrollViewDelegate extends NSObject { /// Constructs a [UIScrollViewDelegate]. UIScrollViewDelegate({ this.scrollViewDidScroll, super.binaryMessenger, super.instanceManager, }) : _scrollViewDelegateApi = UIScrollViewDelegateHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), super.detached() { // Ensures FlutterApis for the WebKit library are set up. WebKitFlutterApis.instance.ensureSetUp(); _scrollViewDelegateApi.createForInstance(this); } /// Constructs a [UIScrollViewDelegate] without creating the associated /// Objective-C object. /// /// This should only be used by subclasses created by this library or to /// create copies. UIScrollViewDelegate.detached({ this.scrollViewDidScroll, super.binaryMessenger, super.instanceManager, }) : _scrollViewDelegateApi = UIScrollViewDelegateHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), super.detached(); final UIScrollViewDelegateHostApiImpl _scrollViewDelegateApi; /// Called when scroll view did scroll. /// /// {@macro webview_flutter_wkwebview.foundation.callbacks} final void Function( UIScrollView scrollView, double x, double y, )? scrollViewDidScroll; @override UIScrollViewDelegate copy() { return UIScrollViewDelegate.detached( scrollViewDidScroll: scrollViewDidScroll, binaryMessenger: _scrollViewDelegateApi.binaryMessenger, instanceManager: _scrollViewDelegateApi.instanceManager, ); } }
packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/ui_kit/ui_kit.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/ui_kit/ui_kit.dart", "repo_id": "packages", "token_count": 2297 }
1,165
# This plugin no-ops below API 25, which is newer than the legacy emulator. # This can be removed once the legacy emulator test is using at least # API level 25. - quick_actions - quick_actions_android # Fails on the legacy emulator. See https://github.com/flutter/flutter/issues/136823 # TODO(stuartmorgan): Remove this if the limitation can be worked around. - video_player - video_player_android # Hangs on the legacy emulator. See https://github.com/flutter/flutter/issues/136824 # TODO(stuartmorgan): Remove this if the hang can be fixed. - webview_flutter - webview_flutter_android
packages/script/configs/exclude_integration_android_legacy_emulator.yaml/0
{ "file_path": "packages/script/configs/exclude_integration_android_legacy_emulator.yaml", "repo_id": "packages", "token_count": 173 }
1,166
// 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:platform/platform.dart'; import 'core.dart'; import 'output_utils.dart'; import 'process_runner.dart'; const String _cacheCommandKey = 'CMAKE_COMMAND:INTERNAL'; /// A utility class for interacting with CMake projects. class CMakeProject { /// Creates an instance that runs commands for [project] with the given /// [processRunner]. CMakeProject( this.flutterProject, { required this.buildMode, this.processRunner = const ProcessRunner(), this.platform = const LocalPlatform(), this.arch, }); /// The directory of a Flutter project to run Gradle commands in. final Directory flutterProject; /// The [ProcessRunner] used to run commands. Overridable for testing. final ProcessRunner processRunner; /// The platform that commands are being run on. final Platform platform; /// The architecture subdirectory of the build. // TODO(stuartmorgan): Make this non-nullable once Flutter 3.13 is no longer // supported, since at that point there will always be a subdirectory. final String? arch; /// The build mode (e.g., Debug, Release). /// /// This is a constructor paramater because on Linux many properties depend /// on the build mode since it uses a single-configuration generator. final String buildMode; late final String _cmakeCommand = _determineCmakeCommand(); /// The project's platform directory name. String get _platformDirName => platform.isWindows ? 'windows' : 'linux'; /// The project's 'example' build directory for this instance's platform. Directory get buildDirectory { Directory buildDir = flutterProject.childDirectory('build').childDirectory(_platformDirName); if (arch != null) { buildDir = buildDir.childDirectory(arch!); } if (platform.isLinux) { // Linux uses a single-config generator, so the base build directory // includes the configuration. buildDir = buildDir.childDirectory(buildMode.toLowerCase()); } return buildDir; } File get _cacheFile => buildDirectory.childFile('CMakeCache.txt'); /// Returns the CMake command to run build commands for this project. /// /// Assumes the project has been built at least once, such that the CMake /// generation step has run. String getCmakeCommand() { return _cmakeCommand; } /// Returns the CMake command to run build commands for this project. This is /// used to initialize _cmakeCommand, and should not be called directly. /// /// Assumes the project has been built at least once, such that the CMake /// generation step has run. String _determineCmakeCommand() { // On Linux 'cmake' is expected to be in the path, so doesn't need to // be lookup up and cached. if (platform.isLinux) { return 'cmake'; } final File cacheFile = _cacheFile; String? command; for (String line in cacheFile.readAsLinesSync()) { line = line.trim(); if (line.startsWith(_cacheCommandKey)) { command = line.substring(line.indexOf('=') + 1).trim(); break; } } if (command == null) { printError('Unable to find CMake command in ${cacheFile.path}'); throw ToolExit(100); } return command; } /// Whether or not the project is ready to have CMake commands run on it /// (i.e., whether the `flutter` tool has generated the necessary files). bool isConfigured() => _cacheFile.existsSync(); /// Runs a `cmake` command with the given parameters. Future<int> runBuild( String target, { List<String> arguments = const <String>[], }) { return processRunner.runAndStream( getCmakeCommand(), <String>[ '--build', buildDirectory.path, '--target', target, if (platform.isWindows) ...<String>['--config', buildMode], ...arguments, ], ); } }
packages/script/tool/lib/src/common/cmake.dart/0
{ "file_path": "packages/script/tool/lib/src/common/cmake.dart", "repo_id": "packages", "token_count": 1284 }
1,167
// 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 'common/package_looping_command.dart'; import 'common/pub_utils.dart'; import 'common/repository_package.dart'; const String _scriptName = 'run_tests.dart'; const String _legacyScriptName = 'run_tests.sh'; /// A command to run custom, package-local tests on packages. /// /// This is an escape hatch for adding tests that this tooling doesn't support. /// It should be used sparingly; prefer instead to add functionality to this /// tooling to eliminate the need for bespoke tests. class CustomTestCommand extends PackageLoopingCommand { /// Creates a custom test command instance. CustomTestCommand( super.packagesDir, { super.processRunner, super.platform, }); @override final String name = 'custom-test'; @override List<String> get aliases => <String>['test-custom']; @override final String description = 'Runs package-specific custom tests defined in ' "a package's tool/$_scriptName file.\n\n" 'This command requires "dart" to be in your path.'; @override Future<PackageResult> runForPackage(RepositoryPackage package) async { final File script = package.directory.childDirectory('tool').childFile(_scriptName); final File legacyScript = package.directory.childFile(_legacyScriptName); String? customSkipReason; bool ranTests = false; // Run the custom Dart script if presest. if (script.existsSync()) { // Ensure that dependencies are available. if (!await runPubGet(package, processRunner, platform)) { return PackageResult.fail( <String>['Unable to get script dependencies']); } final int testExitCode = await processRunner.runAndStream( 'dart', <String>['run', 'tool/$_scriptName'], workingDir: package.directory); if (testExitCode != 0) { return PackageResult.fail(); } ranTests = true; } // Run the legacy script if present. if (legacyScript.existsSync()) { if (platform.isWindows) { customSkipReason = '$_legacyScriptName is not supported on Windows. ' 'Please migrate to $_scriptName.'; } else { final int exitCode = await processRunner.runAndStream( legacyScript.path, <String>[], workingDir: package.directory); if (exitCode != 0) { return PackageResult.fail(); } ranTests = true; } } if (!ranTests) { return PackageResult.skip(customSkipReason ?? 'No custom tests'); } return PackageResult.success(); } }
packages/script/tool/lib/src/custom_test_command.dart/0
{ "file_path": "packages/script/tool/lib/src/custom_test_command.dart", "repo_id": "packages", "token_count": 953 }
1,168
// 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'; import 'package:file/file.dart'; import 'common/core.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; import 'common/plugin_utils.dart'; import 'common/repository_package.dart'; const int _exitUnsupportedPlatform = 2; const int _exitPodNotInstalled = 3; /// Lint the CocoaPod podspecs and run unit tests. /// /// See https://guides.cocoapods.org/terminal/commands.html#pod_lib_lint. class PodspecCheckCommand extends PackageLoopingCommand { /// Creates an instance of the linter command. PodspecCheckCommand( super.packagesDir, { super.processRunner, super.platform, }); @override final String name = 'podspec-check'; @override List<String> get aliases => <String>['podspec', 'podspecs', 'check-podspec']; @override final String description = 'Runs "pod lib lint" on all iOS and macOS plugin podspecs, as well as ' 'making sure the podspecs follow repository standards.\n\n' 'This command requires "pod" and "flutter" to be in your path. Runs on macOS only.'; @override Future<void> initializeRun() async { if (!platform.isMacOS) { printError('This command is only supported on macOS'); throw ToolExit(_exitUnsupportedPlatform); } final ProcessResult result = await processRunner.run( 'which', <String>['pod'], workingDir: packagesDir, logOnError: true, ); if (result.exitCode != 0) { printError('Unable to find "pod". Make sure it is in your path.'); throw ToolExit(_exitPodNotInstalled); } } @override Future<PackageResult> runForPackage(RepositoryPackage package) async { final List<String> errors = <String>[]; final List<File> podspecs = await _podspecsToLint(package); if (podspecs.isEmpty) { return PackageResult.skip('No podspecs.'); } for (final File podspec in podspecs) { if (!await _lintPodspec(podspec)) { errors.add(podspec.basename); } } if (await _hasIOSSwiftCode(package)) { print('iOS Swift code found, checking for search paths settings...'); for (final File podspec in podspecs) { if (_isPodspecMissingSearchPaths(podspec)) { const String workaroundBlock = r''' s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)/ $(SDKROOT)/usr/lib/swift', 'LD_RUNPATH_SEARCH_PATHS' => '/usr/lib/swift', } '''; final String path = getRelativePosixPath(podspec, from: package.directory); printError('$path is missing seach path configuration. Any iOS ' 'plugin implementation that contains Swift implementation code ' 'needs to contain the following:\n\n' '$workaroundBlock\n' 'For more details, see https://github.com/flutter/flutter/issues/118418.'); errors.add(podspec.basename); } } } if (pluginSupportsPlatform(platformIOS, package) && !podspecs.any(_hasPrivacyManifest)) { printError('No PrivacyInfo.xcprivacy file specified. Please ensure that ' 'a privacy manifest is included in the build using ' '`resource_bundles`'); errors.add('No privacy manifest'); } return errors.isEmpty ? PackageResult.success() : PackageResult.fail(errors); } Future<List<File>> _podspecsToLint(RepositoryPackage package) async { final List<File> podspecs = await getFilesForPackage(package).where((File entity) { final String filename = entity.basename; return path.extension(filename) == '.podspec' && filename != 'Flutter.podspec' && filename != 'FlutterMacOS.podspec'; }).toList(); podspecs.sort((File a, File b) => a.basename.compareTo(b.basename)); return podspecs; } Future<bool> _lintPodspec(File podspec) async { // Do not run the static analyzer on plugins with known analyzer issues. final String podspecPath = podspec.path; final String podspecBasename = podspec.basename; print('Linting $podspecBasename'); // Lint plugin as framework (use_frameworks!). final ProcessResult frameworkResult = await _runPodLint(podspecPath, libraryLint: true); print(frameworkResult.stdout); print(frameworkResult.stderr); // Lint plugin as library. final ProcessResult libraryResult = await _runPodLint(podspecPath, libraryLint: false); print(libraryResult.stdout); print(libraryResult.stderr); return frameworkResult.exitCode == 0 && libraryResult.exitCode == 0; } Future<ProcessResult> _runPodLint(String podspecPath, {required bool libraryLint}) async { final List<String> arguments = <String>[ 'lib', 'lint', podspecPath, '--configuration=Debug', // Release targets unsupported arm64 simulators. Use Debug to only build against targeted x86_64 simulator devices. '--skip-tests', '--use-modular-headers', // Flutter sets use_modular_headers! in its templates. if (libraryLint) '--use-libraries' ]; print('Running "pod ${arguments.join(' ')}"'); return processRunner.run('pod', arguments, workingDir: packagesDir, stdoutEncoding: utf8, stderrEncoding: utf8); } /// Returns true if there is any iOS plugin implementation code written in /// Swift. Future<bool> _hasIOSSwiftCode(RepositoryPackage package) async { return getFilesForPackage(package).any((File entity) { final String relativePath = getRelativePosixPath(entity, from: package.directory); // Ignore example code. if (relativePath.startsWith('example/')) { return false; } final String filePath = entity.path; return path.extension(filePath) == '.swift'; }); } /// Returns true if [podspec] could apply to iOS, but does not have the /// workaround for search paths that makes Swift plugins build correctly in /// Objective-C applications. See /// https://github.com/flutter/flutter/issues/118418 for context and details. /// /// This does not check that the plugin has Swift code, and thus whether the /// workaround is needed, only whether or not it is there. bool _isPodspecMissingSearchPaths(File podspec) { final String directory = podspec.parent.basename; // All macOS Flutter apps are Swift, so macOS-only podspecs don't need the // workaround. If it's anywhere other than macos/, err or the side of // assuming it's required. if (directory == 'macos') { return false; } // This errs on the side of being too strict, to minimize the chance of // accidental incorrect configuration. If we ever need more flexibility // due to a false negative we can adjust this as necessary. final RegExp workaround = RegExp(r''' \s*s\.(?:ios\.)?xcconfig = {[^}]* \s*'LIBRARY_SEARCH_PATHS' => '\$\(TOOLCHAIN_DIR\)/usr/lib/swift/\$\(PLATFORM_NAME\)/ \$\(SDKROOT\)/usr/lib/swift', \s*'LD_RUNPATH_SEARCH_PATHS' => '/usr/lib/swift',[^}]* \s*}''', dotAll: true); return !workaround.hasMatch(podspec.readAsStringSync()); } /// Returns true if [podspec] specifies a .xcprivacy file. bool _hasPrivacyManifest(File podspec) { final RegExp manifestBundling = RegExp(r''' \.(?:ios\.)?resource_bundles\s*=\s*{[^}]*PrivacyInfo.xcprivacy''', dotAll: true); return manifestBundling.hasMatch(podspec.readAsStringSync()); } }
packages/script/tool/lib/src/podspec_check_command.dart/0
{ "file_path": "packages/script/tool/lib/src/podspec_check_command.dart", "repo_id": "packages", "token_count": 2790 }
1,169
// 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:file/memory.dart'; import 'package:flutter_plugin_tools/src/common/file_utils.dart'; import 'package:test/test.dart'; void main() { group('childFileWithSubcomponents', () { test('works on Posix', () async { final FileSystem fileSystem = MemoryFileSystem(); final Directory base = fileSystem.directory('/').childDirectory('base'); final File file = childFileWithSubcomponents(base, <String>['foo', 'bar', 'baz.txt']); expect(file.absolute.path, '/base/foo/bar/baz.txt'); }); test('works on Windows', () async { final FileSystem fileSystem = MemoryFileSystem(style: FileSystemStyle.windows); final Directory base = fileSystem.directory(r'C:\').childDirectory('base'); final File file = childFileWithSubcomponents(base, <String>['foo', 'bar', 'baz.txt']); expect(file.absolute.path, r'C:\base\foo\bar\baz.txt'); }); }); group('childDirectoryWithSubcomponents', () { test('works on Posix', () async { final FileSystem fileSystem = MemoryFileSystem(); final Directory base = fileSystem.directory('/').childDirectory('base'); final Directory dir = childDirectoryWithSubcomponents(base, <String>['foo', 'bar', 'baz']); expect(dir.absolute.path, '/base/foo/bar/baz'); }); test('works on Windows', () async { final FileSystem fileSystem = MemoryFileSystem(style: FileSystemStyle.windows); final Directory base = fileSystem.directory(r'C:\').childDirectory('base'); final Directory dir = childDirectoryWithSubcomponents(base, <String>['foo', 'bar', 'baz']); expect(dir.absolute.path, r'C:\base\foo\bar\baz'); }); }); }
packages/script/tool/test/common/file_utils_test.dart/0
{ "file_path": "packages/script/tool/test/common/file_utils_test.dart", "repo_id": "packages", "token_count": 711 }
1,170
// 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/dependabot_check_command.dart'; import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; import 'common/package_command_test.mocks.dart'; import 'util.dart'; void main() { late CommandRunner<void> runner; late FileSystem fileSystem; late Directory root; late Directory packagesDir; setUp(() { fileSystem = MemoryFileSystem(); root = fileSystem.currentDirectory; packagesDir = root.childDirectory('packages'); final MockGitDir gitDir = MockGitDir(); when(gitDir.path).thenReturn(root.path); final DependabotCheckCommand command = DependabotCheckCommand( packagesDir, gitDir: gitDir, ); runner = CommandRunner<void>( 'dependabot_test', 'Test for $DependabotCheckCommand'); runner.addCommand(command); }); void setDependabotCoverage({ Iterable<String> gradleDirs = const <String>[], }) { final Iterable<String> gradleEntries = gradleDirs.map((String directory) => ''' - package-ecosystem: "gradle" directory: "/$directory" schedule: interval: "daily" '''); final File configFile = root.childDirectory('.github').childFile('dependabot.yml'); configFile.createSync(recursive: true); configFile.writeAsStringSync(''' version: 2 updates: ${gradleEntries.join('\n')} '''); } test('skips with no supported ecosystems', () async { setDependabotCoverage(); createFakePackage('a_package', packagesDir); final List<String> output = await runCapturingPrint(runner, <String>['dependabot-check']); expect( output, containsAllInOrder(<Matcher>[ contains('SKIPPING: No supported package ecosystems'), ])); }); test('fails for app missing Gradle coverage', () async { setDependabotCoverage(); final RepositoryPackage package = createFakePackage('a_package', packagesDir); package.directory .childDirectory('example') .childDirectory('android') .childDirectory('app') .createSync(recursive: true); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['dependabot-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Missing Gradle coverage.'), contains( 'Add a "gradle" entry to .github/dependabot.yml for /packages/a_package/example/android/app'), contains('a_package/example:\n' ' Missing Gradle coverage') ])); }); test('fails for plugin missing Gradle coverage', () async { setDependabotCoverage(); final RepositoryPackage plugin = createFakePlugin('a_plugin', packagesDir); plugin.directory.childDirectory('android').createSync(recursive: true); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['dependabot-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Missing Gradle coverage.'), contains( 'Add a "gradle" entry to .github/dependabot.yml for /packages/a_plugin/android'), contains('a_plugin:\n' ' Missing Gradle coverage') ])); }); test('passes for correct Gradle coverage', () async { setDependabotCoverage(gradleDirs: <String>[ 'packages/a_plugin/android', 'packages/a_plugin/example/android/app', ]); final RepositoryPackage plugin = createFakePlugin('a_plugin', packagesDir); // Test the plugin. plugin.directory.childDirectory('android').createSync(recursive: true); // And its example app. plugin.directory .childDirectory('example') .childDirectory('android') .childDirectory('app') .createSync(recursive: true); final List<String> output = await runCapturingPrint(runner, <String>['dependabot-check']); expect(output, containsAllInOrder(<Matcher>[contains('Ran for 2 package(s)')])); }); }
packages/script/tool/test/dependabot_check_command_test.dart/0
{ "file_path": "packages/script/tool/test/dependabot_check_command_test.dart", "repo_id": "packages", "token_count": 1716 }
1,171
// 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:io' as io; 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/publish_command.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; import 'common/package_command_test.mocks.dart'; import 'mocks.dart'; import 'util.dart'; void main() { late MockPlatform platform; late Directory packagesDir; late MockGitDir gitDir; late TestProcessRunner processRunner; late PublishCommand command; late CommandRunner<void> commandRunner; late MockStdin mockStdin; late FileSystem fileSystem; // Map of package name to mock response. late Map<String, Map<String, dynamic>> mockHttpResponses; void createMockCredentialFile() { fileSystem.file(command.credentialsPath) ..createSync(recursive: true) ..writeAsStringSync('some credential'); } setUp(() async { platform = MockPlatform(isLinux: true); platform.environment['HOME'] = '/home'; fileSystem = MemoryFileSystem(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); processRunner = TestProcessRunner(); mockHttpResponses = <String, Map<String, dynamic>>{}; final MockClient mockClient = MockClient((http.Request request) async { final String packageName = request.url.pathSegments.last.replaceAll('.json', ''); final Map<String, dynamic>? response = mockHttpResponses[packageName]; if (response != null) { return http.Response(json.encode(response), 200); } // Default to simulating the plugin never having been published. return http.Response('', 404); }); gitDir = MockGitDir(); when(gitDir.path).thenReturn(packagesDir.parent.path); when(gitDir.runCommand(any, throwOnError: anyNamed('throwOnError'))) .thenAnswer((Invocation invocation) { final List<String> arguments = invocation.positionalArguments[0]! as List<String>; // Route git calls through the process runner, to make mock output // consistent with outer processes. Attach the first argument to the // command to make targeting the mock results easier. final String gitCommand = arguments.removeAt(0); return processRunner.run('git-$gitCommand', arguments); }); mockStdin = MockStdin(); command = PublishCommand( packagesDir, platform: platform, processRunner: processRunner, stdinput: mockStdin, gitDir: gitDir, httpClient: mockClient, ); commandRunner = CommandRunner<void>('tester', '')..addCommand(command); }); group('Initial validation', () { test('refuses to proceed with dirty files', () async { final RepositoryPackage plugin = createFakePlugin('foo', packagesDir, examples: <String>[]); processRunner.mockProcessesForExecutable['git-status'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess( stdout: '?? ${plugin.directory.childFile('tmp').path}\n')) ]; Error? commandError; final List<String> output = await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=foo', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains("There are files in the package directory that haven't " 'been saved in git. Refusing to publish these files:\n\n' '?? /packages/foo/tmp\n\n' 'If the directory should be clean, you can run `git clean -xdf && ' 'git reset --hard HEAD` to wipe all local changes.'), contains('foo:\n' ' uncommitted changes'), ])); }); test("fails immediately if the remote doesn't exist", () async { createFakePlugin('foo', packagesDir, examples: <String>[]); processRunner.mockProcessesForExecutable['git-remote'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1)), ]; Error? commandError; final List<String> output = await runCapturingPrint( commandRunner, <String>['publish', '--packages=foo'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains( 'Unable to find URL for remote upstream; cannot push tags'), ])); }); }); group('Publishes package', () { test('while showing all output from pub publish to the user', () async { createFakePlugin('plugin1', packagesDir, examples: <String>[]); createFakePlugin('plugin2', packagesDir, examples: <String>[]); processRunner.mockProcessesForExecutable['flutter'] = <FakeProcessInfo>[ FakeProcessInfo( MockProcess( stdout: 'Foo', stderr: 'Bar', stdoutEncoding: utf8, stderrEncoding: utf8), <String>['pub', 'publish']), // publish for plugin1 FakeProcessInfo( MockProcess( stdout: 'Baz', stdoutEncoding: utf8, stderrEncoding: utf8), <String>['pub', 'publish']), // publish for plugin2 ]; final List<String> output = await runCapturingPrint( commandRunner, <String>['publish', '--packages=plugin1,plugin2']); expect( output, containsAllInOrder(<Matcher>[ contains('Running `pub publish ` in /packages/plugin1...'), contains('Foo'), contains('Bar'), contains('Package published!'), contains('Running `pub publish ` in /packages/plugin2...'), contains('Baz'), contains('Package published!'), ])); }); test('forwards input from the user to `pub publish`', () async { createFakePlugin('foo', packagesDir, examples: <String>[]); mockStdin.mockUserInputs.add(utf8.encode('user input')); await runCapturingPrint( commandRunner, <String>['publish', '--packages=foo']); expect(processRunner.mockPublishProcess.stdinMock.lines, contains('user input')); }); test('forwards --pub-publish-flags to pub publish', () async { final RepositoryPackage plugin = createFakePlugin('foo', packagesDir, examples: <String>[]); await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=foo', '--pub-publish-flags', '--dry-run,--server=bar' ]); expect( processRunner.recordedCalls, contains(ProcessCall( 'flutter', const <String>['pub', 'publish', '--dry-run', '--server=bar'], plugin.path))); }); test( '--skip-confirmation flag automatically adds --force to --pub-publish-flags', () async { createMockCredentialFile(); final RepositoryPackage plugin = createFakePlugin('foo', packagesDir, examples: <String>[]); await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=foo', '--skip-confirmation', '--pub-publish-flags', '--server=bar' ]); expect( processRunner.recordedCalls, contains(ProcessCall( 'flutter', const <String>['pub', 'publish', '--server=bar', '--force'], plugin.path))); }); test('--force is only added once, regardless of plugin count', () async { createMockCredentialFile(); final RepositoryPackage plugin1 = createFakePlugin('plugin_a', packagesDir, examples: <String>[]); final RepositoryPackage plugin2 = createFakePlugin('plugin_b', packagesDir, examples: <String>[]); await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=plugin_a,plugin_b', '--skip-confirmation', '--pub-publish-flags', '--server=bar' ]); expect( processRunner.recordedCalls, containsAllInOrder(<ProcessCall>[ ProcessCall( 'flutter', const <String>['pub', 'publish', '--server=bar', '--force'], plugin1.path), ProcessCall( 'flutter', const <String>['pub', 'publish', '--server=bar', '--force'], plugin2.path), ])); }); test('creates credential file from envirnoment variable if necessary', () async { createFakePlugin('foo', packagesDir, examples: <String>[]); const String credentials = 'some credential'; platform.environment['PUB_CREDENTIALS'] = credentials; await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=foo', '--skip-confirmation', '--pub-publish-flags', '--server=bar' ]); final File credentialFile = fileSystem.file(command.credentialsPath); expect(credentialFile.existsSync(), true); expect(credentialFile.readAsStringSync(), credentials); }); test('throws if pub publish fails', () async { createFakePlugin('foo', packagesDir, examples: <String>[]); processRunner.mockProcessesForExecutable['flutter'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 128), <String>['pub', 'publish']) ]; Error? commandError; final List<String> output = await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=foo', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Publishing foo failed.'), ])); }); test('publish, dry run', () async { final RepositoryPackage plugin = createFakePlugin('foo', packagesDir, examples: <String>[]); final List<String> output = await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=foo', '--dry-run', ]); expect( processRunner.recordedCalls .map((ProcessCall call) => call.executable), isNot(contains('git-push'))); expect( output, containsAllInOrder(<Matcher>[ contains('=============== DRY RUN ==============='), contains('Running for foo'), contains('Running `pub publish ` in ${plugin.path}...'), contains('Tagging release foo-v0.0.1...'), contains('Pushing tag to upstream...'), contains('Published foo successfully!'), ])); }); test('can publish non-flutter package', () async { const String packageName = 'a_package'; createFakePackage(packageName, packagesDir); final List<String> output = await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=$packageName', ]); expect( output, containsAllInOrder( <Matcher>[ contains('Running `pub publish ` in /packages/a_package...'), contains('Package published!'), ], ), ); }); test('skips publish with --tag-for-auto-publish', () async { const String packageName = 'a_package'; createFakePackage(packageName, packagesDir); final List<String> output = await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=$packageName', '--tag-for-auto-publish', ]); // There should be no variant of any command containing "publish". expect( processRunner.recordedCalls .map((ProcessCall call) => call.toString()), isNot(contains(contains('publish')))); // The output should indicate that it was tagged, not published. expect( output, containsAllInOrder( <Matcher>[ contains('Tagged a_package successfully!'), ], ), ); }); }); group('Tags release', () { test('with the version and name from the pubspec.yaml', () async { createFakePlugin('foo', packagesDir, examples: <String>[]); await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=foo', ]); expect(processRunner.recordedCalls, contains(const ProcessCall('git-tag', <String>['foo-v0.0.1'], null))); }); test('only if publishing succeeded', () async { createFakePlugin('foo', packagesDir, examples: <String>[]); processRunner.mockProcessesForExecutable['flutter'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 128), <String>['pub', 'publish']), ]; Error? commandError; final List<String> output = await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=foo', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Publishing foo failed.'), ])); expect( processRunner.recordedCalls, isNot(contains( const ProcessCall('git-tag', <String>['foo-v0.0.1'], null)))); }); test('when passed --tag-for-auto-publish', () async { createFakePlugin('foo', packagesDir, examples: <String>[]); await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=foo', '--tag-for-auto-publish', ]); expect(processRunner.recordedCalls, contains(const ProcessCall('git-tag', <String>['foo-v0.0.1'], null))); }); }); group('Pushes tags', () { test('to upstream by default', () async { createFakePlugin('foo', packagesDir, examples: <String>[]); mockStdin.readLineOutput = 'y'; final List<String> output = await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=foo', ]); expect( processRunner.recordedCalls, contains(const ProcessCall( 'git-push', <String>['upstream', 'foo-v0.0.1'], null))); expect( output, containsAllInOrder(<Matcher>[ contains('Pushing tag to upstream...'), contains('Published foo successfully!'), ])); }); test('does not ask for user input if the --skip-confirmation flag is on', () async { createMockCredentialFile(); createFakePlugin('foo', packagesDir, examples: <String>[]); final List<String> output = await runCapturingPrint(commandRunner, <String>[ 'publish', '--skip-confirmation', '--packages=foo', ]); expect( processRunner.recordedCalls, contains(const ProcessCall( 'git-push', <String>['upstream', 'foo-v0.0.1'], null))); expect( output, containsAllInOrder(<Matcher>[ contains('Published foo successfully!'), ])); }); test('when passed --tag-for-auto-publish', () async { createFakePlugin('foo', packagesDir, examples: <String>[]); await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=foo', '--skip-confirmation', '--tag-for-auto-publish', ]); expect( processRunner.recordedCalls, contains(const ProcessCall( 'git-push', <String>['upstream', 'foo-v0.0.1'], null))); }); test('to upstream by default, dry run', () async { final RepositoryPackage plugin = createFakePlugin('foo', packagesDir, examples: <String>[]); mockStdin.readLineOutput = 'y'; final List<String> output = await runCapturingPrint( commandRunner, <String>['publish', '--packages=foo', '--dry-run']); expect( processRunner.recordedCalls .map((ProcessCall call) => call.executable), isNot(contains('git-push'))); expect( output, containsAllInOrder(<Matcher>[ contains('=============== DRY RUN ==============='), contains('Running `pub publish ` in ${plugin.path}...'), contains('Tagging release foo-v0.0.1...'), contains('Pushing tag to upstream...'), contains('Published foo successfully!'), ])); }); test('to different remotes based on a flag', () async { createFakePlugin('foo', packagesDir, examples: <String>[]); mockStdin.readLineOutput = 'y'; final List<String> output = await runCapturingPrint(commandRunner, <String>[ 'publish', '--packages=foo', '--remote', 'origin', ]); expect( processRunner.recordedCalls, contains(const ProcessCall( 'git-push', <String>['origin', 'foo-v0.0.1'], null))); expect( output, containsAllInOrder(<Matcher>[ contains('Published foo successfully!'), ])); }); }); group('--already-tagged', () { test('passes when HEAD has the expected tag', () async { createFakePlugin('foo', packagesDir, examples: <String>[]); processRunner.mockProcessesForExecutable['git-tag'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess()), // Skip the initializeRun call. FakeProcessInfo(MockProcess(stdout: 'foo-v0.0.1\n'), <String>['--points-at', 'HEAD']) ]; await runCapturingPrint(commandRunner, <String>['publish', '--packages=foo', '--already-tagged']); }); test('fails if HEAD does not have the expected tag', () async { createFakePlugin('foo', packagesDir, examples: <String>[]); Error? commandError; final List<String> output = await runCapturingPrint(commandRunner, <String>['publish', '--packages=foo', '--already-tagged'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The current checkout is not already tagged "foo-v0.0.1"'), contains('missing tag'), ])); }); test('does not create or push tags', () async { createFakePlugin('foo', packagesDir, examples: <String>[]); processRunner.mockProcessesForExecutable['git-tag'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess()), // Skip the initializeRun call. FakeProcessInfo(MockProcess(stdout: 'foo-v0.0.1\n'), <String>['--points-at', 'HEAD']) ]; await runCapturingPrint(commandRunner, <String>['publish', '--packages=foo', '--already-tagged']); expect( processRunner.recordedCalls, isNot(contains( const ProcessCall('git-tag', <String>['foo-v0.0.1'], null)))); expect( processRunner.recordedCalls .map((ProcessCall call) => call.executable), isNot(contains('git-push'))); }); }); group('Auto release (all-changed flag)', () { test('can release newly created plugins', () async { mockHttpResponses['plugin1'] = <String, dynamic>{ 'name': 'plugin1', 'versions': <String>[], }; mockHttpResponses['plugin2'] = <String, dynamic>{ 'name': 'plugin2', 'versions': <String>[], }; // Non-federated final RepositoryPackage plugin1 = createFakePlugin('plugin1', packagesDir); // federated final RepositoryPackage plugin2 = createFakePlugin( 'plugin2', packagesDir.childDirectory('plugin2'), ); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess( stdout: '${plugin1.pubspecFile.path}\n' '${plugin2.pubspecFile.path}\n')) ]; mockStdin.readLineOutput = 'y'; final List<String> output = await runCapturingPrint(commandRunner, <String>['publish', '--all-changed', '--base-sha=HEAD~']); expect( output, containsAllInOrder(<Matcher>[ contains( 'Publishing all packages that have changed relative to "HEAD~"'), contains('Running `pub publish ` in ${plugin1.path}...'), contains('Running `pub publish ` in ${plugin2.path}...'), contains('plugin1 - published'), contains('plugin2/plugin2 - published'), ])); expect( processRunner.recordedCalls, contains(const ProcessCall( 'git-push', <String>['upstream', 'plugin1-v0.0.1'], null))); expect( processRunner.recordedCalls, contains(const ProcessCall( 'git-push', <String>['upstream', 'plugin2-v0.0.1'], null))); }); test('can release newly created plugins, while there are existing plugins', () async { mockHttpResponses['plugin0'] = <String, dynamic>{ 'name': 'plugin0', 'versions': <String>['0.0.1'], }; mockHttpResponses['plugin1'] = <String, dynamic>{ 'name': 'plugin1', 'versions': <String>[], }; mockHttpResponses['plugin2'] = <String, dynamic>{ 'name': 'plugin2', 'versions': <String>[], }; // The existing plugin. createFakePlugin('plugin0', packagesDir); // Non-federated final RepositoryPackage plugin1 = createFakePlugin('plugin1', packagesDir); // federated final RepositoryPackage plugin2 = createFakePlugin('plugin2', packagesDir.childDirectory('plugin2')); // Git results for plugin0 having been released already, and plugin1 and // plugin2 being new. processRunner.mockProcessesForExecutable['git-tag'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(stdout: 'plugin0-v0.0.1\n')) ]; processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess( stdout: '${plugin1.pubspecFile.path}\n' '${plugin2.pubspecFile.path}\n')) ]; mockStdin.readLineOutput = 'y'; final List<String> output = await runCapturingPrint(commandRunner, <String>['publish', '--all-changed', '--base-sha=HEAD~']); expect( output, containsAllInOrder(<String>[ 'Running `pub publish ` in ${plugin1.path}...\n', 'Running `pub publish ` in ${plugin2.path}...\n', ])); expect( processRunner.recordedCalls, contains(const ProcessCall( 'git-push', <String>['upstream', 'plugin1-v0.0.1'], null))); expect( processRunner.recordedCalls, contains(const ProcessCall( 'git-push', <String>['upstream', 'plugin2-v0.0.1'], null))); }); test('can release newly created plugins, dry run', () async { mockHttpResponses['plugin1'] = <String, dynamic>{ 'name': 'plugin1', 'versions': <String>[], }; mockHttpResponses['plugin2'] = <String, dynamic>{ 'name': 'plugin2', 'versions': <String>[], }; // Non-federated final RepositoryPackage plugin1 = createFakePlugin('plugin1', packagesDir); // federated final RepositoryPackage plugin2 = createFakePlugin('plugin2', packagesDir.childDirectory('plugin2')); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess( stdout: '${plugin1.pubspecFile.path}\n' '${plugin2.pubspecFile.path}\n')) ]; mockStdin.readLineOutput = 'y'; final List<String> output = await runCapturingPrint( commandRunner, <String>[ 'publish', '--all-changed', '--base-sha=HEAD~', '--dry-run' ]); expect( output, containsAllInOrder(<Matcher>[ contains('=============== DRY RUN ==============='), contains('Running `pub publish ` in ${plugin1.path}...'), contains('Tagging release plugin1-v0.0.1...'), contains('Pushing tag to upstream...'), contains('Published plugin1 successfully!'), contains('Running `pub publish ` in ${plugin2.path}...'), contains('Tagging release plugin2-v0.0.1...'), contains('Pushing tag to upstream...'), contains('Published plugin2 successfully!'), ])); expect( processRunner.recordedCalls .map((ProcessCall call) => call.executable), isNot(contains('git-push'))); }); test('version change triggers releases.', () async { mockHttpResponses['plugin1'] = <String, dynamic>{ 'name': 'plugin1', 'versions': <String>['0.0.1'], }; mockHttpResponses['plugin2'] = <String, dynamic>{ 'name': 'plugin2', 'versions': <String>['0.0.1'], }; // Non-federated final RepositoryPackage plugin1 = createFakePlugin('plugin1', packagesDir, version: '0.0.2'); // federated final RepositoryPackage plugin2 = createFakePlugin( 'plugin2', packagesDir.childDirectory('plugin2'), version: '0.0.2'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess( stdout: '${plugin1.pubspecFile.path}\n' '${plugin2.pubspecFile.path}\n')) ]; mockStdin.readLineOutput = 'y'; final List<String> output2 = await runCapturingPrint(commandRunner, <String>['publish', '--all-changed', '--base-sha=HEAD~']); expect( output2, containsAllInOrder(<Matcher>[ contains('Running `pub publish ` in ${plugin1.path}...'), contains('Published plugin1 successfully!'), contains('Running `pub publish ` in ${plugin2.path}...'), contains('Published plugin2 successfully!'), ])); expect( processRunner.recordedCalls, contains(const ProcessCall( 'git-push', <String>['upstream', 'plugin1-v0.0.2'], null))); expect( processRunner.recordedCalls, contains(const ProcessCall( 'git-push', <String>['upstream', 'plugin2-v0.0.2'], null))); }); test( 'delete package will not trigger publish but exit the command successfully!', () async { mockHttpResponses['plugin1'] = <String, dynamic>{ 'name': 'plugin1', 'versions': <String>['0.0.1'], }; mockHttpResponses['plugin2'] = <String, dynamic>{ 'name': 'plugin2', 'versions': <String>['0.0.1'], }; // Non-federated final RepositoryPackage plugin1 = createFakePlugin('plugin1', packagesDir, version: '0.0.2'); // federated final RepositoryPackage plugin2 = createFakePlugin('plugin2', packagesDir.childDirectory('plugin2')); plugin2.directory.deleteSync(recursive: true); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess( stdout: '${plugin1.pubspecFile.path}\n' '${plugin2.pubspecFile.path}\n')) ]; mockStdin.readLineOutput = 'y'; final List<String> output2 = await runCapturingPrint(commandRunner, <String>['publish', '--all-changed', '--base-sha=HEAD~']); expect( output2, containsAllInOrder(<Matcher>[ contains('Running `pub publish ` in ${plugin1.path}...'), contains('Published plugin1 successfully!'), contains( 'The pubspec file for plugin2/plugin2 does not exist, so no publishing will happen.\nSafe to ignore if the package is deleted in this commit.\n'), contains('SKIPPING: package deleted'), contains('skipped (with warning)'), ])); expect( processRunner.recordedCalls, contains(const ProcessCall( 'git-push', <String>['upstream', 'plugin1-v0.0.2'], null))); }); test('Existing versions do not trigger release, also prints out message.', () async { mockHttpResponses['plugin1'] = <String, dynamic>{ 'name': 'plugin1', 'versions': <String>['0.0.2'], }; mockHttpResponses['plugin2'] = <String, dynamic>{ 'name': 'plugin2', 'versions': <String>['0.0.2'], }; // Non-federated final RepositoryPackage plugin1 = createFakePlugin('plugin1', packagesDir, version: '0.0.2'); // federated final RepositoryPackage plugin2 = createFakePlugin( 'plugin2', packagesDir.childDirectory('plugin2'), version: '0.0.2'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess( stdout: '${plugin1.pubspecFile.path}\n' '${plugin2.pubspecFile.path}\n')) ]; processRunner.mockProcessesForExecutable['git-tag'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess( stdout: 'plugin1-v0.0.2\n' 'plugin2-v0.0.2\n')) ]; final List<String> output = await runCapturingPrint(commandRunner, <String>['publish', '--all-changed', '--base-sha=HEAD~']); expect( output, containsAllInOrder(<Matcher>[ contains('plugin1 0.0.2 has already been published'), contains('SKIPPING: already published'), contains('plugin2 0.0.2 has already been published'), contains('SKIPPING: already published'), ])); expect( processRunner.recordedCalls .map((ProcessCall call) => call.executable), isNot(contains('git-push'))); }); test( 'Existing versions do not trigger release, but fail if the tags do not exist.', () async { mockHttpResponses['plugin1'] = <String, dynamic>{ 'name': 'plugin1', 'versions': <String>['0.0.2'], }; mockHttpResponses['plugin2'] = <String, dynamic>{ 'name': 'plugin2', 'versions': <String>['0.0.2'], }; // Non-federated final RepositoryPackage plugin1 = createFakePlugin('plugin1', packagesDir, version: '0.0.2'); // federated final RepositoryPackage plugin2 = createFakePlugin( 'plugin2', packagesDir.childDirectory('plugin2'), version: '0.0.2'); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess( stdout: '${plugin1.pubspecFile.path}\n' '${plugin2.pubspecFile.path}\n')) ]; Error? commandError; final List<String> output = await runCapturingPrint(commandRunner, <String>['publish', '--all-changed', '--base-sha=HEAD~'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('plugin1 0.0.2 has already been published, ' 'however the git release tag (plugin1-v0.0.2) was not found.'), contains('plugin2 0.0.2 has already been published, ' 'however the git release tag (plugin2-v0.0.2) was not found.'), ])); expect( processRunner.recordedCalls .map((ProcessCall call) => call.executable), isNot(contains('git-push'))); }); test('No version change does not release any plugins', () async { // Non-federated final RepositoryPackage plugin1 = createFakePlugin('plugin1', packagesDir); // federated final RepositoryPackage plugin2 = createFakePlugin('plugin2', packagesDir.childDirectory('plugin2')); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess( stdout: '${plugin1.libDirectory.childFile('plugin1.dart').path}\n' '${plugin2.libDirectory.childFile('plugin2.dart').path}\n')) ]; final List<String> output = await runCapturingPrint(commandRunner, <String>['publish', '--all-changed', '--base-sha=HEAD~']); expect(output, containsAllInOrder(<String>['Ran for 0 package(s)'])); expect( processRunner.recordedCalls .map((ProcessCall call) => call.executable), isNot(contains('git-push'))); }); test('Do not release flutter_plugin_tools', () async { mockHttpResponses['plugin1'] = <String, dynamic>{ 'name': 'flutter_plugin_tools', 'versions': <String>[], }; final RepositoryPackage flutterPluginTools = createFakePlugin('flutter_plugin_tools', packagesDir); processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[ FakeProcessInfo( MockProcess(stdout: flutterPluginTools.pubspecFile.path)) ]; final List<String> output = await runCapturingPrint(commandRunner, <String>['publish', '--all-changed', '--base-sha=HEAD~']); expect( output, containsAllInOrder(<Matcher>[ contains( 'SKIPPING: publishing flutter_plugin_tools via the tool is not supported') ])); expect( output.contains( 'Running `pub publish ` in ${flutterPluginTools.path}...', ), isFalse); expect( processRunner.recordedCalls .map((ProcessCall call) => call.executable), isNot(contains('git-push'))); }); }); group('credential location', () { test('Linux with XDG', () async { platform = MockPlatform(isLinux: true); platform.environment['XDG_CONFIG_HOME'] = '/xdghome/config'; command = PublishCommand(packagesDir, platform: platform); expect( command.credentialsPath, '/xdghome/config/dart/pub-credentials.json'); }); test('Linux without XDG', () async { platform = MockPlatform(isLinux: true); platform.environment['HOME'] = '/home'; command = PublishCommand(packagesDir, platform: platform); expect( command.credentialsPath, '/home/.config/dart/pub-credentials.json'); }); test('macOS', () async { platform = MockPlatform(isMacOS: true); platform.environment['HOME'] = '/Users/someuser'; command = PublishCommand(packagesDir, platform: platform); expect(command.credentialsPath, '/Users/someuser/Library/Application Support/dart/pub-credentials.json'); }); test('Windows', () async { platform = MockPlatform(isWindows: true); platform.environment['APPDATA'] = r'C:\Users\SomeUser\AppData'; command = PublishCommand(packagesDir, platform: platform); expect(command.credentialsPath, r'C:\Users\SomeUser\AppData\dart\pub-credentials.json'); }); }); } /// An extension of [RecordingProcessRunner] that stores 'flutter pub publish' /// calls so that their input streams can be checked in tests. class TestProcessRunner extends RecordingProcessRunner { // Most recent returned publish process. late MockProcess mockPublishProcess; @override Future<io.Process> start(String executable, List<String> args, {Directory? workingDirectory}) async { final io.Process process = await super.start(executable, args, workingDirectory: workingDirectory); if (executable == 'flutter' && args.isNotEmpty && args[0] == 'pub' && args[1] == 'publish') { mockPublishProcess = process as MockProcess; } return process; } } class MockStdin extends Mock implements io.Stdin { List<List<int>> mockUserInputs = <List<int>>[]; final StreamController<List<int>> _controller = StreamController<List<int>>(); String? readLineOutput; @override Stream<S> transform<S>(StreamTransformer<List<int>, S> streamTransformer) { mockUserInputs.forEach(_addUserInputsToSteam); return _controller.stream.transform(streamTransformer); } @override StreamSubscription<List<int>> listen(void Function(List<int> event)? onData, {Function? onError, void Function()? onDone, bool? cancelOnError}) { return _controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } @override String? readLineSync( {Encoding encoding = io.systemEncoding, bool retainNewlines = false}) => readLineOutput; void _addUserInputsToSteam(List<int> input) => _controller.add(input); }
packages/script/tool/test/publish_command_test.dart/0
{ "file_path": "packages/script/tool/test/publish_command_test.dart", "repo_id": "packages", "token_count": 15851 }
1,172
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Launch", "request": "launch", "type": "dart", "program": "lib/main.dart", "args": ["-d", "chrome", "--web-renderer", "html"] } ] }
photobooth/.vscode/launch.json/0
{ "file_path": "photobooth/.vscode/launch.json", "repo_id": "photobooth", "token_count": 165 }
1,173
export default ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" type="image/png" href="{{{assetUrls.favicon}}}"> <meta name="viewport" content="width=device-width,initial-scale=1" /> <title>{{meta.title}}</title> <meta name="descripton" content="{{meta.desc}}"> {{{ga}}} <meta property="og:title" content="{{meta.title}}"> <meta property="og:description" content="{{meta.desc}}"> <meta property="og:url" content="{{{shareUrl}}}"> <meta property="og:image" content="{{{assetUrls.notFoundPhoto}}}"> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:title" content="{{meta.title}}"> <meta name="twitter:text:title" content="{{meta.title}}"> <meta name="twitter:description" content="{{meta.desc}}"> <meta name="twitter:image" content="{{{assetUrls.notFoundPhoto}}}"> <meta name="twitter:site" content="@flutterdev"> <link href="https://fonts.googleapis.com/css?family=Google+Sans:400,500" rel="stylesheet"> <style>{{{styles}}}</style> </head> <body> <div class="backdrop"></div> <img src="{{{assetUrls.fixedPhotosLeft}}}" class="fixed-photos left"> <img src="{{{assetUrls.fixedPhotosRight}}}" class="fixed-photos right"> <main> <div class="share-image no-shadow"> <img src="{{{assetUrls.notFoundPhoto}}}"> </div> <div class="text"> <h1>Taken with I/O Photo Booth</h1> <h2>Oops! This photo is gone, but that doesn't mean the fun has to end.</h2> <a class="share-btn" href="/">Take your own</a> </div> </main> {{{footer}}} </body> </html> `;
photobooth/functions/src/share/templates/notfound.ts/0
{ "file_path": "photobooth/functions/src/share/templates/notfound.ts", "repo_id": "photobooth", "token_count": 673 }
1,174
{ "@@locale": "en", "landingPageHeading": "Welcome to the I\u2215O Photo Booth", "@landingPageHeading": { "description": "Heading shown on the landing page." }, "landingPageSubheading": "Take a photo and share it with the community!", "@landingPageSubheading": { "description": "Subheading shown on the landing page." }, "landingPageTakePhotoButtonText": "Get started", "@landingPageTakePhotoButtonText": { "description": "Button text shown on the landing page which navigates to the photo booth." }, "footerMadeWithText": "Made with ", "@footerMadeWithText": { "description": "Text shown on the footer which mentions technologies used to build the app." }, "footerMadeWithFlutterLinkText": "Flutter", "@footerMadeWithFlutterLinkText": { "description": "Text on the link shown on the footer which navigates to the Flutter page" }, "footerMadeWithFirebaseLinkText": "Firebase", "@footerMadeWithFirebaseLinkText": { "description": "Text on the link shown on the footer which navigates to the Firebase page" }, "footerGoogleIOLinkText": "Google I\u2215O", "@footerGoogleIOLinkText": { "description": "Text on the link shown on the footer which navigates to the Google I\u2215O page." }, "footerCodelabLinkText": "Codelab", "@footerCodelabLinkText": { "description": "Text on the link shown on the footer which navigates to the Codelab page." }, "footerHowItsMadeLinkText": "How It's Made", "@footerHowItsMadeLinkText": { "description": "Text on the link shown on the footer which navigates to the How It's Made page." }, "footerTermsOfServiceLinkText": "Terms of Service", "@footerTermsOfServiceLinkText": { "description": "Text on the link shown on the footer which navigates to the Terms of Service page." }, "footerPrivacyPolicyLinkText": "Privacy Policy", "@footerPrivacyPolicyLinkText": { "description": "Text on the link shown on the footer which navigates to the Privacy Policy page." }, "sharePageHeading": "Share your photo with the community!", "@sharePageHeading": { "description": "Heading shown on the share page." }, "sharePageSubheading": "Share your photo with the community!", "@sharePageSubheading": { "description": "Subheading shown on the share page." }, "sharePageSuccessHeading": "Photo Shared!", "@sharePageSuccessHeading": { "description": "Heading shown on the share page after successful share." }, "sharePageSuccessSubheading": "Thanks for using our Flutter web app! Your photo has been published at this unique URL", "@sharePageSuccessSubheading": { "description": "Subheading shown on the share page after successful share." }, "sharePageSuccessCaption1": "Your photo will be available at that URL for 30 days and then automatically deleted. To request early deletion of your photo, please contact ", "@sharePageSuccessCaption1": { "description": "First part of the caption shown at the bottom of the share page after successful share." }, "sharePageSuccessCaption2": "flutter-photo-booth@google.com", "@sharePageSuccessCaption2": { "description": "Second part of the caption shown at the bottom of the share page after successful share." }, "sharePageSuccessCaption3": " and be sure to include your unique URL in your request.", "@sharePageSuccessCaption3": { "description": "Third part of the caption shown at the bottom of the share page after successful share." }, "sharePageRetakeButtonText": "Take new photo", "@sharePageRetakeButtonText": { "description": "Button text shown on the share page which navigates back to the photo booth." }, "sharePageShareButtonText": "Share", "@sharePageShareButtonText": { "description": "Button text shown on the share page which opens a dialog to share the taken photo." }, "sharePageDownloadButtonText": "Download", "@sharePageDownloadButtonText": { "description": "Button text shown on the share page which downloads the taken photo." }, "socialMediaShareLinkText": "Just took a selfie at the #IOPhotoBooth. See you at #GoogleIO!", "@socialMediaShareLinkText": { "description": "Text that is put into the social media share URL link." }, "previewPageCameraNotAllowedText": "You have denied camera permissions. Please grant access in order to use app.", "@previewPageCameraNotAllowedText": { "description": "Text shown when user denies camera permission" }, "sharePageSocialMediaShareClarification1": "If you choose to share your photo on social media, it will be available at a unique URL for 30 days and then automatically deleted. Photos that are not shared, are not stored. To request early deletion of your photo, please contact ", "@sharePageSocialMediaShareClarification1": { "description": "First part of the text shown at the bottom of the share page that clarifies how photos are stored on the backend when shared on social medias" }, "sharePageSocialMediaShareClarification2": "flutter-photo-booth@google.com", "@sharePageSocialMediaShareClarification2": { "description": "Second part of the text shown at the bottom of the share page that clarifies how photos are stored on the backend when shared on social medias" }, "sharePageSocialMediaShareClarification3": " and be sure to include your unique URL in your request.", "@sharePageSocialMediaShareClarification3": { "description": "Third part of the text shown at the bottom of the share page that clarifies how photos are stored on the backend when shared on social medias" }, "sharePageCopyLinkButton": "Copy", "@sharePageCopyLinkButton": { "description": "Title of the button used to copy the share link." }, "sharePageLinkedCopiedButton": "Copied", "@sharePageLinkedCopiedButton": { "description": "Title of the button used to indicate that the link has been copied." }, "sharePageErrorHeading": "We're having trouble processing your image", "@sharePageErrorHeading": { "description": "Heading shown on the share page when an error occurs." }, "sharePageErrorSubheading": "Please make sure your device and browser are up to date. If this issue persists, please contact flutter-photo-booth@google.com.", "@sharePageErrorSubheading": { "description": "Subheading shown on the share page when an error occurs." }, "shareDialogHeading": "Share your photo!", "@shareDialogHeading": { "description": "Heading shown on the share dialog." }, "shareDialogSubheading": "Let everyone know you're at Google I\u2215O by sharing your photo & updating your profile picture during the event!", "@shareDialogSubheading": { "description": "Subheading shown on the share dialog." }, "shareErrorDialogHeading": "Oops!", "@shareErrorDialogHeading": { "description": "Heading shown on the share error dialog." }, "shareErrorDialogTryAgainButton": "Go back", "@shareErrorDialogTryAgainButton": { "description": "Title of the button displayed on the share error dialog used to retry the upload operation." }, "shareErrorDialogSubheading": "Something went wrong and we couldn't load your photo.", "@shareErrorDialogSubheading": { "description": "Subheading shown on the share error dialog." }, "sharePageProgressOverlayHeading": "We're making your photo pixel perfect with Flutter! ", "@sharePageProgressOverlayHeading": { "description": "Heading shown on the share page progress overlay." }, "sharePageProgressOverlaySubheading": "Please do not close this tab.", "@sharePageProgressOverlaySubheading": { "description": "Subheading shown on the share page progress overlay." }, "shareDialogTwitterButtonText": "Twitter", "@shareDialogTwitterButtonText": { "description": "Button text shown on the share dialog which shares on Twitter the photo." }, "shareDialogFacebookButtonText": "Facebook", "@shareDialogFacebookButtonText": { "description": "Button text shown on the share dialog which shares on Facebook the photo." }, "photoBoothCameraAccessDeniedHeadline": "Camera access denied", "@photoBoothCameraAccessDeniedHeadline": { "description": "Text displayed on headline on the photobooth page when camera permissions is not granted" }, "photoBoothCameraAccessDeniedSubheadline": "To take a photo, you must allow browser access to your camera.", "@photoBoothCameraAccessDeniedSubheadline": { "description": "Text displayed on subheadline on the photobooth page when camera permissions is not granted" }, "photoBoothCameraNotFoundHeadline": "We can’t find your camera", "@photoBoothCameraNotFoundHeadline": { "description": "Text displayed on headline on the photobooth page when camera is not found" }, "photoBoothCameraNotFoundSubheadline1": "Looks like your device does not have a camera or it is not working.", "@photoBoothCameraNotFoundSubheadline1": { "description": "Text displayed on the first subheadline on the photobooth page when camera is not found" }, "photoBoothCameraNotFoundSubheadline2": "To take a photo, please revisit I\u2215O Photo Booth from a device with a camera.", "@photoBoothCameraNotFoundSubheadline2": { "description": "Text displayed on the second subheadline on the photobooth page when camera is not found" }, "photoBoothCameraErrorHeadline": "Oops! Something went wrong", "@photoBoothCameraErrorHeadline": { "description": "Text displayed on headline on the photobooth page when unknown error occurs" }, "photoBoothCameraErrorSubheadline1": "Please refresh your browser and try again.", "@photoBoothCameraErrorSubheadline1": { "description": "Text displayed on the first subheadline on the photobooth page when unknown error occurs" }, "photoBoothCameraErrorSubheadline2": "If this issue persists, please contact flutter-photo-booth@google.com", "@photoBoothCameraErrorSubheadline2": { "description": "Text displayed on the second subheadline on the photobooth page when unknown error occurs" }, "photoBoothCameraNotSupportedHeadline": "Oops! Something went wrong", "@photoBoothCameraNotSupportedHeadline": { "description": "Text displayed on headline on the photobooth page when camera is not supported" }, "photoBoothCameraNotSupportedSubheadline": "Please make sure your device and browser are up to date.", "@photoBoothCameraNotSupportedSubheadline": { "description": "Text displayed on subheadline on the photobooth page when camera is not supported" }, "stickersDrawerTitle": "Add Props", "@stickersDrawerTitle": { "description": "Text displayed on the stickers drawer as title" }, "openStickersTooltip": "Add Props", "@openStickersTooltip": { "description": "Text displayed on the tooltip for the open stickers button" }, "retakeButtonTooltip": "Retake", "@retakeButtonTooltip": { "description": "Text displayed on the tooltip for the retake button" }, "clearStickersButtonTooltip": "Clear Props", "@clearStickersButtonTooltip": { "description": "Text displayed on the tooltip for the clear stickers button" }, "charactersCaptionText": "Add Friends", "@charactersCaptionText": { "description": "Text displayed as a caption on the characters layout" }, "sharePageLearnMoreAboutTextPart1": "Learn more about ", "@sharePageLearnMoreAboutTextPart1": { "description": "Part 1 text shown on the share page which mentions technologies used to build the app." }, "sharePageLearnMoreAboutTextPart2": " and ", "@sharePageLearnMoreAboutTextPart2": { "description": "Part 2 text shown on the share page which mentions technologies used to build the app." }, "sharePageLearnMoreAboutTextPart3": " or dive right into the ", "@sharePageLearnMoreAboutTextPart3": { "description": "Part 3 text shown on the share page which mentions technologies used to build the app." }, "sharePageLearnMoreAboutTextPart4": "open source code", "@sharePageLearnMoreAboutTextPart4": { "description": "Part 4 text shown on the share page which mentions technologies used to build the app." }, "goToGoogleIOButtonText": "Go to Google I\u2215O", "@goToGoogleIOButtonText": { "description": "Text displayed on the button to navigate to Google I\u2215O" }, "clearStickersDialogHeading": "Clear all props?", "@clearStickersDialogHeading": { "description": "Heading displayed on the clear stickers dialog" }, "clearStickersDialogSubheading": "Do you want to remove all of the props from the screen?", "@clearStickersDialogSubheading": { "description": "Subheading displayed on the clear stickers dialog" }, "clearStickersDialogCancelButtonText": "No, take me back", "@clearStickersDialogCancelButtonText": { "description": "Cancel button text displayed on the clear stickers dialog" }, "clearStickersDialogConfirmButtonText": "Yes, clear all props", "@clearStickersDialogConfirmButtonText": { "description": "Confirm button text displayed on the clear stickers dialog" }, "propsReminderText": "Add some props", "@propsReminderText": { "description": "Helper text to add props" }, "stickersNextConfirmationHeading": "Ready to see the final photo?", "@stickersNextConfirmationHeading": { "description": "Heading shown in the confirmation when user taps the next button" }, "stickersNextConfirmationSubheading": "Once you leave this screen you won't be able to make any changes", "@stickersNextConfirmationSubheading": { "description": "Subheading shown in the confirmation when user taps the next button" }, "stickersNextConfirmationCancelButtonText": "No, I'm still creating", "@stickersNextConfirmationCancelButtonText": { "description": "Cancel button text shown in the confirmation when user taps the next button" }, "stickersNextConfirmationConfirmButtonText": "Yes, show me", "@stickersNextConfirmationConfirmButtonText": { "description": "Confirm button text shown in the confirmation when user taps the next button" }, "stickersRetakeConfirmationHeading": "Are you sure?", "@stickersRetakeConfirmationHeading": { "description": "Heading shown in the confirmation when user taps the retake button" }, "stickersRetakeConfirmationSubheading": "Retaking the photo will remove any props you've added", "@stickersRetakeConfirmationSubheading": { "description": "Subheading shown in the confirmation when user taps the retake button" }, "stickersRetakeConfirmationCancelButtonText": "No, stay here", "@stickersRetakeConfirmationCancelButtonText": { "description": "Cancel button text shown in the confirmation when user taps the retake button" }, "stickersRetakeConfirmationConfirmButtonText": "Yes, retake photo", "@stickersRetakeConfirmationConfirmButtonText": { "description": "Confirm button text shown in the confirmation when user taps the retake button" }, "shareRetakeConfirmationHeading": "Ready to take a new photo?", "@shareRetakeConfirmationHeading": { "description": "Heading shown in the confirmation when user taps the retake button" }, "shareRetakeConfirmationSubheading": "Remember to download or share this one first", "@shareRetakeConfirmationSubheading": { "description": "Subheading shown in the confirmation when user taps the retake button" }, "shareRetakeConfirmationCancelButtonText": "No, stay here", "@shareRetakeConfirmationCancelButtonText": { "description": "Cancel button text shown in the confirmation when user taps the retake button" }, "shareRetakeConfirmationConfirmButtonText": "Yes, retake photo", "@shareRetakeConfirmationConfirmButtonText": { "description": "Confirm button text shown in the confirmation when user taps the retake button" }, "shutterButtonLabelText": "Take photo", "@shutterButtonLabelText": { "description": "Semantic label for the shutter button used to take a photo" }, "stickersNextButtonLabelText": "Create final photo", "@stickersNextButtonLabelText": { "description": "Semantic label for the next button used to proceed to the share page" }, "dashButtonLabelText": "Add dash friend", "@dashButtonLabelText": { "description": "Semantic label for the dash character button" }, "sparkyButtonLabelText": "Add sparky friend", "@sparkyButtonLabelText": { "description": "Semantic label for the sparky character button" }, "dinoButtonLabelText": "Add dino friend", "@dinoButtonLabelText": { "description": "Semantic label for the dino character button" }, "androidButtonLabelText": "Add android jetpack friend", "@androidButtonLabelText": { "description": "Semantic label for the android jetpack character button" }, "addStickersButtonLabelText": "Add props", "@addStickersButtonLabelText": { "description": "Semantic label for the add props button" }, "retakePhotoButtonLabelText": "Retake photo", "@retakePhotoButtonLabelText": { "description": "Semantic label for the retake photo button" }, "clearAllStickersButtonLabelText": "Clear all props", "@clearAllStickersButtonLabelText": { "description": "Semantic label for the clear all stickers button" } }
photobooth/lib/l10n/arb/app_en.arb/0
{ "file_path": "photobooth/lib/l10n/arb/app_en.arb", "repo_id": "photobooth", "token_count": 5676 }
1,175
import 'package:flutter/material.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class LandingBackground extends StatelessWidget { const LandingBackground({super.key}); @override Widget build(BuildContext context) { return Container( key: const Key('landingPage_background'), decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ PhotoboothColors.gray, PhotoboothColors.white, ], ), ), ); } }
photobooth/lib/landing/widgets/landing_background.dart/0
{ "file_path": "photobooth/lib/landing/widgets/landing_background.dart", "repo_id": "photobooth", "token_count": 246 }
1,176
import 'package:flutter/material.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class CharactersCaption extends StatelessWidget { const CharactersCaption({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; return Semantics( button: false, child: AppTooltip.custom( visible: true, message: l10n.charactersCaptionText, ), ); } }
photobooth/lib/photobooth/widgets/characters_caption.dart/0
{ "file_path": "photobooth/lib/photobooth/widgets/characters_caption.dart", "repo_id": "photobooth", "token_count": 189 }
1,177
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 ShareErrorDialog extends StatelessWidget { const ShareErrorDialog({super.key}); @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: [ SizedBox( height: 300, child: Image.asset( 'assets/images/error_photo_desktop.png', ), ), const SizedBox(height: 60), Text( l10n.shareErrorDialogHeading, key: const Key('shareErrorDialog_heading'), style: theme.textTheme.displayLarge, textAlign: TextAlign.center, ), const SizedBox(height: 24), Text( l10n.shareErrorDialogSubheading, key: const Key('shareErrorDialog_subheading'), style: theme.textTheme.displaySmall, textAlign: TextAlign.center, ), const SizedBox(height: 42), const ShareTryAgainButton(), const SizedBox(height: 16), ], ), ), ), ), 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_error_dialog.dart/0
{ "file_path": "photobooth/lib/share/view/share_error_dialog.dart", "repo_id": "photobooth", "token_count": 1488 }
1,178
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 ShareSubheading extends StatelessWidget { const ShareSubheading({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); return SelectableText.rich( TextSpan( text: l10n.sharePageLearnMoreAboutTextPart1, style: theme.textTheme.displaySmall?.copyWith( fontWeight: PhotoboothFontWeight.regular, color: PhotoboothColors.white, ), children: <TextSpan>[ TextSpan( text: l10n.footerMadeWithFlutterLinkText, recognizer: TapGestureRecognizer()..onTap = launchFlutterDevLink, style: const TextStyle(decoration: TextDecoration.underline), ), TextSpan( text: l10n.sharePageLearnMoreAboutTextPart2, ), TextSpan( text: l10n.footerMadeWithFirebaseLinkText, recognizer: TapGestureRecognizer()..onTap = launchFirebaseLink, style: const TextStyle(decoration: TextDecoration.underline), ), TextSpan( text: l10n.sharePageLearnMoreAboutTextPart3, ), TextSpan( text: l10n.sharePageLearnMoreAboutTextPart4, recognizer: TapGestureRecognizer()..onTap = launchOpenSourceLink, style: const TextStyle(decoration: TextDecoration.underline), ), ], ), textAlign: TextAlign.center, ); } } class ShareSuccessSubheading extends StatelessWidget { const ShareSuccessSubheading({super.key}); @override Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = context.l10n; return SelectableText( l10n.sharePageSuccessSubheading, style: theme.textTheme.displaySmall?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ); } } class ShareErrorSubheading extends StatelessWidget { const ShareErrorSubheading({super.key}); @override Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = context.l10n; return SelectableText( l10n.sharePageErrorSubheading, style: theme.textTheme.displaySmall?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ); } }
photobooth/lib/share/widgets/share_subheading.dart/0
{ "file_path": "photobooth/lib/share/widgets/share_subheading.dart", "repo_id": "photobooth", "token_count": 1099 }
1,179
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:io_photobooth/stickers/stickers.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class StickersDrawerLayer extends StatefulWidget { const StickersDrawerLayer({super.key}); @override State<StickersDrawerLayer> createState() => _StickersDrawerLayerState(); } class _StickersDrawerLayerState extends State<StickersDrawerLayer> { final PageStorageBucket _bucket = PageStorageBucket(); @override Widget build(BuildContext context) { return BlocConsumer<StickersBloc, StickersState>( listenWhen: (previous, current) => current.isDrawerActive && current != previous, listener: (context, state) { if (MediaQuery.of(context).size.width < PhotoboothBreakpoints.small) { showModalBottomSheet<void>( context: context, barrierColor: PhotoboothColors.black.withOpacity(0.75), backgroundColor: PhotoboothColors.transparent, isScrollControlled: true, builder: (_) => MobileStickersDrawer( initialIndex: state.tabIndex, bucket: _bucket, onTabChanged: (index) => context .read<StickersBloc>() .add(StickersDrawerTabTapped(index: index)), onStickerSelected: (sticker) { context .read<PhotoboothBloc>() .add(PhotoStickerTapped(sticker: sticker)); Navigator.of(context).pop(); }, ), ); context.read<StickersBloc>().add(const StickersDrawerToggled()); } }, buildWhen: (previous, current) => current != previous, builder: (context, state) { if (state.isDrawerActive && MediaQuery.of(context).size.width >= PhotoboothBreakpoints.small) { return Positioned( right: 0, top: 0, bottom: 0, child: DesktopStickersDrawer( initialIndex: state.tabIndex, bucket: _bucket, onTabChanged: (index) => context .read<StickersBloc>() .add(StickersDrawerTabTapped(index: index)), onStickerSelected: (sticker) { context.read<StickersBloc>().add(const StickersDrawerToggled()); context .read<PhotoboothBloc>() .add(PhotoStickerTapped(sticker: sticker)); }, onCloseTapped: () => context .read<StickersBloc>() .add(const StickersDrawerToggled()), ), ); } return const SizedBox(); }, ); } }
photobooth/lib/stickers/widgets/stickers_drawer_layer/stickers_drawer_layer.dart/0
{ "file_path": "photobooth/lib/stickers/widgets/stickers_drawer_layer/stickers_drawer_layer.dart", "repo_id": "photobooth", "token_count": 1367 }
1,180
name: authentication_repository description: Repository which manages user authentication using Firebase Authentication. version: 1.0.0+1 environment: sdk: ">=2.19.0 <3.0.0" dependencies: equatable: ^2.0.5 firebase_auth: ^4.2.5 firebase_core: ^2.4.1 flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter mocktail: ^0.3.0 very_good_analysis: ^4.0.0+1
photobooth/packages/authentication_repository/pubspec.yaml/0
{ "file_path": "photobooth/packages/authentication_repository/pubspec.yaml", "repo_id": "photobooth", "token_count": 161 }
1,181
part of '../camera.dart'; enum CameraStatus { uninitialized, available, unavailable } class CameraState { const CameraState._({ this.status = CameraStatus.uninitialized, this.error, }); const CameraState.uninitialized() : this._(); const CameraState.available() : this._(status: CameraStatus.available); const CameraState.unavailable(CameraException error) : this._(status: CameraStatus.unavailable, error: error); final CameraStatus status; final CameraException? error; } class CameraController extends ValueNotifier<CameraState> { CameraController({this.options = const CameraOptions()}) : _cameraPlatform = CameraPlatform.instance, super(const CameraState.uninitialized()); final CameraOptions options; final CameraPlatform _cameraPlatform; // The id of a texture that hasn't been initialized. @visibleForTesting static const int kUninitializedTextureId = -1; int _textureId = kUninitializedTextureId; bool get _isInitialized => _textureId != kUninitializedTextureId; /// This is just exposed for testing. It shouldn't be used by anyone depending /// on the plugin. @visibleForTesting int get textureId => _textureId; /// Attempts to use the given [options] to initialize a camera. Future<void> initialize() async { try { await _cameraPlatform.init(); _textureId = await _cameraPlatform.create(options); value = const CameraState.available(); } on CameraException catch (e) { value = CameraState.unavailable(e); } catch (e) { value = const CameraState.unavailable(CameraUnknownException()); } } Future<void> play() => _cameraPlatform.play(_textureId); Future<void> stop() => _cameraPlatform.stop(_textureId); Future<CameraImage> takePicture() { return _cameraPlatform.takePicture(_textureId); } @override Future<void> dispose() async { if (_isInitialized) { await _cameraPlatform.dispose(_textureId); } value = const CameraState.uninitialized(); super.dispose(); } }
photobooth/packages/camera/camera/lib/src/controller.dart/0
{ "file_path": "photobooth/packages/camera/camera/lib/src/controller.dart", "repo_id": "photobooth", "token_count": 613 }
1,182
import 'dart:async'; import 'dart:html' as html; import 'dart:ui' as ui; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:camera_web/camera_web.dart'; import 'package:flutter/material.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; String _getViewType(int cameraId) => 'plugins.flutter.io/camera_$cameraId'; /// The web implementation of [CameraPlatform]. /// /// This class implements the `package:camera` functionality for the web. class CameraPlugin extends CameraPlatform { /// Registers this class as the default instance of [CameraPlatform]. static void registerWith(Registrar registrar) { CameraPlatform.instance = CameraPlugin(); } final _cameras = <int, Camera>{}; var _textureCounter = 1; @visibleForTesting html.Window? window; @override Future<void> init() async { _disposeAllCameras(); } @override Future<void> dispose(int textureId) async { _cameras[textureId]!.dispose(); _cameras.remove(textureId); } @override Future<int> create(CameraOptions options) async { final textureId = _textureCounter; _textureCounter++; final camera = Camera( options: options, textureId: textureId, window: window, ); await camera.initialize(); _cameras[textureId] = camera; return textureId; } @override Widget buildView(int textureId) { return HtmlElementView(viewType: _getViewType(textureId)); } @override Future<void> play(int textureId) => _cameras[textureId]!.play(); @override Future<void> stop(int textureId) async => _cameras[textureId]!.stop(); @override Future<CameraImage> takePicture(int textureId) { return _cameras[textureId]!.takePicture(); } void _disposeAllCameras() { for (final camera in _cameras.values) { camera.dispose(); } _cameras.clear(); } @override Future<List<MediaDeviceInfo>> getMediaDevices() async { final videoDevices = <MediaDeviceInfo>[]; if (html.window.navigator.mediaDevices != null) { final devices = await html.window.navigator.mediaDevices?.enumerateDevices() ?? []; for (var deviceIndex = 0; deviceIndex < devices.length; deviceIndex++) { final device = devices[deviceIndex]; if (device is html.MediaDeviceInfo && device.kind == 'videoinput') { videoDevices.add( MediaDeviceInfo( deviceId: device.deviceId, label: device.label, ), ); } } } return videoDevices; } @override Future<String?> getDefaultDeviceId() async { String? defaultId = VideoConstraints.defaultDeviceId; if (browserEngine != BrowserEngine.blink) { /// For browsers other than Chrome, enumerate video devices and return /// first one since it is the default selected for the browser. final devices = await getMediaDevices(); if (devices.isNotEmpty) { defaultId = devices[0].deviceId; } } return defaultId; } } class Camera { Camera({ required this.textureId, this.options = const CameraOptions(), html.Window? window, }) : window = window ?? html.window; late html.VideoElement videoElement; late html.DivElement divElement; final CameraOptions options; final int textureId; final html.Window window; Future<void> initialize() async { final isSupported = window.navigator.mediaDevices?.getUserMedia != null; if (!isSupported) { throw const CameraNotSupportedException(); } videoElement = html.VideoElement()..applyDefaultStyles(); divElement = html.DivElement() ..style.setProperty('object-fit', 'cover') ..append(videoElement); // ignore: avoid_dynamic_calls ui.platformViewRegistry.registerViewFactory( _getViewType(textureId), (_) => divElement, ); final stream = await _getMediaStream(); videoElement ..autoplay = false ..muted = !options.audio.enabled ..srcObject = stream ..setAttribute('playsinline', ''); } Future<html.MediaStream> _getMediaStream() async { try { final constraints = await options.toJson(); return await window.navigator.mediaDevices!.getUserMedia( constraints, ); } on html.DomException catch (e) { switch (e.name) { case 'NotFoundError': case 'DevicesNotFoundError': throw const CameraNotFoundException(); case 'NotReadableError': case 'TrackStartError': throw const CameraNotReadableException(); case 'OverconstrainedError': case 'ConstraintNotSatisfiedError': throw const CameraOverconstrainedException(); case 'NotAllowedError': case 'PermissionDeniedError': throw const CameraNotAllowedException(); case 'TypeError': throw const CameraTypeException(); default: throw const CameraUnknownException(); } } catch (_) { throw const CameraUnknownException(); } } Future<void> play() async { if (videoElement.srcObject == null) { final stream = await _getMediaStream(); videoElement.srcObject = stream; } await videoElement.play(); } void stop() { final tracks = videoElement.srcObject?.getVideoTracks(); if (tracks != null) { for (final track in tracks) { track.stop(); } } videoElement.srcObject = null; } void dispose() { stop(); videoElement ..srcObject = null ..load(); } Future<CameraImage> takePicture() async { final videoWidth = videoElement.videoWidth; final videoHeight = videoElement.videoHeight; final canvas = html.CanvasElement(width: videoWidth, height: videoHeight); canvas.context2D ..translate(videoWidth, 0) ..scale(-1, 1) ..drawImageScaled(videoElement, 0, 0, videoWidth, videoHeight); final blob = await canvas.toBlob(); return CameraImage( data: html.Url.createObjectUrl(blob), width: videoWidth, height: videoHeight, ); } } extension on html.VideoElement { void applyDefaultStyles() { style ..removeProperty('transform-origin') ..setProperty('pointer-events', 'none') ..setProperty('width', '100%') ..setProperty('height', '100%') ..setProperty('transform', 'scaleX(-1)') ..setProperty('object-fit', 'cover') ..setProperty('-webkit-transform', 'scaleX(-1)') ..setProperty('-moz-transform', 'scaleX(-1)'); } }
photobooth/packages/camera/camera_web/lib/src/camera_web.dart/0
{ "file_path": "photobooth/packages/camera/camera_web/lib/src/camera_web.dart", "repo_id": "photobooth", "token_count": 2433 }
1,183
include: package:very_good_analysis/analysis_options.yaml
photobooth/packages/photobooth_ui/analysis_options.yaml/0
{ "file_path": "photobooth/packages/photobooth_ui/analysis_options.yaml", "repo_id": "photobooth", "token_count": 16 }
1,184
export 'asset.dart';
photobooth/packages/photobooth_ui/lib/src/models/models.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/src/models/models.dart", "repo_id": "photobooth", "token_count": 9 }
1,185
import 'package:flutter/material.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; /// {@template app_tooltip} /// A custom [Tooltip] for the photobooth_ui toolkit. /// {@endtemplate} class AppTooltip extends StatelessWidget { /// {@macro app_tooltip} const AppTooltip({ required String message, required Widget child, EdgeInsets? padding, Key? key, }) : this._( key: key, message: message, child: child, padding: padding, ); const AppTooltip._({ required this.message, required this.child, this.visible = false, this.padding, this.verticalOffset, super.key, }); /// {@macro app_tooltip} const AppTooltip.custom({ required String message, required bool visible, EdgeInsets? padding, double? verticalOffset, Widget? child, Key? key, }) : this._( key: key, message: message, visible: visible, padding: padding, verticalOffset: verticalOffset, child: child, ); /// The tooltip message. final String message; /// Whether or not the tooltip is currently visible. final bool visible; /// An optional padding. final EdgeInsets? padding; /// An optional vertical offset. final double? verticalOffset; /// An optional child widget. final Widget? child; @override Widget build(BuildContext context) { final child = this.child; if (visible) { return Column( mainAxisSize: MainAxisSize.min, children: [ if (child != null) child, Container( decoration: const BoxDecoration( color: PhotoboothColors.charcoal, borderRadius: BorderRadius.all(Radius.circular(5)), ), padding: padding ?? const EdgeInsets.all(10), child: Text( message, style: Theme.of(context) .textTheme .bodyMedium ?.copyWith(color: PhotoboothColors.white), ), ), ], ); } return Tooltip( message: message, verticalOffset: verticalOffset, child: child, ); } }
photobooth/packages/photobooth_ui/lib/src/widgets/app_tooltip.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/src/widgets/app_tooltip.dart", "repo_id": "photobooth", "token_count": 968 }
1,186
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class MockBuildContext extends Mock implements BuildContext {} class MockAnimation extends Mock implements Animation<double> {} void main() { group('AppPageRoute', () { testWidgets('is a MaterialPageRoute', (tester) async { final route = AppPageRoute<void>(builder: (_) => const SizedBox()); expect(route, isA<MaterialPageRoute<void>>()); }); testWidgets('has no transition', (tester) async { const child = SizedBox(); final route = AppPageRoute<void>(builder: (_) => child); final transition = route.buildTransitions( MockBuildContext(), MockAnimation(), MockAnimation(), child, ); expect(transition, equals(child)); }); }); }
photobooth/packages/photobooth_ui/test/src/navigation/app_page_route_test.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/test/src/navigation/app_page_route_test.dart", "repo_id": "photobooth", "token_count": 324 }
1,187
import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import '../helpers/helpers.dart'; void main() { group('ResponsiveLayout', () { testWidgets('displays a large layout if medium is not provided', (tester) async { tester.setDisplaySize(const Size(PhotoboothBreakpoints.medium, 800)); const smallKey = Key('__small__'); const largeKey = Key('__large__'); await tester.pumpWidget( ResponsiveLayoutBuilder( small: (_, __) => const SizedBox(key: smallKey), large: (_, __) => const SizedBox(key: largeKey), ), ); expect(find.byKey(smallKey), findsNothing); expect(find.byKey(largeKey), findsOneWidget); }); testWidgets('displays a medium layout', (tester) async { tester.setDisplaySize(const Size(PhotoboothBreakpoints.small + 1, 800)); const smallKey = Key('__small__'); const mediumKey = Key('__medium__'); const largeKey = Key('__large__'); await tester.pumpWidget( ResponsiveLayoutBuilder( small: (_, __) => const SizedBox(key: smallKey), medium: (_, __) => const SizedBox(key: mediumKey), large: (_, __) => const SizedBox(key: largeKey), ), ); expect(find.byKey(smallKey), findsNothing); expect(find.byKey(mediumKey), findsOneWidget); expect(find.byKey(largeKey), findsNothing); }); testWidgets('displays a large layout if xLarge is not provided', (tester) async { tester.setDisplaySize(const Size(PhotoboothBreakpoints.large + 1, 800)); const smallKey = Key('__small__'); const largeKey = Key('__large__'); await tester.pumpWidget( ResponsiveLayoutBuilder( small: (_, __) => const SizedBox(key: smallKey), large: (_, __) => const SizedBox(key: largeKey), ), ); expect(find.byKey(smallKey), findsNothing); expect(find.byKey(largeKey), findsOneWidget); }); testWidgets('displays a xLarge layout', (tester) async { tester.setDisplaySize(const Size(PhotoboothBreakpoints.large + 1, 800)); const smallKey = Key('__small__'); const largeKey = Key('__large__'); const xLargeKey = Key('__xLarge__'); await tester.pumpWidget( ResponsiveLayoutBuilder( small: (_, __) => const SizedBox(key: smallKey), large: (_, __) => const SizedBox(key: largeKey), xLarge: (_, __) => const SizedBox(key: xLargeKey), ), ); expect(find.byKey(smallKey), findsNothing); expect(find.byKey(largeKey), findsNothing); expect(find.byKey(xLargeKey), findsOneWidget); }); testWidgets('displays a large layout', (tester) async { tester.setDisplaySize(const Size(PhotoboothBreakpoints.large, 800)); const smallKey = Key('__small__'); const largeKey = Key('__large__'); const xLargeKey = Key('__xLarge__'); await tester.pumpWidget( ResponsiveLayoutBuilder( small: (_, __) => const SizedBox(key: smallKey), large: (_, __) => const SizedBox(key: largeKey), xLarge: (_, __) => const SizedBox(key: xLargeKey), ), ); expect(find.byKey(largeKey), findsOneWidget); expect(find.byKey(smallKey), findsNothing); expect(find.byKey(xLargeKey), findsNothing); }); testWidgets('displays a small layout', (tester) async { tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 800)); const smallKey = Key('__small__'); const largeKey = Key('__large__'); await tester.pumpWidget( ResponsiveLayoutBuilder( small: (_, __) => const SizedBox(key: smallKey), large: (_, __) => const SizedBox(key: largeKey), ), ); expect(find.byKey(largeKey), findsNothing); expect(find.byKey(smallKey), findsOneWidget); }); testWidgets('displays child when available (large)', (tester) async { const smallKey = Key('__small__'); const largeKey = Key('__large__'); const childKey = Key('__child__'); await tester.pumpWidget( ResponsiveLayoutBuilder( small: (_, child) => SizedBox(key: smallKey, child: child), large: (_, child) => SizedBox(key: largeKey, child: child), child: const SizedBox(key: childKey), ), ); expect(find.byKey(largeKey), findsOneWidget); expect(find.byKey(smallKey), findsNothing); expect(find.byKey(childKey), findsOneWidget); }); testWidgets('displays child when available (small)', (tester) async { tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 800)); const smallKey = Key('__small__'); const largeKey = Key('__large__'); const childKey = Key('__child__'); await tester.pumpWidget( ResponsiveLayoutBuilder( small: (_, child) => SizedBox(key: smallKey, child: child), large: (_, child) => SizedBox(key: largeKey, child: child), child: const SizedBox(key: childKey), ), ); expect(find.byKey(largeKey), findsNothing); expect(find.byKey(smallKey), findsOneWidget); expect(find.byKey(childKey), findsOneWidget); addTearDown(tester.binding.window.clearPhysicalSizeTestValue); }); }); }
photobooth/packages/photobooth_ui/test/src/widgets/responsive_layout_builder_test.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/test/src/widgets/responsive_layout_builder_test.dart", "repo_id": "photobooth", "token_count": 2210 }
1,188
name: platform_helper description: A Flutter package which helps detect the host platform environment: sdk: ">=2.19.0 <3.0.0" dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter mocktail: ^0.3.0 test: ^1.21.7 very_good_analysis: ^4.0.0+1
photobooth/packages/platform_helper/pubspec.yaml/0
{ "file_path": "photobooth/packages/platform_helper/pubspec.yaml", "repo_id": "photobooth", "token_count": 123 }
1,189
// ignore_for_file: prefer_const_constructors import 'package:bloc_test/bloc_test.dart'; import 'package:camera/camera.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/assets.g.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:mocktail/mocktail.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class MockCameraImage extends Mock implements CameraImage {} void main() { group('PhotoboothBloc', () { const aspectRatio = PhotoboothAspectRatio.landscape; late CameraImage image; late String id; String uuid() => id; setUp(() { id = '0'; image = MockCameraImage(); }); test('initial state is PhotoboothState', () { expect(PhotoboothBloc(uuid).state, equals(PhotoboothState())); }); group('PhotoCaptured', () { blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state with image', build: () => PhotoboothBloc(uuid), act: (bloc) => bloc.add( PhotoCaptured(aspectRatio: aspectRatio, image: image), ), expect: () => [PhotoboothState(image: image, imageId: id)], ); blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state with image and no selected asset', build: () => PhotoboothBloc(uuid), seed: () => PhotoboothState(selectedAssetId: '0'), act: (bloc) => bloc.add( PhotoCaptured(aspectRatio: aspectRatio, image: image), ), expect: () => [PhotoboothState(image: image, imageId: id)], ); }); group('PhotoCharacterToggled', () { blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state with character ' 'when character did not exist (android)', build: () => PhotoboothBloc(uuid), act: (bloc) => bloc.add( PhotoCharacterToggled(character: Assets.android), ), expect: () => [ PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.android)], selectedAssetId: '0', ) ], ); blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state with character ' 'when character did not exist (dash)', build: () => PhotoboothBloc(uuid), act: (bloc) => bloc.add(PhotoCharacterToggled(character: Assets.dash)), expect: () => [ PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.dash)], selectedAssetId: '0', ) ], ); blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state with character ' 'when character did not exist (sparky)', build: () => PhotoboothBloc(uuid), act: (bloc) => bloc.add( PhotoCharacterToggled(character: Assets.sparky), ), expect: () => [ PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.sparky)], selectedAssetId: '0', ) ], ); blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state with character ' 'when character did exist (android)', build: () => PhotoboothBloc(uuid), seed: () => PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.android)], ), act: (bloc) => bloc.add( PhotoCharacterToggled(character: Assets.android), ), expect: () => [PhotoboothState()], ); blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state with character ' 'when character did exist (dash)', build: () => PhotoboothBloc(uuid), seed: () => PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.dash)], ), act: (bloc) => bloc.add( PhotoCharacterToggled(character: Assets.dash), ), expect: () => [PhotoboothState()], ); blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state with character ' 'when character did exist (sparky)', build: () => PhotoboothBloc(uuid), seed: () => PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.sparky)], ), act: (bloc) => bloc.add( PhotoCharacterToggled(character: Assets.sparky), ), expect: () => [PhotoboothState()], ); }); group('PhotoCharacterDragged', () { blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state', build: () => PhotoboothBloc(uuid), seed: () => PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.sparky)], ), act: (bloc) => bloc.add( PhotoCharacterDragged( character: PhotoAsset(id: '0', asset: Assets.sparky), update: DragUpdate( angle: 42, position: Offset(42, 42), constraints: Size(42, 42), size: Size(42, 42), ), ), ), expect: () => [ PhotoboothState( characters: const [ PhotoAsset( id: '0', asset: Assets.sparky, angle: 42, position: PhotoAssetPosition(dx: 42, dy: 42), constraint: PhotoConstraint(width: 42, height: 42), size: PhotoAssetSize(width: 42, height: 42), ), ], selectedAssetId: '0', ) ], ); }); group('PhotoStickerTapped', () { blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state with sticker', build: () => PhotoboothBloc(uuid), act: (bloc) => bloc.add( PhotoStickerTapped(sticker: Assets.props.first), ), expect: () => [ PhotoboothState( stickers: [PhotoAsset(id: '0', asset: Assets.props.first)], selectedAssetId: '0', ) ], ); }); group('PhotoStickerDragged', () { blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state', build: () => PhotoboothBloc(uuid), seed: () => PhotoboothState( stickers: [PhotoAsset(id: '0', asset: Assets.props.first)], ), act: (bloc) => bloc.add( PhotoStickerDragged( sticker: PhotoAsset(id: '0', asset: Assets.props.first), update: DragUpdate( angle: 42, position: Offset(42, 42), constraints: Size(42, 42), size: Size(42, 42), ), ), ), expect: () => [ PhotoboothState( stickers: [ PhotoAsset( id: '0', asset: Assets.props.first, angle: 42, position: PhotoAssetPosition(dx: 42, dy: 42), constraint: PhotoConstraint(width: 42, height: 42), size: PhotoAssetSize(width: 42, height: 42), ), ], selectedAssetId: '0', ) ], ); }); group('PhotoClearStickersTapped', () { blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state with no stickers', build: () => PhotoboothBloc(uuid), seed: () => PhotoboothState( stickers: [PhotoAsset(id: '0', asset: Assets.props.first)], ), act: (bloc) => bloc.add(PhotoClearStickersTapped()), expect: () => [PhotoboothState()], ); }); group('PhotoClearAllTapped', () { blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state with no characters or stickers', build: () => PhotoboothBloc(uuid), seed: () => PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.dash)], stickers: [PhotoAsset(id: '0', asset: Assets.props.first)], ), act: (bloc) => bloc.add(PhotoClearAllTapped()), expect: () => [PhotoboothState()], ); }); group('PhotoTapped', () { blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state with no selectedAssetId', build: () => PhotoboothBloc(uuid), seed: () => PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.dash)], stickers: [PhotoAsset(id: '0', asset: Assets.props.first)], selectedAssetId: '0', ), act: (bloc) => bloc.add(PhotoTapped()), expect: () => [ PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.dash)], stickers: [PhotoAsset(id: '0', asset: Assets.props.first)], ), ], ); }); group('PhotoDeleteSelectedStickerTapped', () { blocTest<PhotoboothBloc, PhotoboothState>( 'emits updated state without the sticker', build: () => PhotoboothBloc(uuid), seed: () => PhotoboothState( stickers: [PhotoAsset(id: '0', asset: Assets.props.first)], selectedAssetId: '0', ), act: (bloc) => bloc.add(PhotoDeleteSelectedStickerTapped()), expect: () => [PhotoboothState()], ); }); }); }
photobooth/test/photobooth/bloc/photobooth_bloc_test.dart/0
{ "file_path": "photobooth/test/photobooth/bloc/photobooth_bloc_test.dart", "repo_id": "photobooth", "token_count": 4393 }
1,190
// ignore_for_file: prefer_const_constructors import 'dart:typed_data'; import 'package:bloc_test/bloc_test.dart'; import 'package:camera/camera.dart'; import 'package:cross_file/cross_file.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/external_links/external_links.dart'; import 'package:io_photobooth/footer/footer.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:mocktail/mocktail.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import 'package:photos_repository/photos_repository.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import '../../helpers/helpers.dart'; class FakePhotoboothEvent extends Fake implements PhotoboothEvent {} class FakePhotoboothState extends Fake implements PhotoboothState {} class MockPhotoboothBloc extends MockBloc<PhotoboothEvent, PhotoboothState> implements PhotoboothBloc {} class MockUrlLauncher extends Mock with MockPlatformInterfaceMixin implements UrlLauncherPlatform {} class MockPhotosRepository extends Mock implements PhotosRepository {} class MockXFile extends Mock implements XFile {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); const width = 1; const height = 1; const data = ''; const image = CameraImage(width: width, height: height, data: data); late PhotosRepository photosRepository; late PhotoboothBloc photoboothBloc; late ShareBloc shareBloc; late XFile file; late UrlLauncherPlatform originalUrlLauncher; setUpAll(() { registerFallbackValue(FakePhotoboothEvent()); registerFallbackValue(FakePhotoboothState()); registerFallbackValue(FakeShareEvent()); registerFallbackValue(FakeShareState()); registerFallbackValue(LaunchOptions()); }); setUp(() { file = MockXFile(); photosRepository = MockPhotosRepository(); when( () => photosRepository.composite( width: width, height: height, data: data, layers: [], aspectRatio: any(named: 'aspectRatio'), ), ).thenAnswer((_) async => Uint8List.fromList([])); photoboothBloc = MockPhotoboothBloc(); when(() => photoboothBloc.state).thenReturn(PhotoboothState(image: image)); shareBloc = MockShareBloc(); whenListen( shareBloc, Stream.fromIterable([ShareState()]), initialState: ShareState(), ); originalUrlLauncher = UrlLauncherPlatform.instance; }); tearDown(() { UrlLauncherPlatform.instance = originalUrlLauncher; }); group('SharePage', () { test('is routable', () { expect(SharePage.route(), isA<MaterialPageRoute<void>>()); }); testWidgets('renders a ShareView', (tester) async { await tester.pumpApp( SharePage(), photosRepository: photosRepository, photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(ShareView), findsOneWidget); }); }); group('ShareView', () { testWidgets('displays a ShareBackground', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(ShareBackground), findsOneWidget); }); testWidgets('displays a ShareBody', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(ShareBody), findsOneWidget); }); testWidgets('displays a WhiteFooter', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); await tester.ensureVisible(find.byType(WhiteFooter, skipOffstage: false)); }); testWidgets('displays a ShareRetakeButton', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect( find.byKey(const Key('sharePage_retake_appTooltipButton')), findsOneWidget, ); }); testWidgets('displays a ShareProgressOverlay', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(ShareProgressOverlay), findsOneWidget); }); }); group('ShareBody', () { setUp(() { when(() => shareBloc.state).thenReturn( ShareState( compositeStatus: ShareStatus.success, bytes: Uint8List(0), file: file, ), ); }); testWidgets('renders', (tester) async { await tester.pumpApp( SingleChildScrollView(child: ShareBody()), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(ShareBody), findsOneWidget); }); testWidgets('displays a AnimatedPhotoIndicator', (tester) async { tester.setDisplaySize(Size(PhotoboothBreakpoints.medium, 800)); await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(AnimatedPhotoIndicator), findsOneWidget); }); testWidgets('displays a AnimatedPhotoboothPhoto', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(AnimatedPhotoboothPhoto), findsOneWidget); }); testWidgets('displays a ShareHeading', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect( find.byType(ShareHeading), findsOneWidget, ); }); testWidgets( 'displays a ShareSuccessHeading ' 'when uploadStatus is success', (tester) async { when(() => shareBloc.state).thenReturn( ShareState( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.success, file: file, ), ); await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect( find.byType(ShareSuccessHeading), findsOneWidget, ); }); testWidgets( 'displays a ShareErrorHeading ' 'when compositeStatus is failure', (tester) async { when(() => shareBloc.state).thenReturn( ShareState( compositeStatus: ShareStatus.failure, file: file, ), ); await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect( find.byType(ShareErrorHeading), findsOneWidget, ); }); testWidgets('displays a ShareSubheading', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(ShareSubheading), findsOneWidget); }); testWidgets( 'displays a ShareSuccessSubheading ' 'when uploadStatus is success', (tester) async { when(() => shareBloc.state).thenReturn( ShareState( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.success, file: file, ), ); await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(ShareSuccessSubheading), findsOneWidget); }); testWidgets( 'displays a ShareErrorSubheading ' 'when compositeStatus is failure', (tester) async { when(() => shareBloc.state).thenReturn( ShareState( compositeStatus: ShareStatus.failure, file: file, ), ); await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(ShareErrorSubheading), findsOneWidget); }); testWidgets( 'displays a ShareSuccessCaption ' 'when uploadStatus is success', (tester) async { when(() => shareBloc.state).thenReturn( ShareState( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.success, file: file, ), ); await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(ShareSuccessCaption), findsOneWidget); }); testWidgets( 'displays a ShareCopyableLink ' 'when uploadStatus is success', (tester) async { when(() => shareBloc.state).thenReturn( ShareState( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.success, file: file, ), ); await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(ShareCopyableLink), findsOneWidget); }); testWidgets('displays a RetakeButton', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect( find.byKey(const Key('sharePage_retake_appTooltipButton')), findsOneWidget, ); }); testWidgets('displays a ShareButton', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(ShareButton), findsOneWidget); }); testWidgets('displays a DownloadButton', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(DownloadButton), findsOneWidget); }); testWidgets('displays a GoToGoogleIOButton', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(GoToGoogleIOButton), findsOneWidget); }); group('GoToGoogleIOButton', () { testWidgets('opens link when tapped', (tester) async { final mock = MockUrlLauncher(); const url = googleIOExternalLink; UrlLauncherPlatform.instance = mock; when(() => mock.canLaunch(any())).thenAnswer((_) async => true); when(() => mock.launchUrl(url, any())).thenAnswer((_) async => true); tester.setDisplaySize(Size(2500, 2500)); await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); await tester.ensureVisible( find.byType( GoToGoogleIOButton, skipOffstage: false, ), ); await tester.tap(find.byType(GoToGoogleIOButton, skipOffstage: false)); verify(() => mock.launchUrl(url, any())).called(1); }); }); group('RetakeButton', () { testWidgets( 'tapping on retake button + close ' 'does not go back to PhotoboothPage', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); final retakeButtonFinder = find.byKey( const Key('sharePage_retake_appTooltipButton'), ); tester.widget<AppTooltipButton>(retakeButtonFinder).onPressed(); await tester.pumpAndSettle(); tester.widget<IconButton>(find.byType(IconButton)).onPressed!(); await tester.pumpAndSettle(); expect(retakeButtonFinder, findsOneWidget); expect(find.byType(PhotoboothPage), findsNothing); verifyNever(() => photoboothBloc.add(PhotoClearAllTapped())); }); testWidgets( 'tapping on retake button + cancel ' 'does not go back to PhotoboothPage', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); final retakeButtonFinder = find.byKey( const Key('sharePage_retake_appTooltipButton'), ); tester.widget<AppTooltipButton>(retakeButtonFinder).onPressed(); await tester.pumpAndSettle(); final cancelButtonFinder = find.byKey( const Key('sharePage_retakeCancel_elevatedButton'), ); tester.widget<OutlinedButton>(cancelButtonFinder).onPressed!(); await tester.pumpAndSettle(); expect(retakeButtonFinder, findsOneWidget); expect(find.byType(PhotoboothPage), findsNothing); verifyNever(() => photoboothBloc.add(PhotoClearAllTapped())); }); testWidgets( 'tapping on retake button + confirm goes back to PhotoboothPage', (tester) async { await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); final retakeButtonFinder = find.byKey( const Key('sharePage_retake_appTooltipButton'), ); tester.widget<AppTooltipButton>(retakeButtonFinder).onPressed(); await tester.pumpAndSettle(); final confirmButtonFinder = find.byKey( const Key('sharePage_retakeConfirm_elevatedButton'), ); tester.widget<ElevatedButton>(confirmButtonFinder).onPressed!(); await tester.pumpAndSettle(); expect(retakeButtonFinder, findsNothing); expect(find.byType(PhotoboothPage), findsOneWidget); verify(() => photoboothBloc.add(PhotoClearAllTapped())).called(1); }); }); group('ResponsiveLayout', () { testWidgets('displays a DesktopButtonsLayout', (tester) async { tester.setDisplaySize(const Size(PhotoboothBreakpoints.large, 1000)); await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(DesktopButtonsLayout), findsOneWidget); }); testWidgets('displays a MobileButtonsLayout', (tester) async { tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 1000)); await tester.pumpApp( ShareView(), photoboothBloc: photoboothBloc, shareBloc: shareBloc, ); expect(find.byType(MobileButtonsLayout), findsOneWidget); }); }); }); }
photobooth/test/share/view/share_page_test.dart/0
{ "file_path": "photobooth/test/share/view/share_page_test.dart", "repo_id": "photobooth", "token_count": 6385 }
1,191
#!/bin/bash # Script used to analyze bundled assets and generate a dart file which contains # the relevant metadata needed at runtime without forcing the application to # download the assets. # # Usage: # ./tool/generate_asset_metadata.sh > lib/assets.g.dart set -e output_metadata () { width=$(sips -g pixelWidth $1 | tail -n1 | cut -d" " -f4) height=$(sips -g pixelHeight $1 | tail -n1 | cut -d" " -f4) filepath=$1 name=$(basename "${filepath%.*}") echo "Asset(name: '$name', path: '$1', size: Size($width, $height));" } echo "// GENERATED CODE - DO NOT MODIFY BY HAND" echo "" echo "import 'package:flutter/widgets.dart';" echo "import 'package:photobooth_ui/photobooth_ui.dart';" echo "" echo "class Assets {" characters=("android.png" "dash.png" "dino.png" "sparky.png") for character in "${characters[@]}" do path="assets/images/$character" width=$(sips -g pixelWidth $path | tail -n1 | cut -d" " -f4) height=$(sips -g pixelHeight $path | tail -n1 | cut -d" " -f4) name=$(basename "${path%.*}") echo " static const $name = Asset(name: '$name', path: '$path', size: Size($width, $height),);" done googleProps=assets/props/google/*.png echo " static const googleProps = {" for prop in $googleProps do width=$(sips -g pixelWidth $prop | tail -n1 | cut -d" " -f4) height=$(sips -g pixelHeight $prop | tail -n1 | cut -d" " -f4) name=$(basename "${prop%.*}") echo " Asset(name: '$name', path: '$prop', size: Size($width, $height),)," done echo " };" hatProps=assets/props/hats/*.png echo " static const hatProps = {" for prop in $hatProps do width=$(sips -g pixelWidth $prop | tail -n1 | cut -d" " -f4) height=$(sips -g pixelHeight $prop | tail -n1 | cut -d" " -f4) name=$(basename "${prop%.*}") echo " Asset(name: '$name', path: '$prop', size: Size($width, $height),)," done echo " };" eyewearProps=assets/props/eyewear/*.png echo " static const eyewearProps = {" for prop in $eyewearProps do width=$(sips -g pixelWidth $prop | tail -n1 | cut -d" " -f4) height=$(sips -g pixelHeight $prop | tail -n1 | cut -d" " -f4) name=$(basename "${prop%.*}") echo " Asset(name: '$name', path: '$prop', size: Size($width, $height),)," done echo " };" foodProps=assets/props/food/*.png echo " static const foodProps = {" for prop in $foodProps do width=$(sips -g pixelWidth $prop | tail -n1 | cut -d" " -f4) height=$(sips -g pixelHeight $prop | tail -n1 | cut -d" " -f4) name=$(basename "${prop%.*}") echo " Asset(name: '$name', path: '$prop', size: Size($width, $height),)," done echo " };" shapeProps=assets/props/shapes/*.png echo " static const shapeProps = {" for prop in $shapeProps do width=$(sips -g pixelWidth $prop | tail -n1 | cut -d" " -f4) height=$(sips -g pixelHeight $prop | tail -n1 | cut -d" " -f4) name=$(basename "${prop%.*}") echo " Asset(name: '$name', path: '$prop', size: Size($width, $height),)," done echo " };" echo " static const props = {...googleProps, ...eyewearProps, ...hatProps, ...foodProps, ...shapeProps};" echo "}"
photobooth/tool/generate_asset_metadata.sh/0
{ "file_path": "photobooth/tool/generate_asset_metadata.sh", "repo_id": "photobooth", "token_count": 1311 }
1,192
export 'cubit/assets_manager_cubit.dart'; export 'views/views.dart';
pinball/lib/assets_manager/assets_manager.dart/0
{ "file_path": "pinball/lib/assets_manager/assets_manager.dart", "repo_id": "pinball", "token_count": 28 }
1,193
// 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 RolloverNoiseBehavior extends ContactBehavior { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); readProvider<PinballAudioPlayer>().play(PinballAudio.rollover); } }
pinball/lib/game/behaviors/rollover_noise_behavior.dart/0
{ "file_path": "pinball/lib/game/behaviors/rollover_noise_behavior.dart", "repo_id": "pinball", "token_count": 144 }
1,194
part of 'backbox_bloc.dart'; /// {@template backbox_state} /// The base state for all [BackboxState]. /// {@endtemplate backbox_state} abstract class BackboxState extends Equatable { /// {@macro backbox_state} const BackboxState(); } /// Loading state for the backbox. class LoadingState extends BackboxState { @override List<Object?> get props => []; } /// {@template leaderboard_success_state} /// State when the leaderboard was successfully loaded. /// {@endtemplate} class LeaderboardSuccessState extends BackboxState { /// {@macro leaderboard_success_state} const LeaderboardSuccessState({required this.entries}); /// Current entries final List<LeaderboardEntryData> entries; @override List<Object?> get props => [entries]; } /// State when the leaderboard failed to load. class LeaderboardFailureState extends BackboxState { @override List<Object?> get props => []; } /// {@template initials_form_state} /// State when the user is inputting their initials. /// {@endtemplate} class InitialsFormState extends BackboxState { /// {@macro initials_form_state} const InitialsFormState({ required this.score, required this.character, }) : super(); /// Player's score. final int score; /// Player's character. final CharacterTheme character; @override List<Object?> get props => [score, character]; } /// {@template initials_success_state} /// State when the score and initials were successfully submitted. /// {@endtemplate} class InitialsSuccessState extends BackboxState { /// {@macro initials_success_state} const InitialsSuccessState({ required this.score, }) : super(); /// Player's score. final int score; @override List<Object?> get props => [score]; } /// State when the initials submission failed. class InitialsFailureState extends BackboxState { const InitialsFailureState({ required this.score, required this.character, }); /// Player's score. final int score; /// Player's character. final CharacterTheme character; @override List<Object?> get props => [score, character]; } /// {@template share_state} /// State when the user is sharing their score. /// {@endtemplate} class ShareState extends BackboxState { /// {@macro share_state} const ShareState({ required this.score, }) : super(); /// Player's score. final int score; @override List<Object?> get props => [score]; }
pinball/lib/game/components/backbox/bloc/backbox_state.dart/0
{ "file_path": "pinball/lib/game/components/backbox/bloc/backbox_state.dart", "repo_id": "pinball", "token_count": 713 }
1,195
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// Handles removing a [Ball] from the game. class DrainingBehavior extends ContactBehavior<Drain> with HasGameRef { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); if (other is! Ball) return; other.removeFromParent(); final ballsLeft = gameRef.descendants().whereType<Ball>().length; if (ballsLeft - 1 == 0) { ancestors() .whereType<FlameBlocProvider<GameBloc, GameState>>() .first .bloc .add(const RoundLost()); } } }
pinball/lib/game/components/drain/behaviors/draining_behavior.dart/0
{ "file_path": "pinball/lib/game/components/drain/behaviors/draining_behavior.dart", "repo_id": "pinball", "token_count": 315 }
1,196
export 'sparky_computer_bonus_behavior.dart';
pinball/lib/game/components/sparky_scorch/behaviors/behaviors.dart/0
{ "file_path": "pinball/lib/game/components/sparky_scorch/behaviors/behaviors.dart", "repo_id": "pinball", "token_count": 17 }
1,197
export 'bonus_animation.dart'; export 'game_hud.dart'; export 'mobile_controls.dart'; export 'mobile_dpad.dart'; export 'play_button_overlay.dart'; export 'replay_button_overlay.dart'; export 'round_count_display.dart'; export 'score_view.dart';
pinball/lib/game/view/widgets/widgets.dart/0
{ "file_path": "pinball/lib/game/view/widgets/widgets.dart", "repo_id": "pinball", "token_count": 94 }
1,198
import 'package:flame/components.dart'; import 'package:flame/flame.dart'; import 'package:flame/sprite.dart'; import 'package:flutter/material.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:pinball_theme/pinball_theme.dart'; /// {@template selected_character} /// Shows an animated version of the character currently selected. /// {@endtemplate} class SelectedCharacter extends StatefulWidget { /// {@macro selected_character} const SelectedCharacter({ Key? key, required this.currentCharacter, }) : super(key: key); /// The character that is selected at the moment. final CharacterTheme currentCharacter; @override State<SelectedCharacter> createState() => _SelectedCharacterState(); /// Returns a list of assets to be loaded. static List<Future Function()> loadAssets() { return [ () => Flame.images.load(const DashTheme().animation.keyName), () => Flame.images.load(const AndroidTheme().animation.keyName), () => Flame.images.load(const DinoTheme().animation.keyName), () => Flame.images.load(const SparkyTheme().animation.keyName), ]; } } class _SelectedCharacterState extends State<SelectedCharacter> with TickerProviderStateMixin { SpriteAnimationController? _controller; @override void initState() { super.initState(); _setupCharacterAnimation(); } @override void didUpdateWidget(covariant SelectedCharacter oldWidget) { super.didUpdateWidget(oldWidget); _setupCharacterAnimation(); } @override void dispose() { _controller?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( children: [ Text( widget.currentCharacter.name, style: Theme.of(context).textTheme.headline2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, ), const SizedBox(height: 10), Expanded( child: LayoutBuilder( builder: (context, constraints) { return SizedBox( width: constraints.maxWidth, height: constraints.maxHeight, child: SpriteAnimationWidget( controller: _controller!, anchor: Anchor.center, ), ); }, ), ), ], ); } void _setupCharacterAnimation() { final spriteSheet = SpriteSheet.fromColumnsAndRows( image: Flame.images.fromCache(widget.currentCharacter.animation.keyName), columns: 12, rows: 6, ); final animation = spriteSheet.createAnimation( row: 0, stepTime: 1 / 12, to: spriteSheet.rows * spriteSheet.columns, ); if (_controller != null) _controller?.dispose(); _controller = SpriteAnimationController(vsync: this, animation: animation) ..forward() ..repeat(); } }
pinball/lib/select_character/view/selected_character.dart/0
{ "file_path": "pinball/lib/select_character/view/selected_character.dart", "repo_id": "pinball", "token_count": 1116 }
1,199
include: package:very_good_analysis/analysis_options.2.4.0.yaml
pinball/packages/geometry/analysis_options.yaml/0
{ "file_path": "pinball/packages/geometry/analysis_options.yaml", "repo_id": "pinball", "token_count": 22 }
1,200
import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:test/test.dart'; void main() { group('LeaderboardEntry', () { const data = <String, dynamic>{ 'playerInitials': 'ABC', 'score': 1500, 'character': 'dash', }; const leaderboardEntry = LeaderboardEntryData( playerInitials: 'ABC', score: 1500, character: CharacterType.dash, ); test('can be instantiated', () { const leaderboardEntry = LeaderboardEntryData.empty; expect(leaderboardEntry, isNotNull); }); test('supports value equality.', () { const leaderboardEntry = LeaderboardEntryData.empty; const leaderboardEntry2 = LeaderboardEntryData.empty; expect(leaderboardEntry, equals(leaderboardEntry2)); }); test('can be converted to json', () { expect(leaderboardEntry.toJson(), equals(data)); }); test('can be obtained from json', () { final leaderboardEntryFrom = LeaderboardEntryData.fromJson(data); expect(leaderboardEntry, equals(leaderboardEntryFrom)); }); }); }
pinball/packages/leaderboard_repository/test/src/models/leaderboard_entry_data_test.dart/0
{ "file_path": "pinball/packages/leaderboard_repository/test/src/models/leaderboard_entry_data_test.dart", "repo_id": "pinball", "token_count": 392 }
1,201
import 'package:bloc/bloc.dart'; part 'android_spaceship_state.dart'; class AndroidSpaceshipCubit extends Cubit<AndroidSpaceshipState> { AndroidSpaceshipCubit() : super(AndroidSpaceshipState.withoutBonus); void onBallContacted() => emit(AndroidSpaceshipState.withBonus); void onBonusAwarded() => emit(AndroidSpaceshipState.withoutBonus); }
pinball/packages/pinball_components/lib/src/components/android_spaceship/cubit/android_spaceship_cubit.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/android_spaceship/cubit/android_spaceship_cubit.dart", "repo_id": "pinball", "token_count": 113 }
1,202
import 'dart:math' as math; import 'package:flame/extensions.dart'; /// {@template board_dimensions} /// Contains various board properties and dimensions for global use. /// {@endtemplate} class BoardDimensions { /// Width and height of the board. static final size = Vector2(101.6, 143.8); /// [Rect] for easier access to board boundaries. static final bounds = Rect.fromCenter( center: Offset.zero, width: size.x, height: size.y, ); /// 3D perspective angle of the board in radians. static final perspectiveAngle = -math.atan(18.6 / bounds.height); /// Factor the board shrinks by from the closest point to the farthest. static const perspectiveShrinkFactor = 0.63; }
pinball/packages/pinball_components/lib/src/components/board_dimensions.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/board_dimensions.dart", "repo_id": "pinball", "token_count": 215 }
1,203
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class DashBumperBallContactBehavior extends ContactBehavior<DashBumper> { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); if (other is! Ball) return; readBloc<DashBumpersCubit, DashBumpersState>().onBallContacted(parent.id); } }
pinball/packages/pinball_components/lib/src/components/dash_bumper/behaviors/dash_bumper_ball_contact_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/dash_bumper/behaviors/dash_bumper_ball_contact_behavior.dart", "repo_id": "pinball", "token_count": 158 }
1,204
import 'dart:async'; import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flutter/foundation.dart'; import 'package:pinball_components/pinball_components.dart'; export 'behaviors/behaviors.dart'; export 'cubit/flipper_cubit.dart'; /// {@template flipper} /// A bat, typically found in pairs at the bottom of the board. /// /// [Flipper] can be controlled by the player in an arc motion. /// {@endtemplate flipper} class Flipper extends BodyComponent with KeyboardHandler, InitialPosition { /// {@macro flipper} Flipper({ required this.side, }) : super( renderBody: false, children: [ _FlipperSpriteComponent(side: side), FlipperJointingBehavior(), FlameBlocProvider<FlipperCubit, FlipperState>( create: FlipperCubit.new, children: [ FlipperMovingBehavior(strength: 90), FlipperNoiseBehavior(), ], ), ], ); /// Creates a [Flipper] without any children. /// /// This can be used for testing [Flipper]'s behaviors in isolation. @visibleForTesting Flipper.test({required this.side}); /// The size of the [Flipper]. static final size = Vector2(13.5, 4.3); /// Whether the [Flipper] is on the left or right side of the board. /// /// A [Flipper] with [BoardSide.left] has a counter-clockwise arc motion, /// whereas a [Flipper] with [BoardSide.right] has a clockwise arc motion. final BoardSide side; List<FixtureDef> _createFixtureDefs() { final direction = side.direction; final assetShadow = Flipper.size.x * 0.012 * -direction; final size = Vector2( Flipper.size.x - (assetShadow * 2), Flipper.size.y, ); final bigCircleShape = CircleShape()..radius = size.y / 2 - 0.2; bigCircleShape.position.setValues( ((size.x / 2) * direction) + (bigCircleShape.radius * -direction) + assetShadow, 0, ); final smallCircleShape = CircleShape()..radius = size.y * 0.23; smallCircleShape.position.setValues( ((size.x / 2) * -direction) + (smallCircleShape.radius * direction) - assetShadow, 0, ); final trapeziumVertices = side.isLeft ? [ Vector2(bigCircleShape.position.x, bigCircleShape.radius), Vector2(smallCircleShape.position.x, smallCircleShape.radius), Vector2(smallCircleShape.position.x, -smallCircleShape.radius), Vector2(bigCircleShape.position.x, -bigCircleShape.radius), ] : [ Vector2(smallCircleShape.position.x, smallCircleShape.radius), Vector2(bigCircleShape.position.x, bigCircleShape.radius), Vector2(bigCircleShape.position.x, -bigCircleShape.radius), Vector2(smallCircleShape.position.x, -smallCircleShape.radius), ]; final trapezium = PolygonShape()..set(trapeziumVertices); return [ FixtureDef(bigCircleShape), FixtureDef(smallCircleShape), FixtureDef( trapezium, density: 50, friction: .1, ), ]; } @override Body createBody() { final bodyDef = BodyDef( position: initialPosition, gravityScale: Vector2.zero(), type: BodyType.dynamic, ); final body = world.createBody(bodyDef); _createFixtureDefs().forEach(body.createFixture); return body; } } class _FlipperSpriteComponent extends SpriteComponent with HasGameRef { _FlipperSpriteComponent({required BoardSide side}) : _side = side, super(anchor: Anchor.center); final BoardSide _side; @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( (_side.isLeft) ? Assets.images.flipper.left.keyName : Assets.images.flipper.right.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; } }
pinball/packages/pinball_components/lib/src/components/flipper/flipper.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/flipper/flipper.dart", "repo_id": "pinball", "token_count": 1696 }
1,205
part of 'kicker_cubit.dart'; enum KickerState { lit, dimmed, }
pinball/packages/pinball_components/lib/src/components/kicker/cubit/kicker_state.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/kicker/cubit/kicker_state.dart", "repo_id": "pinball", "token_count": 32 }
1,206
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flutter/services.dart'; import 'package:pinball_components/pinball_components.dart'; /// Allows controlling the [Plunger]'s movement with keyboard input. class PlungerKeyControllingBehavior extends Component with KeyboardHandler, FlameBlocReader<PlungerCubit, PlungerState> { /// The [LogicalKeyboardKey]s that will control the [Plunger]. /// /// [onKeyEvent] method listens to when one of these keys is pressed. static const List<LogicalKeyboardKey> _keys = [ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.space, LogicalKeyboardKey.keyS, ]; @override bool onKeyEvent( RawKeyEvent event, Set<LogicalKeyboardKey> keysPressed, ) { if (!_keys.contains(event.logicalKey)) return true; if (event is RawKeyDownEvent) { bloc.pulled(); } else if (event is RawKeyUpEvent) { bloc.released(); } return false; } }
pinball/packages/pinball_components/lib/src/components/plunger/behaviors/plunger_key_controlling_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/plunger/behaviors/plunger_key_controlling_behavior.dart", "repo_id": "pinball", "token_count": 348 }
1,207
import 'package:flame/components.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// {@template skill_shot_blinking_behavior} /// Makes a [SkillShot] blink between [SkillShotSpriteState.lit] and /// [SkillShotSpriteState.dimmed] for a set amount of blinks. /// {@endtemplate} class SkillShotBlinkingBehavior extends TimerComponent with ParentIsA<SkillShot> { /// {@macro skill_shot_blinking_behavior} SkillShotBlinkingBehavior() : super(period: 0.15); final _maxBlinks = 4; int _blinks = 0; void _onNewState(SkillShotState state) { if (state.isBlinking) { timer ..reset() ..start(); } } @override Future<void> onLoad() async { await super.onLoad(); timer.stop(); parent.bloc.stream.listen(_onNewState); } @override void onTick() { super.onTick(); if (_blinks != _maxBlinks * 2) { parent.bloc.switched(); _blinks++; } else { _blinks = 0; timer.stop(); parent.bloc.onBlinkingFinished(); } } }
pinball/packages/pinball_components/lib/src/components/skill_shot/behaviors/skill_shot_blinking_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/skill_shot/behaviors/skill_shot_blinking_behavior.dart", "repo_id": "pinball", "token_count": 430 }
1,208
part of 'sparky_bumper_cubit.dart'; enum SparkyBumperState { lit, dimmed, }
pinball/packages/pinball_components/lib/src/components/sparky_bumper/cubit/sparky_bumper_state.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/sparky_bumper/cubit/sparky_bumper_state.dart", "repo_id": "pinball", "token_count": 38 }
1,209
include: package:very_good_analysis/analysis_options.2.4.0.yaml linter: rules: public_member_api_docs: false
pinball/packages/pinball_components/sandbox/analysis_options.yaml/0
{ "file_path": "pinball/packages/pinball_components/sandbox/analysis_options.yaml", "repo_id": "pinball", "token_count": 44 }
1,210
import 'package:flame/components.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_theme/pinball_theme.dart' as theme; import 'package:sandbox/common/common.dart'; class BallBoosterGame extends LineGame { BallBoosterGame() : super( imagesFileNames: [ theme.Assets.images.android.ball.keyName, theme.Assets.images.dash.ball.keyName, theme.Assets.images.dino.ball.keyName, theme.Assets.images.sparky.ball.keyName, Assets.images.ball.flameEffect.keyName, ], ); static const description = ''' Shows how a Ball with a boost works. - Drag to launch a boosted Ball. '''; @override void onLine(Vector2 line) { final ball = Ball(); final impulse = line * -1 * 20; ball.add(BallTurboChargingBehavior(impulse: impulse)); add(ball); } }
pinball/packages/pinball_components/sandbox/lib/stories/ball/ball_booster_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/ball/ball_booster_game.dart", "repo_id": "pinball", "token_count": 371 }
1,211
import 'package:flame/components.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:sandbox/common/common.dart'; class ErrorComponentGame extends AssetsGame { ErrorComponentGame({required this.text}); static const description = 'Shows how ErrorComponents are rendered.'; final String text; @override Future<void> onLoad() async { camera.followVector2(Vector2.zero()); await add(ErrorComponent(label: text)); await add( ErrorComponent.bold( label: text, position: Vector2(0, 10), ), ); } }
pinball/packages/pinball_components/sandbox/lib/stories/error_component/error_component_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/error_component/error_component_game.dart", "repo_id": "pinball", "token_count": 201 }
1,212
import 'package:dashbook/dashbook.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/multipliers/multipliers_game.dart'; void addMultipliersStories(Dashbook dashbook) { dashbook.storiesOf('Multipliers').addGame( title: 'Multipliers', description: MultipliersGame.description, gameBuilder: (_) => MultipliersGame(), ); }
pinball/packages/pinball_components/sandbox/lib/stories/multipliers/stories.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/multipliers/stories.dart", "repo_id": "pinball", "token_count": 141 }
1,213
// 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:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:pinball_theme/pinball_theme.dart' as theme; import '../../../helpers/helpers.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final assets = [ theme.Assets.images.android.ball.keyName, theme.Assets.images.dash.ball.keyName, theme.Assets.images.dino.ball.keyName, theme.Assets.images.sparky.ball.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); group('Ball', () { test( 'can be instantiated', () { expect(Ball(), isA<Ball>()); expect(Ball.test(), isA<Ball>()); }, ); flameTester.test( 'loads correctly', (game) async { final ball = Ball(); await game.ready(); await game.ensureAdd(ball); expect(game.contains(ball), isTrue); }, ); flameTester.test( 'has only one SpriteComponent', (game) async { final ball = Ball(); await game.ready(); await game.ensureAdd(ball); expect( ball.descendants().whereType<SpriteComponent>().length, equals(1), ); }, ); flameTester.test( 'BallSpriteComponent changes sprite onNewState', (game) async { final ball = Ball(); await game.ready(); await game.ensureAdd(ball); final ballSprite = ball.descendants().whereType<BallSpriteComponent>().single; final originalSprite = ballSprite.sprite; ballSprite.onNewState( const BallState(characterTheme: theme.DinoTheme()), ); await game.ready(); final newSprite = ballSprite.sprite; expect(newSprite != originalSprite, isTrue); }, ); group('adds', () { flameTester.test('a BallScalingBehavior', (game) async { final ball = Ball(); await game.ensureAdd(ball); expect( ball.descendants().whereType<BallScalingBehavior>().length, equals(1), ); }); flameTester.test('a BallGravitatingBehavior', (game) async { final ball = Ball(); await game.ensureAdd(ball); expect( ball.descendants().whereType<BallGravitatingBehavior>().length, equals(1), ); }); }); group('body', () { flameTester.test( 'is dynamic', (game) async { final ball = Ball(); await game.ensureAdd(ball); expect(ball.body.bodyType, equals(BodyType.dynamic)); }, ); group('can be moved', () { flameTester.test('by its weight', (game) async { final ball = Ball(); await game.ensureAdd(ball); game.update(1); expect(ball.body.position, isNot(equals(ball.initialPosition))); }); flameTester.test('by applying velocity', (game) async { final ball = Ball(); await game.ensureAdd(ball); ball.body.gravityScale = Vector2.zero(); ball.body.linearVelocity.setValues(10, 10); game.update(1); expect(ball.body.position, isNot(equals(ball.initialPosition))); }); }); }); group('fixture', () { flameTester.test( 'exists', (game) async { final ball = Ball(); await game.ensureAdd(ball); expect(ball.body.fixtures[0], isA<Fixture>()); }, ); flameTester.test( 'is dense', (game) async { final ball = Ball(); await game.ensureAdd(ball); final fixture = ball.body.fixtures[0]; expect(fixture.density, greaterThan(0)); }, ); flameTester.test( 'shape is circular', (game) async { final ball = Ball(); await game.ensureAdd(ball); final fixture = ball.body.fixtures[0]; expect(fixture.shape.shapeType, equals(ShapeType.circle)); expect(fixture.shape.radius, equals(2.065)); }, ); flameTester.test( 'has Layer.all as default filter maskBits', (game) async { final ball = Ball(); await game.ready(); await game.ensureAdd(ball); await game.ready(); final fixture = ball.body.fixtures[0]; expect(fixture.filterData.maskBits, equals(Layer.board.maskBits)); }, ); }); group('stop', () { group("can't be moved", () { flameTester.test('by its weight', (game) async { final ball = Ball(); await game.ensureAdd(ball); ball.stop(); game.update(1); expect(ball.body.position, equals(ball.initialPosition)); }); }); }); group('resume', () { group('can move', () { flameTester.test( 'by its weight when previously stopped', (game) async { final ball = Ball(); await game.ensureAdd(ball); ball.stop(); ball.resume(); game.update(1); expect(ball.body.position, isNot(equals(ball.initialPosition))); }, ); flameTester.test( 'by applying velocity when previously stopped', (game) async { final ball = Ball(); await game.ensureAdd(ball); ball.stop(); ball.resume(); ball.body.gravityScale = Vector2.zero(); ball.body.linearVelocity.setValues(10, 10); game.update(1); expect(ball.body.position, isNot(equals(ball.initialPosition))); }, ); }); }); }); }
pinball/packages/pinball_components/test/src/components/ball/ball_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/ball/ball_test.dart", "repo_id": "pinball", "token_count": 2784 }
1,214
// ignore_for_file: cascade_invocations import 'dart:async'; 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/chrome_dino/behaviors/behaviors.dart'; import 'package:pinball_theme/pinball_theme.dart' as theme; import '../../../../helpers/helpers.dart'; class _MockChromeDinoCubit extends Mock implements ChromeDinoCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final assets = [ theme.Assets.images.dash.ball.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); group( 'ChromeDinoSpittingBehavior', () { test('can be instantiated', () { expect( ChromeDinoSpittingBehavior(), isA<ChromeDinoSpittingBehavior>(), ); }); group('on the next time the mouth opens and status is chomping', () { flameTester.test( 'sets ball sprite to visible and sets a linear velocity', (game) async { final ball = Ball(); final behavior = ChromeDinoSpittingBehavior(); final bloc = _MockChromeDinoCubit(); final streamController = StreamController<ChromeDinoState>(); final chompingState = ChromeDinoState( status: ChromeDinoStatus.chomping, isMouthOpen: true, ball: ball, ); whenListen( bloc, streamController.stream, initialState: chompingState, ); final chromeDino = ChromeDino.test(bloc: bloc); await chromeDino.add(behavior); await game.ensureAddAll([chromeDino, ball]); streamController.add(chompingState.copyWith(isMouthOpen: false)); streamController.add(chompingState.copyWith(isMouthOpen: true)); await game.ready(); game .descendants() .whereType<TimerComponent>() .single .timer .onTick!(); expect( ball .descendants() .whereType<SpriteComponent>() .single .getOpacity(), equals(1), ); expect(ball.body.linearVelocity, equals(Vector2(-50, 0))); }, ); flameTester.test( 'calls onSpit', (game) async { final ball = Ball(); final behavior = ChromeDinoSpittingBehavior(); final bloc = _MockChromeDinoCubit(); final streamController = StreamController<ChromeDinoState>(); final chompingState = ChromeDinoState( status: ChromeDinoStatus.chomping, isMouthOpen: true, ball: ball, ); whenListen( bloc, streamController.stream, initialState: chompingState, ); final chromeDino = ChromeDino.test(bloc: bloc); await chromeDino.add(behavior); await game.ensureAddAll([chromeDino, ball]); streamController.add(chompingState.copyWith(isMouthOpen: false)); streamController.add(chompingState.copyWith(isMouthOpen: true)); await game.ready(); game .descendants() .whereType<TimerComponent>() .single .timer .onTick!(); verify(bloc.onSpit).called(1); }, ); }); }, ); }
pinball/packages/pinball_components/test/src/components/chrome_dino/behaviors/chrome_dino_spitting_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/chrome_dino/behaviors/chrome_dino_spitting_behavior_test.dart", "repo_id": "pinball", "token_count": 1868 }
1,215
// 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'; import 'package:pinball_components/src/components/flapper/behaviors/behaviors.dart'; import 'package:pinball_flame/pinball_flame.dart'; import '../../../helpers/helpers.dart'; void main() { group('Flapper', () { TestWidgetsFlutterBinding.ensureInitialized(); final assets = [ Assets.images.flapper.flap.keyName, Assets.images.flapper.backSupport.keyName, Assets.images.flapper.frontSupport.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); flameTester.test('loads correctly', (game) async { final component = Flapper(); await game.ensureAdd(component); expect(game.contains(component), isTrue); }); flameTester.testGameWidget( 'renders correctly', setUp: (game, tester) async { await game.images.loadAll(assets); final canvas = ZCanvasComponent(children: [Flapper()]); await game.ensureAdd(canvas); game.camera ..followVector2(Vector2(3, -70)) ..zoom = 25; await tester.pump(); }, verify: (game, tester) async { const goldenFilePath = '../golden/flapper/'; final flapSpriteAnimationComponent = game .descendants() .whereType<FlapSpriteAnimationComponent>() .first ..playing = true; final animationDuration = flapSpriteAnimationComponent.animation!.totalDuration(); await expectLater( find.byGame<TestGame>(), matchesGoldenFile('${goldenFilePath}start.png'), ); game.update(animationDuration * 0.25); await tester.pump(); await expectLater( find.byGame<TestGame>(), matchesGoldenFile('${goldenFilePath}middle.png'), ); game.update(animationDuration * 0.75); await tester.pump(); await expectLater( find.byGame<TestGame>(), matchesGoldenFile('${goldenFilePath}end.png'), ); }, ); flameTester.test('adds a FlapperSpinningBehavior to FlapperEntrance', (game) async { final flapper = Flapper(); await game.ensureAdd(flapper); final flapperEntrance = flapper.firstChild<FlapperEntrance>()!; expect( flapperEntrance.firstChild<FlapperSpinningBehavior>(), isNotNull, ); }); flameTester.test( 'flap stops animating after animation completes', (game) async { final flapper = Flapper(); await game.ensureAdd(flapper); final flapSpriteAnimationComponent = flapper.firstChild<FlapSpriteAnimationComponent>()!; flapSpriteAnimationComponent.playing = true; game.update( flapSpriteAnimationComponent.animation!.totalDuration() + 0.1, ); expect(flapSpriteAnimationComponent.playing, isFalse); }, ); }); }
pinball/packages/pinball_components/test/src/components/flapper/flapper_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/flapper/flapper_test.dart", "repo_id": "pinball", "token_count": 1312 }
1,216
// ignore_for_file: cascade_invocations import 'package:bloc_test/bloc_test.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/kicker/behaviors/behaviors.dart'; import '../../../../helpers/helpers.dart'; class _MockKickerCubit extends Mock implements KickerCubit {} class _MockBall extends Mock implements Ball {} class _MockContact extends Mock implements Contact {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(TestGame.new); group( 'KickerBallContactBehavior', () { test('can be instantiated', () { expect( KickerBallContactBehavior(), isA<KickerBallContactBehavior>(), ); }); flameTester.test( 'beginContact emits onBallContacted when contacts with a ball', (game) async { final behavior = KickerBallContactBehavior(); final bloc = _MockKickerCubit(); whenListen( bloc, const Stream<KickerState>.empty(), initialState: KickerState.lit, ); final kicker = Kicker.test( side: BoardSide.left, bloc: bloc, ); await kicker.add(behavior); await game.ensureAdd(kicker); behavior.beginContact(_MockBall(), _MockContact()); verify(kicker.bloc.onBallContacted).called(1); }, ); }, ); }
pinball/packages/pinball_components/test/src/components/kicker/behaviors/kicker_ball_contact_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/kicker/behaviors/kicker_ball_contact_behavior_test.dart", "repo_id": "pinball", "token_count": 694 }
1,217
// ignore_for_file: cascade_invocations 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_audio/pinball_audio.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class _TestGame extends Forge2DGame { Future<void> pump( Component child, { PinballAudioPlayer? pinballAudioPlayer, PlungerCubit? plungerBloc, }) async { final parent = Component(); await ensureAdd(parent); return parent.ensureAdd( FlameProvider<PinballAudioPlayer>.value( pinballAudioPlayer ?? _MockPinballAudioPlayer(), children: [ FlameBlocProvider<PlungerCubit, PlungerState>.value( value: plungerBloc ?? PlungerCubit(), children: [child], ), ], ), ); } } class _MockPinballAudioPlayer extends Mock implements PinballAudioPlayer {} class _MockPlungerCubit extends Mock implements PlungerCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(_TestGame.new); group('PlungerNoiseBehavior', () { late PinballAudioPlayer audioPlayer; setUp(() { audioPlayer = _MockPinballAudioPlayer(); }); test('can be instantiated', () { expect( PlungerNoiseBehavior(), isA<PlungerNoiseBehavior>(), ); }); flameTester.test('can be loaded', (game) async { final behavior = PlungerNoiseBehavior(); await game.pump(behavior); expect(game.descendants(), contains(behavior)); }); flameTester.test( 'plays the correct sound when released', (game) async { final plungerBloc = _MockPlungerCubit(); final streamController = StreamController<PlungerState>(); whenListen<PlungerState>( plungerBloc, streamController.stream, initialState: PlungerState.pulling, ); final behavior = PlungerNoiseBehavior(); await game.pump( behavior, pinballAudioPlayer: audioPlayer, plungerBloc: plungerBloc, ); streamController.add(PlungerState.releasing); await Future<void>.delayed(Duration.zero); verify(() => audioPlayer.play(PinballAudio.launcher)).called(1); }, ); }); }
pinball/packages/pinball_components/test/src/components/plunger/behaviors/plunger_noise_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/plunger/behaviors/plunger_noise_behavior_test.dart", "repo_id": "pinball", "token_count": 1048 }
1,218
// 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'; import '../../helpers/helpers.dart'; void main() { group('SpaceshipRail', () { TestWidgetsFlutterBinding.ensureInitialized(); final assets = [ Assets.images.android.rail.main.keyName, Assets.images.android.rail.exit.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); flameTester.test('loads correctly', (game) async { final component = SpaceshipRail(); await game.ensureAdd(component); expect(game.contains(component), isTrue); }); flameTester.testGameWidget( 'renders correctly', setUp: (game, tester) async { await game.images.loadAll(assets); await game.ensureAdd(SpaceshipRail()); await tester.pump(); game.camera.followVector2(Vector2.zero()); game.camera.zoom = 8; }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/spaceship_rail.png'), ); }, ); }); }
pinball/packages/pinball_components/test/src/components/spaceship_rail_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/spaceship_rail_test.dart", "repo_id": "pinball", "token_count": 512 }
1,219
include: package:very_good_analysis/analysis_options.2.4.0.yaml
pinball/packages/pinball_flame/analysis_options.yaml/0
{ "file_path": "pinball/packages/pinball_flame/analysis_options.yaml", "repo_id": "pinball", "token_count": 22 }
1,220
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:geometry/geometry.dart'; /// {@template bezier_curve_shape} /// Creates a bezier curve. /// {@endtemplate} class BezierCurveShape extends ChainShape { /// {@macro bezier_curve_shape} BezierCurveShape({ required this.controlPoints, }) { createChain(calculateBezierCurve(controlPoints: controlPoints)); } /// Specifies the control points of the curve. /// /// First and last [controlPoints] set the beginning and end of the curve, /// inner points between them set its final shape. final List<Vector2> controlPoints; }
pinball/packages/pinball_flame/lib/src/shapes/bezier_curve_shape.dart/0
{ "file_path": "pinball/packages/pinball_flame/lib/src/shapes/bezier_curve_shape.dart", "repo_id": "pinball", "token_count": 201 }
1,221