text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
packages/packages/rfw/example/local/android/gradle.properties/0
{ "file_path": "packages/packages/rfw/example/local/android/gradle.properties", "repo_id": "packages", "token_count": 31 }
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. // This file is hand-formatted. import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:rfw/formats.dart'; // This is a number that requires more than 32 bits but less than 53 bits, so // that it works in a JS Number and tests the logic that parses 64 bit ints as // two separate 32 bit ints. const int largeNumber = 9007199254730661; void main() { testWidgets('String example', (WidgetTester tester) async { final Uint8List bytes = encodeDataBlob('Hello'); expect(bytes, <int>[ 0xFE, 0x52, 0x57, 0x44, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x65, 0x6C, 0x6C, 0x6F ]); final Object value = decodeDataBlob(bytes); expect(value, isA<String>()); expect(value, 'Hello'); }); testWidgets('Big integer example', (WidgetTester tester) async { // This value is intentionally inside the JS Number range but above 2^32. final Uint8List bytes = encodeDataBlob(largeNumber); expect(bytes, <int>[ 0xfe, 0x52, 0x57, 0x44, 0x02, 0xa5, 0xd7, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, ]); final Object value = decodeDataBlob(bytes); expect(value, isA<int>()); expect(value, largeNumber); }); testWidgets('Big negative integer example', (WidgetTester tester) async { final Uint8List bytes = encodeDataBlob(-largeNumber); expect(bytes, <int>[ 0xfe, 0x52, 0x57, 0x44, 0x02, 0x5b, 0x28, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, ]); final Object value = decodeDataBlob(bytes); expect(value, isA<int>()); expect(value, -largeNumber); }); testWidgets('Small integer example', (WidgetTester tester) async { final Uint8List bytes = encodeDataBlob(1); expect(bytes, <int>[ 0xfe, 0x52, 0x57, 0x44, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]); final Object value = decodeDataBlob(bytes); expect(value, isA<int>()); expect(value, 1); }); testWidgets('Small negative integer example', (WidgetTester tester) async { final Uint8List bytes = encodeDataBlob(-1); expect(bytes, <int>[ 0xfe, 0x52, 0x57, 0x44, 0x02, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, ]); final Object value = decodeDataBlob(bytes); expect(value, isA<int>()); expect(value, -1); }); testWidgets('Zero integer example', (WidgetTester tester) async { // This value is intentionally inside the JS Number range but above 2^32. final Uint8List bytes = encodeDataBlob(0); expect(bytes, <int>[ 0xfe, 0x52, 0x57, 0x44, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]); final Object value = decodeDataBlob(bytes); expect(value, isA<int>()); expect(value, 0); }); testWidgets('Map example', (WidgetTester tester) async { final Uint8List bytes = encodeDataBlob(const <String, Object?>{ 'a': 15 }); expect(bytes, <int>[ 0xFE, 0x52, 0x57, 0x44, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x02, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]); final Object value = decodeDataBlob(bytes); expect(value, isA<DynamicMap>()); expect(value, const <String, Object?>{ 'a': 15 }); }); testWidgets('Signature check in decoders', (WidgetTester tester) async { try { decodeDataBlob(Uint8List.fromList(<int>[ 0xFE, 0x52, 0x46, 0x57, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x65, 0x6C, 0x6C, 0x6F ])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('File signature mismatch. Expected FE 52 57 44 but found FE 52 46 57.')); } try { decodeLibraryBlob(Uint8List.fromList(<int>[ 0xFE, 0x52, 0x57, 0x44, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x65, 0x6C, 0x6C, 0x6F ])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('File signature mismatch. Expected FE 52 46 57 but found FE 52 57 44.')); } }); testWidgets('Trailing byte check', (WidgetTester tester) async { try { decodeDataBlob(Uint8List.fromList(<int>[ 0xFE, 0x52, 0x57, 0x44, 0x00, 0x00 ])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Unexpected trailing bytes after value.')); } try { decodeLibraryBlob(Uint8List.fromList(<int>[ 0xFE, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Unexpected trailing bytes after constructors.')); } }); testWidgets('Incomplete files in signatures', (WidgetTester tester) async { try { decodeDataBlob(Uint8List.fromList(<int>[ 0xFE, 0x52, 0x57 ])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Could not read byte at offset 3: unexpected end of file.')); } try { decodeLibraryBlob(Uint8List.fromList(<int>[ 0xFE, 0x52, 0x46 ])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Could not read byte at offset 3: unexpected end of file.')); } }); testWidgets('Incomplete files after signatures', (WidgetTester tester) async { try { decodeDataBlob(Uint8List.fromList(<int>[ 0xFE, 0x52, 0x57, 0x44 ])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Could not read byte at offset 4: unexpected end of file.')); } try { decodeLibraryBlob(Uint8List.fromList(<int>[ 0xFE, 0x52, 0x46, 0x57 ])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Could not read int64 at offset 4: unexpected end of file.')); } }); testWidgets('Invalid value tag', (WidgetTester tester) async { try { decodeDataBlob(Uint8List.fromList(<int>[ 0xFE, 0x52, 0x57, 0x44, 0xCC ])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Unrecognized data type 0xCC while decoding blob.')); } }); testWidgets('Library encoder smoke test', (WidgetTester tester) async { final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary(<Import>[], <WidgetDeclaration>[])); expect(bytes, <int>[ 0xFE, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); expect(value.widgets, isEmpty); }); testWidgets('Library encoder: imports', (WidgetTester tester) async { final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary(<Import>[Import(LibraryName(<String>['a']))], <WidgetDeclaration>[])); expect(bytes, <int>[ 0xFE, 0x52, 0x46, 0x57, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, hasLength(1)); expect(value.imports.single.name, const LibraryName(<String>['a'])); expect(value.widgets, isEmpty); }); testWidgets('Doubles', (WidgetTester tester) async { final Uint8List bytes = encodeDataBlob(0.25); expect(bytes, <int>[ 0xFE, 0x52, 0x57, 0x44, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0x3F ]); final Object value = decodeDataBlob(bytes); expect(value, isA<double>()); expect(value, 0.25); }); testWidgets('Library decoder: invalid widget declaration root', (WidgetTester tester) async { final Uint8List bytes = Uint8List.fromList(<int>[ 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEF, ]); try { decodeLibraryBlob(bytes); } on FormatException catch (e) { expect('$e', contains('Unrecognized data type 0xEF while decoding widget declaration root.')); } }); testWidgets('Library encoder: args references', (WidgetTester tester) async { final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary(<Import>[], <WidgetDeclaration>[ WidgetDeclaration('a', null, ConstructorCall('b', <String, Object?>{ 'c': <Object?>[ ArgsReference(<Object>['d', 5]) ] })), ])); expect(bytes, <int>[ 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x02, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); expect(value.widgets, hasLength(1)); expect(value.widgets.first.name, 'a'); expect(value.widgets.first.initialState, isNull); expect(value.widgets.first.root, isA<ConstructorCall>()); expect((value.widgets.first.root as ConstructorCall).name, 'b'); expect((value.widgets.first.root as ConstructorCall).arguments, hasLength(1)); expect((value.widgets.first.root as ConstructorCall).arguments.keys, <Object?>['c']); expect((value.widgets.first.root as ConstructorCall).arguments['c'], hasLength(1)); expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0], isA<ArgsReference>()); expect((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as ArgsReference).parts, hasLength(2)); expect((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as ArgsReference).parts[0], 'd'); expect((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as ArgsReference).parts[1], 5); }); testWidgets('Library encoder: invalid args references', (WidgetTester tester) async { try { encodeLibraryBlob(const RemoteWidgetLibrary(<Import>[], <WidgetDeclaration>[ WidgetDeclaration('a', null, ConstructorCall('b', <String, Object?>{ 'c': <Object?>[ ArgsReference(<Object>[false]) ] })), ])); } on StateError catch (e) { expect('$e', contains('Unexpected type bool while encoding blob.')); } }); testWidgets('Library decoder: invalid args references', (WidgetTester tester) async { final Uint8List bytes = Uint8List.fromList(<int>[ 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAC, ]); try { decodeLibraryBlob(bytes); } on FormatException catch (e) { expect('$e', contains('Invalid reference type 0xAC while decoding blob.')); } }); testWidgets('Library encoder: switches', (WidgetTester tester) async { final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary(<Import>[], <WidgetDeclaration>[ WidgetDeclaration('a', null, Switch('b', <Object?, Object>{ null: 'c' })), ])); expect(bytes, <int>[ 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); expect(value.widgets, hasLength(1)); expect(value.widgets.first.name, 'a'); expect(value.widgets.first.initialState, isNull); expect(value.widgets.first.root, isA<Switch>()); expect((value.widgets.first.root as Switch).input, 'b'); expect((value.widgets.first.root as Switch).outputs, hasLength(1)); expect((value.widgets.first.root as Switch).outputs.keys, <Object?>[null]); expect((value.widgets.first.root as Switch).outputs[null], 'c'); }); testWidgets('Library encoder: switches', (WidgetTester tester) async { final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary(<Import>[], <WidgetDeclaration>[ WidgetDeclaration('a', null, Switch('b', <Object?, Object>{ 'c': 'd' })), ])); expect(bytes, <int>[ 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); expect(value.widgets, hasLength(1)); expect(value.widgets.first.name, 'a'); expect(value.widgets.first.initialState, isNull); expect(value.widgets.first.root, isA<Switch>()); expect((value.widgets.first.root as Switch).input, 'b'); expect((value.widgets.first.root as Switch).outputs, hasLength(1)); expect((value.widgets.first.root as Switch).outputs.keys, <Object?>['c']); expect((value.widgets.first.root as Switch).outputs['c'], 'd'); }); testWidgets('Bools', (WidgetTester tester) async { final Uint8List bytes = encodeDataBlob(const <Object?>[ false, true ]); expect(bytes, <int>[ 0xFE, 0x52, 0x57, 0x44, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, ]); final Object value = decodeDataBlob(bytes); expect(value, isA<DynamicList>()); expect(value, const <Object?>{ false, true }); }); testWidgets('Library encoder: loops', (WidgetTester tester) async { final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary(<Import>[], <WidgetDeclaration>[ WidgetDeclaration('a', null, ConstructorCall('b', <String, Object?>{ 'c': <Object?>[ Loop(<Object?>[], ConstructorCall('d', <String, Object?>{ 'e': LoopReference(0, <Object>[]) })), ] })), ])); expect(bytes, <int>[ 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); expect(value.widgets, hasLength(1)); expect(value.widgets.first.name, 'a'); expect(value.widgets.first.initialState, isNull); expect(value.widgets.first.root, isA<ConstructorCall>()); expect((value.widgets.first.root as ConstructorCall).name, 'b'); expect((value.widgets.first.root as ConstructorCall).arguments, hasLength(1)); expect((value.widgets.first.root as ConstructorCall).arguments.keys, <Object?>['c']); expect((value.widgets.first.root as ConstructorCall).arguments['c'], hasLength(1)); expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0], isA<Loop>()); expect((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop).input, isEmpty); expect((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop).output, isA<ConstructorCall>()); expect(((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop).output as ConstructorCall).name, 'd'); expect(((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop).output as ConstructorCall).arguments, hasLength(1)); expect(((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop).output as ConstructorCall).arguments['e'], isA<LoopReference>()); expect((((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop).output as ConstructorCall).arguments['e']! as LoopReference).loop, 0); expect((((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop).output as ConstructorCall).arguments['e']! as LoopReference).parts, isEmpty); }); testWidgets('Library encoder: data references', (WidgetTester tester) async { final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary(<Import>[], <WidgetDeclaration>[ WidgetDeclaration('a', null, ConstructorCall('b', <String, Object?>{ 'c': DataReference(<Object>['d']) })), ])); expect(bytes, <int>[ 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x0B, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); expect(value.widgets, hasLength(1)); expect(value.widgets.first.name, 'a'); expect(value.widgets.first.initialState, isNull); expect(value.widgets.first.root, isA<ConstructorCall>()); expect((value.widgets.first.root as ConstructorCall).name, 'b'); expect((value.widgets.first.root as ConstructorCall).arguments, hasLength(1)); expect((value.widgets.first.root as ConstructorCall).arguments.keys, <Object?>['c']); expect((value.widgets.first.root as ConstructorCall).arguments['c'], isA<DataReference>()); expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as DataReference).parts, const <Object>[ 'd' ]); }); testWidgets('Library encoder: state references', (WidgetTester tester) async { final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary(<Import>[], <WidgetDeclaration>[ WidgetDeclaration('a', null, ConstructorCall('b', <String, Object?>{ 'c': StateReference(<Object>['d']) })), ])); expect(bytes, <int>[ 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x0D, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); expect(value.widgets, hasLength(1)); expect(value.widgets.first.name, 'a'); expect(value.widgets.first.initialState, isNull); expect(value.widgets.first.root, isA<ConstructorCall>()); expect((value.widgets.first.root as ConstructorCall).name, 'b'); expect((value.widgets.first.root as ConstructorCall).arguments, hasLength(1)); expect((value.widgets.first.root as ConstructorCall).arguments.keys, <Object?>['c']); expect((value.widgets.first.root as ConstructorCall).arguments['c'], isA<StateReference>()); expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as StateReference).parts, const <Object>[ 'd' ]); }); testWidgets('Library encoder: event handler', (WidgetTester tester) async { final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary(<Import>[], <WidgetDeclaration>[ WidgetDeclaration('a', null, ConstructorCall('b', <String, Object?>{ 'c': EventHandler('d', <String, Object?>{}) })), ])); expect(bytes, <int>[ 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x0E, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); expect(value.widgets, hasLength(1)); expect(value.widgets.first.name, 'a'); expect(value.widgets.first.initialState, isNull); expect(value.widgets.first.root, isA<ConstructorCall>()); expect((value.widgets.first.root as ConstructorCall).name, 'b'); expect((value.widgets.first.root as ConstructorCall).arguments, hasLength(1)); expect((value.widgets.first.root as ConstructorCall).arguments.keys, <Object?>['c']); expect((value.widgets.first.root as ConstructorCall).arguments['c'], isA<EventHandler>()); expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as EventHandler).eventName, 'd'); expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as EventHandler).eventArguments, isEmpty); }); testWidgets('Library encoder: state setter', (WidgetTester tester) async { final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary(<Import>[], <WidgetDeclaration>[ WidgetDeclaration('a', null, ConstructorCall('b', <String, Object?>{ 'c': SetStateHandler(StateReference(<Object>['d']), false) })), ])); expect(bytes, <int>[ 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x11, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); expect(value.widgets, hasLength(1)); expect(value.widgets.first.name, 'a'); expect(value.widgets.first.initialState, isNull); expect(value.widgets.first.root, isA<ConstructorCall>()); expect((value.widgets.first.root as ConstructorCall).name, 'b'); expect((value.widgets.first.root as ConstructorCall).arguments, hasLength(1)); expect((value.widgets.first.root as ConstructorCall).arguments.keys, <Object?>['c']); expect((value.widgets.first.root as ConstructorCall).arguments['c'], isA<SetStateHandler>()); expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as SetStateHandler).stateReference.parts, <Object>['d']); expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as SetStateHandler).value, false); }); testWidgets('Library encoder: switch', (WidgetTester tester) async { final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary(<Import>[], <WidgetDeclaration>[ WidgetDeclaration('a', null, ConstructorCall('b', <String, Object?>{ 'c': Switch(false, <Object?, Object>{} ) })), ])); expect(bytes, <int>[ 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); expect(value.widgets, hasLength(1)); expect(value.widgets.first.name, 'a'); expect(value.widgets.first.initialState, isNull); expect(value.widgets.first.root, isA<ConstructorCall>()); expect((value.widgets.first.root as ConstructorCall).name, 'b'); expect((value.widgets.first.root as ConstructorCall).arguments, hasLength(1)); expect((value.widgets.first.root as ConstructorCall).arguments.keys, <Object?>['c']); expect((value.widgets.first.root as ConstructorCall).arguments['c'], isA<Switch>()); expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as Switch).input, false); expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as Switch).outputs, isEmpty); }); testWidgets('Library encoder: initial state', (WidgetTester tester) async { final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary(<Import>[], <WidgetDeclaration>[ WidgetDeclaration('a', <String, Object?>{}, ConstructorCall('b', <String, Object?>{})), ])); expect(bytes, <int>[ 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); expect(value.widgets, hasLength(1)); expect(value.widgets.first.name, 'a'); expect(value.widgets.first.initialState, isNull); expect(value.widgets.first.root, isA<ConstructorCall>()); expect((value.widgets.first.root as ConstructorCall).name, 'b'); expect((value.widgets.first.root as ConstructorCall).arguments, isEmpty); }); testWidgets('Library encoder: initial state', (WidgetTester tester) async { final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary(<Import>[], <WidgetDeclaration>[ WidgetDeclaration('a', <String, Object?>{ 'b': false }, ConstructorCall('c', <String, Object?>{})), ])); expect(bytes, <int>[ 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); expect(value.widgets, hasLength(1)); expect(value.widgets.first.name, 'a'); expect(value.widgets.first.initialState, isNotNull); expect(value.widgets.first.initialState, hasLength(1)); expect(value.widgets.first.initialState!['b'], false); expect(value.widgets.first.root, isA<ConstructorCall>()); expect((value.widgets.first.root as ConstructorCall).name, 'c'); expect((value.widgets.first.root as ConstructorCall).arguments, isEmpty); }); testWidgets('Library encoder: widget builders work', (WidgetTester tester) async { const String source = ''' widget Foo = Builder( builder: (scope) => Text(text: scope.text), ); '''; final RemoteWidgetLibrary library = parseLibraryFile(source); final Uint8List encoded = encodeLibraryBlob(library); final RemoteWidgetLibrary decoded = decodeLibraryBlob(encoded); expect(library.toString(), decoded.toString()); }); testWidgets('Library encoder: widget builders throws', (WidgetTester tester) async { const RemoteWidgetLibrary remoteWidgetLibrary = RemoteWidgetLibrary( <Import>[], <WidgetDeclaration>[ WidgetDeclaration( 'a', <String, Object?>{}, ConstructorCall( 'c', <String, Object?>{ 'builder': WidgetBuilderDeclaration('scope', ArgsReference(<Object>[])), }, ), ), ], ); try { decodeLibraryBlob(encodeLibraryBlob(remoteWidgetLibrary)); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Unrecognized data type 0x0A while decoding widget builder blob.')); } }); }
packages/packages/rfw/test/binary_test.dart/0
{ "file_path": "packages/packages/rfw/test/binary_test.dart", "repo_id": "packages", "token_count": 13448 }
1,140
# Shared preferences plugin <?code-excerpt path-base="example/lib"?> [![pub package](https://img.shields.io/pub/v/shared_preferences.svg)](https://pub.dev/packages/shared_preferences) Wraps platform-specific persistent storage for simple data (NSUserDefaults on iOS and macOS, SharedPreferences on Android, etc.). Data may be persisted to disk asynchronously, and there is no guarantee that writes will be persisted to disk after returning, so this plugin must not be used for storing critical data. Supported data types are `int`, `double`, `bool`, `String` and `List<String>`. | | Android | iOS | Linux | macOS | Web | Windows | |-------------|---------|-------|-------|--------|-----|-------------| | **Support** | SDK 16+ | 12.0+ | Any | 10.14+ | Any | Any | ## Usage To use this plugin, add `shared_preferences` as a [dependency in your pubspec.yaml file](https://flutter.dev/docs/development/platform-integration/platform-channels). ### Examples Here are small examples that show you how to use the API. #### Write data <?code-excerpt "readme_excerpts.dart (Write)"?> ```dart // Obtain shared preferences. final SharedPreferences prefs = await SharedPreferences.getInstance(); // Save an integer value to 'counter' key. await prefs.setInt('counter', 10); // Save an boolean value to 'repeat' key. await prefs.setBool('repeat', true); // Save an double value to 'decimal' key. await prefs.setDouble('decimal', 1.5); // Save an String value to 'action' key. await prefs.setString('action', 'Start'); // Save an list of strings to 'items' key. await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']); ``` #### Read data <?code-excerpt "readme_excerpts.dart (Read)"?> ```dart // Try reading data from the 'counter' key. If it doesn't exist, returns null. final int? counter = prefs.getInt('counter'); // Try reading data from the 'repeat' key. If it doesn't exist, returns null. final bool? repeat = prefs.getBool('repeat'); // Try reading data from the 'decimal' key. If it doesn't exist, returns null. final double? decimal = prefs.getDouble('decimal'); // Try reading data from the 'action' key. If it doesn't exist, returns null. final String? action = prefs.getString('action'); // Try reading data from the 'items' key. If it doesn't exist, returns null. final List<String>? items = prefs.getStringList('items'); ``` #### Remove an entry <?code-excerpt "readme_excerpts.dart (Clear)"?> ```dart // Remove data for the 'counter' key. await prefs.remove('counter'); ``` ### Multiple instances In order to make preference lookup via the `get*` methods synchronous, `shared_preferences` uses a cache on the Dart side, which is normally only updated by the `set*` methods. Usually this is an implementation detail that does not affect callers, but it can cause issues in a few cases: - If you are using `shared_preferences` from multiple isolates, since each isolate has its own `SharedPreferences` singleton and cache. - If you are using `shared_preferences` in multiple engine instances (including those created by plugins that create background contexts on mobile devices, such as `firebase_messaging`). - If you are modifying the underlying system preference store through something other than the `shared_preferences` plugin, such as native code. If you need to read a preference value that may have been changed by anything other than the `SharedPreferences` instance you are reading it from, you should call `reload()` on the instance before reading from it to update its cache with any external changes. If this is problematic for your use case, you can thumbs up [this issue](https://github.com/flutter/flutter/issues/123078) to express interest in APIs that provide direct (asynchronous) access to the underlying preference store, and/or subscribe to it for updates. ### Migration and Prefixes By default, the `SharedPreferences` plugin will only read (and write) preferences that begin with the prefix `flutter.`. This is all handled internally by the plugin and does not require manually adding this prefix. Alternatively, `SharedPreferences` can be configured to use any prefix by adding a call to `setPrefix` before any instances of `SharedPreferences` are instantiated. Calling `setPrefix` after an instance of `SharedPreferences` is created will fail. Setting the prefix to an empty string `''` will allow access to all preferences created by any non-flutter versions of the app (for migrating from a native app to flutter). If the prefix is set to a value such as `''` that causes it to read values that were not originally stored by the `SharedPreferences`, initializing `SharedPreferences` may fail if any of the values are of types that are not supported by `SharedPreferences`. In this case, you can set an `allowList` that contains only preferences of supported types. If you decide to remove the prefix entirely, you can still access previously created preferences by manually adding the previous prefix `flutter.` to the beginning of the preference key. If you have been using `SharedPreferences` with the default prefix but wish to change to a new prefix, you will need to transform your current preferences manually to add the new prefix otherwise the old preferences will be inaccessible. ### Testing In tests, you can replace the standard `SharedPreferences` implementation with a mock implementation with initial values. This implementation is in-memory only, and will not persist values to the usual preference store. <?code-excerpt "readme_excerpts.dart (Tests)"?> ```dart final Map<String, Object> values = <String, Object>{'counter': 1}; SharedPreferences.setMockInitialValues(values); ``` ### Storage location by platform | Platform | Location | | :--- | :--- | | Android | SharedPreferences | | iOS | NSUserDefaults | | Linux | In the XDG_DATA_HOME directory | | macOS | NSUserDefaults | | Web | LocalStorage | | Windows | In the roaming AppData directory |
packages/packages/shared_preferences/shared_preferences/README.md/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences/README.md", "repo_id": "packages", "token_count": 1654 }
1,141
// 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.sharedpreferences; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.anyString; import android.content.Context; import android.content.SharedPreferences; import androidx.annotation.NonNull; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.plugin.common.BinaryMessenger; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; public class SharedPreferencesTest { SharedPreferencesPlugin plugin; @Mock BinaryMessenger mockMessenger; @Mock FlutterPlugin.FlutterPluginBinding flutterPluginBinding; @Before public void before() { Context context = Mockito.mock(Context.class); SharedPreferences sharedPrefs = new FakeSharedPreferences(); flutterPluginBinding = Mockito.mock(FlutterPlugin.FlutterPluginBinding.class); Mockito.when(flutterPluginBinding.getBinaryMessenger()).thenReturn(mockMessenger); Mockito.when(flutterPluginBinding.getApplicationContext()).thenReturn(context); Mockito.when(context.getSharedPreferences(anyString(), anyInt())).thenReturn(sharedPrefs); plugin = new SharedPreferencesPlugin(new ListEncoder()); plugin.onAttachedToEngine(flutterPluginBinding); } private static final Map<String, Object> data = new HashMap<>(); static { data.put("Language", "Java"); data.put("Counter", 0L); data.put("Pie", 3.14); data.put("Names", Arrays.asList("Flutter", "Dart")); data.put("NewToFlutter", false); data.put("flutter.Language", "Java"); data.put("flutter.Counter", 0L); data.put("flutter.Pie", 3.14); data.put("flutter.Names", Arrays.asList("Flutter", "Dart")); data.put("flutter.NewToFlutter", false); data.put("prefix.Language", "Java"); data.put("prefix.Counter", 0L); data.put("prefix.Pie", 3.14); data.put("prefix.Names", Arrays.asList("Flutter", "Dart")); data.put("prefix.NewToFlutter", false); } @Test public void getAll() { assertEquals(plugin.getAll("", null).size(), 0); addData(); Map<String, Object> flutterData = plugin.getAll("flutter.", null); assertEquals(flutterData.size(), 5); assertEquals(flutterData.get("flutter.Language"), "Java"); assertEquals(flutterData.get("flutter.Counter"), 0L); assertEquals(flutterData.get("flutter.Pie"), 3.14); assertEquals(flutterData.get("flutter.Names"), Arrays.asList("Flutter", "Dart")); assertEquals(flutterData.get("flutter.NewToFlutter"), false); Map<String, Object> allData = plugin.getAll("", null); assertEquals(allData, data); } @Test public void allowList() { assertEquals(plugin.getAll("", null).size(), 0); addData(); final List<String> allowList = Arrays.asList("flutter.Language"); Map<String, Object> allData = plugin.getAll("flutter.", allowList); assertEquals(allData.size(), 1); assertEquals(allData.get("flutter.Language"), "Java"); assertEquals(allData.get("flutter.Counter"), null); allData = plugin.getAll("", allowList); assertEquals(allData.size(), 1); assertEquals(allData.get("flutter.Language"), "Java"); assertEquals(allData.get("flutter.Counter"), null); allData = plugin.getAll("prefix.", allowList); assertEquals(allData.size(), 0); assertEquals(allData.get("flutter.Language"), null); } @Test public void setString() { final String key = "language"; final String value = "Java"; plugin.setString(key, value); Map<String, Object> flutterData = plugin.getAll("", null); assertEquals(flutterData.get(key), value); } @Test public void setInt() { final String key = "Counter"; final Long value = 0L; plugin.setInt(key, value); Map<String, Object> flutterData = plugin.getAll("", null); assertEquals(flutterData.get(key), value); } @Test public void setDouble() { final String key = "Pie"; final double value = 3.14; plugin.setDouble(key, value); Map<String, Object> flutterData = plugin.getAll("", null); assertEquals(flutterData.get(key), value); } @Test public void setStringList() { final String key = "Names"; final List<String> value = Arrays.asList("Flutter", "Dart"); plugin.setStringList(key, value); Map<String, Object> flutterData = plugin.getAll("", null); assertEquals(flutterData.get(key), value); } @Test public void setBool() { final String key = "NewToFlutter"; final boolean value = false; plugin.setBool(key, value); Map<String, Object> flutterData = plugin.getAll("", null); assertEquals(flutterData.get(key), value); } @Test public void clearWithNoAllowList() { addData(); assertEquals(plugin.getAll("", null).size(), 15); plugin.clear("flutter.", null); assertEquals(plugin.getAll("", null).size(), 10); } @Test public void clearWithAllowList() { addData(); assertEquals(plugin.getAll("", null).size(), 15); plugin.clear("flutter.", Arrays.asList("flutter.Language")); assertEquals(plugin.getAll("", null).size(), 14); } @Test public void clearAll() { addData(); assertEquals(plugin.getAll("", null).size(), 15); plugin.clear("", null); assertEquals(plugin.getAll("", null).size(), 0); } @Test public void testRemove() { final String key = "NewToFlutter"; final boolean value = true; plugin.setBool(key, value); assert (plugin.getAll("", null).containsKey(key)); plugin.remove(key); assertFalse(plugin.getAll("", null).containsKey(key)); } private void addData() { plugin.setString("Language", "Java"); plugin.setInt("Counter", 0L); plugin.setDouble("Pie", 3.14); plugin.setStringList("Names", Arrays.asList("Flutter", "Dart")); plugin.setBool("NewToFlutter", false); plugin.setString("flutter.Language", "Java"); plugin.setInt("flutter.Counter", 0L); plugin.setDouble("flutter.Pie", 3.14); plugin.setStringList("flutter.Names", Arrays.asList("Flutter", "Dart")); plugin.setBool("flutter.NewToFlutter", false); plugin.setString("prefix.Language", "Java"); plugin.setInt("prefix.Counter", 0L); plugin.setDouble("prefix.Pie", 3.14); plugin.setStringList("prefix.Names", Arrays.asList("Flutter", "Dart")); plugin.setBool("prefix.NewToFlutter", false); } /** A dummy implementation for tests for use with FakeSharedPreferences */ public static class FakeSharedPreferencesEditor implements SharedPreferences.Editor { private final Map<String, Object> sharedPrefData; FakeSharedPreferencesEditor(@NonNull Map<String, Object> data) { sharedPrefData = data; } @Override public @NonNull SharedPreferences.Editor putString(@NonNull String key, @NonNull String value) { sharedPrefData.put(key, value); return this; } @Override public @NonNull SharedPreferences.Editor putStringSet( @NonNull String key, @NonNull Set<String> values) { sharedPrefData.put(key, values); return this; } @Override public @NonNull SharedPreferences.Editor putBoolean( @NonNull String key, @NonNull boolean value) { sharedPrefData.put(key, value); return this; } @Override public @NonNull SharedPreferences.Editor putInt(@NonNull String key, @NonNull int value) { sharedPrefData.put(key, value); return this; } @Override public @NonNull SharedPreferences.Editor putLong(@NonNull String key, @NonNull long value) { sharedPrefData.put(key, value); return this; } @Override public @NonNull SharedPreferences.Editor putFloat(@NonNull String key, @NonNull float value) { sharedPrefData.put(key, value); return this; } @Override public @NonNull SharedPreferences.Editor remove(@NonNull String key) { sharedPrefData.remove(key); return this; } @Override public @NonNull boolean commit() { return true; } @Override public void apply() { throw new UnsupportedOperationException("This method is not implemented for testing"); } @Override public @NonNull SharedPreferences.Editor clear() { throw new UnsupportedOperationException("This method is not implemented for testing"); } } /** A dummy implementation of SharedPreferences for tests that store values in memory. */ private static class FakeSharedPreferences implements SharedPreferences { Map<String, Object> sharedPrefData = new HashMap<>(); @Override public @NonNull Map<String, ?> getAll() { return sharedPrefData; } @Override public @NonNull SharedPreferences.Editor edit() { return new FakeSharedPreferencesEditor(sharedPrefData); } // All methods below are not implemented. @Override public @NonNull boolean contains(@NonNull String key) { throw new UnsupportedOperationException("This method is not implemented for testing"); } @Override public @NonNull boolean getBoolean(@NonNull String key, @NonNull boolean defValue) { throw new UnsupportedOperationException("This method is not implemented for testing"); } @Override public @NonNull float getFloat(@NonNull String key, @NonNull float defValue) { throw new UnsupportedOperationException("This method is not implemented for testing"); } @Override public @NonNull int getInt(@NonNull String key, @NonNull int defValue) { throw new UnsupportedOperationException("This method is not implemented for testing"); } @Override public @NonNull long getLong(@NonNull String key, @NonNull long defValue) { throw new UnsupportedOperationException("This method is not implemented for testing"); } @Override public @NonNull String getString(@NonNull String key, @NonNull String defValue) { throw new UnsupportedOperationException("This method is not implemented for testing"); } @Override public @NonNull Set<String> getStringSet(@NonNull String key, @NonNull Set<String> defValues) { throw new UnsupportedOperationException("This method is not implemented for testing"); } @Override public void registerOnSharedPreferenceChangeListener( @NonNull SharedPreferences.OnSharedPreferenceChangeListener listener) { throw new UnsupportedOperationException("This method is not implemented for testing"); } @Override public void unregisterOnSharedPreferenceChangeListener( @NonNull SharedPreferences.OnSharedPreferenceChangeListener listener) { throw new UnsupportedOperationException("This method is not implemented for testing"); } } /** A dummy implementation of SharedPreferencesListEncoder for tests that store List<String>. */ static class ListEncoder implements SharedPreferencesListEncoder { @Override public @NonNull String encode(@NonNull List<String> list) { return String.join(";-;", list); } @Override public @NonNull List<String> decode(@NonNull String listString) { return Arrays.asList(listString.split(";-;")); } } }
packages/packages/shared_preferences/shared_preferences_android/android/src/test/java/io/flutter/plugins/sharedpreferences/SharedPreferencesTest.java/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_android/android/src/test/java/io/flutter/plugins/sharedpreferences/SharedPreferencesTest.java", "repo_id": "packages", "token_count": 3950 }
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. import 'package:pigeon/pigeon.dart'; @ConfigurePigeon(PigeonOptions( input: 'pigeons/messages.dart', javaOut: 'android/src/main/java/io/flutter/plugins/sharedpreferences/Messages.java', javaOptions: JavaOptions( className: 'Messages', package: 'io.flutter.plugins.sharedpreferences'), dartOut: 'lib/src/messages.g.dart', copyrightHeader: 'pigeons/copyright.txt', )) @HostApi(dartHostTestHandler: 'TestSharedPreferencesApi') abstract class SharedPreferencesApi { /// Removes property from shared preferences data set. @TaskQueue(type: TaskQueueType.serialBackgroundThread) bool remove(String key); /// Adds property to shared preferences data set of type bool. @TaskQueue(type: TaskQueueType.serialBackgroundThread) bool setBool(String key, bool value); /// Adds property to shared preferences data set of type String. @TaskQueue(type: TaskQueueType.serialBackgroundThread) bool setString(String key, String value); /// Adds property to shared preferences data set of type int. @TaskQueue(type: TaskQueueType.serialBackgroundThread) bool setInt(String key, int value); /// Adds property to shared preferences data set of type double. @TaskQueue(type: TaskQueueType.serialBackgroundThread) bool setDouble(String key, double value); /// Adds property to shared preferences data set of type List<String>. @TaskQueue(type: TaskQueueType.serialBackgroundThread) bool setStringList(String key, List<String> value); /// Removes all properties from shared preferences data set with matching prefix. @TaskQueue(type: TaskQueueType.serialBackgroundThread) bool clear( String prefix, List<String>? allowList, ); /// Gets all properties from shared preferences data set with matching prefix. @TaskQueue(type: TaskQueueType.serialBackgroundThread) Map<String, Object> getAll( String prefix, List<String>? allowList, ); }
packages/packages/shared_preferences/shared_preferences_android/pigeons/messages.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_android/pigeons/messages.dart", "repo_id": "packages", "token_count": 604 }
1,143
// 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 'package:file/memory.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as path; import 'package:path_provider_linux/path_provider_linux.dart'; import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; import 'package:shared_preferences_linux/shared_preferences_linux.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; import 'package:shared_preferences_platform_interface/types.dart'; void main() { late MemoryFileSystem fs; late PathProviderLinux pathProvider; SharedPreferencesLinux.registerWith(); const Map<String, Object> flutterTestValues = <String, Object>{ 'flutter.String': 'hello world', 'flutter.Bool': true, 'flutter.Int': 42, 'flutter.Double': 3.14159, 'flutter.StringList': <String>['foo', 'bar'], }; const Map<String, Object> prefixTestValues = <String, Object>{ 'prefix.String': 'hello world', 'prefix.Bool': true, 'prefix.Int': 42, 'prefix.Double': 3.14159, 'prefix.StringList': <String>['foo', 'bar'], }; const Map<String, Object> nonPrefixTestValues = <String, Object>{ 'String': 'hello world', 'Bool': true, 'Int': 42, 'Double': 3.14159, 'StringList': <String>['foo', 'bar'], }; final Map<String, Object> allTestValues = <String, Object>{}; allTestValues.addAll(flutterTestValues); allTestValues.addAll(prefixTestValues); allTestValues.addAll(nonPrefixTestValues); setUp(() { fs = MemoryFileSystem.test(); pathProvider = FakePathProviderLinux(); }); Future<String> getFilePath() async { final String? directory = await pathProvider.getApplicationSupportPath(); return path.join(directory!, 'shared_preferences.json'); } Future<void> writeTestFile(String value) async { fs.file(await getFilePath()) ..createSync(recursive: true) ..writeAsStringSync(value); } Future<String> readTestFile() async { return fs.file(await getFilePath()).readAsStringSync(); } SharedPreferencesLinux getPreferences() { final SharedPreferencesLinux prefs = SharedPreferencesLinux(); prefs.fs = fs; prefs.pathProvider = pathProvider; return prefs; } test('registered instance', () { SharedPreferencesLinux.registerWith(); expect( SharedPreferencesStorePlatform.instance, isA<SharedPreferencesLinux>()); }); test('getAll', () async { await writeTestFile(json.encode(allTestValues)); final SharedPreferencesLinux prefs = getPreferences(); final Map<String, Object> values = await prefs.getAll(); expect(values, hasLength(5)); expect(values, flutterTestValues); }); test('getAllWithPrefix', () async { await writeTestFile(json.encode(allTestValues)); final SharedPreferencesLinux prefs = getPreferences(); final Map<String, Object> values = await prefs.getAllWithPrefix('prefix.'); expect(values, hasLength(5)); expect(values, prefixTestValues); }); test('getAllWithParameters', () async { await writeTestFile(json.encode(allTestValues)); final SharedPreferencesLinux prefs = getPreferences(); final Map<String, Object> values = await prefs.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(values, hasLength(5)); expect(values, prefixTestValues); }); test('getAllWithParameters with allow list', () async { await writeTestFile(json.encode(allTestValues)); final SharedPreferencesLinux prefs = getPreferences(); final Map<String?, Object?> all = await prefs.getAllWithParameters( GetAllParameters( filter: PreferencesFilter( prefix: 'prefix.', allowList: <String>{'prefix.Bool'}, ), ), ); expect(all.length, 1); expect(all['prefix.Bool'], prefixTestValues['prefix.Bool']); }); test('remove', () async { await writeTestFile('{"key1":"one","key2":2}'); final SharedPreferencesLinux prefs = getPreferences(); await prefs.remove('key2'); expect(await readTestFile(), '{"key1":"one"}'); }); test('setValue', () async { await writeTestFile('{}'); final SharedPreferencesLinux prefs = getPreferences(); await prefs.setValue('', 'key1', 'one'); await prefs.setValue('', 'key2', 2); expect(await readTestFile(), '{"key1":"one","key2":2}'); }); test('clear', () async { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesLinux prefs = getPreferences(); expect(await readTestFile(), json.encode(flutterTestValues)); await prefs.clear(); expect(await readTestFile(), '{}'); }); test('clearWithPrefix', () async { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesLinux prefs = getPreferences(); await prefs.clearWithPrefix('prefix.'); final Map<String, Object> noValues = await prefs.getAllWithPrefix('prefix.'); expect(noValues, hasLength(0)); final Map<String, Object> values = await prefs.getAll(); expect(values, hasLength(5)); expect(values, flutterTestValues); }); test('getAllWithNoPrefix', () async { await writeTestFile(json.encode(allTestValues)); final SharedPreferencesLinux prefs = getPreferences(); final Map<String, Object> values = await prefs.getAllWithPrefix(''); expect(values, hasLength(15)); expect(values, allTestValues); }); test('clearWithNoPrefix', () async { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesLinux prefs = getPreferences(); await prefs.clearWithPrefix(''); final Map<String, Object> noValues = await prefs.getAllWithPrefix(''); expect(noValues, hasLength(0)); }); test('clearWithParameters', () async { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesLinux prefs = getPreferences(); await prefs.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); final Map<String, Object> noValues = await prefs.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(noValues, hasLength(0)); final Map<String, Object> values = await prefs.getAll(); expect(values, hasLength(5)); expect(values, flutterTestValues); }); test('clearWithParameters with allow list', () async { await writeTestFile(json.encode(prefixTestValues)); final SharedPreferencesLinux prefs = getPreferences(); await prefs.clearWithParameters( ClearParameters( filter: PreferencesFilter( prefix: 'prefix.', allowList: <String>{'prefix.StringList'}, ), ), ); final Map<String, Object> someValues = await prefs.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(someValues, hasLength(4)); }); test('getAllWithNoPrefix', () async { await writeTestFile(json.encode(allTestValues)); final SharedPreferencesLinux prefs = getPreferences(); final Map<String, Object> values = await prefs.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values, hasLength(15)); expect(values, allTestValues); }); test('clearWithNoPrefix', () async { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesLinux prefs = getPreferences(); await prefs.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: ''), ), ); final Map<String, Object> noValues = await prefs.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(noValues, hasLength(0)); }); } /// Fake implementation of PathProviderLinux that returns hard-coded paths, /// allowing tests to run on any platform. /// /// Note that this should only be used with an in-memory filesystem, as the /// path it returns is a root path that does not actually exist on Linux. class FakePathProviderLinux extends PathProviderPlatform implements PathProviderLinux { @override Future<String?> getApplicationSupportPath() async => r'/appsupport'; @override Future<String?> getTemporaryPath() async => null; @override Future<String?> getLibraryPath() async => null; @override Future<String?> getApplicationDocumentsPath() async => null; @override Future<String?> getDownloadsPath() async => null; }
packages/packages/shared_preferences/shared_preferences_linux/test/shared_preferences_linux_test.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_linux/test/shared_preferences_linux_test.dart", "repo_id": "packages", "token_count": 3014 }
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:integration_test/integration_test.dart'; import 'package:shared_preferences_platform_interface/method_channel_shared_preferences.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; import 'package:shared_preferences_platform_interface/types.dart'; import 'package:shared_preferences_web/shared_preferences_web.dart'; import 'package:shared_preferences_web/src/keys_extension.dart'; import 'package:web/web.dart' as html; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); setUp(() { html.window.localStorage.clear(); }); testWidgets('registers itself', (WidgetTester tester) async { SharedPreferencesStorePlatform.instance = MethodChannelSharedPreferencesStore(); expect(SharedPreferencesStorePlatform.instance, isNot(isA<SharedPreferencesPlugin>())); SharedPreferencesPlugin.registerWith(null); expect(SharedPreferencesStorePlatform.instance, isA<SharedPreferencesPlugin>()); }); const Map<String, Object> flutterTestValues = <String, Object>{ 'flutter.String': 'hello world', 'flutter.Bool': true, 'flutter.Int': 42, 'flutter.Double': 3.14159, 'flutter.StringList': <String>['foo', 'bar'], }; const Map<String, Object> prefixTestValues = <String, Object>{ 'prefix.String': 'hello world', 'prefix.Bool': true, 'prefix.Int': 42, 'prefix.Double': 3.14159, 'prefix.StringList': <String>['foo', 'bar'], }; const Map<String, Object> nonPrefixTestValues = <String, Object>{ 'String': 'hello world', 'Bool': true, 'Int': 42, 'Double': 3.14159, 'StringList': <String>['foo', 'bar'], }; final Map<String, Object> allTestValues = <String, Object>{}; allTestValues.addAll(flutterTestValues); allTestValues.addAll(prefixTestValues); allTestValues.addAll(nonPrefixTestValues); late SharedPreferencesStorePlatform preferences; setUp(() async { preferences = SharedPreferencesStorePlatform.instance; }); tearDown(() async { await preferences.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: ''), ), ); }); testWidgets('reading', (WidgetTester _) async { final Map<String, Object> values = await preferences.getAll(); expect(values.length, 0); }); Future<void> addData() async { await preferences.setValue('String', 'String', allTestValues['String']!); await preferences.setValue('Bool', 'Bool', allTestValues['Bool']!); await preferences.setValue('Int', 'Int', allTestValues['Int']!); await preferences.setValue('Double', 'Double', allTestValues['Double']!); await preferences.setValue( 'StringList', 'StringList', allTestValues['StringList']!); await preferences.setValue( 'String', 'prefix.String', allTestValues['prefix.String']!); await preferences.setValue( 'Bool', 'prefix.Bool', allTestValues['prefix.Bool']!); await preferences.setValue( 'Int', 'prefix.Int', allTestValues['prefix.Int']!); await preferences.setValue( 'Double', 'prefix.Double', allTestValues['prefix.Double']!); await preferences.setValue( 'StringList', 'prefix.StringList', allTestValues['prefix.StringList']!); await preferences.setValue( 'String', 'flutter.String', allTestValues['flutter.String']!); await preferences.setValue( 'Bool', 'flutter.Bool', allTestValues['flutter.Bool']!); await preferences.setValue( 'Int', 'flutter.Int', allTestValues['flutter.Int']!); await preferences.setValue( 'Double', 'flutter.Double', allTestValues['flutter.Double']!); await preferences.setValue('StringList', 'flutter.StringList', allTestValues['flutter.StringList']!); } testWidgets('keys', (WidgetTester _) async { await addData(); final Iterable<String> keys = html.window.localStorage.keys; final Iterable<String> expectedKeys = allTestValues.keys; expect(keys, hasLength(expectedKeys.length)); expect(keys, containsAll(expectedKeys)); }); testWidgets('clear', (WidgetTester _) async { await addData(); await preferences.clear(); final Map<String, Object> values = await preferences.getAll(); expect(values['flutter.String'], null); expect(values['flutter.Bool'], null); expect(values['flutter.Int'], null); expect(values['flutter.Double'], null); expect(values['flutter.StringList'], null); }); group('withPrefix', () { setUp(() async { await addData(); }); testWidgets('remove', (WidgetTester _) async { const String key = 'flutter.String'; await preferences.remove(key); final Map<String, Object> values = // ignore: deprecated_member_use await preferences.getAllWithPrefix(''); expect(values[key], isNull); }); testWidgets('get all with prefix', (WidgetTester _) async { final Map<String, Object> values = // ignore: deprecated_member_use await preferences.getAllWithPrefix('prefix.'); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); expect(values['prefix.Double'], allTestValues['prefix.Double']); expect(values['prefix.StringList'], allTestValues['prefix.StringList']); }); testWidgets('getAllWithNoPrefix', (WidgetTester _) async { final Map<String, Object> values = // ignore: deprecated_member_use await preferences.getAllWithPrefix(''); expect(values['String'], allTestValues['String']); expect(values['Bool'], allTestValues['Bool']); expect(values['Int'], allTestValues['Int']); expect(values['Double'], allTestValues['Double']); expect(values['StringList'], allTestValues['StringList']); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithPrefix', (WidgetTester _) async { // ignore: deprecated_member_use await preferences.clearWithPrefix('prefix.'); Map<String, Object> values = // ignore: deprecated_member_use await preferences.getAllWithPrefix('prefix.'); expect(values['prefix.String'], null); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); expect(values['prefix.Double'], null); expect(values['prefix.StringList'], null); // ignore: deprecated_member_use values = await preferences.getAllWithPrefix('flutter.'); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { // ignore: deprecated_member_use await preferences.clearWithPrefix(''); final Map<String, Object> values = // ignore: deprecated_member_use await preferences.getAllWithPrefix(''); expect(values['String'], null); expect(values['Bool'], null); expect(values['Int'], null); expect(values['Double'], null); expect(values['StringList'], null); expect(values['flutter.String'], null); expect(values['flutter.Bool'], null); expect(values['flutter.Int'], null); expect(values['flutter.Double'], null); expect(values['flutter.StringList'], null); }); }); group('withParameters', () { setUp(() async { await addData(); }); testWidgets('remove', (WidgetTester _) async { const String key = 'flutter.String'; await preferences.remove(key); final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values[key], isNull); }); testWidgets('get all with prefix', (WidgetTester _) async { final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); expect(values['prefix.Double'], allTestValues['prefix.Double']); expect(values['prefix.StringList'], allTestValues['prefix.StringList']); }); testWidgets('get all with allow list', (WidgetTester _) async { final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter( prefix: 'prefix.', allowList: <String>{'prefix.String'}, ), ), ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); expect(values['prefix.Double'], null); expect(values['prefix.StringList'], null); }); testWidgets('getAllWithNoPrefix', (WidgetTester _) async { final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values['String'], allTestValues['String']); expect(values['Bool'], allTestValues['Bool']); expect(values['Int'], allTestValues['Int']); expect(values['Double'], allTestValues['Double']); expect(values['StringList'], allTestValues['StringList']); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithParameters', (WidgetTester _) async { await preferences.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(values['prefix.String'], null); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); expect(values['prefix.Double'], null); expect(values['prefix.StringList'], null); values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'flutter.'), ), ); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithParameters with allow list', (WidgetTester _) async { await addData(); await preferences.clearWithParameters( ClearParameters( filter: PreferencesFilter( prefix: 'prefix.', allowList: <String>{'prefix.StringList'}, ), ), ); Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); expect(values['prefix.Double'], allTestValues['prefix.Double']); expect(values['prefix.StringList'], null); values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'flutter.'), ), ); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { await preferences.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: ''), ), ); final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values['String'], null); expect(values['Bool'], null); expect(values['Int'], null); expect(values['Double'], null); expect(values['StringList'], null); expect(values['flutter.String'], null); expect(values['flutter.Bool'], null); expect(values['flutter.Int'], null); expect(values['flutter.Double'], null); expect(values['flutter.StringList'], null); }); }); testWidgets('simultaneous writes', (WidgetTester _) async { final List<Future<bool>> writes = <Future<bool>>[]; const int writeCount = 100; for (int i = 1; i <= writeCount; i++) { writes.add(preferences.setValue('Int', 'Int', i)); } final List<bool> result = await Future.wait(writes, eagerError: true); // All writes should succeed. expect(result.where((bool element) => !element), isEmpty); // The last write should win. final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values['Int'], writeCount); }); }
packages/packages/shared_preferences/shared_preferences_web/example/integration_test/shared_preferences_web_test.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_web/example/integration_test/shared_preferences_web_test.dart", "repo_id": "packages", "token_count": 5498 }
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 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:table_view_example/main.dart'; void main() { testWidgets('Example app builds & scrolls', (WidgetTester tester) async { await tester.pumpWidget(const TableExampleApp()); await tester.pump(); expect(find.text('Jump to Top'), findsOneWidget); expect(find.text('Jump to Bottom'), findsOneWidget); expect(find.text('Add 10 Rows'), findsOneWidget); final Finder scrollable = find.byWidgetPredicate((Widget widget) { if (widget is Scrollable) { return widget.axisDirection == AxisDirection.down; } return false; }); final ScrollPosition position = (tester.state(scrollable) as ScrollableState).position; expect(position.axis, Axis.vertical); expect(position.pixels, 0.0); position.jumpTo(10); await tester.pump(); expect(position.pixels, 10.0); }); testWidgets('Example app buttons work', (WidgetTester tester) async { await tester.pumpWidget(const TableExampleApp()); await tester.pump(); final Finder scrollable = find.byWidgetPredicate((Widget widget) { if (widget is Scrollable) { return widget.axisDirection == AxisDirection.down; } return false; }); final ScrollPosition position = (tester.state(scrollable) as ScrollableState).position; expect(position.maxScrollExtent, greaterThan(750)); await tester.tap(find.text('Add 10 Rows')); await tester.pump(); expect(position.maxScrollExtent, greaterThan(1380)); await tester.tap(find.text('Jump to Bottom')); await tester.pump(); expect(position.pixels, greaterThan(1380)); await tester.tap(find.text('Jump to Top')); await tester.pump(); expect(position.pixels, 0.0); }); }
packages/packages/two_dimensional_scrollables/example/test/table_view_example_test.dart/0
{ "file_path": "packages/packages/two_dimensional_scrollables/example/test/table_view_example_test.dart", "repo_id": "packages", "token_count": 705 }
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/material.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:two_dimensional_scrollables/two_dimensional_scrollables.dart'; void main() { group('TableSpanExtent', () { test('FixedTableSpanExtent', () { FixedTableSpanExtent extent = const FixedTableSpanExtent(150); expect( extent.calculateExtent( const TableSpanExtentDelegate(precedingExtent: 0, viewportExtent: 0), ), 150, ); expect( extent.calculateExtent( const TableSpanExtentDelegate( precedingExtent: 100, viewportExtent: 1000), ), 150, ); // asserts value is valid expect( () { extent = FixedTableSpanExtent(-100); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('pixels >= 0.0'), ), ), ); }); test('FractionalTableSpanExtent', () { FractionalTableSpanExtent extent = const FractionalTableSpanExtent(0.5); expect( extent.calculateExtent( const TableSpanExtentDelegate(precedingExtent: 0, viewportExtent: 0), ), 0.0, ); expect( extent.calculateExtent( const TableSpanExtentDelegate( precedingExtent: 100, viewportExtent: 1000), ), 500, ); // asserts value is valid expect( () { extent = FractionalTableSpanExtent(-20); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('fraction >= 0.0'), ), ), ); }); test('RemainingTableSpanExtent', () { const RemainingTableSpanExtent extent = RemainingTableSpanExtent(); expect( extent.calculateExtent( const TableSpanExtentDelegate(precedingExtent: 0, viewportExtent: 0), ), 0.0, ); expect( extent.calculateExtent( const TableSpanExtentDelegate( precedingExtent: 100, viewportExtent: 1000), ), 900, ); }); test('CombiningTableSpanExtent', () { final CombiningTableSpanExtent extent = CombiningTableSpanExtent( const FixedTableSpanExtent(100), const RemainingTableSpanExtent(), (double a, double b) { return a + b; }, ); expect( extent.calculateExtent( const TableSpanExtentDelegate(precedingExtent: 0, viewportExtent: 0), ), 100, ); expect( extent.calculateExtent( const TableSpanExtentDelegate( precedingExtent: 100, viewportExtent: 1000), ), 1000, ); }); test('MaxTableSpanExtent', () { const MaxTableSpanExtent extent = MaxTableSpanExtent( FixedTableSpanExtent(100), RemainingTableSpanExtent(), ); expect( extent.calculateExtent( const TableSpanExtentDelegate(precedingExtent: 0, viewportExtent: 0), ), 100, ); expect( extent.calculateExtent( const TableSpanExtentDelegate( precedingExtent: 100, viewportExtent: 1000), ), 900, ); }); test('MinTableSpanExtent', () { const MinTableSpanExtent extent = MinTableSpanExtent( FixedTableSpanExtent(100), RemainingTableSpanExtent(), ); expect( extent.calculateExtent( const TableSpanExtentDelegate(precedingExtent: 0, viewportExtent: 0), ), 0, ); expect( extent.calculateExtent( const TableSpanExtentDelegate( precedingExtent: 100, viewportExtent: 1000), ), 100, ); }); }); test('TableSpanDecoration', () { TableSpanDecoration decoration = const TableSpanDecoration( color: Color(0xffff0000), ); final TestCanvas canvas = TestCanvas(); const Rect rect = Rect.fromLTWH(0, 0, 10, 10); final TableSpanDecorationPaintDetails details = TableSpanDecorationPaintDetails( canvas: canvas, rect: rect, axisDirection: AxisDirection.down, ); final BorderRadius radius = BorderRadius.circular(10.0); decoration.paint(details); expect(canvas.rect, rect); expect(canvas.paint.color, const Color(0xffff0000)); expect(canvas.paint.isAntiAlias, isFalse); final TestTableSpanBorder border = TestTableSpanBorder( leading: const BorderSide(), ); decoration = TableSpanDecoration( border: border, borderRadius: radius, ); decoration.paint(details); expect(border.details, details); expect(border.radius, radius); }); group('Decoration rects account for reversed axes', () { late ScrollController verticalController; late ScrollController horizontalController; setUp(() { verticalController = ScrollController(); horizontalController = ScrollController(); }); tearDown(() { verticalController.dispose(); horizontalController.dispose(); }); TableViewCell buildCell(BuildContext context, TableVicinity vicinity) { return const TableViewCell(child: SizedBox.shrink()); } TableSpan buildSpan(bool isColumn) { return TableSpan( extent: const FixedTableSpanExtent(100), foregroundDecoration: TableSpanDecoration( color: isColumn ? const Color(0xFFE1BEE7) : const Color(0xFFBBDEFB), ), ); } testWidgets('Vertical main axis, vertical reversed', (WidgetTester tester) async { final TableView table = TableView.builder( verticalDetails: ScrollableDetails.vertical( controller: verticalController, reverse: true, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), rowCount: 10, columnCount: 10, rowBuilder: (_) => buildSpan(false), columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: table, )); await tester.pumpAndSettle(); expect( find.byType(TableViewport), paints // Rows first, bottom to top for reversed axis ..rect( rect: const Rect.fromLTRB(0.0, 500.0, 1000.0, 600.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, 400.0, 1000.0, 500.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, 300.0, 1000.0, 400.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, 200.0, 1000.0, 300.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, 100.0, 1000.0, 200.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, 0.0, 1000.0, 100.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, -100.0, 1000.0, 0.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, -200.0, 1000.0, -100.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, -300.0, 1000.0, -200.0), color: const Color(0xffbbdefb), ) // Columns next ..rect( rect: const Rect.fromLTRB(0.0, -300.0, 100.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(100.0, -300.0, 200.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(200.0, -300.0, 300.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(300.0, -300.0, 400.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(400.0, -300.0, 500.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(500.0, -300.0, 600.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(600.0, -300.0, 700.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(700.0, -300.0, 800.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(800.0, -300.0, 900.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(900.0, -300.0, 1000.0, 600.0), color: const Color(0xffe1bee7), ), ); }); testWidgets('Vertical main axis, horizontal reversed', (WidgetTester tester) async { final TableView table = TableView.builder( verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, reverse: true, ), rowCount: 10, columnCount: 10, rowBuilder: (_) => buildSpan(false), columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: table, )); await tester.pumpAndSettle(); expect( find.byType(TableViewport), paints // Rows first ..rect( rect: const Rect.fromLTRB(-200.0, 0.0, 800.0, 100.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 100.0, 800.0, 200.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 200.0, 800.0, 300.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 300.0, 800.0, 400.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 400.0, 800.0, 500.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 500.0, 800.0, 600.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 600.0, 800.0, 700.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 700.0, 800.0, 800.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 800.0, 800.0, 900.0), color: const Color(0xffbbdefb), ) // Columns next, right to left for reversed axis ..rect( rect: const Rect.fromLTRB(700.0, 0.0, 800.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(600.0, 0.0, 700.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(500.0, 0.0, 600.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(400.0, 0.0, 500.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(300.0, 0.0, 400.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(200.0, 0.0, 300.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(100.0, 0.0, 200.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(-100.0, 0.0, 0.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(-200.0, 0.0, -100.0, 900.0), color: const Color(0xffe1bee7), ), ); }); testWidgets('Vertical main axis, both reversed', (WidgetTester tester) async { final TableView table = TableView.builder( verticalDetails: ScrollableDetails.vertical( controller: verticalController, reverse: true, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, reverse: true, ), rowCount: 10, columnCount: 10, rowBuilder: (_) => buildSpan(false), columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: table, )); await tester.pumpAndSettle(); expect( find.byType(TableViewport), paints // Rows first, bottom to top for reversed axis ..rect( rect: const Rect.fromLTRB(-200.0, 500.0, 800.0, 600.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 400.0, 800.0, 500.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 300.0, 800.0, 400.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 200.0, 800.0, 300.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 100.0, 800.0, 200.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 0.0, 800.0, 100.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, -100.0, 800.0, 0.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, -200.0, 800.0, -100.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, -300.0, 800.0, -200.0), color: const Color(0xffbbdefb), ) // Columns next, right to left for reversed axis ..rect( rect: const Rect.fromLTRB(700.0, -300.0, 800.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(600.0, -300.0, 700.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(500.0, -300.0, 600.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(400.0, -300.0, 500.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(300.0, -300.0, 400.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(200.0, -300.0, 300.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(100.0, -300.0, 200.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(0.0, -300.0, 100.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(-100.0, -300.0, 0.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(-200.0, -300.0, -100.0, 600.0), color: const Color(0xffe1bee7), ), ); }); testWidgets('Horizontal main axis, vertical reversed', (WidgetTester tester) async { final TableView table = TableView.builder( mainAxis: Axis.horizontal, verticalDetails: ScrollableDetails.vertical( controller: verticalController, reverse: true, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), rowCount: 10, columnCount: 10, rowBuilder: (_) => buildSpan(false), columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: table, )); await tester.pumpAndSettle(); expect( find.byType(TableViewport), paints // Columns first ..rect( rect: const Rect.fromLTRB(0.0, -300.0, 100.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(100.0, -300.0, 200.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(200.0, -300.0, 300.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(300.0, -300.0, 400.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(400.0, -300.0, 500.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(500.0, -300.0, 600.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(600.0, -300.0, 700.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(700.0, -300.0, 800.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(800.0, -300.0, 900.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(900.0, -300.0, 1000.0, 600.0), color: const Color(0xffe1bee7), ) // Rows next, bottom to top for reversed axis ..rect( rect: const Rect.fromLTRB(0.0, 500.0, 1000.0, 600.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, 400.0, 1000.0, 500.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, 300.0, 1000.0, 400.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, 200.0, 1000.0, 300.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, 100.0, 1000.0, 200.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, 0.0, 1000.0, 100.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, -100.0, 1000.0, 0.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, -200.0, 1000.0, -100.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(0.0, -300.0, 1000.0, -200.0), color: const Color(0xffbbdefb), ), ); }); testWidgets('Horizontal main axis, horizontal reversed', (WidgetTester tester) async { final TableView table = TableView.builder( mainAxis: Axis.horizontal, verticalDetails: ScrollableDetails.vertical( controller: verticalController, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, reverse: true, ), rowCount: 10, columnCount: 10, rowBuilder: (_) => buildSpan(false), columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: table, )); await tester.pumpAndSettle(); expect( find.byType(TableViewport), paints // Columns first, right to left for reversed axis ..rect( rect: const Rect.fromLTRB(700.0, 0.0, 800.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(600.0, 0.0, 700.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(500.0, 0.0, 600.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(400.0, 0.0, 500.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(300.0, 0.0, 400.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(200.0, 0.0, 300.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(100.0, 0.0, 200.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(-100.0, 0.0, 0.0, 900.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(-200.0, 0.0, -100.0, 900.0), color: const Color(0xffe1bee7), ) // Rows next ..rect( rect: const Rect.fromLTRB(-200.0, 0.0, 800.0, 100.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 100.0, 800.0, 200.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 200.0, 800.0, 300.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 300.0, 800.0, 400.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 400.0, 800.0, 500.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 500.0, 800.0, 600.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 600.0, 800.0, 700.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 700.0, 800.0, 800.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 800.0, 800.0, 900.0), color: const Color(0xffbbdefb), ), ); }); testWidgets('Horizontal main axis, both reversed', (WidgetTester tester) async { final TableView table = TableView.builder( mainAxis: Axis.horizontal, verticalDetails: ScrollableDetails.vertical( controller: verticalController, reverse: true, ), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, reverse: true, ), rowCount: 10, columnCount: 10, rowBuilder: (_) => buildSpan(false), columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: table, )); await tester.pumpAndSettle(); expect( find.byType(TableViewport), paints // Columns first, right to left for reversed axis ..rect( rect: const Rect.fromLTRB(700.0, -300.0, 800.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(600.0, -300.0, 700.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(500.0, -300.0, 600.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(400.0, -300.0, 500.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(300.0, -300.0, 400.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(200.0, -300.0, 300.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(100.0, -300.0, 200.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(0.0, -300.0, 100.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(-100.0, -300.0, 0.0, 600.0), color: const Color(0xffe1bee7), ) ..rect( rect: const Rect.fromLTRB(-200.0, -300.0, -100.0, 600.0), color: const Color(0xffe1bee7), ) // Rows next, bottom to top for reversed axis ..rect( rect: const Rect.fromLTRB(-200.0, 500.0, 800.0, 600.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 400.0, 800.0, 500.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 300.0, 800.0, 400.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 200.0, 800.0, 300.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 100.0, 800.0, 200.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, 0.0, 800.0, 100.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, -100.0, 800.0, 0.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, -200.0, 800.0, -100.0), color: const Color(0xffbbdefb), ) ..rect( rect: const Rect.fromLTRB(-200.0, -300.0, 800.0, -200.0), color: const Color(0xffbbdefb), ), ); }); }); group('merged cell decorations', () { // Visualizing test cases in this group of tests ---------- // For each test configuration, these 3 scenarios are validated. // Each test represents a permutation of // TableView.mainAxis vertical (default) and horizontal, with // - natural scroll directions // - vertical reversed // - horizontal reversed // - both reversed // Scenario 1 // Cluster of merged rows (M) surrounded by regular cells (...). // This tiered scenario verifies that the correct decoration is applied // for merged rows. // +---------+--------+--------+ // | M(0,0)//|////////|////////| // |/////////|////////|////////| // +/////////+--------+--------+ // |/////////| M(1,1) | | // |/////////| | | // +---------+ +--------+ // | | | M(2,2) | // | | | | // +---------+--------+ + // |*********|********| | // |*********|********| | // +---------+--------+--------+ final Map<TableVicinity, (int, int)> scenario1MergedRows = <TableVicinity, (int, int)>{ TableVicinity.zero: (0, 2), TableVicinity.zero.copyWith(row: 1): (0, 2), const TableVicinity(row: 1, column: 1): (1, 2), const TableVicinity(row: 2, column: 1): (1, 2), const TableVicinity(row: 2, column: 2): (2, 2), const TableVicinity(row: 3, column: 2): (2, 2), }; TableView buildScenario1({ bool reverseVertical = false, bool reverseHorizontal = false, }) { return TableView.builder( verticalDetails: ScrollableDetails.vertical( reverse: reverseVertical, ), horizontalDetails: ScrollableDetails.horizontal( reverse: reverseHorizontal, ), columnCount: 3, rowCount: 4, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( rowMergeStart: scenario1MergedRows[vicinity]?.$1, rowMergeSpan: scenario1MergedRows[vicinity]?.$2, child: const SizedBox.expand(), ); }, columnBuilder: (_) { return const TableSpan(extent: FixedTableSpanExtent(100.0)); }, rowBuilder: (int index) { Color? color; switch (index) { case 0: color = const Color(0xFF2196F3); case 3: color = const Color(0xFF4CAF50); } return TableSpan( extent: const FixedTableSpanExtent(100.0), backgroundDecoration: color == null ? null : TableSpanDecoration(color: color), ); }, ); } // Scenario 2 // Cluster of merged cells (M) surrounded by regular cells (...). // This tiered scenario verifies that the correct decoration is applied // to merged columns. // +--------+--------+--------+--------+ // | M(0,0)//////////|********| | // |/////////////////|********| | // +--------+--------+--------+--------+ // |////////| M(1,1) | | // |////////| | | // +--------+--------+--------+--------+ // |////////| |M(2,2)***********| // |////////| |*****************| // +--------+--------+--------+--------+ final Map<TableVicinity, (int, int)> scenario2MergedColumns = <TableVicinity, (int, int)>{ TableVicinity.zero: (0, 2), TableVicinity.zero.copyWith(column: 1): (0, 2), const TableVicinity(row: 1, column: 1): (1, 2), const TableVicinity(row: 1, column: 2): (1, 2), const TableVicinity(row: 2, column: 2): (2, 2), const TableVicinity(row: 2, column: 3): (2, 2), }; TableView buildScenario2({ bool reverseVertical = false, bool reverseHorizontal = false, }) { return TableView.builder( verticalDetails: ScrollableDetails.vertical( reverse: reverseVertical, ), horizontalDetails: ScrollableDetails.horizontal( reverse: reverseHorizontal, ), columnCount: 4, rowCount: 3, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( columnMergeStart: scenario2MergedColumns[vicinity]?.$1, columnMergeSpan: scenario2MergedColumns[vicinity]?.$2, child: const SizedBox.expand(), ); }, rowBuilder: (_) { return const TableSpan(extent: FixedTableSpanExtent(100.0)); }, columnBuilder: (int index) { Color? color; switch (index) { case 0: color = const Color(0xFF2196F3); case 2: color = const Color(0xFF4CAF50); } return TableSpan( extent: const FixedTableSpanExtent(100.0), backgroundDecoration: color == null ? null : TableSpanDecoration(color: color), ); }, ); } // Scenario 3 // Cluster of merged cells (M) surrounded by regular cells (...). // This tiered scenario verifies that the correct decoration is applied // for merged cells over both rows and columns. // \\ = blue // // = green // XX = intersection // +--------+--------+--------+--------+ // | M(0,0)XXXXXXXXXX|\\\\\\\\|XXXXXXXX| // |XXXXXXXXXXXXXXXXX|\\\\\\\\|XXXXXXXX| // +XXXXXXXXXXXXXXXXX+--------+--------+ // |XXXXXXXXXXXXXXXXX| M(1,2) | // |XXXXXXXXXXXXXXXXX| | // +--------+--------+ | // |////////| | | // |////////| | | // +--------+--------+--------+--------+ final Map<TableVicinity, (int, int)> scenario3MergedRows = <TableVicinity, (int, int)>{ TableVicinity.zero: (0, 2), const TableVicinity(row: 1, column: 0): (0, 2), const TableVicinity(row: 0, column: 1): (0, 2), const TableVicinity(row: 1, column: 1): (0, 2), const TableVicinity(row: 1, column: 2): (1, 2), const TableVicinity(row: 2, column: 2): (1, 2), const TableVicinity(row: 1, column: 3): (1, 2), const TableVicinity(row: 2, column: 3): (1, 2), }; final Map<TableVicinity, (int, int)> scenario3MergedColumns = <TableVicinity, (int, int)>{ TableVicinity.zero: (0, 2), const TableVicinity(row: 1, column: 0): (0, 2), const TableVicinity(row: 0, column: 1): (0, 2), const TableVicinity(row: 1, column: 1): (0, 2), const TableVicinity(row: 1, column: 2): (2, 2), const TableVicinity(row: 2, column: 2): (2, 2), const TableVicinity(row: 1, column: 3): (2, 2), const TableVicinity(row: 2, column: 3): (2, 2), }; TableView buildScenario3({ Axis mainAxis = Axis.vertical, bool reverseVertical = false, bool reverseHorizontal = false, }) { return TableView.builder( mainAxis: mainAxis, verticalDetails: ScrollableDetails.vertical( reverse: reverseVertical, ), horizontalDetails: ScrollableDetails.horizontal( reverse: reverseHorizontal, ), columnCount: 4, rowCount: 3, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( columnMergeStart: scenario3MergedColumns[vicinity]?.$1, columnMergeSpan: scenario3MergedColumns[vicinity]?.$2, rowMergeStart: scenario3MergedRows[vicinity]?.$1, rowMergeSpan: scenario3MergedRows[vicinity]?.$2, child: const SizedBox.expand(), ); }, rowBuilder: (int index) { Color? color; switch (index) { case 0: color = const Color(0xFF2196F3); } return TableSpan( extent: const FixedTableSpanExtent(100.0), backgroundDecoration: color == null ? null : TableSpanDecoration(color: color), ); }, columnBuilder: (int index) { Color? color; switch (index) { case 0: case 3: color = const Color(0xFF4CAF50); } return TableSpan( extent: const FixedTableSpanExtent(100.0), backgroundDecoration: color == null ? null : TableSpanDecoration(color: color), ); }, ); } testWidgets('Vertical main axis, natural scroll directions', (WidgetTester tester) async { // Scenario 1 await tester.pumpWidget(buildScenario1()); expect( find.byType(TableViewport), paints // Top row decorations ..rect( rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 200.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first row rect: const Rect.fromLTRB(100.0, 0.0, 300.0, 100.0), color: const Color(0xFF2196F3), ) // Bottom row decoration, does not extend into last column ..rect( rect: const Rect.fromLTRB(0.0, 300.0, 200.0, 400.0), color: const Color(0xff4caf50), )); // Scenario 2 await tester.pumpWidget(buildScenario2()); expect( find.byType(TableViewport), paints // First column decorations ..rect( rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 100.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first column rect: const Rect.fromLTRB(0.0, 100.0, 100.0, 300.0), color: const Color(0xFF2196F3), ) // Third column decorations, does not extend into last column ..rect( // Unmerged section rect: const Rect.fromLTRB(200.0, 0.0, 300.0, 100.0), color: const Color(0xff4caf50), ) ..rect( rect: const Rect.fromLTRB(200.0, 200.0, 400.0, 300.0), // M(2,2) color: const Color(0xff4caf50), ), ); // Scenario 3 await tester.pumpWidget(buildScenario3()); expect( find.byType(TableViewport), paints // Row decorations ..rect( rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first row rect: const Rect.fromLTRB(200.0, 0.0, 400.0, 100.0), color: const Color(0xFF2196F3), ) // Column decorations ..rect( rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), // M(0,0) color: const Color(0xff4caf50), ) ..rect( // Rest of the first column rect: const Rect.fromLTRB(0.0, 200.0, 100.0, 300.0), color: const Color(0xff4caf50), ) ..rect( rect: const Rect.fromLTRB(300.0, 0.0, 400.0, 100.0), // Last column color: const Color(0xff4caf50), ), ); }); testWidgets('Vertical main axis, vertical reversed', (WidgetTester tester) async { // Scenario 1 await tester.pumpWidget(buildScenario1(reverseVertical: true)); expect( find.byType(TableViewport), paints // Bottom row decorations ..rect( rect: const Rect.fromLTRB(0.0, 400.0, 100.0, 600.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first row rect: const Rect.fromLTRB(100.0, 500.0, 300.0, 600.0), color: const Color(0xFF2196F3), ) // Top row decoration, does not extend into last column ..rect( rect: const Rect.fromLTRB(0.0, 200.0, 200.0, 300.0), color: const Color(0xff4caf50), ), ); // Scenario 2 await tester.pumpWidget(buildScenario2(reverseVertical: true)); expect( find.byType(TableViewport), paints // First column decorations ..rect( rect: const Rect.fromLTRB(0.0, 500.0, 200.0, 600.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first column rect: const Rect.fromLTRB(0.0, 300.0, 100.0, 500.0), color: const Color(0xFF2196F3), ) // Third column decorations, does not extend into last column ..rect( // Unmerged section rect: const Rect.fromLTRB(200.0, 500.0, 300.0, 600.0), color: const Color(0xff4caf50), ) ..rect( rect: const Rect.fromLTRB(200.0, 300.0, 400.0, 400.0), // M(2,2) color: const Color(0xff4caf50), ), ); // Scenario 3 await tester.pumpWidget(buildScenario3(reverseVertical: true)); expect( find.byType(TableViewport), paints // Row decorations ..rect( rect: const Rect.fromLTRB(0.0, 400.0, 200.0, 600.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first row rect: const Rect.fromLTRB(200.0, 500.0, 400.0, 600.0), color: const Color(0xFF2196F3), ) // Column decorations ..rect( rect: const Rect.fromLTRB(0.0, 400.0, 200.0, 600.0), // M(0,0) color: const Color(0xff4caf50), ) ..rect( // Rest of the first column rect: const Rect.fromLTRB(0.0, 300.0, 100.0, 400.0), color: const Color(0xff4caf50), ) ..rect( rect: const Rect.fromLTRB(300.0, 500.0, 400.0, 600.0), // Last column color: const Color(0xff4caf50), ), ); }); testWidgets('Vertical main axis, horizontal reversed', (WidgetTester tester) async { // Scenario 1 await tester.pumpWidget(buildScenario1(reverseHorizontal: true)); expect( find.byType(TableViewport), paints // Top row decorations ..rect( rect: const Rect.fromLTRB(700.0, 0.0, 800.0, 200.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first row rect: const Rect.fromLTRB(500.0, 0.0, 700.0, 100.0), color: const Color(0xFF2196F3), ) // Bottom row decoration, does not extend into last column ..rect( rect: const Rect.fromLTRB(600.0, 300.0, 800.0, 400.0), color: const Color(0xff4caf50), ), ); // Scenario 2 await tester.pumpWidget(buildScenario2(reverseHorizontal: true)); expect( find.byType(TableViewport), paints // First column decorations ..rect( rect: const Rect.fromLTRB(600.0, 0.0, 800.0, 100.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first column rect: const Rect.fromLTRB(700.0, 100.0, 800.0, 300.0), color: const Color(0xFF2196F3), ) // Third column decorations, does not extend into last column ..rect( // Unmerged section rect: const Rect.fromLTRB(500.0, 0.0, 600.0, 100.0), color: const Color(0xff4caf50), ) ..rect( rect: const Rect.fromLTRB(400.0, 200.0, 600.0, 300.0), // M(2,2) color: const Color(0xff4caf50), ), ); // Scenario 3 await tester.pumpWidget(buildScenario3(reverseHorizontal: true)); expect( find.byType(TableViewport), paints // Row decorations ..rect( rect: const Rect.fromLTRB(600.0, 0.0, 800.0, 200.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first row rect: const Rect.fromLTRB(400.0, 0.0, 600.0, 100.0), color: const Color(0xFF2196F3), ) // Column decorations ..rect( rect: const Rect.fromLTRB(600.0, 0.0, 800.0, 200.0), // M(0,0) color: const Color(0xff4caf50), ) ..rect( // Rest of the first column rect: const Rect.fromLTRB(700.0, 200.0, 800.0, 300.0), color: const Color(0xff4caf50), ) ..rect( rect: const Rect.fromLTRB(400.0, 0.0, 500.0, 100.0), // Last column color: const Color(0xff4caf50), ), ); }); testWidgets('Vertical main axis, both reversed', (WidgetTester tester) async { // Scenario 1 await tester.pumpWidget(buildScenario1( reverseHorizontal: true, reverseVertical: true, )); expect( find.byType(TableViewport), paints // Top row decorations ..rect( rect: const Rect.fromLTRB(700.0, 400.0, 800.0, 600.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first row rect: const Rect.fromLTRB(500.0, 500.0, 700.0, 600.0), color: const Color(0xFF2196F3), ) // Bottom row decoration, does not extend into last column ..rect( rect: const Rect.fromLTRB(600.0, 200.0, 800.0, 300.0), color: const Color(0xff4caf50), ), ); // Scenario 2 await tester.pumpWidget(buildScenario2( reverseHorizontal: true, reverseVertical: true, )); expect( find.byType(TableViewport), paints // First column decorations ..rect( rect: const Rect.fromLTRB(600.0, 500.0, 800.0, 600.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first column rect: const Rect.fromLTRB(700.0, 300.0, 800.0, 500.0), color: const Color(0xFF2196F3), ) // Third column decorations, does not extend into last column ..rect( // Unmerged section rect: const Rect.fromLTRB(500.0, 500.0, 600.0, 600.0), color: const Color(0xff4caf50), ) ..rect( rect: const Rect.fromLTRB(400.0, 300.0, 600.0, 400.0), // M(2,2) color: const Color(0xff4caf50), ), ); // Scenario 3 await tester.pumpWidget(buildScenario3( reverseHorizontal: true, reverseVertical: true, )); expect( find.byType(TableViewport), paints // Row decorations ..rect( rect: const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first row rect: const Rect.fromLTRB(400.0, 500.0, 600.0, 600.0), color: const Color(0xFF2196F3), ) // Column decorations ..rect( rect: const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0), // M(0,0) color: const Color(0xff4caf50), ) ..rect( // Rest of the first column rect: const Rect.fromLTRB(700.0, 300.0, 800.0, 400.0), color: const Color(0xff4caf50), ) ..rect( // Last column rect: const Rect.fromLTRB(400.0, 500.0, 500.0, 600.0), color: const Color(0xff4caf50), ), ); }); testWidgets('Horizontal main axis, natural scroll directions', (WidgetTester tester) async { // Scenarios 1 & 2 do not mix column and row decorations, so main axis // does not affect them. // Scenario 3 await tester.pumpWidget(buildScenario3(mainAxis: Axis.horizontal)); expect( find.byType(TableViewport), paints // Column decorations ..rect( rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), // M(0,0) color: const Color(0xff4caf50), ) ..rect( // Rest of the first column rect: const Rect.fromLTRB(0.0, 200.0, 100.0, 300.0), color: const Color(0xff4caf50), ) ..rect( rect: const Rect.fromLTRB(300.0, 0.0, 400.0, 100.0), // Last column color: const Color(0xff4caf50), ) // Row decorations ..rect( rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first row rect: const Rect.fromLTRB(200.0, 0.0, 400.0, 100.0), color: const Color(0xFF2196F3), ), ); }); testWidgets('Horizontal main axis, vertical reversed', (WidgetTester tester) async { // Scenarios 1 & 2 do not mix column and row decorations, so main axis // does not affect them. // Scenario 3 await tester.pumpWidget(buildScenario3( reverseVertical: true, mainAxis: Axis.horizontal, )); expect( find.byType(TableViewport), paints // Column decorations ..rect( rect: const Rect.fromLTRB(0.0, 400.0, 200.0, 600.0), // M(0,0) color: const Color(0xff4caf50), ) ..rect( // Rest of the first column rect: const Rect.fromLTRB(0.0, 300.0, 100.0, 400.0), color: const Color(0xff4caf50), ) ..rect( // Last column rect: const Rect.fromLTRB(300.0, 500.0, 400.0, 600.0), color: const Color(0xff4caf50), ) // Row decorations ..rect( rect: const Rect.fromLTRB(0.0, 400.0, 200.0, 600.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first row rect: const Rect.fromLTRB(200.0, 500.0, 400.0, 600.0), color: const Color(0xFF2196F3), ), ); }); testWidgets('Horizontal main axis, horizontal reversed', (WidgetTester tester) async { // Scenarios 1 & 2 do not mix column and row decorations, so main axis // does not affect them. // Scenario 3 await tester.pumpWidget(buildScenario3( reverseHorizontal: true, mainAxis: Axis.horizontal, )); expect( find.byType(TableViewport), paints // Column decorations ..rect( rect: const Rect.fromLTRB(600.0, 0.0, 800.0, 200.0), // M(0,0) color: const Color(0xff4caf50), ) ..rect( // Rest of the first column rect: const Rect.fromLTRB(700.0, 200.0, 800.0, 300.0), color: const Color(0xff4caf50), ) ..rect( rect: const Rect.fromLTRB(400.0, 0.0, 500.0, 100.0), // Last column color: const Color(0xff4caf50), ) // Row decorations ..rect( rect: const Rect.fromLTRB(600.0, 0.0, 800.0, 200.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first row rect: const Rect.fromLTRB(400.0, 0.0, 600.0, 100.0), color: const Color(0xFF2196F3), ), ); }); testWidgets('Horizontal main axis, both reversed', (WidgetTester tester) async { // Scenarios 1 & 2 do not mix column and row decorations, so main axis // does not affect them. // Scenario 3 await tester.pumpWidget(buildScenario3( reverseHorizontal: true, reverseVertical: true, mainAxis: Axis.horizontal, )); expect( find.byType(TableViewport), paints // Column decorations ..rect( rect: const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0), // M(0,0) color: const Color(0xff4caf50), ) ..rect( // Rest of the first column rect: const Rect.fromLTRB(700.0, 300.0, 800.0, 400.0), color: const Color(0xff4caf50), ) ..rect( rect: const Rect.fromLTRB(400.0, 500.0, 500.0, 600.0), // Last column color: const Color(0xff4caf50), ) // Row decorations ..rect( rect: const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0), // M(0,0) color: const Color(0xFF2196F3), ) ..rect( // Rest of the unmerged first row rect: const Rect.fromLTRB(400.0, 500.0, 600.0, 600.0), color: const Color(0xFF2196F3), ), ); }); }); testWidgets('merged cells account for row/column padding', (WidgetTester tester) async { // Leading padding on the leading cell, and trailing padding on the // trailing cell should be excluded. Interim leading/trailing // paddings are consumed by the merged cell. // Example: This is one whole cell spanning 2 merged columns. // l indicates leading padding, t trailing padding // +---------------------------------------------------------+ // | l | column extent | t | l | column extent | t | // +---------------------------------------------------------+ // | <--------- extent of merged cell ---------> | // Merged Row await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TableView.builder( rowCount: 2, columnCount: 1, cellBuilder: (_, __) { return const TableViewCell( rowMergeStart: 0, rowMergeSpan: 2, child: Text('M(0,0)'), ); }, columnBuilder: (_) => const TableSpan(extent: FixedTableSpanExtent(100.0)), rowBuilder: (_) { return const TableSpan( extent: FixedTableSpanExtent(100.0), padding: TableSpanPadding(leading: 10.0, trailing: 15.0), ); }, ), ), ); await tester.pumpAndSettle(); expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(0.0, 10.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 225.0)); // Merged Column await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TableView.builder( rowCount: 1, columnCount: 2, cellBuilder: (_, __) { return const TableViewCell( columnMergeStart: 0, columnMergeSpan: 2, child: Text('M(0,0)'), ); }, rowBuilder: (_) => const TableSpan( extent: FixedTableSpanExtent(100.0), ), columnBuilder: (_) { return const TableSpan( extent: FixedTableSpanExtent(100.0), padding: TableSpanPadding(leading: 10.0, trailing: 15.0), ); }, ), ), ); await tester.pumpAndSettle(); expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(10.0, 0)); expect(tester.getSize(find.text('M(0,0)')), const Size(225.0, 100.0)); // Merged Square await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TableView.builder( rowCount: 2, columnCount: 2, cellBuilder: (_, __) { return const TableViewCell( rowMergeStart: 0, rowMergeSpan: 2, columnMergeStart: 0, columnMergeSpan: 2, child: Text('M(0,0)'), ); }, columnBuilder: (_) { return const TableSpan( extent: FixedTableSpanExtent(100.0), padding: TableSpanPadding(leading: 10.0, trailing: 15.0), ); }, rowBuilder: (_) { return const TableSpan( extent: FixedTableSpanExtent(100.0), padding: TableSpanPadding(leading: 10.0, trailing: 15.0), ); }, ), ), ); await tester.pumpAndSettle(); expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(10.0, 10.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(225.0, 225.0)); }); } class TestCanvas implements Canvas { final List<Invocation> noSuchMethodInvocations = <Invocation>[]; late Rect rect; late Paint paint; @override void drawRect(Rect rect, Paint paint) { this.rect = rect; this.paint = paint; } @override void noSuchMethod(Invocation invocation) { noSuchMethodInvocations.add(invocation); } } class TestTableSpanBorder extends TableSpanBorder { TestTableSpanBorder({super.leading}); TableSpanDecorationPaintDetails? details; BorderRadius? radius; @override void paint(TableSpanDecorationPaintDetails details, BorderRadius? radius) { this.details = details; this.radius = radius; } }
packages/packages/two_dimensional_scrollables/test/table_view/table_span_test.dart/0
{ "file_path": "packages/packages/two_dimensional_scrollables/test/table_view/table_span_test.dart", "repo_id": "packages", "token_count": 29923 }
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. import 'package:flutter_test/flutter_test.dart'; import 'package:url_launcher/src/types.dart'; import 'package:url_launcher/src/url_launcher_uri.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import '../mocks/mock_url_launcher_platform.dart'; void main() { final MockUrlLauncher mock = MockUrlLauncher(); UrlLauncherPlatform.instance = mock; test('closeInAppWebView', () async { await closeInAppWebView(); expect(mock.closeWebViewCalled, isTrue); }); group('canLaunchUrl', () { test('handles returning true', () async { final Uri url = Uri.parse('https://flutter.dev'); mock ..setCanLaunchExpectations(url.toString()) ..setResponse(true); final bool result = await canLaunchUrl(url); expect(result, isTrue); }); test('handles returning false', () async { final Uri url = Uri.parse('https://flutter.dev'); mock ..setCanLaunchExpectations(url.toString()) ..setResponse(false); final bool result = await canLaunchUrl(url); expect(result, isFalse); }); }); group('launchUrl', () { test('default behavior with web URL', () async { final Uri url = Uri.parse('https://flutter.dev'); mock ..setLaunchExpectations( url: url.toString(), launchMode: PreferredLaunchMode.platformDefault, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect(await launchUrl(url), isTrue); }); test('default behavior with non-web URL', () async { final Uri url = Uri.parse('customscheme:foo'); mock ..setLaunchExpectations( url: url.toString(), launchMode: PreferredLaunchMode.platformDefault, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect(await launchUrl(url), isTrue); }); test('explicit default launch mode with web URL', () async { final Uri url = Uri.parse('https://flutter.dev'); mock ..setLaunchExpectations( url: url.toString(), launchMode: PreferredLaunchMode.platformDefault, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect(await launchUrl(url), isTrue); }); test('explicit default launch mode with non-web URL', () async { final Uri url = Uri.parse('customscheme:foo'); mock ..setLaunchExpectations( url: url.toString(), launchMode: PreferredLaunchMode.platformDefault, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect(await launchUrl(url), isTrue); }); test('in-app webview', () async { final Uri url = Uri.parse('https://flutter.dev'); mock ..setLaunchExpectations( url: url.toString(), launchMode: PreferredLaunchMode.inAppWebView, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect(await launchUrl(url, mode: LaunchMode.inAppWebView), isTrue); }); test('external browser', () async { final Uri url = Uri.parse('https://flutter.dev'); mock ..setLaunchExpectations( url: url.toString(), launchMode: PreferredLaunchMode.externalApplication, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect( await launchUrl(url, mode: LaunchMode.externalApplication), isTrue); }); test('external non-browser only', () async { final Uri url = Uri.parse('https://flutter.dev'); mock ..setLaunchExpectations( url: url.toString(), launchMode: PreferredLaunchMode.externalNonBrowserApplication, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: true, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect( await launchUrl(url, mode: LaunchMode.externalNonBrowserApplication), isTrue); }); test('in-app webview without javascript', () async { final Uri url = Uri.parse('https://flutter.dev'); mock ..setLaunchExpectations( url: url.toString(), launchMode: PreferredLaunchMode.inAppWebView, enableJavaScript: false, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect( await launchUrl(url, mode: LaunchMode.inAppWebView, webViewConfiguration: const WebViewConfiguration(enableJavaScript: false)), isTrue); }); test('in-app webview without DOM storage', () async { final Uri url = Uri.parse('https://flutter.dev'); mock ..setLaunchExpectations( url: url.toString(), launchMode: PreferredLaunchMode.inAppWebView, enableJavaScript: true, enableDomStorage: false, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect( await launchUrl(url, mode: LaunchMode.inAppWebView, webViewConfiguration: const WebViewConfiguration(enableDomStorage: false)), isTrue); }); test('in-app webview with headers', () async { final Uri url = Uri.parse('https://flutter.dev'); mock ..setLaunchExpectations( url: url.toString(), launchMode: PreferredLaunchMode.inAppWebView, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{'key': 'value'}, webOnlyWindowName: null, ) ..setResponse(true); expect( await launchUrl(url, mode: LaunchMode.inAppWebView, webViewConfiguration: const WebViewConfiguration( headers: <String, String>{'key': 'value'})), isTrue); }); test('cannot launch a non-web URL in a webview', () async { expect( () async => launchUrl(Uri(scheme: 'tel', path: '555-555-5555'), mode: LaunchMode.inAppWebView), throwsA(isA<ArgumentError>())); }); test('non-web URL with default options', () async { final Uri emailLaunchUrl = Uri( scheme: 'mailto', path: '[email protected]', queryParameters: <String, String>{'subject': 'Hello'}, ); mock ..setLaunchExpectations( url: emailLaunchUrl.toString(), launchMode: PreferredLaunchMode.platformDefault, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect(await launchUrl(emailLaunchUrl), isTrue); }); }); group('supportsLaunchMode', () { test('handles returning true', () async { mock.setResponse(true); expect(await supportsLaunchMode(LaunchMode.inAppBrowserView), true); expect(mock.launchMode, PreferredLaunchMode.inAppBrowserView); }); test('handles returning false', () async { mock.setResponse(false); expect(await supportsLaunchMode(LaunchMode.inAppBrowserView), false); expect(mock.launchMode, PreferredLaunchMode.inAppBrowserView); }); }); group('supportsCloseForLaunchMode', () { test('handles returning true', () async { mock.setResponse(true); expect( await supportsCloseForLaunchMode(LaunchMode.inAppBrowserView), true); expect(mock.launchMode, PreferredLaunchMode.inAppBrowserView); }); test('handles returning false', () async { mock.setResponse(false); expect( await supportsCloseForLaunchMode(LaunchMode.inAppBrowserView), false); expect(mock.launchMode, PreferredLaunchMode.inAppBrowserView); }); }); }
packages/packages/url_launcher/url_launcher/test/src/url_launcher_uri_test.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher/test/src/url_launcher_uri_test.dart", "repo_id": "packages", "token_count": 3858 }
1,148
name: url_launcher_example description: Demonstrates how to use the url_launcher plugin. publish_to: none environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: flutter: sdk: flutter url_launcher_android: # When depending on this package from a real application you should use: # url_launcher_android: ^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.3.1 dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter mockito: 5.4.4 plugin_platform_interface: ^2.1.7 flutter: uses-material-design: true
packages/packages/url_launcher/url_launcher_android/example/pubspec.yaml/0
{ "file_path": "packages/packages/url_launcher/url_launcher_android/example/pubspec.yaml", "repo_id": "packages", "token_count": 289 }
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. // ignore_for_file: public_member_api_docs import 'dart:async'; import 'package:flutter/material.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'URL Launcher', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'URL Launcher'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { Future<void>? _launched; String _phone = ''; Future<void> _launchInBrowser(String url) async { final UrlLauncherPlatform launcher = UrlLauncherPlatform.instance; if (await launcher.canLaunch(url)) { await launcher.launch( url, useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: <String, String>{'my_header_key': 'my_header_value'}, ); } else { throw Exception('Could not launch $url'); } } Future<void> _launchInWebViewOrVC(String url) async { final UrlLauncherPlatform launcher = UrlLauncherPlatform.instance; if (await launcher.canLaunch(url)) { await launcher.launch( url, useSafariVC: true, useWebView: true, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: <String, String>{'my_header_key': 'my_header_value'}, ); } else { throw Exception('Could not launch $url'); } } Future<void> _launchInWebViewWithJavaScript(String url) async { final UrlLauncherPlatform launcher = UrlLauncherPlatform.instance; if (await launcher.canLaunch(url)) { await launcher.launch( url, useSafariVC: true, useWebView: true, enableJavaScript: true, enableDomStorage: false, universalLinksOnly: false, headers: <String, String>{}, ); } else { throw Exception('Could not launch $url'); } } Future<void> _launchInWebViewWithDomStorage(String url) async { final UrlLauncherPlatform launcher = UrlLauncherPlatform.instance; if (await launcher.canLaunch(url)) { await launcher.launch( url, useSafariVC: true, useWebView: true, enableJavaScript: false, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, ); } else { throw Exception('Could not launch $url'); } } Future<void> _launchUniversalLinkIos(String url) async { final UrlLauncherPlatform launcher = UrlLauncherPlatform.instance; if (await launcher.canLaunch(url)) { final bool nativeAppLaunchSucceeded = await launcher.launch( url, useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: true, headers: <String, String>{}, ); if (!nativeAppLaunchSucceeded) { await launcher.launch( url, useSafariVC: true, useWebView: true, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: true, headers: <String, String>{}, ); } } } Widget _launchStatus(BuildContext context, AsyncSnapshot<void> snapshot) { if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { return const Text(''); } } Future<void> _makePhoneCall(String url) async { final UrlLauncherPlatform launcher = UrlLauncherPlatform.instance; if (await launcher.canLaunch(url)) { await launcher.launch( url, useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: true, headers: <String, String>{}, ); } else { throw Exception('Could not launch $url'); } } @override Widget build(BuildContext context) { const String toLaunch = 'https://www.cylog.org/headers/'; return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: ListView( children: <Widget>[ Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.all(16.0), child: TextField( onChanged: (String text) => _phone = text, decoration: const InputDecoration( hintText: 'Input the phone number to launch')), ), ElevatedButton( onPressed: () => setState(() { _launched = _makePhoneCall('tel:$_phone'); }), child: const Text('Make phone call'), ), const Padding( padding: EdgeInsets.all(16.0), child: Text(toLaunch), ), ElevatedButton( onPressed: () => setState(() { _launched = _launchInBrowser(toLaunch); }), child: const Text('Launch in browser'), ), const Padding(padding: EdgeInsets.all(16.0)), ElevatedButton( onPressed: () => setState(() { _launched = _launchInWebViewOrVC(toLaunch); }), child: const Text('Launch in app'), ), ElevatedButton( onPressed: () => setState(() { _launched = _launchInWebViewWithJavaScript(toLaunch); }), child: const Text('Launch in app(JavaScript ON)'), ), ElevatedButton( onPressed: () => setState(() { _launched = _launchInWebViewWithDomStorage(toLaunch); }), child: const Text('Launch in app(DOM storage ON)'), ), const Padding(padding: EdgeInsets.all(16.0)), ElevatedButton( onPressed: () => setState(() { _launched = _launchUniversalLinkIos(toLaunch); }), child: const Text( 'Launch a universal link in a native app, fallback to Safari.(Youtube)'), ), const Padding(padding: EdgeInsets.all(16.0)), ElevatedButton( onPressed: () => setState(() { _launched = _launchInWebViewOrVC(toLaunch); Timer(const Duration(seconds: 5), () { UrlLauncherPlatform.instance.closeWebView(); }); }), child: const Text('Launch in app + close after 5 seconds'), ), const Padding(padding: EdgeInsets.all(16.0)), FutureBuilder<void>(future: _launched, builder: _launchStatus), ], ), ], ), ); } }
packages/packages/url_launcher/url_launcher_ios/example/lib/main.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_ios/example/lib/main.dart", "repo_id": "packages", "token_count": 3503 }
1,150
// Mocks generated by Mockito 5.4.4 from annotations // in url_launcher_ios/test/url_launcher_ios_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; import 'package:url_launcher_ios/src/messages.g.dart' as _i2; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class /// A class which mocks [UrlLauncherApi]. /// /// See the documentation for Mockito's code generation for more information. class MockUrlLauncherApi extends _i1.Mock implements _i2.UrlLauncherApi { MockUrlLauncherApi() { _i1.throwOnMissingStub(this); } @override _i3.Future<_i2.LaunchResult> canLaunchUrl(String? arg_url) => (super.noSuchMethod( Invocation.method( #canLaunchUrl, [arg_url], ), returnValue: _i3.Future<_i2.LaunchResult>.value(_i2.LaunchResult.success), ) as _i3.Future<_i2.LaunchResult>); @override _i3.Future<_i2.LaunchResult> launchUrl( String? arg_url, bool? arg_universalLinksOnly, ) => (super.noSuchMethod( Invocation.method( #launchUrl, [ arg_url, arg_universalLinksOnly, ], ), returnValue: _i3.Future<_i2.LaunchResult>.value(_i2.LaunchResult.success), ) as _i3.Future<_i2.LaunchResult>); @override _i3.Future<_i2.InAppLoadResult> openUrlInSafariViewController( String? arg_url) => (super.noSuchMethod( Invocation.method( #openUrlInSafariViewController, [arg_url], ), returnValue: _i3.Future<_i2.InAppLoadResult>.value(_i2.InAppLoadResult.success), ) as _i3.Future<_i2.InAppLoadResult>); @override _i3.Future<void> closeSafariViewController() => (super.noSuchMethod( Invocation.method( #closeSafariViewController, [], ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); }
packages/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.mocks.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.mocks.dart", "repo_id": "packages", "token_count": 1126 }
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 'package:flutter/foundation.dart'; /// The desired mode to launch a URL. /// /// Support for these modes varies by platform. Platforms that do not support /// the requested mode may substitute another mode. enum PreferredLaunchMode { /// Leaves the decision of how to launch the URL to the platform /// implementation. platformDefault, /// Loads the URL in an in-app web view (e.g., Android WebView). inAppWebView, /// Loads the URL in an in-app browser view (e.g., Android Custom Tabs, /// SFSafariViewController). inAppBrowserView, /// Passes the URL to the OS to be handled by another application. externalApplication, /// Passes the URL to the OS to be handled by another non-browser application. externalNonBrowserApplication, } /// Additional configuration options for [PreferredLaunchMode.inAppWebView]. /// /// Not all options are supported on all platforms. This is a superset of /// available options exposed across all implementations. @immutable class InAppWebViewConfiguration { /// Creates a new WebViewConfiguration with the given settings. const InAppWebViewConfiguration({ this.enableJavaScript = true, this.enableDomStorage = true, this.headers = const <String, String>{}, }); /// Whether or not JavaScript is enabled for the web content. final bool enableJavaScript; /// Whether or not DOM storage is enabled for the web content. final bool enableDomStorage; /// Additional headers to pass in the load request. final Map<String, String> headers; } /// Additional configuration options for [PreferredLaunchMode.inAppBrowserView]. @immutable class InAppBrowserConfiguration { /// Creates a new InAppBrowserConfiguration with given settings. const InAppBrowserConfiguration({this.showTitle = false}); /// Whether or not to show the webpage title. /// /// May not be supported on all platforms. final bool showTitle; } /// Options for [launchUrl]. @immutable class LaunchOptions { /// Creates a new parameter object with the given options. const LaunchOptions({ this.mode = PreferredLaunchMode.platformDefault, this.webViewConfiguration = const InAppWebViewConfiguration(), this.browserConfiguration = const InAppBrowserConfiguration(), this.webOnlyWindowName, }); /// The requested launch mode. final PreferredLaunchMode mode; /// Configuration for the web view in [PreferredLaunchMode.inAppWebView] mode. final InAppWebViewConfiguration webViewConfiguration; /// Configuration for the browser view in [PreferredLaunchMode.inAppBrowserView] mode. final InAppBrowserConfiguration browserConfiguration; /// A web-platform-specific option to set the link target. /// /// Default behaviour when unset should be to open the url in a new tab. final String? webOnlyWindowName; }
packages/packages/url_launcher/url_launcher_platform_interface/lib/src/types.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_platform_interface/lib/src/types.dart", "repo_id": "packages", "token_count": 767 }
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. #ifndef PACKAGES_URL_LAUNCHER_URL_LAUNCHER_WINDOWS_WINDOWS_INCLUDE_URL_LAUNCHER_WINDOWS_URL_LAUNCHER_PLUGIN_H_ #define PACKAGES_URL_LAUNCHER_URL_LAUNCHER_WINDOWS_WINDOWS_INCLUDE_URL_LAUNCHER_WINDOWS_URL_LAUNCHER_PLUGIN_H_ #include <flutter_plugin_registrar.h> #ifdef FLUTTER_PLUGIN_IMPL #define FLUTTER_PLUGIN_EXPORT __declspec(dllexport) #else #define FLUTTER_PLUGIN_EXPORT __declspec(dllimport) #endif #if defined(__cplusplus) extern "C" { #endif FLUTTER_PLUGIN_EXPORT void UrlLauncherWindowsRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar); #if defined(__cplusplus) } // extern "C" #endif #endif // PACKAGES_URL_LAUNCHER_URL_LAUNCHER_WINDOWS_WINDOWS_INCLUDE_URL_LAUNCHER_WINDOWS_URL_LAUNCHER_PLUGIN_H_
packages/packages/url_launcher/url_launcher_windows/windows/include/url_launcher_windows/url_launcher_windows.h/0
{ "file_path": "packages/packages/url_launcher/url_launcher_windows/windows/include/url_launcher_windows/url_launcher_windows.h", "repo_id": "packages", "token_count": 348 }
1,153
# video_player_example Demonstrates how to use the video_player plugin.
packages/packages/video_player/video_player/example/README.md/0
{ "file_path": "packages/packages/video_player/video_player/example/README.md", "repo_id": "packages", "token_count": 21 }
1,154
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
packages/packages/video_player/video_player/example/android/gradle.properties/0
{ "file_path": "packages/packages/video_player/video_player/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
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 'dart:convert'; import 'package:html/dom.dart'; import 'package:html/parser.dart' as html_parser; import 'closed_caption_file.dart'; /// Represents a [ClosedCaptionFile], parsed from the WebVTT file format. /// See: https://en.wikipedia.org/wiki/WebVTT class WebVTTCaptionFile extends ClosedCaptionFile { /// Parses a string into a [ClosedCaptionFile], assuming [fileContents] is in /// the WebVTT file format. /// * See: https://en.wikipedia.org/wiki/WebVTT WebVTTCaptionFile(String fileContents) : _captions = _parseCaptionsFromWebVTTString(fileContents); @override List<Caption> get captions => _captions; final List<Caption> _captions; } List<Caption> _parseCaptionsFromWebVTTString(String file) { final List<Caption> captions = <Caption>[]; // Ignore metadata final Set<String> metadata = <String>{'HEADER', 'NOTE', 'REGION', 'WEBVTT'}; int captionNumber = 1; for (final List<String> captionLines in _readWebVTTFile(file)) { // CaptionLines represent a complete caption. // E.g // [ // [00:00.000 --> 01:24.000 align:center] // ['Introduction'] // ] // If caption has just header or time, but no text, `captionLines.length` will be 1. if (captionLines.length < 2) { continue; } // If caption has header equal metadata, ignore. final String metadaType = captionLines[0].split(' ')[0]; if (metadata.contains(metadaType)) { continue; } // Caption has header final bool hasHeader = captionLines.length > 2; if (hasHeader) { final int? tryParseCaptionNumber = int.tryParse(captionLines[0]); if (tryParseCaptionNumber != null) { captionNumber = tryParseCaptionNumber; } } final _CaptionRange? captionRange = _CaptionRange.fromWebVTTString( hasHeader ? captionLines[1] : captionLines[0], ); if (captionRange == null) { continue; } final String text = captionLines.sublist(hasHeader ? 2 : 1).join('\n'); // TODO(cyanglaz): Handle special syntax in VTT captions. // https://github.com/flutter/flutter/issues/90007. final String textWithoutFormat = _extractTextFromHtml(text); final Caption newCaption = Caption( number: captionNumber, start: captionRange.start, end: captionRange.end, text: textWithoutFormat, ); captions.add(newCaption); captionNumber++; } return captions; } class _CaptionRange { _CaptionRange(this.start, this.end); final Duration start; final Duration end; // Assumes format from an VTT file. // For example: // 00:09.000 --> 00:11.000 static _CaptionRange? fromWebVTTString(String line) { final RegExp format = RegExp(_webVTTTimeStamp + _webVTTArrow + _webVTTTimeStamp); if (!format.hasMatch(line)) { return null; } final List<String> times = line.split(_webVTTArrow); final Duration? start = _parseWebVTTTimestamp(times[0]); final Duration? end = _parseWebVTTTimestamp(times[1]); if (start == null || end == null) { return null; } return _CaptionRange(start, end); } } String _extractTextFromHtml(String htmlString) { final Document document = html_parser.parse(htmlString); final Element? body = document.body; if (body == null) { return ''; } final Element? bodyElement = html_parser.parse(body.text).documentElement; return bodyElement?.text ?? ''; } // Parses a time stamp in an VTT file into a Duration. // // Returns `null` if `timestampString` is in an invalid format. // // For example: // // _parseWebVTTTimestamp('00:01:08.430') // returns // Duration(hours: 0, minutes: 1, seconds: 8, milliseconds: 430) Duration? _parseWebVTTTimestamp(String timestampString) { if (!RegExp(_webVTTTimeStamp).hasMatch(timestampString)) { return null; } final List<String> dotSections = timestampString.split('.'); final List<String> timeComponents = dotSections[0].split(':'); // Validating and parsing the `timestampString`, invalid format will result this method // to return `null`. See https://www.w3.org/TR/webvtt1/#webvtt-timestamp for valid // WebVTT timestamp format. if (timeComponents.length > 3 || timeComponents.length < 2) { return null; } int hours = 0; if (timeComponents.length == 3) { final String hourString = timeComponents.removeAt(0); if (hourString.length < 2) { return null; } hours = int.parse(hourString); } final int minutes = int.parse(timeComponents.removeAt(0)); if (minutes < 0 || minutes > 59) { return null; } final int seconds = int.parse(timeComponents.removeAt(0)); if (seconds < 0 || seconds > 59) { return null; } final List<String> milisecondsStyles = dotSections[1].split(' '); // TODO(cyanglaz): Handle caption styles. // https://github.com/flutter/flutter/issues/90009. // ```dart // if (milisecondsStyles.length > 1) { // List<String> styles = milisecondsStyles.sublist(1); // } // ``` // For a better readable code style, style parsing should happen before // calling this method. See: https://github.com/flutter/plugins/pull/2878/files#r713381134. final int milliseconds = int.parse(milisecondsStyles[0]); return Duration( hours: hours, minutes: minutes, seconds: seconds, milliseconds: milliseconds, ); } // Reads on VTT file and splits it into Lists of strings where each list is one // caption. List<List<String>> _readWebVTTFile(String file) { final List<String> lines = LineSplitter.split(file).toList(); final List<List<String>> captionStrings = <List<String>>[]; List<String> currentCaption = <String>[]; int lineIndex = 0; for (final String line in lines) { final bool isLineBlank = line.trim().isEmpty; if (!isLineBlank) { currentCaption.add(line); } if (isLineBlank || lineIndex == lines.length - 1) { captionStrings.add(currentCaption); currentCaption = <String>[]; } lineIndex += 1; } return captionStrings; } const String _webVTTTimeStamp = r'(\d+):(\d{2})(:\d{2})?\.(\d{3})'; const String _webVTTArrow = r' --> ';
packages/packages/video_player/video_player/lib/src/web_vtt.dart/0
{ "file_path": "packages/packages/video_player/video_player/lib/src/web_vtt.dart", "repo_id": "packages", "token_count": 2253 }
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. package io.flutter.plugins.videoplayer; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; // SSLSocketFactory does not have nullability annotations. @SuppressWarnings("UnknownNullness") public class CustomSSLSocketFactory extends SSLSocketFactory { private final SSLSocketFactory sslSocketFactory; public CustomSSLSocketFactory() throws KeyManagementException, NoSuchAlgorithmException { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, null, null); sslSocketFactory = context.getSocketFactory(); } @Override public String[] getDefaultCipherSuites() { return sslSocketFactory.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return sslSocketFactory.getSupportedCipherSuites(); } @Override public Socket createSocket() throws IOException { return enableProtocols(sslSocketFactory.createSocket()); } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { return enableProtocols(sslSocketFactory.createSocket(s, host, port, autoClose)); } @Override public Socket createSocket(String host, int port) throws IOException { return enableProtocols(sslSocketFactory.createSocket(host, port)); } @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { return enableProtocols(sslSocketFactory.createSocket(host, port, localHost, localPort)); } @Override public Socket createSocket(InetAddress host, int port) throws IOException { return enableProtocols(sslSocketFactory.createSocket(host, port)); } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return enableProtocols(sslSocketFactory.createSocket(address, port, localAddress, localPort)); } private Socket enableProtocols(Socket socket) { if (socket instanceof SSLSocket) { ((SSLSocket) socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"}); } return socket; } }
packages/packages/video_player/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/CustomSSLSocketFactory.java/0
{ "file_path": "packages/packages/video_player/video_player_android/android/src/main/java/io/flutter/plugins/videoplayer/CustomSSLSocketFactory.java", "repo_id": "packages", "token_count": 753 }
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 'package:flutter/material.dart'; import 'mini_controller.dart'; void main() { runApp( MaterialApp( home: _App(), ), ); } class _App extends StatelessWidget { @override Widget build(BuildContext context) { return DefaultTabController( length: 2, child: Scaffold( key: const ValueKey<String>('home_page'), appBar: AppBar( title: const Text('Video player example'), bottom: const TabBar( isScrollable: true, tabs: <Widget>[ Tab( icon: Icon(Icons.cloud), text: 'Remote', ), Tab(icon: Icon(Icons.insert_drive_file), text: 'Asset'), ], ), ), body: TabBarView( children: <Widget>[ _BumbleBeeRemoteVideo(), _ButterFlyAssetVideo(), ], ), ), ); } } class _ButterFlyAssetVideo extends StatefulWidget { @override _ButterFlyAssetVideoState createState() => _ButterFlyAssetVideoState(); } class _ButterFlyAssetVideoState extends State<_ButterFlyAssetVideo> { late MiniController _controller; @override void initState() { super.initState(); _controller = MiniController.asset('assets/Butterfly-209.mp4'); _controller.addListener(() { setState(() {}); }); _controller.initialize().then((_) => setState(() {})); _controller.play(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return SingleChildScrollView( child: Column( children: <Widget>[ Container( padding: const EdgeInsets.only(top: 20.0), ), const Text('With assets mp4'), Container( padding: const EdgeInsets.all(20), child: AspectRatio( aspectRatio: _controller.value.aspectRatio, child: Stack( alignment: Alignment.bottomCenter, children: <Widget>[ VideoPlayer(_controller), _ControlsOverlay(controller: _controller), VideoProgressIndicator(_controller), ], ), ), ), ], ), ); } } class _BumbleBeeRemoteVideo extends StatefulWidget { @override _BumbleBeeRemoteVideoState createState() => _BumbleBeeRemoteVideoState(); } class _BumbleBeeRemoteVideoState extends State<_BumbleBeeRemoteVideo> { late MiniController _controller; @override void initState() { super.initState(); _controller = MiniController.network( 'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4', ); _controller.addListener(() { setState(() {}); }); _controller.initialize(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return SingleChildScrollView( child: Column( children: <Widget>[ Container(padding: const EdgeInsets.only(top: 20.0)), const Text('With remote mp4'), Container( padding: const EdgeInsets.all(20), child: AspectRatio( aspectRatio: _controller.value.aspectRatio, child: Stack( alignment: Alignment.bottomCenter, children: <Widget>[ VideoPlayer(_controller), _ControlsOverlay(controller: _controller), VideoProgressIndicator(_controller), ], ), ), ), ], ), ); } } class _ControlsOverlay extends StatelessWidget { const _ControlsOverlay({required this.controller}); static const List<double> _examplePlaybackRates = <double>[ 0.25, 0.5, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0, ]; final MiniController controller; @override Widget build(BuildContext context) { return Stack( children: <Widget>[ AnimatedSwitcher( duration: const Duration(milliseconds: 50), reverseDuration: const Duration(milliseconds: 200), child: controller.value.isPlaying ? const SizedBox.shrink() : const ColoredBox( color: Colors.black26, child: Center( child: Icon( Icons.play_arrow, color: Colors.white, size: 100.0, semanticLabel: 'Play', ), ), ), ), GestureDetector( onTap: () { controller.value.isPlaying ? controller.pause() : controller.play(); }, ), Align( alignment: Alignment.topRight, child: PopupMenuButton<double>( initialValue: controller.value.playbackSpeed, tooltip: 'Playback speed', onSelected: (double speed) { controller.setPlaybackSpeed(speed); }, itemBuilder: (BuildContext context) { return <PopupMenuItem<double>>[ for (final double speed in _examplePlaybackRates) PopupMenuItem<double>( value: speed, child: Text('${speed}x'), ) ]; }, child: Padding( padding: const EdgeInsets.symmetric( // Using less vertical padding as the text is also longer // horizontally, so it feels like it would need more spacing // horizontally (matching the aspect ratio of the video). vertical: 12, horizontal: 16, ), child: Text('${controller.value.playbackSpeed}x'), ), ), ), ], ); } }
packages/packages/video_player/video_player_android/example/lib/main.dart/0
{ "file_path": "packages/packages/video_player/video_player_android/example/lib/main.dart", "repo_id": "packages", "token_count": 2978 }
1,158
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/video_player/video_player_avfoundation/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/video_player/video_player_avfoundation/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
1,159
// 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 // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import // ignore_for_file: avoid_relative_lib_imports 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'; import 'package:flutter_test/flutter_test.dart'; import 'package:video_player_avfoundation/src/messages.g.dart'; class _TestHostVideoPlayerApiCodec extends StandardMessageCodec { const _TestHostVideoPlayerApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is CreateMessage) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is LoopingMessage) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is MixWithOthersMessage) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else if (value is PlaybackSpeedMessage) { buffer.putUint8(131); writeValue(buffer, value.encode()); } else if (value is PositionMessage) { buffer.putUint8(132); writeValue(buffer, value.encode()); } else if (value is TextureMessage) { buffer.putUint8(133); writeValue(buffer, value.encode()); } else if (value is VolumeMessage) { buffer.putUint8(134); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return CreateMessage.decode(readValue(buffer)!); case 129: return LoopingMessage.decode(readValue(buffer)!); case 130: return MixWithOthersMessage.decode(readValue(buffer)!); case 131: return PlaybackSpeedMessage.decode(readValue(buffer)!); case 132: return PositionMessage.decode(readValue(buffer)!); case 133: return TextureMessage.decode(readValue(buffer)!); case 134: return VolumeMessage.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } abstract class TestHostVideoPlayerApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = _TestHostVideoPlayerApiCodec(); void initialize(); TextureMessage create(CreateMessage msg); void dispose(TextureMessage msg); void setLooping(LoopingMessage msg); void setVolume(VolumeMessage msg); void setPlaybackSpeed(PlaybackSpeedMessage msg); void play(TextureMessage msg); PositionMessage position(TextureMessage msg); Future<void> seekTo(PositionMessage msg); void pause(TextureMessage msg); void setMixWithOthers(MixWithOthersMessage msg); static void setup(TestHostVideoPlayerApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.initialize', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { try { api.initialize(); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.create', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.create was null.'); final List<Object?> args = (message as List<Object?>?)!; final CreateMessage? arg_msg = (args[0] as CreateMessage?); assert(arg_msg != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.create was null, expected non-null CreateMessage.'); try { final TextureMessage output = api.create(arg_msg!); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.dispose', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.dispose was null.'); final List<Object?> args = (message as List<Object?>?)!; final TextureMessage? arg_msg = (args[0] as TextureMessage?); assert(arg_msg != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.dispose was null, expected non-null TextureMessage.'); try { api.dispose(arg_msg!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.setLooping', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.setLooping was null.'); final List<Object?> args = (message as List<Object?>?)!; final LoopingMessage? arg_msg = (args[0] as LoopingMessage?); assert(arg_msg != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.setLooping was null, expected non-null LoopingMessage.'); try { api.setLooping(arg_msg!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.setVolume', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.setVolume was null.'); final List<Object?> args = (message as List<Object?>?)!; final VolumeMessage? arg_msg = (args[0] as VolumeMessage?); assert(arg_msg != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.setVolume was null, expected non-null VolumeMessage.'); try { api.setVolume(arg_msg!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.setPlaybackSpeed', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.setPlaybackSpeed was null.'); final List<Object?> args = (message as List<Object?>?)!; final PlaybackSpeedMessage? arg_msg = (args[0] as PlaybackSpeedMessage?); assert(arg_msg != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.setPlaybackSpeed was null, expected non-null PlaybackSpeedMessage.'); try { api.setPlaybackSpeed(arg_msg!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.play', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.play was null.'); final List<Object?> args = (message as List<Object?>?)!; final TextureMessage? arg_msg = (args[0] as TextureMessage?); assert(arg_msg != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.play was null, expected non-null TextureMessage.'); try { api.play(arg_msg!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.position', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.position was null.'); final List<Object?> args = (message as List<Object?>?)!; final TextureMessage? arg_msg = (args[0] as TextureMessage?); assert(arg_msg != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.position was null, expected non-null TextureMessage.'); try { final PositionMessage output = api.position(arg_msg!); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.seekTo', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.seekTo was null.'); final List<Object?> args = (message as List<Object?>?)!; final PositionMessage? arg_msg = (args[0] as PositionMessage?); assert(arg_msg != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.seekTo was null, expected non-null PositionMessage.'); try { await api.seekTo(arg_msg!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.pause', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.pause was null.'); final List<Object?> args = (message as List<Object?>?)!; final TextureMessage? arg_msg = (args[0] as TextureMessage?); assert(arg_msg != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.pause was null, expected non-null TextureMessage.'); try { api.pause(arg_msg!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.setMixWithOthers', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.setMixWithOthers was null.'); final List<Object?> args = (message as List<Object?>?)!; final MixWithOthersMessage? arg_msg = (args[0] as MixWithOthersMessage?); assert(arg_msg != null, 'Argument for dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.setMixWithOthers was null, expected non-null MixWithOthersMessage.'); try { api.setMixWithOthers(arg_msg!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } }
packages/packages/video_player/video_player_avfoundation/test/test_api.g.dart/0
{ "file_path": "packages/packages/video_player/video_player_avfoundation/test/test_api.g.dart", "repo_id": "packages", "token_count": 7880 }
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 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:video_player_web/src/duration_utils.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('convertNumVideoDurationToPluginDuration', () { testWidgets('Finite value converts to milliseconds', (WidgetTester _) async { final Duration? result = convertNumVideoDurationToPluginDuration(1.5); final Duration? zero = convertNumVideoDurationToPluginDuration(0.0001); expect(result, isNotNull); expect(result!.inMilliseconds, equals(1500)); expect(zero, equals(Duration.zero)); }); testWidgets('Finite value rounds 3rd decimal value', (WidgetTester _) async { final Duration? result = convertNumVideoDurationToPluginDuration(1.567899089087); final Duration? another = convertNumVideoDurationToPluginDuration(1.567199089087); expect(result, isNotNull); expect(result!.inMilliseconds, equals(1568)); expect(another!.inMilliseconds, equals(1567)); }); testWidgets('Infinite value returns magic constant', (WidgetTester _) async { final Duration? result = convertNumVideoDurationToPluginDuration(double.infinity); expect(result, isNotNull); expect(result, equals(jsCompatibleTimeUnset)); expect(result!.inMilliseconds, equals(-9007199254740990)); }); testWidgets('NaN value returns null', (WidgetTester _) async { final Duration? result = convertNumVideoDurationToPluginDuration(double.nan); expect(result, isNull); }); }); }
packages/packages/video_player/video_player_web/example/integration_test/duration_utils_test.dart/0
{ "file_path": "packages/packages/video_player/video_player_web/example/integration_test/duration_utils_test.dart", "repo_id": "packages", "token_count": 644 }
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. // 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/analysis.dart'; void main() { group('averageBenchmarkResults', () { test('succeeds for identical benchmark names and metrics', () { final BenchmarkResults result1 = BenchmarkResults( <String, List<BenchmarkScore>>{ 'foo': <BenchmarkScore>[ BenchmarkScore(metric: 'foo.bar', value: 6), BenchmarkScore(metric: 'foo.baz', value: 10), ], 'bar': <BenchmarkScore>[ BenchmarkScore(metric: 'bar.foo', value: 2.4), ], }, ); final BenchmarkResults result2 = BenchmarkResults( <String, List<BenchmarkScore>>{ 'foo': <BenchmarkScore>[ BenchmarkScore(metric: 'foo.bar', value: 4), BenchmarkScore(metric: 'foo.baz', value: 10), ], 'bar': <BenchmarkScore>[ BenchmarkScore(metric: 'bar.foo', value: 1.2), ], }, ); final BenchmarkResults average = computeAverage(<BenchmarkResults>[result1, result2]); expect( average.toJson(), <String, List<Map<String, Object?>>>{ 'foo': <Map<String, Object?>>[ <String, Object?>{'metric': 'foo.bar', 'value': 5}, <String, Object?>{'metric': 'foo.baz', 'value': 10}, ], 'bar': <Map<String, Object?>>[ <String, Object?>{'metric': 'bar.foo', 'value': 1.7999999999999998}, ], }, ); }); test('fails for mismatched benchmark names', () { final BenchmarkResults result1 = BenchmarkResults( <String, List<BenchmarkScore>>{ 'foo': <BenchmarkScore>[BenchmarkScore(metric: 'foo.bar', value: 6)], }, ); final BenchmarkResults result2 = BenchmarkResults( <String, List<BenchmarkScore>>{ 'foo1': <BenchmarkScore>[BenchmarkScore(metric: 'foo.bar', value: 4)], }, ); expect( () { computeAverage(<BenchmarkResults>[result1, result2]); }, throwsException, ); }); test('fails for mismatched benchmark metrics', () { final BenchmarkResults result1 = BenchmarkResults( <String, List<BenchmarkScore>>{ 'foo': <BenchmarkScore>[BenchmarkScore(metric: 'foo.bar', value: 6)], }, ); final BenchmarkResults result2 = BenchmarkResults( <String, List<BenchmarkScore>>{ 'foo': <BenchmarkScore>[BenchmarkScore(metric: 'foo.boo', value: 4)], }, ); expect( () { computeAverage(<BenchmarkResults>[result1, result2]); }, throwsException, ); }); }); test('computeDelta', () { final BenchmarkResults benchmark1 = BenchmarkResults.parse(testBenchmarkResults1); final BenchmarkResults benchmark2 = BenchmarkResults.parse(testBenchmarkResults2); final BenchmarkResults delta = computeDelta(benchmark1, benchmark2); expect(delta.toJson(), expectedBenchmarkDelta); }); } final Map<String, List<Map<String, Object?>>> testBenchmarkResults1 = <String, List<Map<String, Object?>>>{ 'foo': <Map<String, Object?>>[ <String, Object?>{'metric': 'preroll_frame.average', 'value': 60.5}, <String, Object?>{'metric': 'preroll_frame.outlierAverage', 'value': 1400}, <String, Object?>{'metric': 'preroll_frame.outlierRatio', 'value': 20.2}, <String, Object?>{'metric': 'preroll_frame.noise', 'value': 0.85}, <String, Object?>{'metric': 'apply_frame.average', 'value': 80.0}, <String, Object?>{'metric': 'apply_frame.outlierAverage', 'value': 200.6}, <String, Object?>{'metric': 'apply_frame.outlierRatio', 'value': 2.5}, <String, Object?>{'metric': 'apply_frame.noise', 'value': 0.4}, <String, Object?>{'metric': 'drawFrameDuration.average', 'value': 2058.9}, <String, Object?>{ 'metric': 'drawFrameDuration.outlierAverage', 'value': 24000, }, <String, Object?>{ 'metric': 'drawFrameDuration.outlierRatio', 'value': 12.05, }, <String, Object?>{'metric': 'drawFrameDuration.noise', 'value': 0.34}, <String, Object?>{'metric': 'totalUiFrame.average', 'value': 4166}, ], 'bar': <Map<String, Object?>>[ <String, Object?>{'metric': 'preroll_frame.average', 'value': 60.5}, <String, Object?>{'metric': 'preroll_frame.outlierAverage', 'value': 1400}, <String, Object?>{'metric': 'preroll_frame.outlierRatio', 'value': 20.2}, <String, Object?>{'metric': 'preroll_frame.noise', 'value': 0.85}, <String, Object?>{'metric': 'apply_frame.average', 'value': 80.0}, <String, Object?>{'metric': 'apply_frame.outlierAverage', 'value': 200.6}, <String, Object?>{'metric': 'apply_frame.outlierRatio', 'value': 2.5}, <String, Object?>{'metric': 'apply_frame.noise', 'value': 0.4}, <String, Object?>{'metric': 'drawFrameDuration.average', 'value': 2058.9}, <String, Object?>{ 'metric': 'drawFrameDuration.outlierAverage', 'value': 24000, }, <String, Object?>{ 'metric': 'drawFrameDuration.outlierRatio', 'value': 12.05, }, <String, Object?>{'metric': 'drawFrameDuration.noise', 'value': 0.34}, <String, Object?>{'metric': 'totalUiFrame.average', 'value': 4166}, ], }; final Map<String, List<Map<String, Object?>>> testBenchmarkResults2 = <String, List<Map<String, Object?>>>{ 'foo': <Map<String, Object?>>[ <String, Object?>{'metric': 'preroll_frame.average', 'value': 65.5}, <String, Object?>{'metric': 'preroll_frame.outlierAverage', 'value': 1410}, <String, Object?>{'metric': 'preroll_frame.outlierRatio', 'value': 20.0}, <String, Object?>{'metric': 'preroll_frame.noise', 'value': 1.5}, <String, Object?>{'metric': 'apply_frame.average', 'value': 50.0}, <String, Object?>{'metric': 'apply_frame.outlierAverage', 'value': 100.0}, <String, Object?>{'metric': 'apply_frame.outlierRatio', 'value': 2.55}, <String, Object?>{'metric': 'apply_frame.noise', 'value': 0.9}, <String, Object?>{'metric': 'drawFrameDuration.average', 'value': 2000.0}, <String, Object?>{ 'metric': 'drawFrameDuration.outlierAverage', 'value': 20000 }, <String, Object?>{ 'metric': 'drawFrameDuration.outlierRatio', 'value': 11.05 }, <String, Object?>{'metric': 'drawFrameDuration.noise', 'value': 1.34}, <String, Object?>{'metric': 'totalUiFrame.average', 'value': 4150}, ], 'bar': <Map<String, Object?>>[ <String, Object?>{'metric': 'preroll_frame.average', 'value': 65.5}, <String, Object?>{'metric': 'preroll_frame.outlierAverage', 'value': 1410}, <String, Object?>{'metric': 'preroll_frame.outlierRatio', 'value': 20.0}, <String, Object?>{'metric': 'preroll_frame.noise', 'value': 1.5}, <String, Object?>{'metric': 'apply_frame.average', 'value': 50.0}, <String, Object?>{'metric': 'apply_frame.outlierAverage', 'value': 100.0}, <String, Object?>{'metric': 'apply_frame.outlierRatio', 'value': 2.55}, <String, Object?>{'metric': 'apply_frame.noise', 'value': 0.9}, <String, Object?>{'metric': 'drawFrameDuration.average', 'value': 2000.0}, <String, Object?>{ 'metric': 'drawFrameDuration.outlierAverage', 'value': 20000 }, <String, Object?>{ 'metric': 'drawFrameDuration.outlierRatio', 'value': 11.05 }, <String, Object?>{'metric': 'drawFrameDuration.noise', 'value': 1.34}, <String, Object?>{'metric': 'totalUiFrame.average', 'value': 4150}, ], }; final Map<String, List<Map<String, Object?>>> expectedBenchmarkDelta = <String, List<Map<String, Object?>>>{ 'foo': <Map<String, Object?>>[ <String, Object?>{ 'metric': 'preroll_frame.average', 'value': 65.5, 'delta': 5.0 }, <String, Object?>{ 'metric': 'preroll_frame.outlierAverage', 'value': 1410.0, 'delta': 10.0, }, <String, Object?>{ 'metric': 'preroll_frame.outlierRatio', 'value': 20.0, 'delta': -0.1999999999999993, }, <String, Object?>{ 'metric': 'preroll_frame.noise', 'value': 1.5, 'delta': 0.65, }, <String, Object?>{ 'metric': 'apply_frame.average', 'value': 50.0, 'delta': -30.0, }, <String, Object?>{ 'metric': 'apply_frame.outlierAverage', 'value': 100.0, 'delta': -100.6, }, <String, Object?>{ 'metric': 'apply_frame.outlierRatio', 'value': 2.55, 'delta': 0.04999999999999982, }, <String, Object?>{ 'metric': 'apply_frame.noise', 'value': 0.9, 'delta': 0.5, }, <String, Object?>{ 'metric': 'drawFrameDuration.average', 'value': 2000.0, 'delta': -58.90000000000009, }, <String, Object?>{ 'metric': 'drawFrameDuration.outlierAverage', 'value': 20000.0, 'delta': -4000.0, }, <String, Object?>{ 'metric': 'drawFrameDuration.outlierRatio', 'value': 11.05, 'delta': -1.0, }, <String, Object?>{ 'metric': 'drawFrameDuration.noise', 'value': 1.34, 'delta': 1.0, }, <String, Object?>{ 'metric': 'totalUiFrame.average', 'value': 4150.0, 'delta': -16.0, }, ], 'bar': <Map<String, Object?>>[ <String, Object?>{ 'metric': 'preroll_frame.average', 'value': 65.5, 'delta': 5.0, }, <String, Object?>{ 'metric': 'preroll_frame.outlierAverage', 'value': 1410.0, 'delta': 10.0, }, <String, Object?>{ 'metric': 'preroll_frame.outlierRatio', 'value': 20.0, 'delta': -0.1999999999999993, }, <String, Object?>{ 'metric': 'preroll_frame.noise', 'value': 1.5, 'delta': 0.65, }, <String, Object?>{ 'metric': 'apply_frame.average', 'value': 50.0, 'delta': -30.0, }, <String, Object?>{ 'metric': 'apply_frame.outlierAverage', 'value': 100.0, 'delta': -100.6, }, <String, Object?>{ 'metric': 'apply_frame.outlierRatio', 'value': 2.55, 'delta': 0.04999999999999982, }, <String, Object?>{ 'metric': 'apply_frame.noise', 'value': 0.9, 'delta': 0.5, }, <String, Object?>{ 'metric': 'drawFrameDuration.average', 'value': 2000.0, 'delta': -58.90000000000009, }, <String, Object?>{ 'metric': 'drawFrameDuration.outlierAverage', 'value': 20000.0, 'delta': -4000.0, }, <String, Object?>{ 'metric': 'drawFrameDuration.outlierRatio', 'value': 11.05, 'delta': -1.0, }, <String, Object?>{ 'metric': 'drawFrameDuration.noise', 'value': 1.34, 'delta': 1.0, }, <String, Object?>{ 'metric': 'totalUiFrame.average', 'value': 4150.0, 'delta': -16.0, }, ], };
packages/packages/web_benchmarks/test/src/analysis_test.dart/0
{ "file_path": "packages/packages/web_benchmarks/test/src/analysis_test.dart", "repo_id": "packages", "token_count": 5054 }
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. // ignore_for_file: unnecessary_statements import 'package:flutter_test/flutter_test.dart'; import 'package:webview_flutter/webview_flutter.dart' as main_file; void main() { group('webview_flutter', () { test( 'ensure webview_flutter.dart exports classes from platform interface', () { main_file.HttpAuthRequest; main_file.JavaScriptConsoleMessage; main_file.JavaScriptLogLevel; main_file.JavaScriptMessage; main_file.JavaScriptMode; main_file.LoadRequestMethod; main_file.NavigationDecision; main_file.NavigationRequest; main_file.NavigationRequestCallback; main_file.PageEventCallback; main_file.PlatformNavigationDelegateCreationParams; main_file.PlatformWebViewControllerCreationParams; main_file.PlatformWebViewCookieManagerCreationParams; main_file.PlatformWebViewPermissionRequest; main_file.PlatformWebViewWidgetCreationParams; main_file.ProgressCallback; main_file.WebViewPermissionResourceType; main_file.WebResourceError; main_file.WebResourceErrorCallback; main_file.WebViewCookie; main_file.WebViewCredential; main_file.WebResourceErrorType; main_file.UrlChange; }, ); }); }
packages/packages/webview_flutter/webview_flutter/test/webview_flutter_export_test.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter/test/webview_flutter_export_test.dart", "repo_id": "packages", "token_count": 574 }
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. package io.flutter.plugins.webviewflutter; import android.os.Build; import android.webkit.WebChromeClient; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import io.flutter.plugin.common.BinaryMessenger; import java.util.Arrays; /** * Flutter Api implementation for {@link android.webkit.WebChromeClient.FileChooserParams}. * * <p>Passes arguments of callbacks methods from a {@link * android.webkit.WebChromeClient.FileChooserParams} to Dart. */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public class FileChooserParamsFlutterApiImpl extends GeneratedAndroidWebView.FileChooserParamsFlutterApi { private final InstanceManager instanceManager; /** * 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 FileChooserParamsFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { super(binaryMessenger); this.instanceManager = instanceManager; } private static GeneratedAndroidWebView.FileChooserMode toFileChooserEnumData(int mode) { switch (mode) { case WebChromeClient.FileChooserParams.MODE_OPEN: return GeneratedAndroidWebView.FileChooserMode.OPEN; case WebChromeClient.FileChooserParams.MODE_OPEN_MULTIPLE: return GeneratedAndroidWebView.FileChooserMode.OPEN_MULTIPLE; case WebChromeClient.FileChooserParams.MODE_SAVE: return GeneratedAndroidWebView.FileChooserMode.SAVE; default: throw new IllegalArgumentException(String.format("Unsupported FileChooserMode: %d", mode)); } } /** * Stores the FileChooserParams instance and notifies Dart to create a new FileChooserParams * instance that is attached to this one. */ public void create( @NonNull WebChromeClient.FileChooserParams instance, @NonNull Reply<Void> callback) { if (!instanceManager.containsInstance(instance)) { create( instanceManager.addHostCreatedInstance(instance), instance.isCaptureEnabled(), Arrays.asList(instance.getAcceptTypes()), toFileChooserEnumData(instance.getMode()), instance.getFilenameHint(), callback); } } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/FileChooserParamsFlutterApiImpl.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/FileChooserParamsFlutterApiImpl.java", "repo_id": "packages", "token_count": 839 }
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. package io.flutter.plugins.webviewflutter; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.ViewFlutterApi; /** * Flutter API implementation for `View`. * * <p>This class may handle adding native instances that are attached to a Dart instance or passing * arguments of callbacks methods to a Dart instance. */ public class ViewFlutterApiImpl { // To ease adding additional methods, this value is added prematurely. @SuppressWarnings({"unused", "FieldCanBeLocal"}) private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; private ViewFlutterApi api; /** * Constructs a {@link ViewFlutterApiImpl}. * * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param instanceManager maintains instances stored to communicate with attached Dart objects */ public ViewFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; api = new ViewFlutterApi(binaryMessenger); } /** * Stores the `View` instance and notifies Dart to create and store a new `View` instance that is * attached to this one. If `instance` has already been added, this method does nothing. */ public void create(@NonNull View instance, @NonNull ViewFlutterApi.Reply<Void> callback) { if (!instanceManager.containsInstance(instance)) { api.create(instanceManager.addHostCreatedInstance(instance), callback); } } /** * Sets the Flutter API used to send messages to Dart. * * <p>This is only visible for testing. */ @VisibleForTesting void setApi(@NonNull ViewFlutterApi api) { this.api = api; } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/ViewFlutterApiImpl.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/ViewFlutterApiImpl.java", "repo_id": "packages", "token_count": 613 }
1,165
// 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. /// Information about a navigation action that is about to be executed. class NavigationRequest { NavigationRequest._({required this.url, required this.isForMainFrame}); /// The URL that will be loaded if the navigation is executed. final String url; /// Whether the navigation request is to be loaded as the main frame. final bool isForMainFrame; @override String toString() { return '$NavigationRequest(url: $url, isForMainFrame: $isForMainFrame)'; } }
packages/packages/webview_flutter/webview_flutter_android/example/lib/legacy/navigation_request.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/example/lib/legacy/navigation_request.dart", "repo_id": "packages", "token_count": 171 }
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:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; // ignore: implementation_imports import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart'; import '../android_webview.dart'; import 'webview_android.dart'; import 'webview_android_widget.dart'; /// Android [WebViewPlatform] that uses [AndroidViewSurface] to build the /// [WebView] widget. /// /// To use this, set [WebView.platform] to an instance of this class. /// /// This implementation uses [AndroidViewSurface] to render the [WebView] on /// Android. It solves multiple issues related to accessibility and interaction /// with the [WebView] at the cost of some performance on Android versions below /// 10. /// /// To support transparent backgrounds on all Android devices, this /// implementation uses hybrid composition when the opacity of /// `CreationParams.backgroundColor` is less than 1.0. See /// https://github.com/flutter/flutter/wiki/Hybrid-Composition for more /// information. class SurfaceAndroidWebView extends AndroidWebView { /// Constructs a [SurfaceAndroidWebView]. SurfaceAndroidWebView({@visibleForTesting super.instanceManager}); @override Widget build({ required BuildContext context, required CreationParams creationParams, required JavascriptChannelRegistry javascriptChannelRegistry, WebViewPlatformCreatedCallback? onWebViewPlatformCreated, Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers, required WebViewPlatformCallbacksHandler webViewPlatformCallbacksHandler, }) { return WebViewAndroidWidget( creationParams: creationParams, callbacksHandler: webViewPlatformCallbacksHandler, javascriptChannelRegistry: javascriptChannelRegistry, onBuildWidget: (WebViewAndroidPlatformController controller) { return PlatformViewLink( viewType: 'plugins.flutter.io/webview', surfaceFactory: ( BuildContext context, PlatformViewController controller, ) { return AndroidViewSurface( controller: controller as AndroidViewController, gestureRecognizers: gestureRecognizers ?? const <Factory<OneSequenceGestureRecognizer>>{}, hitTestBehavior: PlatformViewHitTestBehavior.opaque, ); }, onCreatePlatformView: (PlatformViewCreationParams params) { final Color? backgroundColor = creationParams.backgroundColor; return _createViewController( // On some Android devices, transparent backgrounds can cause // rendering issues on the non hybrid composition // AndroidViewSurface. This switches the WebView to Hybrid // Composition when the background color is not 100% opaque. hybridComposition: backgroundColor != null && backgroundColor.opacity < 1.0, id: params.id, viewType: 'plugins.flutter.io/webview', // WebView content is not affected by the Android view's layout direction, // we explicitly set it here so that the widget doesn't require an ambient // directionality. layoutDirection: Directionality.maybeOf(context) ?? TextDirection.ltr, webViewIdentifier: instanceManager.getIdentifier(controller.webView)!, ) ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated) ..addOnPlatformViewCreatedListener((int id) { if (onWebViewPlatformCreated != null) { onWebViewPlatformCreated(controller); } }) ..create(); }, ); }, ); } AndroidViewController _createViewController({ required bool hybridComposition, required int id, required String viewType, required TextDirection layoutDirection, required int webViewIdentifier, }) { if (hybridComposition) { return PlatformViewsService.initExpensiveAndroidView( id: id, viewType: viewType, layoutDirection: layoutDirection, creationParams: webViewIdentifier, creationParamsCodec: const StandardMessageCodec(), ); } return PlatformViewsService.initSurfaceAndroidView( id: id, viewType: viewType, layoutDirection: layoutDirection, creationParams: webViewIdentifier, creationParamsCodec: const StandardMessageCodec(), ); } }
packages/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_surface_android.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_surface_android.dart", "repo_id": "packages", "token_count": 1765 }
1,167
// Mocks generated by Mockito 5.4.4 from annotations // in webview_flutter_android/test/instance_manager_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'package:mockito/mockito.dart' as _i1; import 'test_android_webview.g.dart' as _i2; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class /// A class which mocks [TestInstanceManagerHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestInstanceManagerHostApi extends _i1.Mock implements _i2.TestInstanceManagerHostApi { MockTestInstanceManagerHostApi() { _i1.throwOnMissingStub(this); } @override void clear() => super.noSuchMethod( Invocation.method( #clear, [], ), returnValueForMissingStub: null, ); }
packages/packages/webview_flutter/webview_flutter_android/test/instance_manager_test.mocks.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/test/instance_manager_test.mocks.dart", "repo_id": "packages", "token_count": 476 }
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 '../types/types.dart'; import 'webview_platform_callbacks_handler.dart'; /// Interface for talking to the webview's platform implementation. /// /// An instance implementing this interface is passed to the `onWebViewPlatformCreated` callback that is /// passed to [WebViewPlatformBuilder#onWebViewPlatformCreated]. /// /// Platform implementations that live in a separate package should extend this class rather than /// implement it as webview_flutter 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 [WebViewPlatformController] methods. abstract class WebViewPlatformController { /// Creates a new WebViewPlatform. /// /// Callbacks made by the WebView will be delegated to `handler`. /// /// The `handler` parameter must not be null. // TODO(mvanbeusekom): Remove unused constructor parameter with the next // breaking change (see issue https://github.com/flutter/flutter/issues/94292). // ignore: avoid_unused_constructor_parameters WebViewPlatformController(WebViewPlatformCallbacksHandler handler); /// 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, ) { throw UnimplementedError( 'WebView loadFile is not implemented on the current platform'); } /// 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, ) { throw UnimplementedError( 'WebView loadFlutterAsset is not implemented on the current platform'); } /// 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, }) { throw UnimplementedError( 'WebView loadHtmlString is not implemented on the current platform'); } /// 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, ) { throw UnimplementedError( 'WebView loadUrl is not implemented on the current platform'); } /// Makes a specific HTTP request ands loads the response in the webview. /// /// [WebViewRequest.method] must be one of the supported HTTP methods /// in [WebViewRequestMethod]. /// /// If [WebViewRequest.headers] is not empty, its key-value pairs will be /// added as the headers for the request. /// /// If [WebViewRequest.body] is not null, it will be added as the body /// for the request. /// /// Throws an ArgumentError if [WebViewRequest.uri] has empty scheme. Future<void> loadRequest( WebViewRequest request, ) { throw UnimplementedError( 'WebView loadRequest is not implemented on the current platform'); } /// Updates the webview settings. /// /// Any non null field in `settings` will be set as the new setting value. /// All null fields in `settings` are ignored. Future<void> updateSettings(WebSettings setting) { throw UnimplementedError( 'WebView updateSettings is not implemented on the current platform'); } /// Accessor to the current URL that the WebView is displaying. /// /// If no URL was ever loaded, returns `null`. Future<String?> currentUrl() { throw UnimplementedError( 'WebView currentUrl is not implemented on the current platform'); } /// Checks whether there's a back history item. Future<bool> canGoBack() { throw UnimplementedError( 'WebView canGoBack is not implemented on the current platform'); } /// Checks whether there's a forward history item. Future<bool> canGoForward() { throw UnimplementedError( 'WebView canGoForward is not implemented on the current platform'); } /// Goes back in the history of this WebView. /// /// If there is no back history item this is a no-op. Future<void> goBack() { throw UnimplementedError( 'WebView goBack is not implemented on the current platform'); } /// Goes forward in the history of this WebView. /// /// If there is no forward history item this is a no-op. Future<void> goForward() { throw UnimplementedError( 'WebView goForward is not implemented on the current platform'); } /// Reloads the current URL. Future<void> reload() { throw UnimplementedError( 'WebView reload is not implemented on the current platform'); } /// 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. Future<void> clearCache() { throw UnimplementedError( 'WebView clearCache is not implemented on the current platform'); } /// Evaluates a JavaScript expression in the context of the current page. /// /// The Future completes with an error if a JavaScript error occurred, or if the type of the /// evaluated expression is not supported (e.g on iOS not all non-primitive types can be evaluated). Future<String> evaluateJavascript(String javascript) { throw UnimplementedError( 'WebView evaluateJavascript is not implemented on the current platform'); } /// Runs the given JavaScript in the context of the current page. /// /// The Future completes with an error if a JavaScript error occurred. Future<void> runJavascript(String javascript) { throw UnimplementedError( 'WebView runJavascript is not implemented on the current platform'); } /// Runs the given JavaScript in the context of the current page, and returns the result. /// /// The Future completes with an error if a JavaScript error occurred, or if the /// type the given expression evaluates to is unsupported. Unsupported values include /// certain non-primitive types on iOS, as well as `undefined` or `null` on iOS 14+. Future<String> runJavascriptReturningResult(String javascript) { throw UnimplementedError( 'WebView runJavascriptReturningResult is not implemented on the current platform'); } /// Adds new JavaScript channels to the set of enabled channels. /// /// For each value in this list the platform's webview should make sure that a corresponding /// property with a postMessage method is set on `window`. For example for a JavaScript channel /// named `Foo` it should be possible for JavaScript code executing in the webview to do /// /// ```javascript /// Foo.postMessage('hello'); /// ``` /// /// See also: [CreationParams.javascriptChannelNames]. Future<void> addJavascriptChannels(Set<String> javascriptChannelNames) { throw UnimplementedError( 'WebView addJavascriptChannels is not implemented on the current platform'); } /// Removes JavaScript channel names from the set of enabled channels. /// /// This disables channels that were previously enabled by [addJavascriptChannels] or through /// [CreationParams.javascriptChannelNames]. Future<void> removeJavascriptChannels(Set<String> javascriptChannelNames) { throw UnimplementedError( 'WebView removeJavascriptChannels is not implemented on the current platform'); } /// Returns the title of the currently loaded page. Future<String?> getTitle() { throw UnimplementedError( 'WebView getTitle is not implemented on the current platform'); } /// Set the scrolled position of this view. /// /// The parameters `x` and `y` specify the position to scroll to in WebView pixels. Future<void> scrollTo(int x, int y) { throw UnimplementedError( 'WebView scrollTo is not implemented on the current platform'); } /// Move the scrolled position of this view. /// /// The parameters `x` and `y` specify the amount of WebView pixels to scroll by. Future<void> scrollBy(int x, int y) { throw UnimplementedError( 'WebView scrollBy is not implemented on the current platform'); } /// Return the horizontal scroll position of this view. /// /// Scroll position is measured from left. Future<int> getScrollX() { throw UnimplementedError( 'WebView getScrollX is not implemented on the current platform'); } /// Return the vertical scroll position of this view. /// /// Scroll position is measured from top. Future<int> getScrollY() { throw UnimplementedError( 'WebView getScrollY is not implemented on the current platform'); } }
packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform_controller.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/platform_interface/webview_platform_controller.dart", "repo_id": "packages", "token_count": 2745 }
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:flutter/foundation.dart'; import 'webview_credential.dart'; /// Defines the parameters of a pending HTTP authentication request received by /// the webview through a [HttpAuthRequestCallback]. /// /// Platform specific implementations can add additional fields by extending /// this class and providing a factory method that takes the [HttpAuthRequest] /// as a parameter. /// /// This example demonstrates how to extend the [HttpAuthRequest] to provide /// additional platform specific parameters. /// /// When extending [HttpAuthRequest], additional parameters should always accept /// `null` or have a default value to prevent breaking changes. /// /// ```dart /// @immutable /// class WKWebViewHttpAuthRequest extends HttpAuthRequest { /// WKWebViewHttpAuthRequest._( /// HttpAuthRequest authRequest, /// this.extraData, /// ) : super( /// onProceed: authRequest.onProceed, /// onCancel: authRequest.onCancel, /// host: authRequest.host, /// realm: authRequest.realm, /// ); /// /// factory WKWebViewHttpAuthRequest.fromHttpAuthRequest( /// HttpAuthRequest authRequest, { /// String? extraData, /// }) { /// return WKWebViewHttpAuthRequest._( /// authRequest, /// extraData: extraData, /// ); /// } /// /// final String? extraData; /// } /// ``` @immutable class HttpAuthRequest { /// Creates a [HttpAuthRequest]. const HttpAuthRequest({ required this.onProceed, required this.onCancel, required this.host, this.realm, }); /// The callback to authenticate. final void Function(WebViewCredential credential) onProceed; /// The callback to cancel authentication. final void Function() onCancel; /// The host requiring authentication. final String host; /// The realm requiring authentication. final String? realm; }
packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/http_auth_request.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/http_auth_request.dart", "repo_id": "packages", "token_count": 604 }
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. export 'http_auth_request.dart'; export 'http_response_error.dart'; export 'javascript_console_message.dart'; export 'javascript_dialog_request.dart'; export 'javascript_log_level.dart'; export 'javascript_message.dart'; export 'javascript_mode.dart'; export 'load_request_params.dart'; export 'navigation_decision.dart'; export 'navigation_request.dart'; export 'platform_navigation_delegate_creation_params.dart'; export 'platform_webview_controller_creation_params.dart'; export 'platform_webview_cookie_manager_creation_params.dart'; export 'platform_webview_permission_request.dart'; export 'platform_webview_widget_creation_params.dart'; export 'scroll_position_change.dart'; export 'url_change.dart'; export 'web_resource_error.dart'; export 'web_resource_request.dart'; export 'web_resource_response.dart'; export 'webview_cookie.dart'; export 'webview_credential.dart';
packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/types.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/types.dart", "repo_id": "packages", "token_count": 327 }
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 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'webview_platform_test.mocks.dart'; void main() { setUp(() { WebViewPlatform.instance = MockWebViewPlatformWithMixin(); }); test('Cannot be implemented with `implements`', () { const PlatformNavigationDelegateCreationParams params = PlatformNavigationDelegateCreationParams(); when(WebViewPlatform.instance!.createPlatformNavigationDelegate(params)) .thenReturn(ImplementsPlatformNavigationDelegate()); expect(() { PlatformNavigationDelegate(params); // In versions of `package:plugin_platform_interface` prior to fixing // https://github.com/flutter/flutter/issues/109339, an attempt to // implement a platform interface using `implements` would sometimes throw // a `NoSuchMethodError` and other times throw an `AssertionError`. After // the issue is fixed, an `AssertionError` will always be thrown. For the // purpose of this test, we don't really care what exception is thrown, so // just allow any exception. }, throwsA(anything)); }); test('Can be extended', () { const PlatformNavigationDelegateCreationParams params = PlatformNavigationDelegateCreationParams(); when(WebViewPlatform.instance!.createPlatformNavigationDelegate(params)) .thenReturn(ExtendsPlatformNavigationDelegate(params)); expect(PlatformNavigationDelegate(params), isNotNull); }); test('Can be mocked with `implements`', () { const PlatformNavigationDelegateCreationParams params = PlatformNavigationDelegateCreationParams(); when(WebViewPlatform.instance!.createPlatformNavigationDelegate(params)) .thenReturn(MockNavigationDelegate()); expect(PlatformNavigationDelegate(params), isNotNull); }); test( 'Default implementation of setOnNavigationRequest should throw unimplemented error', () { final PlatformNavigationDelegate callbackDelegate = ExtendsPlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams()); expect( () => callbackDelegate.setOnNavigationRequest( (NavigationRequest navigationRequest) => NavigationDecision.navigate), throwsUnimplementedError, ); }); test( 'Default implementation of setOnPageStarted should throw unimplemented error', () { final PlatformNavigationDelegate callbackDelegate = ExtendsPlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams()); expect( () => callbackDelegate.setOnPageStarted((String url) {}), throwsUnimplementedError, ); }); test( 'Default implementation of setOnPageFinished should throw unimplemented error', () { final PlatformNavigationDelegate callbackDelegate = ExtendsPlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams()); expect( () => callbackDelegate.setOnPageFinished((String url) {}), throwsUnimplementedError, ); }); test( 'Default implementation of setOnHttpError should throw unimplemented error', () { final PlatformNavigationDelegate callbackDelegate = ExtendsPlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams()); expect( () => callbackDelegate.setOnHttpError((HttpResponseError error) {}), throwsUnimplementedError, ); }); test( // ignore: lines_longer_than_80_chars 'Default implementation of setOnProgress should throw unimplemented error', () { final PlatformNavigationDelegate callbackDelegate = ExtendsPlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams()); expect( () => callbackDelegate.setOnProgress((int progress) {}), throwsUnimplementedError, ); }); test( 'Default implementation of setOnWebResourceError should throw unimplemented error', () { final PlatformNavigationDelegate callbackDelegate = ExtendsPlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams()); expect( () => callbackDelegate.setOnWebResourceError((WebResourceError error) {}), throwsUnimplementedError, ); }); test( 'Default implementation of setOnUrlChange should throw unimplemented error', () { final PlatformNavigationDelegate callbackDelegate = ExtendsPlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams()); expect( () => callbackDelegate.setOnUrlChange((UrlChange change) {}), throwsUnimplementedError, ); }); test( 'Default implementation of setOnHttpAuthRequest should throw unimplemented error', () { final PlatformNavigationDelegate callbackDelegate = ExtendsPlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams()); expect( () => callbackDelegate.setOnHttpAuthRequest((HttpAuthRequest request) {}), throwsUnimplementedError, ); }); } class MockWebViewPlatformWithMixin extends MockWebViewPlatform with // ignore: prefer_mixin MockPlatformInterfaceMixin {} class ImplementsPlatformNavigationDelegate implements PlatformNavigationDelegate { @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } class MockNavigationDelegate extends Mock with // ignore: prefer_mixin MockPlatformInterfaceMixin implements PlatformNavigationDelegate {} class ExtendsPlatformNavigationDelegate extends PlatformNavigationDelegate { ExtendsPlatformNavigationDelegate(super.params) : super.implementation(); }
packages/packages/webview_flutter/webview_flutter_platform_interface/test/platform_navigation_delegate_test.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/test/platform_navigation_delegate_test.dart", "repo_id": "packages", "token_count": 2017 }
1,172
// 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'; // ignore: implementation_imports import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart'; // ignore: implementation_imports import 'package:webview_flutter_web/src/webview_flutter_web_legacy.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); /// A web view widget for showing html content. /// /// The [WebView] widget wraps around the [WebWebViewPlatform]. /// /// 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_web` 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. const WebView({ super.key, this.onWebViewCreated, this.initialUrl, }); /// The WebView platform that's used by this WebView. /// /// The default value is [WebWebViewPlatform]. /// This property can be set to use a custom platform implementation for WebViews. /// Setting `platform` doesn't affect [WebView]s that were already created. static WebViewPlatform platform = WebWebViewPlatform(); /// If not null invoked once the web view is created. final WebViewCreatedCallback? onWebViewCreated; /// The initial URL to load. final String? initialUrl; @override State<WebView> createState() => _WebViewState(); } class _WebViewState extends State<WebView> { final Completer<WebViewController> _controller = Completer<WebViewController>(); late final _PlatformCallbacksHandler _platformCallbacksHandler; @override void initState() { super.initState(); _platformCallbacksHandler = _PlatformCallbacksHandler(); } @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!, ); _controller.complete(controller); if (widget.onWebViewCreated != null) { widget.onWebViewCreated!(controller); } }, webViewPlatformCallbacksHandler: _platformCallbacksHandler, creationParams: CreationParams( initialUrl: widget.initialUrl, webSettings: _webSettingsFromWidget(widget), ), javascriptChannelRegistry: JavascriptChannelRegistry(<JavascriptChannel>{}), ); } } class _PlatformCallbacksHandler implements WebViewPlatformCallbacksHandler { _PlatformCallbacksHandler(); @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) {} } /// 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, ) { _settings = _webSettingsFromWidget(_widget); } final WebViewPlatformController _webViewPlatformController; late WebSettings _settings; WebView _widget; /// 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)); } Future<void> _updateSettings(WebSettings newSettings) { final WebSettings update = _clearUnchangedWebSettings(_settings, newSettings); _settings = newSettings; return _webViewPlatformController.updateSettings(update); } @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, ); } // 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: JavascriptMode.unrestricted, hasNavigationDelegate: false, hasProgressTracking: false, debuggingEnabled: false, gestureNavigationEnabled: false, allowsInlineMediaPlayback: true, userAgent: const WebSetting<String?>.of(''), zoomEnabled: false, ); }
packages/packages/webview_flutter/webview_flutter_web/example/lib/legacy/web_view.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_web/example/lib/legacy/web_view.dart", "repo_id": "packages", "token_count": 3995 }
1,173
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN typedef void (^FWFOnDeallocCallback)(long identifier); /// Maintains instances used to communicate with the corresponding objects in Dart. /// /// When an instance is added with an identifier, either can be used to retrieve the other. /// /// Added instances are added as a weak reference and a strong reference. When the strong reference /// is removed with `removeStrongReferenceWithIdentifier:` and the weak reference is deallocated, /// the `deallocCallback` is made with the instance's identifier. However, if the strong reference /// is removed and then the identifier is retrieved with the intention to pass the identifier to /// Dart (e.g. calling `identifierForInstance:identifierWillBePassedToFlutter:` with /// `identifierWillBePassedToFlutter` set to YES), the strong reference to the instance is /// recreated. The strong reference will then need to be removed manually again. /// /// Accessing and inserting to an InstanceManager is thread safe. @interface FWFInstanceManager : NSObject @property(readonly) FWFOnDeallocCallback deallocCallback; - (instancetype)initWithDeallocCallback:(FWFOnDeallocCallback)callback; // TODO(bparrishMines): Pairs should not be able to be overwritten and this feature // should be replaced with a call to clear the manager in the event of a hot restart. /// Adds a new instance that was instantiated from Dart. /// /// If an instance or identifier has already been added, it will be replaced by the new values. The /// Dart InstanceManager is considered the source of truth and has the capability to overwrite /// stored pairs in response to hot restarts. /// /// @param instance The instance to be stored. /// @param instanceIdentifier The identifier to be paired with instance. This value must be >= 0. - (void)addDartCreatedInstance:(NSObject *)instance withIdentifier:(long)instanceIdentifier; /// Adds a new instance that was instantiated from the host platform. /// /// @param instance The instance to be stored. /// @return The unique identifier stored with instance. - (long)addHostCreatedInstance:(nonnull NSObject *)instance; /// Removes `instanceIdentifier` and its associated strongly referenced instance, if present, from /// the manager. /// /// @param instanceIdentifier The identifier paired to an instance. /// /// @return The removed instance if the manager contains the given instanceIdentifier, otherwise /// nil. - (nullable NSObject *)removeInstanceWithIdentifier:(long)instanceIdentifier; /// Retrieves the instance associated with identifier. /// /// @param instanceIdentifier The identifier paired to an instance. /// /// @return The instance associated with `instanceIdentifier` if the manager contains the value, /// otherwise nil. - (nullable NSObject *)instanceForIdentifier:(long)instanceIdentifier; /// Retrieves the identifier paired with an instance. /// /// If the manager contains `instance`, as a strong or weak reference, the strong reference to /// `instance` will be recreated and will need to be removed again with /// `removeInstanceWithIdentifier:`. /// /// This method also expects the Dart `InstanceManager` to have, or recreate, a weak reference to /// the instance the identifier is associated with once it receives it. /// /// @param instance An instance that may be stored in the manager. /// /// @return The identifier associated with `instance` if the manager contains the value, otherwise /// NSNotFound. - (long)identifierWithStrongReferenceForInstance:(nonnull NSObject *)instance; /// Returns whether this manager contains the given `instance`. /// /// @return Whether this manager contains the given `instance`. - (BOOL)containsInstance:(nonnull NSObject *)instance; @end NS_ASSUME_NONNULL_END
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFInstanceManager.h/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFInstanceManager.h", "repo_id": "packages", "token_count": 958 }
1,174
// 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 "FWFUIDelegateHostApi.h" #import "FWFDataConverters.h" @interface FWFUIDelegateFlutterApiImpl () // BinaryMessenger must be weak to prevent a circular reference with the host API it // references. @property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger; // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFUIDelegateFlutterApiImpl - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self initWithBinaryMessenger:binaryMessenger]; if (self) { _binaryMessenger = binaryMessenger; _instanceManager = instanceManager; _webViewConfigurationFlutterApi = [[FWFWebViewConfigurationFlutterApiImpl alloc] initWithBinaryMessenger:binaryMessenger instanceManager:instanceManager]; } return self; } - (long)identifierForDelegate:(FWFUIDelegate *)instance { return [self.instanceManager identifierWithStrongReferenceForInstance:instance]; } - (void)onCreateWebViewForDelegate:(FWFUIDelegate *)instance webView:(WKWebView *)webView configuration:(WKWebViewConfiguration *)configuration navigationAction:(WKNavigationAction *)navigationAction completion:(void (^)(FlutterError *_Nullable))completion { if (![self.instanceManager containsInstance:configuration]) { [self.webViewConfigurationFlutterApi createWithConfiguration:configuration completion:^(FlutterError *error) { NSAssert(!error, @"%@", error); }]; } NSInteger configurationIdentifier = [self.instanceManager identifierWithStrongReferenceForInstance:configuration]; FWFWKNavigationActionData *navigationActionData = FWFWKNavigationActionDataFromNativeWKNavigationAction(navigationAction); [self onCreateWebViewForDelegateWithIdentifier:[self identifierForDelegate:instance] webViewIdentifier:[self.instanceManager identifierWithStrongReferenceForInstance:webView] configurationIdentifier:configurationIdentifier navigationAction:navigationActionData completion:completion]; } - (void)requestMediaCapturePermissionForDelegateWithIdentifier:(FWFUIDelegate *)instance webView:(WKWebView *)webView origin:(WKSecurityOrigin *)origin frame:(WKFrameInfo *)frame type:(WKMediaCaptureType)type completion: (void (^)(WKPermissionDecision))completion API_AVAILABLE(ios(15.0)) { [self requestMediaCapturePermissionForDelegateWithIdentifier:[self identifierForDelegate:instance] webViewIdentifier: [self.instanceManager identifierWithStrongReferenceForInstance:webView] origin: FWFWKSecurityOriginDataFromNativeWKSecurityOrigin( origin) frame: FWFWKFrameInfoDataFromNativeWKFrameInfo( frame) type: FWFWKMediaCaptureTypeDataFromNativeWKMediaCaptureType( type) completion:^( FWFWKPermissionDecisionData *decision, FlutterError *error) { NSAssert(!error, @"%@", error); completion( FWFNativeWKPermissionDecisionFromData( decision)); }]; } - (void)runJavaScriptAlertPanelForDelegateWithIdentifier:(FWFUIDelegate *)instance message:(NSString *)message frame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler { [self runJavaScriptAlertPanelForDelegateWithIdentifier:[self identifierForDelegate:instance] message:message frame:FWFWKFrameInfoDataFromNativeWKFrameInfo( frame) completion:^(FlutterError *error) { NSAssert(!error, @"%@", error); completionHandler(); }]; } - (void)runJavaScriptConfirmPanelForDelegateWithIdentifier:(FWFUIDelegate *)instance message:(NSString *)message frame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler { [self runJavaScriptConfirmPanelForDelegateWithIdentifier:[self identifierForDelegate:instance] message:message frame:FWFWKFrameInfoDataFromNativeWKFrameInfo( frame) completion:^(NSNumber *isConfirmed, FlutterError *error) { NSAssert(!error, @"%@", error); if (error) { completionHandler(NO); } else { completionHandler(isConfirmed.boolValue); } }]; } - (void)runJavaScriptTextInputPanelForDelegateWithIdentifier:(FWFUIDelegate *)instance prompt:(NSString *)prompt defaultText:(NSString *)defaultText frame:(WKFrameInfo *)frame completionHandler: (void (^)(NSString *_Nullable))completionHandler { [self runJavaScriptTextInputPanelForDelegateWithIdentifier:[self identifierForDelegate:instance] prompt:prompt defaultText:defaultText frame:FWFWKFrameInfoDataFromNativeWKFrameInfo( frame) completion:^(NSString *inputText, FlutterError *error) { NSAssert(!error, @"%@", error); if (error) { completionHandler(nil); } else { completionHandler(inputText); } }]; } @end @implementation FWFUIDelegate - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [super initWithBinaryMessenger:binaryMessenger instanceManager:instanceManager]; if (self) { _UIDelegateAPI = [[FWFUIDelegateFlutterApiImpl alloc] initWithBinaryMessenger:binaryMessenger instanceManager:instanceManager]; } return self; } - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures { [self.UIDelegateAPI onCreateWebViewForDelegate:self webView:webView configuration:configuration navigationAction:navigationAction completion:^(FlutterError *error) { NSAssert(!error, @"%@", error); }]; return nil; } - (void)webView:(WKWebView *)webView requestMediaCapturePermissionForOrigin:(WKSecurityOrigin *)origin initiatedByFrame:(WKFrameInfo *)frame type:(WKMediaCaptureType)type decisionHandler:(void (^)(WKPermissionDecision))decisionHandler API_AVAILABLE(ios(15.0)) { [self.UIDelegateAPI requestMediaCapturePermissionForDelegateWithIdentifier:self webView:webView origin:origin frame:frame type:type completion:^(WKPermissionDecision decision) { decisionHandler(decision); }]; } - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler { [self.UIDelegateAPI runJavaScriptAlertPanelForDelegateWithIdentifier:self message:message frame:frame completionHandler:completionHandler]; } - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler { [self.UIDelegateAPI runJavaScriptConfirmPanelForDelegateWithIdentifier:self message:message frame:frame completionHandler:completionHandler]; } - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *_Nullable))completionHandler { [self.UIDelegateAPI runJavaScriptTextInputPanelForDelegateWithIdentifier:self prompt:prompt defaultText:defaultText frame:frame completionHandler:completionHandler]; } @end @interface FWFUIDelegateHostApiImpl () // BinaryMessenger must be weak to prevent a circular reference with the host API it // references. @property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger; // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFUIDelegateHostApiImpl - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _binaryMessenger = binaryMessenger; _instanceManager = instanceManager; } return self; } - (FWFUIDelegate *)delegateForIdentifier:(NSNumber *)identifier { return (FWFUIDelegate *)[self.instanceManager instanceForIdentifier:identifier.longValue]; } - (void)createWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error { FWFUIDelegate *uIDelegate = [[FWFUIDelegate alloc] initWithBinaryMessenger:self.binaryMessenger instanceManager:self.instanceManager]; [self.instanceManager addDartCreatedInstance:uIDelegate withIdentifier:identifier]; } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUIDelegateHostApi.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUIDelegateHostApi.m", "repo_id": "packages", "token_count": 8251 }
1,175
// 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 "FWFWebViewFlutterWKWebViewExternalAPI.h" #import "FWFInstanceManager.h" @implementation FWFWebViewFlutterWKWebViewExternalAPI + (nullable WKWebView *)webViewForIdentifier:(long)identifier withPluginRegistry:(id<FlutterPluginRegistry>)registry { FWFInstanceManager *instanceManager = (FWFInstanceManager *)[registry valuePublishedByPlugin:@"FLTWebViewFlutterPlugin"]; id instance = [instanceManager instanceForIdentifier:identifier]; if ([instance isKindOfClass:[WKWebView class]]) { return instance; } return nil; } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebViewFlutterWKWebViewExternalAPI.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebViewFlutterWKWebViewExternalAPI.m", "repo_id": "packages", "token_count": 246 }
1,176
// 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/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart'; import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart'; import 'package:webview_flutter_wkwebview/src/legacy/web_kit_webview_widget.dart'; import 'package:webview_flutter_wkwebview/src/ui_kit/ui_kit.dart'; import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart'; import 'web_kit_webview_widget_test.mocks.dart'; @GenerateMocks(<Type>[ UIScrollView, WKNavigationDelegate, WKPreferences, WKScriptMessageHandler, WKWebView, WKWebViewConfiguration, WKWebsiteDataStore, WKUIDelegate, WKUserContentController, JavascriptChannelRegistry, WebViewPlatformCallbacksHandler, WebViewWidgetProxy, ]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('WebKitWebViewWidget', () { _WebViewMocks configureMocks() { final _WebViewMocks mocks = _WebViewMocks( webView: MockWKWebView(), webViewWidgetProxy: MockWebViewWidgetProxy(), userContentController: MockWKUserContentController(), preferences: MockWKPreferences(), webViewConfiguration: MockWKWebViewConfiguration(), uiDelegate: MockWKUIDelegate(), scrollView: MockUIScrollView(), websiteDataStore: MockWKWebsiteDataStore(), navigationDelegate: MockWKNavigationDelegate(), callbacksHandler: MockWebViewPlatformCallbacksHandler(), javascriptChannelRegistry: MockJavascriptChannelRegistry()); when( mocks.webViewWidgetProxy.createWebView( any, observeValue: anyNamed('observeValue'), ), ).thenReturn(mocks.webView); when( mocks.webViewWidgetProxy.createUIDelgate( onCreateWebView: captureAnyNamed('onCreateWebView'), ), ).thenReturn(mocks.uiDelegate); when(mocks.webViewWidgetProxy.createNavigationDelegate( didFinishNavigation: anyNamed('didFinishNavigation'), didStartProvisionalNavigation: anyNamed('didStartProvisionalNavigation'), decidePolicyForNavigationAction: anyNamed('decidePolicyForNavigationAction'), didFailNavigation: anyNamed('didFailNavigation'), didFailProvisionalNavigation: anyNamed('didFailProvisionalNavigation'), webViewWebContentProcessDidTerminate: anyNamed('webViewWebContentProcessDidTerminate'), )).thenReturn(mocks.navigationDelegate); when(mocks.webView.configuration).thenReturn(mocks.webViewConfiguration); when(mocks.webViewConfiguration.userContentController).thenReturn( mocks.userContentController, ); when(mocks.webViewConfiguration.preferences) .thenReturn(mocks.preferences); when(mocks.webView.scrollView).thenReturn(mocks.scrollView); when(mocks.webViewConfiguration.websiteDataStore).thenReturn( mocks.websiteDataStore, ); return mocks; } // Builds a WebViewCupertinoWidget with default parameters and returns its // controller. Future<WebKitWebViewPlatformController> buildWidget( WidgetTester tester, _WebViewMocks mocks, { CreationParams? creationParams, bool hasNavigationDelegate = false, bool hasProgressTracking = false, }) async { final Completer<WebKitWebViewPlatformController> testController = Completer<WebKitWebViewPlatformController>(); await tester.pumpWidget(WebKitWebViewWidget( creationParams: creationParams ?? CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: hasNavigationDelegate, hasProgressTracking: hasProgressTracking, )), callbacksHandler: mocks.callbacksHandler, javascriptChannelRegistry: mocks.javascriptChannelRegistry, webViewProxy: mocks.webViewWidgetProxy, configuration: mocks.webViewConfiguration, onBuildWidget: (WebKitWebViewPlatformController controller) { testController.complete(controller); return Container(); }, )); await tester.pumpAndSettle(); return testController.future; } testWidgets('build WebKitWebViewWidget', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget(tester, mocks); }); testWidgets('Requests to open a new window loads request in same window', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget(tester, mocks); final void Function(WKWebView, WKWebViewConfiguration, WKNavigationAction) onCreateWebView = verify(mocks.webViewWidgetProxy.createUIDelgate( onCreateWebView: captureAnyNamed('onCreateWebView'))) .captured .single as void Function( WKWebView, WKWebViewConfiguration, WKNavigationAction); const NSUrlRequest request = NSUrlRequest(url: 'https://google.com'); onCreateWebView( mocks.webView, mocks.webViewConfiguration, const WKNavigationAction( request: request, targetFrame: WKFrameInfo(isMainFrame: false, request: request), navigationType: WKNavigationType.linkActivated, ), ); verify(mocks.webView.loadRequest(request)); }); group('CreationParams', () { testWidgets('initialUrl', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget( tester, mocks, creationParams: CreationParams( initialUrl: 'https://www.google.com', webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: false, ), ), ); final NSUrlRequest request = verify(mocks.webView.loadRequest(captureAny)).captured.single as NSUrlRequest; expect(request.url, 'https://www.google.com'); }); testWidgets('backgroundColor', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget( tester, mocks, creationParams: CreationParams( backgroundColor: Colors.red, webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: false, ), ), ); verify(mocks.webView.setOpaque(false)); verify(mocks.webView.setBackgroundColor(Colors.transparent)); verify(mocks.scrollView.setBackgroundColor(Colors.red)); }); testWidgets('userAgent', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget( tester, mocks, creationParams: CreationParams( userAgent: 'MyUserAgent', webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: false, ), ), ); verify(mocks.webView.setCustomUserAgent('MyUserAgent')); }); testWidgets('autoMediaPlaybackPolicy true', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget( tester, mocks, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: false, ), ), ); verify(mocks.webViewConfiguration .setMediaTypesRequiringUserActionForPlayback(<WKAudiovisualMediaType>{ WKAudiovisualMediaType.all, })); }); testWidgets('autoMediaPlaybackPolicy false', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget( tester, mocks, creationParams: CreationParams( autoMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow, webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: false, ), ), ); verify(mocks.webViewConfiguration .setMediaTypesRequiringUserActionForPlayback(<WKAudiovisualMediaType>{ WKAudiovisualMediaType.none, })); }); testWidgets('javascriptChannelNames', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); when( mocks.webViewWidgetProxy.createScriptMessageHandler( didReceiveScriptMessage: anyNamed('didReceiveScriptMessage'), ), ).thenReturn( MockWKScriptMessageHandler(), ); await buildWidget( tester, mocks, creationParams: CreationParams( javascriptChannelNames: <String>{'a', 'b'}, webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: false, ), ), ); final List<dynamic> javaScriptChannels = verify( mocks.userContentController.addScriptMessageHandler( captureAny, captureAny, ), ).captured; expect( javaScriptChannels[0], isA<WKScriptMessageHandler>(), ); expect(javaScriptChannels[1], 'a'); expect( javaScriptChannels[2], isA<WKScriptMessageHandler>(), ); expect(javaScriptChannels[3], 'b'); }); group('WebSettings', () { testWidgets('javascriptMode', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget( tester, mocks, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), javascriptMode: JavascriptMode.unrestricted, hasNavigationDelegate: false, ), ), ); verify(mocks.preferences.setJavaScriptEnabled(true)); }); testWidgets('userAgent', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget( tester, mocks, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.of('myUserAgent'), hasNavigationDelegate: false, ), ), ); verify(mocks.webView.setCustomUserAgent('myUserAgent')); }); testWidgets( 'enabling zoom re-adds JavaScript channels', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); when( mocks.webViewWidgetProxy.createScriptMessageHandler( didReceiveScriptMessage: anyNamed('didReceiveScriptMessage'), ), ).thenReturn( MockWKScriptMessageHandler(), ); final WebKitWebViewPlatformController testController = await buildWidget( tester, mocks, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), zoomEnabled: false, hasNavigationDelegate: false, ), javascriptChannelNames: <String>{'myChannel'}, ), ); clearInteractions(mocks.userContentController); await testController.updateSettings(WebSettings( userAgent: const WebSetting<String?>.absent(), zoomEnabled: true, )); final List<dynamic> javaScriptChannels = verifyInOrder(<Object>[ mocks.userContentController.removeAllUserScripts(), mocks.userContentController .removeScriptMessageHandler('myChannel'), mocks.userContentController.addScriptMessageHandler( captureAny, captureAny, ), ]).captured[2]; expect( javaScriptChannels[0], isA<WKScriptMessageHandler>(), ); expect(javaScriptChannels[1], 'myChannel'); }, ); testWidgets( 'enabling zoom removes script', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget( tester, mocks, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), zoomEnabled: false, hasNavigationDelegate: false, ), ), ); clearInteractions(mocks.userContentController); await testController.updateSettings(WebSettings( userAgent: const WebSetting<String?>.absent(), zoomEnabled: true, )); verify(mocks.userContentController.removeAllUserScripts()); verifyNever(mocks.userContentController.addScriptMessageHandler( any, any, )); }, ); testWidgets('zoomEnabled is false', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget( tester, mocks, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), zoomEnabled: false, hasNavigationDelegate: false, ), ), ); final WKUserScript zoomScript = verify(mocks.userContentController.addUserScript(captureAny)) .captured .first as WKUserScript; expect(zoomScript.isMainFrameOnly, isTrue); expect(zoomScript.injectionTime, WKUserScriptInjectionTime.atDocumentEnd); expect( zoomScript.source, "var meta = document.createElement('meta');\n" "meta.name = 'viewport';\n" "meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, " "user-scalable=no';\n" "var head = document.getElementsByTagName('head')[0];head.appendChild(meta);", ); }); testWidgets('allowsInlineMediaPlayback', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget( tester, mocks, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), allowsInlineMediaPlayback: true, ), ), ); verify(mocks.webViewConfiguration.setAllowsInlineMediaPlayback(true)); }); }); }); group('WebKitWebViewPlatformController', () { testWidgets('loadFile', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.loadFile('/path/to/file.html'); verify(mocks.webView.loadFileUrl( '/path/to/file.html', readAccessUrl: '/path/to', )); }); testWidgets('loadFlutterAsset', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.loadFlutterAsset('test_assets/index.html'); verify(mocks.webView.loadFlutterAsset('test_assets/index.html')); }); testWidgets('loadHtmlString', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); const String htmlString = '<html><body>Test data.</body></html>'; await testController.loadHtmlString(htmlString, baseUrl: 'baseUrl'); verify(mocks.webView.loadHtmlString( '<html><body>Test data.</body></html>', baseUrl: 'baseUrl', )); }); testWidgets('loadUrl', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.loadUrl( 'https://www.google.com', <String, String>{'a': 'header'}, ); final NSUrlRequest request = verify(mocks.webView.loadRequest(captureAny)).captured.single as NSUrlRequest; expect(request.url, 'https://www.google.com'); expect(request.allHttpHeaderFields, <String, String>{'a': 'header'}); }); group('loadRequest', () { testWidgets('Throws ArgumentError for empty scheme', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); expect( () async => testController.loadRequest( WebViewRequest( uri: Uri.parse('www.google.com'), method: WebViewRequestMethod.get, ), ), throwsA(const TypeMatcher<ArgumentError>())); }); testWidgets('GET without headers', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.loadRequest(WebViewRequest( uri: Uri.parse('https://www.google.com'), method: WebViewRequestMethod.get, )); final NSUrlRequest request = verify(mocks.webView.loadRequest(captureAny)).captured.single as NSUrlRequest; expect(request.url, 'https://www.google.com'); expect(request.allHttpHeaderFields, <String, String>{}); expect(request.httpMethod, 'get'); }); testWidgets('GET with headers', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.loadRequest(WebViewRequest( uri: Uri.parse('https://www.google.com'), method: WebViewRequestMethod.get, headers: <String, String>{'a': 'header'}, )); final NSUrlRequest request = verify(mocks.webView.loadRequest(captureAny)).captured.single as NSUrlRequest; expect(request.url, 'https://www.google.com'); expect(request.allHttpHeaderFields, <String, String>{'a': 'header'}); expect(request.httpMethod, 'get'); }); testWidgets('POST without body', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.loadRequest(WebViewRequest( uri: Uri.parse('https://www.google.com'), method: WebViewRequestMethod.post, )); final NSUrlRequest request = verify(mocks.webView.loadRequest(captureAny)).captured.single as NSUrlRequest; expect(request.url, 'https://www.google.com'); expect(request.httpMethod, 'post'); }); testWidgets('POST with body', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.loadRequest(WebViewRequest( uri: Uri.parse('https://www.google.com'), method: WebViewRequestMethod.post, body: Uint8List.fromList('Test Body'.codeUnits))); final NSUrlRequest request = verify(mocks.webView.loadRequest(captureAny)).captured.single as NSUrlRequest; expect(request.url, 'https://www.google.com'); expect(request.httpMethod, 'post'); expect( request.httpBody, Uint8List.fromList('Test Body'.codeUnits), ); }); }); testWidgets('canGoBack', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.canGoBack()).thenAnswer( (_) => Future<bool>.value(false), ); expect(testController.canGoBack(), completion(false)); }); testWidgets('canGoForward', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.canGoForward()).thenAnswer( (_) => Future<bool>.value(true), ); expect(testController.canGoForward(), completion(true)); }); testWidgets('goBack', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.goBack(); verify(mocks.webView.goBack()); }); testWidgets('goForward', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.goForward(); verify(mocks.webView.goForward()); }); testWidgets('reload', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.reload(); verify(mocks.webView.reload()); }); testWidgets('evaluateJavascript', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.evaluateJavaScript('runJavaScript')).thenAnswer( (_) => Future<String>.value('returnString'), ); expect( testController.evaluateJavascript('runJavaScript'), completion('returnString'), ); }); testWidgets('evaluateJavascript with null return value', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.evaluateJavaScript('runJavaScript')).thenAnswer( (_) => Future<Object?>.value(), ); // The legacy implementation of webview_flutter_wkwebview would convert // objects to strings before returning them to Dart. This verifies null // is represented the way it is in Objective-C. expect( testController.evaluateJavascript('runJavaScript'), completion('(null)'), ); }); testWidgets('evaluateJavascript with bool return value', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.evaluateJavaScript('runJavaScript')).thenAnswer( (_) => Future<Object?>.value(true), ); // The legacy implementation of webview_flutter_wkwebview would convert // objects to strings before returning them to Dart. This verifies bool // is represented the way it is in Objective-C. // `NSNumber.description` converts bool values to a 1 or 0. expect( testController.evaluateJavascript('runJavaScript'), completion('1'), ); }); testWidgets('evaluateJavascript with double return value', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.evaluateJavaScript('runJavaScript')).thenAnswer( (_) => Future<Object?>.value(1.0), ); // The legacy implementation of webview_flutter_wkwebview would convert // objects to strings before returning them to Dart. This verifies // double is represented the way it is in Objective-C. If a double // doesn't contain any decimal values, it gets truncated to an int. // This should be happening because NSNumber converts float values // with no decimals to an int when using `NSNumber.description`. expect( testController.evaluateJavascript('runJavaScript'), completion('1'), ); }); testWidgets('evaluateJavascript with list return value', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.evaluateJavaScript('runJavaScript')).thenAnswer( (_) => Future<Object?>.value(<Object?>[1, 'string', null]), ); // The legacy implementation of webview_flutter_wkwebview would convert // objects to strings before returning them to Dart. This verifies list // is represented the way it is in Objective-C. expect( testController.evaluateJavascript('runJavaScript'), completion('(1,string,"<null>")'), ); }); testWidgets('evaluateJavascript with map return value', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.evaluateJavaScript('runJavaScript')).thenAnswer( (_) => Future<Object?>.value(<Object?, Object?>{ 1: 'string', null: null, }), ); // The legacy implementation of webview_flutter_wkwebview would convert // objects to strings before returning them to Dart. This verifies map // is represented the way it is in Objective-C. expect( testController.evaluateJavascript('runJavaScript'), completion('{1 = string;"<null>" = "<null>"}'), ); }); testWidgets('evaluateJavascript throws exception', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.evaluateJavaScript('runJavaScript')) .thenThrow(Error()); expect( testController.evaluateJavascript('runJavaScript'), throwsA(isA<Error>()), ); }); testWidgets('runJavascriptReturningResult', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.evaluateJavaScript('runJavaScript')).thenAnswer( (_) => Future<String>.value('returnString'), ); expect( testController.runJavascriptReturningResult('runJavaScript'), completion('returnString'), ); }); testWidgets( 'runJavascriptReturningResult throws error on null return value', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.evaluateJavaScript('runJavaScript')).thenAnswer( (_) => Future<String?>.value(), ); expect( () => testController.runJavascriptReturningResult('runJavaScript'), throwsArgumentError, ); }); testWidgets('runJavascriptReturningResult with bool return value', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.evaluateJavaScript('runJavaScript')).thenAnswer( (_) => Future<Object?>.value(false), ); // The legacy implementation of webview_flutter_wkwebview would convert // objects to strings before returning them to Dart. This verifies bool // is represented the way it is in Objective-C. // `NSNumber.description` converts bool values to a 1 or 0. expect( testController.runJavascriptReturningResult('runJavaScript'), completion('0'), ); }); testWidgets('runJavascript', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.evaluateJavaScript('runJavaScript')).thenAnswer( (_) => Future<String>.value('returnString'), ); expect( testController.runJavascript('runJavaScript'), completes, ); }); testWidgets( 'runJavascript ignores exception with unsupported javascript type', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.evaluateJavaScript('runJavaScript')) .thenThrow(PlatformException( code: '', details: const NSError( code: WKErrorCode.javaScriptResultTypeIsUnsupported, domain: '', ), )); expect( testController.runJavascript('runJavaScript'), completes, ); }); testWidgets('getTitle', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.getTitle()) .thenAnswer((_) => Future<String>.value('Web Title')); expect(testController.getTitle(), completion('Web Title')); }); testWidgets('currentUrl', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.webView.getUrl()) .thenAnswer((_) => Future<String>.value('myUrl.com')); expect(testController.currentUrl(), completion('myUrl.com')); }); testWidgets('scrollTo', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.scrollTo(2, 4); verify( mocks.scrollView.setContentOffset(const Point<double>(2.0, 4.0))); }); testWidgets('scrollBy', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.scrollBy(2, 4); verify(mocks.scrollView.scrollBy(const Point<double>(2.0, 4.0))); }); testWidgets('getScrollX', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.scrollView.getContentOffset()).thenAnswer( (_) => Future<Point<double>>.value(const Point<double>(8.0, 16.0))); expect(testController.getScrollX(), completion(8.0)); }); testWidgets('getScrollY', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when(mocks.scrollView.getContentOffset()).thenAnswer( (_) => Future<Point<double>>.value(const Point<double>(8.0, 16.0))); expect(testController.getScrollY(), completion(16.0)); }); testWidgets('clearCache', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); when( mocks.websiteDataStore.removeDataOfTypes( <WKWebsiteDataType>{ WKWebsiteDataType.memoryCache, WKWebsiteDataType.diskCache, WKWebsiteDataType.offlineWebApplicationCache, WKWebsiteDataType.localStorage, }, DateTime.fromMillisecondsSinceEpoch(0), ), ).thenAnswer((_) => Future<bool>.value(false)); expect(testController.clearCache(), completes); }); testWidgets('addJavascriptChannels', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); when( mocks.webViewWidgetProxy.createScriptMessageHandler( didReceiveScriptMessage: anyNamed('didReceiveScriptMessage'), ), ).thenReturn( MockWKScriptMessageHandler(), ); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.addJavascriptChannels(<String>{'c', 'd'}); final List<dynamic> javaScriptChannels = verify( mocks.userContentController .addScriptMessageHandler(captureAny, captureAny), ).captured; expect( javaScriptChannels[0], isA<WKScriptMessageHandler>(), ); expect(javaScriptChannels[1], 'c'); expect( javaScriptChannels[2], isA<WKScriptMessageHandler>(), ); expect(javaScriptChannels[3], 'd'); final List<WKUserScript> userScripts = verify(mocks.userContentController.addUserScript(captureAny)) .captured .cast<WKUserScript>(); expect(userScripts[0].source, 'window.c = webkit.messageHandlers.c;'); expect( userScripts[0].injectionTime, WKUserScriptInjectionTime.atDocumentStart, ); expect(userScripts[0].isMainFrameOnly, false); expect(userScripts[1].source, 'window.d = webkit.messageHandlers.d;'); expect( userScripts[1].injectionTime, WKUserScriptInjectionTime.atDocumentStart, ); expect(userScripts[0].isMainFrameOnly, false); }); testWidgets('removeJavascriptChannels', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); when( mocks.webViewWidgetProxy.createScriptMessageHandler( didReceiveScriptMessage: anyNamed('didReceiveScriptMessage'), ), ).thenReturn( MockWKScriptMessageHandler(), ); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.addJavascriptChannels(<String>{'c', 'd'}); reset(mocks.userContentController); await testController.removeJavascriptChannels(<String>{'c'}); verify(mocks.userContentController.removeAllUserScripts()); verify(mocks.userContentController.removeScriptMessageHandler('c')); verify(mocks.userContentController.removeScriptMessageHandler('d')); final List<dynamic> javaScriptChannels = verify( mocks.userContentController.addScriptMessageHandler( captureAny, captureAny, ), ).captured; expect( javaScriptChannels[0], isA<WKScriptMessageHandler>(), ); expect(javaScriptChannels[1], 'd'); final List<WKUserScript> userScripts = verify(mocks.userContentController.addUserScript(captureAny)) .captured .cast<WKUserScript>(); expect(userScripts[0].source, 'window.d = webkit.messageHandlers.d;'); expect( userScripts[0].injectionTime, WKUserScriptInjectionTime.atDocumentStart, ); expect(userScripts[0].isMainFrameOnly, false); }); testWidgets('removeJavascriptChannels with zoom disabled', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); when( mocks.webViewWidgetProxy.createScriptMessageHandler( didReceiveScriptMessage: anyNamed('didReceiveScriptMessage'), ), ).thenReturn( MockWKScriptMessageHandler(), ); final WebKitWebViewPlatformController testController = await buildWidget( tester, mocks, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), zoomEnabled: false, hasNavigationDelegate: false, ), ), ); await testController.addJavascriptChannels(<String>{'c'}); clearInteractions(mocks.userContentController); await testController.removeJavascriptChannels(<String>{'c'}); final WKUserScript zoomScript = verify(mocks.userContentController.addUserScript(captureAny)) .captured .first as WKUserScript; expect(zoomScript.isMainFrameOnly, isTrue); expect( zoomScript.injectionTime, WKUserScriptInjectionTime.atDocumentEnd); expect( zoomScript.source, "var meta = document.createElement('meta');\n" "meta.name = 'viewport';\n" "meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, " "user-scalable=no';\n" "var head = document.getElementsByTagName('head')[0];head.appendChild(meta);", ); }); }); group('WebViewPlatformCallbacksHandler', () { testWidgets('onPageStarted', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget(tester, mocks); final void Function(WKWebView, String) didStartProvisionalNavigation = verify(mocks.webViewWidgetProxy.createNavigationDelegate( didFinishNavigation: anyNamed('didFinishNavigation'), didStartProvisionalNavigation: captureAnyNamed('didStartProvisionalNavigation'), decidePolicyForNavigationAction: anyNamed('decidePolicyForNavigationAction'), didFailNavigation: anyNamed('didFailNavigation'), didFailProvisionalNavigation: anyNamed('didFailProvisionalNavigation'), webViewWebContentProcessDidTerminate: anyNamed('webViewWebContentProcessDidTerminate'), )).captured.single as void Function(WKWebView, String); didStartProvisionalNavigation(mocks.webView, 'https://google.com'); verify(mocks.callbacksHandler.onPageStarted('https://google.com')); }); testWidgets('onPageFinished', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget(tester, mocks); final void Function(WKWebView, String) didFinishNavigation = verify(mocks.webViewWidgetProxy.createNavigationDelegate( didFinishNavigation: captureAnyNamed('didFinishNavigation'), didStartProvisionalNavigation: anyNamed('didStartProvisionalNavigation'), decidePolicyForNavigationAction: anyNamed('decidePolicyForNavigationAction'), didFailNavigation: anyNamed('didFailNavigation'), didFailProvisionalNavigation: anyNamed('didFailProvisionalNavigation'), webViewWebContentProcessDidTerminate: anyNamed('webViewWebContentProcessDidTerminate'), )).captured.single as void Function(WKWebView, String); didFinishNavigation(mocks.webView, 'https://google.com'); verify(mocks.callbacksHandler.onPageFinished('https://google.com')); }); testWidgets('onWebResourceError from didFailNavigation', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget(tester, mocks); final void Function(WKWebView, NSError) didFailNavigation = verify(mocks.webViewWidgetProxy.createNavigationDelegate( didFinishNavigation: anyNamed('didFinishNavigation'), didStartProvisionalNavigation: anyNamed('didStartProvisionalNavigation'), decidePolicyForNavigationAction: anyNamed('decidePolicyForNavigationAction'), didFailNavigation: captureAnyNamed('didFailNavigation'), didFailProvisionalNavigation: anyNamed('didFailProvisionalNavigation'), webViewWebContentProcessDidTerminate: anyNamed('webViewWebContentProcessDidTerminate'), )).captured.single as void Function(WKWebView, NSError); didFailNavigation( mocks.webView, const NSError( code: WKErrorCode.webViewInvalidated, domain: 'domain', userInfo: <String, Object?>{ NSErrorUserInfoKey.NSLocalizedDescription: 'my desc', }, ), ); final WebResourceError error = verify(mocks.callbacksHandler.onWebResourceError(captureAny)) .captured .single as WebResourceError; expect(error.description, 'my desc'); expect(error.errorCode, WKErrorCode.webViewInvalidated); expect(error.domain, 'domain'); expect(error.errorType, WebResourceErrorType.webViewInvalidated); }); testWidgets('onWebResourceError from didFailProvisionalNavigation', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget(tester, mocks); final void Function(WKWebView, NSError) didFailProvisionalNavigation = verify(mocks.webViewWidgetProxy.createNavigationDelegate( didFinishNavigation: anyNamed('didFinishNavigation'), didStartProvisionalNavigation: anyNamed('didStartProvisionalNavigation'), decidePolicyForNavigationAction: anyNamed('decidePolicyForNavigationAction'), didFailNavigation: anyNamed('didFailNavigation'), didFailProvisionalNavigation: captureAnyNamed('didFailProvisionalNavigation'), webViewWebContentProcessDidTerminate: anyNamed('webViewWebContentProcessDidTerminate'), )).captured.single as void Function(WKWebView, NSError); didFailProvisionalNavigation( mocks.webView, const NSError( code: WKErrorCode.webContentProcessTerminated, domain: 'domain', userInfo: <String, Object?>{ NSErrorUserInfoKey.NSLocalizedDescription: 'my desc', }, ), ); final WebResourceError error = verify(mocks.callbacksHandler.onWebResourceError(captureAny)) .captured .single as WebResourceError; expect(error.description, 'my desc'); expect(error.errorCode, WKErrorCode.webContentProcessTerminated); expect(error.domain, 'domain'); expect( error.errorType, WebResourceErrorType.webContentProcessTerminated, ); }); testWidgets( 'onWebResourceError from webViewWebContentProcessDidTerminate', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget(tester, mocks); final void Function(WKWebView) webViewWebContentProcessDidTerminate = verify(mocks.webViewWidgetProxy.createNavigationDelegate( didFinishNavigation: anyNamed('didFinishNavigation'), didStartProvisionalNavigation: anyNamed('didStartProvisionalNavigation'), decidePolicyForNavigationAction: anyNamed('decidePolicyForNavigationAction'), didFailNavigation: anyNamed('didFailNavigation'), didFailProvisionalNavigation: anyNamed('didFailProvisionalNavigation'), webViewWebContentProcessDidTerminate: captureAnyNamed('webViewWebContentProcessDidTerminate'), )).captured.single as void Function(WKWebView); webViewWebContentProcessDidTerminate(mocks.webView); final WebResourceError error = verify(mocks.callbacksHandler.onWebResourceError(captureAny)) .captured .single as WebResourceError; expect(error.description, ''); expect(error.errorCode, WKErrorCode.webContentProcessTerminated); expect(error.domain, 'WKErrorDomain'); expect( error.errorType, WebResourceErrorType.webContentProcessTerminated, ); }); testWidgets('onNavigationRequest from decidePolicyForNavigationAction', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget(tester, mocks, hasNavigationDelegate: true); final Future<WKNavigationActionPolicy> Function( WKWebView, WKNavigationAction) decidePolicyForNavigationAction = verify(mocks.webViewWidgetProxy.createNavigationDelegate( didFinishNavigation: anyNamed('didFinishNavigation'), didStartProvisionalNavigation: anyNamed('didStartProvisionalNavigation'), decidePolicyForNavigationAction: captureAnyNamed('decidePolicyForNavigationAction'), didFailNavigation: anyNamed('didFailNavigation'), didFailProvisionalNavigation: anyNamed('didFailProvisionalNavigation'), webViewWebContentProcessDidTerminate: anyNamed('webViewWebContentProcessDidTerminate'), )).captured.single as Future<WKNavigationActionPolicy> Function( WKWebView, WKNavigationAction); when(mocks.callbacksHandler.onNavigationRequest( isForMainFrame: argThat(isFalse, named: 'isForMainFrame'), url: 'https://google.com', )).thenReturn(true); expect( decidePolicyForNavigationAction( mocks.webView, const WKNavigationAction( request: NSUrlRequest(url: 'https://google.com'), targetFrame: WKFrameInfo( isMainFrame: false, request: NSUrlRequest(url: 'https://google.com')), navigationType: WKNavigationType.linkActivated, ), ), completion(WKNavigationActionPolicy.allow), ); verify(mocks.callbacksHandler.onNavigationRequest( url: 'https://google.com', isForMainFrame: false, )); }); testWidgets('onProgress', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget(tester, mocks, hasProgressTracking: true); verify(mocks.webView.addObserver( mocks.webView, keyPath: 'estimatedProgress', options: <NSKeyValueObservingOptions>{ NSKeyValueObservingOptions.newValue, }, )); final void Function(String, NSObject, Map<NSKeyValueChangeKey, Object?>) observeValue = verify(mocks.webViewWidgetProxy.createWebView(any, observeValue: captureAnyNamed('observeValue'))) .captured .single as void Function( String, NSObject, Map<NSKeyValueChangeKey, Object?>); observeValue( 'estimatedProgress', mocks.webView, <NSKeyValueChangeKey, Object?>{NSKeyValueChangeKey.newValue: 0.32}, ); verify(mocks.callbacksHandler.onProgress(32)); }); testWidgets('progress observer is not removed without being set first', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); await buildWidget(tester, mocks); verifyNever(mocks.webView.removeObserver( mocks.webView, keyPath: 'estimatedProgress', )); }); }); group('JavascriptChannelRegistry', () { testWidgets('onJavascriptChannelMessage', (WidgetTester tester) async { final _WebViewMocks mocks = configureMocks(); when( mocks.webViewWidgetProxy.createScriptMessageHandler( didReceiveScriptMessage: anyNamed('didReceiveScriptMessage'), ), ).thenReturn( MockWKScriptMessageHandler(), ); final WebKitWebViewPlatformController testController = await buildWidget(tester, mocks); await testController.addJavascriptChannels(<String>{'hello'}); final void Function(WKUserContentController, WKScriptMessage) didReceiveScriptMessage = verify(mocks.webViewWidgetProxy .createScriptMessageHandler( didReceiveScriptMessage: captureAnyNamed('didReceiveScriptMessage'))) .captured .single as void Function(WKUserContentController, WKScriptMessage); didReceiveScriptMessage( mocks.userContentController, const WKScriptMessage(name: 'hello', body: 'A message.'), ); verify(mocks.javascriptChannelRegistry.onJavascriptChannelMessage( 'hello', 'A message.', )); }); }); }); } /// A collection of mocks used in constructing a WebViewWidget. class _WebViewMocks { _WebViewMocks({ required this.webView, required this.webViewWidgetProxy, required this.userContentController, required this.preferences, required this.webViewConfiguration, required this.uiDelegate, required this.scrollView, required this.websiteDataStore, required this.navigationDelegate, required this.callbacksHandler, required this.javascriptChannelRegistry, }); final MockWKWebView webView; final MockWebViewWidgetProxy webViewWidgetProxy; final MockWKUserContentController userContentController; final MockWKPreferences preferences; final MockWKWebViewConfiguration webViewConfiguration; final MockWKUIDelegate uiDelegate; final MockUIScrollView scrollView; final MockWKWebsiteDataStore websiteDataStore; final MockWKNavigationDelegate navigationDelegate; final MockWebViewPlatformCallbacksHandler callbacksHandler; final MockJavascriptChannelRegistry javascriptChannelRegistry; }
packages/packages/webview_flutter/webview_flutter_wkwebview/test/legacy/web_kit_webview_widget_test.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/test/legacy/web_kit_webview_widget_test.dart", "repo_id": "packages", "token_count": 22948 }
1,177
// Mocks generated by Mockito 5.4.4 from annotations // in webview_flutter_wkwebview/test/webkit_webview_widget_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart' as _i4; import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart' as _i2; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeWKUIDelegate_0 extends _i1.SmartFake implements _i2.WKUIDelegate { _FakeWKUIDelegate_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWKUserContentController_1 extends _i1.SmartFake implements _i2.WKUserContentController { _FakeWKUserContentController_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWKPreferences_2 extends _i1.SmartFake implements _i2.WKPreferences { _FakeWKPreferences_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWKWebsiteDataStore_3 extends _i1.SmartFake implements _i2.WKWebsiteDataStore { _FakeWKWebsiteDataStore_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWKWebViewConfiguration_4 extends _i1.SmartFake implements _i2.WKWebViewConfiguration { _FakeWKWebViewConfiguration_4( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [WKUIDelegate]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockWKUIDelegate extends _i1.Mock implements _i2.WKUIDelegate { MockWKUIDelegate() { _i1.throwOnMissingStub(this); } @override _i2.WKUIDelegate copy() => (super.noSuchMethod( Invocation.method( #copy, [], ), returnValue: _FakeWKUIDelegate_0( this, Invocation.method( #copy, [], ), ), ) as _i2.WKUIDelegate); @override _i3.Future<void> addObserver( _i4.NSObject? observer, { required String? keyPath, required Set<_i4.NSKeyValueObservingOptions>? options, }) => (super.noSuchMethod( Invocation.method( #addObserver, [observer], { #keyPath: keyPath, #options: options, }, ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); @override _i3.Future<void> removeObserver( _i4.NSObject? observer, { required String? keyPath, }) => (super.noSuchMethod( Invocation.method( #removeObserver, [observer], {#keyPath: keyPath}, ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); } /// A class which mocks [WKWebViewConfiguration]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable class MockWKWebViewConfiguration extends _i1.Mock implements _i2.WKWebViewConfiguration { MockWKWebViewConfiguration() { _i1.throwOnMissingStub(this); } @override _i2.WKUserContentController get userContentController => (super.noSuchMethod( Invocation.getter(#userContentController), returnValue: _FakeWKUserContentController_1( this, Invocation.getter(#userContentController), ), ) as _i2.WKUserContentController); @override _i2.WKPreferences get preferences => (super.noSuchMethod( Invocation.getter(#preferences), returnValue: _FakeWKPreferences_2( this, Invocation.getter(#preferences), ), ) as _i2.WKPreferences); @override _i2.WKWebsiteDataStore get websiteDataStore => (super.noSuchMethod( Invocation.getter(#websiteDataStore), returnValue: _FakeWKWebsiteDataStore_3( this, Invocation.getter(#websiteDataStore), ), ) as _i2.WKWebsiteDataStore); @override _i3.Future<void> setAllowsInlineMediaPlayback(bool? allow) => (super.noSuchMethod( Invocation.method( #setAllowsInlineMediaPlayback, [allow], ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); @override _i3.Future<void> setLimitsNavigationsToAppBoundDomains(bool? limit) => (super.noSuchMethod( Invocation.method( #setLimitsNavigationsToAppBoundDomains, [limit], ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); @override _i3.Future<void> setMediaTypesRequiringUserActionForPlayback( Set<_i2.WKAudiovisualMediaType>? types) => (super.noSuchMethod( Invocation.method( #setMediaTypesRequiringUserActionForPlayback, [types], ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); @override _i2.WKWebViewConfiguration copy() => (super.noSuchMethod( Invocation.method( #copy, [], ), returnValue: _FakeWKWebViewConfiguration_4( this, Invocation.method( #copy, [], ), ), ) as _i2.WKWebViewConfiguration); @override _i3.Future<void> addObserver( _i4.NSObject? observer, { required String? keyPath, required Set<_i4.NSKeyValueObservingOptions>? options, }) => (super.noSuchMethod( Invocation.method( #addObserver, [observer], { #keyPath: keyPath, #options: options, }, ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); @override _i3.Future<void> removeObserver( _i4.NSObject? observer, { required String? keyPath, }) => (super.noSuchMethod( Invocation.method( #removeObserver, [observer], {#keyPath: keyPath}, ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); }
packages/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_webview_widget_test.mocks.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_webview_widget_test.mocks.dart", "repo_id": "packages", "token_count": 3236 }
1,178
# Hangs due to permission issue, see https://github.com/flutter/flutter/issues/130987 # TODO(stuartmorgan): Remove once the permission issue is addressed. - camera/camera - camera_android - camera_android_camerax # Frequent flaky failures, see https://github.com/flutter/flutter/issues/130986 # TODO(stuartmorgan): Remove once the flake is fixed. - google_maps_flutter - google_maps_flutter_android
packages/script/configs/exclude_integration_android_emulator.yaml/0
{ "file_path": "packages/script/configs/exclude_integration_android_emulator.yaml", "repo_id": "packages", "token_count": 124 }
1,179
// 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:yaml/yaml.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'; /// Key for APK. const String _platformFlagApk = 'apk'; const String _pluginToolsConfigFileName = '.pluginToolsConfig.yaml'; const String _pluginToolsConfigBuildFlagsKey = 'buildFlags'; const String _pluginToolsConfigGlobalKey = 'global'; const String _pluginToolsConfigExample = ''' $_pluginToolsConfigBuildFlagsKey: $_pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing" '''; const int _exitNoPlatformFlags = 3; const int _exitInvalidPluginToolsConfig = 4; // Flutter build types. These are the values passed to `flutter build <foo>`. const String _flutterBuildTypeAndroid = 'apk'; const String _flutterBuildTypeIOS = 'ios'; const String _flutterBuildTypeLinux = 'linux'; const String _flutterBuildTypeMacOS = 'macos'; const String _flutterBuildTypeWeb = 'web'; const String _flutterBuildTypeWindows = 'windows'; const String _flutterBuildTypeAndroidAlias = 'android'; /// A command to build the example applications for packages. class BuildExamplesCommand extends PackageLoopingCommand { /// Creates an instance of the build command. BuildExamplesCommand( super.packagesDir, { super.processRunner, super.platform, }) { argParser.addFlag(platformLinux); argParser.addFlag(platformMacOS); argParser.addFlag(platformWeb); argParser.addFlag(platformWindows); argParser.addFlag(platformIOS); argParser.addFlag(_platformFlagApk, aliases: const <String>[_flutterBuildTypeAndroidAlias]); argParser.addOption( kEnableExperiment, defaultsTo: '', help: 'Enables the given Dart SDK experiments.', ); } // Maps the switch this command uses to identify a platform to information // about it. static final Map<String, _PlatformDetails> _platforms = <String, _PlatformDetails>{ _platformFlagApk: const _PlatformDetails( 'Android', pluginPlatform: platformAndroid, flutterBuildType: _flutterBuildTypeAndroid, ), platformIOS: const _PlatformDetails( 'iOS', pluginPlatform: platformIOS, flutterBuildType: _flutterBuildTypeIOS, extraBuildFlags: <String>['--no-codesign'], ), platformLinux: const _PlatformDetails( 'Linux', pluginPlatform: platformLinux, flutterBuildType: _flutterBuildTypeLinux, ), platformMacOS: const _PlatformDetails( 'macOS', pluginPlatform: platformMacOS, flutterBuildType: _flutterBuildTypeMacOS, ), platformWeb: const _PlatformDetails( 'web', pluginPlatform: platformWeb, flutterBuildType: _flutterBuildTypeWeb, ), platformWindows: const _PlatformDetails( 'Windows', pluginPlatform: platformWindows, flutterBuildType: _flutterBuildTypeWindows, ), }; @override final String name = 'build-examples'; @override final String description = 'Builds all example apps (IPA for iOS and APK for Android).\n\n' 'This command requires "flutter" to be in your path.\n\n' 'A $_pluginToolsConfigFileName file can be placed in an example app ' 'directory to specify additional build arguments. It should be a YAML ' 'file with a top-level map containing a single key ' '"$_pluginToolsConfigBuildFlagsKey" containing a map containing a ' 'single key "$_pluginToolsConfigGlobalKey" containing a list of build ' 'arguments.'; @override Future<void> initializeRun() async { final List<String> platformFlags = _platforms.keys.toList(); platformFlags.sort(); if (!platformFlags.any((String platform) => getBoolArg(platform))) { printError( 'None of ${platformFlags.map((String platform) => '--$platform').join(', ')} ' 'were specified. At least one platform must be provided.'); throw ToolExit(_exitNoPlatformFlags); } } @override Future<PackageResult> runForPackage(RepositoryPackage package) async { final List<String> errors = <String>[]; final bool isPlugin = isFlutterPlugin(package); final Iterable<_PlatformDetails> requestedPlatforms = _platforms.entries .where( (MapEntry<String, _PlatformDetails> entry) => getBoolArg(entry.key)) .map((MapEntry<String, _PlatformDetails> entry) => entry.value); // Platform support is checked at the package level for plugins; there is // no package-level platform information for non-plugin packages. final Set<_PlatformDetails> buildPlatforms = isPlugin ? requestedPlatforms .where((_PlatformDetails platform) => pluginSupportsPlatform(platform.pluginPlatform, package)) .toSet() : requestedPlatforms.toSet(); String platformDisplayList(Iterable<_PlatformDetails> platforms) { return platforms.map((_PlatformDetails p) => p.label).join(', '); } if (buildPlatforms.isEmpty) { final String unsupported = requestedPlatforms.length == 1 ? '${requestedPlatforms.first.label} is not supported' : 'None of [${platformDisplayList(requestedPlatforms)}] are supported'; return PackageResult.skip('$unsupported by this plugin'); } print('Building for: ${platformDisplayList(buildPlatforms)}'); final Set<_PlatformDetails> unsupportedPlatforms = requestedPlatforms.toSet().difference(buildPlatforms); if (unsupportedPlatforms.isNotEmpty) { final List<String> skippedPlatforms = unsupportedPlatforms .map((_PlatformDetails platform) => platform.label) .toList(); skippedPlatforms.sort(); print('Skipping unsupported platform(s): ' '${skippedPlatforms.join(', ')}'); } print(''); bool builtSomething = false; for (final RepositoryPackage example in package.getExamples()) { final String packageName = getRelativePosixPath(example.directory, from: packagesDir); for (final _PlatformDetails platform in buildPlatforms) { // Repo policy is that a plugin must have examples configured for all // supported platforms. For packages, just log and skip any requested // platform that a package doesn't have set up. if (!isPlugin && !example.appSupportsPlatform( getPlatformByName(platform.pluginPlatform))) { print('Skipping ${platform.label} for $packageName; not supported.'); continue; } builtSomething = true; String buildPlatform = platform.label; if (platform.label.toLowerCase() != platform.flutterBuildType) { buildPlatform += ' (${platform.flutterBuildType})'; } print('\nBUILDING $packageName for $buildPlatform'); if (!await _buildExample(example, platform.flutterBuildType, extraBuildFlags: platform.extraBuildFlags)) { errors.add('$packageName (${platform.label})'); } } } if (!builtSomething) { if (isPlugin) { errors.add('No examples found'); } else { return PackageResult.skip( 'No examples found supporting requested platform(s).'); } } return errors.isEmpty ? PackageResult.success() : PackageResult.fail(errors); } Iterable<String> _readExtraBuildFlagsConfiguration( Directory directory) sync* { final File pluginToolsConfig = directory.childFile(_pluginToolsConfigFileName); if (pluginToolsConfig.existsSync()) { final Object? configuration = loadYaml(pluginToolsConfig.readAsStringSync()); if (configuration is! YamlMap) { printError('The $_pluginToolsConfigFileName file must be a YAML map.'); printError( 'Currently, the key "$_pluginToolsConfigBuildFlagsKey" is the only one that has an effect.'); printError( 'It must itself be a map. Currently, in that map only the key "$_pluginToolsConfigGlobalKey"'); printError( 'has any effect; it must contain a list of arguments to pass to the'); printError('flutter tool.'); printError(_pluginToolsConfigExample); throw ToolExit(_exitInvalidPluginToolsConfig); } if (configuration.containsKey(_pluginToolsConfigBuildFlagsKey)) { final Object? buildFlagsConfiguration = configuration[_pluginToolsConfigBuildFlagsKey]; if (buildFlagsConfiguration is! YamlMap) { printError( 'The $_pluginToolsConfigFileName file\'s "$_pluginToolsConfigBuildFlagsKey" key must be a map.'); printError( 'Currently, in that map only the key "$_pluginToolsConfigGlobalKey" has any effect; it must '); printError( 'contain a list of arguments to pass to the flutter tool.'); printError(_pluginToolsConfigExample); throw ToolExit(_exitInvalidPluginToolsConfig); } if (buildFlagsConfiguration.containsKey(_pluginToolsConfigGlobalKey)) { final Object? globalBuildFlagsConfiguration = buildFlagsConfiguration[_pluginToolsConfigGlobalKey]; if (globalBuildFlagsConfiguration is! YamlList) { printError( 'The $_pluginToolsConfigFileName file\'s "$_pluginToolsConfigBuildFlagsKey" key must be a map'); printError('whose "$_pluginToolsConfigGlobalKey" key is a list.'); printError( 'That list must contain a list of arguments to pass to the flutter tool.'); printError( 'For example, the $_pluginToolsConfigFileName file could look like:'); printError(_pluginToolsConfigExample); throw ToolExit(_exitInvalidPluginToolsConfig); } yield* globalBuildFlagsConfiguration.cast<String>(); } } } } Future<bool> _buildExample( RepositoryPackage example, String flutterBuildType, { List<String> extraBuildFlags = const <String>[], }) async { final String enableExperiment = getStringArg(kEnableExperiment); final int exitCode = await processRunner.runAndStream( flutterCommand, <String>[ 'build', flutterBuildType, ...extraBuildFlags, ..._readExtraBuildFlagsConfiguration(example.directory), if (enableExperiment.isNotEmpty) '--enable-experiment=$enableExperiment', ], workingDir: example.directory, ); return exitCode == 0; } } /// A collection of information related to a specific platform. class _PlatformDetails { const _PlatformDetails( this.label, { required this.pluginPlatform, required this.flutterBuildType, this.extraBuildFlags = const <String>[], }); /// The name to use in output. final String label; /// The key in a pubspec's platform: entry. final String pluginPlatform; /// The `flutter build` build type. final String flutterBuildType; /// Any extra flags to pass to `flutter build`. final List<String> extraBuildFlags; }
packages/script/tool/lib/src/build_examples_command.dart/0
{ "file_path": "packages/script/tool/lib/src/build_examples_command.dart", "repo_id": "packages", "token_count": 4061 }
1,180
// 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:meta/meta.dart'; import 'package:path/path.dart' as p; import 'package:platform/platform.dart'; import 'package:pub_semver/pub_semver.dart'; import 'package:pubspec_parse/pubspec_parse.dart'; import 'common/core.dart'; import 'common/file_utils.dart'; import 'common/output_utils.dart'; import 'common/package_command.dart'; import 'common/process_runner.dart'; import 'common/pub_utils.dart'; import 'common/repository_package.dart'; /// The name of the build-all-packages project, as passed to `flutter create`. @visibleForTesting const String allPackagesProjectName = 'all_packages'; const int _exitFlutterCreateFailed = 3; const int _exitGenNativeBuildFilesFailed = 4; const int _exitMissingFile = 5; const int _exitMissingLegacySource = 6; /// A command to create an application that builds all in a single application. class CreateAllPackagesAppCommand extends PackageCommand { /// Creates an instance of the builder command. CreateAllPackagesAppCommand( Directory packagesDir, { ProcessRunner processRunner = const ProcessRunner(), Platform platform = const LocalPlatform(), }) : super(packagesDir, processRunner: processRunner, platform: platform) { argParser.addOption(_outputDirectoryFlag, defaultsTo: packagesDir.parent.path, help: 'The path the directory to create the "$allPackagesProjectName" ' 'project in.\n' 'Defaults to the repository root.'); argParser.addOption(_legacySourceFlag, help: 'A partial project directory to use as a source for replacing ' 'portions of the created app. All top-level directories in the ' 'source will replace the corresponding directories in the output ' 'directory post-create.\n\n' 'The replacement will be done before any tool-driven ' 'modifications.'); } static const String _legacySourceFlag = 'legacy-source'; static const String _outputDirectoryFlag = 'output-dir'; /// The location to create the synthesized app project. Directory get _appDirectory => packagesDir.fileSystem .directory(getStringArg(_outputDirectoryFlag)) .childDirectory(allPackagesProjectName); /// The synthesized app project. RepositoryPackage get app => RepositoryPackage(_appDirectory); @override String get description => 'Generate Flutter app that includes all target packagas.'; @override String get name => 'create-all-packages-app'; @override Future<void> run() async { final int exitCode = await _createApp(); if (exitCode != 0) { printError('Failed to `flutter create`: $exitCode'); throw ToolExit(_exitFlutterCreateFailed); } final String? legacySource = getNullableStringArg(_legacySourceFlag); if (legacySource != null) { final Directory legacyDir = packagesDir.fileSystem.directory(legacySource); await _replaceWithLegacy(target: _appDirectory, source: legacyDir); } final Set<String> excluded = getExcludedPackageNames(); if (excluded.isNotEmpty) { print('Exluding the following plugins from the combined build:'); for (final String plugin in excluded) { print(' $plugin'); } print(''); } await _genPubspecWithAllPlugins(); // Run `flutter pub get` to generate all native build files. // TODO(stuartmorgan): This hangs on Windows for some reason. Since it's // currently not needed on Windows, skip it there, but we should investigate // further and/or implement https://github.com/flutter/flutter/issues/93407, // and remove the need for this conditional. if (!platform.isWindows) { if (!await runPubGet(app, processRunner, platform)) { printError( "Failed to generate native build files via 'flutter pub get'"); throw ToolExit(_exitGenNativeBuildFilesFailed); } } await Future.wait(<Future<void>>[ _updateAppGradle(), _updateMacosPbxproj(), // This step requires the native file generation triggered by // flutter pub get above, so can't currently be run on Windows. if (!platform.isWindows) _updateMacosPodfile(), ]); } Future<int> _createApp() async { return processRunner.runAndStream( flutterCommand, <String>[ 'create', '--template=app', '--project-name=$allPackagesProjectName', _appDirectory.path, ], ); } Future<void> _replaceWithLegacy( {required Directory target, required Directory source}) async { if (!source.existsSync()) { printError('No such legacy source directory: ${source.path}'); throw ToolExit(_exitMissingLegacySource); } for (final FileSystemEntity entity in source.listSync()) { final String basename = entity.basename; print('Replacing $basename with legacy version...'); if (entity is Directory) { target.childDirectory(basename).deleteSync(recursive: true); } else { target.childFile(basename).deleteSync(); } _copyDirectory(source: source, target: target); } } void _copyDirectory({required Directory target, required Directory source}) { target.createSync(recursive: true); for (final FileSystemEntity entity in source.listSync(recursive: true)) { final List<String> subcomponents = p.split(p.relative(entity.path, from: source.path)); if (entity is Directory) { childDirectoryWithSubcomponents(target, subcomponents) .createSync(recursive: true); } else if (entity is File) { final File targetFile = childFileWithSubcomponents(target, subcomponents); targetFile.parent.createSync(recursive: true); entity.copySync(targetFile.path); } else { throw UnimplementedError('Unsupported entity: $entity'); } } } /// Rewrites [file], replacing any lines contain a key in [replacements] with /// the lines in the corresponding value, and adding any lines in [additions]' /// values after lines containing the key. void _adjustFile( File file, { Map<String, List<String>> replacements = const <String, List<String>>{}, Map<String, List<String>> additions = const <String, List<String>>{}, Map<RegExp, List<String>> regexReplacements = const <RegExp, List<String>>{}, }) { if (replacements.isEmpty && additions.isEmpty) { return; } if (!file.existsSync()) { printError('Unable to find ${file.path} for updating.'); throw ToolExit(_exitMissingFile); } final StringBuffer output = StringBuffer(); for (final String line in file.readAsLinesSync()) { List<String>? replacementLines; for (final MapEntry<String, List<String>> replacement in replacements.entries) { if (line.contains(replacement.key)) { replacementLines = replacement.value; break; } } if (replacementLines == null) { for (final MapEntry<RegExp, List<String>> replacement in regexReplacements.entries) { final RegExpMatch? match = replacement.key.firstMatch(line); if (match != null) { replacementLines = replacement.value; break; } } } (replacementLines ?? <String>[line]).forEach(output.writeln); for (final String targetString in additions.keys) { if (line.contains(targetString)) { additions[targetString]!.forEach(output.writeln); } } } file.writeAsStringSync(output.toString()); } Future<void> _updateAppGradle() async { final File gradleFile = app .platformDirectory(FlutterPlatform.android) .childDirectory('app') .childFile('build.gradle'); // Ensure that there is a dependencies section, so the dependencies addition // below will work. final String content = gradleFile.readAsStringSync(); if (!content.contains('\ndependencies {')) { gradleFile.writeAsStringSync(''' $content dependencies {} '''); } const String lifecycleDependency = " implementation 'androidx.lifecycle:lifecycle-runtime:2.2.0-rc01'"; _adjustFile( gradleFile, replacements: <String, List<String>>{ // minSdkVersion 21 is required by camera_android. 'minSdkVersion': <String>['minSdkVersion 21'], 'compileSdkVersion': <String>['compileSdk 34'], }, additions: <String, List<String>>{ 'defaultConfig {': <String>[' multiDexEnabled true'], }, regexReplacements: <RegExp, List<String>>{ // Tests for https://github.com/flutter/flutter/issues/43383 // Handling of 'dependencies' is more complex since it hasn't been very // stable across template versions. // - Handle an empty, collapsed dependencies section. RegExp(r'^dependencies\s+{\s*}$'): <String>[ 'dependencies {', lifecycleDependency, '}', ], // - Handle a normal dependencies section. RegExp(r'^dependencies\s+{$'): <String>[ 'dependencies {', lifecycleDependency, ], // - See below for handling of the case where there is no dependencies // section. }, ); } Future<void> _genPubspecWithAllPlugins() async { // Read the old pubspec file's Dart SDK version, in order to preserve it // in the new file. The template sometimes relies on having opted in to // specific language features via SDK version, so using a different one // can cause compilation failures. final Pubspec originalPubspec = app.parsePubspec(); const String dartSdkKey = 'sdk'; final VersionConstraint dartSdkConstraint = originalPubspec.environment?[dartSdkKey] ?? VersionConstraint.compatibleWith( Version.parse('2.12.0'), ); final Map<String, PathDependency> pluginDeps = await _getValidPathDependencies(); final Pubspec pubspec = Pubspec( allPackagesProjectName, description: 'Flutter app containing all 1st party plugins.', version: Version.parse('1.0.0+1'), environment: <String, VersionConstraint>{ dartSdkKey: dartSdkConstraint, }, dependencies: <String, Dependency>{ 'flutter': SdkDependency('flutter'), }..addAll(pluginDeps), devDependencies: <String, Dependency>{ 'flutter_test': SdkDependency('flutter'), }, dependencyOverrides: pluginDeps, ); // An application cannot depend directly on multiple federated // implementations of the same plugin for the same platform, which means the // app cannot directly depend on both camera_android and // camera_android_androidx. Since camera_android is endorsed, it will be // included transitively already, so exclude it from the direct dependency // list to allow including camera_android_androidx to ensure that they don't // conflict at build time (if they did, it would be impossible to use // camera_android_androidx while camera_android is endorsed). // This is special-cased here, rather than being done via the normal // exclusion config file mechanism, because it still needs to be in the // depenedency overrides list to ensure that the version from path is used. pubspec.dependencies.remove('camera_android'); app.pubspecFile.writeAsStringSync(_pubspecToString(pubspec)); } Future<Map<String, PathDependency>> _getValidPathDependencies() async { final Map<String, PathDependency> pathDependencies = <String, PathDependency>{}; await for (final PackageEnumerationEntry entry in getTargetPackages()) { final RepositoryPackage package = entry.package; final Directory pluginDirectory = package.directory; final String pluginName = pluginDirectory.basename; final Pubspec pubspec = package.parsePubspec(); if (pubspec.publishTo != 'none') { pathDependencies[pluginName] = PathDependency(pluginDirectory.path); } } return pathDependencies; } String _pubspecToString(Pubspec pubspec) { return ''' ### Generated file. Do not edit. Run `dart pub global run flutter_plugin_tools gen-pubspec` to update. name: ${pubspec.name} description: ${pubspec.description} publish_to: none version: ${pubspec.version} environment:${_pubspecMapString(pubspec.environment!)} dependencies:${_pubspecMapString(pubspec.dependencies)} dependency_overrides:${_pubspecMapString(pubspec.dependencyOverrides)} dev_dependencies:${_pubspecMapString(pubspec.devDependencies)} ###'''; } String _pubspecMapString(Map<String, Object?> values) { final StringBuffer buffer = StringBuffer(); for (final MapEntry<String, Object?> entry in values.entries) { buffer.writeln(); final Object? entryValue = entry.value; if (entryValue is VersionConstraint) { String value = entryValue.toString(); // Range constraints require quoting. if (value.startsWith('>') || value.startsWith('<')) { value = "'$value'"; } buffer.write(' ${entry.key}: $value'); } else if (entryValue is SdkDependency) { buffer.write(' ${entry.key}: \n sdk: ${entryValue.sdk}'); } else if (entryValue is PathDependency) { String depPath = entryValue.path; if (path.style == p.Style.windows) { // Posix-style path separators are preferred in pubspec.yaml (and // using a consistent format makes unit testing simpler), so convert. final List<String> components = path.split(depPath); final String firstComponent = components.first; // path.split leaves a \ on drive components that isn't necessary, // and confuses pub, so remove it. if (firstComponent.endsWith(r':\')) { components[0] = firstComponent.substring(0, firstComponent.length - 1); } depPath = p.posix.joinAll(components); } buffer.write(' ${entry.key}: \n path: $depPath'); } else { throw UnimplementedError( 'Not available for type: ${entryValue.runtimeType}', ); } } return buffer.toString(); } Future<void> _updateMacosPodfile() async { /// Only change the macOS deployment target if the host platform is macOS. /// The Podfile is not generated on other platforms. if (!platform.isMacOS) { return; } final File podfile = app.platformDirectory(FlutterPlatform.macos).childFile('Podfile'); _adjustFile( podfile, replacements: <String, List<String>>{ // macOS 10.15 is required by in_app_purchase. 'platform :osx': <String>["platform :osx, '10.15'"], }, ); } Future<void> _updateMacosPbxproj() async { final File pbxprojFile = app .platformDirectory(FlutterPlatform.macos) .childDirectory('Runner.xcodeproj') .childFile('project.pbxproj'); _adjustFile( pbxprojFile, replacements: <String, List<String>>{ // macOS 10.15 is required by in_app_purchase. 'MACOSX_DEPLOYMENT_TARGET': <String>[ ' MACOSX_DEPLOYMENT_TARGET = 10.15;' ], }, ); } }
packages/script/tool/lib/src/create_all_packages_app_command.dart/0
{ "file_path": "packages/script/tool/lib/src/create_all_packages_app_command.dart", "repo_id": "packages", "token_count": 5692 }
1,181
// 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:ffi'; import 'package:file/file.dart'; import 'package:meta/meta.dart'; import 'common/cmake.dart'; import 'common/core.dart'; import 'common/gradle.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; import 'common/plugin_utils.dart'; import 'common/repository_package.dart'; import 'common/xcode.dart'; const String _unitTestFlag = 'unit'; const String _integrationTestFlag = 'integration'; const String _iOSDestinationFlag = 'ios-destination'; const int _exitNoIOSSimulators = 3; /// The error message logged when a FlutterTestRunner test is not annotated with /// @DartIntegrationTest. @visibleForTesting const String misconfiguredJavaIntegrationTestErrorExplanation = 'The following files use @RunWith(FlutterTestRunner.class) ' 'but not @DartIntegrationTest, which will cause hangs when run with ' 'this command. See ' 'https://github.com/flutter/flutter/wiki/Plugin-Tests#enabling-android-ui-tests ' 'for instructions.'; /// The command to run native tests for plugins: /// - iOS and macOS: XCTests (XCUnitTest and XCUITest) /// - Android: JUnit tests /// - Windows and Linux: GoogleTest tests class NativeTestCommand extends PackageLoopingCommand { /// Creates an instance of the test command. NativeTestCommand( super.packagesDir, { super.processRunner, super.platform, Abi? abi, }) : _abi = abi ?? Abi.current(), _xcode = Xcode(processRunner: processRunner, log: true) { argParser.addOption( _iOSDestinationFlag, help: 'Specify the destination when running iOS tests.\n' 'This is passed to the `-destination` argument in the xcodebuild command.\n' 'See https://developer.apple.com/library/archive/technotes/tn2339/_index.html#//apple_ref/doc/uid/DTS40014588-CH1-UNIT ' 'for details on how to specify the destination.', ); argParser.addFlag(platformAndroid, help: 'Runs Android tests'); argParser.addFlag(platformIOS, help: 'Runs iOS tests'); argParser.addFlag(platformLinux, help: 'Runs Linux tests'); argParser.addFlag(platformMacOS, help: 'Runs macOS tests'); argParser.addFlag(platformWindows, help: 'Runs Windows tests'); // By default, both unit tests and integration tests are run, but provide // flags to disable one or the other. argParser.addFlag(_unitTestFlag, help: 'Runs native unit tests', defaultsTo: true); argParser.addFlag(_integrationTestFlag, help: 'Runs native integration (UI) tests', defaultsTo: true); } // The ABI of the host. final Abi _abi; // The device destination flags for iOS tests. List<String> _iOSDestinationFlags = <String>[]; final Xcode _xcode; @override final String name = 'native-test'; @override List<String> get aliases => <String>['test-native']; @override final String description = ''' Runs native unit tests and native integration tests. Currently supported platforms: - Android - iOS: requires 'xcrun' to be in your path. - Linux (unit tests only) - macOS: requires 'xcrun' to be in your path. - Windows (unit tests only) The example app(s) must be built for all targeted platforms before running this command. '''; Map<String, _PlatformDetails> _platforms = <String, _PlatformDetails>{}; List<String> _requestedPlatforms = <String>[]; @override Future<void> initializeRun() async { _platforms = <String, _PlatformDetails>{ platformAndroid: _PlatformDetails('Android', _testAndroid), platformIOS: _PlatformDetails('iOS', _testIOS), platformLinux: _PlatformDetails('Linux', _testLinux), platformMacOS: _PlatformDetails('macOS', _testMacOS), platformWindows: _PlatformDetails('Windows', _testWindows), }; _requestedPlatforms = _platforms.keys .where((String platform) => getBoolArg(platform)) .toList(); _requestedPlatforms.sort(); if (_requestedPlatforms.isEmpty) { printError('At least one platform flag must be provided.'); throw ToolExit(exitInvalidArguments); } if (!(getBoolArg(_unitTestFlag) || getBoolArg(_integrationTestFlag))) { printError('At least one test type must be enabled.'); throw ToolExit(exitInvalidArguments); } if (getBoolArg(platformWindows) && getBoolArg(_integrationTestFlag)) { logWarning('This command currently only supports unit tests for Windows. ' 'See https://github.com/flutter/flutter/issues/70233.'); } if (getBoolArg(platformLinux) && getBoolArg(_integrationTestFlag)) { logWarning('This command currently only supports unit tests for Linux. ' 'See https://github.com/flutter/flutter/issues/70235.'); } // iOS-specific run-level state. if (_requestedPlatforms.contains('ios')) { String destination = getStringArg(_iOSDestinationFlag); if (destination.isEmpty) { final String? simulatorId = await _xcode.findBestAvailableIphoneSimulator(); if (simulatorId == null) { printError('Cannot find any available iOS simulators.'); throw ToolExit(_exitNoIOSSimulators); } destination = 'id=$simulatorId'; } _iOSDestinationFlags = <String>[ '-destination', destination, ]; } } @override Future<PackageResult> runForPackage(RepositoryPackage package) async { final List<String> testPlatforms = <String>[]; for (final String platform in _requestedPlatforms) { if (!pluginSupportsPlatform(platform, package, requiredMode: PlatformSupport.inline)) { print('No implementation for ${_platforms[platform]!.label}.'); continue; } if (!pluginHasNativeCodeForPlatform(platform, package)) { print('No native code for ${_platforms[platform]!.label}.'); continue; } testPlatforms.add(platform); } if (testPlatforms.isEmpty) { return PackageResult.skip('Nothing to test for target platform(s).'); } final _TestMode mode = _TestMode( unit: getBoolArg(_unitTestFlag), integration: getBoolArg(_integrationTestFlag), ); bool ranTests = false; bool failed = false; final List<String> failureMessages = <String>[]; for (final String platform in testPlatforms) { final _PlatformDetails platformInfo = _platforms[platform]!; print('Running tests for ${platformInfo.label}...'); print('----------------------------------------'); final _PlatformResult result = await platformInfo.testFunction(package, mode); ranTests |= result.state != RunState.skipped; if (result.state == RunState.failed) { failed = true; final String? error = result.error; // Only provide the failing platforms in the failure details if testing // multiple platforms, otherwise it's just noise. if (_requestedPlatforms.length > 1) { failureMessages.add(error != null ? '${platformInfo.label}: $error' : platformInfo.label); } else if (error != null) { // If there's only one platform, only provide error details in the // summary if the platform returned a message. failureMessages.add(error); } } } if (!ranTests) { return PackageResult.skip('No tests found.'); } return failed ? PackageResult.fail(failureMessages) : PackageResult.success(); } Future<_PlatformResult> _testAndroid( RepositoryPackage plugin, _TestMode mode) async { bool exampleHasUnitTests(RepositoryPackage example) { return example .platformDirectory(FlutterPlatform.android) .childDirectory('app') .childDirectory('src') .childDirectory('test') .existsSync() || plugin .platformDirectory(FlutterPlatform.android) .childDirectory('src') .childDirectory('test') .existsSync(); } _JavaTestInfo getJavaTestInfo(File testFile) { final List<String> contents = testFile.readAsLinesSync(); return _JavaTestInfo( usesFlutterTestRunner: contents.any((String line) => line.trimLeft().startsWith('@RunWith(FlutterTestRunner.class)')), hasDartIntegrationTestAnnotation: contents.any((String line) => line.trimLeft().startsWith('@DartIntegrationTest'))); } Map<File, _JavaTestInfo> findIntegrationTestFiles( RepositoryPackage example) { final Directory integrationTestDirectory = example .platformDirectory(FlutterPlatform.android) .childDirectory('app') .childDirectory('src') .childDirectory('androidTest'); // There are two types of integration tests that can be in the androidTest // directory: // - FlutterTestRunner.class tests, which bridge to Dart integration tests // - Purely native integration tests // Only the latter is supported by this command; the former will hang if // run here because they will wait for a Dart call that will never come. // // Find all test files, and determine which kind of test they are based on // the annotations they use. // // Ignore DartIntegrationTest.java, which defines the annotation used // below for filtering the former out when running tests. if (!integrationTestDirectory.existsSync()) { return <File, _JavaTestInfo>{}; } final Iterable<File> integrationTestFiles = integrationTestDirectory .listSync(recursive: true) .whereType<File>() .where((File file) { final String basename = file.basename; return basename != 'DartIntegrationTest.java' && basename != 'DartIntegrationTest.kt'; }); return <File, _JavaTestInfo>{ for (final File file in integrationTestFiles) file: getJavaTestInfo(file) }; } final Iterable<RepositoryPackage> examples = plugin.getExamples(); final String pluginName = plugin.directory.basename; bool ranUnitTests = false; bool ranAnyTests = false; bool failed = false; bool hasMisconfiguredIntegrationTest = false; // Iterate through all examples (in the rare case that there is more than // one example); running any tests found for each one. Requirements on what // tests are present are enforced at the overall package level, not a per- // example level. E.g., it's fine for only one example to have unit tests. for (final RepositoryPackage example in examples) { final bool hasUnitTests = exampleHasUnitTests(example); final Map<File, _JavaTestInfo> candidateIntegrationTestFiles = findIntegrationTestFiles(example); final bool hasIntegrationTests = candidateIntegrationTestFiles.values .any((_JavaTestInfo info) => !info.hasDartIntegrationTestAnnotation); if (mode.unit && !hasUnitTests) { _printNoExampleTestsMessage(example, 'Android unit'); } if (mode.integration && !hasIntegrationTests) { _printNoExampleTestsMessage(example, 'Android integration'); } final bool runUnitTests = mode.unit && hasUnitTests; final bool runIntegrationTests = mode.integration && hasIntegrationTests; if (!runUnitTests && !runIntegrationTests) { continue; } final String exampleName = example.displayName; _printRunningExampleTestsMessage(example, 'Android'); final GradleProject project = GradleProject( example, processRunner: processRunner, platform: platform, ); if (!project.isConfigured()) { final int exitCode = await processRunner.runAndStream( flutterCommand, <String>['build', 'apk', '--config-only'], workingDir: example.directory, ); if (exitCode != 0) { printError('Unable to configure Gradle project.'); failed = true; continue; } } if (runUnitTests) { print('Running unit tests...'); const String taskName = 'testDebugUnitTest'; // Target the unit tests in the app and plugin specifically, to avoid // transitively running tests in dependencies. If unit tests have // already run in an earlier example, only run any app-level unit tests. final List<String> pluginTestTask = <String>[ if (!ranUnitTests) '$pluginName:$taskName' ]; final int exitCode = await project.runCommand('app:$taskName', additionalTasks: pluginTestTask); if (exitCode != 0) { printError('$exampleName unit tests failed.'); failed = true; } ranUnitTests = true; ranAnyTests = true; } if (runIntegrationTests) { // FlutterTestRunner-based tests will hang forever if run in a normal // app build, since they wait for a Dart call from integration_test // that will never come. Those tests have an extra annotation to allow // filtering them out. final List<File> misconfiguredTestFiles = candidateIntegrationTestFiles .entries .where((MapEntry<File, _JavaTestInfo> entry) => entry.value.usesFlutterTestRunner && !entry.value.hasDartIntegrationTestAnnotation) .map((MapEntry<File, _JavaTestInfo> entry) => entry.key) .toList(); if (misconfiguredTestFiles.isEmpty) { // Ideally we would filter out @RunWith(FlutterTestRunner.class) // tests directly, but there doesn't seem to be a way to filter based // on annotation contents, so the DartIntegrationTest annotation was // created as a proxy for that. const String filter = 'notAnnotation=io.flutter.plugins.DartIntegrationTest'; print('Running integration tests...'); final int exitCode = await project.runCommand( 'app:connectedAndroidTest', arguments: <String>[ '-Pandroid.testInstrumentationRunnerArguments.$filter', ], ); if (exitCode != 0) { printError('$exampleName integration tests failed.'); failed = true; } ranAnyTests = true; } else { hasMisconfiguredIntegrationTest = true; printError('$misconfiguredJavaIntegrationTestErrorExplanation\n' '${misconfiguredTestFiles.map((File f) => ' ${f.path}').join('\n')}'); } } } if (failed) { return _PlatformResult(RunState.failed); } if (hasMisconfiguredIntegrationTest) { return _PlatformResult(RunState.failed, error: 'Misconfigured integration test.'); } if (!mode.integrationOnly && !ranUnitTests) { printError('No unit tests ran. Plugins are required to have unit tests.'); return _PlatformResult(RunState.failed, error: 'No unit tests ran (use --exclude if this is intentional).'); } if (!ranAnyTests) { return _PlatformResult(RunState.skipped); } return _PlatformResult(RunState.succeeded); } Future<_PlatformResult> _testIOS(RepositoryPackage plugin, _TestMode mode) { return _runXcodeTests(plugin, 'iOS', mode, extraFlags: _iOSDestinationFlags); } Future<_PlatformResult> _testMacOS(RepositoryPackage plugin, _TestMode mode) { return _runXcodeTests(plugin, 'macOS', mode); } /// Runs all applicable tests for [plugin], printing status and returning /// the test result. /// /// The tests targets must be added to the Xcode project of the example app, /// usually at "example/{ios,macos}/Runner.xcworkspace". Future<_PlatformResult> _runXcodeTests( RepositoryPackage plugin, String platform, _TestMode mode, { List<String> extraFlags = const <String>[], }) async { String? testTarget; const String unitTestTarget = 'RunnerTests'; if (mode.unitOnly) { testTarget = unitTestTarget; } else if (mode.integrationOnly) { testTarget = 'RunnerUITests'; } bool ranUnitTests = false; // Assume skipped until at least one test has run. RunState overallResult = RunState.skipped; for (final RepositoryPackage example in plugin.getExamples()) { final String exampleName = example.displayName; // If running a specific target, check that. Otherwise, check if there // are unit tests, since having no unit tests for a plugin is fatal // (by repo policy) even if there are integration tests. bool exampleHasUnitTests = false; final String? targetToCheck = testTarget ?? (mode.unit ? unitTestTarget : null); final Directory xcodeProject = example.directory .childDirectory(platform.toLowerCase()) .childDirectory('Runner.xcodeproj'); if (targetToCheck != null) { final bool? hasTarget = await _xcode.projectHasTarget(xcodeProject, targetToCheck); if (hasTarget == null) { printError('Unable to check targets for $exampleName.'); overallResult = RunState.failed; continue; } else if (!hasTarget) { print('No "$targetToCheck" target in $exampleName; skipping.'); continue; } else if (targetToCheck == unitTestTarget) { exampleHasUnitTests = true; } } _printRunningExampleTestsMessage(example, platform); final int exitCode = await _xcode.runXcodeBuild( example.directory, actions: <String>['test'], workspace: '${platform.toLowerCase()}/Runner.xcworkspace', scheme: 'Runner', configuration: 'Debug', extraFlags: <String>[ if (testTarget != null) '-only-testing:$testTarget', ...extraFlags, 'GCC_TREAT_WARNINGS_AS_ERRORS=YES', ], ); // The exit code from 'xcodebuild test' when there are no tests. const int xcodebuildNoTestExitCode = 66; switch (exitCode) { case xcodebuildNoTestExitCode: _printNoExampleTestsMessage(example, platform); case 0: printSuccess('Successfully ran $platform xctest for $exampleName'); // If this is the first test, assume success until something fails. if (overallResult == RunState.skipped) { overallResult = RunState.succeeded; } if (exampleHasUnitTests) { ranUnitTests = true; } default: // Any failure means a failure overall. overallResult = RunState.failed; // If unit tests ran, note that even if they failed. if (exampleHasUnitTests) { ranUnitTests = true; } break; } } if (!mode.integrationOnly && !ranUnitTests) { printError('No unit tests ran. Plugins are required to have unit tests.'); // Only return a specific summary error message about the missing unit // tests if there weren't also failures, to avoid having a misleadingly // specific message. if (overallResult != RunState.failed) { return _PlatformResult(RunState.failed, error: 'No unit tests ran (use --exclude if this is intentional).'); } } return _PlatformResult(overallResult); } Future<_PlatformResult> _testWindows( RepositoryPackage plugin, _TestMode mode) async { if (mode.integrationOnly) { return _PlatformResult(RunState.skipped); } bool isTestBinary(File file) { return file.basename.endsWith('_test.exe') || file.basename.endsWith('_tests.exe'); } return _runGoogleTestTests(plugin, 'Windows', 'Debug', isTestBinary: isTestBinary); } Future<_PlatformResult> _testLinux( RepositoryPackage plugin, _TestMode mode) async { if (mode.integrationOnly) { return _PlatformResult(RunState.skipped); } bool isTestBinary(File file) { return file.basename.endsWith('_test') || file.basename.endsWith('_tests'); } // Since Linux uses a single-config generator, building-examples only // generates the build files for release, so the tests have to be run in // release mode as well. // // TODO(stuartmorgan): Consider adding a command to `flutter` that would // generate build files without doing a build, and using that instead of // relying on running build-examples. See // https://github.com/flutter/flutter/issues/93407. return _runGoogleTestTests(plugin, 'Linux', 'Release', isTestBinary: isTestBinary); } /// Finds every file in the relevant (based on [platformName], [buildMode], /// and [arch]) subdirectory of [plugin]'s build directory for which /// [isTestBinary] is true, and runs all of them, returning the overall /// result. /// /// The binaries are assumed to be Google Test test binaries, thus returning /// zero for success and non-zero for failure. Future<_PlatformResult> _runGoogleTestTests( RepositoryPackage plugin, String platformName, String buildMode, { required bool Function(File) isTestBinary, }) async { final List<File> testBinaries = <File>[]; bool hasMissingBuild = false; bool buildFailed = false; String? arch; const String x64DirName = 'x64'; const String arm64DirName = 'arm64'; if (platform.isWindows) { arch = _abi == Abi.windowsX64 ? x64DirName : arm64DirName; } else if (platform.isLinux) { // TODO(stuartmorgan): Support arm64 if that ever becomes a supported // CI configuration for the repository. arch = 'x64'; } for (final RepositoryPackage example in plugin.getExamples()) { CMakeProject project = CMakeProject(example.directory, buildMode: buildMode, processRunner: processRunner, platform: platform, arch: arch); if (platform.isWindows) { if (arch == arm64DirName && !project.isConfigured()) { // Check for x64, to handle builds newer than 3.13, but that don't yet // have https://github.com/flutter/flutter/issues/129807. // TODO(stuartmorgan): Remove this when CI no longer supports a // version of Flutter without the issue above fixed. project = CMakeProject(example.directory, buildMode: buildMode, processRunner: processRunner, platform: platform, arch: x64DirName); } if (!project.isConfigured()) { // Check again without the arch subdirectory, since 3.13 doesn't // have it yet. // TODO(stuartmorgan): Remove this when CI no longer supports Flutter // 3.13. project = CMakeProject(example.directory, buildMode: buildMode, processRunner: processRunner, platform: platform); } } if (!project.isConfigured()) { printError('ERROR: Run "flutter build" on ${example.displayName}, ' 'or run this tool\'s "build-examples" command, for the target ' 'platform before executing tests.'); hasMissingBuild = true; continue; } // By repository convention, example projects create an aggregate target // called 'unit_tests' that builds all unit tests (usually just an alias // for a specific test target). final int exitCode = await project.runBuild('unit_tests'); if (exitCode != 0) { printError('${example.displayName} unit tests failed to build.'); buildFailed = true; } testBinaries.addAll(project.buildDirectory .listSync(recursive: true) .whereType<File>() .where(isTestBinary) .where((File file) { // Only run the `buildMode` build of the unit tests, to avoid running // the same tests multiple times. final List<String> components = path.split(file.path); return components.contains(buildMode) || components.contains(buildMode.toLowerCase()); })); } if (hasMissingBuild) { return _PlatformResult(RunState.failed, error: 'Examples must be built before testing.'); } if (buildFailed) { return _PlatformResult(RunState.failed, error: 'Failed to build $platformName unit tests.'); } if (testBinaries.isEmpty) { final String binaryExtension = platform.isWindows ? '.exe' : ''; printError( 'No test binaries found. At least one *_test(s)$binaryExtension ' 'binary should be built by the example(s)'); return _PlatformResult(RunState.failed, error: 'No $platformName unit tests found'); } bool passing = true; for (final File test in testBinaries) { print('Running ${test.basename}...'); final int exitCode = await processRunner.runAndStream(test.path, <String>[]); passing &= exitCode == 0; } return _PlatformResult(passing ? RunState.succeeded : RunState.failed); } /// Prints a standard format message indicating that [platform] tests for /// [plugin]'s [example] are about to be run. void _printRunningExampleTestsMessage( RepositoryPackage example, String platform) { print('Running $platform tests for ${example.displayName}...'); } /// Prints a standard format message indicating that no tests were found for /// [plugin]'s [example] for [platform]. void _printNoExampleTestsMessage(RepositoryPackage example, String platform) { print('No $platform tests found for ${example.displayName}'); } } // The type for a function that takes a plugin directory and runs its native // tests for a specific platform. typedef _TestFunction = Future<_PlatformResult> Function( RepositoryPackage, _TestMode); /// A collection of information related to a specific platform. class _PlatformDetails { const _PlatformDetails( this.label, this.testFunction, ); /// The name to use in output. final String label; /// The function to call to run tests. final _TestFunction testFunction; } /// Enabled state for different test types. class _TestMode { const _TestMode({required this.unit, required this.integration}); final bool unit; final bool integration; bool get integrationOnly => integration && !unit; bool get unitOnly => unit && !integration; } /// The result of running a single platform's tests. class _PlatformResult { _PlatformResult(this.state, {this.error}); /// The overall state of the platform's tests. This should be: /// - failed if any tests failed. /// - succeeded if at least one test ran, and all tests passed. /// - skipped if no tests ran. final RunState state; /// An optional error string to include in the summary for this platform. /// /// Ignored unless [state] is `failed`. final String? error; } /// The state of a .java test file. class _JavaTestInfo { const _JavaTestInfo( {required this.usesFlutterTestRunner, required this.hasDartIntegrationTestAnnotation}); /// Whether the test class uses the FlutterTestRunner. final bool usesFlutterTestRunner; /// Whether the test class has the @DartIntegrationTest annotation. final bool hasDartIntegrationTestAnnotation; }
packages/script/tool/lib/src/native_test_command.dart/0
{ "file_path": "packages/script/tool/lib/src/native_test_command.dart", "repo_id": "packages", "token_count": 10166 }
1,182
// 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/build_examples_command.dart'; import 'package:flutter_plugin_tools/src/common/core.dart'; import 'package:flutter_plugin_tools/src/common/plugin_utils.dart'; import 'package:test/test.dart'; import 'mocks.dart'; import 'util.dart'; void main() { group('build-example', () { late FileSystem fileSystem; late MockPlatform mockPlatform; late Directory packagesDir; late CommandRunner<void> runner; late RecordingProcessRunner processRunner; setUp(() { fileSystem = MemoryFileSystem(); mockPlatform = MockPlatform(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); processRunner = RecordingProcessRunner(); final BuildExamplesCommand command = BuildExamplesCommand( packagesDir, processRunner: processRunner, platform: mockPlatform, ); runner = CommandRunner<void>( 'build_examples_command', 'Test for build_example_command'); runner.addCommand(command); }); test('fails if no plaform flags are passed', () async { Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['build-examples'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('At least one platform must be provided'), ])); }); test('fails if building fails', () async { createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline), }); processRunner .mockProcessesForExecutable[getFlutterCommand(mockPlatform)] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1), <String>['build']) ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['build-examples', '--ios'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The following packages had errors:'), contains(' plugin:\n' ' plugin/example (iOS)'), ])); }); test('fails if a plugin has no examples', () async { createFakePlugin('plugin', packagesDir, examples: <String>[], platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline) }); processRunner .mockProcessesForExecutable[getFlutterCommand(mockPlatform)] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1), <String>['pub', 'get']) ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['build-examples', '--ios'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The following packages had errors:'), contains(' plugin:\n' ' No examples found'), ])); }); test('building for iOS when plugin is not set up for iOS results in no-op', () async { mockPlatform.isMacOS = true; createFakePlugin('plugin', packagesDir); final List<String> output = await runCapturingPrint(runner, <String>['build-examples', '--ios']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin'), contains('iOS is not supported by this plugin'), ]), ); // Output should be empty since running build-examples --macos with no macos // implementation is a no-op. expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('building for iOS', () async { mockPlatform.isMacOS = true; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); final List<String> output = await runCapturingPrint(runner, <String>['build-examples', '--ios', '--enable-experiment=exp1']); expect( output, containsAllInOrder(<String>[ '\nBUILDING plugin/example for iOS', ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>[ 'build', 'ios', '--no-codesign', '--enable-experiment=exp1' ], pluginExampleDirectory.path), ])); }); test( 'building for Linux when plugin is not set up for Linux results in no-op', () async { mockPlatform.isLinux = true; createFakePlugin('plugin', packagesDir); final List<String> output = await runCapturingPrint( runner, <String>['build-examples', '--linux']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin'), contains('Linux is not supported by this plugin'), ]), ); // Output should be empty since running build-examples --linux with no // Linux implementation is a no-op. expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('building for Linux', () async { mockPlatform.isLinux = true; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformLinux: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); final List<String> output = await runCapturingPrint( runner, <String>['build-examples', '--linux']); expect( output, containsAllInOrder(<String>[ '\nBUILDING plugin/example for Linux', ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall(getFlutterCommand(mockPlatform), const <String>['build', 'linux'], pluginExampleDirectory.path), ])); }); test('building for macOS with no implementation results in no-op', () async { mockPlatform.isMacOS = true; createFakePlugin('plugin', packagesDir); final List<String> output = await runCapturingPrint( runner, <String>['build-examples', '--macos']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin'), contains('macOS is not supported by this plugin'), ]), ); // Output should be empty since running build-examples --macos with no macos // implementation is a no-op. expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('building for macOS', () async { mockPlatform.isMacOS = true; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); final List<String> output = await runCapturingPrint( runner, <String>['build-examples', '--macos']); expect( output, containsAllInOrder(<String>[ '\nBUILDING plugin/example for macOS', ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall(getFlutterCommand(mockPlatform), const <String>['build', 'macos'], pluginExampleDirectory.path), ])); }); test('building for web with no implementation results in no-op', () async { createFakePlugin('plugin', packagesDir); final List<String> output = await runCapturingPrint(runner, <String>['build-examples', '--web']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin'), contains('web is not supported by this plugin'), ]), ); // Output should be empty since running build-examples --macos with no macos // implementation is a no-op. expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('building for web', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformWeb: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); final List<String> output = await runCapturingPrint(runner, <String>['build-examples', '--web']); expect( output, containsAllInOrder(<String>[ '\nBUILDING plugin/example for web', ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall(getFlutterCommand(mockPlatform), const <String>['build', 'web'], pluginExampleDirectory.path), ])); }); test( 'building for Windows when plugin is not set up for Windows results in no-op', () async { mockPlatform.isWindows = true; createFakePlugin('plugin', packagesDir); final List<String> output = await runCapturingPrint( runner, <String>['build-examples', '--windows']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin'), contains('Windows is not supported by this plugin'), ]), ); // Output should be empty since running build-examples --windows with no // Windows implementation is a no-op. expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('building for Windows', () async { mockPlatform.isWindows = true; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformWindows: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); final List<String> output = await runCapturingPrint( runner, <String>['build-examples', '--windows']); expect( output, containsAllInOrder(<String>[ '\nBUILDING plugin/example for Windows', ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['build', 'windows'], pluginExampleDirectory.path), ])); }); test( 'building for Android when plugin is not set up for Android results in no-op', () async { createFakePlugin('plugin', packagesDir); final List<String> output = await runCapturingPrint(runner, <String>['build-examples', '--apk']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin'), contains('Android is not supported by this plugin'), ]), ); // Output should be empty since running build-examples --macos with no macos // implementation is a no-op. expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('building for Android', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); final List<String> output = await runCapturingPrint(runner, <String>[ 'build-examples', '--apk', ]); expect( output, containsAllInOrder(<String>[ '\nBUILDING plugin/example for Android (apk)', ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall(getFlutterCommand(mockPlatform), const <String>['build', 'apk'], pluginExampleDirectory.path), ])); }); test('building for Android with alias', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); final List<String> output = await runCapturingPrint(runner, <String>[ 'build-examples', '--android', ]); expect( output, containsAllInOrder(<String>[ '\nBUILDING plugin/example for Android (apk)', ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall(getFlutterCommand(mockPlatform), const <String>['build', 'apk'], pluginExampleDirectory.path), ])); }); test('enable-experiment flag for Android', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); await runCapturingPrint(runner, <String>['build-examples', '--apk', '--enable-experiment=exp1']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['build', 'apk', '--enable-experiment=exp1'], pluginExampleDirectory.path), ])); }); test('enable-experiment flag for ios', () async { final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); await runCapturingPrint(runner, <String>['build-examples', '--ios', '--enable-experiment=exp1']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>[ 'build', 'ios', '--no-codesign', '--enable-experiment=exp1' ], pluginExampleDirectory.path), ])); }); test('logs skipped platforms', () async { createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline), }); final List<String> output = await runCapturingPrint( runner, <String>['build-examples', '--apk', '--ios', '--macos']); expect( output, containsAllInOrder(<Matcher>[ contains('Skipping unsupported platform(s): iOS, macOS'), ]), ); }); group('packages', () { test('builds when requested platform is supported by example', () async { final RepositoryPackage package = createFakePackage( 'package', packagesDir, isFlutter: true, extraFiles: <String>[ 'example/ios/Runner.xcodeproj/project.pbxproj' ]); final List<String> output = await runCapturingPrint( runner, <String>['build-examples', '--ios']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for package'), contains('BUILDING package/example for iOS'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>[ 'build', 'ios', '--no-codesign', ], getExampleDir(package).path), ])); }); test('skips non-Flutter examples', () async { createFakePackage('package', packagesDir); final List<String> output = await runCapturingPrint( runner, <String>['build-examples', '--ios']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for package'), contains('No examples found supporting requested platform(s).'), ]), ); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('skips when there is no example', () async { createFakePackage('package', packagesDir, isFlutter: true, examples: <String>[]); final List<String> output = await runCapturingPrint( runner, <String>['build-examples', '--ios']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for package'), contains('No examples found supporting requested platform(s).'), ]), ); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('skip when example does not support requested platform', () async { createFakePackage('package', packagesDir, isFlutter: true, extraFiles: <String>['example/linux/CMakeLists.txt']); final List<String> output = await runCapturingPrint( runner, <String>['build-examples', '--ios']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for package'), contains('Skipping iOS for package/example; not supported.'), contains('No examples found supporting requested platform(s).'), ]), ); expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[])); }); test('logs skipped platforms when only some are supported', () async { final RepositoryPackage package = createFakePackage( 'package', packagesDir, isFlutter: true, extraFiles: <String>['example/linux/CMakeLists.txt']); final List<String> output = await runCapturingPrint( runner, <String>['build-examples', '--apk', '--linux']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for package'), contains('Building for: Android, Linux'), contains('Skipping Android for package/example; not supported.'), ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['build', 'linux'], getExampleDir(package).path), ])); }); }); test('The .pluginToolsConfig.yaml file', () async { mockPlatform.isLinux = true; final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir, platformSupport: <String, PlatformDetails>{ platformLinux: const PlatformDetails(PlatformSupport.inline), platformMacOS: const PlatformDetails(PlatformSupport.inline), }); final Directory pluginExampleDirectory = getExampleDir(plugin); final File pluginExampleConfigFile = pluginExampleDirectory.childFile('.pluginToolsConfig.yaml'); pluginExampleConfigFile .writeAsStringSync('buildFlags:\n global:\n - "test argument"'); final List<String> output = <String>[ ...await runCapturingPrint( runner, <String>['build-examples', '--linux']), ...await runCapturingPrint( runner, <String>['build-examples', '--macos']), ]; expect( output, containsAllInOrder(<String>[ '\nBUILDING plugin/example for Linux', '\nBUILDING plugin/example for macOS', ]), ); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['build', 'linux', 'test argument'], pluginExampleDirectory.path), ProcessCall( getFlutterCommand(mockPlatform), const <String>['build', 'macos', 'test argument'], pluginExampleDirectory.path), ])); }); }); }
packages/script/tool/test/build_examples_command_test.dart/0
{ "file_path": "packages/script/tool/test/build_examples_command_test.dart", "repo_id": "packages", "token_count": 9097 }
1,183
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/common/core.dart'; import 'package:flutter_plugin_tools/src/common/plugin_utils.dart'; import 'package:flutter_plugin_tools/src/dart_test_command.dart'; import 'package:platform/platform.dart'; import 'package:test/test.dart'; import 'mocks.dart'; import 'util.dart'; void main() { group('TestCommand', () { late FileSystem fileSystem; late Platform mockPlatform; late Directory packagesDir; late CommandRunner<void> runner; late RecordingProcessRunner processRunner; setUp(() { fileSystem = MemoryFileSystem(); mockPlatform = MockPlatform(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); processRunner = RecordingProcessRunner(); final DartTestCommand command = DartTestCommand( packagesDir, processRunner: processRunner, platform: mockPlatform, ); runner = CommandRunner<void>('test_test', 'Test for $DartTestCommand'); runner.addCommand(command); }); test('legacy "test" name still works', () async { final RepositoryPackage plugin = createFakePlugin('a_plugin', packagesDir, extraFiles: <String>['test/a_test.dart']); await runCapturingPrint(runner, <String>['test']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall(getFlutterCommand(mockPlatform), const <String>['test', '--color'], plugin.path), ]), ); }); test('runs flutter test on each plugin', () async { final RepositoryPackage plugin1 = createFakePlugin('plugin1', packagesDir, extraFiles: <String>['test/empty_test.dart']); final RepositoryPackage plugin2 = createFakePlugin('plugin2', packagesDir, extraFiles: <String>['test/empty_test.dart']); await runCapturingPrint(runner, <String>['dart-test']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall(getFlutterCommand(mockPlatform), const <String>['test', '--color'], plugin1.path), ProcessCall(getFlutterCommand(mockPlatform), const <String>['test', '--color'], plugin2.path), ]), ); }); test('runs flutter test on Flutter package example tests', () async { final RepositoryPackage plugin = createFakePlugin('a_plugin', packagesDir, extraFiles: <String>[ 'test/empty_test.dart', 'example/test/an_example_test.dart' ]); await runCapturingPrint(runner, <String>['dart-test']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall(getFlutterCommand(mockPlatform), const <String>['test', '--color'], plugin.path), ProcessCall(getFlutterCommand(mockPlatform), const <String>['test', '--color'], getExampleDir(plugin).path), ]), ); }); test('fails when Flutter tests fail', () async { createFakePlugin('plugin1', packagesDir, extraFiles: <String>['test/empty_test.dart']); createFakePlugin('plugin2', packagesDir, extraFiles: <String>['test/empty_test.dart']); processRunner .mockProcessesForExecutable[getFlutterCommand(mockPlatform)] = <FakeProcessInfo>[ FakeProcessInfo( MockProcess(exitCode: 1), <String>['dart-test']), // plugin 1 test FakeProcessInfo(MockProcess(), <String>['dart-test']), // plugin 2 test ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['dart-test'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The following packages had errors:'), contains(' plugin1'), ])); }); test('skips testing plugins without test directory', () async { createFakePlugin('plugin1', packagesDir); final RepositoryPackage plugin2 = createFakePlugin('plugin2', packagesDir, extraFiles: <String>['test/empty_test.dart']); await runCapturingPrint(runner, <String>['dart-test']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall(getFlutterCommand(mockPlatform), const <String>['test', '--color'], plugin2.path), ]), ); }); test('runs dart run test on non-Flutter packages', () async { final RepositoryPackage plugin = createFakePlugin('a', packagesDir, extraFiles: <String>['test/empty_test.dart']); final RepositoryPackage package = createFakePackage('b', packagesDir, extraFiles: <String>['test/empty_test.dart']); await runCapturingPrint( runner, <String>['dart-test', '--enable-experiment=exp1']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['test', '--color', '--enable-experiment=exp1'], plugin.path), ProcessCall('dart', const <String>['pub', 'get'], package.path), ProcessCall( 'dart', const <String>['run', '--enable-experiment=exp1', 'test'], package.path), ]), ); }); test('runs dart run test on non-Flutter package examples', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, extraFiles: <String>[ 'test/empty_test.dart', 'example/test/an_example_test.dart' ]); await runCapturingPrint(runner, <String>['dart-test']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall('dart', const <String>['pub', 'get'], package.path), ProcessCall('dart', const <String>['run', 'test'], package.path), ProcessCall('dart', const <String>['pub', 'get'], getExampleDir(package).path), ProcessCall('dart', const <String>['run', 'test'], getExampleDir(package).path), ]), ); }); test('fails when getting non-Flutter package dependencies fails', () async { createFakePackage('a_package', packagesDir, extraFiles: <String>['test/empty_test.dart']); processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1), <String>['pub', 'get']) ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['dart-test'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Unable to fetch dependencies'), contains('The following packages had errors:'), contains(' a_package'), ])); }); test('fails when non-Flutter tests fail', () async { createFakePackage('a_package', packagesDir, extraFiles: <String>['test/empty_test.dart']); processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(), <String>['pub', 'get']), FakeProcessInfo(MockProcess(exitCode: 1), <String>['run']), // run test ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['dart-test'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('The following packages had errors:'), contains(' a_package'), ])); }); test('converts --platform=vm to no argument for flutter test', () async { final RepositoryPackage plugin = createFakePlugin( 'some_plugin', packagesDir, extraFiles: <String>['test/empty_test.dart'], ); await runCapturingPrint(runner, <String>['dart-test', '--platform=vm']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall(getFlutterCommand(mockPlatform), const <String>['test', '--color'], plugin.path), ]), ); }); test('runs in Chrome when requested for Flutter package', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, isFlutter: true, extraFiles: <String>['test/empty_test.dart'], ); await runCapturingPrint( runner, <String>['dart-test', '--platform=chrome']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['test', '--color', '--platform=chrome', '--web-renderer=html'], package.path), ]), ); }); test('runs in Chrome by default for Flutter plugins that implement web', () async { final RepositoryPackage plugin = createFakePlugin( 'some_plugin_web', packagesDir, extraFiles: <String>['test/empty_test.dart'], platformSupport: <String, PlatformDetails>{ platformWeb: const PlatformDetails(PlatformSupport.inline), }, ); await runCapturingPrint(runner, <String>['dart-test']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['test', '--color', '--platform=chrome', '--web-renderer=html'], plugin.path), ]), ); }); test('runs in Chrome when requested for Flutter plugins that implement web', () async { final RepositoryPackage plugin = createFakePlugin( 'some_plugin_web', packagesDir, extraFiles: <String>['test/empty_test.dart'], platformSupport: <String, PlatformDetails>{ platformWeb: const PlatformDetails(PlatformSupport.inline), }, ); await runCapturingPrint( runner, <String>['dart-test', '--platform=chrome']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['test', '--color', '--platform=chrome', '--web-renderer=html'], plugin.path), ]), ); }); test('runs in Chrome when requested for Flutter plugin that endorse web', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin', packagesDir, extraFiles: <String>['test/empty_test.dart'], platformSupport: <String, PlatformDetails>{ platformWeb: const PlatformDetails(PlatformSupport.federated), }, ); await runCapturingPrint( runner, <String>['dart-test', '--platform=chrome']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['test', '--color', '--platform=chrome', '--web-renderer=html'], plugin.path), ]), ); }); test('skips running non-web plugins in browser mode', () async { createFakePlugin( 'non_web_plugin', packagesDir, extraFiles: <String>['test/empty_test.dart'], ); final List<String> output = await runCapturingPrint( runner, <String>['dart-test', '--platform=chrome']); expect( output, containsAllInOrder(<Matcher>[ contains("Non-web plugin tests don't need web testing."), ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[]), ); }); test('skips running web plugins in explicit vm mode', () async { createFakePlugin( 'some_plugin_web', packagesDir, extraFiles: <String>['test/empty_test.dart'], platformSupport: <String, PlatformDetails>{ platformWeb: const PlatformDetails(PlatformSupport.inline), }, ); final List<String> output = await runCapturingPrint( runner, <String>['dart-test', '--platform=vm']); expect( output, containsAllInOrder(<Matcher>[ contains("Web plugin tests don't need vm testing."), ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[]), ); }); test('does not skip for plugins that endorse web', () async { final RepositoryPackage plugin = createFakePlugin( 'some_plugin', packagesDir, extraFiles: <String>['test/empty_test.dart'], platformSupport: <String, PlatformDetails>{ platformWeb: const PlatformDetails(PlatformSupport.federated), platformAndroid: const PlatformDetails(PlatformSupport.federated), }, ); await runCapturingPrint( runner, <String>['dart-test', '--platform=chrome']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['test', '--color', '--platform=chrome', '--web-renderer=html'], plugin.path), ]), ); }); test('runs in Chrome when requested for Dart package', () async { final RepositoryPackage package = createFakePackage( 'package', packagesDir, extraFiles: <String>['test/empty_test.dart'], ); await runCapturingPrint( runner, <String>['dart-test', '--platform=chrome']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall('dart', const <String>['pub', 'get'], package.path), ProcessCall('dart', const <String>['run', 'test', '--platform=chrome'], package.path), ]), ); }); test('skips running in browser mode if package opts out', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, extraFiles: <String>['test/empty_test.dart'], ); package.directory.childFile('dart_test.yaml').writeAsStringSync(''' test_on: vm '''); final List<String> output = await runCapturingPrint( runner, <String>['dart-test', '--platform=chrome']); expect( output, containsAllInOrder(<Matcher>[ contains('Package has opted out of non-vm testing.'), ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[]), ); }); test('skips running in vm mode if package opts out', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, extraFiles: <String>['test/empty_test.dart'], ); package.directory.childFile('dart_test.yaml').writeAsStringSync(''' test_on: browser '''); final List<String> output = await runCapturingPrint( runner, <String>['dart-test', '--platform=vm']); expect( output, containsAllInOrder(<Matcher>[ contains('Package has opted out of vm testing.'), ])); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[]), ); }); test('tries to run for a test_on that the tool does not recognize', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, extraFiles: <String>['test/empty_test.dart'], ); package.directory.childFile('dart_test.yaml').writeAsStringSync(''' test_on: !vm && firefox '''); await runCapturingPrint(runner, <String>['dart-test']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall('dart', const <String>['pub', 'get'], package.path), ProcessCall('dart', const <String>['run', 'test'], package.path), ]), ); }); test('enable-experiment flag', () async { final RepositoryPackage plugin = createFakePlugin('a', packagesDir, extraFiles: <String>['test/empty_test.dart']); final RepositoryPackage package = createFakePackage('b', packagesDir, extraFiles: <String>['test/empty_test.dart']); await runCapturingPrint( runner, <String>['dart-test', '--enable-experiment=exp1']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['test', '--color', '--enable-experiment=exp1'], plugin.path), ProcessCall('dart', const <String>['pub', 'get'], package.path), ProcessCall( 'dart', const <String>['run', '--enable-experiment=exp1', 'test'], package.path), ]), ); }); }); }
packages/script/tool/test/dart_test_command_test.dart/0
{ "file_path": "packages/script/tool/test/dart_test_command_test.dart", "repo_id": "packages", "token_count": 7482 }
1,184
// 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 '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_check_command.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; import 'package:test/test.dart'; import 'mocks.dart'; import 'util.dart'; void main() { group('PublishCheckCommand tests', () { FileSystem fileSystem; late MockPlatform mockPlatform; late Directory packagesDir; late RecordingProcessRunner processRunner; late CommandRunner<void> runner; setUp(() { fileSystem = MemoryFileSystem(); mockPlatform = MockPlatform(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); processRunner = RecordingProcessRunner(); final PublishCheckCommand publishCheckCommand = PublishCheckCommand( packagesDir, processRunner: processRunner, platform: mockPlatform, ); runner = CommandRunner<void>( 'publish_check_command', 'Test for publish-check command.', ); runner.addCommand(publishCheckCommand); }); test('publish check all packages', () async { final RepositoryPackage plugin1 = createFakePlugin( 'plugin_tools_test_package_a', packagesDir, examples: <String>[], ); final RepositoryPackage plugin2 = createFakePlugin( 'plugin_tools_test_package_b', packagesDir, examples: <String>[], ); await runCapturingPrint(runner, <String>['publish-check']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( 'flutter', const <String>['pub', 'publish', '--', '--dry-run'], plugin1.path), ProcessCall( 'flutter', const <String>['pub', 'publish', '--', '--dry-run'], plugin2.path), ])); }); test('publish prepares dependencies of examples (when present)', () async { final RepositoryPackage plugin1 = createFakePlugin( 'plugin_tools_test_package_a', packagesDir, examples: <String>['example1', 'example2'], ); final RepositoryPackage plugin2 = createFakePlugin( 'plugin_tools_test_package_b', packagesDir, examples: <String>[], ); await runCapturingPrint(runner, <String>['publish-check']); // For plugin1, these are the expected pub get calls that will happen final Iterable<ProcessCall> pubGetCalls = plugin1.getExamples().map((RepositoryPackage example) { return ProcessCall( getFlutterCommand(mockPlatform), const <String>['pub', 'get'], example.path, ); }); expect(pubGetCalls, hasLength(2)); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ // plugin1 has 2 examples, so there's some 'dart pub get' calls. ...pubGetCalls, ProcessCall( 'flutter', const <String>['pub', 'publish', '--', '--dry-run'], plugin1.path), // plugin2 has no examples, so there's no extra 'dart pub get' calls. ProcessCall( 'flutter', const <String>['pub', 'publish', '--', '--dry-run'], plugin2.path), ]), ); }); test('fail on negative test', () async { createFakePlugin('plugin_tools_test_package_a', packagesDir); processRunner.mockProcessesForExecutable['flutter'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(), <String>['pub', 'get']), FakeProcessInfo(MockProcess(exitCode: 1, stdout: 'Some error from pub'), <String>['pub', 'publish']) ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['publish-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Some error from pub'), contains('Unable to publish plugin_tools_test_package_a'), ]), ); }); test('fail on bad pubspec', () async { final RepositoryPackage package = createFakePlugin('c', packagesDir); await package.pubspecFile.writeAsString('bad-yaml'); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['publish-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('No valid pubspec found.'), ]), ); }); test('fails if AUTHORS is missing', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); package.authorsFile.deleteSync(); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['publish-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains( 'No AUTHORS file found. Packages must include an AUTHORS file.'), ]), ); }); test('does not require AUTHORS for third-party', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir.parent .childDirectory('third_party') .childDirectory('packages')); package.authorsFile.deleteSync(); final List<String> output = await runCapturingPrint(runner, <String>['publish-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Running for a_package'), ]), ); }); test('pass on prerelease if --allow-pre-release flag is on', () async { createFakePlugin('d', packagesDir); final MockProcess process = MockProcess( exitCode: 1, stdout: 'Package has 1 warning.\n' 'Packages with an SDK constraint on a pre-release of the Dart ' 'SDK should themselves be published as a pre-release version.'); processRunner.mockProcessesForExecutable['flutter'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(), <String>['pub', 'get']), FakeProcessInfo(process, <String>['pub', 'publish']), ]; expect( runCapturingPrint( runner, <String>['publish-check', '--allow-pre-release']), completes); }); test('fail on prerelease if --allow-pre-release flag is off', () async { createFakePlugin('d', packagesDir); final MockProcess process = MockProcess( exitCode: 1, stdout: 'Package has 1 warning.\n' 'Packages with an SDK constraint on a pre-release of the Dart ' 'SDK should themselves be published as a pre-release version.'); processRunner.mockProcessesForExecutable['flutter'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(), <String>['pub', 'get']), FakeProcessInfo(process, <String>['pub', 'publish']), ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['publish-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains( 'Packages with an SDK constraint on a pre-release of the Dart SDK'), contains('Unable to publish d'), ]), ); }); test('Success message on stderr is not printed as an error', () async { createFakePlugin('d', packagesDir); processRunner.mockProcessesForExecutable['flutter'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(), <String>['pub', 'get']), FakeProcessInfo(MockProcess(stdout: 'Package has 0 warnings.'), <String>['pub', 'publish']), ]; final List<String> output = await runCapturingPrint(runner, <String>['publish-check']); expect(output, isNot(contains(contains('ERROR:')))); }); test( 'runs validation even for packages that are already published and reports failure', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir, version: '0.1.0'); final MockClient mockClient = MockClient((http.Request request) async { if (request.url.pathSegments.last == 'a_package.json') { return http.Response( json.encode(<String, dynamic>{ 'name': 'a_package', 'versions': <String>[ '0.0.1', '0.1.0', ], }), 200); } return http.Response('', 500); }); runner = CommandRunner<void>( 'publish_check_command', 'Test for publish-check command.', ); runner.addCommand(PublishCheckCommand(packagesDir, platform: mockPlatform, processRunner: processRunner, httpClient: mockClient)); processRunner.mockProcessesForExecutable['flutter'] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1, stdout: 'Some error from pub'), <String>['pub', 'publish']) ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['publish-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('Unable to publish a_package'), ]), ); expect( processRunner.recordedCalls, contains( ProcessCall( 'flutter', const <String>['pub', 'publish', '--', '--dry-run'], package.path), )); }); test( 'runs validation even for packages that are already published and reports success', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir, version: '0.1.0'); final MockClient mockClient = MockClient((http.Request request) async { if (request.url.pathSegments.last == 'a_package.json') { return http.Response( json.encode(<String, dynamic>{ 'name': 'a_package', 'versions': <String>[ '0.0.1', '0.1.0', ], }), 200); } return http.Response('', 500); }); runner = CommandRunner<void>( 'publish_check_command', 'Test for publish-check command.', ); runner.addCommand(PublishCheckCommand(packagesDir, platform: mockPlatform, processRunner: processRunner, httpClient: mockClient)); final List<String> output = await runCapturingPrint(runner, <String>['publish-check']); expect( output, containsAllInOrder(<Matcher>[ contains( 'Package a_package version: 0.1.0 has already been published on pub.'), ]), ); expect( processRunner.recordedCalls, contains( ProcessCall( 'flutter', const <String>['pub', 'publish', '--', '--dry-run'], package.path), )); }); test( '--machine: Log JSON with status:no-publish and correct human message, if there are no packages need to be published. ', () async { const Map<String, dynamic> httpResponseA = <String, dynamic>{ 'name': 'a', 'versions': <String>[ '0.0.1', '0.1.0', ], }; const Map<String, dynamic> httpResponseB = <String, dynamic>{ 'name': 'b', 'versions': <String>[ '0.0.1', '0.1.0', '0.2.0', ], }; final MockClient mockClient = MockClient((http.Request request) async { if (request.url.pathSegments.last == 'no_publish_a.json') { return http.Response(json.encode(httpResponseA), 200); } else if (request.url.pathSegments.last == 'no_publish_b.json') { return http.Response(json.encode(httpResponseB), 200); } return http.Response('', 500); }); final PublishCheckCommand command = PublishCheckCommand(packagesDir, processRunner: processRunner, httpClient: mockClient); runner = CommandRunner<void>( 'publish_check_command', 'Test for publish-check command.', ); runner.addCommand(command); createFakePlugin('no_publish_a', packagesDir, version: '0.1.0'); createFakePlugin('no_publish_b', packagesDir, version: '0.2.0'); final List<String> output = await runCapturingPrint( runner, <String>['publish-check', '--machine']); expect(output.first, r''' { "status": "no-publish", "humanMessage": [ "\n============================================================\n|| Running for no_publish_a\n============================================================\n", "Running pub publish --dry-run:", "Package no_publish_a version: 0.1.0 has already been published on pub.", "\n============================================================\n|| Running for no_publish_b\n============================================================\n", "Running pub publish --dry-run:", "Package no_publish_b version: 0.2.0 has already been published on pub.", "\n", "------------------------------------------------------------", "Run overview:", " no_publish_a - ran", " no_publish_b - ran", "", "Ran for 2 package(s)", "\n", "No issues found!" ] }'''); }); test( '--machine: Log JSON with status:needs-publish and correct human message, if there is at least 1 plugin needs to be published.', () async { const Map<String, dynamic> httpResponseA = <String, dynamic>{ 'name': 'a', 'versions': <String>[ '0.0.1', '0.1.0', ], }; const Map<String, dynamic> httpResponseB = <String, dynamic>{ 'name': 'b', 'versions': <String>[ '0.0.1', '0.1.0', ], }; final MockClient mockClient = MockClient((http.Request request) async { if (request.url.pathSegments.last == 'no_publish_a.json') { return http.Response(json.encode(httpResponseA), 200); } else if (request.url.pathSegments.last == 'no_publish_b.json') { return http.Response(json.encode(httpResponseB), 200); } return http.Response('', 500); }); final PublishCheckCommand command = PublishCheckCommand(packagesDir, processRunner: processRunner, httpClient: mockClient); runner = CommandRunner<void>( 'publish_check_command', 'Test for publish-check command.', ); runner.addCommand(command); createFakePlugin('no_publish_a', packagesDir, version: '0.1.0'); createFakePlugin('no_publish_b', packagesDir, version: '0.2.0'); final List<String> output = await runCapturingPrint( runner, <String>['publish-check', '--machine']); expect(output.first, r''' { "status": "needs-publish", "humanMessage": [ "\n============================================================\n|| Running for no_publish_a\n============================================================\n", "Running pub publish --dry-run:", "Package no_publish_a version: 0.1.0 has already been published on pub.", "\n============================================================\n|| Running for no_publish_b\n============================================================\n", "Running pub publish --dry-run:", "Package no_publish_b is able to be published.", "\n", "------------------------------------------------------------", "Run overview:", " no_publish_a - ran", " no_publish_b - ran", "", "Ran for 2 package(s)", "\n", "No issues found!" ] }'''); }); test( '--machine: Log correct JSON, if there is at least 1 plugin contains error.', () async { const Map<String, dynamic> httpResponseA = <String, dynamic>{ 'name': 'a', 'versions': <String>[ '0.0.1', '0.1.0', ], }; const Map<String, dynamic> httpResponseB = <String, dynamic>{ 'name': 'b', 'versions': <String>[ '0.0.1', '0.1.0', ], }; final MockClient mockClient = MockClient((http.Request request) async { print('url ${request.url}'); print(request.url.pathSegments.last); if (request.url.pathSegments.last == 'no_publish_a.json') { return http.Response(json.encode(httpResponseA), 200); } else if (request.url.pathSegments.last == 'no_publish_b.json') { return http.Response(json.encode(httpResponseB), 200); } return http.Response('', 500); }); final PublishCheckCommand command = PublishCheckCommand(packagesDir, processRunner: processRunner, httpClient: mockClient); runner = CommandRunner<void>( 'publish_check_command', 'Test for publish-check command.', ); runner.addCommand(command); final RepositoryPackage plugin = createFakePlugin('no_publish_a', packagesDir, version: '0.1.0'); createFakePlugin('no_publish_b', packagesDir, version: '0.2.0'); await plugin.pubspecFile.writeAsString('bad-yaml'); bool hasError = false; final List<String> output = await runCapturingPrint( runner, <String>['publish-check', '--machine'], errorHandler: (Error error) { expect(error, isA<ToolExit>()); hasError = true; }); expect(hasError, isTrue); expect(output.first, contains(r''' { "status": "error", "humanMessage": [ "\n============================================================\n|| Running for no_publish_a\n============================================================\n", "Failed to parse `pubspec.yaml` at /packages/no_publish_a/pubspec.yaml: ParsedYamlException:''')); // This is split into two checks since the details of the YamlException // aren't controlled by this package, so asserting its exact format would // make the test fragile to irrelevant changes in those details. expect(output.first, contains(r''' "No valid pubspec found.", "\n============================================================\n|| Running for no_publish_b\n============================================================\n", "url https://pub.dev/packages/no_publish_b.json", "no_publish_b.json", "Running pub publish --dry-run:", "Package no_publish_b is able to be published.", "\n", "The following packages had errors:", " no_publish_a", "See above for full details." ] }''')); }); }); }
packages/script/tool/test/publish_check_command_test.dart/0
{ "file_path": "packages/script/tool/test/publish_check_command_test.dart", "repo_id": "packages", "token_count": 8178 }
1,185
# Cupertino Icons This is an asset repo containing the default set of icon assets used by Flutter's [Cupertino widgets](https://github.com/flutter/flutter/tree/master/packages/flutter/lib/src/cupertino). # Usage https://pub.dev/packages/cupertino_icons [![pub package](https://img.shields.io/pub/v/cupertino_icons.svg)](https://pub.dev/packages/cupertino_icons) ```yaml dependencies: cupertino_icons: ^<latest-version> ``` # Issues For issues, file directly in the [main Flutter repo](https://github.com/flutter/flutter). # Icons [![icon gallery preview](gallery_preview_1.0.0.png)](https://api.flutter.dev/flutter/cupertino/CupertinoIcons-class.html) For a list of all icons, see [`CupertinoIcons` class documentation constants](https://api.flutter.dev/flutter/cupertino/CupertinoIcons-class.html#constants). For versions 0.1.3 and below, see this [glyph map](https://raw.githubusercontent.com/flutter/packages/main/third_party/packages/cupertino_icons/map.png).
packages/third_party/packages/cupertino_icons/README.md/0
{ "file_path": "packages/third_party/packages/cupertino_icons/README.md", "repo_id": "packages", "token_count": 341 }
1,186
export default ` <script> (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-ND4LWWZ'); </script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-67589403-1', 'auto'); ga('send', 'pageview'); </script> `;
photobooth/functions/src/share/templates/ga.ts/0
{ "file_path": "photobooth/functions/src/share/templates/ga.ts", "repo_id": "photobooth", "token_count": 372 }
1,187
export 'footer.dart'; export 'footer_link.dart'; export 'icon_link.dart';
photobooth/lib/footer/widgets/widgets.dart/0
{ "file_path": "photobooth/lib/footer/widgets/widgets.dart", "repo_id": "photobooth", "token_count": 30 }
1,188
import 'package:flutter/material.dart'; import 'package:io_photobooth/footer/footer.dart'; import 'package:io_photobooth/landing/landing.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class LandingPage extends StatelessWidget { const LandingPage({super.key}); @override Widget build(BuildContext context) { return const Scaffold( backgroundColor: PhotoboothColors.white, body: LandingView(), ); } } class LandingView extends StatelessWidget { const LandingView({super.key}); @override Widget build(BuildContext context) { return const AppPageView( background: LandingBackground(), body: LandingBody(), footer: BlackFooter(), ); } }
photobooth/lib/landing/view/landing_page.dart/0
{ "file_path": "photobooth/lib/landing/view/landing_page.dart", "repo_id": "photobooth", "token_count": 248 }
1,189
import 'package:flutter/material.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; const _characterIconButtonSizeLandscape = 90.0; const _characterIconButtonSizePortait = 60.0; class CharacterIconButton extends StatelessWidget { const CharacterIconButton({ required this.icon, required this.isSelected, required this.label, this.onPressed, super.key, }); final AssetImage icon; final VoidCallback? onPressed; final bool isSelected; final String label; @override Widget build(BuildContext context) { final orientation = MediaQuery.of(context).orientation; return Semantics( focusable: true, button: true, label: label, onTap: onPressed, child: Opacity( opacity: isSelected ? 0.6 : 1, child: Padding( padding: const EdgeInsets.all(12), child: Material( color: PhotoboothColors.transparent, shape: const CircleBorder(), clipBehavior: Clip.hardEdge, child: Ink.image( fit: BoxFit.cover, image: icon, width: orientation == Orientation.landscape ? _characterIconButtonSizeLandscape : _characterIconButtonSizePortait, height: orientation == Orientation.landscape ? _characterIconButtonSizeLandscape : _characterIconButtonSizePortait, child: InkWell(onTap: onPressed), ), ), ), ), ); } }
photobooth/lib/photobooth/widgets/character_icon_button.dart/0
{ "file_path": "photobooth/lib/photobooth/widgets/character_icon_button.dart", "repo_id": "photobooth", "token_count": 672 }
1,190
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 ShareErrorBottomSheet extends StatelessWidget { const ShareErrorBottomSheet({super.key}); @override Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = context.l10n; return Stack( children: [ SingleChildScrollView( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 24, vertical: 32, ), child: Column( mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 32), Padding( padding: const EdgeInsets.symmetric(horizontal: 58), child: Image.asset( 'assets/images/error_photo_mobile.png', ), ), const SizedBox(height: 60), Text( l10n.shareErrorDialogHeading, key: const Key('shareErrorBottomSheet_heading'), style: theme.textTheme.displayLarge?.copyWith(fontSize: 32), textAlign: TextAlign.center, ), const SizedBox(height: 24), Text( l10n.shareErrorDialogSubheading, key: const Key('shareErrorBottomSheet_subheading'), style: theme.textTheme.displaySmall?.copyWith(fontSize: 18), textAlign: TextAlign.center, ), const SizedBox(height: 42), const ShareTryAgainButton(), const SizedBox(height: 16), ], ), ), ), Positioned( right: 24, top: 24, child: IconButton( icon: const Icon( Icons.clear, color: PhotoboothColors.black54, ), onPressed: () => Navigator.of(context).pop(), ), ), ], ); } }
photobooth/lib/share/view/share_error_bottom_sheet.dart/0
{ "file_path": "photobooth/lib/share/view/share_error_bottom_sheet.dart", "repo_id": "photobooth", "token_count": 1171 }
1,191
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import 'package:platform_helper/platform_helper.dart'; class ShareStateListener extends StatelessWidget { ShareStateListener({ required this.child, super.key, PlatformHelper? platformHelper, }) : platformHelper = platformHelper ?? PlatformHelper(); final Widget child; /// Optional [PlatformHelper] instance. final PlatformHelper platformHelper; @override Widget build(BuildContext context) { return BlocListener<ShareBloc, ShareState>( listener: _onShareStateChange, child: child, ); } void _onShareStateChange(BuildContext context, ShareState state) { if (state.uploadStatus.isFailure) { _onShareError(context, state); } else if (state.uploadStatus.isSuccess) { _onShareSuccess(context, state); } } void _onShareError(BuildContext context, ShareState state) { showAppModal<void>( platformHelper: platformHelper, context: context, portraitChild: const ShareErrorBottomSheet(), landscapeChild: const ShareErrorDialog(), ); } void _onShareSuccess(BuildContext context, ShareState state) { openLink( state.shareUrl == ShareUrl.twitter ? state.twitterShareUrl : state.facebookShareUrl, ); } }
photobooth/lib/share/widgets/share_state_listener.dart/0
{ "file_path": "photobooth/lib/share/widgets/share_state_listener.dart", "repo_id": "photobooth", "token_count": 493 }
1,192
import 'package:flutter/material.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:io_photobooth/stickers/stickers.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class MobileStickersDrawer extends StatelessWidget { const MobileStickersDrawer({ required this.initialIndex, required this.onStickerSelected, required this.onTabChanged, required this.bucket, super.key, }); final int initialIndex; final ValueSetter<Asset> onStickerSelected; final ValueSetter<int> onTabChanged; final PageStorageBucket bucket; @override Widget build(BuildContext context) { final l10n = context.l10n; final screenHeight = MediaQuery.of(context).size.height; return PageStorage( bucket: bucket, child: Container( margin: const EdgeInsets.only(top: 30), height: screenHeight < PhotoboothBreakpoints.small ? screenHeight : screenHeight * 0.75, decoration: const BoxDecoration( color: PhotoboothColors.white, borderRadius: BorderRadius.vertical(top: Radius.circular(12)), ), child: Stack( children: [ Column( children: [ const SizedBox(height: 32), Align( alignment: Alignment.topLeft, child: Padding( padding: const EdgeInsets.only(left: 24), child: Text( l10n.stickersDrawerTitle, style: Theme.of(context) .textTheme .displaySmall ?.copyWith(fontSize: 24), ), ), ), const SizedBox(height: 35), Flexible( child: StickersTabs( initialIndex: initialIndex, onTabChanged: onTabChanged, onStickerSelected: onStickerSelected, ), ), ], ), Positioned( right: 24, top: 24, child: IconButton( key: const Key('stickersDrawer_close_iconButton'), icon: const Icon( Icons.clear, color: PhotoboothColors.black54, ), onPressed: () => Navigator.of(context).pop(), ), ), ], ), ), ); } }
photobooth/lib/stickers/widgets/stickers_drawer_layer/mobile_stickers_drawer.dart/0
{ "file_path": "photobooth/lib/stickers/widgets/stickers_drawer_layer/mobile_stickers_drawer.dart", "repo_id": "photobooth", "token_count": 1349 }
1,193
import 'package:firebase_auth/firebase_auth.dart' as firebase_auth; /// Thrown when signing in anonymously process fails. class SignInAnonymouslyException implements Exception {} /// {@template authentication_repository} /// Repository which manages user authentication using Firebase Authentication. /// {@endtemplate} class AuthenticationRepository { /// {@macro authentication_repository} const AuthenticationRepository({ required firebase_auth.FirebaseAuth firebaseAuth, }) : _firebaseAuth = firebaseAuth; final firebase_auth.FirebaseAuth _firebaseAuth; /// Logs in into the app as an anonymous user. /// /// Throws [SignInAnonymouslyException] when operation fails. Future<void> signInAnonymously() async { try { await _firebaseAuth.signInAnonymously(); } catch (_) { throw SignInAnonymouslyException(); } } }
photobooth/packages/authentication_repository/lib/src/authentication_repository.dart/0
{ "file_path": "photobooth/packages/authentication_repository/lib/src/authentication_repository.dart", "repo_id": "photobooth", "token_count": 256 }
1,194
part of '../camera.dart'; typedef PlaceholderBuilder = Widget Function(BuildContext); typedef PreviewBuilder = Widget Function(BuildContext, Widget); typedef ErrorBuilder = Widget Function(BuildContext, CameraException); class Camera extends StatefulWidget { Camera({ required this.controller, PlaceholderBuilder? placeholder, PreviewBuilder? preview, ErrorBuilder? error, super.key, }) : placeholder = (placeholder ?? (_) => const SizedBox()), preview = (preview ?? (_, preview) => preview), error = (error ?? (_, __) => const SizedBox()); final CameraController controller; final PlaceholderBuilder placeholder; final PreviewBuilder preview; final ErrorBuilder error; @override State<Camera> createState() => _CameraState(); } class _CameraState extends State<Camera> { Widget? _preview; Widget get preview { return _preview ??= CameraPlatform.instance.buildView(widget.controller.textureId); } @override Widget build(BuildContext context) { return ValueListenableBuilder( valueListenable: widget.controller, builder: (BuildContext context, CameraState state, _) { switch (state.status) { case CameraStatus.uninitialized: return widget.placeholder(context); case CameraStatus.available: return widget.preview(context, preview); case CameraStatus.unavailable: return widget.error(context, state.error!); } }, ); } }
photobooth/packages/camera/camera/lib/src/camera.dart/0
{ "file_path": "photobooth/packages/camera/camera/lib/src/camera.dart", "repo_id": "photobooth", "token_count": 513 }
1,195
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:html' as html; import 'package:meta/meta.dart'; /// The HTML engine used by the current browser. enum BrowserEngine { /// The engine that powers Chrome, Samsung Internet Browser, UC Browser, /// Microsoft Edge, Opera, and others. blink, /// The engine that powers Safari. webkit, /// The engine that powers Firefox. firefox, /// The engine that powers Edge. edge, /// The engine that powers Internet Explorer 11. ie11, /// The engine that powers Samsung stock browser. It is based on blink. samsung, /// We were unable to detect the current browser engine. unknown, } /// html webgl version qualifier constants. abstract class WebGLVersion { // WebGL 1.0 is based on OpenGL ES 2.0 / GLSL 1.00 static const int webgl1 = 1; // WebGL 2.0 is based on OpenGL ES 3.0 / GLSL 3.00 static const int webgl2 = 2; } /// Lazily initialized current browser engine. // ignore: unnecessary_late late final BrowserEngine _browserEngine = _detectBrowserEngine(); /// Override the value of [browserEngine]. /// /// Setting this to `null` lets [browserEngine] detect the browser that the /// app is running on. /// /// This is intended to be used for testing and debugging only. BrowserEngine? debugBrowserEngineOverride; /// Returns the [BrowserEngine] used by the current browser. /// /// This is used to implement browser-specific behavior. BrowserEngine get browserEngine { return debugBrowserEngineOverride ?? _browserEngine; } BrowserEngine _detectBrowserEngine() { final vendor = html.window.navigator.vendor; final agent = html.window.navigator.userAgent.toLowerCase(); return detectBrowserEngineByVendorAgent(vendor, agent); } /// Detects samsung blink variants. /// /// Example patterns: /// Note 2 : GT-N7100 /// Note 3 : SM-N900T /// Tab 4 : SM-T330NU /// Galaxy S4: SHV-E330S /// Galaxy Note2: SHV-E250L /// Note: SAMSUNG-SGH-I717 /// SPH/SCH are very old Palm models. bool _isSamsungBrowser(String agent) { final exp = RegExp( 'SAMSUNG|SGH-[I|N|T]|GT-[I|N]|SM-[A|N|P|T|Z]|SHV-E|SCH-[I|J|R|S]|SPH-L', ); return exp.hasMatch(agent.toUpperCase()); } @visibleForTesting BrowserEngine detectBrowserEngineByVendorAgent(String vendor, String agent) { if (vendor == 'Google Inc.') { // Samsung browser is based on blink, check for variant. if (_isSamsungBrowser(agent)) { return BrowserEngine.samsung; } return BrowserEngine.blink; } else if (vendor == 'Apple Computer, Inc.') { return BrowserEngine.webkit; } else if (agent.contains('edge/')) { return BrowserEngine.edge; } else if (agent.contains('Edg/')) { // Chromium based Microsoft Edge has `Edg` in the user-agent. // https://docs.microsoft.com/en-us/microsoft-edge/web-platform/user-agent-string return BrowserEngine.blink; } else if (agent.contains('trident/7.0')) { return BrowserEngine.ie11; } else if (vendor == '' && agent.contains('firefox')) { // An empty string means firefox: // https://developer.mozilla.org/en-US/docs/Web/API/Navigator/vendor return BrowserEngine.firefox; } // Assume unknown otherwise, but issue a warning. // ignore: avoid_print print('WARNING: failed to detect current browser engine.'); return BrowserEngine.unknown; } /// Operating system where the current browser runs. /// /// Taken from the navigator platform. /// <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID/platform> enum OperatingSystem { /// iOS: <http://www.apple.com/ios/> iOs, /// Android: <https://www.android.com/> android, /// Linux: <https://www.linux.org/> linux, /// Windows: <https://www.microsoft.com/windows/> windows, /// MacOs: <https://www.apple.com/macos/> macOs, /// We were unable to detect the current operating system. unknown, } /// Lazily initialized current operating system. // ignore: unnecessary_late late final _operatingSystem = _detectOperatingSystem(); /// Returns the [OperatingSystem] the current browsers works on. /// /// This is used to implement operating system specific behavior such as /// soft keyboards. OperatingSystem get operatingSystem { return debugOperatingSystemOverride ?? _operatingSystem; } /// Override the value of [operatingSystem]. /// /// Setting this to `null` lets [operatingSystem] detect the real OS that the /// app is running on. /// /// This is intended to be used for testing and debugging only. OperatingSystem? debugOperatingSystemOverride; OperatingSystem _detectOperatingSystem() { final platform = html.window.navigator.platform!; final userAgent = html.window.navigator.userAgent; if (platform.startsWith('Mac')) { return OperatingSystem.macOs; } else if (platform.toLowerCase().contains('iphone') || platform.toLowerCase().contains('ipad') || platform.toLowerCase().contains('ipod')) { return OperatingSystem.iOs; } else if (userAgent.contains('Android')) { // The Android OS reports itself as "Linux armv8l" in // [html.window.navigator.platform]. So we have to check the user-agent to // determine if the OS is Android or not. return OperatingSystem.android; } else if (platform.startsWith('Linux')) { return OperatingSystem.linux; } else if (platform.startsWith('Win')) { return OperatingSystem.windows; } else { return OperatingSystem.unknown; } } /// List of Operating Systems we know to be working on laptops/desktops. /// /// These devices tend to behave differently on many core issues such as events, /// screen readers, input devices. const Set<OperatingSystem> _desktopOperatingSystems = { OperatingSystem.macOs, OperatingSystem.linux, OperatingSystem.windows, }; /// A flag to check if the current operating system is a laptop/desktop /// operating system. /// /// See [_desktopOperatingSystems]. bool get isDesktop => _desktopOperatingSystems.contains(operatingSystem); int? _cachedWebGLVersion; /// The highest WebGL version supported by the current browser, or -1 if WebGL /// is not supported. int get webGLVersion => _cachedWebGLVersion ?? (_cachedWebGLVersion = _detectWebGLVersion()); /// Detects the highest WebGL version supported by the current browser, or /// -1 if WebGL is not supported. int _detectWebGLVersion() { final canvas = html.CanvasElement( width: 1, height: 1, ); if (canvas.getContext('webgl2') != null) { return WebGLVersion.webgl2; } if (canvas.getContext('webgl') != null) { return WebGLVersion.webgl1; } return -1; }
photobooth/packages/camera/camera_web/lib/src/browser_detection.dart/0
{ "file_path": "photobooth/packages/camera/camera_web/lib/src/browser_detection.dart", "repo_id": "photobooth", "token_count": 2094 }
1,196
# photobooth_ui UI Toolkit for the Photobooth Flutter Application
photobooth/packages/photobooth_ui/README.md/0
{ "file_path": "photobooth/packages/photobooth_ui/README.md", "repo_id": "photobooth", "token_count": 20 }
1,197
import 'package:flutter/widgets.dart'; /// {@template asset} /// A Dart object which holds metadata for a given asset. /// {@endtemplate} class Asset { /// {@macro asset} const Asset({ required this.name, required this.path, required this.size, }); /// The name of the image. final String name; /// The path to the asset. final String path; /// The size of the asset. final Size size; }
photobooth/packages/photobooth_ui/lib/src/models/asset.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/src/models/asset.dart", "repo_id": "photobooth", "token_count": 137 }
1,198
import 'package:flutter/material.dart'; /// {@template app_page_view} /// A widget that constructs a page view consisting of a [background] /// [body], [footer] pinned to the bottom of the page and an optional /// list of overlay widgets displayed on top of the [body]. /// {@endtemplate} class AppPageView extends StatelessWidget { /// {@macro app_page_view} const AppPageView({ required this.body, required this.footer, this.background = const SizedBox(), this.overlays = const <Widget>[], super.key, }); /// A body of the [AppPageView] final Widget body; /// Sticky footer displayed at the bottom of the [AppPageView] final Widget footer; /// An optional background of the [AppPageView] final Widget background; /// An optional list of overlays displayed on top of the [body] final List<Widget> overlays; @override Widget build(BuildContext context) { return Stack( fit: StackFit.expand, children: [ background, CustomScrollView( slivers: [ SliverToBoxAdapter(child: body), SliverFillRemaining( hasScrollBody: false, child: Container( alignment: Alignment.bottomCenter, height: 200, child: footer, ), ), ], ), ...overlays, ], ); } }
photobooth/packages/photobooth_ui/lib/src/widgets/app_page_view.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/src/widgets/app_page_view.dart", "repo_id": "photobooth", "token_count": 563 }
1,199
// ignore_for_file: prefer_const_constructors import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; void main() { group('Asset', () { test('does not support value equality', () { const name = 'image'; const path = 'path/to/image.png'; const size = Size(10, 10); final assetA = Asset(name: name, path: path, size: size); final assetB = Asset(name: name, path: path, size: size); expect(assetA, isNot(equals(assetB))); }); }); }
photobooth/packages/photobooth_ui/test/src/models/asset_test.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/test/src/models/asset_test.dart", "repo_id": "photobooth", "token_count": 220 }
1,200
// ignore_for_file: prefer_const_constructors import 'dart:convert'; 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() { final data = 'data:image/png,${base64.encode(transparentImage)}'; group('PreviewImage', () { testWidgets('renders with height and width', (tester) async { await tester.pumpWidget( PreviewImage( data: data, height: 100, width: 100, ), ); expect(find.byType(Image), findsOneWidget); }); testWidgets('anti-aliasing is enabled', (tester) async { await tester.pumpWidget( PreviewImage( data: data, height: 100, width: 100, ), ); final image = tester.widget<Image>(find.byType(Image)); expect(image.isAntiAlias, isTrue); }); testWidgets('renders without width as parameter', (tester) async { await tester.pumpWidget(PreviewImage(data: data, height: 100)); expect(find.byType(Image), findsOneWidget); }); testWidgets('renders without height as parameter', (tester) async { await tester.pumpWidget(PreviewImage(data: data, width: 100)); expect(find.byType(Image), findsOneWidget); }); testWidgets('renders without height/width as parameter', (tester) async { await tester.pumpWidget(PreviewImage(data: data)); expect(find.byType(Image), findsOneWidget); }); testWidgets('renders error with empty image', (tester) async { await tester.pumpWidget(PreviewImage(data: '')); await tester.pumpAndSettle(); final exception = tester.takeException(); expect(exception, isNotNull); expect(find.byKey(const Key('previewImage_errorText')), findsOneWidget); }); }); }
photobooth/packages/photobooth_ui/test/src/widgets/preview_image_test.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/test/src/widgets/preview_image_test.dart", "repo_id": "photobooth", "token_count": 747 }
1,201
import 'dart:html' as html; import 'package:flutter/foundation.dart'; /// Web Implementation of [PlatformHelper] class PlatformHelper { /// Window can be overridden for testing purposes only. @visibleForTesting html.Window? window; html.Window get _window => window ?? html.window; /// Returns whether the current platform is running on a mobile device. bool get isMobile { final userAgent = _window.navigator.userAgent.toLowerCase(); if (userAgent.contains('iphone') || userAgent.contains('android') || userAgent.contains('ipad')) return true; return false; } }
photobooth/packages/platform_helper/lib/src/web.dart/0
{ "file_path": "photobooth/packages/platform_helper/lib/src/web.dart", "repo_id": "photobooth", "token_count": 191 }
1,202
// ignore_for_file: prefer_const_constructors import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/footer/footer.dart'; import 'package:io_photobooth/landing/landing.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import '../../helpers/helpers.dart'; void main() { group('LandingPage', () { testWidgets('renders landing view', (tester) async { await tester.pumpApp(const LandingPage()); expect(find.byType(LandingView), findsOneWidget); }); }); group('LandingView', () { testWidgets('renders background', (tester) async { await tester.pumpApp(const LandingView()); expect(find.byKey(Key('landingPage_background')), findsOneWidget); }); testWidgets('renders heading', (tester) async { await tester.pumpApp(const LandingView()); expect(find.byKey(Key('landingPage_heading_text')), findsOneWidget); }); testWidgets('renders image', (tester) async { await tester.pumpApp(const LandingView()); expect(find.byType(Image), findsOneWidget); }); testWidgets('renders image on small screens', (tester) async { tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 1000)); await tester.pumpApp(const LandingView()); expect(find.byType(Image), findsOneWidget); }); testWidgets('renders subheading', (tester) async { await tester.pumpApp(const LandingView()); expect(find.byKey(Key('landingPage_subheading_text')), findsOneWidget); }); testWidgets('renders take photo button', (tester) async { await tester.pumpApp(const LandingView()); expect(find.byType(LandingTakePhotoButton), findsOneWidget); }); testWidgets('renders black footer', (tester) async { await tester.pumpApp(const LandingView()); await tester.ensureVisible(find.byType(BlackFooter, skipOffstage: false)); await tester.pumpAndSettle(); expect(find.byType(BlackFooter), findsOneWidget); }); testWidgets('tapping on take photo button navigates to PhotoboothPage', (tester) async { await runZonedGuarded( () async { await tester.pumpApp(const LandingView()); await tester.ensureVisible( find.byType( LandingTakePhotoButton, skipOffstage: false, ), ); await tester.pumpAndSettle(); await tester.tap( find.byType( LandingTakePhotoButton, skipOffstage: false, ), ); await tester.pumpAndSettle(); }, (_, __) {}, ); expect(find.byType(PhotoboothPage), findsOneWidget); expect(find.byType(LandingView), findsNothing); }); }); }
photobooth/test/landing/view/landing_page_test.dart/0
{ "file_path": "photobooth/test/landing/view/landing_page_test.dart", "repo_id": "photobooth", "token_count": 1184 }
1,203
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/share/share.dart'; import '../../helpers/helpers.dart'; void main() { group('ShareErrorDialog', () { testWidgets('displays heading', (tester) async { await tester.pumpApp(Scaffold(body: ShareErrorDialog())); expect(find.byKey(Key('shareErrorDialog_heading')), findsOneWidget); }); testWidgets('displays subheading', (tester) async { await tester.pumpApp(Scaffold(body: ShareErrorDialog())); expect(find.byKey(Key('shareErrorDialog_subheading')), findsOneWidget); }); testWidgets('displays a ShareTryAgainButton button', (tester) async { await tester.pumpApp(Scaffold(body: ShareErrorDialog())); expect(find.byType(ShareTryAgainButton), findsOneWidget); }); testWidgets('pops when tapped on ShareTryAgainButton button', (tester) async { await tester.pumpApp(Scaffold(body: ShareErrorDialog())); await tester.ensureVisible(find.byType(ShareTryAgainButton)); await tester.tap(find.byType(ShareTryAgainButton)); await tester.pumpAndSettle(); expect(find.byType(ShareErrorDialog), findsNothing); }); testWidgets('pops when tapped on close button', (tester) async { await tester.pumpApp(Scaffold(body: ShareErrorDialog())); await tester.tap(find.byIcon(Icons.clear)); await tester.pumpAndSettle(); expect(find.byType(ShareErrorDialog), findsNothing); }); }); }
photobooth/test/share/view/share_error_dialog_test.dart/0
{ "file_path": "photobooth/test/share/view/share_error_dialog_test.dart", "repo_id": "photobooth", "token_count": 586 }
1,204
#!/bin/bash # This script can be used to run flutter test for a given directory (defaults to the current directory) # It will exclude generated code and translations (mimicking the ci) and open the coverage report in a # new window once it has run successfully. # # To run in main project: # ./tool/coverage.sh # # To run in other directory: # ./tool/coverage.sh ./path/to/other/project set -e PROJECT_PATH="${1:-.}" PROJECT_COVERAGE=./coverage/lcov.info cd ${PROJECT_PATH} rm -rf coverage if grep -q "flutter:" pubspec.yaml; then flutter test --no-pub --test-randomize-ordering-seed random --coverage else dart test --coverage=coverage && pub run coverage:format_coverage --lcov --in=coverage --out=coverage/lcov.info --packages=.packages --report-on=lib fi lcov --remove ${PROJECT_COVERAGE} -o ${PROJECT_COVERAGE} \ '**/*.g.dart' \ '**/l10n/*.dart' \ '**/l10n/**/*.dart' \ '**/main/bootstrap.dart' \ '**/*.gen.dart' genhtml ${PROJECT_COVERAGE} -o coverage open ./coverage/index.html
photobooth/tool/coverage.sh/0
{ "file_path": "photobooth/tool/coverage.sh", "repo_id": "photobooth", "token_count": 376 }
1,205
import 'package:authentication_repository/authentication_repository.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball/select_character/select_character.dart'; import 'package:pinball/start_game/start_game.dart'; import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_ui/pinball_ui.dart'; import 'package:platform_helper/platform_helper.dart'; import 'package:share_repository/share_repository.dart'; class App extends StatelessWidget { const App({ Key? key, required AuthenticationRepository authenticationRepository, required LeaderboardRepository leaderboardRepository, required ShareRepository shareRepository, required PinballAudioPlayer pinballAudioPlayer, required PlatformHelper platformHelper, }) : _authenticationRepository = authenticationRepository, _leaderboardRepository = leaderboardRepository, _shareRepository = shareRepository, _pinballAudioPlayer = pinballAudioPlayer, _platformHelper = platformHelper, super(key: key); final AuthenticationRepository _authenticationRepository; final LeaderboardRepository _leaderboardRepository; final ShareRepository _shareRepository; final PinballAudioPlayer _pinballAudioPlayer; final PlatformHelper _platformHelper; @override Widget build(BuildContext context) { return MultiRepositoryProvider( providers: [ RepositoryProvider.value(value: _authenticationRepository), RepositoryProvider.value(value: _leaderboardRepository), RepositoryProvider.value(value: _shareRepository), RepositoryProvider.value(value: _pinballAudioPlayer), RepositoryProvider.value(value: _platformHelper), ], child: MultiBlocProvider( providers: [ BlocProvider(create: (_) => CharacterThemeCubit()), BlocProvider(create: (_) => StartGameBloc()), BlocProvider(create: (_) => GameBloc()), ], child: MaterialApp( title: 'I/O Pinball', theme: PinballTheme.standard, localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, ], supportedLocales: AppLocalizations.supportedLocales, home: const PinballGamePage(), ), ), ); } }
pinball/lib/app/view/app.dart/0
{ "file_path": "pinball/lib/app/view/app.dart", "repo_id": "pinball", "token_count": 918 }
1,206
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_flame/pinball_flame.dart'; class KickerNoiseBehavior extends ContactBehavior { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); readProvider<PinballAudioPlayer>().play(PinballAudio.kicker); } }
pinball/lib/game/behaviors/kicker_noise_behavior.dart/0
{ "file_path": "pinball/lib/game/behaviors/kicker_noise_behavior.dart", "repo_id": "pinball", "token_count": 128 }
1,207
part of 'backbox_bloc.dart'; /// {@template backbox_event} /// Base class for backbox events. /// {@endtemplate} abstract class BackboxEvent extends Equatable { /// {@macro backbox_event} const BackboxEvent(); } /// {@template player_initials_requested} /// Event that triggers the user initials display. /// {@endtemplate} class PlayerInitialsRequested extends BackboxEvent { /// {@macro player_initials_requested} const PlayerInitialsRequested({ 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 player_initials_submitted} /// Event that submits the user score and initials. /// {@endtemplate} class PlayerInitialsSubmitted extends BackboxEvent { /// {@macro player_initials_submitted} const PlayerInitialsSubmitted({ required this.score, required this.initials, required this.character, }); /// Player's score. final int score; /// Player's initials. final String initials; /// Player's character. final CharacterTheme character; @override List<Object?> get props => [score, initials, character]; } /// {@template share_score_requested} /// Event when user requests to share their score. /// {@endtemplate} class ShareScoreRequested extends BackboxEvent { /// {@macro share_score_requested} const ShareScoreRequested({ required this.score, }); /// Player's score. final int score; @override List<Object?> get props => [score]; } /// Event that triggers the fetching of the leaderboard class LeaderboardRequested extends BackboxEvent { @override List<Object?> get props => []; }
pinball/lib/game/components/backbox/bloc/backbox_event.dart/0
{ "file_path": "pinball/lib/game/components/backbox/bloc/backbox_event.dart", "repo_id": "pinball", "token_count": 524 }
1,208
export 'draining_behavior.dart';
pinball/lib/game/components/drain/behaviors/behaviors.dart/0
{ "file_path": "pinball/lib/game/components/drain/behaviors/behaviors.dart", "repo_id": "pinball", "token_count": 11 }
1,209
import 'dart:math' as math; import 'package:flame/components.dart'; import 'package:flutter/material.dart'; import 'package:pinball/game/components/multipliers/behaviors/behaviors.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// {@template multipliers} /// A group for the multipliers on the board. /// {@endtemplate} class Multipliers extends Component with ZIndex { /// {@macro multipliers} Multipliers() : super( children: [ Multiplier.x2( position: Vector2(-19.6, -2), angle: -15 * math.pi / 180, ), Multiplier.x3( position: Vector2(12.8, -9.4), angle: 15 * math.pi / 180, ), Multiplier.x4( position: Vector2(-0.3, -21.2), angle: 3 * math.pi / 180, ), Multiplier.x5( position: Vector2(-8.9, -28), angle: -3 * math.pi / 180, ), Multiplier.x6( position: Vector2(9.8, -30.7), angle: 8 * math.pi / 180, ), MultipliersBehavior(), ], ) { zIndex = ZIndexes.decal; } /// Creates [Multipliers] without any children. /// /// This can be used for testing [Multipliers]'s behaviors in isolation. @visibleForTesting Multipliers.test(); }
pinball/lib/game/components/multipliers/multipliers.dart/0
{ "file_path": "pinball/lib/game/components/multipliers/multipliers.dart", "repo_id": "pinball", "token_count": 705 }
1,210
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball_components/pinball_components.dart'; /// {@template score_view} /// [Widget] that displays the score. /// {@endtemplate} class ScoreView extends StatelessWidget { /// {@macro score_view} const ScoreView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final isGameOver = context.select((GameBloc bloc) => bloc.state.status.isGameOver); return Padding( padding: const EdgeInsets.only( left: 12, top: 2, bottom: 2, ), child: AnimatedSwitcher( duration: kThemeAnimationDuration, child: isGameOver ? const _GameOver() : const _ScoreDisplay(), ), ); } } class _GameOver extends StatelessWidget { const _GameOver({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final l10n = context.l10n; return Text( l10n.gameOver, style: Theme.of(context).textTheme.headline1, ); } } class _ScoreDisplay extends StatelessWidget { const _ScoreDisplay({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final l10n = context.l10n; return Row( children: [ FittedBox( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text( l10n.score.toLowerCase(), style: Theme.of(context).textTheme.subtitle1, ), const _ScoreText(), const RoundCountDisplay(), ], ), ), ], ); } } class _ScoreText extends StatelessWidget { const _ScoreText({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final score = context.select((GameBloc bloc) => bloc.state.displayScore); return Text( score.formatScore(), style: Theme.of(context).textTheme.headline1, ); } }
pinball/lib/game/view/widgets/score_view.dart/0
{ "file_path": "pinball/lib/game/view/widgets/score_view.dart", "repo_id": "pinball", "token_count": 915 }
1,211
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball/select_character/select_character.dart'; import 'package:pinball/start_game/start_game.dart'; import 'package:pinball_theme/pinball_theme.dart'; import 'package:pinball_ui/pinball_ui.dart'; /// {@template character_selection_dialog} /// Dialog used to select the playing character of the game. /// {@endtemplate character_selection_dialog} class CharacterSelectionDialog extends StatelessWidget { /// {@macro character_selection_dialog} const CharacterSelectionDialog({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final l10n = context.l10n; return PinballDialog( title: l10n.characterSelectionTitle, subtitle: l10n.characterSelectionSubtitle, child: Padding( padding: const EdgeInsets.all(12), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Row( children: [ Expanded(child: _CharacterPreview()), Expanded(child: _CharacterGrid()), ], ), ), const SizedBox(height: 8), const _SelectCharacterButton(), ], ), ), ); } } class _SelectCharacterButton extends StatelessWidget { const _SelectCharacterButton({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final l10n = context.l10n; return PinballButton( onTap: () async { Navigator.of(context).pop(); context.read<StartGameBloc>().add(const CharacterSelected()); }, text: l10n.select, ); } } class _CharacterGrid extends StatelessWidget { @override Widget build(BuildContext context) { return BlocBuilder<CharacterThemeCubit, CharacterThemeState>( builder: (context, state) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Column( children: [ _Character( key: const Key('dash_character_selection'), character: const DashTheme(), isSelected: state.isDashSelected, ), const SizedBox(height: 6), _Character( key: const Key('android_character_selection'), character: const AndroidTheme(), isSelected: state.isAndroidSelected, ), ], ), ), const SizedBox(width: 6), Expanded( child: Column( children: [ _Character( key: const Key('sparky_character_selection'), character: const SparkyTheme(), isSelected: state.isSparkySelected, ), const SizedBox(height: 6), _Character( key: const Key('dino_character_selection'), character: const DinoTheme(), isSelected: state.isDinoSelected, ), ], ), ), ], ); }, ); } } class _CharacterPreview extends StatelessWidget { @override Widget build(BuildContext context) { return BlocBuilder<CharacterThemeCubit, CharacterThemeState>( builder: (context, state) { return SelectedCharacter(currentCharacter: state.characterTheme); }, ); } } class _Character extends StatelessWidget { const _Character({ Key? key, required this.character, required this.isSelected, }) : super(key: key); final CharacterTheme character; final bool isSelected; @override Widget build(BuildContext context) { return Expanded( child: Opacity( opacity: isSelected ? 1 : 0.4, child: TextButton( onPressed: () => context.read<CharacterThemeCubit>().characterSelected(character), style: ButtonStyle( overlayColor: MaterialStateProperty.all( PinballColors.transparent, ), ), child: character.icon.image(fit: BoxFit.contain), ), ), ); } }
pinball/lib/select_character/view/character_selection_page.dart/0
{ "file_path": "pinball/lib/select_character/view/character_selection_page.dart", "repo_id": "pinball", "token_count": 2091 }
1,212
# geometry [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] Provides a set of helpers for working with 2D geometry. [license_badge]: https://img.shields.io/badge/license-MIT-blue.svg [license_link]: https://opensource.org/licenses/MIT [very_good_analysis_badge]: https://img.shields.io/badge/style-very_good_analysis-B22C89.svg [very_good_analysis_link]: https://pub.dev/packages/very_good_analysis
pinball/packages/geometry/README.md/0
{ "file_path": "pinball/packages/geometry/README.md", "repo_id": "pinball", "token_count": 170 }
1,213
// ignore_for_file: prefer_const_constructors, subtype_of_sealed_class import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; class _MockFirebaseFirestore extends Mock implements FirebaseFirestore {} class _MockCollectionReference extends Mock implements CollectionReference<Map<String, dynamic>> {} class _MockQuery extends Mock implements Query<Map<String, dynamic>> {} class _MockQuerySnapshot extends Mock implements QuerySnapshot<Map<String, dynamic>> {} class _MockQueryDocumentSnapshot extends Mock implements QueryDocumentSnapshot<Map<String, dynamic>> {} class _MockDocumentReference extends Mock implements DocumentReference<Map<String, dynamic>> {} void main() { group('LeaderboardRepository', () { late FirebaseFirestore firestore; setUp(() { firestore = _MockFirebaseFirestore(); }); test('can be instantiated', () { expect(LeaderboardRepository(firestore), isNotNull); }); group('fetchTop10Leaderboard', () { late LeaderboardRepository leaderboardRepository; late CollectionReference<Map<String, dynamic>> collectionReference; late Query<Map<String, dynamic>> query; late QuerySnapshot<Map<String, dynamic>> querySnapshot; late List<QueryDocumentSnapshot<Map<String, dynamic>>> queryDocumentSnapshots; final top10Scores = [ 2500, 2200, 2200, 2000, 1800, 1400, 1300, 1000, 600, 300, 100, ]; final top10Leaderboard = top10Scores .map( (score) => LeaderboardEntryData( playerInitials: 'user$score', score: score, character: CharacterType.dash, ), ) .toList(); setUp(() { leaderboardRepository = LeaderboardRepository(firestore); collectionReference = _MockCollectionReference(); query = _MockQuery(); querySnapshot = _MockQuerySnapshot(); queryDocumentSnapshots = top10Scores.map((score) { final queryDocumentSnapshot = _MockQueryDocumentSnapshot(); when(queryDocumentSnapshot.data).thenReturn(<String, dynamic>{ 'character': 'dash', 'playerInitials': 'user$score', 'score': score }); return queryDocumentSnapshot; }).toList(); when(() => firestore.collection('leaderboard')) .thenAnswer((_) => collectionReference); when(() => collectionReference.orderBy('score', descending: true)) .thenAnswer((_) => query); when(() => query.limit(10)).thenAnswer((_) => query); when(query.get).thenAnswer((_) async => querySnapshot); when(() => querySnapshot.docs).thenReturn(queryDocumentSnapshots); }); test( 'returns top 10 entries when ' 'retrieving information from firestore succeeds', () async { final top10LeaderboardResults = await leaderboardRepository.fetchTop10Leaderboard(); expect(top10LeaderboardResults, equals(top10Leaderboard)); }); test( 'throws FetchTop10LeaderboardException when Exception occurs ' 'when trying to retrieve information from firestore', () async { when(() => firestore.collection('leaderboard')).thenThrow(Exception()); expect( () => leaderboardRepository.fetchTop10Leaderboard(), throwsA(isA<FetchTop10LeaderboardException>()), ); }); test( 'throws LeaderboardDeserializationException when Exception occurs ' 'during deserialization', () async { final top10LeaderboardDataMalformed = <String, dynamic>{ 'playerInitials': 'ABC', 'score': 1500, }; final queryDocumentSnapshot = _MockQueryDocumentSnapshot(); when(() => querySnapshot.docs).thenReturn([queryDocumentSnapshot]); when(queryDocumentSnapshot.data) .thenReturn(top10LeaderboardDataMalformed); expect( () => leaderboardRepository.fetchTop10Leaderboard(), throwsA(isA<LeaderboardDeserializationException>()), ); }); }); group('addLeaderboardEntry', () { late LeaderboardRepository leaderboardRepository; late CollectionReference<Map<String, dynamic>> collectionReference; late DocumentReference<Map<String, dynamic>> documentReference; late Query<Map<String, dynamic>> query; late QuerySnapshot<Map<String, dynamic>> querySnapshot; late List<QueryDocumentSnapshot<Map<String, dynamic>>> queryDocumentSnapshots; const entryScore = 1500; final leaderboardScores = [ 2500, 2200, entryScore, 1000, ]; final leaderboardEntry = LeaderboardEntryData( playerInitials: 'ABC', score: entryScore, character: CharacterType.dash, ); const entryDocumentId = 'id$entryScore'; setUp(() { leaderboardRepository = LeaderboardRepository(firestore); collectionReference = _MockCollectionReference(); documentReference = _MockDocumentReference(); query = _MockQuery(); querySnapshot = _MockQuerySnapshot(); queryDocumentSnapshots = leaderboardScores.map((score) { final queryDocumentSnapshot = _MockQueryDocumentSnapshot(); when(queryDocumentSnapshot.data).thenReturn(<String, dynamic>{ 'character': 'dash', 'playerInitials': 'AAA', 'score': score }); when(() => queryDocumentSnapshot.id).thenReturn('id$score'); return queryDocumentSnapshot; }).toList(); when(() => firestore.collection('leaderboard')) .thenAnswer((_) => collectionReference); when(() => collectionReference.add(any())) .thenAnswer((_) async => documentReference); when(() => collectionReference.orderBy('score', descending: true)) .thenAnswer((_) => query); when(query.get).thenAnswer((_) async => querySnapshot); when(() => querySnapshot.docs).thenReturn(queryDocumentSnapshots); when(() => documentReference.id).thenReturn(entryDocumentId); }); test( 'throws FetchLeaderboardException ' 'when querying the leaderboard fails', () { when(() => firestore.collection('leaderboard')).thenThrow(Exception()); expect( () => leaderboardRepository.addLeaderboardEntry(leaderboardEntry), throwsA(isA<FetchLeaderboardException>()), ); }); test( 'saves the new score if the existing leaderboard ' 'has less than 10 scores', () async { await leaderboardRepository.addLeaderboardEntry(leaderboardEntry); verify( () => collectionReference.add(leaderboardEntry.toJson()), ).called(1); }); test( 'throws AddLeaderboardEntryException ' 'when adding a new entry fails', () async { when(() => collectionReference.add(leaderboardEntry.toJson())) .thenThrow(Exception('oops')); expect( () => leaderboardRepository.addLeaderboardEntry(leaderboardEntry), throwsA(isA<AddLeaderboardEntryException>()), ); }); test( 'does nothing if there are more than 10 scores in the leaderboard ' 'and the new score is smaller than the top 10', () async { final leaderboardScores = [ 10000, 9500, 9000, 8500, 8000, 7500, 7000, 6500, 6000, 5500, 5000 ]; final queryDocumentSnapshots = leaderboardScores.map((score) { final queryDocumentSnapshot = _MockQueryDocumentSnapshot(); when(queryDocumentSnapshot.data).thenReturn(<String, dynamic>{ 'character': 'dash', 'playerInitials': 'AAA', 'score': score }); when(() => queryDocumentSnapshot.id).thenReturn('id$score'); return queryDocumentSnapshot; }).toList(); when(() => querySnapshot.docs).thenReturn(queryDocumentSnapshots); await leaderboardRepository.addLeaderboardEntry(leaderboardEntry); verifyNever( () => collectionReference.add(leaderboardEntry.toJson()), ); }); test( 'saves the new score when there are more than 10 scores in the ' 'leaderboard and the new score is higher than the lowest top 10', () async { final newScore = LeaderboardEntryData( playerInitials: 'ABC', score: 15000, character: CharacterType.android, ); final leaderboardScores = [ 10000, 9500, 9000, 8500, 8000, 7500, 7000, 6500, 6000, 5500, 5000, ]; final queryDocumentSnapshots = leaderboardScores.map((score) { final queryDocumentSnapshot = _MockQueryDocumentSnapshot(); when(queryDocumentSnapshot.data).thenReturn(<String, dynamic>{ 'character': 'dash', 'playerInitials': 'AAA', 'score': score }); when(() => queryDocumentSnapshot.id).thenReturn('id$score'); when(() => queryDocumentSnapshot.reference) .thenReturn(documentReference); return queryDocumentSnapshot; }).toList(); when(() => querySnapshot.docs).thenReturn(queryDocumentSnapshots); await leaderboardRepository.addLeaderboardEntry(newScore); verify(() => collectionReference.add(newScore.toJson())).called(1); }); }); }); }
pinball/packages/leaderboard_repository/test/src/leaderboard_repository_test.dart/0
{ "file_path": "pinball/packages/leaderboard_repository/test/src/leaderboard_repository_test.dart", "repo_id": "pinball", "token_count": 4141 }
1,214
import 'dart:async'; import 'dart:math' as math; import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flutter/material.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; export 'cubit/android_spaceship_cubit.dart'; class AndroidSpaceship extends Component { AndroidSpaceship({required Vector2 position}) : super( children: [ _SpaceshipSaucer()..initialPosition = position, _SpaceshipSaucerSpriteAnimationComponent()..position = position, _LightBeamSpriteComponent()..position = position + Vector2(2.5, 5), _SpaceshipHole( outsideLayer: Layer.spaceshipExitRail, outsidePriority: ZIndexes.ballOnSpaceshipRail, )..initialPosition = position - Vector2(5.3, -5.4), _SpaceshipHole( outsideLayer: Layer.board, outsidePriority: ZIndexes.ballOnBoard, )..initialPosition = position - Vector2(-7.5, -1.1), ], ); /// Creates an [AndroidSpaceship] without any children. /// /// This can be used for testing [AndroidSpaceship]'s behaviors in isolation. @visibleForTesting AndroidSpaceship.test({ Iterable<Component>? children, }) : super(children: children); } class _SpaceshipSaucer extends BodyComponent with InitialPosition, Layered { _SpaceshipSaucer() : super(renderBody: false) { layer = Layer.spaceship; } @override Body createBody() { final shape = _SpaceshipSaucerShape(); final bodyDef = BodyDef( position: initialPosition, userData: this, angle: -1.7, ); return world.createBody(bodyDef)..createFixtureFromShape(shape); } } class _SpaceshipSaucerShape extends ChainShape { _SpaceshipSaucerShape() { const minorRadius = 9.75; const majorRadius = 11.9; createChain( [ for (var angle = 0.2618; angle <= 6.0214; angle += math.pi / 180) Vector2( minorRadius * math.cos(angle), majorRadius * math.sin(angle), ), ], ); } } class _SpaceshipSaucerSpriteAnimationComponent extends SpriteAnimationComponent with HasGameRef, ZIndex { _SpaceshipSaucerSpriteAnimationComponent() : super( anchor: Anchor.center, ) { zIndex = ZIndexes.spaceshipSaucer; } @override Future<void> onLoad() async { await super.onLoad(); final spriteSheet = gameRef.images.fromCache( Assets.images.android.spaceship.saucer.keyName, ); const amountPerRow = 5; const amountPerColumn = 3; final textureSize = Vector2( spriteSheet.width / amountPerRow, spriteSheet.height / amountPerColumn, ); size = textureSize / 10; animation = SpriteAnimation.fromFrameData( spriteSheet, SpriteAnimationData.sequenced( amount: amountPerRow * amountPerColumn, amountPerRow: amountPerRow, stepTime: 1 / 12, textureSize: textureSize, ), ); } } class _LightBeamSpriteComponent extends SpriteComponent with HasGameRef, ZIndex { _LightBeamSpriteComponent() : super( anchor: Anchor.center, ) { zIndex = ZIndexes.spaceshipLightBeam; } @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.android.spaceship.lightBeam.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; } } class _SpaceshipHole extends LayerSensor { _SpaceshipHole({required Layer outsideLayer, required int outsidePriority}) : super( insideLayer: Layer.spaceship, outsideLayer: outsideLayer, orientation: LayerEntranceOrientation.down, insideZIndex: ZIndexes.ballOnSpaceship, outsideZIndex: outsidePriority, ) { layer = Layer.spaceship; } @override Shape get shape { return ArcShape( center: Vector2(0, -3.2), arcRadius: 5, angle: 1, rotation: -2, ); } }
pinball/packages/pinball_components/lib/src/components/android_spaceship/android_spaceship.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/android_spaceship/android_spaceship.dart", "repo_id": "pinball", "token_count": 1724 }
1,215
import 'package:flame/components.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class BoardBackgroundSpriteComponent extends SpriteComponent with HasGameRef, ZIndex { BoardBackgroundSpriteComponent() : super( anchor: Anchor.center, position: Vector2(-0.2, 0.1), ) { zIndex = ZIndexes.boardBackground; } @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.boardBackground.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; } }
pinball/packages/pinball_components/lib/src/components/board_background_sprite_component.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/board_background_sprite_component.dart", "repo_id": "pinball", "token_count": 266 }
1,216
export 'dash_bumper_ball_contact_behavior.dart';
pinball/packages/pinball_components/lib/src/components/dash_bumper/behaviors/behaviors.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/dash_bumper/behaviors/behaviors.dart", "repo_id": "pinball", "token_count": 17 }
1,217
part of 'flipper_cubit.dart'; enum FlipperState { movingDown, movingUp, } extension FlipperStateX on FlipperState { bool get isMovingDown => this == FlipperState.movingDown; bool get isMovingUp => this == FlipperState.movingUp; }
pinball/packages/pinball_components/lib/src/components/flipper/cubit/flipper_state.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/flipper/cubit/flipper_state.dart", "repo_id": "pinball", "token_count": 82 }
1,218
import 'package:bloc/bloc.dart'; part 'kicker_state.dart'; class KickerCubit extends Cubit<KickerState> { KickerCubit() : super(KickerState.lit); void onBallContacted() { emit(KickerState.dimmed); } void onBlinked() { emit(KickerState.lit); } }
pinball/packages/pinball_components/lib/src/components/kicker/cubit/kicker_cubit.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/kicker/cubit/kicker_cubit.dart", "repo_id": "pinball", "token_count": 109 }
1,219
import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class PlungerJointingBehavior extends Component with ParentIsA<Plunger> { PlungerJointingBehavior({required double compressionDistance}) : _compressionDistance = compressionDistance; final double _compressionDistance; @override Future<void> onLoad() async { await super.onLoad(); final anchor = JointAnchor() ..initialPosition = Vector2(0, _compressionDistance); await add(anchor); final jointDef = _PlungerAnchorPrismaticJointDef( plunger: parent, anchor: anchor, ); parent.world.createJoint( PrismaticJoint(jointDef)..setLimits(-_compressionDistance, 0), ); } } /// [PrismaticJointDef] between a [Plunger] and an [JointAnchor] with motion on /// the vertical axis. /// /// The [Plunger] is constrained vertically between its starting position and /// the [JointAnchor]. The [JointAnchor] must be below the [Plunger]. class _PlungerAnchorPrismaticJointDef extends PrismaticJointDef { /// {@macro plunger_anchor_prismatic_joint_def} _PlungerAnchorPrismaticJointDef({ required Plunger plunger, required BodyComponent anchor, }) { initialize( plunger.body, anchor.body, plunger.body.position + anchor.body.position, Vector2(16, BoardDimensions.bounds.height), ); enableLimit = true; lowerTranslation = double.negativeInfinity; enableMotor = true; motorSpeed = 1000; maxMotorForce = motorSpeed; collideConnected = true; } }
pinball/packages/pinball_components/lib/src/components/plunger/behaviors/plunger_jointing_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/plunger/behaviors/plunger_jointing_behavior.dart", "repo_id": "pinball", "token_count": 601 }
1,220
import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class SkillShotBallContactBehavior extends ContactBehavior<SkillShot> { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); if (other is! Ball) return; parent.bloc.onBallContacted(); parent.firstChild<SpriteAnimationComponent>()?.playing = true; } }
pinball/packages/pinball_components/lib/src/components/skill_shot/behaviors/skill_shot_ball_contact_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/skill_shot/behaviors/skill_shot_ball_contact_behavior.dart", "repo_id": "pinball", "token_count": 173 }
1,221
import 'package:bloc/bloc.dart'; part 'sparky_bumper_state.dart'; class SparkyBumperCubit extends Cubit<SparkyBumperState> { SparkyBumperCubit() : super(SparkyBumperState.lit); void onBallContacted() { emit(SparkyBumperState.dimmed); } void onBlinked() { emit(SparkyBumperState.lit); } }
pinball/packages/pinball_components/lib/src/components/sparky_bumper/cubit/sparky_bumper_cubit.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/sparky_bumper/cubit/sparky_bumper_cubit.dart", "repo_id": "pinball", "token_count": 129 }
1,222
# Pinball Components Sandbox ![coverage][coverage_badge] [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] Generated by the [Very Good CLI][very_good_cli_link] πŸ€– A sandbox application where components are showcased and developed in an isolated way --- ## Getting Started πŸš€ This project contains 3 flavors: - development - staging - production To run the desired flavor either use the launch configuration in VSCode/Android Studio or use the following commands: ```sh # Development $ flutter run --flavor development --target lib/main_development.dart # Staging $ flutter run --flavor staging --target lib/main_staging.dart # Production $ flutter run --flavor production --target lib/main_production.dart ``` _\*Sandbox works on iOS, Android, Web, and Windows._ --- ## Running Tests πŸ§ͺ To run all unit and widget tests use the following command: ```sh $ flutter test --coverage --test-randomize-ordering-seed random ``` To view the generated coverage report you can use [lcov](https://github.com/linux-test-project/lcov). ```sh # Generate Coverage Report $ genhtml coverage/lcov.info -o coverage/ # Open Coverage Report $ open coverage/index.html ``` --- ## Working with Translations 🌐 This project relies on [flutter_localizations][flutter_localizations_link] and follows the [official internationalization guide for Flutter][internationalization_link]. ### Adding Strings 1. To add a new localizable string, open the `app_en.arb` file at `lib/l10n/arb/app_en.arb`. ```arb { "@@locale": "en", "counterAppBarTitle": "Counter", "@counterAppBarTitle": { "description": "Text shown in the AppBar of the Counter Page" } } ``` 2. Then add a new key/value and description ```arb { "@@locale": "en", "counterAppBarTitle": "Counter", "@counterAppBarTitle": { "description": "Text shown in the AppBar of the Counter Page" }, "helloWorld": "Hello World", "@helloWorld": { "description": "Hello World Text" } } ``` 3. Use the new string ```dart import 'package:sandbox/l10n/l10n.dart'; @override Widget build(BuildContext context) { final l10n = context.l10n; return Text(l10n.helloWorld); } ``` ### Adding Supported Locales Update the `CFBundleLocalizations` array in the `Info.plist` at `ios/Runner/Info.plist` to include the new locale. ```xml ... <key>CFBundleLocalizations</key> <array> <string>en</string> <string>es</string> </array> ... ``` ### Adding Translations 1. For each supported locale, add a new ARB file in `lib/l10n/arb`. ``` β”œβ”€β”€ l10n β”‚ β”œβ”€β”€ arb β”‚ β”‚ β”œβ”€β”€ app_en.arb β”‚ β”‚ └── app_es.arb ``` 2. Add the translated strings to each `.arb` file: `app_en.arb` ```arb { "@@locale": "en", "counterAppBarTitle": "Counter", "@counterAppBarTitle": { "description": "Text shown in the AppBar of the Counter Page" } } ``` `app_es.arb` ```arb { "@@locale": "es", "counterAppBarTitle": "Contador", "@counterAppBarTitle": { "description": "Texto mostrado en la AppBar de la pΓ‘gina del contador" } } ``` [coverage_badge]: coverage_badge.svg [flutter_localizations_link]: https://api.flutter.dev/flutter/flutter_localizations/flutter_localizations-library.html [internationalization_link]: https://flutter.dev/docs/development/accessibility-and-localization/internationalization [license_badge]: https://img.shields.io/badge/license-MIT-blue.svg [license_link]: https://opensource.org/licenses/MIT [very_good_analysis_badge]: https://img.shields.io/badge/style-very_good_analysis-B22C89.svg [very_good_analysis_link]: https://pub.dev/packages/very_good_analysis [very_good_cli_link]: https://github.com/VeryGoodOpenSource/very_good_cli
pinball/packages/pinball_components/sandbox/README.md/0
{ "file_path": "pinball/packages/pinball_components/sandbox/README.md", "repo_id": "pinball", "token_count": 1351 }
1,223
import 'package:dashbook/dashbook.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/arrow_icon/arrow_icon_game.dart'; void addArrowIconStories(Dashbook dashbook) { dashbook.storiesOf('ArrowIcon').addGame( title: 'Basic', description: ArrowIconGame.description, gameBuilder: (context) => ArrowIconGame(), ); }
pinball/packages/pinball_components/sandbox/lib/stories/arrow_icon/stories.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/arrow_icon/stories.dart", "repo_id": "pinball", "token_count": 140 }
1,224
import 'package:dashbook/dashbook.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/effects/camera_zoom_game.dart'; void addEffectsStories(Dashbook dashbook) { dashbook.storiesOf('Effects').addGame( title: 'CameraZoom', description: CameraZoomGame.description, gameBuilder: (_) => CameraZoomGame(), ); }
pinball/packages/pinball_components/sandbox/lib/stories/effects/stories.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/effects/stories.dart", "repo_id": "pinball", "token_count": 138 }
1,225
import 'dart:math' as math; import 'package:flame/input.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class MultipliersGame extends BallGame with KeyboardEvents { MultipliersGame() : super( imagesFileNames: [ Assets.images.multiplier.x2.lit.keyName, Assets.images.multiplier.x2.dimmed.keyName, Assets.images.multiplier.x3.lit.keyName, Assets.images.multiplier.x3.dimmed.keyName, Assets.images.multiplier.x4.lit.keyName, Assets.images.multiplier.x4.dimmed.keyName, Assets.images.multiplier.x5.lit.keyName, Assets.images.multiplier.x5.dimmed.keyName, Assets.images.multiplier.x6.lit.keyName, Assets.images.multiplier.x6.dimmed.keyName, ], ); static const description = ''' Shows how the Multipliers are rendered. - Tap anywhere on the screen to spawn a ball into the game. - Press digits 2 to 6 for toggle state multipliers 2 to 6. '''; final List<Multiplier> multipliers = [ Multiplier.x2( position: Vector2(-20, 0), angle: -15 * math.pi / 180, ), Multiplier.x3( position: Vector2(20, -5), angle: 15 * math.pi / 180, ), Multiplier.x4( position: Vector2(0, -15), angle: 0, ), Multiplier.x5( position: Vector2(-10, -25), angle: -3 * math.pi / 180, ), Multiplier.x6( position: Vector2(10, -35), angle: 8 * math.pi / 180, ), ]; @override Future<void> onLoad() async { await super.onLoad(); camera.followVector2(Vector2.zero()); await addAll(multipliers); await traceAllBodies(); } @override KeyEventResult onKeyEvent( RawKeyEvent event, Set<LogicalKeyboardKey> keysPressed, ) { if (event is RawKeyDownEvent) { var currentMultiplier = 1; if (event.logicalKey == LogicalKeyboardKey.digit2) { currentMultiplier = 2; } if (event.logicalKey == LogicalKeyboardKey.digit3) { currentMultiplier = 3; } if (event.logicalKey == LogicalKeyboardKey.digit4) { currentMultiplier = 4; } if (event.logicalKey == LogicalKeyboardKey.digit5) { currentMultiplier = 5; } if (event.logicalKey == LogicalKeyboardKey.digit6) { currentMultiplier = 6; } for (final multiplier in multipliers) { multiplier.bloc.next(currentMultiplier); } return KeyEventResult.handled; } return KeyEventResult.ignored; } }
pinball/packages/pinball_components/sandbox/lib/stories/multipliers/multipliers_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/multipliers/multipliers_game.dart", "repo_id": "pinball", "token_count": 1192 }
1,226
// ignore_for_file: cascade_invocations, one_member_abstracts 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 '../../helpers/helpers.dart'; abstract class _VoidCallbackStubBase { void onCall(); } class _VoidCallbackStub extends Mock implements _VoidCallbackStubBase {} void main() { group('ArrowIcon', () { TestWidgetsFlutterBinding.ensureInitialized(); final assets = [ Assets.images.displayArrows.arrowLeft.keyName, Assets.images.displayArrows.arrowRight.keyName, ]; final flameTester = FlameTester(() => TappablesTestGame(assets)); flameTester.testGameWidget( 'is tappable', setUp: (game, tester) async { final stub = _VoidCallbackStub(); await game.images.loadAll(assets); await game.ensureAdd( ArrowIcon( position: Vector2.zero(), direction: ArrowIconDirection.left, onTap: stub.onCall, ), ); await tester.pump(); await tester.tapAt(Offset.zero); await tester.pump(); }, verify: (game, tester) async { final icon = game.descendants().whereType<ArrowIcon>().single; verify(icon.onTap).called(1); }, ); group('left', () { flameTester.testGameWidget( 'renders correctly', setUp: (game, tester) async { await game.images.loadAll(assets); game.camera.followVector2(Vector2.zero()); await game.add( ArrowIcon( position: Vector2.zero(), direction: ArrowIconDirection.left, onTap: () {}, ), ); await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/arrow_icon_left.png'), ); }, ); }); group('right', () { flameTester.testGameWidget( 'renders correctly', setUp: (game, tester) async { await game.images.loadAll(assets); game.camera.followVector2(Vector2.zero()); await game.add( ArrowIcon( position: Vector2.zero(), direction: ArrowIconDirection.right, onTap: () {}, ), ); await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/arrow_icon_right.png'), ); }, ); }); }); }
pinball/packages/pinball_components/test/src/components/arrow_icon_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/arrow_icon_test.dart", "repo_id": "pinball", "token_count": 1298 }
1,227
// 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/chrome_dino/behaviors/behaviors.dart'; import '../../../../helpers/helpers.dart'; class _MockChromeDinoCubit extends Mock implements ChromeDinoCubit {} class _MockContact extends Mock implements Contact {} class _MockFixture extends Mock implements Fixture {} class _MockBall extends Mock implements Ball {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(TestGame.new); group( 'ChromeDinoMouthOpeningBehavior', () { test('can be instantiated', () { expect( ChromeDinoMouthOpeningBehavior(), isA<ChromeDinoMouthOpeningBehavior>(), ); }); flameTester.test( 'preSolve disables contact when the mouth is open ' 'and there is not ball in the mouth', (game) async { final behavior = ChromeDinoMouthOpeningBehavior(); final bloc = _MockChromeDinoCubit(); whenListen( bloc, const Stream<ChromeDinoState>.empty(), initialState: const ChromeDinoState( status: ChromeDinoStatus.idle, isMouthOpen: true, ), ); final chromeDino = ChromeDino.test(bloc: bloc); await chromeDino.add(behavior); await game.ensureAdd(chromeDino); final contact = _MockContact(); final fixture = _MockFixture(); when(() => contact.fixtureA).thenReturn(fixture); when(() => fixture.userData).thenReturn('mouth_opening'); behavior.preSolve(_MockBall(), contact, Manifold()); verify(() => contact.setEnabled(false)).called(1); }, ); }, ); }
pinball/packages/pinball_components/test/src/components/chrome_dino/behaviors/chrome_dino_mouth_opening_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/chrome_dino/behaviors/chrome_dino_mouth_opening_behavior_test.dart", "repo_id": "pinball", "token_count": 856 }
1,228
// 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:mocktail/mocktail.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/src/components/flapper/behaviors/behaviors.dart'; import '../../../../helpers/helpers.dart'; class _MockBall extends Mock implements Ball {} class _MockContact extends Mock implements Contact {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final assets = [ Assets.images.flapper.flap.keyName, Assets.images.flapper.backSupport.keyName, Assets.images.flapper.frontSupport.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); group( 'FlapperSpinningBehavior', () { test('can be instantiated', () { expect( FlapperSpinningBehavior(), isA<FlapperSpinningBehavior>(), ); }); flameTester.test( 'beginContact plays the flapper animation', (game) async { final behavior = FlapperSpinningBehavior(); final entrance = FlapperEntrance(); final flap = FlapSpriteAnimationComponent(); final flapper = Flapper.test(); await flapper.addAll([entrance, flap]); await entrance.add(behavior); await game.ensureAdd(flapper); behavior.beginContact(_MockBall(), _MockContact()); expect(flap.playing, isTrue); }, ); }, ); }
pinball/packages/pinball_components/test/src/components/flapper/behaviors/flapper_spinning_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/flapper/behaviors/flapper_spinning_behavior_test.dart", "repo_id": "pinball", "token_count": 622 }
1,229
// ignore_for_file: cascade_invocations import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(Forge2DGame.new); group('JointAnchor', () { flameTester.test( 'loads correctly', (game) async { final anchor = JointAnchor(); await game.ready(); await game.ensureAdd(anchor); expect(game.contains(anchor), isTrue); }, ); group('body', () { flameTester.test( 'is static', (game) async { await game.ready(); final anchor = JointAnchor(); await game.ensureAdd(anchor); expect(anchor.body.bodyType, equals(BodyType.static)); }, ); }); group('fixtures', () { flameTester.test( 'has none', (game) async { final anchor = JointAnchor(); await game.ensureAdd(anchor); expect(anchor.body.fixtures, isEmpty); }, ); }); }); }
pinball/packages/pinball_components/test/src/components/joint_anchor_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/joint_anchor_test.dart", "repo_id": "pinball", "token_count": 532 }
1,230
// ignore_for_file: cascade_invocations import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { Future<void> pump( PlungerKeyControllingBehavior child, { PlungerCubit? plungerBloc, }) async { final plunger = Plunger.test(); await ensureAdd(plunger); return plunger.ensureAdd( FlameBlocProvider<PlungerCubit, PlungerState>.value( value: plungerBloc ?? _MockPlungerCubit(), children: [child], ), ); } } class _MockRawKeyDownEvent extends Mock implements RawKeyDownEvent { @override String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { return super.toString(); } } class _MockRawKeyUpEvent extends Mock implements RawKeyUpEvent { @override String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { return super.toString(); } } class _MockPlungerCubit extends Mock implements PlungerCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(_TestGame.new); group('PlungerKeyControllingBehavior', () { test('can be instantiated', () { expect( PlungerKeyControllingBehavior(), isA<PlungerKeyControllingBehavior>(), ); }); flameTester.test('can be loaded', (game) async { final behavior = PlungerKeyControllingBehavior(); await game.pump(behavior); expect(game.descendants(), contains(behavior)); }); group('onKeyEvent', () { late PlungerCubit plungerBloc; setUp(() { plungerBloc = _MockPlungerCubit(); }); group('pulls when', () { flameTester.test( 'down arrow is pressed', (game) async { final behavior = PlungerKeyControllingBehavior(); await game.pump( behavior, plungerBloc: plungerBloc, ); final event = _MockRawKeyDownEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.arrowDown, ); behavior.onKeyEvent(event, {}); verify(() => plungerBloc.pulled()).called(1); }, ); flameTester.test( '"s" is pressed', (game) async { final behavior = PlungerKeyControllingBehavior(); await game.pump( behavior, plungerBloc: plungerBloc, ); final event = _MockRawKeyDownEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.keyS, ); behavior.onKeyEvent(event, {}); verify(() => plungerBloc.pulled()).called(1); }, ); flameTester.test( 'space is pressed', (game) async { final behavior = PlungerKeyControllingBehavior(); await game.pump( behavior, plungerBloc: plungerBloc, ); final event = _MockRawKeyDownEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.space, ); behavior.onKeyEvent(event, {}); verify(() => plungerBloc.pulled()).called(1); }, ); }); group('releases when', () { flameTester.test( 'down arrow is released', (game) async { final behavior = PlungerKeyControllingBehavior(); await game.pump( behavior, plungerBloc: plungerBloc, ); final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.arrowDown, ); behavior.onKeyEvent(event, {}); verify(() => plungerBloc.released()).called(1); }, ); flameTester.test( '"s" is released', (game) async { final behavior = PlungerKeyControllingBehavior(); await game.pump( behavior, plungerBloc: plungerBloc, ); final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.keyS, ); behavior.onKeyEvent(event, {}); verify(() => plungerBloc.released()).called(1); }, ); flameTester.test( 'space is released', (game) async { final behavior = PlungerKeyControllingBehavior(); await game.pump( behavior, plungerBloc: plungerBloc, ); final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn( LogicalKeyboardKey.space, ); behavior.onKeyEvent(event, {}); verify(() => plungerBloc.released()).called(1); }, ); }); }); }); }
pinball/packages/pinball_components/test/src/components/plunger/behaviors/plunger_key_controlling_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/plunger/behaviors/plunger_key_controlling_behavior_test.dart", "repo_id": "pinball", "token_count": 2536 }
1,231
// 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/bumping_behavior.dart'; import '../../helpers/helpers.dart'; void main() { group('Slingshot', () { final assets = [ Assets.images.slingshot.upper.keyName, Assets.images.slingshot.lower.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); flameTester.test('loads correctly', (game) async { final component = Slingshots(); 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(Slingshots()); game.camera.followVector2(Vector2.zero()); await game.ready(); await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/slingshots.png'), ); }, ); flameTester.test('adds BumpingBehavior', (game) async { final slingshots = Slingshots(); await game.ensureAdd(slingshots); for (final slingshot in slingshots.children) { expect(slingshot.firstChild<BumpingBehavior>(), isNotNull); } }); }); }
pinball/packages/pinball_components/test/src/components/slingshot_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/slingshot_test.dart", "repo_id": "pinball", "token_count": 624 }
1,232
# pinball_flame [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] Set of out-of-the-way solutions for common Pinball game problems. [license_badge]: https://img.shields.io/badge/license-MIT-blue.svg [license_link]: https://opensource.org/licenses/MIT [very_good_analysis_badge]: https://img.shields.io/badge/style-very_good_analysis-B22C89.svg [very_good_analysis_link]: https://pub.dev/packages/very_good_analysis
pinball/packages/pinball_flame/README.md/0
{ "file_path": "pinball/packages/pinball_flame/README.md", "repo_id": "pinball", "token_count": 176 }
1,233
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:geometry/geometry.dart'; /// {@template arc_shape} /// Creates an arc. /// {@endtemplate} class ArcShape extends ChainShape { /// {@macro arc_shape} ArcShape({ required this.center, required this.arcRadius, required this.angle, this.rotation = 0, }) { createChain( calculateArc( center: center, radius: arcRadius, angle: angle, offsetAngle: rotation, ), ); } /// The center of the arc. final Vector2 center; /// The radius of the arc. final double arcRadius; /// Specifies the size of the arc, in radians. /// /// For example, two pi returns a complete circumference. final double angle; /// Angle in radians to rotate the arc around its [center]. final double rotation; }
pinball/packages/pinball_flame/lib/src/shapes/arc_shape.dart/0
{ "file_path": "pinball/packages/pinball_flame/lib/src/shapes/arc_shape.dart", "repo_id": "pinball", "token_count": 303 }
1,234
// ignore_for_file: cascade_invocations, one_member_abstracts import 'package:flame/game.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_flame/pinball_flame.dart'; class _TestGame extends FlameGame { bool pressed = false; @override Future<void>? onLoad() async { await super.onLoad(); await add( KeyboardInputController( keyUp: { LogicalKeyboardKey.enter: () { pressed = true; return true; }, LogicalKeyboardKey.escape: () { return false; }, }, ), ); } } abstract class _KeyCall { bool onCall(); } class _MockKeyCall extends Mock implements _KeyCall {} class _MockRawKeyUpEvent extends Mock implements RawKeyUpEvent { @override String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { return super.toString(); } } RawKeyUpEvent _mockKeyUp(LogicalKeyboardKey key) { final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn(key); return event; } void main() { group('KeyboardInputController', () { test('calls registered handlers', () { final stub = _MockKeyCall(); when(stub.onCall).thenReturn(true); final input = KeyboardInputController( keyUp: { LogicalKeyboardKey.arrowUp: stub.onCall, }, ); input.onKeyEvent(_mockKeyUp(LogicalKeyboardKey.arrowUp), {}); verify(stub.onCall).called(1); }); test( 'returns false the handler return value', () { final stub = _MockKeyCall(); when(stub.onCall).thenReturn(false); final input = KeyboardInputController( keyUp: { LogicalKeyboardKey.arrowUp: stub.onCall, }, ); expect( input.onKeyEvent(_mockKeyUp(LogicalKeyboardKey.arrowUp), {}), isFalse, ); }, ); test( 'returns true (allowing event to bubble) when no handler is registered', () { final stub = _MockKeyCall(); when(stub.onCall).thenReturn(true); final input = KeyboardInputController(); expect( input.onKeyEvent(_mockKeyUp(LogicalKeyboardKey.arrowUp), {}), isTrue, ); }, ); }); group('VirtualKeyEvents', () { final flameTester = FlameTester(_TestGame.new); group('onVirtualKeyUp', () { flameTester.test('triggers the event', (game) async { await game.ready(); game.triggerVirtualKeyUp(LogicalKeyboardKey.enter); expect(game.pressed, isTrue); }); }); }); }
pinball/packages/pinball_flame/test/src/keyboard_input_controller_test.dart/0
{ "file_path": "pinball/packages/pinball_flame/test/src/keyboard_input_controller_test.dart", "repo_id": "pinball", "token_count": 1182 }
1,235
# pinball_ui [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] UI Toolkit for the Pinball Flutter Application [license_badge]: https://img.shields.io/badge/license-MIT-blue.svg [license_link]: https://opensource.org/licenses/MIT [very_good_analysis_badge]: https://img.shields.io/badge/style-very_good_analysis-B22C89.svg [very_good_analysis_link]: https://pub.dev/packages/very_good_analysis
pinball/packages/pinball_ui/README.md/0
{ "file_path": "pinball/packages/pinball_ui/README.md", "repo_id": "pinball", "token_count": 170 }
1,236
import 'package:flutter/material.dart'; import 'package:pinball_ui/pinball_ui.dart'; /// {@template pinball_dialog} /// Pinball-themed dialog. /// {@endtemplate} class PinballDialog extends StatelessWidget { /// {@macro pinball_dialog} const PinballDialog({ Key? key, required this.title, required this.child, this.subtitle, }) : super(key: key); /// Title shown in the dialog. final String title; /// Optional subtitle shown below the [title]. final String? subtitle; /// Body of the dialog. final Widget child; @override Widget build(BuildContext context) { final height = MediaQuery.of(context).size.height * 0.5; return Center( child: SizedBox( height: height, width: height * 1.4, child: PixelatedDecoration( header: subtitle != null ? _TitleAndSubtitle(title: title, subtitle: subtitle!) : _Title(title: title), body: child, ), ), ); } } class _Title extends StatelessWidget { const _Title({Key? key, required this.title}) : super(key: key); final String title; @override Widget build(BuildContext context) => Text( title, style: Theme.of(context).textTheme.headline3!.copyWith( fontWeight: FontWeight.bold, color: PinballColors.darkBlue, ), overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, ); } class _TitleAndSubtitle extends StatelessWidget { const _TitleAndSubtitle({ Key? key, required this.title, required this.subtitle, }) : super(key: key); final String title; final String subtitle; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; return Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.center, children: [ _Title(title: title), Text( subtitle, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: textTheme.headline3!.copyWith(fontWeight: FontWeight.normal), ), ], ); } }
pinball/packages/pinball_ui/lib/src/dialog/pinball_dialog.dart/0
{ "file_path": "pinball/packages/pinball_ui/lib/src/dialog/pinball_dialog.dart", "repo_id": "pinball", "token_count": 873 }
1,237
import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_ui/pinball_ui.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; class _MockUrlLauncher extends Mock with MockPlatformInterfaceMixin implements UrlLauncherPlatform {} void main() { late UrlLauncherPlatform urlLauncher; setUp(() { urlLauncher = _MockUrlLauncher(); UrlLauncherPlatform.instance = urlLauncher; }); group('openLink', () { test('launches the link', () async { when( () => urlLauncher.canLaunch(any()), ).thenAnswer( (_) async => true, ); when( () => urlLauncher.launch( any(), useSafariVC: any(named: 'useSafariVC'), useWebView: any(named: 'useWebView'), enableJavaScript: any(named: 'enableJavaScript'), enableDomStorage: any(named: 'enableDomStorage'), universalLinksOnly: any(named: 'universalLinksOnly'), headers: any(named: 'headers'), ), ).thenAnswer( (_) async => true, ); await openLink('uri'); verify( () => urlLauncher.launch( any(), useSafariVC: any(named: 'useSafariVC'), useWebView: any(named: 'useWebView'), enableJavaScript: any(named: 'enableJavaScript'), enableDomStorage: any(named: 'enableDomStorage'), universalLinksOnly: any(named: 'universalLinksOnly'), headers: any(named: 'headers'), ), ); }); test('executes the onError callback when it cannot launch', () async { var wasCalled = false; when( () => urlLauncher.canLaunch(any()), ).thenAnswer( (_) async => false, ); when( () => urlLauncher.launch( any(), useSafariVC: any(named: 'useSafariVC'), useWebView: any(named: 'useWebView'), enableJavaScript: any(named: 'enableJavaScript'), enableDomStorage: any(named: 'enableDomStorage'), universalLinksOnly: any(named: 'universalLinksOnly'), headers: any(named: 'headers'), ), ).thenAnswer( (_) async => true, ); await openLink( 'url', onError: () { wasCalled = true; }, ); await expectLater(wasCalled, isTrue); }); }); }
pinball/packages/pinball_ui/test/src/external_links/external_links_test.dart/0
{ "file_path": "pinball/packages/pinball_ui/test/src/external_links/external_links_test.dart", "repo_id": "pinball", "token_count": 1065 }
1,238