text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. part of '../google_maps_flutter_web.dart'; // Default values for when the gmaps objects return null/undefined values. final gmaps.LatLng _nullGmapsLatLng = gmaps.LatLng(0, 0); final gmaps.LatLngBounds _nullGmapsLatLngBounds = gmaps.LatLngBounds(_nullGmapsLatLng, _nullGmapsLatLng); // The TrustedType Policy used by this plugin. Used to sanitize InfoWindow contents. TrustedTypePolicy? _gmapsTrustedTypePolicy; // Converts a [Color] into a valid CSS value #RRGGBB. String _getCssColor(Color color) { return '#${color.value.toRadixString(16).padLeft(8, '0').substring(2)}'; } // Extracts the opacity from a [Color]. double _getCssOpacity(Color color) { return color.opacity; } // Converts options from the plugin into gmaps.MapOptions that can be used by the JS SDK. // The following options are not handled here, for various reasons: // The following are not available in web, because the map doesn't rotate there: // compassEnabled // rotateGesturesEnabled // tiltGesturesEnabled // mapToolbarEnabled is unused in web, there's no "map toolbar" // myLocationButtonEnabled Widget not available in web yet, it needs to be built on top of the maps widget // See: https://developers.google.com/maps/documentation/javascript/examples/control-custom // myLocationEnabled needs to be built through `navigator.geolocation` from package:web. // See: https://api.dart.dev/stable/2.8.4/dart-html/Geolocation-class.html // trafficEnabled is handled when creating the GMap object, since it needs to be added as a layer. // trackCameraPosition is just a boolean value that indicates if the map has an onCameraMove handler. // indoorViewEnabled seems to not have an equivalent in web // buildingsEnabled seems to not have an equivalent in web // padding seems to behave differently in web than mobile. You can't move UI elements in web. gmaps.MapOptions _configurationAndStyleToGmapsOptions( MapConfiguration configuration, List<gmaps.MapTypeStyle> styles) { final gmaps.MapOptions options = gmaps.MapOptions(); if (configuration.mapType != null) { options.mapTypeId = _gmapTypeIDForPluginType(configuration.mapType!); } final MinMaxZoomPreference? zoomPreference = configuration.minMaxZoomPreference; if (zoomPreference != null) { options ..minZoom = zoomPreference.minZoom ..maxZoom = zoomPreference.maxZoom; } if (configuration.cameraTargetBounds != null) { // Needs gmaps.MapOptions.restriction and gmaps.MapRestriction // see: https://developers.google.com/maps/documentation/javascript/reference/map#MapOptions.restriction } if (configuration.zoomControlsEnabled != null) { options.zoomControl = configuration.zoomControlsEnabled; } if (configuration.webGestureHandling != null) { options.gestureHandling = configuration.webGestureHandling!.name; } else if (configuration.scrollGesturesEnabled == false || configuration.zoomGesturesEnabled == false) { // Old behavior options.gestureHandling = WebGestureHandling.none.name; } else { options.gestureHandling = WebGestureHandling.auto.name; } if (configuration.fortyFiveDegreeImageryEnabled != null) { options.rotateControl = configuration.fortyFiveDegreeImageryEnabled; } // These don't have any configuration entries, but they seem to be off in the // native maps. options.mapTypeControl = false; options.fullscreenControl = false; options.streetViewControl = false; // See updateMapConfiguration for why this is not using configuration.style. options.styles = styles; options.mapId = configuration.cloudMapId; return options; } gmaps.MapTypeId _gmapTypeIDForPluginType(MapType type) { switch (type) { case MapType.satellite: return gmaps.MapTypeId.SATELLITE; case MapType.terrain: return gmaps.MapTypeId.TERRAIN; case MapType.hybrid: return gmaps.MapTypeId.HYBRID; case MapType.normal: case MapType.none: return gmaps.MapTypeId.ROADMAP; } // The enum comes from a different package, which could get a new value at // any time, so provide a fallback that ensures this won't break when used // with a version that contains new values. This is deliberately outside // the switch rather than a `default` so that the linter will flag the // switch as needing an update. // ignore: dead_code return gmaps.MapTypeId.ROADMAP; } gmaps.MapOptions _applyInitialPosition( CameraPosition initialPosition, gmaps.MapOptions options, ) { // Adjust the initial position, if passed... options.zoom = initialPosition.zoom; options.center = gmaps.LatLng( initialPosition.target.latitude, initialPosition.target.longitude); return options; } // The keys we'd expect to see in a serialized MapTypeStyle JSON object. final Set<String> _mapStyleKeys = <String>{ 'elementType', 'featureType', 'stylers', }; // Checks if the passed in Map contains some of the _mapStyleKeys. bool _isJsonMapStyle(Map<String, Object?> value) { return _mapStyleKeys.intersection(value.keys.toSet()).isNotEmpty; } // Converts an incoming JSON-encoded Style info, into the correct gmaps array. List<gmaps.MapTypeStyle> _mapStyles(String? mapStyleJson) { List<gmaps.MapTypeStyle> styles = <gmaps.MapTypeStyle>[]; if (mapStyleJson != null) { try { styles = (json.decode(mapStyleJson, reviver: (Object? key, Object? value) { if (value is Map && _isJsonMapStyle(value as Map<String, Object?>)) { List<MapStyler> stylers = <MapStyler>[]; if (value['stylers'] != null) { stylers = (value['stylers']! as List<Object?>) .whereType<Map<String, Object?>>() .map(MapStyler.fromJson) .toList(); } return gmaps.MapTypeStyle() ..elementType = value['elementType'] as String? ..featureType = value['featureType'] as String? ..stylers = stylers; } return value; }) as List<Object?>) .where((Object? element) => element != null) .cast<gmaps.MapTypeStyle>() .toList(); // .toList calls are required so the JS API understands the underlying data structure. } on FormatException catch (e) { throw MapStyleException(e.message); } } return styles; } gmaps.LatLng _latLngToGmLatLng(LatLng latLng) { return gmaps.LatLng(latLng.latitude, latLng.longitude); } LatLng _gmLatLngToLatLng(gmaps.LatLng latLng) { return LatLng(latLng.lat.toDouble(), latLng.lng.toDouble()); } LatLngBounds _gmLatLngBoundsTolatLngBounds(gmaps.LatLngBounds latLngBounds) { return LatLngBounds( southwest: _gmLatLngToLatLng(latLngBounds.southWest), northeast: _gmLatLngToLatLng(latLngBounds.northEast), ); } CameraPosition _gmViewportToCameraPosition(gmaps.GMap map) { return CameraPosition( target: _gmLatLngToLatLng(map.center ?? _nullGmapsLatLng), bearing: map.heading?.toDouble() ?? 0, tilt: map.tilt?.toDouble() ?? 0, zoom: map.zoom?.toDouble() ?? 0, ); } // Convert plugin objects to gmaps.Options objects // TODO(ditman): Move to their appropriate objects, maybe make them copy constructors? // Marker.fromMarker(anotherMarker, moreOptions); gmaps.InfoWindowOptions? _infoWindowOptionsFromMarker(Marker marker) { final String markerTitle = marker.infoWindow.title ?? ''; final String markerSnippet = marker.infoWindow.snippet ?? ''; // If both the title and snippet of an infowindow are empty, we don't really // want an infowindow... if ((markerTitle.isEmpty) && (markerSnippet.isEmpty)) { return null; } // Add an outer wrapper to the contents of the infowindow, we need it to listen // to click events... final HTMLElement container = createDivElement() ..id = 'gmaps-marker-${marker.markerId.value}-infowindow'; if (markerTitle.isNotEmpty) { final HTMLHeadingElement title = (document.createElement('h3') as HTMLHeadingElement) ..className = 'infowindow-title' ..innerText = markerTitle; container.appendChild(title); } if (markerSnippet.isNotEmpty) { final HTMLElement snippet = createDivElement() ..className = 'infowindow-snippet'; // Firefox and Safari don't support Trusted Types yet. // See https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicyFactory#browser_compatibility if (window.nullableTrustedTypes != null) { _gmapsTrustedTypePolicy ??= window.trustedTypes.createPolicy( 'google_maps_flutter_sanitize', TrustedTypePolicyOptions( createHTML: (String html) { return sanitizeHtml(html).toJS; }.toJS, ), ); snippet.trustedInnerHTML = _gmapsTrustedTypePolicy!.createHTMLNoArgs(markerSnippet); } else { // `sanitizeHtml` is used to clean the (potential) user input from (potential) // XSS attacks through the contents of the marker InfoWindow. // See: https://pub.dev/documentation/sanitize_html/latest/sanitize_html/sanitizeHtml.html // See: b/159137885, b/159598165 // ignore: unsafe_html snippet.innerHTML = sanitizeHtml(markerSnippet); } container.appendChild(snippet); } return gmaps.InfoWindowOptions() ..content = container ..zIndex = marker.zIndex; // TODO(ditman): Compute the pixelOffset of the infoWindow, from the size of the Marker, // and the marker.infoWindow.anchor property. } // Attempts to extract a [gmaps.Size] from `iconConfig[sizeIndex]`. gmaps.Size? _gmSizeFromIconConfig(List<Object?> iconConfig, int sizeIndex) { gmaps.Size? size; if (iconConfig.length >= sizeIndex + 1) { final List<Object?>? rawIconSize = iconConfig[sizeIndex] as List<Object?>?; if (rawIconSize != null) { size = gmaps.Size( rawIconSize[0] as num?, rawIconSize[1] as num?, ); } } return size; } // Converts a [BitmapDescriptor] into a [gmaps.Icon] that can be used in Markers. gmaps.Icon? _gmIconFromBitmapDescriptor(BitmapDescriptor bitmapDescriptor) { final List<Object?> iconConfig = bitmapDescriptor.toJson() as List<Object?>; gmaps.Icon? icon; if (iconConfig[0] == 'fromAssetImage') { assert(iconConfig.length >= 2); // iconConfig[2] contains the DPIs of the screen, but that information is // already encoded in the iconConfig[1] icon = gmaps.Icon() ..url = ui_web.assetManager.getAssetUrl(iconConfig[1]! as String); final gmaps.Size? size = _gmSizeFromIconConfig(iconConfig, 3); if (size != null) { icon ..size = size ..scaledSize = size; } } else if (iconConfig[0] == 'fromBytes') { // Grab the bytes, and put them into a blob final List<int> bytes = iconConfig[1]! as List<int>; // Create a Blob from bytes, but let the browser figure out the encoding final Blob blob; assert( bytes is Uint8List, 'The bytes for a BitmapDescriptor icon must be a Uint8List', ); // TODO(ditman): Improve this conversion // See https://github.com/dart-lang/web/issues/180 blob = Blob(<JSUint8Array>[(bytes as Uint8List).toJS].toJS); icon = gmaps.Icon()..url = URL.createObjectURL(blob as JSObject); final gmaps.Size? size = _gmSizeFromIconConfig(iconConfig, 2); if (size != null) { icon ..size = size ..scaledSize = size; } } return icon; } // Computes the options for a new [gmaps.Marker] from an incoming set of options // [marker], and the existing marker registered with the map: [currentMarker]. gmaps.MarkerOptions _markerOptionsFromMarker( Marker marker, gmaps.Marker? currentMarker, ) { return gmaps.MarkerOptions() ..position = gmaps.LatLng( marker.position.latitude, marker.position.longitude, ) ..title = sanitizeHtml(marker.infoWindow.title ?? '') ..zIndex = marker.zIndex ..visible = marker.visible ..opacity = marker.alpha ..draggable = marker.draggable ..icon = _gmIconFromBitmapDescriptor(marker.icon); // TODO(ditman): Compute anchor properly, otherwise infowindows attach to the wrong spot. // Flat and Rotation are not supported directly on the web. } gmaps.CircleOptions _circleOptionsFromCircle(Circle circle) { final gmaps.CircleOptions circleOptions = gmaps.CircleOptions() ..strokeColor = _getCssColor(circle.strokeColor) ..strokeOpacity = _getCssOpacity(circle.strokeColor) ..strokeWeight = circle.strokeWidth ..fillColor = _getCssColor(circle.fillColor) ..fillOpacity = _getCssOpacity(circle.fillColor) ..center = gmaps.LatLng(circle.center.latitude, circle.center.longitude) ..radius = circle.radius ..visible = circle.visible ..zIndex = circle.zIndex; return circleOptions; } gmaps.PolygonOptions _polygonOptionsFromPolygon( gmaps.GMap googleMap, Polygon polygon) { // Convert all points to GmLatLng final List<gmaps.LatLng> path = polygon.points.map(_latLngToGmLatLng).toList(); final bool isClockwisePolygon = _isPolygonClockwise(path); final List<List<gmaps.LatLng>> paths = <List<gmaps.LatLng>>[path]; for (int i = 0; i < polygon.holes.length; i++) { final List<LatLng> hole = polygon.holes[i]; final List<gmaps.LatLng> correctHole = _ensureHoleHasReverseWinding( hole, isClockwisePolygon, holeId: i, polygonId: polygon.polygonId, ); paths.add(correctHole); } return gmaps.PolygonOptions() ..paths = paths ..strokeColor = _getCssColor(polygon.strokeColor) ..strokeOpacity = _getCssOpacity(polygon.strokeColor) ..strokeWeight = polygon.strokeWidth ..fillColor = _getCssColor(polygon.fillColor) ..fillOpacity = _getCssOpacity(polygon.fillColor) ..visible = polygon.visible ..zIndex = polygon.zIndex ..geodesic = polygon.geodesic; } List<gmaps.LatLng> _ensureHoleHasReverseWinding( List<LatLng> hole, bool polyIsClockwise, { required int holeId, required PolygonId polygonId, }) { List<gmaps.LatLng> holePath = hole.map(_latLngToGmLatLng).toList(); final bool holeIsClockwise = _isPolygonClockwise(holePath); if (holeIsClockwise == polyIsClockwise) { holePath = holePath.reversed.toList(); if (kDebugMode) { print('Hole [$holeId] in Polygon [${polygonId.value}] has been reversed.' ' Ensure holes in polygons are "wound in the opposite direction to the outer path."' ' More info: https://github.com/flutter/flutter/issues/74096'); } } return holePath; } /// Calculates the direction of a given Polygon /// based on: https://stackoverflow.com/a/1165943 /// /// returns [true] if clockwise [false] if counterclockwise /// /// This method expects that the incoming [path] is a `List` of well-formed, /// non-null [gmaps.LatLng] objects. /// /// Currently, this method is only called from [_polygonOptionsFromPolygon], and /// the `path` is a transformed version of [Polygon.points] or each of the /// [Polygon.holes], guaranteeing that `lat` and `lng` can be accessed with `!`. bool _isPolygonClockwise(List<gmaps.LatLng> path) { double direction = 0.0; for (int i = 0; i < path.length; i++) { direction = direction + ((path[(i + 1) % path.length].lat - path[i].lat) * (path[(i + 1) % path.length].lng + path[i].lng)); } return direction >= 0; } gmaps.PolylineOptions _polylineOptionsFromPolyline( gmaps.GMap googleMap, Polyline polyline) { final List<gmaps.LatLng> paths = polyline.points.map(_latLngToGmLatLng).toList(); return gmaps.PolylineOptions() ..path = paths ..strokeWeight = polyline.width ..strokeColor = _getCssColor(polyline.color) ..strokeOpacity = _getCssOpacity(polyline.color) ..visible = polyline.visible ..zIndex = polyline.zIndex ..geodesic = polyline.geodesic; // this.endCap = Cap.buttCap, // this.jointType = JointType.mitered, // this.patterns = const <PatternItem>[], // this.startCap = Cap.buttCap, // this.width = 10, } // Translates a [CameraUpdate] into operations on a [gmaps.GMap]. void _applyCameraUpdate(gmaps.GMap map, CameraUpdate update) { // Casts [value] to a JSON dictionary (string -> nullable object). [value] // must be a non-null JSON dictionary. Map<String, Object?> asJsonObject(dynamic value) { return (value as Map<Object?, Object?>).cast<String, Object?>(); } // Casts [value] to a JSON list. [value] must be a non-null JSON list. List<Object?> asJsonList(dynamic value) { return value as List<Object?>; } final List<dynamic> json = update.toJson() as List<dynamic>; switch (json[0]) { case 'newCameraPosition': final Map<String, Object?> position = asJsonObject(json[1]); final List<Object?> latLng = asJsonList(position['target']); map.heading = position['bearing'] as num?; map.zoom = position['zoom'] as num?; map.panTo( gmaps.LatLng(latLng[0] as num?, latLng[1] as num?), ); map.tilt = position['tilt'] as num?; case 'newLatLng': final List<Object?> latLng = asJsonList(json[1]); map.panTo(gmaps.LatLng(latLng[0] as num?, latLng[1] as num?)); case 'newLatLngZoom': final List<Object?> latLng = asJsonList(json[1]); map.zoom = json[2] as num?; map.panTo(gmaps.LatLng(latLng[0] as num?, latLng[1] as num?)); case 'newLatLngBounds': final List<Object?> latLngPair = asJsonList(json[1]); final List<Object?> latLng1 = asJsonList(latLngPair[0]); final List<Object?> latLng2 = asJsonList(latLngPair[1]); final double padding = json[2] as double; map.fitBounds( gmaps.LatLngBounds( gmaps.LatLng(latLng1[0] as num?, latLng1[1] as num?), gmaps.LatLng(latLng2[0] as num?, latLng2[1] as num?), ), padding, ); case 'scrollBy': map.panBy(json[1] as num?, json[2] as num?); case 'zoomBy': gmaps.LatLng? focusLatLng; final double zoomDelta = json[1] as double? ?? 0; // Web only supports integer changes... final int newZoomDelta = zoomDelta < 0 ? zoomDelta.floor() : zoomDelta.ceil(); if (json.length == 3) { final List<Object?> latLng = asJsonList(json[2]); // With focus try { focusLatLng = _pixelToLatLng(map, latLng[0]! as int, latLng[1]! as int); } catch (e) { // https://github.com/a14n/dart-google-maps/issues/87 // print('Error computing new focus LatLng. JS Error: ' + e.toString()); } } map.zoom = (map.zoom ?? 0) + newZoomDelta; if (focusLatLng != null) { map.panTo(focusLatLng); } case 'zoomIn': map.zoom = (map.zoom ?? 0) + 1; case 'zoomOut': map.zoom = (map.zoom ?? 0) - 1; case 'zoomTo': map.zoom = json[1] as num?; default: throw UnimplementedError('Unimplemented CameraMove: ${json[0]}.'); } } // original JS by: Byron Singh (https://stackoverflow.com/a/30541162) gmaps.LatLng _pixelToLatLng(gmaps.GMap map, int x, int y) { final gmaps.LatLngBounds? bounds = map.bounds; final gmaps.Projection? projection = map.projection; final num? zoom = map.zoom; assert( bounds != null, 'Map Bounds required to compute LatLng of screen x/y.'); assert(projection != null, 'Map Projection required to compute LatLng of screen x/y'); assert(zoom != null, 'Current map zoom level required to compute LatLng of screen x/y'); final gmaps.LatLng ne = bounds!.northEast; final gmaps.LatLng sw = bounds.southWest; final gmaps.Point topRight = projection!.fromLatLngToPoint!(ne)!; final gmaps.Point bottomLeft = projection.fromLatLngToPoint!(sw)!; final int scale = 1 << (zoom!.toInt()); // 2 ^ zoom final gmaps.Point point = gmaps.Point((x / scale) + bottomLeft.x!, (y / scale) + topRight.y!); return projection.fromPointToLatLng!(point)!; }
packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/convert.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/convert.dart", "repo_id": "packages", "token_count": 7568 }
1,200
// The MIT License (MIT) // // Copyright (c) 2008 Krasimir Tsonev // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import 'package:google_maps/google_maps.dart' as gmaps; /// Returns a screen location that corresponds to a geographical coordinate ([gmaps.LatLng]). /// /// The screen location is in pixels relative to the top left of the Map widget /// (not of the whole screen/app). /// /// See: https://developers.google.com/maps/documentation/android-sdk/reference/com/google/android/libraries/maps/Projection#public-point-toscreenlocation-latlng-location gmaps.Point toScreenLocation(gmaps.GMap map, gmaps.LatLng coords) { final num? zoom = map.zoom; final gmaps.LatLngBounds? bounds = map.bounds; final gmaps.Projection? projection = map.projection; assert( bounds != null, 'Map Bounds required to compute screen x/y of LatLng.'); assert(projection != null, 'Map Projection required to compute screen x/y of LatLng.'); assert(zoom != null, 'Current map zoom level required to compute screen x/y of LatLng.'); final gmaps.LatLng ne = bounds!.northEast; final gmaps.LatLng sw = bounds.southWest; final gmaps.Point topRight = projection!.fromLatLngToPoint!(ne)!; final gmaps.Point bottomLeft = projection.fromLatLngToPoint!(sw)!; final int scale = 1 << (zoom!.toInt()); // 2 ^ zoom final gmaps.Point worldPoint = projection.fromLatLngToPoint!(coords)!; return gmaps.Point( ((worldPoint.x! - bottomLeft.x!) * scale).toInt(), ((worldPoint.y! - topRight.y!) * scale).toInt(), ); }
packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/third_party/to_screen_location/to_screen_location.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/third_party/to_screen_location/to_screen_location.dart", "repo_id": "packages", "token_count": 769 }
1,201
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.googlesigninexample; import androidx.test.rule.ActivityTestRule; import dev.flutter.plugins.integration_test.FlutterTestRunner; import io.flutter.embedding.android.FlutterActivity; import io.flutter.plugins.DartIntegrationTest; import org.junit.Rule; import org.junit.runner.RunWith; @DartIntegrationTest @RunWith(FlutterTestRunner.class) public class FlutterActivityTest { @Rule public ActivityTestRule<FlutterActivity> rule = new ActivityTestRule<>(FlutterActivity.class); }
packages/packages/google_sign_in/google_sign_in/example/android/app/src/androidTest/java/io/flutter/plugins/googlesigninexample/FlutterActivityTest.java/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in/example/android/app/src/androidTest/java/io/flutter/plugins/googlesigninexample/FlutterActivityTest.java", "repo_id": "packages", "token_count": 203 }
1,202
# google\_sign\_in\_ios The iOS and macOS implementation of [`google_sign_in`][1]. ## Usage This package is [endorsed][2], which means you can simply use `google_sign_in` normally. This package will be automatically included in your app when you do, so you do not need to add it to your `pubspec.yaml`. However, if you `import` this package to use any of its APIs directly, you should add it to your `pubspec.yaml` as usual. ### macOS setup The GoogleSignIn SDK requires keychain sharing to be enabled, by [adding the following entitlements](https://docs.flutter.dev/platform-integration/macos/building#entitlements-and-the-app-sandbox): ```xml <key>keychain-access-groups</key> <array> <string>$(AppIdentifierPrefix)com.google.GIDSignIn</string> </array> ``` Without this step, the plugin will throw a `keychain error` `PlatformException` when trying to sign in. [1]: https://pub.dev/packages/google_sign_in [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin ### iOS integration 1. [Create a Firebase project](https://firebase.google.com/docs/ios/setup#create-firebase-project) and [register your application](https://firebase.google.com/docs/ios/setup#register-app). 2. [Enable Google Sign-In for your Firebase project](https://firebase.google.com/docs/auth/ios/google-signin#enable_google_sign-in_for_your_firebase_project). 3. Make sure to download a new copy of your project's `GoogleService-Info.plist` from step 2. Do not put this file in your project. 4. Add the client ID from the `GoogleService-Info.plist` into your app's `[my_project]/ios/Runner/Info.plist` file. ```xml <key>GIDClientID</key> <!-- TODO Replace this value: --> <!-- Copied from GoogleService-Info.plist key CLIENT_ID --> <string>[YOUR IOS CLIENT ID]</string> ``` 5. If you need to authenticate to a backend server you can add a `GIDServerClientID` key value pair in your `[my_project]/ios/Runner/Info.plist` file. ```xml <key>GIDServerClientID</key> <string>[YOUR SERVER CLIENT ID]</string> ``` 6. Then add the `CFBundleURLTypes` attributes below into the `[my_project]/ios/Runner/Info.plist` file. ```xml <!-- Put me in the [my_project]/ios/Runner/Info.plist file --> <!-- Google Sign-in Section --> <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLSchemes</key> <array> <!-- TODO Replace this value: --> <!-- Copied from GoogleService-Info.plist key REVERSED_CLIENT_ID --> <string>com.googleusercontent.apps.861823949799-vc35cprkp249096uujjn0vvnmcvjppkn</string> </array> </dict> </array> <!-- End of the Google Sign-in Section --> ``` As an alternative to editing the `Info.plist` in your Xcode project, you can instead configure your app in Dart code. In this case, skip steps 4 to 5 and pass `clientId` and `serverClientId` to the `GoogleSignIn` constructor: <?code-excerpt "../google_sign_in/test/google_sign_in_test.dart (GoogleSignIn)"?> ```dart final GoogleSignIn googleSignIn = GoogleSignIn( // The OAuth client id of your app. This is required. clientId: 'Your Client ID', // If you need to authenticate to a backend server, specify its OAuth client. This is optional. serverClientId: 'Your Server ID', ); ``` Note that step 6 is still required.
packages/packages/google_sign_in/google_sign_in_ios/README.md/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_ios/README.md", "repo_id": "packages", "token_count": 1147 }
1,203
#include "Generated.xcconfig" #include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
packages/packages/google_sign_in/google_sign_in_ios/example/ios/Flutter/Debug.xcconfig/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_ios/example/ios/Flutter/Debug.xcconfig", "repo_id": "packages", "token_count": 40 }
1,204
// 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 (v11.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; /// Pigeon version of SignInInitParams. /// /// See SignInInitParams for details. class InitParams { InitParams({ required this.scopes, this.hostedDomain, this.clientId, this.serverClientId, }); List<String?> scopes; String? hostedDomain; String? clientId; String? serverClientId; Object encode() { return <Object?>[ scopes, hostedDomain, clientId, serverClientId, ]; } static InitParams decode(Object result) { result as List<Object?>; return InitParams( scopes: (result[0] as List<Object?>?)!.cast<String?>(), hostedDomain: result[1] as String?, clientId: result[2] as String?, serverClientId: result[3] as String?, ); } } /// Pigeon version of GoogleSignInUserData. /// /// See GoogleSignInUserData for details. class UserData { UserData({ this.displayName, required this.email, required this.userId, this.photoUrl, this.serverAuthCode, this.idToken, }); String? displayName; String email; String userId; String? photoUrl; String? serverAuthCode; String? idToken; Object encode() { return <Object?>[ displayName, email, userId, photoUrl, serverAuthCode, idToken, ]; } static UserData decode(Object result) { result as List<Object?>; return UserData( displayName: result[0] as String?, email: result[1]! as String, userId: result[2]! as String, photoUrl: result[3] as String?, serverAuthCode: result[4] as String?, idToken: result[5] as String?, ); } } /// Pigeon version of GoogleSignInTokenData. /// /// See GoogleSignInTokenData for details. class TokenData { TokenData({ this.idToken, this.accessToken, }); String? idToken; String? accessToken; Object encode() { return <Object?>[ idToken, accessToken, ]; } static TokenData decode(Object result) { result as List<Object?>; return TokenData( idToken: result[0] as String?, accessToken: result[1] as String?, ); } } class _GoogleSignInApiCodec extends StandardMessageCodec { const _GoogleSignInApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is InitParams) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is TokenData) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is UserData) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return InitParams.decode(readValue(buffer)!); case 129: return TokenData.decode(readValue(buffer)!); case 130: return UserData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class GoogleSignInApi { /// Constructor for [GoogleSignInApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. GoogleSignInApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = _GoogleSignInApiCodec(); /// Initializes a sign in request with the given parameters. Future<void> init(InitParams arg_params) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.init', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_params]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return; } } /// Starts a silent sign in. Future<UserData> signInSilently() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.signInSilently', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as UserData?)!; } } /// Starts a sign in with user interaction. Future<UserData> signIn() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.signIn', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as UserData?)!; } } /// Requests the access token for the current sign in. Future<TokenData> getAccessToken() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.getAccessToken', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as TokenData?)!; } } /// Signs out the current user. Future<void> signOut() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.signOut', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return; } } /// Revokes scope grants to the application. Future<void> disconnect() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.disconnect', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return; } } /// Returns whether the user is currently signed in. Future<bool> isSignedIn() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.isSignedIn', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Requests access to the given scopes. Future<bool> requestScopes(List<String?> arg_scopes) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.requestScopes', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_scopes]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } }
packages/packages/google_sign_in/google_sign_in_ios/lib/src/messages.g.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_ios/lib/src/messages.g.dart", "repo_id": "packages", "token_count": 4460 }
1,205
// Mocks generated by Mockito 5.4.4 from annotations // in google_sign_in_web_integration_tests/integration_test/web_only_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart' as _i2; import 'package:google_sign_in_web/src/button_configuration.dart' as _i5; import 'package:google_sign_in_web/src/gis_client.dart' as _i3; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: 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 _FakeGoogleSignInTokenData_0 extends _i1.SmartFake implements _i2.GoogleSignInTokenData { _FakeGoogleSignInTokenData_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [GisSdkClient]. /// /// See the documentation for Mockito's code generation for more information. class MockGisSdkClient extends _i1.Mock implements _i3.GisSdkClient { @override _i4.Future<_i2.GoogleSignInUserData?> signInSilently() => (super.noSuchMethod( Invocation.method( #signInSilently, [], ), returnValue: _i4.Future<_i2.GoogleSignInUserData?>.value(), returnValueForMissingStub: _i4.Future<_i2.GoogleSignInUserData?>.value(), ) as _i4.Future<_i2.GoogleSignInUserData?>); @override _i4.Future<void> renderButton( Object? parent, _i5.GSIButtonConfiguration? options, ) => (super.noSuchMethod( Invocation.method( #renderButton, [ parent, options, ], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<String?> requestServerAuthCode() => (super.noSuchMethod( Invocation.method( #requestServerAuthCode, [], ), returnValue: _i4.Future<String?>.value(), returnValueForMissingStub: _i4.Future<String?>.value(), ) as _i4.Future<String?>); @override _i4.Future<_i2.GoogleSignInUserData?> signIn() => (super.noSuchMethod( Invocation.method( #signIn, [], ), returnValue: _i4.Future<_i2.GoogleSignInUserData?>.value(), returnValueForMissingStub: _i4.Future<_i2.GoogleSignInUserData?>.value(), ) as _i4.Future<_i2.GoogleSignInUserData?>); @override _i2.GoogleSignInTokenData getTokens() => (super.noSuchMethod( Invocation.method( #getTokens, [], ), returnValue: _FakeGoogleSignInTokenData_0( this, Invocation.method( #getTokens, [], ), ), returnValueForMissingStub: _FakeGoogleSignInTokenData_0( this, Invocation.method( #getTokens, [], ), ), ) as _i2.GoogleSignInTokenData); @override _i4.Future<void> signOut() => (super.noSuchMethod( Invocation.method( #signOut, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<void> disconnect() => (super.noSuchMethod( Invocation.method( #disconnect, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool> isSignedIn() => (super.noSuchMethod( Invocation.method( #isSignedIn, [], ), returnValue: _i4.Future<bool>.value(false), returnValueForMissingStub: _i4.Future<bool>.value(false), ) as _i4.Future<bool>); @override _i4.Future<void> clearAuthCache() => (super.noSuchMethod( Invocation.method( #clearAuthCache, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool> requestScopes(List<String>? scopes) => (super.noSuchMethod( Invocation.method( #requestScopes, [scopes], ), returnValue: _i4.Future<bool>.value(false), returnValueForMissingStub: _i4.Future<bool>.value(false), ) as _i4.Future<bool>); @override _i4.Future<bool> canAccessScopes( List<String>? scopes, String? accessToken, ) => (super.noSuchMethod( Invocation.method( #canAccessScopes, [ scopes, accessToken, ], ), returnValue: _i4.Future<bool>.value(false), returnValueForMissingStub: _i4.Future<bool>.value(false), ) as _i4.Future<bool>); }
packages/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.mocks.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.mocks.dart", "repo_id": "packages", "token_count": 2496 }
1,206
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: avoid_print import 'package:flutter_test/flutter_test.dart'; void main() { test('Tell the user where to find the real tests', () { print('---'); print('This package uses integration_test for its tests.'); print('See `example/README.md` for more info.'); print('---'); }); }
packages/packages/google_sign_in/google_sign_in_web/test/tests_exist_elsewhere_test.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_web/test/tests_exist_elsewhere_test.dart", "repo_id": "packages", "token_count": 152 }
1,207
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter_window.h" #include <optional> #include "flutter/generated_plugin_registrant.h" FlutterWindow::FlutterWindow(const flutter::DartProject& project) : project_(project) {} FlutterWindow::~FlutterWindow() {} bool FlutterWindow::OnCreate() { if (!Win32Window::OnCreate()) { return false; } RECT frame = GetClientArea(); // The size here must match the window dimensions to avoid unnecessary surface // creation / destruction in the startup path. flutter_controller_ = std::make_unique<flutter::FlutterViewController>( frame.right - frame.left, frame.bottom - frame.top, project_); // Ensure that basic setup of the controller was successful. if (!flutter_controller_->engine() || !flutter_controller_->view()) { return false; } RegisterPlugins(flutter_controller_->engine()); SetChildContent(flutter_controller_->view()->GetNativeWindow()); flutter_controller_->engine()->SetNextFrameCallback([&]() { this->Show(); }); return true; } void FlutterWindow::OnDestroy() { if (flutter_controller_) { flutter_controller_ = nullptr; } Win32Window::OnDestroy(); } LRESULT FlutterWindow::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { // Give Flutter, including plugins, an opportunity to handle window messages. if (flutter_controller_) { std::optional<LRESULT> result = flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, lparam); if (result) { return *result; } } switch (message) { case WM_FONTCHANGE: flutter_controller_->engine()->ReloadSystemFonts(); break; } return Win32Window::MessageHandler(hwnd, message, wparam, lparam); }
packages/packages/image_picker/image_picker/example/windows/runner/flutter_window.cpp/0
{ "file_path": "packages/packages/image_picker/image_picker/example/windows/runner/flutter_window.cpp", "repo_id": "packages", "token_count": 727 }
1,208
<?xml version="1.0" encoding="utf-8"?> <paths> <cache-path name="cached_files" path="."/> </paths>
packages/packages/image_picker/image_picker_android/android/src/main/res/xml/flutter_image_picker_file_paths.xml/0
{ "file_path": "packages/packages/image_picker/image_picker_android/android/src/main/res/xml/flutter_image_picker_file_paths.xml", "repo_id": "packages", "token_count": 45 }
1,209
// 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; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * Annotation to aid repository tooling in determining if a test is * a native java unit test or a java class with a dart integration. * * See: https://github.com/flutter/flutter/wiki/Plugin-Tests#enabling-android-ui-tests * for more infomation. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface DartIntegrationTest {}
packages/packages/image_picker/image_picker_android/example/android/app/src/androidTest/java/io/flutter/plugins/DartIntegrationTest.java/0
{ "file_path": "packages/packages/image_picker/image_picker_android/example/android/app/src/androidTest/java/io/flutter/plugins/DartIntegrationTest.java", "repo_id": "packages", "token_count": 208 }
1,210
## 3.0.3 * Migrates package and tests to `package:web`. * Updates minimum supported SDK version to Flutter 3.19/Dart 3.3. ## 3.0.2 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Removes input element after completion ## 3.0.1 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 3.0.0 * **BREAKING CHANGE:** Removes all code and tests mentioning `PickedFile`. * Listens to `cancel` event on file selection. When the selection is canceled: * `Future<XFile?>` methods return `null` * `Future<List<XFile>>` methods return an empty list. ## 2.2.0 * Adds `getMedia` method. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 2.1.12 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 2.1.11 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 2.1.10 * Updates code for `no_leading_underscores_for_local_identifiers` lint. ## 2.1.9 * Updates imports for `prefer_relative_imports`. * Updates minimum Flutter version to 2.10. * Fixes violations of new analysis option use_named_constants. ## 2.1.8 * Minor fixes for new analysis options. ## 2.1.7 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 2.1.6 * Internal code cleanup for stricter analysis options. ## 2.1.5 * Removes dependency on `meta`. ## 2.1.4 * Implemented `maxWidth`, `maxHeight` and `imageQuality` when selecting images (except for gifs). ## 2.1.3 * Add `implements` to pubspec. ## 2.1.2 * Updated installation instructions in README. # 2.1.1 * Implemented `getMultiImage`. * Initialized the following `XFile` attributes for picked files: * `name`, `length`, `mimeType` and `lastModified`. # 2.1.0 * Implemented `getImage`, `getVideo` and `getFile` methods that return `XFile` instances. * Move tests to `example` directory, so they run as integration_tests with `flutter drive`. # 2.0.0 * Migrate to null safety. * Add doc comments to point out that some arguments aren't supported on the web. # 0.1.0+3 * Update Flutter SDK constraint. # 0.1.0+2 * Adds Video MIME Types for the safari browser for acception # 0.1.0+1 * Remove `android` directory. # 0.1.0 * Initial open-source release.
packages/packages/image_picker/image_picker_for_web/CHANGELOG.md/0
{ "file_path": "packages/packages/image_picker/image_picker_for_web/CHANGELOG.md", "repo_id": "packages", "token_count": 802 }
1,211
// 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:ui'; import 'package:flutter_test/flutter_test.dart'; import 'package:image_picker_for_web/src/image_resizer_utils.dart'; void main() { group('Image Resizer Utils', () { group('calculateSizeOfScaledImage', () { test( "scaled image height and width are same if max width and max height are same as image's width and height", () { expect(calculateSizeOfDownScaledImage(const Size(500, 300), 500, 300), const Size(500, 300)); }); test( 'scaled image height and width are same if max width and max height are null', () { expect(calculateSizeOfDownScaledImage(const Size(500, 300), null, null), const Size(500, 300)); }); test('image size is scaled when maxWidth is set', () { const Size imageSize = Size(500, 300); const int maxWidth = 400; final Size scaledSize = calculateSizeOfDownScaledImage( Size(imageSize.width, imageSize.height), maxWidth.toDouble(), null); expect(scaledSize.height <= imageSize.height, true); expect(scaledSize.width <= maxWidth, true); }); test('image size is scaled when maxHeight is set', () { const Size imageSize = Size(500, 300); const int maxHeight = 400; final Size scaledSize = calculateSizeOfDownScaledImage( Size(imageSize.width, imageSize.height), null, maxHeight.toDouble()); expect(scaledSize.height <= maxHeight, true); expect(scaledSize.width <= imageSize.width, true); }); test('image size is scaled when both maxWidth and maxHeight is set', () { const Size imageSize = Size(1120, 2000); const int maxHeight = 1200; const int maxWidth = 99; final Size scaledSize = calculateSizeOfDownScaledImage( Size(imageSize.width, imageSize.height), maxWidth.toDouble(), maxHeight.toDouble()); expect(scaledSize.height <= maxHeight, true); expect(scaledSize.width <= maxWidth, true); }); }); group('imageResizeNeeded', () { test('image needs to be resized when maxWidth is set', () { expect(imageResizeNeeded(50, null, null), true); }); test('image needs to be resized when maxHeight is set', () { expect(imageResizeNeeded(null, 50, null), true); }); test('image needs to be resized when imageQuality is set', () { expect(imageResizeNeeded(null, null, 100), true); }); test('image will not be resized when imageQuality is not valid', () { expect(imageResizeNeeded(null, null, 101), false); expect(imageResizeNeeded(null, null, -1), false); }); }); group('isImageQualityValid', () { test('image quality is valid in 0 to 100', () { expect(isImageQualityValid(50), true); expect(isImageQualityValid(0), true); expect(isImageQualityValid(100), true); }); test( 'image quality is not valid when imageQuality is less than 0 or greater than 100', () { expect(isImageQualityValid(-1), false); expect(isImageQualityValid(101), false); }); }); }); }
packages/packages/image_picker/image_picker_for_web/test/image_resizer_utils_test.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_for_web/test/image_resizer_utils_test.dart", "repo_id": "packages", "token_count": 1351 }
1,212
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <OCMock/OCMock.h> @import image_picker_ios; @import image_picker_ios.Test; @import UniformTypeIdentifiers; @import XCTest; @interface PickerSaveImageToPathOperationTests : XCTestCase @end @implementation PickerSaveImageToPathOperationTests - (void)testSaveWebPImage API_AVAILABLE(ios(14)) { NSURL *imageURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"webpImage" withExtension:@"webp"]; NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithContentsOfURL:imageURL]; PHPickerResult *result = [self createPickerResultWithProvider:itemProvider]; [self verifySavingImageWithPickerResult:result fullMetadata:YES withExtension:@"jpg"]; } - (void)testSavePNGImage API_AVAILABLE(ios(14)) { NSURL *imageURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"pngImage" withExtension:@"png"]; NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithContentsOfURL:imageURL]; PHPickerResult *result = [self createPickerResultWithProvider:itemProvider]; [self verifySavingImageWithPickerResult:result fullMetadata:YES withExtension:@"png"]; } - (void)testSaveJPGImage API_AVAILABLE(ios(14)) { NSURL *imageURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"jpgImage" withExtension:@"jpg"]; NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithContentsOfURL:imageURL]; PHPickerResult *result = [self createPickerResultWithProvider:itemProvider]; [self verifySavingImageWithPickerResult:result fullMetadata:YES withExtension:@"jpg"]; } - (void)testSaveGIFImage API_AVAILABLE(ios(14)) { NSURL *imageURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"gifImage" withExtension:@"gif"]; NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithContentsOfURL:imageURL]; PHPickerResult *result = [self createPickerResultWithProvider:itemProvider]; NSData *dataGIF = [NSData dataWithContentsOfURL:imageURL]; CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)dataGIF, nil); size_t numberOfFrames = CGImageSourceGetCount(imageSource); XCTestExpectation *pathExpectation = [self expectationWithDescription:@"Path was created"]; XCTestExpectation *operationExpectation = [self expectationWithDescription:@"Operation completed"]; FLTPHPickerSaveImageToPathOperation *operation = [[FLTPHPickerSaveImageToPathOperation alloc] initWithResult:result maxHeight:@100 maxWidth:@100 desiredImageQuality:@100 fullMetadata:NO savedPathBlock:^(NSString *savedPath, FlutterError *error) { XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:savedPath]); // Ensure gif is animated. XCTAssertEqualObjects([NSURL URLWithString:savedPath].pathExtension, @"gif"); NSData *newDataGIF = [NSData dataWithContentsOfFile:savedPath]; CGImageSourceRef newImageSource = CGImageSourceCreateWithData((__bridge CFDataRef)newDataGIF, nil); size_t newNumberOfFrames = CGImageSourceGetCount(newImageSource); XCTAssertEqual(numberOfFrames, newNumberOfFrames); [pathExpectation fulfill]; }]; operation.completionBlock = ^{ [operationExpectation fulfill]; }; [operation start]; [self waitForExpectationsWithTimeout:30 handler:nil]; XCTAssertTrue(operation.isFinished); } - (void)testSaveBMPImage API_AVAILABLE(ios(14)) { NSURL *imageURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"bmpImage" withExtension:@"bmp"]; NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithContentsOfURL:imageURL]; PHPickerResult *result = [self createPickerResultWithProvider:itemProvider]; [self verifySavingImageWithPickerResult:result fullMetadata:YES withExtension:@"jpg"]; } - (void)testSaveHEICImage API_AVAILABLE(ios(14)) { NSURL *imageURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"heicImage" withExtension:@"heic"]; NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithContentsOfURL:imageURL]; PHPickerResult *result = [self createPickerResultWithProvider:itemProvider]; [self verifySavingImageWithPickerResult:result fullMetadata:YES withExtension:@"jpg"]; } - (void)testSaveWithOrientation API_AVAILABLE(ios(14)) { NSURL *imageURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"jpgImageWithRightOrientation" withExtension:@"jpg"]; NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithContentsOfURL:imageURL]; PHPickerResult *result = [self createPickerResultWithProvider:itemProvider]; XCTestExpectation *pathExpectation = [self expectationWithDescription:@"Path was created"]; XCTestExpectation *operationExpectation = [self expectationWithDescription:@"Operation completed"]; FLTPHPickerSaveImageToPathOperation *operation = [[FLTPHPickerSaveImageToPathOperation alloc] initWithResult:result maxHeight:@10 maxWidth:@10 desiredImageQuality:@100 fullMetadata:NO savedPathBlock:^(NSString *savedPath, FlutterError *error) { XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:savedPath]); // Ensure image retained it's orientation data. XCTAssertEqualObjects([NSURL URLWithString:savedPath].pathExtension, @"jpg"); UIImage *image = [UIImage imageWithContentsOfFile:savedPath]; XCTAssertEqual(image.imageOrientation, UIImageOrientationRight); XCTAssertEqual(image.size.width, 7); XCTAssertEqual(image.size.height, 10); [pathExpectation fulfill]; }]; operation.completionBlock = ^{ [operationExpectation fulfill]; }; [operation start]; [self waitForExpectationsWithTimeout:30 handler:nil]; XCTAssertTrue(operation.isFinished); } - (void)testSaveICNSImage API_AVAILABLE(ios(14)) { NSURL *imageURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"icnsImage" withExtension:@"icns"]; NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithContentsOfURL:imageURL]; PHPickerResult *result = [self createPickerResultWithProvider:itemProvider]; [self verifySavingImageWithPickerResult:result fullMetadata:YES withExtension:@"jpg"]; } - (void)testSaveICOImage API_AVAILABLE(ios(14)) { NSURL *imageURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"icoImage" withExtension:@"ico"]; NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithContentsOfURL:imageURL]; PHPickerResult *result = [self createPickerResultWithProvider:itemProvider]; [self verifySavingImageWithPickerResult:result fullMetadata:YES withExtension:@"jpg"]; } - (void)testSaveProRAWImage API_AVAILABLE(ios(14)) { NSURL *imageURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"proRawImage" withExtension:@"dng"]; NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithContentsOfURL:imageURL]; PHPickerResult *result = [self createPickerResultWithProvider:itemProvider]; [self verifySavingImageWithPickerResult:result fullMetadata:YES withExtension:@"jpg"]; } - (void)testSaveTIFFImage API_AVAILABLE(ios(14)) { NSURL *imageURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"tiffImage" withExtension:@"tiff"]; NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithContentsOfURL:imageURL]; PHPickerResult *result = [self createPickerResultWithProvider:itemProvider]; [self verifySavingImageWithPickerResult:result fullMetadata:YES withExtension:@"jpg"]; } - (void)testNonexistentImage API_AVAILABLE(ios(14)) { NSURL *imageURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"bogus" withExtension:@"png"]; NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithContentsOfURL:imageURL]; PHPickerResult *result = [self createPickerResultWithProvider:itemProvider]; XCTestExpectation *errorExpectation = [self expectationWithDescription:@"invalid source error"]; FLTPHPickerSaveImageToPathOperation *operation = [[FLTPHPickerSaveImageToPathOperation alloc] initWithResult:result maxHeight:@100 maxWidth:@100 desiredImageQuality:@100 fullMetadata:YES savedPathBlock:^(NSString *savedPath, FlutterError *error) { XCTAssertEqualObjects(error.code, @"invalid_source"); [errorExpectation fulfill]; }]; [operation start]; [self waitForExpectationsWithTimeout:30 handler:nil]; } - (void)testFailingImageLoad API_AVAILABLE(ios(14)) { NSError *loadDataError = [NSError errorWithDomain:@"PHPickerDomain" code:1234 userInfo:nil]; id mockItemProvider = OCMClassMock([NSItemProvider class]); OCMStub([mockItemProvider hasItemConformingToTypeIdentifier:OCMOCK_ANY]).andReturn(YES); [[mockItemProvider stub] loadDataRepresentationForTypeIdentifier:OCMOCK_ANY completionHandler:[OCMArg invokeBlockWithArgs:[NSNull null], loadDataError, nil]]; id pickerResult = OCMClassMock([PHPickerResult class]); OCMStub([pickerResult itemProvider]).andReturn(mockItemProvider); XCTestExpectation *errorExpectation = [self expectationWithDescription:@"invalid image error"]; FLTPHPickerSaveImageToPathOperation *operation = [[FLTPHPickerSaveImageToPathOperation alloc] initWithResult:pickerResult maxHeight:@100 maxWidth:@100 desiredImageQuality:@100 fullMetadata:YES savedPathBlock:^(NSString *savedPath, FlutterError *error) { XCTAssertEqualObjects(error.code, @"invalid_image"); XCTAssertEqualObjects(error.message, loadDataError.localizedDescription); XCTAssertEqualObjects(error.details, @"PHPickerDomain"); [errorExpectation fulfill]; }]; [operation start]; [self waitForExpectationsWithTimeout:30 handler:nil]; } - (void)testSavePNGImageWithoutFullMetadata API_AVAILABLE(ios(14)) { id photoAssetUtil = OCMClassMock([PHAsset class]); NSURL *imageURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"pngImage" withExtension:@"png"]; NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithContentsOfURL:imageURL]; PHPickerResult *result = [self createPickerResultWithProvider:itemProvider]; OCMReject([photoAssetUtil fetchAssetsWithLocalIdentifiers:OCMOCK_ANY options:OCMOCK_ANY]); [self verifySavingImageWithPickerResult:result fullMetadata:NO withExtension:@"png"]; OCMVerifyAll(photoAssetUtil); } /** * Creates a mock picker result using NSItemProvider. * * @param itemProvider an item provider that will be used as picker result */ - (PHPickerResult *)createPickerResultWithProvider:(NSItemProvider *)itemProvider API_AVAILABLE(ios(14)) { PHPickerResult *result = OCMClassMock([PHPickerResult class]); OCMStub([result itemProvider]).andReturn(itemProvider); OCMStub([result assetIdentifier]).andReturn(itemProvider.registeredTypeIdentifiers.firstObject); return result; } /** * Validates a saving process of FLTPHPickerSaveImageToPathOperation. * * FLTPHPickerSaveImageToPathOperation is responsible for saving a picked image to the disk for * later use. It is expected that the saving is always successful. * * @param result the picker result */ - (void)verifySavingImageWithPickerResult:(PHPickerResult *)result fullMetadata:(BOOL)fullMetadata withExtension:(NSString *)extension API_AVAILABLE(ios(14)) { XCTestExpectation *pathExpectation = [self expectationWithDescription:@"Path was created"]; XCTestExpectation *operationExpectation = [self expectationWithDescription:@"Operation completed"]; FLTPHPickerSaveImageToPathOperation *operation = [[FLTPHPickerSaveImageToPathOperation alloc] initWithResult:result maxHeight:@100 maxWidth:@100 desiredImageQuality:@100 fullMetadata:fullMetadata savedPathBlock:^(NSString *savedPath, FlutterError *error) { XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:savedPath]); XCTAssertEqualObjects([NSURL URLWithString:savedPath].pathExtension, extension); [pathExpectation fulfill]; }]; operation.completionBlock = ^{ [operationExpectation fulfill]; }; [operation start]; [self waitForExpectationsWithTimeout:30 handler:nil]; XCTAssertTrue(operation.isFinished); } @end
packages/packages/image_picker/image_picker_ios/example/ios/RunnerTests/PickerSaveImageToPathOperationTests.m/0
{ "file_path": "packages/packages/image_picker/image_picker_ios/example/ios/RunnerTests/PickerSaveImageToPathOperationTests.m", "repo_id": "packages", "token_count": 5397 }
1,213
framework module image_picker_ios { umbrella header "image_picker_ios-umbrella.h" export * module * { export * } explicit module Test { header "FLTImagePickerPlugin_Test.h" header "FLTImagePickerImageUtil.h" header "FLTImagePickerMetaDataUtil.h" header "FLTImagePickerPhotoAssetUtil.h" header "FLTPHPickerSaveImageToPathOperation.h" } }
packages/packages/image_picker/image_picker_ios/ios/Classes/ImagePickerPlugin.modulemap/0
{ "file_path": "packages/packages/image_picker/image_picker_ios/ios/Classes/ImagePickerPlugin.modulemap", "repo_id": "packages", "token_count": 138 }
1,214
# image\_picker\_linux A Linux implementation of [`image_picker`][1]. ## Limitations `ImageSource.camera` is not supported unless a `cameraDelegate` is set. ### pickImage() The arguments `maxWidth`, `maxHeight`, and `imageQuality` are not currently supported. ### pickVideo() The argument `maxDuration` is not currently supported. ## Usage ### Import the package This package is [endorsed][2], which means you can simply use `file_selector` normally. This package will be automatically included in your app when you do, so you do not need to add it to your `pubspec.yaml`. However, if you `import` this package to use any of its APIs directly, you should add it to your `pubspec.yaml` as usual. [1]: https://pub.dev/packages/image_picker [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
packages/packages/image_picker/image_picker_linux/README.md/0
{ "file_path": "packages/packages/image_picker/image_picker_linux/README.md", "repo_id": "packages", "token_count": 254 }
1,215
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 0.2.1+1 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 0.2.1 * Adds `getMedia` method. ## 0.2.0 * Implements initial macOS support.
packages/packages/image_picker/image_picker_macos/CHANGELOG.md/0
{ "file_path": "packages/packages/image_picker/image_picker_macos/CHANGELOG.md", "repo_id": "packages", "token_count": 100 }
1,216
name: example description: Example for image_picker_macos implementation. publish_to: 'none' version: 1.0.0 environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: flutter: sdk: flutter image_picker_macos: # When depending on this package from a real application you should use: # image_picker_macos: ^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: .. image_picker_platform_interface: ^2.8.0 mime: ^1.0.4 video_player: ^2.1.4 dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true
packages/packages/image_picker/image_picker_macos/example/pubspec.yaml/0
{ "file_path": "packages/packages/image_picker/image_picker_macos/example/pubspec.yaml", "repo_id": "packages", "token_count": 277 }
1,217
// 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:cross_file/cross_file.dart'; import 'package:flutter/services.dart'; import 'types.dart'; /// The response object of [ImagePicker.getLostData]. /// /// Only applies to Android. /// See also: /// * [ImagePicker.getLostData] for more details on retrieving lost data. class LostDataResponse { /// Creates an instance with the given [file], [exception], and [type]. Any of /// the params may be null, but this is never considered to be empty. LostDataResponse({ this.file, this.exception, this.type, this.files, }); /// Initializes an instance with all member params set to null and considered /// to be empty. LostDataResponse.empty() : file = null, exception = null, type = null, _empty = true, files = null; /// Whether it is an empty response. /// /// An empty response should have [file], [exception] and [type] to be null. bool get isEmpty => _empty; /// The file that was lost in a previous [getImage], [getMultiImage], /// [getVideo] or [getMedia] call due to MainActivity being destroyed. /// /// Can be null if [exception] exists. final XFile? file; /// The exception of the last [getImage], [getMultiImage] or [getVideo]. /// /// If the last [getImage], [getMultiImage] or [getVideo] threw some exception before the MainActivity destruction, /// this variable keeps that exception. /// You should handle this exception as if the [getImage], [getMultiImage] or [getVideo] got an exception when /// the MainActivity was not destroyed. /// /// Note that it is not the exception that caused the destruction of the MainActivity. final PlatformException? exception; /// Can either be [RetrieveType.image], [RetrieveType.video], or [RetrieveType.media]. /// /// If the lost data is empty, this will be null. final RetrieveType? type; bool _empty = false; /// The list of files that were lost in a previous [getMultiImage] call due to MainActivity being destroyed. /// /// When [files] is populated, [file] will refer to the last item in the [files] list. /// /// Can be null if [exception] exists. final List<XFile>? files; }
packages/packages/image_picker/image_picker_platform_interface/lib/src/types/lost_data_response.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_platform_interface/lib/src/types/lost_data_response.dart", "repo_id": "packages", "token_count": 699 }
1,218
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @TestOn('chrome') // Uses web-only Flutter SDK library; import 'dart:convert'; import 'dart:html' as html; import 'package:flutter_test/flutter_test.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; const String expectedStringContents = 'Hello, world!'; final List<int> bytes = utf8.encode(expectedStringContents); final html.File textFile = html.File(<List<int>>[bytes], 'hello.txt'); final String textFileUrl = html.Url.createObjectUrl(textFile); void main() { group('Create with an objectUrl', () { final PickedFile pickedFile = PickedFile(textFileUrl); test('Can be read as a string', () async { expect(await pickedFile.readAsString(), equals(expectedStringContents)); }); test('Can be read as bytes', () async { expect(await pickedFile.readAsBytes(), equals(bytes)); }); test('Can be read as a stream', () async { expect(await pickedFile.openRead().first, equals(bytes)); }); test('Stream can be sliced', () async { expect( await pickedFile.openRead(2, 5).first, equals(bytes.sublist(2, 5))); }); }); }
packages/packages/image_picker/image_picker_platform_interface/test/picked_file_html_test.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_platform_interface/test/picked_file_html_test.dart", "repo_id": "packages", "token_count": 434 }
1,219
A storefront-independent API for purchases in Flutter apps. <!-- If this package were in its own repo, we'd put badges here --> This plugin supports in-app purchases (_IAP_) through an _underlying store_, which can be the App Store (on iOS and macOS) or Google Play (on Android). | | Android | iOS | macOS | |-------------|---------|-------|--------| | **Support** | SDK 16+ | 12.0+ | 10.15+ | <p> <img src="https://github.com/flutter/packages/blob/main/packages/in_app_purchase/in_app_purchase/doc/iap_ios.gif?raw=true" alt="An animated image of the iOS in-app purchase UI" height="400"/> &nbsp;&nbsp;&nbsp;&nbsp; <img src="https://github.com/flutter/packages/blob/main/packages/in_app_purchase/in_app_purchase/doc/iap_android.gif?raw=true" alt="An animated image of the Android in-app purchase UI" height="400"/> </p> ## Features Use this plugin in your Flutter app to: * Show in-app products that are available for sale from the underlying store. Products can include consumables, permanent upgrades, and subscriptions. * Load in-app products that the user owns. * Send the user to the underlying store to purchase products. * Present a UI for redeeming subscription offer codes. (iOS 14 only) ## Getting started This plugin relies on the App Store and Google Play for making in-app purchases. It exposes a unified surface, but you still need to understand and configure your app with each store. Both stores have extensive guides: * [App Store documentation](https://developer.apple.com/in-app-purchase/) * [Google Play documentation](https://developer.android.com/google/play/billing/billing_overview) > NOTE: Further in this document the App Store and Google Play will be referred > to as "the store" or "the underlying store", except when a feature is specific > to a particular store. For a list of steps for configuring in-app purchases in both stores, see the [example app README](https://github.com/flutter/packages/blob/main/packages/in_app_purchase/in_app_purchase/example/README.md). Once you've configured your in-app purchases in their respective stores, you can start using the plugin. Two basic options are available: 1. A generic, idiomatic Flutter API: [in_app_purchase](https://pub.dev/documentation/in_app_purchase/latest/in_app_purchase/in_app_purchase-library.html). This API supports most use cases for loading and making purchases. 2. Platform-specific Dart APIs: [store_kit_wrappers](https://pub.dev/documentation/in_app_purchase_storekit/latest/store_kit_wrappers/store_kit_wrappers-library.html) and [billing_client_wrappers](https://pub.dev/documentation/in_app_purchase_android/latest/billing_client_wrappers/billing_client_wrappers-library.html). These APIs expose platform-specific behavior and allow for more fine-tuned control when needed. However, if you use one of these APIs, your purchase-handling logic is significantly different for the different storefronts. See also the codelab for [in-app purchases in Flutter](https://codelabs.developers.google.com/codelabs/flutter-in-app-purchases) for a detailed guide on adding in-app purchase support to a Flutter App. ## Usage This section has examples of code for the following tasks: * [Listening to purchase updates](#listening-to-purchase-updates) * [Connecting to the underlying store](#connecting-to-the-underlying-store) * [Loading products for sale](#loading-products-for-sale) * [Restoring previous purchases](#restoring-previous-purchases) * [Making a purchase](#making-a-purchase) * [Completing a purchase](#completing-a-purchase) * [Upgrading or downgrading an existing in-app subscription](#upgrading-or-downgrading-an-existing-in-app-subscription) * [Accessing platform specific product or purchase properties](#accessing-platform-specific-product-or-purchase-properties) * [Presenting a code redemption sheet (iOS 14)](#presenting-a-code-redemption-sheet-ios-14) **Note:** It is not necessary to depend on `com.android.billingclient:billing` in your own app's `android/app/build.gradle` file. If you choose to do so know that conflicts might occur. ### Listening to purchase updates In your app's `initState` method, subscribe to any incoming purchases. These can propagate from either underlying store. You should always start listening to purchase update as early as possible to be able to catch all purchase updates, including the ones from the previous app session. To listen to the update: ```dart class _MyAppState extends State<MyApp> { StreamSubscription<List<PurchaseDetails>> _subscription; @override void initState() { final Stream purchaseUpdated = InAppPurchase.instance.purchaseStream; _subscription = purchaseUpdated.listen((purchaseDetailsList) { _listenToPurchaseUpdated(purchaseDetailsList); }, onDone: () { _subscription.cancel(); }, onError: (error) { // handle error here. }); super.initState(); } @override void dispose() { _subscription.cancel(); super.dispose(); } ``` Here is an example of how to handle purchase updates: ```dart void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) { purchaseDetailsList.forEach((PurchaseDetails purchaseDetails) async { if (purchaseDetails.status == PurchaseStatus.pending) { _showPendingUI(); } else { if (purchaseDetails.status == PurchaseStatus.error) { _handleError(purchaseDetails.error!); } else if (purchaseDetails.status == PurchaseStatus.purchased || purchaseDetails.status == PurchaseStatus.restored) { bool valid = await _verifyPurchase(purchaseDetails); if (valid) { _deliverProduct(purchaseDetails); } else { _handleInvalidPurchase(purchaseDetails); } } if (purchaseDetails.pendingCompletePurchase) { await InAppPurchase.instance .completePurchase(purchaseDetails); } } }); } ``` ### Connecting to the underlying store ```dart final bool available = await InAppPurchase.instance.isAvailable(); if (!available) { // The store cannot be reached or accessed. Update the UI accordingly. } ``` ### Loading products for sale ```dart // Set literals require Dart 2.2. Alternatively, use // `Set<String> _kIds = <String>['product1', 'product2'].toSet()`. const Set<String> _kIds = <String>{'product1', 'product2'}; final ProductDetailsResponse response = await InAppPurchase.instance.queryProductDetails(_kIds); if (response.notFoundIDs.isNotEmpty) { // Handle the error. } List<ProductDetails> products = response.productDetails; ``` ### Restoring previous purchases Restored purchases will be emitted on the `InAppPurchase.purchaseStream`, make sure to validate restored purchases following the best practices for each underlying store: * [Verifying App Store purchases](https://developer.apple.com/documentation/storekit/in-app_purchase/validating_receipts_with_the_app_store) * [Verifying Google Play purchases](https://developer.android.com/google/play/billing/security#verify) ```dart await InAppPurchase.instance.restorePurchases(); ``` Note that the App Store does not have any APIs for querying consumable products, and Google Play considers consumable products to no longer be owned once they're marked as consumed and fails to return them here. For restoring these across devices you'll need to persist them on your own server and query that as well. ### Making a purchase Both underlying stores handle consumable and non-consumable products differently. If you're using `InAppPurchase`, you need to make a distinction here and call the right purchase method for each type. ```dart final ProductDetails productDetails = ... // Saved earlier from queryProductDetails(). final PurchaseParam purchaseParam = PurchaseParam(productDetails: productDetails); if (_isConsumable(productDetails)) { InAppPurchase.instance.buyConsumable(purchaseParam: purchaseParam); } else { InAppPurchase.instance.buyNonConsumable(purchaseParam: purchaseParam); } // From here the purchase flow will be handled by the underlying store. // Updates will be delivered to the `InAppPurchase.instance.purchaseStream`. ``` ### Completing a purchase The `InAppPurchase.purchaseStream` will send purchase updates after initiating the purchase flow using `InAppPurchase.buyConsumable` or `InAppPurchase.buyNonConsumable`. After verifying the purchase receipt and the delivering the content to the user it is important to call `InAppPurchase.completePurchase` to tell the underlying store that the purchase has been completed. Calling `InAppPurchase.completePurchase` will inform the underlying store that the app verified and processed the purchase and the store can proceed to finalize the transaction and bill the end user's payment account. > **Warning:** Failure to call `InAppPurchase.completePurchase` and > get a successful response within 3 days of the purchase will result a refund. ### Upgrading or downgrading an existing in-app subscription To upgrade/downgrade an existing in-app subscription in Google Play, you need to provide an instance of `ChangeSubscriptionParam` with the old `PurchaseDetails` that the user needs to migrate from, and an optional `ProrationMode` with the `GooglePlayPurchaseParam` object while calling `InAppPurchase.buyNonConsumable`. The App Store does not require this because it provides a subscription grouping mechanism. Each subscription you offer must be assigned to a subscription group. Grouping related subscriptions together can help prevent users from accidentally purchasing multiple subscriptions. Refer to the [Creating a Subscription Group](https://developer.apple.com/app-store/subscriptions/#groups) section of [Apple's subscription guide](https://developer.apple.com/app-store/subscriptions/). ```dart final PurchaseDetails oldPurchaseDetails = ...; PurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: productDetails, changeSubscriptionParam: ChangeSubscriptionParam( oldPurchaseDetails: oldPurchaseDetails, prorationMode: ProrationMode.immediateWithTimeProration)); InAppPurchase.instance .buyNonConsumable(purchaseParam: purchaseParam); ``` ### Confirming subscription price changes When the price of a subscription is changed the consumer will need to confirm that price change. If the consumer does not confirm the price change the subscription will not be auto-renewed. By default on both iOS and Android the consumer will automatically get a popup to confirm the price change. Depending on the platform there are different ways to interact with this flow as explained in the following paragraphs. #### Google Play Store (Android) When changing the price of an existing subscription base plan or offer, existing subscribers are placed in a legacy price cohort. App developers can choose to [end a legacy price cohort](https://developer.android.com/google/play/billing/price-changes#end-legacy) and move subscribers into the current base plan price. When the new subscription base plan price is lower, Google will notify the consumer via email and notifications. The consumer will start paying the lower price next time they pay for their base plan. When the subscription price is raised, Google will automatically start notifying consumers through email and notifications 7 days after the legacy price cohort was ended. It is highly recommended to give consumers advanced notice of the price change and provide a deep link to the Play Store subscription screen to help them review the price change. The official documentation can be found [here](https://developer.android.com/google/play/billing/price-changes). #### Apple App Store (iOS) When the price of a subscription is raised iOS will also show a popup in the app. The StoreKit Payment Queue will notify the app that it wants to show a price change confirmation popup. By default the queue will get the response that it can continue and show the popup. However, it is possible to prevent this popup via the 'InAppPurchaseStoreKitPlatformAddition' and show the popup at a different time, for example after clicking a button. To know when the App Store wants to show a popup and prevent this from happening a queue delegate can be registered. The `InAppPurchaseStoreKitPlatformAddition` contains a `setDelegate(SKPaymentQueueDelegateWrapper? delegate)` function that can be used to set a delegate or remove one by setting it to `null`. ```dart //import for InAppPurchaseStoreKitPlatformAddition import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart'; Future<void> initStoreInfo() async { if (Platform.isIOS) { var iosPlatformAddition = _inAppPurchase .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>(); await iosPlatformAddition.setDelegate(ExamplePaymentQueueDelegate()); } } @override Future<void> disposeStore() { if (Platform.isIOS) { var iosPlatformAddition = _inAppPurchase .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>(); await iosPlatformAddition.setDelegate(null); } } ``` The delegate that is set should implement `SKPaymentQueueDelegateWrapper` and handle `shouldContinueTransaction` and `shouldShowPriceConsent`. When setting `shouldShowPriceConsent` to false the default popup will not be shown and the app needs to show this later. ```dart // import for SKPaymentQueueDelegateWrapper import 'package:in_app_purchase_storekit/store_kit_wrappers.dart'; class ExamplePaymentQueueDelegate implements SKPaymentQueueDelegateWrapper { @override bool shouldContinueTransaction( SKPaymentTransactionWrapper transaction, SKStorefrontWrapper storefront) { return true; } @override bool shouldShowPriceConsent() { return false; } } ``` The dialog can be shown by calling `showPriceConsentIfNeeded` on the `InAppPurchaseStoreKitPlatformAddition`. This future will complete immediately when the dialog is shown. A confirmed transaction will be delivered on the `purchaseStream`. ```dart if (Platform.isIOS) { var iapStoreKitPlatformAddition = _inAppPurchase .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>(); await iapStoreKitPlatformAddition.showPriceConsentIfNeeded(); } ``` ### Accessing platform specific product or purchase properties The function `_inAppPurchase.queryProductDetails(productIds);` provides a `ProductDetailsResponse` with a list of purchasable products of type `List<ProductDetails>`. This `ProductDetails` class is a platform independent class containing properties only available on all endorsed platforms. However, in some cases it is necessary to access platform specific properties. The `ProductDetails` instance is of subtype `GooglePlayProductDetails` when the platform is Android and `AppStoreProductDetails` on iOS. Accessing the skuDetails (on Android) or the skProduct (on iOS) provides all the information that is available in the original platform objects. This is an example on how to get the `introductoryPricePeriod` on Android: ```dart //import for GooglePlayProductDetails import 'package:in_app_purchase_android/in_app_purchase_android.dart'; //import for SkuDetailsWrapper import 'package:in_app_purchase_android/billing_client_wrappers.dart'; if (productDetails is GooglePlayProductDetails) { SkuDetailsWrapper skuDetails = (productDetails as GooglePlayProductDetails).skuDetails; print(skuDetails.introductoryPricePeriod); } ``` And this is the way to get the subscriptionGroupIdentifier of a subscription on iOS: ```dart //import for AppStoreProductDetails import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart'; //import for SKProductWrapper import 'package:in_app_purchase_storekit/store_kit_wrappers.dart'; if (productDetails is AppStoreProductDetails) { SKProductWrapper skProduct = (productDetails as AppStoreProductDetails).skProduct; print(skProduct.subscriptionGroupIdentifier); } ``` The `purchaseStream` provides objects of type `PurchaseDetails`. PurchaseDetails' provides all information that is available on all endorsed platforms, such as purchaseID and transactionDate. In addition, it is possible to access the platform specific properties. The `PurchaseDetails` object is of subtype `GooglePlayPurchaseDetails` when the platform is Android and `AppStorePurchaseDetails` on iOS. Accessing the billingClientPurchase, resp. skPaymentTransaction provides all the information that is available in the original platform objects. This is an example on how to get the `originalJson` on Android: ```dart //import for GooglePlayPurchaseDetails import 'package:in_app_purchase_android/in_app_purchase_android.dart'; //import for PurchaseWrapper import 'package:in_app_purchase_android/billing_client_wrappers.dart'; if (purchaseDetails is GooglePlayPurchaseDetails) { PurchaseWrapper billingClientPurchase = (purchaseDetails as GooglePlayPurchaseDetails).billingClientPurchase; print(billingClientPurchase.originalJson); } ``` How to get the `transactionState` of a purchase in iOS: ```dart //import for AppStorePurchaseDetails import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart'; //import for SKProductWrapper import 'package:in_app_purchase_storekit/store_kit_wrappers.dart'; if (purchaseDetails is AppStorePurchaseDetails) { SKPaymentTransactionWrapper skProduct = (purchaseDetails as AppStorePurchaseDetails).skPaymentTransaction; print(skProduct.transactionState); } ``` Please note that it is required to import `in_app_purchase_android` and/or `in_app_purchase_storekit`. ### Presenting a code redemption sheet (iOS 14) The following code brings up a sheet that enables the user to redeem offer codes that you've set up in App Store Connect. For more information on redeeming offer codes, see [Implementing Offer Codes in Your App](https://developer.apple.com/documentation/storekit/in-app_purchase/subscriptions_and_offers/implementing_offer_codes_in_your_app). ```dart InAppPurchaseStoreKitPlatformAddition iosPlatformAddition = InAppPurchase.getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>(); iosPlatformAddition.presentCodeRedemptionSheet(); ``` > **note:** The `InAppPurchaseStoreKitPlatformAddition` is defined in the `in_app_purchase_storekit.dart` > file so you need to import it into the file you will be using `InAppPurchaseStoreKitPlatformAddition`: > ```dart > import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart'; > ``` ## Contributing to this plugin If you would like to contribute to the plugin, check out our [contribution guide](https://github.com/flutter/packages/blob/main/CONTRIBUTING.md).
packages/packages/in_app_purchase/in_app_purchase/README.md/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase/README.md", "repo_id": "packages", "token_count": 5238 }
1,220
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.inapppurchase; import static io.flutter.plugins.inapppurchase.Translator.fromBillingResult; import static io.flutter.plugins.inapppurchase.Translator.fromPurchasesList; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import com.android.billingclient.api.BillingResult; import com.android.billingclient.api.Purchase; import com.android.billingclient.api.PurchasesUpdatedListener; import io.flutter.plugin.common.MethodChannel; import java.util.HashMap; import java.util.List; import java.util.Map; class PluginPurchaseListener implements PurchasesUpdatedListener { private final MethodChannel channel; @VisibleForTesting static final String ON_PURCHASES_UPDATED = "PurchasesUpdatedListener#onPurchasesUpdated(BillingResult, List<Purchase>)"; PluginPurchaseListener(MethodChannel channel) { this.channel = channel; } @Override public void onPurchasesUpdated( @NonNull BillingResult billingResult, @Nullable List<Purchase> purchases) { final Map<String, Object> callbackArgs = new HashMap<>(); callbackArgs.put("billingResult", fromBillingResult(billingResult)); callbackArgs.put("responseCode", billingResult.getResponseCode()); callbackArgs.put("purchasesList", fromPurchasesList(purchases)); channel.invokeMethod(ON_PURCHASES_UPDATED, callbackArgs); } }
packages/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/PluginPurchaseListener.java/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/PluginPurchaseListener.java", "repo_id": "packages", "token_count": 474 }
1,221
name: in_app_purchase_android_example description: Demonstrates how to use the in_app_purchase_android plugin. publish_to: none environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: flutter: sdk: flutter in_app_purchase_android: # When depending on this package from a real application you should use: # in_app_purchase_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: ../ in_app_purchase_platform_interface: ^1.0.0 shared_preferences: ^2.0.0 dev_dependencies: build_runner: ^2.4.5 flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true
packages/packages/in_app_purchase/in_app_purchase_android/example/pubspec.yaml/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/example/pubspec.yaml", "repo_id": "packages", "token_count": 305 }
1,222
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:json_annotation/json_annotation.dart'; import '../../billing_client_wrappers.dart'; // WARNING: Changes to `@JsonSerializable` classes need to be reflected in the // below generated file. Run `flutter packages pub run build_runner watch` to // rebuild and watch for further changes. part 'product_details_wrapper.g.dart'; /// Dart wrapper around [`com.android.billingclient.api.ProductDetails`](https://developer.android.com/reference/com/android/billingclient/api/ProductDetails). /// /// Contains the details of an available product in Google Play Billing. /// Represents the details of a one-time or subscription product. @JsonSerializable() @ProductTypeConverter() @immutable class ProductDetailsWrapper { /// Creates a [ProductDetailsWrapper] with the given purchase details. @visibleForTesting const ProductDetailsWrapper({ required this.description, required this.name, this.oneTimePurchaseOfferDetails, required this.productId, required this.productType, this.subscriptionOfferDetails, required this.title, }); /// Factory for creating a [ProductDetailsWrapper] from a [Map] with the /// product details. factory ProductDetailsWrapper.fromJson(Map<String, dynamic> map) => _$ProductDetailsWrapperFromJson(map); /// Textual description of the product. @JsonKey(defaultValue: '') final String description; /// The name of the product being sold. /// /// Similar to [title], but does not include the name of the app which owns /// the product. Example: 100 Gold Coins. @JsonKey(defaultValue: '') final String name; /// The offer details of a one-time purchase product. /// /// [oneTimePurchaseOfferDetails] is only set for [ProductType.inapp]. Returns /// null for [ProductType.subs]. @JsonKey(defaultValue: null) final OneTimePurchaseOfferDetailsWrapper? oneTimePurchaseOfferDetails; /// The product's id. @JsonKey(defaultValue: '') final String productId; /// The [ProductType] of the product. @JsonKey(defaultValue: ProductType.subs) final ProductType productType; /// A list containing all available offers to purchase a subscription product. /// /// [subscriptionOfferDetails] is only set for [ProductType.subs]. Returns /// null for [ProductType.inapp]. @JsonKey(defaultValue: null) final List<SubscriptionOfferDetailsWrapper>? subscriptionOfferDetails; /// The title of the product being sold. /// /// Similar to [name], but includes the name of the app which owns the /// product. Example: 100 Gold Coins (Coin selling app). @JsonKey(defaultValue: '') final String title; @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is ProductDetailsWrapper && other.description == description && other.name == name && other.oneTimePurchaseOfferDetails == oneTimePurchaseOfferDetails && other.productId == productId && other.productType == productType && listEquals(other.subscriptionOfferDetails, subscriptionOfferDetails) && other.title == title; } @override int get hashCode { return Object.hash( description.hashCode, name.hashCode, oneTimePurchaseOfferDetails.hashCode, productId.hashCode, productType.hashCode, subscriptionOfferDetails.hashCode, title.hashCode, ); } } /// Translation of [`com.android.billingclient.api.ProductDetailsResponseListener`](https://developer.android.com/reference/com/android/billingclient/api/ProductDetailsResponseListener.html). /// /// Returned by [BillingClient.queryProductDetails]. @JsonSerializable() @immutable class ProductDetailsResponseWrapper implements HasBillingResponse { /// Creates a [ProductDetailsResponseWrapper] with the given purchase details. const ProductDetailsResponseWrapper({ required this.billingResult, required this.productDetailsList, }); /// Constructs an instance of this from a key value map of data. /// /// The map needs to have named string keys with values matching the names and /// types of all of the members on this class. factory ProductDetailsResponseWrapper.fromJson(Map<String, dynamic> map) => _$ProductDetailsResponseWrapperFromJson(map); /// The final result of the [BillingClient.queryProductDetails] call. final BillingResultWrapper billingResult; /// A list of [ProductDetailsWrapper] matching the query to [BillingClient.queryProductDetails]. @JsonKey(defaultValue: <ProductDetailsWrapper>[]) final List<ProductDetailsWrapper> productDetailsList; @override BillingResponse get responseCode => billingResult.responseCode; @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is ProductDetailsResponseWrapper && other.billingResult == billingResult && other.productDetailsList == productDetailsList; } @override int get hashCode => Object.hash(billingResult, productDetailsList); } /// Recurrence mode of the pricing phase. @JsonEnum(alwaysCreate: true) enum RecurrenceMode { /// The billing plan payment recurs for a fixed number of billing period set /// in billingCycleCount. @JsonValue(2) finiteRecurring, /// The billing plan payment recurs for infinite billing periods unless /// cancelled. @JsonValue(1) infiniteRecurring, /// The billing plan payment is a one time charge that does not repeat. @JsonValue(3) nonRecurring, } /// Serializer for [RecurrenceMode]. /// /// Use these in `@JsonSerializable()` classes by annotating them with /// `@RecurrenceModeConverter()`. class RecurrenceModeConverter implements JsonConverter<RecurrenceMode, int?> { /// Default const constructor. const RecurrenceModeConverter(); @override RecurrenceMode fromJson(int? json) { if (json == null) { return RecurrenceMode.nonRecurring; } return $enumDecode(_$RecurrenceModeEnumMap, json); } @override int toJson(RecurrenceMode object) => _$RecurrenceModeEnumMap[object]!; }
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/product_details_wrapper.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/product_details_wrapper.dart", "repo_id": "packages", "token_count": 1905 }
1,223
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import '../../in_app_purchase_android.dart'; /// Google Play specific parameter object for generating a purchase. class GooglePlayPurchaseParam extends PurchaseParam { /// Creates a new [GooglePlayPurchaseParam] object with the given data. GooglePlayPurchaseParam({ required super.productDetails, super.applicationUserName, this.changeSubscriptionParam, }); /// The 'changeSubscriptionParam' containing information for upgrading or /// downgrading an existing subscription. final ChangeSubscriptionParam? changeSubscriptionParam; }
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_purchase_param.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_purchase_param.dart", "repo_id": "packages", "token_count": 212 }
1,224
# Below is a list of people and organizations that have contributed # to the Flutter project. Names should be added to the list like so: # # Name/Organization <email address> Google Inc. The Chromium Authors German Saprykin <[email protected]> Benjamin Sauer <[email protected]> [email protected] Ali Bitek <[email protected]> Pol Batlló <[email protected]> Anatoly Pulyaevskiy Hayden Flinner <[email protected]> Stefano Rodriguez <[email protected]> Salvatore Giordano <[email protected]> Brian Armstrong <[email protected]> Paul DeMarco <[email protected]> Fabricio Nogueira <[email protected]> Simon Lightfoot <[email protected]> Ashton Thomas <[email protected]> Thomas Danner <[email protected]> Diego Velásquez <[email protected]> Hajime Nakamura <[email protected]> Tuyển Vũ Xuân <[email protected]> Miguel Ruivo <[email protected]> Sarthak Verma <[email protected]> Mike Diarmid <[email protected]> Invertase <[email protected]> Elliot Hesp <[email protected]> Vince Varga <[email protected]> Aawaz Gyawali <[email protected]> EUI Limited <[email protected]> Katarina Sheremet <[email protected]> Thomas Stockx <[email protected]> Sarbagya Dhaubanjar <[email protected]> Ozkan Eksi <[email protected]> Rishab Nayak <[email protected]> ko2ic <[email protected]> Jonathan Younger <[email protected]> Jose Sanchez <[email protected]> Debkanchan Samadder <[email protected]> Audrius Karosevicius <[email protected]> Lukasz Piliszczuk <[email protected]> SoundReply Solutions GmbH <[email protected]> Rafal Wachol <[email protected]> Pau Picas <[email protected]> Christian Weder <[email protected]> Alexandru Tuca <[email protected]> Christian Weder <[email protected]> Rhodes Davis Jr. <[email protected]> Luigi Agosti <[email protected]> Quentin Le Guennec <[email protected]> Koushik Ravikumar <[email protected]> Nissim Dsilva <[email protected]> Giancarlo Rocha <[email protected]> Ryo Miyake <[email protected]> Théo Champion <[email protected]> Kazuki Yamaguchi <[email protected]> Eitan Schwartz <[email protected]> Chris Rutkowski <[email protected]> Juan Alvarez <[email protected]> Aleksandr Yurkovskiy <[email protected]> Anton Borries <[email protected]> Alex Li <[email protected]> Rahul Raj <[email protected]> Maurits van Beusekom <[email protected]>
packages/packages/in_app_purchase/in_app_purchase_platform_interface/AUTHORS/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_platform_interface/AUTHORS", "repo_id": "packages", "token_count": 1045 }
1,225
// 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. /// Represents the data that is used to verify purchases. /// /// The property [source] helps you to determine the method to verify purchases. /// Different source of purchase has different methods of verifying purchases. /// /// Both platforms have 2 ways to verify purchase data. You can either choose to /// verify the data locally using [localVerificationData] or verify the data /// using your own server with [serverVerificationData]. It is preferable to /// verify purchases using a server with [serverVerificationData]. /// /// You should never use any purchase data until verified. class PurchaseVerificationData { /// Creates a [PurchaseVerificationData] object with the provided information. PurchaseVerificationData({ required this.localVerificationData, required this.serverVerificationData, required this.source, }); /// The data used for local verification. /// /// The data is formatted according to the specifications of the respective /// store. You can use the [source] field to determine the store from which /// the data originated and proces the data accordingly. final String localVerificationData; /// The data used for server verification. final String serverVerificationData; /// Indicates the source of the purchase. final String source; }
packages/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/purchase_verification_data.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/purchase_verification_data.dart", "repo_id": "packages", "token_count": 342 }
1,226
// 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:in_app_purchase_storekit/store_kit_wrappers.dart'; /// Example implementation of the /// [`SKPaymentQueueDelegate`](https://developer.apple.com/documentation/storekit/skpaymentqueuedelegate?language=objc). /// /// The payment queue delegate can be implementated to provide information /// needed to complete transactions. class ExamplePaymentQueueDelegate implements SKPaymentQueueDelegateWrapper { @override bool shouldContinueTransaction( SKPaymentTransactionWrapper transaction, SKStorefrontWrapper storefront) { return true; } @override bool shouldShowPriceConsent() { return false; } }
packages/packages/in_app_purchase/in_app_purchase_storekit/example/lib/example_payment_queue_delegate.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/example/lib/example_payment_queue_delegate.dart", "repo_id": "packages", "token_count": 224 }
1,227
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:json_annotation/json_annotation.dart'; import '../../store_kit_wrappers.dart'; import '../channel.dart'; import '../in_app_purchase_storekit_platform.dart'; import '../messages.g.dart'; part 'sk_payment_queue_wrapper.g.dart'; InAppPurchaseAPI _hostApi = InAppPurchaseAPI(); /// Set up pigeon API. @visibleForTesting void setInAppPurchaseHostApi(InAppPurchaseAPI api) { _hostApi = api; } /// A wrapper around /// [`SKPaymentQueue`](https://developer.apple.com/documentation/storekit/skpaymentqueue?language=objc). /// /// The payment queue contains payment related operations. It communicates with /// the App Store and presents a user interface for the user to process and /// authorize payments. /// /// Full information on using `SKPaymentQueue` and processing purchases is /// available at the [In-App Purchase Programming /// Guide](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Introduction.html#//apple_ref/doc/uid/TP40008267) class SKPaymentQueueWrapper { /// Returns the default payment queue. /// /// We do not support instantiating a custom payment queue, hence the /// singleton. However, you can override the observer. factory SKPaymentQueueWrapper() { return _singleton; } SKPaymentQueueWrapper._(); static final SKPaymentQueueWrapper _singleton = SKPaymentQueueWrapper._(); SKPaymentQueueDelegateWrapper? _paymentQueueDelegate; SKTransactionObserverWrapper? _observer; /// Calls [`[SKPaymentQueue storefront]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/3182430-storefront?language=objc). /// /// Returns `null` if the user's device is below iOS 13.0 or macOS 10.15. Future<SKStorefrontWrapper?> storefront() async { return SKStorefrontWrapper.convertFromPigeon(await _hostApi.storefront()); } /// Calls [`-[SKPaymentQueue transactions]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/1506026-transactions?language=objc). Future<List<SKPaymentTransactionWrapper>> transactions() async { final List<SKPaymentTransactionMessage?> pigeonMsgs = await _hostApi.transactions(); return pigeonMsgs .map((SKPaymentTransactionMessage? msg) => SKPaymentTransactionWrapper.convertFromPigeon(msg!)) .toList(); } /// Calls [`-[SKPaymentQueue canMakePayments:]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/1506139-canmakepayments?language=objc). static Future<bool> canMakePayments() async => _hostApi.canMakePayments(); /// Sets an observer to listen to all incoming transaction events. /// /// This should be called and set as soon as the app launches in order to /// avoid missing any purchase updates from the App Store. See the /// documentation on StoreKit's [`-[SKPaymentQueue /// addTransactionObserver:]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/1506042-addtransactionobserver?language=objc). void setTransactionObserver(SKTransactionObserverWrapper observer) { _observer = observer; channel.setMethodCallHandler(handleObserverCallbacks); } /// Instructs the iOS implementation to register a transaction observer and /// start listening to it. /// /// Call this method when the first listener is subscribed to the /// [InAppPurchaseStoreKitPlatform.purchaseStream]. Future<void> startObservingTransactionQueue() => _hostApi.startObservingPaymentQueue(); /// Instructs the iOS implementation to remove the transaction observer and /// stop listening to it. /// /// Call this when there are no longer any listeners subscribed to the /// [InAppPurchaseStoreKitPlatform.purchaseStream]. Future<void> stopObservingTransactionQueue() => _hostApi.stopObservingPaymentQueue(); /// Sets an implementation of the [SKPaymentQueueDelegateWrapper]. /// /// The [SKPaymentQueueDelegateWrapper] can be used to inform iOS how to /// finish transactions when the storefront changes or if the price consent /// sheet should be displayed when the price of a subscription has changed. If /// no delegate is registered iOS will fallback to it's default configuration. /// See the documentation on StoreKite's [`-[SKPaymentQueue delegate:]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/3182429-delegate?language=objc). /// /// When set to `null` the payment queue delegate will be removed and the /// default behaviour will apply (see [documentation](https://developer.apple.com/documentation/storekit/skpaymentqueue/3182429-delegate?language=objc)). Future<void> setDelegate(SKPaymentQueueDelegateWrapper? delegate) async { if (delegate == null) { await _hostApi.removePaymentQueueDelegate(); paymentQueueDelegateChannel.setMethodCallHandler(null); } else { await _hostApi.registerPaymentQueueDelegate(); paymentQueueDelegateChannel .setMethodCallHandler(handlePaymentQueueDelegateCallbacks); } _paymentQueueDelegate = delegate; } /// Posts a payment to the queue. /// /// This sends a purchase request to the App Store for confirmation. /// Transaction updates will be delivered to the set /// [SkTransactionObserverWrapper]. /// /// A couple preconditions need to be met before calling this method. /// /// - At least one [SKTransactionObserverWrapper] should have been added to /// the payment queue using [addTransactionObserver]. /// - The [payment.productIdentifier] needs to have been previously fetched /// using [SKRequestMaker.startProductRequest] so that a valid `SKProduct` /// has been cached in the platform side already. Because of this /// [payment.productIdentifier] cannot be hardcoded. /// /// This method calls StoreKit's [`-[SKPaymentQueue addPayment:]`] /// (https://developer.apple.com/documentation/storekit/skpaymentqueue/1506036-addpayment?preferredLanguage=occ). /// /// Also see [sandbox /// testing](https://developer.apple.com/apple-pay/sandbox-testing/). Future<void> addPayment(SKPaymentWrapper payment) async { assert(_observer != null, '[in_app_purchase]: Trying to add a payment without an observer. One must be set using `SkPaymentQueueWrapper.setTransactionObserver` before the app launches.'); await _hostApi.addPayment(payment.toMap()); } /// Finishes a transaction and removes it from the queue. /// /// This method should be called after the given [transaction] has been /// succesfully processed and its content has been delivered to the user. /// Transaction status updates are propagated to [SkTransactionObserver]. /// /// This will throw a Platform exception if [transaction.transactionState] is /// [SKPaymentTransactionStateWrapper.purchasing]. /// /// This method calls StoreKit's [`-[SKPaymentQueue /// finishTransaction:]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/1506003-finishtransaction?language=objc). Future<void> finishTransaction( SKPaymentTransactionWrapper transaction) async { final Map<String, String?> requestMap = transaction.toFinishMap(); await _hostApi.finishTransaction(requestMap); } /// Restore previously purchased transactions. /// /// Use this to load previously purchased content on a new device. /// /// This call triggers purchase updates on the set /// [SKTransactionObserverWrapper] for previously made transactions. This will /// invoke [SKTransactionObserverWrapper.restoreCompletedTransactions], /// [SKTransactionObserverWrapper.paymentQueueRestoreCompletedTransactionsFinished], /// and [SKTransactionObserverWrapper.updatedTransaction]. These restored /// transactions need to be marked complete with [finishTransaction] once the /// content is delivered, like any other transaction. /// /// The `applicationUserName` should match the original /// [SKPaymentWrapper.applicationUsername] used in [addPayment]. /// If no `applicationUserName` was used, `applicationUserName` should be null. /// /// This method either triggers [`-[SKPayment /// restoreCompletedTransactions]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/1506123-restorecompletedtransactions?language=objc) /// or [`-[SKPayment restoreCompletedTransactionsWithApplicationUsername:]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/1505992-restorecompletedtransactionswith?language=objc) /// depending on whether the `applicationUserName` is set. Future<void> restoreTransactions({String? applicationUserName}) async { await _hostApi.restoreTransactions(applicationUserName); } /// Present Code Redemption Sheet /// /// Use this to allow Users to enter and redeem Codes /// /// This method triggers [`-[SKPayment /// presentCodeRedemptionSheet]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/3566726-presentcoderedemptionsheet?language=objc) Future<void> presentCodeRedemptionSheet() async { await _hostApi.presentCodeRedemptionSheet(); } /// Shows the price consent sheet if the user has not yet responded to a /// subscription price change. /// /// Use this function when you have registered a [SKPaymentQueueDelegateWrapper] /// (using the [setDelegate] method) and returned `false` when the /// `SKPaymentQueueDelegateWrapper.shouldShowPriceConsent()` method was called. /// /// See documentation of StoreKit's [`-[SKPaymentQueue showPriceConsentIfNeeded]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/3521327-showpriceconsentifneeded?language=objc). Future<void> showPriceConsentIfNeeded() async { await _hostApi.showPriceConsentIfNeeded(); } /// Triage a method channel call from the platform and triggers the correct observer method. /// /// This method is public for testing purposes only and should not be used /// outside this class. @visibleForTesting Future<dynamic> handleObserverCallbacks(MethodCall call) async { assert(_observer != null, '[in_app_purchase]: (Fatal)The observer has not been set but we received a purchase transaction notification. Please ensure the observer has been set using `setTransactionObserver`. Make sure the observer is added right at the App Launch.'); final SKTransactionObserverWrapper observer = _observer!; switch (call.method) { case 'updatedTransactions': { final List<SKPaymentTransactionWrapper> transactions = _getTransactionList(call.arguments as List<dynamic>); return Future<void>(() { observer.updatedTransactions(transactions: transactions); }); } case 'removedTransactions': { final List<SKPaymentTransactionWrapper> transactions = _getTransactionList(call.arguments as List<dynamic>); return Future<void>(() { observer.removedTransactions(transactions: transactions); }); } case 'restoreCompletedTransactionsFailed': { final SKError error = SKError.fromJson(Map<String, dynamic>.from( call.arguments as Map<dynamic, dynamic>)); return Future<void>(() { observer.restoreCompletedTransactionsFailed(error: error); }); } case 'paymentQueueRestoreCompletedTransactionsFinished': { return Future<void>(() { observer.paymentQueueRestoreCompletedTransactionsFinished(); }); } case 'shouldAddStorePayment': { final Map<Object?, Object?> arguments = call.arguments as Map<Object?, Object?>; final SKPaymentWrapper payment = SKPaymentWrapper.fromJson( (arguments['payment']! as Map<dynamic, dynamic>) .cast<String, dynamic>()); final SKProductWrapper product = SKProductWrapper.fromJson( (arguments['product']! as Map<dynamic, dynamic>) .cast<String, dynamic>()); return Future<void>(() { if (observer.shouldAddStorePayment( payment: payment, product: product)) { SKPaymentQueueWrapper().addPayment(payment); } }); } default: break; } throw PlatformException( code: 'no_such_callback', message: 'Did not recognize the observer callback ${call.method}.'); } // Get transaction wrapper object list from arguments. List<SKPaymentTransactionWrapper> _getTransactionList( List<dynamic> transactionsData) { return transactionsData.map<SKPaymentTransactionWrapper>((dynamic map) { return SKPaymentTransactionWrapper.fromJson( Map.castFrom<dynamic, dynamic, String, dynamic>( map as Map<dynamic, dynamic>)); }).toList(); } /// Triage a method channel call from the platform and triggers the correct /// payment queue delegate method. /// /// This method is public for testing purposes only and should not be used /// outside this class. @visibleForTesting Future<dynamic> handlePaymentQueueDelegateCallbacks(MethodCall call) async { assert(_paymentQueueDelegate != null, '[in_app_purchase]: (Fatal)The payment queue delegate has not been set but we received a payment queue notification. Please ensure the payment queue has been set using `setDelegate`.'); final SKPaymentQueueDelegateWrapper delegate = _paymentQueueDelegate!; switch (call.method) { case 'shouldContinueTransaction': final Map<Object?, Object?> arguments = call.arguments as Map<Object?, Object?>; final SKPaymentTransactionWrapper transaction = SKPaymentTransactionWrapper.fromJson( (arguments['transaction']! as Map<dynamic, dynamic>) .cast<String, dynamic>()); final SKStorefrontWrapper storefront = SKStorefrontWrapper.fromJson( (arguments['storefront']! as Map<dynamic, dynamic>) .cast<String, dynamic>()); return delegate.shouldContinueTransaction(transaction, storefront); case 'shouldShowPriceConsent': return delegate.shouldShowPriceConsent(); default: break; } throw PlatformException( code: 'no_such_callback', message: 'Did not recognize the payment queue delegate callback ${call.method}.'); } } /// Dart wrapper around StoreKit's /// [NSError](https://developer.apple.com/documentation/foundation/nserror?language=objc). @immutable @JsonSerializable() class SKError { /// Creates a new [SKError] object with the provided information. const SKError( {required this.code, required this.domain, required this.userInfo}); /// Constructs an instance of this from a key-value map of data. /// /// The map needs to have named string keys with values matching the names and /// types of all of the members on this class. The `map` parameter must not be /// null. factory SKError.fromJson(Map<String, dynamic> map) { return _$SKErrorFromJson(map); } /// Error [code](https://developer.apple.com/documentation/foundation/1448136-nserror_codes) /// as defined in the Cocoa Framework. @JsonKey(defaultValue: 0) final int code; /// Error /// [domain](https://developer.apple.com/documentation/foundation/nscocoaerrordomain?language=objc) /// as defined in the Cocoa Framework. @JsonKey(defaultValue: '') final String domain; /// A map that contains more detailed information about the error. /// /// Any key of the map must be a valid [NSErrorUserInfoKey](https://developer.apple.com/documentation/foundation/nserroruserinfokey?language=objc). @JsonKey(defaultValue: <String, dynamic>{}) final Map<String?, Object?>? userInfo; @override bool operator ==(Object other) { if (identical(other, this)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is SKError && other.code == code && other.domain == domain && const DeepCollectionEquality.unordered() .equals(other.userInfo, userInfo); } @override int get hashCode => Object.hash( code, domain, userInfo, ); /// Converts [SKErrorMessage] into the dart equivalent static SKError convertFromPigeon(SKErrorMessage msg) { return SKError( code: msg.code, domain: msg.domain, userInfo: msg.userInfo ?? <String, Object>{}); } } /// Dart wrapper around StoreKit's /// [SKPayment](https://developer.apple.com/documentation/storekit/skpayment?language=objc). /// /// Used as the parameter to initiate a payment. In general, a developer should /// not need to create the payment object explicitly; instead, use /// [SKPaymentQueueWrapper.addPayment] directly with a product identifier to /// initiate a payment. @immutable @JsonSerializable(createToJson: true) class SKPaymentWrapper { /// Creates a new [SKPaymentWrapper] with the provided information. const SKPaymentWrapper({ required this.productIdentifier, this.applicationUsername, this.requestData, this.quantity = 1, this.simulatesAskToBuyInSandbox = false, this.paymentDiscount, }); /// Constructs an instance of this from a key value map of data. /// /// The map needs to have named string keys with values matching the names and /// types of all of the members on this class. The `map` parameter must not be /// null. factory SKPaymentWrapper.fromJson(Map<String, dynamic> map) { return _$SKPaymentWrapperFromJson(map); } /// Creates a Map object describes the payment object. Map<String, dynamic> toMap() { return <String, dynamic>{ 'productIdentifier': productIdentifier, 'applicationUsername': applicationUsername, 'requestData': requestData, 'quantity': quantity, 'simulatesAskToBuyInSandbox': simulatesAskToBuyInSandbox, 'paymentDiscount': paymentDiscount?.toMap(), }; } /// The id for the product that the payment is for. @JsonKey(defaultValue: '') final String productIdentifier; /// An opaque id for the user's account. /// /// Used to help the store detect irregular activity. See /// [applicationUsername](https://developer.apple.com/documentation/storekit/skpayment/1506116-applicationusername?language=objc) /// for more details. For example, you can use a one-way hash of the user’s /// account name on your server. Don’t use the Apple ID for your developer /// account, the user’s Apple ID, or the user’s plaintext account name on /// your server. final String? applicationUsername; /// Reserved for future use. /// /// The value must be null before sending the payment. If the value is not /// null, the payment will be rejected. /// // The iOS Platform provided this property but it is reserved for future use. // We also provide this property to match the iOS platform. Converted to // String from NSData from ios platform using UTF8Encoding. The / default is // null. final String? requestData; /// The amount of the product this payment is for. /// /// The default is 1. The minimum is 1. The maximum is 10. /// /// If the object is invalid, the value could be 0. @JsonKey(defaultValue: 0) final int quantity; /// Produces an "ask to buy" flow in the sandbox. /// /// Setting it to `true` will cause a transaction to be in the state [SKPaymentTransactionStateWrapper.deferred], /// which produce an "ask to buy" prompt that interrupts the the payment flow. /// /// Default is `false`. /// /// See https://developer.apple.com/in-app-purchase/ for a guide on Sandbox /// testing. final bool simulatesAskToBuyInSandbox; /// The details of a discount that should be applied to the payment. /// /// See [Implementing Promotional Offers in Your App](https://developer.apple.com/documentation/storekit/original_api_for_in-app_purchase/subscriptions_and_offers/implementing_promotional_offers_in_your_app?language=objc) /// for more information on generating keys and creating offers for /// auto-renewable subscriptions. If set to `null` no discount will be /// applied to this payment. final SKPaymentDiscountWrapper? paymentDiscount; @override bool operator ==(Object other) { if (identical(other, this)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is SKPaymentWrapper && other.productIdentifier == productIdentifier && other.applicationUsername == applicationUsername && other.quantity == quantity && other.simulatesAskToBuyInSandbox == simulatesAskToBuyInSandbox && other.requestData == requestData; } @override int get hashCode => Object.hash(productIdentifier, applicationUsername, quantity, simulatesAskToBuyInSandbox, requestData); @override String toString() => _$SKPaymentWrapperToJson(this).toString(); /// Converts [SKPaymentMessage] into the dart equivalent static SKPaymentWrapper convertFromPigeon(SKPaymentMessage msg) { return SKPaymentWrapper( productIdentifier: msg.productIdentifier, applicationUsername: msg.applicationUsername, quantity: msg.quantity, simulatesAskToBuyInSandbox: msg.simulatesAskToBuyInSandbox, requestData: msg.requestData, paymentDiscount: SKPaymentDiscountWrapper.convertFromPigeon(msg.paymentDiscount)); } } /// Dart wrapper around StoreKit's /// [SKPaymentDiscount](https://developer.apple.com/documentation/storekit/skpaymentdiscount?language=objc). /// /// Used to indicate a discount is applicable to a payment. The /// [SKPaymentDiscountWrapper] instance should be assigned to the /// [SKPaymentWrapper] object to which the discount should be applied. /// Discount offers are set up in App Store Connect. See [Implementing Promotional Offers in Your App](https://developer.apple.com/documentation/storekit/original_api_for_in-app_purchase/subscriptions_and_offers/implementing_promotional_offers_in_your_app?language=objc) /// for more information. @immutable @JsonSerializable(createToJson: true) class SKPaymentDiscountWrapper { /// Creates a new [SKPaymentDiscountWrapper] with the provided information. const SKPaymentDiscountWrapper({ required this.identifier, required this.keyIdentifier, required this.nonce, required this.signature, required this.timestamp, }); /// Constructs an instance of this from a key value map of data. /// /// The map needs to have named string keys with values matching the names and /// types of all of the members on this class. factory SKPaymentDiscountWrapper.fromJson(Map<String, dynamic> map) { return _$SKPaymentDiscountWrapperFromJson(map); } /// Creates a Map object describes the payment object. Map<String, dynamic> toMap() { return <String, dynamic>{ 'identifier': identifier, 'keyIdentifier': keyIdentifier, 'nonce': nonce, 'signature': signature, 'timestamp': timestamp, }; } /// The identifier of the discount offer. /// /// The identifier must match one of the offers set up in App Store Connect. final String identifier; /// A string identifying the key that is used to generate the signature. /// /// Keys are generated and downloaded from App Store Connect. See /// [Generating a Signature for Promotional Offers](https://developer.apple.com/documentation/storekit/original_api_for_in-app_purchase/subscriptions_and_offers/generating_a_signature_for_promotional_offers?language=objc) /// for more information. final String keyIdentifier; /// A universal unique identifier (UUID) created together with the signature. /// /// The UUID should be generated on your server when it creates the /// `signature` for the payment discount. The UUID can be used once, a new /// UUID should be created for each payment request. The string representation /// of the UUID must be lowercase. See /// [Generating a Signature for Promotional Offers](https://developer.apple.com/documentation/storekit/original_api_for_in-app_purchase/subscriptions_and_offers/generating_a_signature_for_promotional_offers?language=objc) /// for more information. final String nonce; /// A cryptographically signed string representing the to properties of the /// promotional offer. /// /// The signature is string signed with a private key and contains all the /// properties of the promotional offer. To keep you private key secure the /// signature should be created on a server. See [Generating a Signature for Promotional Offers](https://developer.apple.com/documentation/storekit/original_api_for_in-app_purchase/subscriptions_and_offers/generating_a_signature_for_promotional_offers?language=objc) /// for more information. final String signature; /// The date and time the signature was created. /// /// The timestamp should be formatted in Unix epoch time. See /// [Generating a Signature for Promotional Offers](https://developer.apple.com/documentation/storekit/original_api_for_in-app_purchase/subscriptions_and_offers/generating_a_signature_for_promotional_offers?language=objc) /// for more information. final int timestamp; @override bool operator ==(Object other) { if (identical(other, this)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is SKPaymentDiscountWrapper && other.identifier == identifier && other.keyIdentifier == keyIdentifier && other.nonce == nonce && other.signature == signature && other.timestamp == timestamp; } @override int get hashCode => Object.hash(identifier, keyIdentifier, nonce, signature, timestamp); /// Converts [SKPaymentDiscountMessage] into the dart equivalent static SKPaymentDiscountWrapper? convertFromPigeon( SKPaymentDiscountMessage? msg) { if (msg == null) { return null; } return SKPaymentDiscountWrapper( identifier: msg.identifier, keyIdentifier: msg.keyIdentifier, nonce: msg.nonce, signature: msg.signature, timestamp: msg.timestamp); } }
packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_queue_wrapper.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_queue_wrapper.dart", "repo_id": "packages", "token_count": 8478 }
1,228
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; @ConfigurePigeon(PigeonOptions( dartOut: 'lib/src/messages.g.dart', dartTestOut: 'test/test_api.g.dart', objcHeaderOut: 'darwin/Classes/messages.g.h', objcSourceOut: 'darwin/Classes/messages.g.m', copyrightHeader: 'pigeons/copyright.txt', )) class SKPaymentTransactionMessage { SKPaymentTransactionMessage({ required this.payment, required this.transactionState, this.originalTransaction, this.transactionTimeStamp, this.transactionIdentifier, this.error, }); final SKPaymentMessage payment; final SKPaymentTransactionStateMessage transactionState; final SKPaymentTransactionMessage? originalTransaction; final double? transactionTimeStamp; final String? transactionIdentifier; final SKErrorMessage? error; } enum SKPaymentTransactionStateMessage { /// Indicates the transaction is being processed in App Store. /// /// You should update your UI to indicate that you are waiting for the /// transaction to update to another state. Never complete a transaction that /// is still in a purchasing state. purchasing, /// The user's payment has been succesfully processed. /// /// You should provide the user the content that they purchased. purchased, /// The transaction failed. /// /// Check the [PaymentTransactionWrapper.error] property from /// [PaymentTransactionWrapper] for details. failed, /// This transaction is restoring content previously purchased by the user. /// /// The previous transaction information can be obtained in /// [PaymentTransactionWrapper.originalTransaction] from /// [PaymentTransactionWrapper]. restored, /// The transaction is in the queue but pending external action. Wait for /// another callback to get the final state. /// /// You should update your UI to indicate that you are waiting for the /// transaction to update to another state. deferred, /// Indicates the transaction is in an unspecified state. unspecified, } class SKPaymentMessage { /// Creates a new [SKPaymentWrapper] with the provided information. const SKPaymentMessage({ required this.productIdentifier, this.applicationUsername, this.requestData, this.quantity = 1, this.simulatesAskToBuyInSandbox = false, this.paymentDiscount, }); final String productIdentifier; final String? applicationUsername; final String? requestData; final int quantity; final bool simulatesAskToBuyInSandbox; final SKPaymentDiscountMessage? paymentDiscount; } class SKErrorMessage { const SKErrorMessage( {required this.code, required this.domain, required this.userInfo}); final int code; final String domain; final Map<String?, Object?>? userInfo; } class SKPaymentDiscountMessage { const SKPaymentDiscountMessage({ required this.identifier, required this.keyIdentifier, required this.nonce, required this.signature, required this.timestamp, }); final String identifier; final String keyIdentifier; final String nonce; final String signature; final int timestamp; } class SKStorefrontMessage { const SKStorefrontMessage({ required this.countryCode, required this.identifier, }); final String countryCode; final String identifier; } class SKProductsResponseMessage { const SKProductsResponseMessage( {required this.products, required this.invalidProductIdentifiers}); final List<SKProductMessage?>? products; final List<String?>? invalidProductIdentifiers; } class SKProductMessage { const SKProductMessage( {required this.productIdentifier, required this.localizedTitle, required this.localizedDescription, required this.priceLocale, required this.price, this.subscriptionGroupIdentifier, this.subscriptionPeriod, this.introductoryPrice, this.discounts}); final String productIdentifier; final String localizedTitle; final String localizedDescription; final SKPriceLocaleMessage priceLocale; final String? subscriptionGroupIdentifier; final String price; final SKProductSubscriptionPeriodMessage? subscriptionPeriod; final SKProductDiscountMessage? introductoryPrice; final List<SKProductDiscountMessage?>? discounts; } class SKPriceLocaleMessage { SKPriceLocaleMessage({ required this.currencySymbol, required this.currencyCode, required this.countryCode, }); ///The currency symbol for the locale, e.g. $ for US locale. final String currencySymbol; ///The currency code for the locale, e.g. USD for US locale. final String currencyCode; ///The country code for the locale, e.g. US for US locale. final String countryCode; } class SKProductDiscountMessage { const SKProductDiscountMessage( {required this.price, required this.priceLocale, required this.numberOfPeriods, required this.paymentMode, required this.subscriptionPeriod, required this.identifier, required this.type}); final String price; final SKPriceLocaleMessage priceLocale; final int numberOfPeriods; final SKProductDiscountPaymentModeMessage paymentMode; final SKProductSubscriptionPeriodMessage subscriptionPeriod; final String? identifier; final SKProductDiscountTypeMessage type; } enum SKProductDiscountTypeMessage { /// A constant indicating the discount type is an introductory offer. introductory, /// A constant indicating the discount type is a promotional offer. subscription, } enum SKProductDiscountPaymentModeMessage { /// Allows user to pay the discounted price at each payment period. payAsYouGo, /// Allows user to pay the discounted price upfront and receive the product for the rest of time that was paid for. payUpFront, /// User pays nothing during the discounted period. freeTrial, /// Unspecified mode. unspecified, } class SKProductSubscriptionPeriodMessage { SKProductSubscriptionPeriodMessage( {required this.numberOfUnits, required this.unit}); final int numberOfUnits; final SKSubscriptionPeriodUnitMessage unit; } enum SKSubscriptionPeriodUnitMessage { day, week, month, year, } @HostApi(dartHostTestHandler: 'TestInAppPurchaseApi') abstract class InAppPurchaseAPI { /// Returns if the current device is able to make payments bool canMakePayments(); List<SKPaymentTransactionMessage> transactions(); SKStorefrontMessage storefront(); void addPayment(Map<String, Object?> paymentMap); @async SKProductsResponseMessage startProductRequest( List<String> productIdentifiers); void finishTransaction(Map<String, String?> finishMap); void restoreTransactions(String? applicationUserName); void presentCodeRedemptionSheet(); String? retrieveReceiptData(); @async void refreshReceipt({Map<String, Object?>? receiptProperties}); void startObservingPaymentQueue(); void stopObservingPaymentQueue(); void registerPaymentQueueDelegate(); void removePaymentQueueDelegate(); void showPriceConsentIfNeeded(); }
packages/packages/in_app_purchase/in_app_purchase_storekit/pigeons/messages.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/pigeons/messages.dart", "repo_id": "packages", "token_count": 2078 }
1,229
## NEXT * Updates minimum iOS version to 12.0 and minimum Flutter version to 3.16.6. ## 0.2.3+2 * Adds privacy manifest. ## 0.2.3+1 * Improves example code in README. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 0.2.3 * Migrates to a Swift implementation. ## 0.2.2+3 * Converts platform communication to Pigeon. ## 0.2.2+2 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. * Aligns Dart and Flutter SDK constraints. ## 0.2.2+1 * Updates links for the merge of flutter/plugins into flutter/packages. ## 0.2.2 * Updates minimum version to iOS 11. ## 0.2.1+1 * Add lint ignore comments ## 0.2.1 * Updates minimum Flutter version to 3.3.0. * Removes usage of deprecated [ImageProvider.load]. * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316). ## 0.2.0+9 * Ignores the warning for the upcoming deprecation of `DecoderCallback`. ## 0.2.0+8 * Ignores the warning for the upcoming deprecation of `ImageProvider.load` in the correct line. ## 0.2.0+7 * Ignores the warning for the upcoming deprecation of `ImageProvider.load`. ## 0.2.0+6 * Removes unnecessary imports. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 0.2.0+5 * Migrates from `ui.hash*` to `Object.hash*`. * Adds OS version support information to README. ## 0.2.0+4 * Internal code cleanup for stricter analysis options. ## 0.2.0+3 * Internal fix for unused field formal parameter. ## 0.2.0+2 * Update minimum Flutter SDK to 2.5 and iOS deployment target to 9.0. ## 0.2.0+1 * Add iOS unit test target. * Fix repository link in pubspec.yaml. ## 0.2.0 * Migrate to null safety. ## 0.1.2+4 * Update Flutter SDK constraint. ## 0.1.2+3 * Remove no-op android folder in the example app. ## 0.1.2+2 * Post-v2 Android embedding cleanups. ## 0.1.2+1 * Remove Android folder from `ios_platform_images`. ## 0.1.2 * Fix crash when parameter extension is null. * Fix CocoaPods podspec lint warnings. ## 0.1.1 * Remove Android dependencies fallback. * Require Flutter SDK 1.12.13+hotfix.5 or greater. ## 0.1.0+2 * Make the pedantic dev_dependency explicit. ## 0.1.0+1 * Removed Android support from the pubspec. ## 0.1.0 * Fixed a bug where the scale value of the image wasn't respected. ## 0.0.1 * Initial release. Includes functionality to share images iOS images with Flutter and Flutter assets with iOS.
packages/packages/ios_platform_images/CHANGELOG.md/0
{ "file_path": "packages/packages/ios_platform_images/CHANGELOG.md", "repo_id": "packages", "token_count": 887 }
1,230
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v11.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; /// A serialization of a platform image's data. class PlatformImageData { PlatformImageData({ required this.data, required this.scale, }); /// The image data. Uint8List data; /// The image's scale factor. double scale; Object encode() { return <Object?>[ data, scale, ]; } static PlatformImageData decode(Object result) { result as List<Object?>; return PlatformImageData( data: result[0]! as Uint8List, scale: result[1]! as double, ); } } class _PlatformImagesApiCodec extends StandardMessageCodec { const _PlatformImagesApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is PlatformImageData) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return PlatformImageData.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class PlatformImagesApi { /// Constructor for [PlatformImagesApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. PlatformImagesApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = _PlatformImagesApiCodec(); /// Returns the URL for the given resource, or null if no such resource is /// found. Future<String?> resolveUrl( String arg_resourceName, String? arg_extension) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ios_platform_images.PlatformImagesApi.resolveUrl', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel .send(<Object?>[arg_resourceName, arg_extension]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return (replyList[0] as String?); } } /// Returns the data for the image resource with the given name, or null if /// no such resource is found. Future<PlatformImageData?> loadImage(String arg_name) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.ios_platform_images.PlatformImagesApi.loadImage', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_name]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return (replyList[0] as PlatformImageData?); } } }
packages/packages/ios_platform_images/lib/src/messages.g.dart/0
{ "file_path": "packages/packages/ios_platform_images/lib/src/messages.g.dart", "repo_id": "packages", "token_count": 1478 }
1,231
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:local_auth/local_auth.dart'; import 'package:local_auth_android/local_auth_android.dart'; import 'package:local_auth_darwin/local_auth_darwin.dart'; import 'package:local_auth_platform_interface/local_auth_platform_interface.dart'; import 'package:local_auth_windows/local_auth_windows.dart'; import 'package:mockito/mockito.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); late LocalAuthentication localAuthentication; late MockLocalAuthPlatform mockLocalAuthPlatform; setUp(() { localAuthentication = LocalAuthentication(); mockLocalAuthPlatform = MockLocalAuthPlatform(); LocalAuthPlatform.instance = mockLocalAuthPlatform; }); test('authenticate calls platform implementation', () { when(mockLocalAuthPlatform.authenticate( localizedReason: anyNamed('localizedReason'), authMessages: anyNamed('authMessages'), options: anyNamed('options'), )).thenAnswer((_) async => true); localAuthentication.authenticate(localizedReason: 'Test Reason'); verify(mockLocalAuthPlatform.authenticate( localizedReason: 'Test Reason', authMessages: <AuthMessages>[ const IOSAuthMessages(), const AndroidAuthMessages(), const WindowsAuthMessages(), ], )).called(1); }); test('isDeviceSupported calls platform implementation', () { when(mockLocalAuthPlatform.isDeviceSupported()) .thenAnswer((_) async => true); localAuthentication.isDeviceSupported(); verify(mockLocalAuthPlatform.isDeviceSupported()).called(1); }); test('getEnrolledBiometrics calls platform implementation', () { when(mockLocalAuthPlatform.getEnrolledBiometrics()) .thenAnswer((_) async => <BiometricType>[]); localAuthentication.getAvailableBiometrics(); verify(mockLocalAuthPlatform.getEnrolledBiometrics()).called(1); }); test('stopAuthentication calls platform implementation', () { when(mockLocalAuthPlatform.stopAuthentication()) .thenAnswer((_) async => true); localAuthentication.stopAuthentication(); verify(mockLocalAuthPlatform.stopAuthentication()).called(1); }); test('canCheckBiometrics returns correct result', () async { when(mockLocalAuthPlatform.deviceSupportsBiometrics()) .thenAnswer((_) async => false); bool? result; result = await localAuthentication.canCheckBiometrics; expect(result, false); when(mockLocalAuthPlatform.deviceSupportsBiometrics()) .thenAnswer((_) async => true); result = await localAuthentication.canCheckBiometrics; expect(result, true); verify(mockLocalAuthPlatform.deviceSupportsBiometrics()).called(2); }); } class MockLocalAuthPlatform extends Mock with MockPlatformInterfaceMixin implements LocalAuthPlatform { MockLocalAuthPlatform() { throwOnMissingStub(this); } @override Future<bool> authenticate({ required String? localizedReason, required Iterable<AuthMessages>? authMessages, AuthenticationOptions? options = const AuthenticationOptions(), }) => super.noSuchMethod( Invocation.method(#authenticate, <Object>[], <Symbol, Object?>{ #localizedReason: localizedReason, #authMessages: authMessages, #options: options, }), returnValue: Future<bool>.value(false)) as Future<bool>; @override Future<List<BiometricType>> getEnrolledBiometrics() => super.noSuchMethod(Invocation.method(#getEnrolledBiometrics, <Object>[]), returnValue: Future<List<BiometricType>>.value(<BiometricType>[])) as Future<List<BiometricType>>; @override Future<bool> isDeviceSupported() => super.noSuchMethod(Invocation.method(#isDeviceSupported, <Object>[]), returnValue: Future<bool>.value(false)) as Future<bool>; @override Future<bool> stopAuthentication() => super.noSuchMethod(Invocation.method(#stopAuthentication, <Object>[]), returnValue: Future<bool>.value(false)) as Future<bool>; @override Future<bool> deviceSupportsBiometrics() => super.noSuchMethod( Invocation.method(#deviceSupportsBiometrics, <Object>[]), returnValue: Future<bool>.value(false)) as Future<bool>; }
packages/packages/local_auth/local_auth/test/local_auth_test.dart/0
{ "file_path": "packages/packages/local_auth/local_auth/test/local_auth_test.dart", "repo_id": "packages", "token_count": 1537 }
1,232
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.localauth; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Activity; import android.app.KeyguardManager; import android.app.NativeActivity; import android.content.Context; import androidx.biometric.BiometricManager; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.Lifecycle; import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.embedding.engine.plugins.lifecycle.HiddenLifecycleReference; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.localauth.AuthenticationHelper.AuthCompletionHandler; import io.flutter.plugins.localauth.Messages.AuthClassification; import io.flutter.plugins.localauth.Messages.AuthClassificationWrapper; import io.flutter.plugins.localauth.Messages.AuthOptions; import io.flutter.plugins.localauth.Messages.AuthResult; import io.flutter.plugins.localauth.Messages.AuthStrings; import io.flutter.plugins.localauth.Messages.Result; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; @RunWith(RobolectricTestRunner.class) public class LocalAuthTest { static final AuthStrings dummyStrings = new AuthStrings.Builder() .setReason("a reason") .setBiometricHint("a hint") .setBiometricNotRecognized("biometric not recognized") .setBiometricRequiredTitle("biometric required") .setCancelButton("cancel") .setDeviceCredentialsRequiredTitle("credentials required") .setDeviceCredentialsSetupDescription("credentials setup description") .setGoToSettingsButton("go") .setGoToSettingsDescription("go to settings description") .setSignInTitle("sign in") .build(); static final AuthOptions defaultOptions = new AuthOptions.Builder() .setBiometricOnly(false) .setSensitiveTransaction(false) .setSticky(false) .setUseErrorDialgs(false) .build(); @Test public void authenticate_returnsErrorWhenAuthInProgress() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); plugin.authInProgress.set(true); @SuppressWarnings("unchecked") final Result<AuthResult> mockResult = mock(Result.class); plugin.authenticate(defaultOptions, dummyStrings, mockResult); ArgumentCaptor<AuthResult> captor = ArgumentCaptor.forClass(AuthResult.class); verify(mockResult).success(captor.capture()); assertEquals(AuthResult.ERROR_ALREADY_IN_PROGRESS, captor.getValue()); } @Test public void authenticate_returnsErrorWithNoForegroundActivity() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); @SuppressWarnings("unchecked") final Result<AuthResult> mockResult = mock(Result.class); plugin.authenticate(defaultOptions, dummyStrings, mockResult); ArgumentCaptor<AuthResult> captor = ArgumentCaptor.forClass(AuthResult.class); verify(mockResult).success(captor.capture()); assertEquals(AuthResult.ERROR_NO_ACTIVITY, captor.getValue()); } @Test public void authenticate_returnsErrorWhenActivityNotFragmentActivity() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); setPluginActivity(plugin, buildMockActivityWithContext(mock(NativeActivity.class))); @SuppressWarnings("unchecked") final Result<AuthResult> mockResult = mock(Result.class); plugin.authenticate(defaultOptions, dummyStrings, mockResult); ArgumentCaptor<AuthResult> captor = ArgumentCaptor.forClass(AuthResult.class); verify(mockResult).success(captor.capture()); assertEquals(AuthResult.ERROR_NOT_FRAGMENT_ACTIVITY, captor.getValue()); } @Test public void authenticate_returnsErrorWhenDeviceNotSupported() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); setPluginActivity(plugin, buildMockActivityWithContext(mock(FragmentActivity.class))); @SuppressWarnings("unchecked") final Result<AuthResult> mockResult = mock(Result.class); plugin.authenticate(defaultOptions, dummyStrings, mockResult); ArgumentCaptor<AuthResult> captor = ArgumentCaptor.forClass(AuthResult.class); verify(mockResult).success(captor.capture()); assertEquals(AuthResult.ERROR_NOT_AVAILABLE, captor.getValue()); } @Test public void authenticate_properlyConfiguresBiometricOnlyAuthenticationRequest() { final LocalAuthPlugin plugin = spy(new LocalAuthPlugin()); setPluginActivity(plugin, buildMockActivityWithContext(mock(FragmentActivity.class))); when(plugin.isDeviceSupported()).thenReturn(true); final BiometricManager mockBiometricManager = mock(BiometricManager.class); when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)) .thenReturn(BiometricManager.BIOMETRIC_SUCCESS); when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL)) .thenReturn(BiometricManager.BIOMETRIC_SUCCESS); plugin.setBiometricManager(mockBiometricManager); ArgumentCaptor<Boolean> allowCredentialsCaptor = ArgumentCaptor.forClass(Boolean.class); doNothing() .when(plugin) .sendAuthenticationRequest( any(AuthOptions.class), any(AuthStrings.class), allowCredentialsCaptor.capture(), any(AuthCompletionHandler.class)); @SuppressWarnings("unchecked") final Result<AuthResult> mockResult = mock(Result.class); final AuthOptions options = new AuthOptions.Builder() .setBiometricOnly(true) .setSensitiveTransaction(false) .setSticky(false) .setUseErrorDialgs(false) .build(); plugin.authenticate(options, dummyStrings, mockResult); assertFalse(allowCredentialsCaptor.getValue()); } @Test @Config(sdk = 30) public void authenticate_properlyConfiguresBiometricAndDeviceCredentialAuthenticationRequest() { final LocalAuthPlugin plugin = spy(new LocalAuthPlugin()); setPluginActivity(plugin, buildMockActivityWithContext(mock(FragmentActivity.class))); when(plugin.isDeviceSupported()).thenReturn(true); final BiometricManager mockBiometricManager = mock(BiometricManager.class); when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL)) .thenReturn(BiometricManager.BIOMETRIC_SUCCESS); plugin.setBiometricManager(mockBiometricManager); ArgumentCaptor<Boolean> allowCredentialsCaptor = ArgumentCaptor.forClass(Boolean.class); doNothing() .when(plugin) .sendAuthenticationRequest( any(AuthOptions.class), any(AuthStrings.class), allowCredentialsCaptor.capture(), any(AuthCompletionHandler.class)); @SuppressWarnings("unchecked") final Result<AuthResult> mockResult = mock(Result.class); plugin.authenticate(defaultOptions, dummyStrings, mockResult); assertTrue(allowCredentialsCaptor.getValue()); } @Test @Config(sdk = 30) public void authenticate_properlyConfiguresDeviceCredentialOnlyAuthenticationRequest() { final LocalAuthPlugin plugin = spy(new LocalAuthPlugin()); setPluginActivity(plugin, buildMockActivityWithContext(mock(FragmentActivity.class))); when(plugin.isDeviceSupported()).thenReturn(true); final BiometricManager mockBiometricManager = mock(BiometricManager.class); when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)) .thenReturn(BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED); when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL)) .thenReturn(BiometricManager.BIOMETRIC_SUCCESS); plugin.setBiometricManager(mockBiometricManager); ArgumentCaptor<Boolean> allowCredentialsCaptor = ArgumentCaptor.forClass(Boolean.class); doNothing() .when(plugin) .sendAuthenticationRequest( any(AuthOptions.class), any(AuthStrings.class), allowCredentialsCaptor.capture(), any(AuthCompletionHandler.class)); @SuppressWarnings("unchecked") final Result<AuthResult> mockResult = mock(Result.class); plugin.authenticate(defaultOptions, dummyStrings, mockResult); assertTrue(allowCredentialsCaptor.getValue()); } @Test public void isDeviceSupportedReturnsFalse() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); assertFalse(plugin.isDeviceSupported()); } @Test public void deviceCanSupportBiometrics_returnsTrueForPresentNonEnrolledBiometrics() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); final BiometricManager mockBiometricManager = mock(BiometricManager.class); when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)) .thenReturn(BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED); plugin.setBiometricManager(mockBiometricManager); assertTrue(plugin.deviceCanSupportBiometrics()); } @Test public void deviceSupportsBiometrics_returnsTrueForPresentEnrolledBiometrics() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); final BiometricManager mockBiometricManager = mock(BiometricManager.class); when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)) .thenReturn(BiometricManager.BIOMETRIC_SUCCESS); plugin.setBiometricManager(mockBiometricManager); assertTrue(plugin.deviceCanSupportBiometrics()); } @Test public void deviceSupportsBiometrics_returnsFalseForNoBiometricHardware() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); final BiometricManager mockBiometricManager = mock(BiometricManager.class); when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)) .thenReturn(BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE); plugin.setBiometricManager(mockBiometricManager); assertFalse(plugin.deviceCanSupportBiometrics()); } @Test public void deviceSupportsBiometrics_returnsFalseForNullBiometricManager() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); plugin.setBiometricManager(null); assertFalse(plugin.deviceCanSupportBiometrics()); } @Test public void onDetachedFromActivity_ShouldReleaseActivity() { final Activity mockActivity = mock(Activity.class); final ActivityPluginBinding mockActivityBinding = mock(ActivityPluginBinding.class); when(mockActivityBinding.getActivity()).thenReturn(mockActivity); Context mockContext = mock(Context.class); when(mockActivity.getBaseContext()).thenReturn(mockContext); when(mockActivity.getApplicationContext()).thenReturn(mockContext); final HiddenLifecycleReference mockLifecycleReference = mock(HiddenLifecycleReference.class); when(mockActivityBinding.getLifecycle()).thenReturn(mockLifecycleReference); final Lifecycle mockLifecycle = mock(Lifecycle.class); when(mockLifecycleReference.getLifecycle()).thenReturn(mockLifecycle); final FlutterPluginBinding mockPluginBinding = mock(FlutterPluginBinding.class); final BinaryMessenger mockMessenger = mock(BinaryMessenger.class); when(mockPluginBinding.getBinaryMessenger()).thenReturn(mockMessenger); final LocalAuthPlugin plugin = new LocalAuthPlugin(); plugin.onAttachedToEngine(mockPluginBinding); plugin.onAttachedToActivity(mockActivityBinding); assertNotNull(plugin.getActivity()); plugin.onDetachedFromActivity(); assertNull(plugin.getActivity()); } @Test public void getEnrolledBiometrics_shouldReturnEmptyList_withoutHardwarePresent() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); setPluginActivity(plugin, buildMockActivityWithContext(mock(Activity.class))); final BiometricManager mockBiometricManager = mock(BiometricManager.class); when(mockBiometricManager.canAuthenticate(anyInt())) .thenReturn(BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE); plugin.setBiometricManager(mockBiometricManager); final List<AuthClassificationWrapper> enrolled = plugin.getEnrolledBiometrics(); assertTrue(enrolled.isEmpty()); } @Test public void getEnrolledBiometrics_shouldReturnEmptyList_withNoMethodsEnrolled() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); setPluginActivity(plugin, buildMockActivityWithContext(mock(Activity.class))); final BiometricManager mockBiometricManager = mock(BiometricManager.class); when(mockBiometricManager.canAuthenticate(anyInt())) .thenReturn(BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED); plugin.setBiometricManager(mockBiometricManager); final List<AuthClassificationWrapper> enrolled = plugin.getEnrolledBiometrics(); assertTrue(enrolled.isEmpty()); } @Test public void getEnrolledBiometrics_shouldOnlyAddEnrolledBiometrics() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); setPluginActivity(plugin, buildMockActivityWithContext(mock(Activity.class))); final BiometricManager mockBiometricManager = mock(BiometricManager.class); when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)) .thenReturn(BiometricManager.BIOMETRIC_SUCCESS); when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG)) .thenReturn(BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED); plugin.setBiometricManager(mockBiometricManager); final List<AuthClassificationWrapper> enrolled = plugin.getEnrolledBiometrics(); assertEquals(1, enrolled.size()); assertEquals(AuthClassification.WEAK, enrolled.get(0).getValue()); } @Test public void getEnrolledBiometrics_shouldAddStrongBiometrics() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); setPluginActivity(plugin, buildMockActivityWithContext(mock(Activity.class))); final BiometricManager mockBiometricManager = mock(BiometricManager.class); when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)) .thenReturn(BiometricManager.BIOMETRIC_SUCCESS); when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG)) .thenReturn(BiometricManager.BIOMETRIC_SUCCESS); plugin.setBiometricManager(mockBiometricManager); final List<AuthClassificationWrapper> enrolled = plugin.getEnrolledBiometrics(); assertEquals(2, enrolled.size()); assertEquals(AuthClassification.WEAK, enrolled.get(0).getValue()); assertEquals(AuthClassification.STRONG, enrolled.get(1).getValue()); } @Test @Config(sdk = 22) public void isDeviceSecure_returnsFalseOnBelowApi23() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); assertFalse(plugin.isDeviceSecure()); } @Test @Config(sdk = 23) public void isDeviceSecure_returnsTrueIfDeviceIsSecure() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); KeyguardManager mockKeyguardManager = mock(KeyguardManager.class); plugin.setKeyguardManager(mockKeyguardManager); when(mockKeyguardManager.isDeviceSecure()).thenReturn(true); assertTrue(plugin.isDeviceSecure()); when(mockKeyguardManager.isDeviceSecure()).thenReturn(false); assertFalse(plugin.isDeviceSecure()); } @Test @Config(sdk = 30) public void canAuthenticateWithDeviceCredential_returnsTrueIfHasBiometricManagerSupportAboveApi30() { final LocalAuthPlugin plugin = new LocalAuthPlugin(); final BiometricManager mockBiometricManager = mock(BiometricManager.class); plugin.setBiometricManager(mockBiometricManager); when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL)) .thenReturn(BiometricManager.BIOMETRIC_SUCCESS); assertTrue(plugin.canAuthenticateWithDeviceCredential()); when(mockBiometricManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL)) .thenReturn(BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED); assertFalse(plugin.canAuthenticateWithDeviceCredential()); } private Activity buildMockActivityWithContext(Activity mockActivity) { final Context mockContext = mock(Context.class); when(mockActivity.getBaseContext()).thenReturn(mockContext); when(mockActivity.getApplicationContext()).thenReturn(mockContext); return mockActivity; } private void setPluginActivity(LocalAuthPlugin plugin, Activity activity) { final HiddenLifecycleReference mockLifecycleReference = mock(HiddenLifecycleReference.class); final FlutterPluginBinding mockPluginBinding = mock(FlutterPluginBinding.class); final ActivityPluginBinding mockActivityBinding = mock(ActivityPluginBinding.class); final BinaryMessenger mockMessenger = mock(BinaryMessenger.class); when(mockPluginBinding.getBinaryMessenger()).thenReturn(mockMessenger); when(mockActivityBinding.getActivity()).thenReturn(activity); when(mockActivityBinding.getLifecycle()).thenReturn(mockLifecycleReference); plugin.onAttachedToEngine(mockPluginBinding); plugin.onAttachedToActivity(mockActivityBinding); } }
packages/packages/local_auth/local_auth_android/android/src/test/java/io/flutter/plugins/localauth/LocalAuthTest.java/0
{ "file_path": "packages/packages/local_auth/local_auth_android/android/src/test/java/io/flutter/plugins/localauth/LocalAuthTest.java", "repo_id": "packages", "token_count": 5911 }
1,233
include ':app' def flutterProjectRoot = rootProject.projectDir.parentFile.toPath() def plugins = new Properties() def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins') if (pluginsFile.exists()) { pluginsFile.withInputStream { stream -> plugins.load(stream) } } plugins.each { name, path -> def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() include ":$name" project(":$name").projectDir = pluginDirectory } // See https://github.com/flutter/flutter/wiki/Plugins-and-Packages-repository-structure#gradle-structure for more info. buildscript { repositories { maven { url "https://plugins.gradle.org/m2/" } } dependencies { classpath "gradle.plugin.com.google.cloud.artifactregistry:artifactregistry-gradle-plugin:2.2.1" } } apply plugin: "com.google.cloud.artifactregistry.gradle-plugin"
packages/packages/local_auth/local_auth_android/example/android/settings.gradle/0
{ "file_path": "packages/packages/local_auth/local_auth_android/example/android/settings.gradle", "repo_id": "packages", "token_count": 305 }
1,234
// 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.1.2), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; PlatformException _createConnectionError(String channelName) { return PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel: "$channelName".', ); } /// Possible outcomes of an authentication attempt. enum AuthResult { /// The user authenticated successfully. success, /// The user failed to successfully authenticate. failure, /// The authentication system was not available. errorNotAvailable, /// No biometrics are enrolled. errorNotEnrolled, /// No passcode is set. errorPasscodeNotSet, } /// Pigeon equivalent of the subset of BiometricType used by iOS. enum AuthBiometric { face, fingerprint, } /// Pigeon version of IOSAuthMessages, plus the authorization reason. /// /// See auth_messages_ios.dart for details. class AuthStrings { AuthStrings({ required this.reason, required this.lockOut, required this.goToSettingsButton, required this.goToSettingsDescription, required this.cancelButton, this.localizedFallbackTitle, }); String reason; String lockOut; String goToSettingsButton; String goToSettingsDescription; String cancelButton; String? localizedFallbackTitle; Object encode() { return <Object?>[ reason, lockOut, goToSettingsButton, goToSettingsDescription, cancelButton, localizedFallbackTitle, ]; } static AuthStrings decode(Object result) { result as List<Object?>; return AuthStrings( reason: result[0]! as String, lockOut: result[1]! as String, goToSettingsButton: result[2]! as String, goToSettingsDescription: result[3]! as String, cancelButton: result[4]! as String, localizedFallbackTitle: result[5] as String?, ); } } class AuthOptions { AuthOptions({ required this.biometricOnly, required this.sticky, required this.useErrorDialogs, }); bool biometricOnly; bool sticky; bool useErrorDialogs; Object encode() { return <Object?>[ biometricOnly, sticky, useErrorDialogs, ]; } static AuthOptions decode(Object result) { result as List<Object?>; return AuthOptions( biometricOnly: result[0]! as bool, sticky: result[1]! as bool, useErrorDialogs: result[2]! as bool, ); } } class AuthResultDetails { AuthResultDetails({ required this.result, this.errorMessage, this.errorDetails, }); /// The result of authenticating. AuthResult result; /// A system-provided error message, if any. String? errorMessage; /// System-provided error details, if any. String? errorDetails; Object encode() { return <Object?>[ result.index, errorMessage, errorDetails, ]; } static AuthResultDetails decode(Object result) { result as List<Object?>; return AuthResultDetails( result: AuthResult.values[result[0]! as int], errorMessage: result[1] as String?, errorDetails: result[2] as String?, ); } } class AuthBiometricWrapper { AuthBiometricWrapper({ required this.value, }); AuthBiometric value; Object encode() { return <Object?>[ value.index, ]; } static AuthBiometricWrapper decode(Object result) { result as List<Object?>; return AuthBiometricWrapper( value: AuthBiometric.values[result[0]! as int], ); } } class _LocalAuthApiCodec extends StandardMessageCodec { const _LocalAuthApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is AuthBiometricWrapper) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is AuthOptions) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is AuthResultDetails) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else if (value is AuthStrings) { buffer.putUint8(131); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return AuthBiometricWrapper.decode(readValue(buffer)!); case 129: return AuthOptions.decode(readValue(buffer)!); case 130: return AuthResultDetails.decode(readValue(buffer)!); case 131: return AuthStrings.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class LocalAuthApi { /// Constructor for [LocalAuthApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. LocalAuthApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = _LocalAuthApiCodec(); /// Returns true if this device supports authentication. Future<bool> isDeviceSupported() async { const String channelName = 'dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.isDeviceSupported'; final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( channelName, codec, binaryMessenger: _binaryMessenger, ); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw _createConnectionError(channelName); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Returns true if this device can support biometric authentication, whether /// any biometrics are enrolled or not. Future<bool> deviceCanSupportBiometrics() async { const String channelName = 'dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.deviceCanSupportBiometrics'; final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( channelName, codec, binaryMessenger: _binaryMessenger, ); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw _createConnectionError(channelName); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as bool?)!; } } /// Returns the biometric types that are enrolled, and can thus be used /// without additional setup. Future<List<AuthBiometricWrapper?>> getEnrolledBiometrics() async { const String channelName = 'dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.getEnrolledBiometrics'; final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( channelName, codec, binaryMessenger: _binaryMessenger, ); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw _createConnectionError(channelName); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as List<Object?>?)!.cast<AuthBiometricWrapper?>(); } } /// Attempts to authenticate the user with the provided [options], and using /// [strings] for any UI. Future<AuthResultDetails> authenticate( AuthOptions arg_options, AuthStrings arg_strings) async { const String channelName = 'dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.authenticate'; final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( channelName, codec, binaryMessenger: _binaryMessenger, ); final List<Object?>? replyList = await channel .send(<Object?>[arg_options, arg_strings]) as List<Object?>?; if (replyList == null) { throw _createConnectionError(channelName); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (replyList[0] as AuthResultDetails?)!; } } }
packages/packages/local_auth/local_auth_darwin/lib/src/messages.g.dart/0
{ "file_path": "packages/packages/local_auth/local_auth_darwin/lib/src/messages.g.dart", "repo_id": "packages", "token_count": 3572 }
1,235
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:local_auth_platform_interface/types/auth_messages.dart'; /// Windows side authentication messages. /// /// Provides default values for all messages. /// /// Currently unused. @immutable class WindowsAuthMessages extends AuthMessages { /// Constructs a new instance. const WindowsAuthMessages(); @override Map<String, String> get args { return <String, String>{}; } }
packages/packages/local_auth/local_auth_windows/lib/types/auth_messages_windows.dart/0
{ "file_path": "packages/packages/local_auth/local_auth_windows/lib/types/auth_messages_windows.dart", "repo_id": "packages", "token_count": 169 }
1,236
## 1.0.13 * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. * Updates dependency on `package:googleapis` to `^12.0.0`. ## 1.0.12 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 1.0.11 * Removes the dependency on `package:equatable`. ## 1.0.10 * Adds retry logic when removing a `GcsLock` file lock in case of failure. ## 1.0.9 * Adds compatibility with `http` 1.0. ## 1.0.8 * Removes obsolete null checks on non-nullable values. * Updates minimum Flutter version to 3.3. ## 1.0.7 * Updates code to fix strict-cast violations. * Updates minimum SDK version to Flutter 3.0. ## 1.0.6 - Fixes lint warnings. ## 1.0.5 - Fix JSON parsing issue when running in sound null-safety mode. ## 1.0.4 - Fix un-await-ed Future in `SkiaPerfDestination.update`. ## 1.0.3 - Filter out host_name, load_avg and caches keys from context before adding to a MetricPoint object. ## 1.0.2 - Updated the GoogleBenchmark parser to correctly parse new keys added in the JSON schema. - Fix `unnecessary_import` lint errors. - Update version titles in CHANGELOG.md so plugins tooling understands them. - (Moved from `# X.Y.Z` to `## X.Y.Z`) ## 1.0.1 - `update` now requires taskName to scale metric writes ## 1.0.0 - Null safety support ## 0.1.1 - Update packages to null safe ## 0.1.0 - `update` now requires DateTime when commit was merged - Removed `github` dependency ## 0.0.9 - Remove legacy datastore and destination. ## 0.0.8 - Allow tests to override LegacyFlutterDestination GCP project id. ## 0.0.7 - Expose constants that were missing since 0.0.4+1. ## 0.0.6 - Allow `datastoreFromCredentialsJson` to specify project id. ## 0.0.5 - `FlutterDestination` writes into both Skia perf GCS and the legacy datastore. - `FlutterDestination.makeFromAccessToken` returns a `Future`. ## 0.0.4+1 - Moved to the `flutter/packages` repository
packages/packages/metrics_center/CHANGELOG.md/0
{ "file_path": "packages/packages/metrics_center/CHANGELOG.md", "repo_id": "packages", "token_count": 675 }
1,237
// Mocks generated by Mockito 5.4.4 from annotations // in metrics_center/test/gcs_lock_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i6; import 'dart:convert' as _i7; import 'dart:typed_data' as _i9; import 'package:_discoveryapis_commons/_discoveryapis_commons.dart' as _i10; import 'package:googleapis/storage/v1.dart' as _i4; import 'package:googleapis_auth/src/access_credentials.dart' as _i2; import 'package:googleapis_auth/src/auth_client.dart' as _i5; import 'package:http/http.dart' as _i3; import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i8; // 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 _FakeAccessCredentials_0 extends _i1.SmartFake implements _i2.AccessCredentials { _FakeAccessCredentials_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeResponse_1 extends _i1.SmartFake implements _i3.Response { _FakeResponse_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeStreamedResponse_2 extends _i1.SmartFake implements _i3.StreamedResponse { _FakeStreamedResponse_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeAnywhereCacheResource_3 extends _i1.SmartFake implements _i4.AnywhereCacheResource { _FakeAnywhereCacheResource_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeBucketAccessControlsResource_4 extends _i1.SmartFake implements _i4.BucketAccessControlsResource { _FakeBucketAccessControlsResource_4( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeBucketsResource_5 extends _i1.SmartFake implements _i4.BucketsResource { _FakeBucketsResource_5( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeChannelsResource_6 extends _i1.SmartFake implements _i4.ChannelsResource { _FakeChannelsResource_6( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeDefaultObjectAccessControlsResource_7 extends _i1.SmartFake implements _i4.DefaultObjectAccessControlsResource { _FakeDefaultObjectAccessControlsResource_7( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeManagedFoldersResource_8 extends _i1.SmartFake implements _i4.ManagedFoldersResource { _FakeManagedFoldersResource_8( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeNotificationsResource_9 extends _i1.SmartFake implements _i4.NotificationsResource { _FakeNotificationsResource_9( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeObjectAccessControlsResource_10 extends _i1.SmartFake implements _i4.ObjectAccessControlsResource { _FakeObjectAccessControlsResource_10( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeObjectsResource_11 extends _i1.SmartFake implements _i4.ObjectsResource { _FakeObjectsResource_11( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeOperationsResource_12 extends _i1.SmartFake implements _i4.OperationsResource { _FakeOperationsResource_12( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeProjectsResource_13 extends _i1.SmartFake implements _i4.ProjectsResource { _FakeProjectsResource_13( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeGoogleLongrunningOperation_14 extends _i1.SmartFake implements _i4.GoogleLongrunningOperation { _FakeGoogleLongrunningOperation_14( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeObject_15 extends _i1.SmartFake implements _i4.Object { _FakeObject_15( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeObject_16 extends _i1.SmartFake implements Object { _FakeObject_16( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakePolicy_17 extends _i1.SmartFake implements _i4.Policy { _FakePolicy_17( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeObjects_18 extends _i1.SmartFake implements _i4.Objects { _FakeObjects_18( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeRewriteResponse_19 extends _i1.SmartFake implements _i4.RewriteResponse { _FakeRewriteResponse_19( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeTestIamPermissionsResponse_20 extends _i1.SmartFake implements _i4.TestIamPermissionsResponse { _FakeTestIamPermissionsResponse_20( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeChannel_21 extends _i1.SmartFake implements _i4.Channel { _FakeChannel_21( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [AuthClient]. /// /// See the documentation for Mockito's code generation for more information. class MockAuthClient extends _i1.Mock implements _i5.AuthClient { MockAuthClient() { _i1.throwOnMissingStub(this); } @override _i2.AccessCredentials get credentials => (super.noSuchMethod( Invocation.getter(#credentials), returnValue: _FakeAccessCredentials_0( this, Invocation.getter(#credentials), ), ) as _i2.AccessCredentials); @override _i6.Future<_i3.Response> head( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #head, [url], {#headers: headers}, ), returnValue: _i6.Future<_i3.Response>.value(_FakeResponse_1( this, Invocation.method( #head, [url], {#headers: headers}, ), )), ) as _i6.Future<_i3.Response>); @override _i6.Future<_i3.Response> get( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #get, [url], {#headers: headers}, ), returnValue: _i6.Future<_i3.Response>.value(_FakeResponse_1( this, Invocation.method( #get, [url], {#headers: headers}, ), )), ) as _i6.Future<_i3.Response>); @override _i6.Future<_i3.Response> post( Uri? url, { Map<String, String>? headers, Object? body, _i7.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i6.Future<_i3.Response>.value(_FakeResponse_1( this, Invocation.method( #post, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i6.Future<_i3.Response>); @override _i6.Future<_i3.Response> put( Uri? url, { Map<String, String>? headers, Object? body, _i7.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i6.Future<_i3.Response>.value(_FakeResponse_1( this, Invocation.method( #put, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i6.Future<_i3.Response>); @override _i6.Future<_i3.Response> patch( Uri? url, { Map<String, String>? headers, Object? body, _i7.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i6.Future<_i3.Response>.value(_FakeResponse_1( this, Invocation.method( #patch, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i6.Future<_i3.Response>); @override _i6.Future<_i3.Response> delete( Uri? url, { Map<String, String>? headers, Object? body, _i7.Encoding? encoding, }) => (super.noSuchMethod( Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), returnValue: _i6.Future<_i3.Response>.value(_FakeResponse_1( this, Invocation.method( #delete, [url], { #headers: headers, #body: body, #encoding: encoding, }, ), )), ) as _i6.Future<_i3.Response>); @override _i6.Future<String> read( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #read, [url], {#headers: headers}, ), returnValue: _i6.Future<String>.value(_i8.dummyValue<String>( this, Invocation.method( #read, [url], {#headers: headers}, ), )), ) as _i6.Future<String>); @override _i6.Future<_i9.Uint8List> readBytes( Uri? url, { Map<String, String>? headers, }) => (super.noSuchMethod( Invocation.method( #readBytes, [url], {#headers: headers}, ), returnValue: _i6.Future<_i9.Uint8List>.value(_i9.Uint8List(0)), ) as _i6.Future<_i9.Uint8List>); @override _i6.Future<_i3.StreamedResponse> send(_i3.BaseRequest? request) => (super.noSuchMethod( Invocation.method( #send, [request], ), returnValue: _i6.Future<_i3.StreamedResponse>.value(_FakeStreamedResponse_2( this, Invocation.method( #send, [request], ), )), ) as _i6.Future<_i3.StreamedResponse>); @override void close() => super.noSuchMethod( Invocation.method( #close, [], ), returnValueForMissingStub: null, ); } /// A class which mocks [StorageApi]. /// /// See the documentation for Mockito's code generation for more information. class MockStorageApi extends _i1.Mock implements _i4.StorageApi { MockStorageApi() { _i1.throwOnMissingStub(this); } @override _i4.AnywhereCacheResource get anywhereCache => (super.noSuchMethod( Invocation.getter(#anywhereCache), returnValue: _FakeAnywhereCacheResource_3( this, Invocation.getter(#anywhereCache), ), ) as _i4.AnywhereCacheResource); @override _i4.BucketAccessControlsResource get bucketAccessControls => (super.noSuchMethod( Invocation.getter(#bucketAccessControls), returnValue: _FakeBucketAccessControlsResource_4( this, Invocation.getter(#bucketAccessControls), ), ) as _i4.BucketAccessControlsResource); @override _i4.BucketsResource get buckets => (super.noSuchMethod( Invocation.getter(#buckets), returnValue: _FakeBucketsResource_5( this, Invocation.getter(#buckets), ), ) as _i4.BucketsResource); @override _i4.ChannelsResource get channels => (super.noSuchMethod( Invocation.getter(#channels), returnValue: _FakeChannelsResource_6( this, Invocation.getter(#channels), ), ) as _i4.ChannelsResource); @override _i4.DefaultObjectAccessControlsResource get defaultObjectAccessControls => (super.noSuchMethod( Invocation.getter(#defaultObjectAccessControls), returnValue: _FakeDefaultObjectAccessControlsResource_7( this, Invocation.getter(#defaultObjectAccessControls), ), ) as _i4.DefaultObjectAccessControlsResource); @override _i4.ManagedFoldersResource get managedFolders => (super.noSuchMethod( Invocation.getter(#managedFolders), returnValue: _FakeManagedFoldersResource_8( this, Invocation.getter(#managedFolders), ), ) as _i4.ManagedFoldersResource); @override _i4.NotificationsResource get notifications => (super.noSuchMethod( Invocation.getter(#notifications), returnValue: _FakeNotificationsResource_9( this, Invocation.getter(#notifications), ), ) as _i4.NotificationsResource); @override _i4.ObjectAccessControlsResource get objectAccessControls => (super.noSuchMethod( Invocation.getter(#objectAccessControls), returnValue: _FakeObjectAccessControlsResource_10( this, Invocation.getter(#objectAccessControls), ), ) as _i4.ObjectAccessControlsResource); @override _i4.ObjectsResource get objects => (super.noSuchMethod( Invocation.getter(#objects), returnValue: _FakeObjectsResource_11( this, Invocation.getter(#objects), ), ) as _i4.ObjectsResource); @override _i4.OperationsResource get operations => (super.noSuchMethod( Invocation.getter(#operations), returnValue: _FakeOperationsResource_12( this, Invocation.getter(#operations), ), ) as _i4.OperationsResource); @override _i4.ProjectsResource get projects => (super.noSuchMethod( Invocation.getter(#projects), returnValue: _FakeProjectsResource_13( this, Invocation.getter(#projects), ), ) as _i4.ProjectsResource); } /// A class which mocks [ObjectsResource]. /// /// See the documentation for Mockito's code generation for more information. class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { @override _i6.Future<_i4.GoogleLongrunningOperation> bulkRestore( _i4.BulkRestoreObjectsRequest? request, String? bucket, { String? $fields, }) => (super.noSuchMethod( Invocation.method( #bulkRestore, [ request, bucket, ], {#$fields: $fields}, ), returnValue: _i6.Future<_i4.GoogleLongrunningOperation>.value( _FakeGoogleLongrunningOperation_14( this, Invocation.method( #bulkRestore, [ request, bucket, ], {#$fields: $fields}, ), )), returnValueForMissingStub: _i6.Future<_i4.GoogleLongrunningOperation>.value( _FakeGoogleLongrunningOperation_14( this, Invocation.method( #bulkRestore, [ request, bucket, ], {#$fields: $fields}, ), )), ) as _i6.Future<_i4.GoogleLongrunningOperation>); @override _i6.Future<_i4.Object> compose( _i4.ComposeRequest? request, String? destinationBucket, String? destinationObject, { String? destinationPredefinedAcl, String? ifGenerationMatch, String? ifMetagenerationMatch, String? kmsKeyName, String? userProject, String? $fields, }) => (super.noSuchMethod( Invocation.method( #compose, [ request, destinationBucket, destinationObject, ], { #destinationPredefinedAcl: destinationPredefinedAcl, #ifGenerationMatch: ifGenerationMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #kmsKeyName: kmsKeyName, #userProject: userProject, #$fields: $fields, }, ), returnValue: _i6.Future<_i4.Object>.value(_FakeObject_15( this, Invocation.method( #compose, [ request, destinationBucket, destinationObject, ], { #destinationPredefinedAcl: destinationPredefinedAcl, #ifGenerationMatch: ifGenerationMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #kmsKeyName: kmsKeyName, #userProject: userProject, #$fields: $fields, }, ), )), returnValueForMissingStub: _i6.Future<_i4.Object>.value(_FakeObject_15( this, Invocation.method( #compose, [ request, destinationBucket, destinationObject, ], { #destinationPredefinedAcl: destinationPredefinedAcl, #ifGenerationMatch: ifGenerationMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #kmsKeyName: kmsKeyName, #userProject: userProject, #$fields: $fields, }, ), )), ) as _i6.Future<_i4.Object>); @override _i6.Future<_i4.Object> copy( _i4.Object? request, String? sourceBucket, String? sourceObject, String? destinationBucket, String? destinationObject, { String? destinationKmsKeyName, String? destinationPredefinedAcl, String? ifGenerationMatch, String? ifGenerationNotMatch, String? ifMetagenerationMatch, String? ifMetagenerationNotMatch, String? ifSourceGenerationMatch, String? ifSourceGenerationNotMatch, String? ifSourceMetagenerationMatch, String? ifSourceMetagenerationNotMatch, String? projection, String? sourceGeneration, String? userProject, String? $fields, }) => (super.noSuchMethod( Invocation.method( #copy, [ request, sourceBucket, sourceObject, destinationBucket, destinationObject, ], { #destinationKmsKeyName: destinationKmsKeyName, #destinationPredefinedAcl: destinationPredefinedAcl, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #ifSourceGenerationMatch: ifSourceGenerationMatch, #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, #projection: projection, #sourceGeneration: sourceGeneration, #userProject: userProject, #$fields: $fields, }, ), returnValue: _i6.Future<_i4.Object>.value(_FakeObject_15( this, Invocation.method( #copy, [ request, sourceBucket, sourceObject, destinationBucket, destinationObject, ], { #destinationKmsKeyName: destinationKmsKeyName, #destinationPredefinedAcl: destinationPredefinedAcl, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #ifSourceGenerationMatch: ifSourceGenerationMatch, #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, #projection: projection, #sourceGeneration: sourceGeneration, #userProject: userProject, #$fields: $fields, }, ), )), returnValueForMissingStub: _i6.Future<_i4.Object>.value(_FakeObject_15( this, Invocation.method( #copy, [ request, sourceBucket, sourceObject, destinationBucket, destinationObject, ], { #destinationKmsKeyName: destinationKmsKeyName, #destinationPredefinedAcl: destinationPredefinedAcl, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #ifSourceGenerationMatch: ifSourceGenerationMatch, #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, #projection: projection, #sourceGeneration: sourceGeneration, #userProject: userProject, #$fields: $fields, }, ), )), ) as _i6.Future<_i4.Object>); @override _i6.Future<void> delete( String? bucket, String? object, { String? generation, String? ifGenerationMatch, String? ifGenerationNotMatch, String? ifMetagenerationMatch, String? ifMetagenerationNotMatch, String? userProject, String? $fields, }) => (super.noSuchMethod( Invocation.method( #delete, [ bucket, object, ], { #generation: generation, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #userProject: userProject, #$fields: $fields, }, ), returnValue: _i6.Future<void>.value(), returnValueForMissingStub: _i6.Future<void>.value(), ) as _i6.Future<void>); @override _i6.Future<Object> get( String? bucket, String? object, { String? generation, String? ifGenerationMatch, String? ifGenerationNotMatch, String? ifMetagenerationMatch, String? ifMetagenerationNotMatch, String? projection, bool? softDeleted, String? userProject, String? $fields, _i10.DownloadOptions? downloadOptions = _i10.DownloadOptions.metadata, }) => (super.noSuchMethod( Invocation.method( #get, [ bucket, object, ], { #generation: generation, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #projection: projection, #softDeleted: softDeleted, #userProject: userProject, #$fields: $fields, #downloadOptions: downloadOptions, }, ), returnValue: _i6.Future<Object>.value(_FakeObject_16( this, Invocation.method( #get, [ bucket, object, ], { #generation: generation, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #projection: projection, #softDeleted: softDeleted, #userProject: userProject, #$fields: $fields, #downloadOptions: downloadOptions, }, ), )), returnValueForMissingStub: _i6.Future<Object>.value(_FakeObject_16( this, Invocation.method( #get, [ bucket, object, ], { #generation: generation, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #projection: projection, #softDeleted: softDeleted, #userProject: userProject, #$fields: $fields, #downloadOptions: downloadOptions, }, ), )), ) as _i6.Future<Object>); @override _i6.Future<_i4.Policy> getIamPolicy( String? bucket, String? object, { String? generation, String? userProject, String? $fields, }) => (super.noSuchMethod( Invocation.method( #getIamPolicy, [ bucket, object, ], { #generation: generation, #userProject: userProject, #$fields: $fields, }, ), returnValue: _i6.Future<_i4.Policy>.value(_FakePolicy_17( this, Invocation.method( #getIamPolicy, [ bucket, object, ], { #generation: generation, #userProject: userProject, #$fields: $fields, }, ), )), returnValueForMissingStub: _i6.Future<_i4.Policy>.value(_FakePolicy_17( this, Invocation.method( #getIamPolicy, [ bucket, object, ], { #generation: generation, #userProject: userProject, #$fields: $fields, }, ), )), ) as _i6.Future<_i4.Policy>); @override _i6.Future<_i4.Object> insert( _i4.Object? request, String? bucket, { String? contentEncoding, String? ifGenerationMatch, String? ifGenerationNotMatch, String? ifMetagenerationMatch, String? ifMetagenerationNotMatch, String? kmsKeyName, String? name, String? predefinedAcl, String? projection, String? userProject, String? $fields, _i10.UploadOptions? uploadOptions = _i10.UploadOptions.defaultOptions, _i10.Media? uploadMedia, }) => (super.noSuchMethod( Invocation.method( #insert, [ request, bucket, ], { #contentEncoding: contentEncoding, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #kmsKeyName: kmsKeyName, #name: name, #predefinedAcl: predefinedAcl, #projection: projection, #userProject: userProject, #$fields: $fields, #uploadOptions: uploadOptions, #uploadMedia: uploadMedia, }, ), returnValue: _i6.Future<_i4.Object>.value(_FakeObject_15( this, Invocation.method( #insert, [ request, bucket, ], { #contentEncoding: contentEncoding, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #kmsKeyName: kmsKeyName, #name: name, #predefinedAcl: predefinedAcl, #projection: projection, #userProject: userProject, #$fields: $fields, #uploadOptions: uploadOptions, #uploadMedia: uploadMedia, }, ), )), returnValueForMissingStub: _i6.Future<_i4.Object>.value(_FakeObject_15( this, Invocation.method( #insert, [ request, bucket, ], { #contentEncoding: contentEncoding, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #kmsKeyName: kmsKeyName, #name: name, #predefinedAcl: predefinedAcl, #projection: projection, #userProject: userProject, #$fields: $fields, #uploadOptions: uploadOptions, #uploadMedia: uploadMedia, }, ), )), ) as _i6.Future<_i4.Object>); @override _i6.Future<_i4.Objects> list( String? bucket, { String? delimiter, String? endOffset, bool? includeFoldersAsPrefixes, bool? includeTrailingDelimiter, String? matchGlob, int? maxResults, String? pageToken, String? prefix, String? projection, bool? softDeleted, String? startOffset, String? userProject, bool? versions, String? $fields, }) => (super.noSuchMethod( Invocation.method( #list, [bucket], { #delimiter: delimiter, #endOffset: endOffset, #includeFoldersAsPrefixes: includeFoldersAsPrefixes, #includeTrailingDelimiter: includeTrailingDelimiter, #matchGlob: matchGlob, #maxResults: maxResults, #pageToken: pageToken, #prefix: prefix, #projection: projection, #softDeleted: softDeleted, #startOffset: startOffset, #userProject: userProject, #versions: versions, #$fields: $fields, }, ), returnValue: _i6.Future<_i4.Objects>.value(_FakeObjects_18( this, Invocation.method( #list, [bucket], { #delimiter: delimiter, #endOffset: endOffset, #includeFoldersAsPrefixes: includeFoldersAsPrefixes, #includeTrailingDelimiter: includeTrailingDelimiter, #matchGlob: matchGlob, #maxResults: maxResults, #pageToken: pageToken, #prefix: prefix, #projection: projection, #softDeleted: softDeleted, #startOffset: startOffset, #userProject: userProject, #versions: versions, #$fields: $fields, }, ), )), returnValueForMissingStub: _i6.Future<_i4.Objects>.value(_FakeObjects_18( this, Invocation.method( #list, [bucket], { #delimiter: delimiter, #endOffset: endOffset, #includeFoldersAsPrefixes: includeFoldersAsPrefixes, #includeTrailingDelimiter: includeTrailingDelimiter, #matchGlob: matchGlob, #maxResults: maxResults, #pageToken: pageToken, #prefix: prefix, #projection: projection, #softDeleted: softDeleted, #startOffset: startOffset, #userProject: userProject, #versions: versions, #$fields: $fields, }, ), )), ) as _i6.Future<_i4.Objects>); @override _i6.Future<_i4.Object> patch( _i4.Object? request, String? bucket, String? object, { String? generation, String? ifGenerationMatch, String? ifGenerationNotMatch, String? ifMetagenerationMatch, String? ifMetagenerationNotMatch, bool? overrideUnlockedRetention, String? predefinedAcl, String? projection, String? userProject, String? $fields, }) => (super.noSuchMethod( Invocation.method( #patch, [ request, bucket, object, ], { #generation: generation, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #overrideUnlockedRetention: overrideUnlockedRetention, #predefinedAcl: predefinedAcl, #projection: projection, #userProject: userProject, #$fields: $fields, }, ), returnValue: _i6.Future<_i4.Object>.value(_FakeObject_15( this, Invocation.method( #patch, [ request, bucket, object, ], { #generation: generation, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #overrideUnlockedRetention: overrideUnlockedRetention, #predefinedAcl: predefinedAcl, #projection: projection, #userProject: userProject, #$fields: $fields, }, ), )), returnValueForMissingStub: _i6.Future<_i4.Object>.value(_FakeObject_15( this, Invocation.method( #patch, [ request, bucket, object, ], { #generation: generation, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #overrideUnlockedRetention: overrideUnlockedRetention, #predefinedAcl: predefinedAcl, #projection: projection, #userProject: userProject, #$fields: $fields, }, ), )), ) as _i6.Future<_i4.Object>); @override _i6.Future<_i4.Object> restore( _i4.Object? request, String? bucket, String? object, String? generation, { bool? copySourceAcl, String? ifGenerationMatch, String? ifGenerationNotMatch, String? ifMetagenerationMatch, String? ifMetagenerationNotMatch, String? projection, String? userProject, String? $fields, }) => (super.noSuchMethod( Invocation.method( #restore, [ request, bucket, object, generation, ], { #copySourceAcl: copySourceAcl, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #projection: projection, #userProject: userProject, #$fields: $fields, }, ), returnValue: _i6.Future<_i4.Object>.value(_FakeObject_15( this, Invocation.method( #restore, [ request, bucket, object, generation, ], { #copySourceAcl: copySourceAcl, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #projection: projection, #userProject: userProject, #$fields: $fields, }, ), )), returnValueForMissingStub: _i6.Future<_i4.Object>.value(_FakeObject_15( this, Invocation.method( #restore, [ request, bucket, object, generation, ], { #copySourceAcl: copySourceAcl, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #projection: projection, #userProject: userProject, #$fields: $fields, }, ), )), ) as _i6.Future<_i4.Object>); @override _i6.Future<_i4.RewriteResponse> rewrite( _i4.Object? request, String? sourceBucket, String? sourceObject, String? destinationBucket, String? destinationObject, { String? destinationKmsKeyName, String? destinationPredefinedAcl, String? ifGenerationMatch, String? ifGenerationNotMatch, String? ifMetagenerationMatch, String? ifMetagenerationNotMatch, String? ifSourceGenerationMatch, String? ifSourceGenerationNotMatch, String? ifSourceMetagenerationMatch, String? ifSourceMetagenerationNotMatch, String? maxBytesRewrittenPerCall, String? projection, String? rewriteToken, String? sourceGeneration, String? userProject, String? $fields, }) => (super.noSuchMethod( Invocation.method( #rewrite, [ request, sourceBucket, sourceObject, destinationBucket, destinationObject, ], { #destinationKmsKeyName: destinationKmsKeyName, #destinationPredefinedAcl: destinationPredefinedAcl, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #ifSourceGenerationMatch: ifSourceGenerationMatch, #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, #projection: projection, #rewriteToken: rewriteToken, #sourceGeneration: sourceGeneration, #userProject: userProject, #$fields: $fields, }, ), returnValue: _i6.Future<_i4.RewriteResponse>.value(_FakeRewriteResponse_19( this, Invocation.method( #rewrite, [ request, sourceBucket, sourceObject, destinationBucket, destinationObject, ], { #destinationKmsKeyName: destinationKmsKeyName, #destinationPredefinedAcl: destinationPredefinedAcl, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #ifSourceGenerationMatch: ifSourceGenerationMatch, #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, #projection: projection, #rewriteToken: rewriteToken, #sourceGeneration: sourceGeneration, #userProject: userProject, #$fields: $fields, }, ), )), returnValueForMissingStub: _i6.Future<_i4.RewriteResponse>.value(_FakeRewriteResponse_19( this, Invocation.method( #rewrite, [ request, sourceBucket, sourceObject, destinationBucket, destinationObject, ], { #destinationKmsKeyName: destinationKmsKeyName, #destinationPredefinedAcl: destinationPredefinedAcl, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #ifSourceGenerationMatch: ifSourceGenerationMatch, #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, #projection: projection, #rewriteToken: rewriteToken, #sourceGeneration: sourceGeneration, #userProject: userProject, #$fields: $fields, }, ), )), ) as _i6.Future<_i4.RewriteResponse>); @override _i6.Future<_i4.Policy> setIamPolicy( _i4.Policy? request, String? bucket, String? object, { String? generation, String? userProject, String? $fields, }) => (super.noSuchMethod( Invocation.method( #setIamPolicy, [ request, bucket, object, ], { #generation: generation, #userProject: userProject, #$fields: $fields, }, ), returnValue: _i6.Future<_i4.Policy>.value(_FakePolicy_17( this, Invocation.method( #setIamPolicy, [ request, bucket, object, ], { #generation: generation, #userProject: userProject, #$fields: $fields, }, ), )), returnValueForMissingStub: _i6.Future<_i4.Policy>.value(_FakePolicy_17( this, Invocation.method( #setIamPolicy, [ request, bucket, object, ], { #generation: generation, #userProject: userProject, #$fields: $fields, }, ), )), ) as _i6.Future<_i4.Policy>); @override _i6.Future<_i4.TestIamPermissionsResponse> testIamPermissions( String? bucket, String? object, List<String>? permissions, { String? generation, String? userProject, String? $fields, }) => (super.noSuchMethod( Invocation.method( #testIamPermissions, [ bucket, object, permissions, ], { #generation: generation, #userProject: userProject, #$fields: $fields, }, ), returnValue: _i6.Future<_i4.TestIamPermissionsResponse>.value( _FakeTestIamPermissionsResponse_20( this, Invocation.method( #testIamPermissions, [ bucket, object, permissions, ], { #generation: generation, #userProject: userProject, #$fields: $fields, }, ), )), returnValueForMissingStub: _i6.Future<_i4.TestIamPermissionsResponse>.value( _FakeTestIamPermissionsResponse_20( this, Invocation.method( #testIamPermissions, [ bucket, object, permissions, ], { #generation: generation, #userProject: userProject, #$fields: $fields, }, ), )), ) as _i6.Future<_i4.TestIamPermissionsResponse>); @override _i6.Future<_i4.Object> update( _i4.Object? request, String? bucket, String? object, { String? generation, String? ifGenerationMatch, String? ifGenerationNotMatch, String? ifMetagenerationMatch, String? ifMetagenerationNotMatch, bool? overrideUnlockedRetention, String? predefinedAcl, String? projection, String? userProject, String? $fields, }) => (super.noSuchMethod( Invocation.method( #update, [ request, bucket, object, ], { #generation: generation, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #overrideUnlockedRetention: overrideUnlockedRetention, #predefinedAcl: predefinedAcl, #projection: projection, #userProject: userProject, #$fields: $fields, }, ), returnValue: _i6.Future<_i4.Object>.value(_FakeObject_15( this, Invocation.method( #update, [ request, bucket, object, ], { #generation: generation, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #overrideUnlockedRetention: overrideUnlockedRetention, #predefinedAcl: predefinedAcl, #projection: projection, #userProject: userProject, #$fields: $fields, }, ), )), returnValueForMissingStub: _i6.Future<_i4.Object>.value(_FakeObject_15( this, Invocation.method( #update, [ request, bucket, object, ], { #generation: generation, #ifGenerationMatch: ifGenerationMatch, #ifGenerationNotMatch: ifGenerationNotMatch, #ifMetagenerationMatch: ifMetagenerationMatch, #ifMetagenerationNotMatch: ifMetagenerationNotMatch, #overrideUnlockedRetention: overrideUnlockedRetention, #predefinedAcl: predefinedAcl, #projection: projection, #userProject: userProject, #$fields: $fields, }, ), )), ) as _i6.Future<_i4.Object>); @override _i6.Future<_i4.Channel> watchAll( _i4.Channel? request, String? bucket, { String? delimiter, String? endOffset, bool? includeTrailingDelimiter, int? maxResults, String? pageToken, String? prefix, String? projection, String? startOffset, String? userProject, bool? versions, String? $fields, }) => (super.noSuchMethod( Invocation.method( #watchAll, [ request, bucket, ], { #delimiter: delimiter, #endOffset: endOffset, #includeTrailingDelimiter: includeTrailingDelimiter, #maxResults: maxResults, #pageToken: pageToken, #prefix: prefix, #projection: projection, #startOffset: startOffset, #userProject: userProject, #versions: versions, #$fields: $fields, }, ), returnValue: _i6.Future<_i4.Channel>.value(_FakeChannel_21( this, Invocation.method( #watchAll, [ request, bucket, ], { #delimiter: delimiter, #endOffset: endOffset, #includeTrailingDelimiter: includeTrailingDelimiter, #maxResults: maxResults, #pageToken: pageToken, #prefix: prefix, #projection: projection, #startOffset: startOffset, #userProject: userProject, #versions: versions, #$fields: $fields, }, ), )), returnValueForMissingStub: _i6.Future<_i4.Channel>.value(_FakeChannel_21( this, Invocation.method( #watchAll, [ request, bucket, ], { #delimiter: delimiter, #endOffset: endOffset, #includeTrailingDelimiter: includeTrailingDelimiter, #maxResults: maxResults, #pageToken: pageToken, #prefix: prefix, #projection: projection, #startOffset: startOffset, #userProject: userProject, #versions: versions, #$fields: $fields, }, ), )), ) as _i6.Future<_i4.Channel>); }
packages/packages/metrics_center/test/gcs_lock_test.mocks.dart/0
{ "file_path": "packages/packages/metrics_center/test/gcs_lock_test.mocks.dart", "repo_id": "packages", "token_count": 26108 }
1,238
// 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:collection'; import 'resource_record.dart'; /// Cache for resource records that have been received. /// /// There can be multiple entries for the same name and type. /// /// The cache is updated with a list of records, because it needs to remove /// all entries that correspond to the name and type of the name/type /// combinations of records that should be updated. For example, a host may /// remove one of its IP addresses and report the remaining address as a /// response - then we need to clear all previous entries for that host before /// updating the cache. class ResourceRecordCache { /// Creates a new ResourceRecordCache. ResourceRecordCache(); final Map<int, SplayTreeMap<String, List<ResourceRecord>>> _cache = <int, SplayTreeMap<String, List<ResourceRecord>>>{}; /// The number of entries in the cache. int get entryCount { int count = 0; for (final SplayTreeMap<String, List<ResourceRecord>> map in _cache.values) { for (final List<ResourceRecord> records in map.values) { count += records.length; } } return count; } /// Update the records in this cache. void updateRecords(List<ResourceRecord> records) { // TODO(karlklose): include flush bit in the record and only flush if // necessary. // Clear the cache for all name/type combinations to be updated. final Map<int, Set<String>> seenRecordTypes = <int, Set<String>>{}; for (final ResourceRecord record in records) { // TODO(dnfield): Update this to use set literal syntax when we're able to bump the SDK constraint. seenRecordTypes[record.resourceRecordType] ??= Set<String>(); // ignore: prefer_collection_literals if (seenRecordTypes[record.resourceRecordType]!.add(record.name)) { _cache[record.resourceRecordType] ??= SplayTreeMap<String, List<ResourceRecord>>(); _cache[record.resourceRecordType]![record.name] = <ResourceRecord>[ record ]; } else { _cache[record.resourceRecordType]![record.name]!.add(record); } } } /// Get a record from this cache. void lookup<T extends ResourceRecord>( String name, int type, List<T> results) { assert(ResourceRecordType.debugAssertValid(type)); final int time = DateTime.now().millisecondsSinceEpoch; final SplayTreeMap<String, List<ResourceRecord>>? candidates = _cache[type]; if (candidates == null) { return; } final List<ResourceRecord>? candidateRecords = candidates[name]; if (candidateRecords == null) { return; } candidateRecords .removeWhere((ResourceRecord candidate) => candidate.validUntil < time); results.addAll(candidateRecords.cast<T>()); } }
packages/packages/multicast_dns/lib/src/native_protocol_client.dart/0
{ "file_path": "packages/packages/multicast_dns/lib/src/native_protocol_client.dart", "repo_id": "packages", "token_count": 947 }
1,239
# image_colors A sample app for demonstrating the PaletteGenerator This app will show you what kinds of palettes the generator creates, and one way to create them from existing image providers.
packages/packages/palette_generator/example/README.md/0
{ "file_path": "packages/packages/palette_generator/example/README.md", "repo_id": "packages", "token_count": 45 }
1,240
org.gradle.jvmargs=-Xmx1536M android.enableR8=true android.useAndroidX=true android.enableJetifier=true
packages/packages/palette_generator/example/android/gradle.properties/0
{ "file_path": "packages/packages/palette_generator/example/android/gradle.properties", "repo_id": "packages", "token_count": 39 }
1,241
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <flutter/dart_project.h> #include <flutter/flutter_view_controller.h> #include <windows.h> #include "flutter_window.h" #include "run_loop.h" #include "utils.h" int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, _In_ wchar_t* command_line, _In_ int show_command) { // Attach to console when present (e.g., 'flutter run') or create a // new console when running with a debugger. if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { CreateAndAttachConsole(); } // Initialize COM, so that it is available for use in the library and/or // plugins. ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); RunLoop run_loop; flutter::DartProject project(L"data"); FlutterWindow window(&run_loop, project); Win32Window::Point origin(10, 10); Win32Window::Size size(1280, 720); if (!window.CreateAndShow(L"example", origin, size)) { return EXIT_FAILURE; } window.SetQuitOnClose(true); run_loop.Run(); ::CoUninitialize(); return EXIT_SUCCESS; }
packages/packages/path_provider/path_provider/example/windows/runner/main.cpp/0
{ "file_path": "packages/packages/path_provider/path_provider/example/windows/runner/main.cpp", "repo_id": "packages", "token_count": 434 }
1,242
# path\_provider\_android The Android implementation of [`path_provider`][1]. ## Usage This package is [endorsed][2], which means you can simply use `path_provider` normally. This package will be automatically included in your app when you do, so you do not need to add it to your `pubspec.yaml`. However, if you `import` this package to use any of its APIs directly, you should add it to your `pubspec.yaml` as usual. [1]: https://pub.dev/packages/path_provider [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
packages/packages/path_provider/path_provider_android/README.md/0
{ "file_path": "packages/packages/path_provider/path_provider_android/README.md", "repo_id": "packages", "token_count": 177 }
1,243
name: path_provider_android description: Android implementation of the path_provider plugin. repository: https://github.com/flutter/packages/tree/main/packages/path_provider/path_provider_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+path_provider%22 version: 2.2.2 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: path_provider platforms: android: package: io.flutter.plugins.pathprovider pluginClass: PathProviderPlugin dartPluginClass: PathProviderAndroid dependencies: flutter: sdk: flutter path_provider_platform_interface: ^2.1.0 dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter pigeon: ^9.2.4 test: ^1.16.0 topics: - files - path-provider - paths
packages/packages/path_provider/path_provider_android/pubspec.yaml/0
{ "file_path": "packages/packages/path_provider/path_provider_android/pubspec.yaml", "repo_id": "packages", "token_count": 339 }
1,244
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path_provider_platform_interface/src/enums.dart'; import 'package:path_provider_platform_interface/src/method_channel_path_provider.dart'; import 'package:platform/platform.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); const String kTemporaryPath = 'temporaryPath'; const String kApplicationSupportPath = 'applicationSupportPath'; const String kLibraryPath = 'libraryPath'; const String kApplicationDocumentsPath = 'applicationDocumentsPath'; const String kApplicationCachePath = 'applicationCachePath'; const String kExternalCachePaths = 'externalCachePaths'; const String kExternalStoragePaths = 'externalStoragePaths'; const String kDownloadsPath = 'downloadsPath'; group('$MethodChannelPathProvider', () { late MethodChannelPathProvider methodChannelPathProvider; final List<MethodCall> log = <MethodCall>[]; setUp(() async { methodChannelPathProvider = MethodChannelPathProvider(); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(methodChannelPathProvider.methodChannel, (MethodCall methodCall) async { log.add(methodCall); switch (methodCall.method) { case 'getTemporaryDirectory': return kTemporaryPath; case 'getApplicationSupportDirectory': return kApplicationSupportPath; case 'getLibraryDirectory': return kLibraryPath; case 'getApplicationDocumentsDirectory': return kApplicationDocumentsPath; case 'getApplicationCacheDirectory': return kApplicationCachePath; case 'getExternalStorageDirectories': return <String>[kExternalStoragePaths]; case 'getExternalCacheDirectories': return <String>[kExternalCachePaths]; case 'getDownloadsDirectory': return kDownloadsPath; default: return null; } }); }); setUp(() { methodChannelPathProvider.setMockPathProviderPlatform( FakePlatform(operatingSystem: 'android')); }); tearDown(() { log.clear(); }); test('getTemporaryPath', () async { final String? path = await methodChannelPathProvider.getTemporaryPath(); expect( log, <Matcher>[isMethodCall('getTemporaryDirectory', arguments: null)], ); expect(path, kTemporaryPath); }); test('getApplicationSupportPath', () async { final String? path = await methodChannelPathProvider.getApplicationSupportPath(); expect( log, <Matcher>[ isMethodCall('getApplicationSupportDirectory', arguments: null) ], ); expect(path, kApplicationSupportPath); }); test('getLibraryPath android fails', () async { try { await methodChannelPathProvider.getLibraryPath(); fail('should throw UnsupportedError'); } catch (e) { expect(e, isUnsupportedError); } }); test('getLibraryPath iOS succeeds', () async { methodChannelPathProvider .setMockPathProviderPlatform(FakePlatform(operatingSystem: 'ios')); final String? path = await methodChannelPathProvider.getLibraryPath(); expect( log, <Matcher>[isMethodCall('getLibraryDirectory', arguments: null)], ); expect(path, kLibraryPath); }); test('getLibraryPath macOS succeeds', () async { methodChannelPathProvider .setMockPathProviderPlatform(FakePlatform(operatingSystem: 'macos')); final String? path = await methodChannelPathProvider.getLibraryPath(); expect( log, <Matcher>[isMethodCall('getLibraryDirectory', arguments: null)], ); expect(path, kLibraryPath); }); test('getApplicationDocumentsPath', () async { final String? path = await methodChannelPathProvider.getApplicationDocumentsPath(); expect( log, <Matcher>[ isMethodCall('getApplicationDocumentsDirectory', arguments: null) ], ); expect(path, kApplicationDocumentsPath); }); test('getApplicationCachePath succeeds', () async { final String? result = await methodChannelPathProvider.getApplicationCachePath(); expect( log, <Matcher>[ isMethodCall('getApplicationCacheDirectory', arguments: null) ], ); expect(result, kApplicationCachePath); }); test('getExternalCachePaths android succeeds', () async { final List<String>? result = await methodChannelPathProvider.getExternalCachePaths(); expect( log, <Matcher>[isMethodCall('getExternalCacheDirectories', arguments: null)], ); expect(result!.length, 1); expect(result.first, kExternalCachePaths); }); test('getExternalCachePaths non-android fails', () async { methodChannelPathProvider .setMockPathProviderPlatform(FakePlatform(operatingSystem: 'ios')); try { await methodChannelPathProvider.getExternalCachePaths(); fail('should throw UnsupportedError'); } catch (e) { expect(e, isUnsupportedError); } }); for (final StorageDirectory? type in <StorageDirectory?>[ null, ...StorageDirectory.values ]) { test('getExternalStoragePaths (type: $type) android succeeds', () async { final List<String>? result = await methodChannelPathProvider.getExternalStoragePaths(type: type); expect( log, <Matcher>[ isMethodCall( 'getExternalStorageDirectories', arguments: <String, dynamic>{'type': type?.index}, ) ], ); expect(result!.length, 1); expect(result.first, kExternalStoragePaths); }); test('getExternalStoragePaths (type: $type) non-android fails', () async { methodChannelPathProvider .setMockPathProviderPlatform(FakePlatform(operatingSystem: 'ios')); try { await methodChannelPathProvider.getExternalStoragePaths(); fail('should throw UnsupportedError'); } catch (e) { expect(e, isUnsupportedError); } }); } // end of for-loop test('getDownloadsPath macos succeeds', () async { methodChannelPathProvider .setMockPathProviderPlatform(FakePlatform(operatingSystem: 'macos')); final String? result = await methodChannelPathProvider.getDownloadsPath(); expect( log, <Matcher>[isMethodCall('getDownloadsDirectory', arguments: null)], ); expect(result, kDownloadsPath); }); test('getDownloadsPath non-macos fails', () async { methodChannelPathProvider.setMockPathProviderPlatform( FakePlatform(operatingSystem: 'android')); try { await methodChannelPathProvider.getDownloadsPath(); fail('should throw UnsupportedError'); } catch (e) { expect(e, isUnsupportedError); } }); }); }
packages/packages/path_provider/path_provider_platform_interface/test/method_channel_path_provider_test.dart/0
{ "file_path": "packages/packages/path_provider/path_provider_platform_interface/test/method_channel_path_provider_test.dart", "repo_id": "packages", "token_count": 2806 }
1,245
// 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. // path_provider_windows is implemented using FFI; export a stub for platforms // that don't support FFI (e.g., web) to avoid having transitive dependencies // break web compilation. export 'src/folders_stub.dart' if (dart.library.ffi) 'src/folders.dart'; export 'src/path_provider_windows_stub.dart' if (dart.library.ffi) 'src/path_provider_windows_real.dart';
packages/packages/path_provider/path_provider_windows/lib/path_provider_windows.dart/0
{ "file_path": "packages/packages/path_provider/path_provider_windows/lib/path_provider_windows.dart", "repo_id": "packages", "token_count": 168 }
1,246
test_on: vm
packages/packages/pigeon/dart_test.yaml/0
{ "file_path": "packages/packages/pigeon/dart_test.yaml", "repo_id": "packages", "token_count": 6 }
1,247
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter_window.h" #include <memory> #include <optional> #include "flutter/generated_plugin_registrant.h" #include "messages.g.h" namespace { using pigeon_example::ErrorOr; using pigeon_example::ExampleHostApi; // #docregion cpp-class class PigeonApiImplementation : public ExampleHostApi { public: PigeonApiImplementation() {} virtual ~PigeonApiImplementation() {} ErrorOr<std::string> GetHostLanguage() override { return "C++"; } ErrorOr<int64_t> Add(int64_t a, int64_t b) { if (a < 0 || b < 0) { return FlutterError("code", "message", "details"); } return a + b; } void SendMessage(const MessageData& message, std::function<void(ErrorOr<bool> reply)> result) { if (message.code == Code.one) { result(FlutterError("code", "message", "details")); return; } result(true); } }; // #enddocregion cpp-class } // namespace FlutterWindow::FlutterWindow(const flutter::DartProject& project) : project_(project) {} FlutterWindow::~FlutterWindow() {} bool FlutterWindow::OnCreate() { if (!Win32Window::OnCreate()) { return false; } // #docregion cpp-method-flutter void TestPlugin::CallFlutterMethod( String aString, std::function<void(ErrorOr<int64_t> reply)> result) { MessageFlutterApi->FlutterMethod( aString, [result](String echo) { result(echo); }, [result](const FlutterError& error) { result(error); }); } // #enddocregion cpp-method-flutter RECT frame = GetClientArea(); // The size here must match the window dimensions to avoid unnecessary surface // creation / destruction in the startup path. flutter_controller_ = std::make_unique<flutter::FlutterViewController>( frame.right - frame.left, frame.bottom - frame.top, project_); // Ensure that basic setup of the controller was successful. if (!flutter_controller_->engine() || !flutter_controller_->view()) { return false; } RegisterPlugins(flutter_controller_->engine()); SetChildContent(flutter_controller_->view()->GetNativeWindow()); pigeonHostApi_ = std::make_unique<PigeonApiImplementation>(); ExampleHostApi::SetUp(flutter_controller_->engine()->messenger(), pigeonHostApi_.get()); flutter_controller_->engine()->SetNextFrameCallback([&]() { this->Show(); }); return true; } void FlutterWindow::OnDestroy() { if (flutter_controller_) { flutter_controller_ = nullptr; } Win32Window::OnDestroy(); } LRESULT FlutterWindow::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { // Give Flutter, including plugins, an opportunity to handle window messages. if (flutter_controller_) { std::optional<LRESULT> result = flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, lparam); if (result) { return *result; } } switch (message) { case WM_FONTCHANGE: flutter_controller_->engine()->ReloadSystemFonts(); break; } return Win32Window::MessageHandler(hwnd, message, wparam, lparam); }
packages/packages/pigeon/example/app/windows/runner/flutter_window.cpp/0
{ "file_path": "packages/packages/pigeon/example/app/windows/runner/flutter_window.cpp", "repo_id": "packages", "token_count": 1252 }
1,248
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'ast.dart'; import 'functional.dart'; import 'generator.dart'; import 'generator_tools.dart'; import 'pigeon_lib.dart' show Error; /// General comment opening token. const String _commentPrefix = '//'; const String _voidType = 'void'; /// Documentation comment spec. const DocumentCommentSpecification _docCommentSpec = DocumentCommentSpecification(_commentPrefix); /// The default serializer for Flutter. const String _defaultCodecSerializer = 'flutter::StandardCodecSerializer'; /// Options that control how C++ code will be generated. class CppOptions { /// Creates a [CppOptions] object const CppOptions({ this.headerIncludePath, this.namespace, this.copyrightHeader, this.headerOutPath, }); /// The path to the header that will get placed in the source filed (example: /// "foo.h"). final String? headerIncludePath; /// The namespace where the generated class will live. final String? namespace; /// A copyright header that will get prepended to generated code. final Iterable<String>? copyrightHeader; /// The path to the output header file location. final String? headerOutPath; /// Creates a [CppOptions] from a Map representation where: /// `x = CppOptions.fromMap(x.toMap())`. static CppOptions fromMap(Map<String, Object> map) { return CppOptions( headerIncludePath: map['header'] as String?, namespace: map['namespace'] as String?, copyrightHeader: map['copyrightHeader'] as Iterable<String>?, headerOutPath: map['cppHeaderOut'] as String?, ); } /// Converts a [CppOptions] to a Map representation where: /// `x = CppOptions.fromMap(x.toMap())`. Map<String, Object> toMap() { final Map<String, Object> result = <String, Object>{ if (headerIncludePath != null) 'header': headerIncludePath!, if (namespace != null) 'namespace': namespace!, if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!, }; return result; } /// Overrides any non-null parameters from [options] into this to make a new /// [CppOptions]. CppOptions merge(CppOptions options) { return CppOptions.fromMap(mergeMaps(toMap(), options.toMap())); } } /// Class that manages all Cpp code generation. class CppGenerator extends Generator<OutputFileOptions<CppOptions>> { /// Constructor. const CppGenerator(); /// Generates C++ file of type specified in [generatorOptions] @override void generate( OutputFileOptions<CppOptions> generatorOptions, Root root, StringSink sink, { required String dartPackageName, }) { assert(generatorOptions.fileType == FileType.header || generatorOptions.fileType == FileType.source); if (generatorOptions.fileType == FileType.header) { const CppHeaderGenerator().generate( generatorOptions.languageOptions, root, sink, dartPackageName: dartPackageName, ); } else if (generatorOptions.fileType == FileType.source) { const CppSourceGenerator().generate( generatorOptions.languageOptions, root, sink, dartPackageName: dartPackageName, ); } } } /// Writes C++ header (.h) file to sink. class CppHeaderGenerator extends StructuredGenerator<CppOptions> { /// Constructor. const CppHeaderGenerator(); @override void writeFilePrologue( CppOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { if (generatorOptions.copyrightHeader != null) { addLines(indent, generatorOptions.copyrightHeader!, linePrefix: '// '); } indent.writeln('$_commentPrefix ${getGeneratedCodeWarning()}'); indent.writeln('$_commentPrefix $seeAlsoWarning'); indent.newln(); } @override void writeFileImports( CppOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { final String guardName = _getGuardName(generatorOptions.headerIncludePath); indent.writeln('#ifndef $guardName'); indent.writeln('#define $guardName'); _writeSystemHeaderIncludeBlock(indent, <String>[ 'flutter/basic_message_channel.h', 'flutter/binary_messenger.h', 'flutter/encodable_value.h', 'flutter/standard_message_codec.h', ]); indent.newln(); _writeSystemHeaderIncludeBlock(indent, <String>[ 'map', 'string', 'optional', ]); indent.newln(); if (generatorOptions.namespace != null) { indent.writeln('namespace ${generatorOptions.namespace} {'); } indent.newln(); if (generatorOptions.namespace?.endsWith('_pigeontest') ?? false) { final String testFixtureClass = '${_pascalCaseFromSnakeCase(generatorOptions.namespace!.replaceAll('_pigeontest', ''))}Test'; indent.writeln('class $testFixtureClass;'); } indent.newln(); indent.writeln('$_commentPrefix Generated class from Pigeon.'); } @override void writeEnum( CppOptions generatorOptions, Root root, Indent indent, Enum anEnum, { required String dartPackageName, }) { indent.newln(); addDocumentationComments( indent, anEnum.documentationComments, _docCommentSpec); indent.write('enum class ${anEnum.name} '); indent.addScoped('{', '};', () { enumerate(anEnum.members, (int index, final EnumMember member) { addDocumentationComments( indent, member.documentationComments, _docCommentSpec); indent.writeln( '${member.name} = $index${index == anEnum.members.length - 1 ? '' : ','}'); }); }); } @override void writeGeneralUtilities( CppOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { final bool hasHostApi = root.apis .whereType<AstHostApi>() .any((Api api) => api.methods.isNotEmpty); final bool hasFlutterApi = root.apis .whereType<AstFlutterApi>() .any((Api api) => api.methods.isNotEmpty); _writeFlutterError(indent); if (hasHostApi) { _writeErrorOr( indent, friends: root.apis .where((Api api) => api is AstFlutterApi || api is AstHostApi) .map((Api api) => api.name), ); } if (hasFlutterApi) { // Nothing yet. } } @override void writeDataClass( CppOptions generatorOptions, Root root, Indent indent, Class classDefinition, { required String dartPackageName, }) { // When generating for a Pigeon unit test, add a test fixture friend class to // allow unit testing private methods, since testing serialization via public // methods is essentially an end-to-end test. String? testFixtureClass; if (generatorOptions.namespace?.endsWith('_pigeontest') ?? false) { testFixtureClass = '${_pascalCaseFromSnakeCase(generatorOptions.namespace!.replaceAll('_pigeontest', ''))}Test'; } indent.newln(); const List<String> generatedMessages = <String>[ ' Generated class from Pigeon that represents data sent in messages.' ]; addDocumentationComments( indent, classDefinition.documentationComments, _docCommentSpec, generatorComments: generatedMessages); final Iterable<NamedType> orderedFields = getFieldsInSerializationOrder(classDefinition); indent.write('class ${classDefinition.name} '); indent.addScoped('{', '};', () { _writeAccessBlock(indent, _ClassAccess.public, () { final Iterable<NamedType> requiredFields = orderedFields.where((NamedType type) => !type.type.isNullable); // Minimal constructor, if needed. if (requiredFields.length != orderedFields.length) { _writeClassConstructor(root, indent, classDefinition, requiredFields, 'Constructs an object setting all non-nullable fields.'); } // All-field constructor. _writeClassConstructor(root, indent, classDefinition, orderedFields, 'Constructs an object setting all fields.'); for (final NamedType field in orderedFields) { addDocumentationComments( indent, field.documentationComments, _docCommentSpec); final HostDatatype baseDatatype = getFieldHostDatatype(field, _baseCppTypeForBuiltinDartType); // Declare a getter and setter. _writeFunctionDeclaration(indent, _makeGetterName(field), returnType: _getterReturnType(baseDatatype), isConst: true); final String setterName = _makeSetterName(field); _writeFunctionDeclaration(indent, setterName, returnType: _voidType, parameters: <String>[ '${_unownedArgumentType(baseDatatype)} value_arg' ]); if (field.type.isNullable) { // Add a second setter that takes the non-nullable version of the // argument for convenience, since setting literal values with the // pointer version is non-trivial. final HostDatatype nonNullType = _nonNullableType(baseDatatype); _writeFunctionDeclaration(indent, setterName, returnType: _voidType, parameters: <String>[ '${_unownedArgumentType(nonNullType)} value_arg' ]); } indent.newln(); } }); _writeAccessBlock(indent, _ClassAccess.private, () { _writeFunctionDeclaration(indent, 'FromEncodableList', returnType: classDefinition.name, parameters: <String>['const flutter::EncodableList& list'], isStatic: true); _writeFunctionDeclaration(indent, 'ToEncodableList', returnType: 'flutter::EncodableList', isConst: true); for (final Class friend in root.classes) { if (friend != classDefinition && friend.fields.any((NamedType element) => element.type.baseName == classDefinition.name)) { indent.writeln('friend class ${friend.name};'); } } for (final Api api in root.apis .where((Api api) => api is AstFlutterApi || api is AstHostApi)) { // TODO(gaaclarke): Find a way to be more precise with our // friendships. indent.writeln('friend class ${api.name};'); indent.writeln('friend class ${_getCodecSerializerName(api)};'); } if (testFixtureClass != null) { indent.writeln('friend class $testFixtureClass;'); } for (final NamedType field in orderedFields) { final HostDatatype hostDatatype = getFieldHostDatatype(field, _baseCppTypeForBuiltinDartType); indent.writeln( '${_valueType(hostDatatype)} ${_makeInstanceVariableName(field)};'); } }); }, nestCount: 0); indent.newln(); } @override void writeFlutterApi( CppOptions generatorOptions, Root root, Indent indent, AstFlutterApi api, { required String dartPackageName, }) { if (getCodecClasses(api, root).isNotEmpty) { _writeCodec(generatorOptions, root, indent, api); } const List<String> generatedMessages = <String>[ ' Generated class from Pigeon that represents Flutter messages that can be called from C++.' ]; addDocumentationComments(indent, api.documentationComments, _docCommentSpec, generatorComments: generatedMessages); indent.write('class ${api.name} '); indent.addScoped('{', '};', () { _writeAccessBlock(indent, _ClassAccess.public, () { _writeFunctionDeclaration(indent, api.name, parameters: <String>['flutter::BinaryMessenger* binary_messenger']); _writeFunctionDeclaration(indent, 'GetCodec', returnType: 'const flutter::StandardMessageCodec&', isStatic: true); for (final Method func in api.methods) { final HostDatatype returnType = getHostDatatype(func.returnType, _baseCppTypeForBuiltinDartType); addDocumentationComments( indent, func.documentationComments, _docCommentSpec); final Iterable<String> argTypes = func.parameters.map((NamedType arg) { final HostDatatype hostType = getFieldHostDatatype(arg, _baseCppTypeForBuiltinDartType); return _flutterApiArgumentType(hostType); }); final Iterable<String> argNames = indexMap(func.parameters, _getArgumentName); final List<String> parameters = <String>[ ...map2(argTypes, argNames, (String x, String y) => '$x $y'), ..._flutterApiCallbackParameters(returnType), ]; _writeFunctionDeclaration(indent, _makeMethodName(func), returnType: _voidType, parameters: parameters); } }); indent.addScoped(' private:', null, () { indent.writeln('flutter::BinaryMessenger* binary_messenger_;'); }); }, nestCount: 0); indent.newln(); } @override void writeHostApi( CppOptions generatorOptions, Root root, Indent indent, AstHostApi api, { required String dartPackageName, }) { if (getCodecClasses(api, root).isNotEmpty) { _writeCodec(generatorOptions, root, indent, api); } const List<String> generatedMessages = <String>[ ' Generated interface from Pigeon that represents a handler of messages from Flutter.' ]; addDocumentationComments(indent, api.documentationComments, _docCommentSpec, generatorComments: generatedMessages); indent.write('class ${api.name} '); indent.addScoped('{', '};', () { _writeAccessBlock(indent, _ClassAccess.public, () { // Prevent copying/assigning. _writeFunctionDeclaration(indent, api.name, parameters: <String>['const ${api.name}&'], deleted: true); _writeFunctionDeclaration(indent, 'operator=', returnType: '${api.name}&', parameters: <String>['const ${api.name}&'], deleted: true); // No-op virtual destructor. _writeFunctionDeclaration(indent, '~${api.name}', isVirtual: true, inlineNoop: true); for (final Method method in api.methods) { final HostDatatype returnType = getHostDatatype( method.returnType, _baseCppTypeForBuiltinDartType); final String returnTypeName = _hostApiReturnType(returnType); final List<String> parameters = <String>[]; if (method.parameters.isNotEmpty) { final Iterable<String> argTypes = method.parameters.map((NamedType arg) { final HostDatatype hostType = getFieldHostDatatype(arg, _baseCppTypeForBuiltinDartType); return _hostApiArgumentType(hostType); }); final Iterable<String> argNames = method.parameters.map((NamedType e) => _makeVariableName(e)); parameters.addAll( map2(argTypes, argNames, (String argType, String argName) { return '$argType $argName'; })); } addDocumentationComments( indent, method.documentationComments, _docCommentSpec); final String methodReturn; if (method.isAsynchronous) { methodReturn = _voidType; parameters.add('std::function<void($returnTypeName reply)> result'); } else { methodReturn = returnTypeName; } _writeFunctionDeclaration(indent, _makeMethodName(method), returnType: methodReturn, parameters: parameters, isVirtual: true, isPureVirtual: true); } indent.newln(); indent.writeln('$_commentPrefix The codec used by ${api.name}.'); _writeFunctionDeclaration(indent, 'GetCodec', returnType: 'const flutter::StandardMessageCodec&', isStatic: true); indent.writeln( '$_commentPrefix Sets up an instance of `${api.name}` to handle messages through the `binary_messenger`.'); _writeFunctionDeclaration(indent, 'SetUp', returnType: _voidType, isStatic: true, parameters: <String>[ 'flutter::BinaryMessenger* binary_messenger', '${api.name}* api', ]); _writeFunctionDeclaration(indent, 'WrapError', returnType: 'flutter::EncodableValue', isStatic: true, parameters: <String>['std::string_view error_message']); _writeFunctionDeclaration(indent, 'WrapError', returnType: 'flutter::EncodableValue', isStatic: true, parameters: <String>['const FlutterError& error']); }); _writeAccessBlock(indent, _ClassAccess.protected, () { indent.writeln('${api.name}() = default;'); }); }, nestCount: 0); } void _writeClassConstructor(Root root, Indent indent, Class classDefinition, Iterable<NamedType> params, String docComment) { final List<String> paramStrings = params.map((NamedType param) { final HostDatatype hostDatatype = getFieldHostDatatype(param, _baseCppTypeForBuiltinDartType); return '${_hostApiArgumentType(hostDatatype)} ${_makeVariableName(param)}'; }).toList(); indent.writeln('$_commentPrefix $docComment'); _writeFunctionDeclaration(indent, classDefinition.name, isConstructor: true, parameters: paramStrings); indent.newln(); } void _writeCodec( CppOptions generatorOptions, Root root, Indent indent, Api api) { assert(getCodecClasses(api, root).isNotEmpty); final String codeSerializerName = _getCodecSerializerName(api); indent .write('class $codeSerializerName : public $_defaultCodecSerializer '); indent.addScoped('{', '};', () { _writeAccessBlock(indent, _ClassAccess.public, () { _writeFunctionDeclaration(indent, codeSerializerName, isConstructor: true); _writeFunctionDeclaration(indent, 'GetInstance', returnType: '$codeSerializerName&', isStatic: true, inlineBody: () { indent.writeln('static $codeSerializerName sInstance;'); indent.writeln('return sInstance;'); }); indent.newln(); _writeFunctionDeclaration(indent, 'WriteValue', returnType: _voidType, parameters: <String>[ 'const flutter::EncodableValue& value', 'flutter::ByteStreamWriter* stream' ], isConst: true, isOverride: true); }); indent.writeScoped(' protected:', '', () { _writeFunctionDeclaration(indent, 'ReadValueOfType', returnType: 'flutter::EncodableValue', parameters: <String>[ 'uint8_t type', 'flutter::ByteStreamReader* stream' ], isConst: true, isOverride: true); }); }, nestCount: 0); indent.newln(); } void _writeFlutterError(Indent indent) { indent.format(''' class FlutterError { public: \texplicit FlutterError(const std::string& code) \t\t: code_(code) {} \texplicit FlutterError(const std::string& code, const std::string& message) \t\t: code_(code), message_(message) {} \texplicit FlutterError(const std::string& code, const std::string& message, const flutter::EncodableValue& details) \t\t: code_(code), message_(message), details_(details) {} \tconst std::string& code() const { return code_; } \tconst std::string& message() const { return message_; } \tconst flutter::EncodableValue& details() const { return details_; } private: \tstd::string code_; \tstd::string message_; \tflutter::EncodableValue details_; };'''); } void _writeErrorOr(Indent indent, {Iterable<String> friends = const <String>[]}) { final String friendLines = friends .map((String className) => '\tfriend class $className;') .join('\n'); indent.format(''' template<class T> class ErrorOr { public: \tErrorOr(const T& rhs) : v_(rhs) {} \tErrorOr(const T&& rhs) : v_(std::move(rhs)) {} \tErrorOr(const FlutterError& rhs) : v_(rhs) {} \tErrorOr(const FlutterError&& rhs) : v_(std::move(rhs)) {} \tbool has_error() const { return std::holds_alternative<FlutterError>(v_); } \tconst T& value() const { return std::get<T>(v_); }; \tconst FlutterError& error() const { return std::get<FlutterError>(v_); }; private: $friendLines \tErrorOr() = default; \tT TakeValue() && { return std::get<T>(std::move(v_)); } \tstd::variant<T, FlutterError> v_; }; '''); } @override void writeCloseNamespace( CppOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { if (generatorOptions.namespace != null) { indent.writeln('} // namespace ${generatorOptions.namespace}'); } final String guardName = _getGuardName(generatorOptions.headerIncludePath); indent.writeln('#endif // $guardName'); } } /// Writes C++ source (.cpp) file to sink. class CppSourceGenerator extends StructuredGenerator<CppOptions> { /// Constructor. const CppSourceGenerator(); @override void writeFilePrologue( CppOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { if (generatorOptions.copyrightHeader != null) { addLines(indent, generatorOptions.copyrightHeader!, linePrefix: '// '); } indent.writeln('$_commentPrefix ${getGeneratedCodeWarning()}'); indent.writeln('$_commentPrefix $seeAlsoWarning'); indent.newln(); indent.addln('#undef _HAS_EXCEPTIONS'); indent.newln(); } @override void writeFileImports( CppOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { indent.writeln('#include "${generatorOptions.headerIncludePath}"'); indent.newln(); _writeSystemHeaderIncludeBlock(indent, <String>[ 'flutter/basic_message_channel.h', 'flutter/binary_messenger.h', 'flutter/encodable_value.h', 'flutter/standard_message_codec.h', ]); indent.newln(); _writeSystemHeaderIncludeBlock(indent, <String>[ 'map', 'string', 'optional', ]); indent.newln(); } @override void writeOpenNamespace( CppOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { if (generatorOptions.namespace != null) { indent.writeln('namespace ${generatorOptions.namespace} {'); } } @override void writeGeneralUtilities( CppOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { final List<String> usingDirectives = <String>[ 'flutter::BasicMessageChannel', 'flutter::CustomEncodableValue', 'flutter::EncodableList', 'flutter::EncodableMap', 'flutter::EncodableValue', ]; usingDirectives.sort(); for (final String using in usingDirectives) { indent.writeln('using $using;'); } indent.newln(); _writeFunctionDefinition(indent, 'CreateConnectionError', returnType: 'FlutterError', parameters: <String>['const std::string channel_name'], body: () { indent.format(''' return FlutterError( "channel-error", "Unable to establish connection on channel: '" + channel_name + "'.", EncodableValue(""));'''); }); } @override void writeDataClass( CppOptions generatorOptions, Root root, Indent indent, Class classDefinition, { required String dartPackageName, }) { indent.writeln('$_commentPrefix ${classDefinition.name}'); indent.newln(); final Iterable<NamedType> orderedFields = getFieldsInSerializationOrder(classDefinition); final Iterable<NamedType> requiredFields = orderedFields.where((NamedType type) => !type.type.isNullable); // Minimal constructor, if needed. if (requiredFields.length != orderedFields.length) { _writeClassConstructor(root, indent, classDefinition, requiredFields); } // All-field constructor. _writeClassConstructor(root, indent, classDefinition, orderedFields); // Getters and setters. for (final NamedType field in orderedFields) { _writeCppSourceClassField( generatorOptions, root, indent, classDefinition, field); } // Serialization. writeClassEncode( generatorOptions, root, indent, classDefinition, dartPackageName: dartPackageName, ); // Deserialization. writeClassDecode( generatorOptions, root, indent, classDefinition, dartPackageName: dartPackageName, ); } @override void writeClassEncode( CppOptions generatorOptions, Root root, Indent indent, Class classDefinition, { required String dartPackageName, }) { _writeFunctionDefinition(indent, 'ToEncodableList', scope: classDefinition.name, returnType: 'EncodableList', isConst: true, body: () { indent.writeln('EncodableList list;'); indent.writeln('list.reserve(${classDefinition.fields.length});'); for (final NamedType field in getFieldsInSerializationOrder(classDefinition)) { final HostDatatype hostDatatype = getFieldHostDatatype(field, _shortBaseCppTypeForBuiltinDartType); final String encodableValue = _wrappedHostApiArgumentExpression( root, _makeInstanceVariableName(field), field.type, hostDatatype, preSerializeClasses: true); indent.writeln('list.push_back($encodableValue);'); } indent.writeln('return list;'); }); } @override void writeClassDecode( CppOptions generatorOptions, Root root, Indent indent, Class classDefinition, { required String dartPackageName, }) { // Returns the expression to convert the given EncodableValue to a field // value. String getValueExpression(NamedType field, String encodable) { if (field.type.isEnum) { return '(${field.type.baseName})(std::get<int32_t>($encodable))'; } else if (field.type.baseName == 'int') { return '$encodable.LongValue()'; } else if (field.type.baseName == 'Object') { return encodable; } else { final HostDatatype hostDatatype = getFieldHostDatatype(field, _shortBaseCppTypeForBuiltinDartType); if (!hostDatatype.isBuiltin && root.classes .map((Class x) => x.name) .contains(field.type.baseName)) { return '${hostDatatype.datatype}::FromEncodableList(std::get<EncodableList>($encodable))'; } else { return 'std::get<${hostDatatype.datatype}>($encodable)'; } } } _writeFunctionDefinition(indent, 'FromEncodableList', scope: classDefinition.name, returnType: classDefinition.name, parameters: <String>['const EncodableList& list'], body: () { const String instanceVariable = 'decoded'; final Iterable<_IndexedField> indexedFields = indexMap( getFieldsInSerializationOrder(classDefinition), (int index, NamedType field) => _IndexedField(index, field)); final Iterable<_IndexedField> nullableFields = indexedFields .where((_IndexedField field) => field.field.type.isNullable); final Iterable<_IndexedField> nonNullableFields = indexedFields .where((_IndexedField field) => !field.field.type.isNullable); // Non-nullable fields must be set via the constructor. String constructorArgs = nonNullableFields .map((_IndexedField param) => getValueExpression(param.field, 'list[${param.index}]')) .join(',\n\t'); if (constructorArgs.isNotEmpty) { constructorArgs = '(\n\t$constructorArgs)'; } indent .format('${classDefinition.name} $instanceVariable$constructorArgs;'); // Add the nullable fields via setters, since converting the encodable // values to the pointer types that the convenience constructor uses for // nullable fields is non-trivial. for (final _IndexedField entry in nullableFields) { final NamedType field = entry.field; final String setterName = _makeSetterName(field); final String encodableFieldName = '${_encodablePrefix}_${_makeVariableName(field)}'; indent.writeln('auto& $encodableFieldName = list[${entry.index}];'); final String valueExpression = getValueExpression(field, encodableFieldName); indent.writeScoped('if (!$encodableFieldName.IsNull()) {', '}', () { indent.writeln('$instanceVariable.$setterName($valueExpression);'); }); } // This returns by value, relying on copy elision, since it makes the // usage more convenient during deserialization than it would be with // explicit transfer via unique_ptr. indent.writeln('return $instanceVariable;'); }); } @override void writeFlutterApi( CppOptions generatorOptions, Root root, Indent indent, AstFlutterApi api, { required String dartPackageName, }) { if (getCodecClasses(api, root).isNotEmpty) { _writeCodec(generatorOptions, root, indent, api); } indent.writeln( '$_commentPrefix Generated class from Pigeon that represents Flutter messages that can be called from C++.'); _writeFunctionDefinition(indent, api.name, scope: api.name, parameters: <String>['flutter::BinaryMessenger* binary_messenger'], initializers: <String>['binary_messenger_(binary_messenger)']); final String codeSerializerName = getCodecClasses(api, root).isNotEmpty ? _getCodecSerializerName(api) : _defaultCodecSerializer; _writeFunctionDefinition(indent, 'GetCodec', scope: api.name, returnType: 'const flutter::StandardMessageCodec&', body: () { indent.writeln( 'return flutter::StandardMessageCodec::GetInstance(&$codeSerializerName::GetInstance());'); }); for (final Method func in api.methods) { final HostDatatype returnType = getHostDatatype(func.returnType, _shortBaseCppTypeForBuiltinDartType); // Determine the input parameter list, saved in a structured form for later // use as platform channel call arguments. final Iterable<_HostNamedType> hostParameters = indexMap(func.parameters, (int i, NamedType arg) { final HostDatatype hostType = getFieldHostDatatype(arg, _shortBaseCppTypeForBuiltinDartType); return _HostNamedType(_getSafeArgumentName(i, arg), hostType, arg.type); }); final List<String> parameters = <String>[ ...hostParameters.map((_HostNamedType arg) => '${_flutterApiArgumentType(arg.hostType)} ${arg.name}'), ..._flutterApiCallbackParameters(returnType), ]; _writeFunctionDefinition(indent, _makeMethodName(func), scope: api.name, returnType: _voidType, parameters: parameters, body: () { indent.writeln( 'const std::string channel_name = "${makeChannelName(api, func, dartPackageName)}";'); indent.writeln('BasicMessageChannel<> channel(binary_messenger_, ' 'channel_name, &GetCodec());'); // Convert arguments to EncodableValue versions. const String argumentListVariableName = 'encoded_api_arguments'; indent.write('EncodableValue $argumentListVariableName = '); if (func.parameters.isEmpty) { indent.addln('EncodableValue();'); } else { indent.addScoped('EncodableValue(EncodableList{', '});', () { for (final _HostNamedType param in hostParameters) { final String encodedArgument = _wrappedHostApiArgumentExpression( root, param.name, param.originalType, param.hostType, preSerializeClasses: false); indent.writeln('$encodedArgument,'); } }); } indent.write('channel.Send($argumentListVariableName, ' // ignore: missing_whitespace_between_adjacent_strings '[channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]' '(const uint8_t* reply, size_t reply_size) '); indent.addScoped('{', '});', () { String successCallbackArgument; successCallbackArgument = 'return_value'; final String encodedReplyName = 'encodable_$successCallbackArgument'; final String listReplyName = 'list_$successCallbackArgument'; indent.writeln( 'std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size);'); indent.writeln('const auto& $encodedReplyName = *response;'); indent.writeln( 'const auto* $listReplyName = std::get_if<EncodableList>(&$encodedReplyName);'); indent.writeScoped('if ($listReplyName) {', '} ', () { indent.writeScoped('if ($listReplyName->size() > 1) {', '} ', () { indent.writeln( 'on_error(FlutterError(std::get<std::string>($listReplyName->at(0)), std::get<std::string>($listReplyName->at(1)), $listReplyName->at(2)));'); }, addTrailingNewline: false); indent.addScoped('else {', '}', () { if (func.returnType.isVoid) { successCallbackArgument = ''; } else { _writeEncodableValueArgumentUnwrapping( indent, root, returnType, argName: successCallbackArgument, encodableArgName: '$listReplyName->at(0)', apiType: ApiType.flutter, ); } indent.writeln('on_success($successCallbackArgument);'); }); }, addTrailingNewline: false); indent.addScoped('else {', '} ', () { indent.writeln('on_error(CreateConnectionError(channel_name));'); }); }); }); } } @override void writeHostApi( CppOptions generatorOptions, Root root, Indent indent, AstHostApi api, { required String dartPackageName, }) { if (getCodecClasses(api, root).isNotEmpty) { _writeCodec(generatorOptions, root, indent, api); } final String codeSerializerName = getCodecClasses(api, root).isNotEmpty ? _getCodecSerializerName(api) : _defaultCodecSerializer; indent.writeln('/// The codec used by ${api.name}.'); _writeFunctionDefinition(indent, 'GetCodec', scope: api.name, returnType: 'const flutter::StandardMessageCodec&', body: () { indent.writeln( 'return flutter::StandardMessageCodec::GetInstance(&$codeSerializerName::GetInstance());'); }); indent.writeln( '$_commentPrefix Sets up an instance of `${api.name}` to handle messages through the `binary_messenger`.'); _writeFunctionDefinition(indent, 'SetUp', scope: api.name, returnType: _voidType, parameters: <String>[ 'flutter::BinaryMessenger* binary_messenger', '${api.name}* api' ], body: () { for (final Method method in api.methods) { final String channelName = makeChannelName(api, method, dartPackageName); indent.writeScoped('{', '}', () { indent.writeln('BasicMessageChannel<> channel(binary_messenger, ' '"$channelName", &GetCodec());'); indent.writeScoped('if (api != nullptr) {', '} else {', () { indent.write( 'channel.SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) '); indent.addScoped('{', '});', () { indent.writeScoped('try {', '}', () { final List<String> methodArgument = <String>[]; if (method.parameters.isNotEmpty) { indent.writeln( 'const auto& args = std::get<EncodableList>(message);'); enumerate(method.parameters, (int index, NamedType arg) { final HostDatatype hostType = getHostDatatype( arg.type, (TypeDeclaration x) => _shortBaseCppTypeForBuiltinDartType(x)); final String argName = _getSafeArgumentName(index, arg); final String encodableArgName = '${_encodablePrefix}_$argName'; indent.writeln( 'const auto& $encodableArgName = args.at($index);'); if (!arg.type.isNullable) { indent.writeScoped( 'if ($encodableArgName.IsNull()) {', '}', () { indent.writeln( 'reply(WrapError("$argName unexpectedly null."));'); indent.writeln('return;'); }); } _writeEncodableValueArgumentUnwrapping( indent, root, hostType, argName: argName, encodableArgName: encodableArgName, apiType: ApiType.host, ); final String unwrapEnum = arg.type.isEnum && arg.type.isNullable ? ' ? &(*$argName) : nullptr' : ''; methodArgument.add('$argName$unwrapEnum'); }); } final HostDatatype returnType = getHostDatatype( method.returnType, _shortBaseCppTypeForBuiltinDartType); final String returnTypeName = _hostApiReturnType(returnType); if (method.isAsynchronous) { methodArgument.add( '[reply]($returnTypeName&& output) {${indent.newline}' '${_wrapResponse(indent, root, method.returnType, prefix: '\t')}${indent.newline}' '}', ); } final String call = 'api->${_makeMethodName(method)}(${methodArgument.join(', ')})'; if (method.isAsynchronous) { indent.format('$call;'); } else { indent.writeln('$returnTypeName output = $call;'); indent.format(_wrapResponse(indent, root, method.returnType)); } }, addTrailingNewline: false); indent.add(' catch (const std::exception& exception) '); indent.addScoped('{', '}', () { // There is a potential here for `reply` to be called twice, which // is a violation of the API contract, because there's no way of // knowing whether or not the plugin code called `reply` before // throwing. Since use of `@async` suggests that the reply is // probably not sent within the scope of the stack, err on the // side of potential double-call rather than no call (which is // also an API violation) so that unexpected errors have a better // chance of being caught and handled in a useful way. indent.writeln('reply(WrapError(exception.what()));'); }); }); }); indent.addScoped(null, '}', () { indent.writeln('channel.SetMessageHandler(nullptr);'); }); }); } }); _writeFunctionDefinition(indent, 'WrapError', scope: api.name, returnType: 'EncodableValue', parameters: <String>['std::string_view error_message'], body: () { indent.format(''' return EncodableValue(EncodableList{ \tEncodableValue(std::string(error_message)), \tEncodableValue("Error"), \tEncodableValue() });'''); }); _writeFunctionDefinition(indent, 'WrapError', scope: api.name, returnType: 'EncodableValue', parameters: <String>['const FlutterError& error'], body: () { indent.format(''' return EncodableValue(EncodableList{ \tEncodableValue(error.code()), \tEncodableValue(error.message()), \terror.details() });'''); }); } void _writeCodec( CppOptions generatorOptions, Root root, Indent indent, Api api, ) { assert(getCodecClasses(api, root).isNotEmpty); final String codeSerializerName = _getCodecSerializerName(api); indent.newln(); _writeFunctionDefinition(indent, codeSerializerName, scope: codeSerializerName); _writeFunctionDefinition(indent, 'ReadValueOfType', scope: codeSerializerName, returnType: 'EncodableValue', parameters: <String>[ 'uint8_t type', 'flutter::ByteStreamReader* stream', ], isConst: true, body: () { indent.write('switch (type) '); indent.addScoped('{', '}', () { for (final EnumeratedClass customClass in getCodecClasses(api, root)) { indent.writeln('case ${customClass.enumeration}:'); indent.nest(1, () { indent.writeln( 'return CustomEncodableValue(${customClass.name}::FromEncodableList(std::get<EncodableList>(ReadValue(stream))));'); }); } indent.writeln('default:'); indent.nest(1, () { indent.writeln( 'return $_defaultCodecSerializer::ReadValueOfType(type, stream);'); }); }); }); _writeFunctionDefinition(indent, 'WriteValue', scope: codeSerializerName, returnType: _voidType, parameters: <String>[ 'const EncodableValue& value', 'flutter::ByteStreamWriter* stream', ], isConst: true, body: () { indent.write( 'if (const CustomEncodableValue* custom_value = std::get_if<CustomEncodableValue>(&value)) '); indent.addScoped('{', '}', () { for (final EnumeratedClass customClass in getCodecClasses(api, root)) { indent.write( 'if (custom_value->type() == typeid(${customClass.name})) '); indent.addScoped('{', '}', () { indent.writeln('stream->WriteByte(${customClass.enumeration});'); indent.writeln( 'WriteValue(EncodableValue(std::any_cast<${customClass.name}>(*custom_value).ToEncodableList()), stream);'); indent.writeln('return;'); }); } }); indent.writeln('$_defaultCodecSerializer::WriteValue(value, stream);'); }); } void _writeClassConstructor(Root root, Indent indent, Class classDefinition, Iterable<NamedType> params) { final Iterable<_HostNamedType> hostParams = params.map((NamedType param) { return _HostNamedType( _makeVariableName(param), getFieldHostDatatype( param, _shortBaseCppTypeForBuiltinDartType, ), param.type, ); }); final List<String> paramStrings = hostParams .map((_HostNamedType param) => '${_hostApiArgumentType(param.hostType)} ${param.name}') .toList(); final List<String> initializerStrings = hostParams .map((_HostNamedType param) => '${param.name}_(${_fieldValueExpression(param.hostType, param.name)})') .toList(); _writeFunctionDefinition(indent, classDefinition.name, scope: classDefinition.name, parameters: paramStrings, initializers: initializerStrings); } void _writeCppSourceClassField(CppOptions generatorOptions, Root root, Indent indent, Class classDefinition, NamedType field) { final HostDatatype hostDatatype = getFieldHostDatatype(field, _shortBaseCppTypeForBuiltinDartType); final String instanceVariableName = _makeInstanceVariableName(field); final String setterName = _makeSetterName(field); final String returnExpression = hostDatatype.isNullable ? '$instanceVariableName ? &(*$instanceVariableName) : nullptr' : instanceVariableName; // Writes a setter treating the type as [type], to allow generating multiple // setter variants. void writeSetter(HostDatatype type) { const String setterArgumentName = 'value_arg'; _writeFunctionDefinition( indent, setterName, scope: classDefinition.name, returnType: _voidType, parameters: <String>[ '${_unownedArgumentType(type)} $setterArgumentName' ], body: () { indent.writeln( '$instanceVariableName = ${_fieldValueExpression(type, setterArgumentName)};'); }, ); } _writeFunctionDefinition( indent, _makeGetterName(field), scope: classDefinition.name, returnType: _getterReturnType(hostDatatype), isConst: true, body: () { indent.writeln('return $returnExpression;'); }, ); writeSetter(hostDatatype); if (hostDatatype.isNullable) { // Write the non-nullable variant; see _writeCppHeaderDataClass. writeSetter(_nonNullableType(hostDatatype)); } indent.newln(); } /// Returns the value to use when setting a field of the given type from /// an argument of that type. /// /// For non-nullable values this is just the variable itself, but for nullable /// values this handles the conversion between an argument type (a pointer) /// and the field type (a std::optional). String _fieldValueExpression(HostDatatype type, String variable) { return type.isNullable ? '$variable ? ${_valueType(type)}(*$variable) : std::nullopt' : variable; } String _wrapResponse(Indent indent, Root root, TypeDeclaration returnType, {String prefix = ''}) { final String nonErrorPath; final String errorCondition; final String errorGetter; const String nullValue = 'EncodableValue()'; String enumPrefix = ''; if (returnType.isEnum) { enumPrefix = '(int) '; } if (returnType.isVoid) { nonErrorPath = '${prefix}wrapped.push_back($nullValue);'; errorCondition = 'output.has_value()'; errorGetter = 'value'; } else { final HostDatatype hostType = getHostDatatype(returnType, _shortBaseCppTypeForBuiltinDartType); const String extractedValue = 'std::move(output).TakeValue()'; final String wrapperType = hostType.isBuiltin || returnType.isEnum ? 'EncodableValue' : 'CustomEncodableValue'; if (returnType.isNullable) { // The value is a std::optional, so needs an extra layer of // handling. nonErrorPath = ''' ${prefix}auto output_optional = $extractedValue; ${prefix}if (output_optional) { $prefix\twrapped.push_back($wrapperType(${enumPrefix}std::move(output_optional).value())); $prefix} else { $prefix\twrapped.push_back($nullValue); $prefix}'''; } else { nonErrorPath = '${prefix}wrapped.push_back($wrapperType($enumPrefix$extractedValue));'; } errorCondition = 'output.has_error()'; errorGetter = 'error'; } // Ideally this code would use an initializer list to create // an EncodableList inline, which would be less code. However, // that would always copy the element, so the slightly more // verbose create-and-push approach is used instead. return ''' ${prefix}if ($errorCondition) { $prefix\treply(WrapError(output.$errorGetter())); $prefix\treturn; $prefix} ${prefix}EncodableList wrapped; $nonErrorPath ${prefix}reply(EncodableValue(std::move(wrapped)));'''; } @override void writeCloseNamespace( CppOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { if (generatorOptions.namespace != null) { indent.writeln('} // namespace ${generatorOptions.namespace}'); } } /// Returns the expression to create an EncodableValue from a host API argument /// with the given [variableName] and types. /// /// If [preSerializeClasses] is true, custom classes will be returned as /// encodable lists rather than CustomEncodableValues; see /// https://github.com/flutter/flutter/issues/119351 for why this is currently /// needed. String _wrappedHostApiArgumentExpression(Root root, String variableName, TypeDeclaration dartType, HostDatatype hostType, {required bool preSerializeClasses}) { final String encodableValue; if (!hostType.isBuiltin && root.classes.any((Class c) => c.name == dartType.baseName)) { if (preSerializeClasses) { final String operator = hostType.isNullable ? '->' : '.'; encodableValue = 'EncodableValue($variableName${operator}ToEncodableList())'; } else { final String nonNullValue = hostType.isNullable ? '*$variableName' : variableName; encodableValue = 'CustomEncodableValue($nonNullValue)'; } } else if (!hostType.isBuiltin && root.enums.any((Enum e) => e.name == dartType.baseName)) { final String nonNullValue = hostType.isNullable ? '(*$variableName)' : variableName; encodableValue = 'EncodableValue((int)$nonNullValue)'; } else if (dartType.baseName == 'Object') { final String operator = hostType.isNullable ? '*' : ''; encodableValue = '$operator$variableName'; } else { final String operator = hostType.isNullable ? '*' : ''; encodableValue = 'EncodableValue($operator$variableName)'; } if (hostType.isNullable) { return '$variableName ? $encodableValue : EncodableValue()'; } return encodableValue; } /// Writes the code to declare and populate a variable of type [hostType] /// called [argName] to use as a parameter to an API method call, from an /// existing EncodableValue variable called [encodableArgName]. void _writeEncodableValueArgumentUnwrapping( Indent indent, Root root, HostDatatype hostType, { required String argName, required String encodableArgName, required ApiType apiType, }) { if (hostType.isNullable) { // Nullable arguments are always pointers, with nullptr corresponding to // null. if (hostType.datatype == 'int64_t') { // The EncodableValue will either be an int32_t or an int64_t depending // on the value, but the generated API requires an int64_t so that it can // handle any case. Create a local variable for the 64-bit value... final String valueVarName = '${argName}_value'; indent.writeln( 'const int64_t $valueVarName = $encodableArgName.IsNull() ? 0 : $encodableArgName.LongValue();'); // ... then declare the arg as a reference to that local. indent.writeln( 'const auto* $argName = $encodableArgName.IsNull() ? nullptr : &$valueVarName;'); } else if (hostType.datatype == 'EncodableValue') { // Generic objects just pass the EncodableValue through directly. indent.writeln('const auto* $argName = &$encodableArgName;'); } else if (hostType.isBuiltin) { indent.writeln( 'const auto* $argName = std::get_if<${hostType.datatype}>(&$encodableArgName);'); } else if (hostType.isEnum) { final String valueVarName = '${argName}_value'; indent.writeln( 'const int64_t $valueVarName = $encodableArgName.IsNull() ? 0 : $encodableArgName.LongValue();'); if (apiType == ApiType.flutter) { indent.writeln( 'const ${hostType.datatype} enum_$argName = (${hostType.datatype})$valueVarName;'); indent.writeln( 'const auto* $argName = $encodableArgName.IsNull() ? nullptr : &enum_$argName;'); } else { indent.writeln( 'const auto $argName = $encodableArgName.IsNull() ? std::nullopt : std::make_optional<${hostType.datatype}>(static_cast<${hostType.datatype}>(${argName}_value));'); } } else { indent.writeln( 'const auto* $argName = &(std::any_cast<const ${hostType.datatype}&>(std::get<CustomEncodableValue>($encodableArgName)));'); } } else { // Non-nullable arguments are either passed by value or reference, but the // extraction doesn't need to distinguish since those are the same at the // call site. if (hostType.datatype == 'int64_t') { // The EncodableValue will either be an int32_t or an int64_t depending // on the value, but the generated API requires an int64_t so that it can // handle any case. indent .writeln('const int64_t $argName = $encodableArgName.LongValue();'); } else if (hostType.datatype == 'EncodableValue') { // Generic objects just pass the EncodableValue through directly. This // creates an alias just to avoid having to special-case the // argName/encodableArgName distinction at a higher level. indent.writeln('const auto& $argName = $encodableArgName;'); } else if (hostType.isBuiltin) { indent.writeln( 'const auto& $argName = std::get<${hostType.datatype}>($encodableArgName);'); } else if (hostType.isEnum) { indent.writeln( 'const ${hostType.datatype}& $argName = (${hostType.datatype})$encodableArgName.LongValue();'); } else { indent.writeln( 'const auto& $argName = std::any_cast<const ${hostType.datatype}&>(std::get<CustomEncodableValue>($encodableArgName));'); } } } /// A wrapper for [_baseCppTypeForBuiltinDartType] that generated Flutter /// types without the namespace, since the implementation file uses `using` /// directives. String? _shortBaseCppTypeForBuiltinDartType(TypeDeclaration type) { return _baseCppTypeForBuiltinDartType(type, includeFlutterNamespace: false); } } /// Contains information about a host function argument. /// /// This is comparable to a [NamedType], but has already gone through host type /// and variable name mapping, and it tracks the original [NamedType] that it /// was created from. class _HostNamedType { const _HostNamedType(this.name, this.hostType, this.originalType); final String name; final HostDatatype hostType; final TypeDeclaration originalType; } /// Contains a class field and its serialization index. class _IndexedField { const _IndexedField(this.index, this.field); final int index; final NamedType field; } String _getCodecSerializerName(Api api) => '${api.name}CodecSerializer'; const String _encodablePrefix = 'encodable'; String _getArgumentName(int count, NamedType argument) => argument.name.isEmpty ? 'arg$count' : _makeVariableName(argument); /// Returns an argument name that can be used in a context where it is possible to collide. String _getSafeArgumentName(int count, NamedType argument) => '${_getArgumentName(count, argument)}_arg'; /// Returns a non-nullable variant of [type]. HostDatatype _nonNullableType(HostDatatype type) { return HostDatatype( datatype: type.datatype, isBuiltin: type.isBuiltin, isNullable: false, isEnum: type.isEnum, ); } String _pascalCaseFromCamelCase(String camelCase) => camelCase[0].toUpperCase() + camelCase.substring(1); String _snakeCaseFromCamelCase(String camelCase) { return camelCase.replaceAllMapped(RegExp(r'[A-Z]'), (Match m) => '${m.start == 0 ? '' : '_'}${m[0]!.toLowerCase()}'); } String _pascalCaseFromSnakeCase(String snakeCase) { final String camelCase = snakeCase.replaceAllMapped( RegExp(r'_([a-z])'), (Match m) => m[1]!.toUpperCase()); return _pascalCaseFromCamelCase(camelCase); } String _makeMethodName(Method method) => _pascalCaseFromCamelCase(method.name); String _makeGetterName(NamedType field) => _snakeCaseFromCamelCase(field.name); String _makeSetterName(NamedType field) => 'set_${_snakeCaseFromCamelCase(field.name)}'; String _makeVariableName(NamedType field) => _snakeCaseFromCamelCase(field.name); String _makeInstanceVariableName(NamedType field) => '${_makeVariableName(field)}_'; // TODO(stuartmorgan): Remove this in favor of _isPodType once callers have // all been updated to using HostDatatypes. bool _isReferenceType(String dataType) { switch (dataType) { case 'bool': case 'int64_t': case 'double': return false; default: return true; } } /// Returns the parameters to use for the success and error callbacks in a /// Flutter API function signature. List<String> _flutterApiCallbackParameters(HostDatatype returnType) { return <String>[ 'std::function<void(${_flutterApiReturnType(returnType)})>&& on_success', 'std::function<void(const FlutterError&)>&& on_error', ]; } /// Returns true if [type] corresponds to a plain-old-data type (i.e., one that /// should generally be passed by value rather than pointer/reference) in C++. bool _isPodType(HostDatatype type) { return !_isReferenceType(type.datatype); } String? _baseCppTypeForBuiltinDartType( TypeDeclaration type, { bool includeFlutterNamespace = true, }) { final String flutterNamespace = includeFlutterNamespace ? 'flutter::' : ''; final Map<String, String> cppTypeForDartTypeMap = <String, String>{ 'void': 'void', 'bool': 'bool', 'int': 'int64_t', 'String': 'std::string', 'double': 'double', 'Uint8List': 'std::vector<uint8_t>', 'Int32List': 'std::vector<int32_t>', 'Int64List': 'std::vector<int64_t>', 'Float64List': 'std::vector<double>', 'Map': '${flutterNamespace}EncodableMap', 'List': '${flutterNamespace}EncodableList', 'Object': '${flutterNamespace}EncodableValue', }; if (cppTypeForDartTypeMap.containsKey(type.baseName)) { return cppTypeForDartTypeMap[type.baseName]; } else { return null; } } /// Returns the C++ type to use in a value context (variable declaration, /// pass-by-value, etc.) for the given C++ base type. String _valueType(HostDatatype type) { final String baseType = type.datatype; return type.isNullable ? 'std::optional<$baseType>' : baseType; } /// Returns the C++ type to use in an argument context without ownership /// transfer for the given base type. String _unownedArgumentType(HostDatatype type) { final bool isString = type.datatype == 'std::string'; final String baseType = isString ? 'std::string_view' : type.datatype; if (isString || _isPodType(type)) { return type.isNullable ? 'const $baseType*' : baseType; } // TODO(stuartmorgan): Consider special-casing `Object?` here, so that there // aren't two ways of representing null (nullptr or an isNull EncodableValue). return type.isNullable ? 'const $baseType*' : 'const $baseType&'; } /// Returns the C++ type to use for arguments to a host API. This is slightly /// different from [_unownedArgumentType] since passing `std::string_view*` in /// to the host API implementation when the actual type is `std::string*` is /// needlessly complicated, so it uses `std::string` directly. String _hostApiArgumentType(HostDatatype type) { final String baseType = type.datatype; if (_isPodType(type)) { return type.isNullable ? 'const $baseType*' : baseType; } return type.isNullable ? 'const $baseType*' : 'const $baseType&'; } /// Returns the C++ type to use for arguments to a Flutter API. String _flutterApiArgumentType(HostDatatype type) { // Nullable strings use std::string* rather than std::string_view* // since there's no implicit conversion for the pointer types, making them // more awkward to use. For consistency, and since EncodableValue will end // up making a std::string internally anyway, std::string is used for the // non-nullable case as well. if (type.datatype == 'std::string') { return type.isNullable ? 'const std::string*' : 'const std::string&'; } return _unownedArgumentType(type); } /// Returns the C++ type to use for the return of a getter for a field of type /// [type]. String _getterReturnType(HostDatatype type) { final String baseType = type.datatype; if (_isPodType(type)) { // Use pointers rather than optionals even for nullable POD, since the // semantics of using them is essentially identical and this makes them // consistent with non-POD. return type.isNullable ? 'const $baseType*' : baseType; } return type.isNullable ? 'const $baseType*' : 'const $baseType&'; } /// Returns the C++ type to use for the return of a host API method returning /// [type]. String _hostApiReturnType(HostDatatype type) { if (type.datatype == 'void') { return 'std::optional<FlutterError>'; } String valueType = type.datatype; if (type.isNullable) { valueType = 'std::optional<$valueType>'; } return 'ErrorOr<$valueType>'; } /// Returns the C++ type to use for the paramer to the asynchronous "return" /// callback of a Flutter API method returning [type]. String _flutterApiReturnType(HostDatatype type) { if (type.datatype == 'void') { return 'void'; } // For anything other than void, handle it the same way as a host API argument // since it has the same basic structure of being a function defined by the // client, being called by the generated code. return _hostApiArgumentType(type); } String _getGuardName(String? headerFileName) { const String prefix = 'PIGEON_'; if (headerFileName != null) { return '$prefix${headerFileName.replaceAll('.', '_').toUpperCase()}_'; } else { return '${prefix}H_'; } } void _writeSystemHeaderIncludeBlock(Indent indent, List<String> headers) { headers.sort(); for (final String header in headers) { indent.writeln('#include <$header>'); } } enum _FunctionOutputType { declaration, definition } /// Writes a function declaration or definition to [indent]. /// /// If [parameters] are given, each should be a string of the form 'type name'. void _writeFunction( Indent indent, _FunctionOutputType type, { required String name, String? returnType, String? scope, List<String> parameters = const <String>[], List<String> startingAnnotations = const <String>[], List<String> trailingAnnotations = const <String>[], List<String> initializers = const <String>[], void Function()? body, }) { assert(body == null || type == _FunctionOutputType.definition); // Set the initial indentation. indent.write(''); // Write any starting annotations (e.g., 'static'). for (final String annotation in startingAnnotations) { indent.add('$annotation '); } // Write the signature. if (returnType != null) { indent.add('$returnType '); } if (scope != null) { indent.add('$scope::'); } indent.add(name); // Write the parameters. if (parameters.isEmpty) { indent.add('()'); } else if (parameters.length == 1) { indent.add('(${parameters.first})'); } else { indent.addScoped('(', null, () { enumerate(parameters, (int index, final String param) { if (index == parameters.length - 1) { indent.write('$param)'); } else { indent.writeln('$param,'); } }); }, addTrailingNewline: false); } // Write any trailing annotations (e.g., 'const'). for (final String annotation in trailingAnnotations) { indent.add(' $annotation'); } // Write the initializer list, if any. if (initializers.isNotEmpty) { indent.newln(); indent.write(' : '); // The first item goes on the same line as the ":", the rest go on their // own lines indented two extra levels, with no comma or newline after the // last one. The easiest way to express the special casing of the first and // last is with a join+format. indent.format(initializers.join(',\n\t\t'), leadingSpace: false, trailingNewline: false); } // Write the body or end the declaration. if (type == _FunctionOutputType.declaration) { indent.addln(';'); } else { if (body != null) { indent.addScoped(' {', '}', body); } else { indent.addln(' {}'); } } } void _writeFunctionDeclaration( Indent indent, String name, { String? returnType, List<String> parameters = const <String>[], bool isStatic = false, bool isVirtual = false, bool isConstructor = false, bool isPureVirtual = false, bool isConst = false, bool isOverride = false, bool deleted = false, bool inlineNoop = false, void Function()? inlineBody, }) { assert(!(isVirtual && isOverride), 'virtual is redundant with override'); assert(isVirtual || !isPureVirtual, 'pure virtual methods must be virtual'); assert(returnType == null || !isConstructor, 'constructors cannot have return types'); _writeFunction( indent, inlineNoop || (inlineBody != null) ? _FunctionOutputType.definition : _FunctionOutputType.declaration, name: name, returnType: returnType, parameters: parameters, startingAnnotations: <String>[ if (inlineBody != null) 'inline', if (isStatic) 'static', if (isVirtual) 'virtual', if (isConstructor && parameters.isNotEmpty) 'explicit' ], trailingAnnotations: <String>[ if (isConst) 'const', if (isOverride) 'override', if (deleted) '= delete', if (isPureVirtual) '= 0', ], body: inlineBody, ); } void _writeFunctionDefinition( Indent indent, String name, { String? returnType, String? scope, List<String> parameters = const <String>[], bool isConst = false, List<String> initializers = const <String>[], void Function()? body, }) { _writeFunction( indent, _FunctionOutputType.definition, name: name, scope: scope, returnType: returnType, parameters: parameters, trailingAnnotations: <String>[ if (isConst) 'const', ], initializers: initializers, body: body, ); indent.newln(); } enum _ClassAccess { public, protected, private } void _writeAccessBlock( Indent indent, _ClassAccess access, void Function() body) { final String accessLabel; switch (access) { case _ClassAccess.public: accessLabel = 'public'; case _ClassAccess.protected: accessLabel = 'protected'; case _ClassAccess.private: accessLabel = 'private'; } indent.addScoped(' $accessLabel:', '', body); } /// Validates an AST to make sure the cpp generator supports everything. List<Error> validateCpp(CppOptions options, Root root) { final List<Error> result = <Error>[]; for (final Api api in root.apis) { for (final Method method in api.methods) { for (final NamedType arg in method.parameters) { if (arg.type.isEnum) { // TODO(gaaclarke): Add line number and filename. result.add(Error( message: "Nullable enum types aren't supported in C++ arguments in method:${api.name}.${method.name} argument:(${arg.type.baseName} ${arg.name}).")); } } } } return result; }
packages/packages/pigeon/lib/cpp_generator.dart/0
{ "file_path": "packages/packages/pigeon/lib/cpp_generator.dart", "repo_id": "packages", "token_count": 26914 }
1,249
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; enum AnEnum { one, two, three, fortyTwo, fourHundredTwentyTwo, } /// A class containing all supported types. class AllTypes { AllTypes({ this.aBool = false, this.anInt = 0, this.anInt64 = 0, this.aDouble = 0, required this.aByteArray, required this.a4ByteArray, required this.a8ByteArray, required this.aFloatArray, this.aList = const <Object?>[], this.aMap = const <String?, Object?>{}, this.anEnum = AnEnum.one, this.aString = '', this.anObject = 0, }); bool aBool; int anInt; int anInt64; double aDouble; Uint8List aByteArray; Int32List a4ByteArray; Int64List a8ByteArray; Float64List aFloatArray; // ignore: always_specify_types, strict_raw_type List aList; // ignore: always_specify_types, strict_raw_type Map aMap; AnEnum anEnum; String aString; Object anObject; } /// A class containing all supported nullable types. class AllNullableTypes { AllNullableTypes( this.aNullableBool, this.aNullableInt, this.aNullableInt64, this.aNullableDouble, this.aNullableByteArray, this.aNullable4ByteArray, this.aNullable8ByteArray, this.aNullableFloatArray, this.aNullableList, this.aNullableMap, this.nullableNestedList, this.nullableMapWithAnnotations, this.nullableMapWithObject, this.aNullableEnum, this.aNullableString, this.aNullableObject, ); bool? aNullableBool; int? aNullableInt; int? aNullableInt64; double? aNullableDouble; Uint8List? aNullableByteArray; Int32List? aNullable4ByteArray; Int64List? aNullable8ByteArray; Float64List? aNullableFloatArray; // ignore: always_specify_types, strict_raw_type List? aNullableList; // ignore: always_specify_types, strict_raw_type Map? aNullableMap; List<List<bool?>?>? nullableNestedList; Map<String?, String?>? nullableMapWithAnnotations; Map<String?, Object?>? nullableMapWithObject; AnEnum? aNullableEnum; String? aNullableString; Object? aNullableObject; } /// A class for testing nested class handling. /// /// This is needed to test nested nullable and non-nullable classes, /// `AllNullableTypes` is non-nullable here as it is easier to instantiate /// than `AllTypes` when testing doesn't require both (ie. testing null classes). class AllClassesWrapper { AllClassesWrapper(this.allNullableTypes, this.allTypes); AllNullableTypes allNullableTypes; AllTypes? allTypes; } /// The core interface that each host language plugin must implement in /// platform_test integration tests. @HostApi() abstract class HostIntegrationCoreApi { // ========== Synchronous method tests ========== /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. void noop(); /// Returns the passed object, to test serialization and deserialization. @ObjCSelector('echoAllTypes:') @SwiftFunction('echo(_:)') AllTypes echoAllTypes(AllTypes everything); /// Returns an error, to test error handling. Object? throwError(); /// Returns an error from a void function, to test error handling. void throwErrorFromVoid(); /// Returns a Flutter error, to test error handling. Object? throwFlutterError(); /// Returns passed in int. @ObjCSelector('echoInt:') @SwiftFunction('echo(_:)') int echoInt(int anInt); /// Returns passed in double. @ObjCSelector('echoDouble:') @SwiftFunction('echo(_:)') double echoDouble(double aDouble); /// Returns the passed in boolean. @ObjCSelector('echoBool:') @SwiftFunction('echo(_:)') bool echoBool(bool aBool); /// Returns the passed in string. @ObjCSelector('echoString:') @SwiftFunction('echo(_:)') String echoString(String aString); /// Returns the passed in Uint8List. @ObjCSelector('echoUint8List:') @SwiftFunction('echo(_:)') Uint8List echoUint8List(Uint8List aUint8List); /// Returns the passed in generic Object. @ObjCSelector('echoObject:') @SwiftFunction('echo(_:)') Object echoObject(Object anObject); /// Returns the passed list, to test serialization and deserialization. @ObjCSelector('echoList:') @SwiftFunction('echo(_:)') List<Object?> echoList(List<Object?> aList); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoMap:') @SwiftFunction('echo(_:)') Map<String?, Object?> echoMap(Map<String?, Object?> aMap); /// Returns the passed map to test nested class serialization and deserialization. @ObjCSelector('echoClassWrapper:') @SwiftFunction('echo(_:)') AllClassesWrapper echoClassWrapper(AllClassesWrapper wrapper); /// Returns the passed enum to test serialization and deserialization. @ObjCSelector('echoEnum:') @SwiftFunction('echo(_:)') AnEnum echoEnum(AnEnum anEnum); /// Returns the default string. @ObjCSelector('echoNamedDefaultString:') @SwiftFunction('echoNamedDefault(_:)') String echoNamedDefaultString({String aString = 'default'}); /// Returns passed in double. @ObjCSelector('echoOptionalDefaultDouble:') @SwiftFunction('echoOptionalDefault(_:)') double echoOptionalDefaultDouble([double aDouble = 3.14]); /// Returns passed in int. @ObjCSelector('echoRequiredInt:') @SwiftFunction('echoRequired(_:)') int echoRequiredInt({required int anInt}); // ========== Synchronous nullable method tests ========== /// Returns the passed object, to test serialization and deserialization. @ObjCSelector('echoAllNullableTypes:') @SwiftFunction('echo(_:)') AllNullableTypes? echoAllNullableTypes(AllNullableTypes? everything); /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. @ObjCSelector('extractNestedNullableStringFrom:') @SwiftFunction('extractNestedNullableString(from:)') String? extractNestedNullableString(AllClassesWrapper wrapper); /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. @ObjCSelector('createNestedObjectWithNullableString:') @SwiftFunction('createNestedObject(with:)') AllClassesWrapper createNestedNullableString(String? nullableString); /// Returns passed in arguments of multiple types. @ObjCSelector('sendMultipleNullableTypesABool:anInt:aString:') @SwiftFunction('sendMultipleNullableTypes(aBool:anInt:aString:)') AllNullableTypes sendMultipleNullableTypes( bool? aNullableBool, int? aNullableInt, String? aNullableString); /// Returns passed in int. @ObjCSelector('echoNullableInt:') @SwiftFunction('echo(_:)') int? echoNullableInt(int? aNullableInt); /// Returns passed in double. @ObjCSelector('echoNullableDouble:') @SwiftFunction('echo(_:)') double? echoNullableDouble(double? aNullableDouble); /// Returns the passed in boolean. @ObjCSelector('echoNullableBool:') @SwiftFunction('echo(_:)') bool? echoNullableBool(bool? aNullableBool); /// Returns the passed in string. @ObjCSelector('echoNullableString:') @SwiftFunction('echo(_:)') String? echoNullableString(String? aNullableString); /// Returns the passed in Uint8List. @ObjCSelector('echoNullableUint8List:') @SwiftFunction('echo(_:)') Uint8List? echoNullableUint8List(Uint8List? aNullableUint8List); /// Returns the passed in generic Object. @ObjCSelector('echoNullableObject:') @SwiftFunction('echo(_:)') Object? echoNullableObject(Object? aNullableObject); /// Returns the passed list, to test serialization and deserialization. @ObjCSelector('echoNullableList:') @SwiftFunction('echoNullable(_:)') List<Object?>? echoNullableList(List<Object?>? aNullableList); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableMap:') @SwiftFunction('echoNullable(_:)') Map<String?, Object?>? echoNullableMap(Map<String?, Object?>? aNullableMap); @ObjCSelector('echoNullableEnum:') @SwiftFunction('echoNullable(_:)') AnEnum? echoNullableEnum(AnEnum? anEnum); /// Returns passed in int. @ObjCSelector('echoOptionalNullableInt:') @SwiftFunction('echoOptional(_:)') int? echoOptionalNullableInt([int? aNullableInt]); /// Returns the passed in string. @ObjCSelector('echoNamedNullableString:') @SwiftFunction('echoNamed(_:)') String? echoNamedNullableString({String? aNullableString}); // ========== Asynchronous method tests ========== /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. @async void noopAsync(); /// Returns passed in int asynchronously. @async @ObjCSelector('echoAsyncInt:') @SwiftFunction('echoAsync(_:)') int echoAsyncInt(int anInt); /// Returns passed in double asynchronously. @async @ObjCSelector('echoAsyncDouble:') @SwiftFunction('echoAsync(_:)') double echoAsyncDouble(double aDouble); /// Returns the passed in boolean asynchronously. @async @ObjCSelector('echoAsyncBool:') @SwiftFunction('echoAsync(_:)') bool echoAsyncBool(bool aBool); /// Returns the passed string asynchronously. @async @ObjCSelector('echoAsyncString:') @SwiftFunction('echoAsync(_:)') String echoAsyncString(String aString); /// Returns the passed in Uint8List asynchronously. @async @ObjCSelector('echoAsyncUint8List:') @SwiftFunction('echoAsync(_:)') Uint8List echoAsyncUint8List(Uint8List aUint8List); /// Returns the passed in generic Object asynchronously. @async @ObjCSelector('echoAsyncObject:') @SwiftFunction('echoAsync(_:)') Object echoAsyncObject(Object anObject); /// Returns the passed list, to test asynchronous serialization and deserialization. @async @ObjCSelector('echoAsyncList:') @SwiftFunction('echoAsync(_:)') List<Object?> echoAsyncList(List<Object?> aList); /// Returns the passed map, to test asynchronous serialization and deserialization. @async @ObjCSelector('echoAsyncMap:') @SwiftFunction('echoAsync(_:)') Map<String?, Object?> echoAsyncMap(Map<String?, Object?> aMap); /// Returns the passed enum, to test asynchronous serialization and deserialization. @async @ObjCSelector('echoAsyncEnum:') @SwiftFunction('echoAsync(_:)') AnEnum echoAsyncEnum(AnEnum anEnum); /// Responds with an error from an async function returning a value. @async Object? throwAsyncError(); /// Responds with an error from an async void function. @async void throwAsyncErrorFromVoid(); /// Responds with a Flutter error from an async function returning a value. @async Object? throwAsyncFlutterError(); /// Returns the passed object, to test async serialization and deserialization. @async @ObjCSelector('echoAsyncAllTypes:') @SwiftFunction('echoAsync(_:)') AllTypes echoAsyncAllTypes(AllTypes everything); /// Returns the passed object, to test serialization and deserialization. @async @ObjCSelector('echoAsyncNullableAllNullableTypes:') @SwiftFunction('echoAsync(_:)') AllNullableTypes? echoAsyncNullableAllNullableTypes( AllNullableTypes? everything); /// Returns passed in int asynchronously. @async @ObjCSelector('echoAsyncNullableInt:') @SwiftFunction('echoAsyncNullable(_:)') int? echoAsyncNullableInt(int? anInt); /// Returns passed in double asynchronously. @async @ObjCSelector('echoAsyncNullableDouble:') @SwiftFunction('echoAsyncNullable(_:)') double? echoAsyncNullableDouble(double? aDouble); /// Returns the passed in boolean asynchronously. @async @ObjCSelector('echoAsyncNullableBool:') @SwiftFunction('echoAsyncNullable(_:)') bool? echoAsyncNullableBool(bool? aBool); /// Returns the passed string asynchronously. @async @ObjCSelector('echoAsyncNullableString:') @SwiftFunction('echoAsyncNullable(_:)') String? echoAsyncNullableString(String? aString); /// Returns the passed in Uint8List asynchronously. @async @ObjCSelector('echoAsyncNullableUint8List:') @SwiftFunction('echoAsyncNullable(_:)') Uint8List? echoAsyncNullableUint8List(Uint8List? aUint8List); /// Returns the passed in generic Object asynchronously. @async @ObjCSelector('echoAsyncNullableObject:') @SwiftFunction('echoAsyncNullable(_:)') Object? echoAsyncNullableObject(Object? anObject); /// Returns the passed list, to test asynchronous serialization and deserialization. @async @ObjCSelector('echoAsyncNullableList:') @SwiftFunction('echoAsyncNullable(_:)') List<Object?>? echoAsyncNullableList(List<Object?>? aList); /// Returns the passed map, to test asynchronous serialization and deserialization. @async @ObjCSelector('echoAsyncNullableMap:') @SwiftFunction('echoAsyncNullable(_:)') Map<String?, Object?>? echoAsyncNullableMap(Map<String?, Object?>? aMap); /// Returns the passed enum, to test asynchronous serialization and deserialization. @async @ObjCSelector('echoAsyncNullableEnum:') @SwiftFunction('echoAsyncNullable(_:)') AnEnum? echoAsyncNullableEnum(AnEnum? anEnum); // ========== Flutter API test wrappers ========== @async void callFlutterNoop(); @async Object? callFlutterThrowError(); @async void callFlutterThrowErrorFromVoid(); @async @ObjCSelector('callFlutterEchoAllTypes:') @SwiftFunction('callFlutterEcho(_:)') AllTypes callFlutterEchoAllTypes(AllTypes everything); @async @ObjCSelector('callFlutterEchoAllNullableTypes:') @SwiftFunction('callFlutterEcho(_:)') AllNullableTypes? callFlutterEchoAllNullableTypes( AllNullableTypes? everything); @async @ObjCSelector('callFlutterSendMultipleNullableTypesABool:anInt:aString:') @SwiftFunction('callFlutterSendMultipleNullableTypes(aBool:anInt:aString:)') AllNullableTypes callFlutterSendMultipleNullableTypes( bool? aNullableBool, int? aNullableInt, String? aNullableString); @async @ObjCSelector('callFlutterEchoBool:') @SwiftFunction('callFlutterEcho(_:)') bool callFlutterEchoBool(bool aBool); @async @ObjCSelector('callFlutterEchoInt:') @SwiftFunction('callFlutterEcho(_:)') int callFlutterEchoInt(int anInt); @async @ObjCSelector('callFlutterEchoDouble:') @SwiftFunction('callFlutterEcho(_:)') double callFlutterEchoDouble(double aDouble); @async @ObjCSelector('callFlutterEchoString:') @SwiftFunction('callFlutterEcho(_:)') String callFlutterEchoString(String aString); @async @ObjCSelector('callFlutterEchoUint8List:') @SwiftFunction('callFlutterEcho(_:)') Uint8List callFlutterEchoUint8List(Uint8List aList); @async @ObjCSelector('callFlutterEchoList:') @SwiftFunction('callFlutterEcho(_:)') List<Object?> callFlutterEchoList(List<Object?> aList); @async @ObjCSelector('callFlutterEchoMap:') @SwiftFunction('callFlutterEcho(_:)') Map<String?, Object?> callFlutterEchoMap(Map<String?, Object?> aMap); @async @ObjCSelector('callFlutterEchoEnum:') @SwiftFunction('callFlutterEcho(_:)') AnEnum callFlutterEchoEnum(AnEnum anEnum); @async @ObjCSelector('callFlutterEchoNullableBool:') @SwiftFunction('callFlutterEchoNullable(_:)') bool? callFlutterEchoNullableBool(bool? aBool); @async @ObjCSelector('callFlutterEchoNullableInt:') @SwiftFunction('callFlutterEchoNullable(_:)') int? callFlutterEchoNullableInt(int? anInt); @async @ObjCSelector('callFlutterEchoNullableDouble:') @SwiftFunction('callFlutterEchoNullable(_:)') double? callFlutterEchoNullableDouble(double? aDouble); @async @ObjCSelector('callFlutterEchoNullableString:') @SwiftFunction('callFlutterEchoNullable(_:)') String? callFlutterEchoNullableString(String? aString); @async @ObjCSelector('callFlutterEchoNullableUint8List:') @SwiftFunction('callFlutterEchoNullable(_:)') Uint8List? callFlutterEchoNullableUint8List(Uint8List? aList); @async @ObjCSelector('callFlutterEchoNullableList:') @SwiftFunction('callFlutterEchoNullable(_:)') List<Object?>? callFlutterEchoNullableList(List<Object?>? aList); @async @ObjCSelector('callFlutterEchoNullableMap:') @SwiftFunction('callFlutterEchoNullable(_:)') Map<String?, Object?>? callFlutterEchoNullableMap( Map<String?, Object?>? aMap); @async @ObjCSelector('callFlutterEchoNullableEnum:') @SwiftFunction('callFlutterNullableEcho(_:)') AnEnum? callFlutterEchoNullableEnum(AnEnum? anEnum); } /// The core interface that the Dart platform_test code implements for host /// integration tests to call into. @FlutterApi() abstract class FlutterIntegrationCoreApi { /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. void noop(); /// Responds with an error from an async function returning a value. Object? throwError(); /// Responds with an error from an async void function. void throwErrorFromVoid(); /// Returns the passed object, to test serialization and deserialization. @ObjCSelector('echoAllTypes:') @SwiftFunction('echo(_:)') AllTypes echoAllTypes(AllTypes everything); /// Returns the passed object, to test serialization and deserialization. @ObjCSelector('echoAllNullableTypes:') @SwiftFunction('echoNullable(_:)') AllNullableTypes? echoAllNullableTypes(AllNullableTypes? everything); /// Returns passed in arguments of multiple types. /// /// Tests multiple-arity FlutterApi handling. @ObjCSelector('sendMultipleNullableTypesABool:anInt:aString:') @SwiftFunction('sendMultipleNullableTypes(aBool:anInt:aString:)') AllNullableTypes sendMultipleNullableTypes( bool? aNullableBool, int? aNullableInt, String? aNullableString); // ========== Non-nullable argument/return type tests ========== /// Returns the passed boolean, to test serialization and deserialization. @ObjCSelector('echoBool:') @SwiftFunction('echo(_:)') bool echoBool(bool aBool); /// Returns the passed int, to test serialization and deserialization. @ObjCSelector('echoInt:') @SwiftFunction('echo(_:)') int echoInt(int anInt); /// Returns the passed double, to test serialization and deserialization. @ObjCSelector('echoDouble:') @SwiftFunction('echo(_:)') double echoDouble(double aDouble); /// Returns the passed string, to test serialization and deserialization. @ObjCSelector('echoString:') @SwiftFunction('echo(_:)') String echoString(String aString); /// Returns the passed byte list, to test serialization and deserialization. @ObjCSelector('echoUint8List:') @SwiftFunction('echo(_:)') Uint8List echoUint8List(Uint8List aList); /// Returns the passed list, to test serialization and deserialization. @ObjCSelector('echoList:') @SwiftFunction('echo(_:)') List<Object?> echoList(List<Object?> aList); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoMap:') @SwiftFunction('echo(_:)') Map<String?, Object?> echoMap(Map<String?, Object?> aMap); /// Returns the passed enum to test serialization and deserialization. @ObjCSelector('echoEnum:') @SwiftFunction('echo(_:)') AnEnum echoEnum(AnEnum anEnum); // ========== Nullable argument/return type tests ========== /// Returns the passed boolean, to test serialization and deserialization. @ObjCSelector('echoNullableBool:') @SwiftFunction('echoNullable(_:)') bool? echoNullableBool(bool? aBool); /// Returns the passed int, to test serialization and deserialization. @ObjCSelector('echoNullableInt:') @SwiftFunction('echoNullable(_:)') int? echoNullableInt(int? anInt); /// Returns the passed double, to test serialization and deserialization. @ObjCSelector('echoNullableDouble:') @SwiftFunction('echoNullable(_:)') double? echoNullableDouble(double? aDouble); /// Returns the passed string, to test serialization and deserialization. @ObjCSelector('echoNullableString:') @SwiftFunction('echoNullable(_:)') String? echoNullableString(String? aString); /// Returns the passed byte list, to test serialization and deserialization. @ObjCSelector('echoNullableUint8List:') @SwiftFunction('echoNullable(_:)') Uint8List? echoNullableUint8List(Uint8List? aList); /// Returns the passed list, to test serialization and deserialization. @ObjCSelector('echoNullableList:') @SwiftFunction('echoNullable(_:)') List<Object?>? echoNullableList(List<Object?>? aList); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableMap:') @SwiftFunction('echoNullable(_:)') Map<String?, Object?>? echoNullableMap(Map<String?, Object?>? aMap); /// Returns the passed enum to test serialization and deserialization. @ObjCSelector('echoNullableEnum:') @SwiftFunction('echoNullable(_:)') AnEnum? echoNullableEnum(AnEnum? anEnum); // ========== Async tests ========== // These are minimal since async FlutterApi only changes Dart generation. // Currently they aren't integration tested, but having them here ensures // analysis coverage. /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. @async void noopAsync(); /// Returns the passed in generic Object asynchronously. @async @ObjCSelector('echoAsyncString:') @SwiftFunction('echoAsync(_:)') String echoAsyncString(String aString); } /// An API that can be implemented for minimal, compile-only tests. // // This is also here to test that multiple host APIs can be generated // successfully in all languages (e.g., in Java where it requires having a // wrapper class). @HostApi() abstract class HostTrivialApi { void noop(); } /// A simple API implemented in some unit tests. // // This is separate from HostIntegrationCoreApi to avoid having to update a // lot of unit tests every time we add something to the integration test API. // TODO(stuartmorgan): Restructure the unit tests to reduce the number of // different APIs we define. @HostApi() abstract class HostSmallApi { @async @ObjCSelector('echoString:') String echo(String aString); @async void voidVoid(); } /// A simple API called in some unit tests. // // This is separate from FlutterIntegrationCoreApi to allow for incrementally // moving from the previous fragmented unit test structure to something more // unified. // TODO(stuartmorgan): Restructure the unit tests to reduce the number of // different APIs we define. @FlutterApi() abstract class FlutterSmallApi { @ObjCSelector('echoWrappedList:') @SwiftFunction('echo(_:)') TestMessage echoWrappedList(TestMessage msg); @ObjCSelector('echoString:') @SwiftFunction('echo(_:)') String echoString(String aString); } /// A data class containing a List, used in unit tests. // TODO(stuartmorgan): Evaluate whether these unit tests are still useful; see // TODOs above about restructuring. class TestMessage { // ignore: always_specify_types, strict_raw_type List? testList; }
packages/packages/pigeon/pigeons/core_tests.dart/0
{ "file_path": "packages/packages/pigeon/pigeons/core_tests.dart", "repo_id": "packages", "token_count": 7491 }
1,250
rootProject.name = 'alternate_language_test_plugin'
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/settings.gradle/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/settings.gradle", "repo_id": "packages", "token_count": 16 }
1,251
org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/android/gradle.properties/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/android/gradle.properties", "repo_id": "packages", "token_count": 31 }
1,252
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import Flutter; @import XCTest; @import alternate_language_test_plugin; #import "EchoMessenger.h" /////////////////////////////////////////////////////////////////////////////////////////// @interface EnumTest : XCTestCase @end /////////////////////////////////////////////////////////////////////////////////////////// @implementation EnumTest - (void)testEcho { PGNDataWithEnum *data = [[PGNDataWithEnum alloc] init]; PGNEnumStateBox *stateBox = [[PGNEnumStateBox alloc] initWithValue:PGNEnumStateError]; data.state = stateBox; EchoBinaryMessenger *binaryMessenger = [[EchoBinaryMessenger alloc] initWithCodec:PGNEnumApi2HostGetCodec()]; PGNEnumApi2Flutter *api = [[PGNEnumApi2Flutter alloc] initWithBinaryMessenger:binaryMessenger]; XCTestExpectation *expectation = [self expectationWithDescription:@"callback"]; [api echoData:data completion:^(PGNDataWithEnum *_Nonnull result, FlutterError *_Nullable error) { XCTAssertEqual(data.state.value, result.state.value); [expectation fulfill]; }]; [self waitForExpectations:@[ expectation ] timeout:1.0]; } @end
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/EnumTest.m/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/EnumTest.m", "repo_id": "packages", "token_count": 408 }
1,253
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Autogenerated from Pigeon, do not edit directly. // See also: https://pub.dev/packages/pigeon #import "CoreTests.gen.h" #if TARGET_OS_OSX #import <FlutterMacOS/FlutterMacOS.h> #else #import <Flutter/Flutter.h> #endif #if !__has_feature(objc_arc) #error File requires ARC to be enabled. #endif static NSArray *wrapResult(id result, FlutterError *error) { if (error) { return @[ error.code ?: [NSNull null], error.message ?: [NSNull null], error.details ?: [NSNull null] ]; } return @[ result ?: [NSNull null] ]; } static FlutterError *createConnectionError(NSString *channelName) { return [FlutterError errorWithCode:@"channel-error" message:[NSString stringWithFormat:@"%@/%@/%@", @"Unable to establish connection on channel: '", channelName, @"'."] details:@""]; } static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) { id result = array[key]; return (result == [NSNull null]) ? nil : result; } @implementation FLTAnEnumBox - (instancetype)initWithValue:(FLTAnEnum)value { self = [super init]; if (self) { _value = value; } return self; } @end @interface FLTAllTypes () + (FLTAllTypes *)fromList:(NSArray *)list; + (nullable FLTAllTypes *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @interface FLTAllNullableTypes () + (FLTAllNullableTypes *)fromList:(NSArray *)list; + (nullable FLTAllNullableTypes *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @interface FLTAllClassesWrapper () + (FLTAllClassesWrapper *)fromList:(NSArray *)list; + (nullable FLTAllClassesWrapper *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @interface FLTTestMessage () + (FLTTestMessage *)fromList:(NSArray *)list; + (nullable FLTTestMessage *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @implementation FLTAllTypes + (instancetype)makeWithABool:(BOOL)aBool anInt:(NSInteger)anInt anInt64:(NSInteger)anInt64 aDouble:(double)aDouble aByteArray:(FlutterStandardTypedData *)aByteArray a4ByteArray:(FlutterStandardTypedData *)a4ByteArray a8ByteArray:(FlutterStandardTypedData *)a8ByteArray aFloatArray:(FlutterStandardTypedData *)aFloatArray aList:(NSArray *)aList aMap:(NSDictionary *)aMap anEnum:(FLTAnEnum)anEnum aString:(NSString *)aString anObject:(id)anObject { FLTAllTypes *pigeonResult = [[FLTAllTypes alloc] init]; pigeonResult.aBool = aBool; pigeonResult.anInt = anInt; pigeonResult.anInt64 = anInt64; pigeonResult.aDouble = aDouble; pigeonResult.aByteArray = aByteArray; pigeonResult.a4ByteArray = a4ByteArray; pigeonResult.a8ByteArray = a8ByteArray; pigeonResult.aFloatArray = aFloatArray; pigeonResult.aList = aList; pigeonResult.aMap = aMap; pigeonResult.anEnum = anEnum; pigeonResult.aString = aString; pigeonResult.anObject = anObject; return pigeonResult; } + (FLTAllTypes *)fromList:(NSArray *)list { FLTAllTypes *pigeonResult = [[FLTAllTypes alloc] init]; pigeonResult.aBool = [GetNullableObjectAtIndex(list, 0) boolValue]; pigeonResult.anInt = [GetNullableObjectAtIndex(list, 1) integerValue]; pigeonResult.anInt64 = [GetNullableObjectAtIndex(list, 2) integerValue]; pigeonResult.aDouble = [GetNullableObjectAtIndex(list, 3) doubleValue]; pigeonResult.aByteArray = GetNullableObjectAtIndex(list, 4); pigeonResult.a4ByteArray = GetNullableObjectAtIndex(list, 5); pigeonResult.a8ByteArray = GetNullableObjectAtIndex(list, 6); pigeonResult.aFloatArray = GetNullableObjectAtIndex(list, 7); pigeonResult.aList = GetNullableObjectAtIndex(list, 8); pigeonResult.aMap = GetNullableObjectAtIndex(list, 9); pigeonResult.anEnum = [GetNullableObjectAtIndex(list, 10) integerValue]; pigeonResult.aString = GetNullableObjectAtIndex(list, 11); pigeonResult.anObject = GetNullableObjectAtIndex(list, 12); return pigeonResult; } + (nullable FLTAllTypes *)nullableFromList:(NSArray *)list { return (list) ? [FLTAllTypes fromList:list] : nil; } - (NSArray *)toList { return @[ @(self.aBool), @(self.anInt), @(self.anInt64), @(self.aDouble), self.aByteArray ?: [NSNull null], self.a4ByteArray ?: [NSNull null], self.a8ByteArray ?: [NSNull null], self.aFloatArray ?: [NSNull null], self.aList ?: [NSNull null], self.aMap ?: [NSNull null], @(self.anEnum), self.aString ?: [NSNull null], self.anObject ?: [NSNull null], ]; } @end @implementation FLTAllNullableTypes + (instancetype)makeWithANullableBool:(nullable NSNumber *)aNullableBool aNullableInt:(nullable NSNumber *)aNullableInt aNullableInt64:(nullable NSNumber *)aNullableInt64 aNullableDouble:(nullable NSNumber *)aNullableDouble aNullableByteArray:(nullable FlutterStandardTypedData *)aNullableByteArray aNullable4ByteArray:(nullable FlutterStandardTypedData *)aNullable4ByteArray aNullable8ByteArray:(nullable FlutterStandardTypedData *)aNullable8ByteArray aNullableFloatArray:(nullable FlutterStandardTypedData *)aNullableFloatArray aNullableList:(nullable NSArray *)aNullableList aNullableMap:(nullable NSDictionary *)aNullableMap nullableNestedList:(nullable NSArray<NSArray<NSNumber *> *> *)nullableNestedList nullableMapWithAnnotations: (nullable NSDictionary<NSString *, NSString *> *)nullableMapWithAnnotations nullableMapWithObject:(nullable NSDictionary<NSString *, id> *)nullableMapWithObject aNullableEnum:(nullable FLTAnEnumBox *)aNullableEnum aNullableString:(nullable NSString *)aNullableString aNullableObject:(nullable id)aNullableObject { FLTAllNullableTypes *pigeonResult = [[FLTAllNullableTypes alloc] init]; pigeonResult.aNullableBool = aNullableBool; pigeonResult.aNullableInt = aNullableInt; pigeonResult.aNullableInt64 = aNullableInt64; pigeonResult.aNullableDouble = aNullableDouble; pigeonResult.aNullableByteArray = aNullableByteArray; pigeonResult.aNullable4ByteArray = aNullable4ByteArray; pigeonResult.aNullable8ByteArray = aNullable8ByteArray; pigeonResult.aNullableFloatArray = aNullableFloatArray; pigeonResult.aNullableList = aNullableList; pigeonResult.aNullableMap = aNullableMap; pigeonResult.nullableNestedList = nullableNestedList; pigeonResult.nullableMapWithAnnotations = nullableMapWithAnnotations; pigeonResult.nullableMapWithObject = nullableMapWithObject; pigeonResult.aNullableEnum = aNullableEnum; pigeonResult.aNullableString = aNullableString; pigeonResult.aNullableObject = aNullableObject; return pigeonResult; } + (FLTAllNullableTypes *)fromList:(NSArray *)list { FLTAllNullableTypes *pigeonResult = [[FLTAllNullableTypes alloc] init]; pigeonResult.aNullableBool = GetNullableObjectAtIndex(list, 0); pigeonResult.aNullableInt = GetNullableObjectAtIndex(list, 1); pigeonResult.aNullableInt64 = GetNullableObjectAtIndex(list, 2); pigeonResult.aNullableDouble = GetNullableObjectAtIndex(list, 3); pigeonResult.aNullableByteArray = GetNullableObjectAtIndex(list, 4); pigeonResult.aNullable4ByteArray = GetNullableObjectAtIndex(list, 5); pigeonResult.aNullable8ByteArray = GetNullableObjectAtIndex(list, 6); pigeonResult.aNullableFloatArray = GetNullableObjectAtIndex(list, 7); pigeonResult.aNullableList = GetNullableObjectAtIndex(list, 8); pigeonResult.aNullableMap = GetNullableObjectAtIndex(list, 9); pigeonResult.nullableNestedList = GetNullableObjectAtIndex(list, 10); pigeonResult.nullableMapWithAnnotations = GetNullableObjectAtIndex(list, 11); pigeonResult.nullableMapWithObject = GetNullableObjectAtIndex(list, 12); NSNumber *aNullableEnumAsNumber = GetNullableObjectAtIndex(list, 13); FLTAnEnumBox *aNullableEnum = aNullableEnumAsNumber == nil ? nil : [[FLTAnEnumBox alloc] initWithValue:[aNullableEnumAsNumber integerValue]]; pigeonResult.aNullableEnum = aNullableEnum; pigeonResult.aNullableString = GetNullableObjectAtIndex(list, 14); pigeonResult.aNullableObject = GetNullableObjectAtIndex(list, 15); return pigeonResult; } + (nullable FLTAllNullableTypes *)nullableFromList:(NSArray *)list { return (list) ? [FLTAllNullableTypes fromList:list] : nil; } - (NSArray *)toList { return @[ self.aNullableBool ?: [NSNull null], self.aNullableInt ?: [NSNull null], self.aNullableInt64 ?: [NSNull null], self.aNullableDouble ?: [NSNull null], self.aNullableByteArray ?: [NSNull null], self.aNullable4ByteArray ?: [NSNull null], self.aNullable8ByteArray ?: [NSNull null], self.aNullableFloatArray ?: [NSNull null], self.aNullableList ?: [NSNull null], self.aNullableMap ?: [NSNull null], self.nullableNestedList ?: [NSNull null], self.nullableMapWithAnnotations ?: [NSNull null], self.nullableMapWithObject ?: [NSNull null], (self.aNullableEnum == nil ? [NSNull null] : [NSNumber numberWithInteger:self.aNullableEnum.value]), self.aNullableString ?: [NSNull null], self.aNullableObject ?: [NSNull null], ]; } @end @implementation FLTAllClassesWrapper + (instancetype)makeWithAllNullableTypes:(FLTAllNullableTypes *)allNullableTypes allTypes:(nullable FLTAllTypes *)allTypes { FLTAllClassesWrapper *pigeonResult = [[FLTAllClassesWrapper alloc] init]; pigeonResult.allNullableTypes = allNullableTypes; pigeonResult.allTypes = allTypes; return pigeonResult; } + (FLTAllClassesWrapper *)fromList:(NSArray *)list { FLTAllClassesWrapper *pigeonResult = [[FLTAllClassesWrapper alloc] init]; pigeonResult.allNullableTypes = [FLTAllNullableTypes nullableFromList:(GetNullableObjectAtIndex(list, 0))]; pigeonResult.allTypes = [FLTAllTypes nullableFromList:(GetNullableObjectAtIndex(list, 1))]; return pigeonResult; } + (nullable FLTAllClassesWrapper *)nullableFromList:(NSArray *)list { return (list) ? [FLTAllClassesWrapper fromList:list] : nil; } - (NSArray *)toList { return @[ (self.allNullableTypes ? [self.allNullableTypes toList] : [NSNull null]), (self.allTypes ? [self.allTypes toList] : [NSNull null]), ]; } @end @implementation FLTTestMessage + (instancetype)makeWithTestList:(nullable NSArray *)testList { FLTTestMessage *pigeonResult = [[FLTTestMessage alloc] init]; pigeonResult.testList = testList; return pigeonResult; } + (FLTTestMessage *)fromList:(NSArray *)list { FLTTestMessage *pigeonResult = [[FLTTestMessage alloc] init]; pigeonResult.testList = GetNullableObjectAtIndex(list, 0); return pigeonResult; } + (nullable FLTTestMessage *)nullableFromList:(NSArray *)list { return (list) ? [FLTTestMessage fromList:list] : nil; } - (NSArray *)toList { return @[ self.testList ?: [NSNull null], ]; } @end @interface FLTHostIntegrationCoreApiCodecReader : FlutterStandardReader @end @implementation FLTHostIntegrationCoreApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { case 128: return [FLTAllClassesWrapper fromList:[self readValue]]; case 129: return [FLTAllNullableTypes fromList:[self readValue]]; case 130: return [FLTAllTypes fromList:[self readValue]]; case 131: return [FLTTestMessage fromList:[self readValue]]; default: return [super readValueOfType:type]; } } @end @interface FLTHostIntegrationCoreApiCodecWriter : FlutterStandardWriter @end @implementation FLTHostIntegrationCoreApiCodecWriter - (void)writeValue:(id)value { if ([value isKindOfClass:[FLTAllClassesWrapper class]]) { [self writeByte:128]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[FLTAllNullableTypes class]]) { [self writeByte:129]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[FLTAllTypes class]]) { [self writeByte:130]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[FLTTestMessage class]]) { [self writeByte:131]; [self writeValue:[value toList]]; } else { [super writeValue:value]; } } @end @interface FLTHostIntegrationCoreApiCodecReaderWriter : FlutterStandardReaderWriter @end @implementation FLTHostIntegrationCoreApiCodecReaderWriter - (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { return [[FLTHostIntegrationCoreApiCodecWriter alloc] initWithData:data]; } - (FlutterStandardReader *)readerWithData:(NSData *)data { return [[FLTHostIntegrationCoreApiCodecReader alloc] initWithData:data]; } @end NSObject<FlutterMessageCodec> *FLTHostIntegrationCoreApiGetCodec(void) { static FlutterStandardMessageCodec *sSharedObject = nil; static dispatch_once_t sPred = 0; dispatch_once(&sPred, ^{ FLTHostIntegrationCoreApiCodecReaderWriter *readerWriter = [[FLTHostIntegrationCoreApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } void SetUpFLTHostIntegrationCoreApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FLTHostIntegrationCoreApi> *api) { /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.noop" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(noopWithError:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to @selector(noopWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; [api noopWithError:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed object, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAllTypes" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoAllTypes:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to @selector(echoAllTypes:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTAllTypes *arg_everything = GetNullableObjectAtIndex(args, 0); FlutterError *error; FLTAllTypes *output = [api echoAllTypes:arg_everything error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns an error, to test error handling. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwError" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(throwErrorWithError:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to @selector(throwErrorWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; id output = [api throwErrorWithError:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns an error from a void function, to test error handling. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"throwErrorFromVoid" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(throwErrorFromVoidWithError:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(throwErrorFromVoidWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; [api throwErrorFromVoidWithError:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns a Flutter error, to test error handling. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"throwFlutterError" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(throwFlutterErrorWithError:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(throwFlutterErrorWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; id output = [api throwFlutterErrorWithError:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in int. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoInt" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoInt:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to @selector(echoInt:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSInteger arg_anInt = [GetNullableObjectAtIndex(args, 0) integerValue]; FlutterError *error; NSNumber *output = [api echoInt:arg_anInt error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in double. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoDouble" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoDouble:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to @selector(echoDouble:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; double arg_aDouble = [GetNullableObjectAtIndex(args, 0) doubleValue]; FlutterError *error; NSNumber *output = [api echoDouble:arg_aDouble error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in boolean. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoBool" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoBool:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to @selector(echoBool:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; BOOL arg_aBool = [GetNullableObjectAtIndex(args, 0) boolValue]; FlutterError *error; NSNumber *output = [api echoBool:arg_aBool error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in string. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoString" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoString:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to @selector(echoString:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aString = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSString *output = [api echoString:arg_aString error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in Uint8List. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoUint8List" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoUint8List:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to @selector(echoUint8List:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FlutterStandardTypedData *arg_aUint8List = GetNullableObjectAtIndex(args, 0); FlutterError *error; FlutterStandardTypedData *output = [api echoUint8List:arg_aUint8List error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in generic Object. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoObject" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(echoObject:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to @selector(echoObject:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; id arg_anObject = GetNullableObjectAtIndex(args, 0); FlutterError *error; id output = [api echoObject:arg_anObject error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed list, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoList" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoList:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to @selector(echoList:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSArray<id> *arg_aList = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSArray<id> *output = [api echoList:arg_aList error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed map, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoMap" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoMap:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to @selector(echoMap:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSDictionary<NSString *, id> *arg_aMap = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSDictionary<NSString *, id> *output = [api echoMap:arg_aMap error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed map to test nested class serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoClassWrapper" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoClassWrapper:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoClassWrapper:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTAllClassesWrapper *arg_wrapper = GetNullableObjectAtIndex(args, 0); FlutterError *error; FLTAllClassesWrapper *output = [api echoClassWrapper:arg_wrapper error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed enum to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoEnum" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoEnum:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to @selector(echoEnum:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTAnEnum arg_anEnum = [GetNullableObjectAtIndex(args, 0) integerValue]; FlutterError *error; FLTAnEnumBox *enumBox = [api echoEnum:arg_anEnum error:&error]; NSNumber *output = enumBox == nil ? nil : [NSNumber numberWithInteger:enumBox.value]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the default string. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNamedDefaultString" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNamedDefaultString:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNamedDefaultString:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aString = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSString *output = [api echoNamedDefaultString:arg_aString error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in double. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoOptionalDefaultDouble" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoOptionalDefaultDouble:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoOptionalDefaultDouble:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; double arg_aDouble = [GetNullableObjectAtIndex(args, 0) doubleValue]; FlutterError *error; NSNumber *output = [api echoOptionalDefaultDouble:arg_aDouble error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in int. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoRequiredInt" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoRequiredInt:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoRequiredInt:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSInteger arg_anInt = [GetNullableObjectAtIndex(args, 0) integerValue]; FlutterError *error; NSNumber *output = [api echoRequiredInt:arg_anInt error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed object, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAllNullableTypes" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAllNullableTypes:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAllNullableTypes:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTAllNullableTypes *arg_everything = GetNullableObjectAtIndex(args, 0); FlutterError *error; FLTAllNullableTypes *output = [api echoAllNullableTypes:arg_everything error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"extractNestedNullableString" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(extractNestedNullableStringFrom:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(extractNestedNullableStringFrom:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTAllClassesWrapper *arg_wrapper = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSString *output = [api extractNestedNullableStringFrom:arg_wrapper error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"createNestedNullableString" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(createNestedObjectWithNullableString:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(createNestedObjectWithNullableString:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_nullableString = GetNullableObjectAtIndex(args, 0); FlutterError *error; FLTAllClassesWrapper *output = [api createNestedObjectWithNullableString:arg_nullableString error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in arguments of multiple types. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"sendMultipleNullableTypes" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(sendMultipleNullableTypesABool: anInt:aString:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(sendMultipleNullableTypesABool:anInt:aString:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aNullableBool = GetNullableObjectAtIndex(args, 0); NSNumber *arg_aNullableInt = GetNullableObjectAtIndex(args, 1); NSString *arg_aNullableString = GetNullableObjectAtIndex(args, 2); FlutterError *error; FLTAllNullableTypes *output = [api sendMultipleNullableTypesABool:arg_aNullableBool anInt:arg_aNullableInt aString:arg_aNullableString error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in int. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableInt" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNullableInt:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNullableInt:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aNullableInt = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSNumber *output = [api echoNullableInt:arg_aNullableInt error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in double. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNullableDouble" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNullableDouble:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNullableDouble:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aNullableDouble = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSNumber *output = [api echoNullableDouble:arg_aNullableDouble error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in boolean. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNullableBool" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNullableBool:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNullableBool:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aNullableBool = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSNumber *output = [api echoNullableBool:arg_aNullableBool error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in string. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNullableString" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNullableString:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNullableString:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aNullableString = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSString *output = [api echoNullableString:arg_aNullableString error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in Uint8List. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNullableUint8List" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNullableUint8List:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNullableUint8List:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FlutterStandardTypedData *arg_aNullableUint8List = GetNullableObjectAtIndex(args, 0); FlutterError *error; FlutterStandardTypedData *output = [api echoNullableUint8List:arg_aNullableUint8List error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in generic Object. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNullableObject" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNullableObject:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNullableObject:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; id arg_aNullableObject = GetNullableObjectAtIndex(args, 0); FlutterError *error; id output = [api echoNullableObject:arg_aNullableObject error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed list, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNullableList" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNullableList:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNullableList:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSArray<id> *arg_aNullableList = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSArray<id> *output = [api echoNullableList:arg_aNullableList error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed map, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableMap" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNullableMap:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNullableMap:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSDictionary<NSString *, id> *arg_aNullableMap = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSDictionary<NSString *, id> *output = [api echoNullableMap:arg_aNullableMap error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNullableEnum" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNullableEnum:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNullableEnum:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_anEnumAsNumber = GetNullableObjectAtIndex(args, 0); FLTAnEnumBox *arg_anEnum = arg_anEnumAsNumber == nil ? nil : [[FLTAnEnumBox alloc] initWithValue:[arg_anEnumAsNumber integerValue]]; FlutterError *error; FLTAnEnumBox *enumBox = [api echoNullableEnum:arg_anEnum error:&error]; NSNumber *output = enumBox == nil ? nil : [NSNumber numberWithInteger:enumBox.value]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in int. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoOptionalNullableInt" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoOptionalNullableInt:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoOptionalNullableInt:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aNullableInt = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSNumber *output = [api echoOptionalNullableInt:arg_aNullableInt error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in string. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoNamedNullableString" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoNamedNullableString:error:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoNamedNullableString:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aNullableString = GetNullableObjectAtIndex(args, 0); FlutterError *error; NSString *output = [api echoNamedNullableString:arg_aNullableString error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.noopAsync" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(noopAsyncWithCompletion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(noopAsyncWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api noopAsyncWithCompletion:^(FlutterError *_Nullable error) { callback(wrapResult(nil, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in int asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncInt" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncInt:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncInt:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSInteger arg_anInt = [GetNullableObjectAtIndex(args, 0) integerValue]; [api echoAsyncInt:arg_anInt completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in double asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncDouble" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncDouble:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncDouble:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; double arg_aDouble = [GetNullableObjectAtIndex(args, 0) doubleValue]; [api echoAsyncDouble:arg_aDouble completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in boolean asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncBool" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncBool:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncBool:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; BOOL arg_aBool = [GetNullableObjectAtIndex(args, 0) boolValue]; [api echoAsyncBool:arg_aBool completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed string asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncString" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncString:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncString:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aString = GetNullableObjectAtIndex(args, 0); [api echoAsyncString:arg_aString completion:^(NSString *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in Uint8List asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncUint8List" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncUint8List:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncUint8List:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FlutterStandardTypedData *arg_aUint8List = GetNullableObjectAtIndex(args, 0); [api echoAsyncUint8List:arg_aUint8List completion:^(FlutterStandardTypedData *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in generic Object asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncObject" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncObject:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncObject:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; id arg_anObject = GetNullableObjectAtIndex(args, 0); [api echoAsyncObject:arg_anObject completion:^(id _Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed list, to test asynchronous serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncList" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncList:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncList:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSArray<id> *arg_aList = GetNullableObjectAtIndex(args, 0); [api echoAsyncList:arg_aList completion:^(NSArray<id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed map, to test asynchronous serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncMap" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncMap:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncMap:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSDictionary<NSString *, id> *arg_aMap = GetNullableObjectAtIndex(args, 0); [api echoAsyncMap:arg_aMap completion:^(NSDictionary<NSString *, id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed enum, to test asynchronous serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncEnum" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncEnum:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncEnum:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTAnEnum arg_anEnum = [GetNullableObjectAtIndex(args, 0) integerValue]; [api echoAsyncEnum:arg_anEnum completion:^(FLTAnEnumBox *_Nullable enumValue, FlutterError *_Nullable error) { NSNumber *output = enumValue == nil ? nil : [NSNumber numberWithInteger:enumValue.value]; callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Responds with an error from an async function returning a value. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwAsyncError" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(throwAsyncErrorWithCompletion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(throwAsyncErrorWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api throwAsyncErrorWithCompletion:^(id _Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Responds with an error from an async void function. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"throwAsyncErrorFromVoid" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(throwAsyncErrorFromVoidWithCompletion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(throwAsyncErrorFromVoidWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api throwAsyncErrorFromVoidWithCompletion:^(FlutterError *_Nullable error) { callback(wrapResult(nil, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Responds with a Flutter error from an async function returning a value. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"throwAsyncFlutterError" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(throwAsyncFlutterErrorWithCompletion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(throwAsyncFlutterErrorWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api throwAsyncFlutterErrorWithCompletion:^(id _Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed object, to test async serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncAllTypes" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncAllTypes:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncAllTypes:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTAllTypes *arg_everything = GetNullableObjectAtIndex(args, 0); [api echoAsyncAllTypes:arg_everything completion:^(FLTAllTypes *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed object, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableAllNullableTypes" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableAllNullableTypes:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableAllNullableTypes:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTAllNullableTypes *arg_everything = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableAllNullableTypes:arg_everything completion:^(FLTAllNullableTypes *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in int asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableInt" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableInt:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableInt:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_anInt = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableInt:arg_anInt completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns passed in double asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableDouble" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableDouble:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableDouble:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aDouble = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableDouble:arg_aDouble completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in boolean asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableBool" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableBool:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableBool:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aBool = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableBool:arg_aBool completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed string asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableString" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableString:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableString:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aString = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableString:arg_aString completion:^(NSString *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in Uint8List asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableUint8List" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableUint8List:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableUint8List:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FlutterStandardTypedData *arg_aUint8List = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableUint8List:arg_aUint8List completion:^(FlutterStandardTypedData *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed in generic Object asynchronously. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableObject" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableObject:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableObject:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; id arg_anObject = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableObject:arg_anObject completion:^(id _Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed list, to test asynchronous serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableList" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableList:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableList:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSArray<id> *arg_aList = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableList:arg_aList completion:^(NSArray<id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed map, to test asynchronous serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableMap" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableMap:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableMap:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSDictionary<NSString *, id> *arg_aMap = GetNullableObjectAtIndex(args, 0); [api echoAsyncNullableMap:arg_aMap completion:^(NSDictionary<NSString *, id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } /// Returns the passed enum, to test asynchronous serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"echoAsyncNullableEnum" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoAsyncNullableEnum:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(echoAsyncNullableEnum:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_anEnumAsNumber = GetNullableObjectAtIndex(args, 0); FLTAnEnumBox *arg_anEnum = arg_anEnumAsNumber == nil ? nil : [[FLTAnEnumBox alloc] initWithValue:[arg_anEnumAsNumber integerValue]]; [api echoAsyncNullableEnum:arg_anEnum completion:^(FLTAnEnumBox *_Nullable enumValue, FlutterError *_Nullable error) { NSNumber *output = enumValue == nil ? nil : [NSNumber numberWithInteger:enumValue.value]; callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName: @"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterNoop" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterNoopWithCompletion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterNoopWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api callFlutterNoopWithCompletion:^(FlutterError *_Nullable error) { callback(wrapResult(nil, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterThrowError" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterThrowErrorWithCompletion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterThrowErrorWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api callFlutterThrowErrorWithCompletion:^(id _Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterThrowErrorFromVoid" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterThrowErrorFromVoidWithCompletion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterThrowErrorFromVoidWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api callFlutterThrowErrorFromVoidWithCompletion:^(FlutterError *_Nullable error) { callback(wrapResult(nil, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoAllTypes" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoAllTypes:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoAllTypes:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTAllTypes *arg_everything = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoAllTypes:arg_everything completion:^(FLTAllTypes *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoAllNullableTypes" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoAllNullableTypes:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoAllNullableTypes:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTAllNullableTypes *arg_everything = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoAllNullableTypes:arg_everything completion:^(FLTAllNullableTypes *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterSendMultipleNullableTypes" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector (callFlutterSendMultipleNullableTypesABool:anInt:aString:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterSendMultipleNullableTypesABool:anInt:aString:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aNullableBool = GetNullableObjectAtIndex(args, 0); NSNumber *arg_aNullableInt = GetNullableObjectAtIndex(args, 1); NSString *arg_aNullableString = GetNullableObjectAtIndex(args, 2); [api callFlutterSendMultipleNullableTypesABool:arg_aNullableBool anInt:arg_aNullableInt aString:arg_aNullableString completion:^(FLTAllNullableTypes *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoBool" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoBool:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoBool:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; BOOL arg_aBool = [GetNullableObjectAtIndex(args, 0) boolValue]; [api callFlutterEchoBool:arg_aBool completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoInt" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoInt:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoInt:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSInteger arg_anInt = [GetNullableObjectAtIndex(args, 0) integerValue]; [api callFlutterEchoInt:arg_anInt completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoDouble" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoDouble:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoDouble:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; double arg_aDouble = [GetNullableObjectAtIndex(args, 0) doubleValue]; [api callFlutterEchoDouble:arg_aDouble completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoString" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoString:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoString:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aString = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoString:arg_aString completion:^(NSString *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoUint8List" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoUint8List:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoUint8List:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FlutterStandardTypedData *arg_aList = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoUint8List:arg_aList completion:^(FlutterStandardTypedData *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoList" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoList:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoList:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSArray<id> *arg_aList = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoList:arg_aList completion:^(NSArray<id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoMap" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoMap:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoMap:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSDictionary<NSString *, id> *arg_aMap = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoMap:arg_aMap completion:^(NSDictionary<NSString *, id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoEnum" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoEnum:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoEnum:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FLTAnEnum arg_anEnum = [GetNullableObjectAtIndex(args, 0) integerValue]; [api callFlutterEchoEnum:arg_anEnum completion:^(FLTAnEnumBox *_Nullable enumValue, FlutterError *_Nullable error) { NSNumber *output = enumValue == nil ? nil : [NSNumber numberWithInteger:enumValue.value]; callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableBool" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableBool:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableBool:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aBool = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoNullableBool:arg_aBool completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableInt" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableInt:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableInt:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_anInt = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoNullableInt:arg_anInt completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableDouble" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableDouble:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableDouble:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_aDouble = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoNullableDouble:arg_aDouble completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableString" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableString:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableString:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aString = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoNullableString:arg_aString completion:^(NSString *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableUint8List" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableUint8List:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableUint8List:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FlutterStandardTypedData *arg_aList = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoNullableUint8List:arg_aList completion:^(FlutterStandardTypedData *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableList" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableList:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableList:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSArray<id> *arg_aList = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoNullableList:arg_aList completion:^(NSArray<id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableMap" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableMap:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableMap:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSDictionary<NSString *, id> *arg_aMap = GetNullableObjectAtIndex(args, 0); [api callFlutterEchoNullableMap:arg_aMap completion:^(NSDictionary<NSString *, id> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." @"callFlutterEchoNullableEnum" binaryMessenger:binaryMessenger codec:FLTHostIntegrationCoreApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(callFlutterEchoNullableEnum:completion:)], @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " @"@selector(callFlutterEchoNullableEnum:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSNumber *arg_anEnumAsNumber = GetNullableObjectAtIndex(args, 0); FLTAnEnumBox *arg_anEnum = arg_anEnumAsNumber == nil ? nil : [[FLTAnEnumBox alloc] initWithValue:[arg_anEnumAsNumber integerValue]]; [api callFlutterEchoNullableEnum:arg_anEnum completion:^(FLTAnEnumBox *_Nullable enumValue, FlutterError *_Nullable error) { NSNumber *output = enumValue == nil ? nil : [NSNumber numberWithInteger:enumValue.value]; callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } } @interface FLTFlutterIntegrationCoreApiCodecReader : FlutterStandardReader @end @implementation FLTFlutterIntegrationCoreApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { case 128: return [FLTAllClassesWrapper fromList:[self readValue]]; case 129: return [FLTAllNullableTypes fromList:[self readValue]]; case 130: return [FLTAllTypes fromList:[self readValue]]; case 131: return [FLTTestMessage fromList:[self readValue]]; default: return [super readValueOfType:type]; } } @end @interface FLTFlutterIntegrationCoreApiCodecWriter : FlutterStandardWriter @end @implementation FLTFlutterIntegrationCoreApiCodecWriter - (void)writeValue:(id)value { if ([value isKindOfClass:[FLTAllClassesWrapper class]]) { [self writeByte:128]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[FLTAllNullableTypes class]]) { [self writeByte:129]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[FLTAllTypes class]]) { [self writeByte:130]; [self writeValue:[value toList]]; } else if ([value isKindOfClass:[FLTTestMessage class]]) { [self writeByte:131]; [self writeValue:[value toList]]; } else { [super writeValue:value]; } } @end @interface FLTFlutterIntegrationCoreApiCodecReaderWriter : FlutterStandardReaderWriter @end @implementation FLTFlutterIntegrationCoreApiCodecReaderWriter - (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { return [[FLTFlutterIntegrationCoreApiCodecWriter alloc] initWithData:data]; } - (FlutterStandardReader *)readerWithData:(NSData *)data { return [[FLTFlutterIntegrationCoreApiCodecReader alloc] initWithData:data]; } @end NSObject<FlutterMessageCodec> *FLTFlutterIntegrationCoreApiGetCodec(void) { static FlutterStandardMessageCodec *sSharedObject = nil; static dispatch_once_t sPred = 0; dispatch_once(&sPred, ^{ FLTFlutterIntegrationCoreApiCodecReaderWriter *readerWriter = [[FLTFlutterIntegrationCoreApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } @interface FLTFlutterIntegrationCoreApi () @property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger; @end @implementation FLTFlutterIntegrationCoreApi - (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger { self = [super init]; if (self) { _binaryMessenger = binaryMessenger; } return self; } - (void)noopWithCompletion:(void (^)(FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noop"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:nil reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion([FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { completion(nil); } } else { completion(createConnectionError(channelName)); } }]; } - (void)throwErrorWithCompletion:(void (^)(id _Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.throwError"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:nil reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { id output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)throwErrorFromVoidWithCompletion:(void (^)(FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.throwErrorFromVoid"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:nil reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion([FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { completion(nil); } } else { completion(createConnectionError(channelName)); } }]; } - (void)echoAllTypes:(FLTAllTypes *)arg_everything completion:(void (^)(FLTAllTypes *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllTypes"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_everything ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { FLTAllTypes *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoAllNullableTypes:(nullable FLTAllNullableTypes *)arg_everything completion:(void (^)(FLTAllNullableTypes *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypes"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_everything ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { FLTAllNullableTypes *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)sendMultipleNullableTypesABool:(nullable NSNumber *)arg_aNullableBool anInt:(nullable NSNumber *)arg_aNullableInt aString:(nullable NSString *)arg_aNullableString completion:(void (^)(FLTAllNullableTypes *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." @"sendMultipleNullableTypes"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aNullableBool ?: [NSNull null], arg_aNullableInt ?: [NSNull null], arg_aNullableString ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { FLTAllNullableTypes *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoBool:(BOOL)arg_aBool completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoBool"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ @(arg_aBool) ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoInt:(NSInteger)arg_anInt completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoInt"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ @(arg_anInt) ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoDouble:(double)arg_aDouble completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoDouble"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ @(arg_aDouble) ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoString:(NSString *)arg_aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoString"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aString ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSString *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoUint8List:(FlutterStandardTypedData *)arg_aList completion: (void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoUint8List"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aList ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { FlutterStandardTypedData *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoList:(NSArray<id> *)arg_aList completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoList"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aList ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSArray<id> *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoMap:(NSDictionary<NSString *, id> *)arg_aMap completion: (void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoMap"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aMap ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSDictionary<NSString *, id> *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoEnum:(FLTAnEnum)arg_anEnum completion:(void (^)(FLTAnEnumBox *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnum"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ [NSNumber numberWithInteger:arg_anEnum] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *outputAsNumber = reply[0] == [NSNull null] ? nil : reply[0]; FLTAnEnumBox *output = outputAsNumber == nil ? nil : [[FLTAnEnumBox alloc] initWithValue:[outputAsNumber integerValue]]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableBool:(nullable NSNumber *)arg_aBool completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableBool"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aBool ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableInt:(nullable NSNumber *)arg_anInt completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableInt"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_anInt ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableDouble:(nullable NSNumber *)arg_aDouble completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableDouble"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aDouble ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableString:(nullable NSString *)arg_aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableString"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aString ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSString *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableUint8List:(nullable FlutterStandardTypedData *)arg_aList completion:(void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." @"echoNullableUint8List"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aList ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { FlutterStandardTypedData *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableList:(nullable NSArray<id> *)arg_aList completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableList"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aList ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSArray<id> *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableMap:(nullable NSDictionary<NSString *, id> *)arg_aMap completion:(void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableMap"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aMap ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSDictionary<NSString *, id> *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoNullableEnum:(nullable FLTAnEnumBox *)arg_anEnum completion:(void (^)(FLTAnEnumBox *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnum"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_anEnum == nil ? [NSNull null] : [NSNumber numberWithInteger:arg_anEnum.value] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSNumber *outputAsNumber = reply[0] == [NSNull null] ? nil : reply[0]; FLTAnEnumBox *output = outputAsNumber == nil ? nil : [[FLTAnEnumBox alloc] initWithValue:[outputAsNumber integerValue]]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)noopAsyncWithCompletion:(void (^)(FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noopAsync"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:nil reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion([FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { completion(nil); } } else { completion(createConnectionError(channelName)); } }]; } - (void)echoAsyncString:(NSString *)arg_aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterIntegrationCoreApiGetCodec()]; [channel sendMessage:@[ arg_aString ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSString *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } @end NSObject<FlutterMessageCodec> *FLTHostTrivialApiGetCodec(void) { static FlutterStandardMessageCodec *sSharedObject = nil; sSharedObject = [FlutterStandardMessageCodec sharedInstance]; return sSharedObject; } void SetUpFLTHostTrivialApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FLTHostTrivialApi> *api) { { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostTrivialApi.noop" binaryMessenger:binaryMessenger codec:FLTHostTrivialApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(noopWithError:)], @"FLTHostTrivialApi api (%@) doesn't respond to @selector(noopWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; [api noopWithError:&error]; callback(wrapResult(nil, error)); }]; } else { [channel setMessageHandler:nil]; } } } NSObject<FlutterMessageCodec> *FLTHostSmallApiGetCodec(void) { static FlutterStandardMessageCodec *sSharedObject = nil; sSharedObject = [FlutterStandardMessageCodec sharedInstance]; return sSharedObject; } void SetUpFLTHostSmallApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FLTHostSmallApi> *api) { { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo" binaryMessenger:binaryMessenger codec:FLTHostSmallApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(echoString:completion:)], @"FLTHostSmallApi api (%@) doesn't respond to @selector(echoString:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_aString = GetNullableObjectAtIndex(args, 0); [api echoString:arg_aString completion:^(NSString *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid" binaryMessenger:binaryMessenger codec:FLTHostSmallApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(voidVoidWithCompletion:)], @"FLTHostSmallApi api (%@) doesn't respond to @selector(voidVoidWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { [api voidVoidWithCompletion:^(FlutterError *_Nullable error) { callback(wrapResult(nil, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } } @interface FLTFlutterSmallApiCodecReader : FlutterStandardReader @end @implementation FLTFlutterSmallApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { case 128: return [FLTTestMessage fromList:[self readValue]]; default: return [super readValueOfType:type]; } } @end @interface FLTFlutterSmallApiCodecWriter : FlutterStandardWriter @end @implementation FLTFlutterSmallApiCodecWriter - (void)writeValue:(id)value { if ([value isKindOfClass:[FLTTestMessage class]]) { [self writeByte:128]; [self writeValue:[value toList]]; } else { [super writeValue:value]; } } @end @interface FLTFlutterSmallApiCodecReaderWriter : FlutterStandardReaderWriter @end @implementation FLTFlutterSmallApiCodecReaderWriter - (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { return [[FLTFlutterSmallApiCodecWriter alloc] initWithData:data]; } - (FlutterStandardReader *)readerWithData:(NSData *)data { return [[FLTFlutterSmallApiCodecReader alloc] initWithData:data]; } @end NSObject<FlutterMessageCodec> *FLTFlutterSmallApiGetCodec(void) { static FlutterStandardMessageCodec *sSharedObject = nil; static dispatch_once_t sPred = 0; dispatch_once(&sPred, ^{ FLTFlutterSmallApiCodecReaderWriter *readerWriter = [[FLTFlutterSmallApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } @interface FLTFlutterSmallApi () @property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger; @end @implementation FLTFlutterSmallApi - (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger { self = [super init]; if (self) { _binaryMessenger = binaryMessenger; } return self; } - (void)echoWrappedList:(FLTTestMessage *)arg_msg completion:(void (^)(FLTTestMessage *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoWrappedList"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterSmallApiGetCodec()]; [channel sendMessage:@[ arg_msg ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { FLTTestMessage *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } - (void)echoString:(NSString *)arg_aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoString"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:FLTFlutterSmallApiGetCodec()]; [channel sendMessage:@[ arg_aString ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSString *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } @end
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/ios/Classes/CoreTests.gen.m/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/ios/Classes/CoreTests.gen.m", "repo_id": "packages", "token_count": 67623 }
1,254
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'generated.dart'; const int _biggerThanBigInt = 3000000000; const int _regularInt = 42; const double _doublePi = 3.14159; /// Possible host languages that test can target. enum TargetGenerator { /// The Windows C++ generator. cpp, /// The Android Java generator. java, /// The Android Kotlin generator. kotlin, /// The iOS Objective-C generator. objc, /// The iOS or macOS Swift generator. swift, } /// Sets up and runs the integration tests. void runPigeonIntegrationTests(TargetGenerator targetGenerator) { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); void compareAllTypes(AllTypes? allTypesOne, AllTypes? allTypesTwo) { expect(allTypesOne == null, allTypesTwo == null); if (allTypesOne == null || allTypesTwo == null) { return; } expect(allTypesOne.aBool, allTypesTwo.aBool); expect(allTypesOne.anInt, allTypesTwo.anInt); expect(allTypesOne.anInt64, allTypesTwo.anInt64); expect(allTypesOne.aDouble, allTypesTwo.aDouble); expect(allTypesOne.aString, allTypesTwo.aString); expect(allTypesOne.aByteArray, allTypesTwo.aByteArray); expect(allTypesOne.a4ByteArray, allTypesTwo.a4ByteArray); expect(allTypesOne.a8ByteArray, allTypesTwo.a8ByteArray); expect(allTypesOne.aFloatArray, allTypesTwo.aFloatArray); expect(listEquals(allTypesOne.aList, allTypesTwo.aList), true); expect(mapEquals(allTypesOne.aMap, allTypesTwo.aMap), true); expect(allTypesOne.anEnum, allTypesTwo.anEnum); expect(allTypesOne.anObject, allTypesTwo.anObject); } void compareAllNullableTypes(AllNullableTypes? allNullableTypesOne, AllNullableTypes? allNullableTypesTwo) { expect(allNullableTypesOne == null, allNullableTypesTwo == null); if (allNullableTypesOne == null || allNullableTypesTwo == null) { return; } expect( allNullableTypesOne.aNullableBool, allNullableTypesTwo.aNullableBool); expect(allNullableTypesOne.aNullableInt, allNullableTypesTwo.aNullableInt); expect( allNullableTypesOne.aNullableInt64, allNullableTypesTwo.aNullableInt64); expect(allNullableTypesOne.aNullableDouble, allNullableTypesTwo.aNullableDouble); expect(allNullableTypesOne.aNullableString, allNullableTypesTwo.aNullableString); expect(allNullableTypesOne.aNullableByteArray, allNullableTypesTwo.aNullableByteArray); expect(allNullableTypesOne.aNullable4ByteArray, allNullableTypesTwo.aNullable4ByteArray); expect(allNullableTypesOne.aNullable8ByteArray, allNullableTypesTwo.aNullable8ByteArray); expect(allNullableTypesOne.aNullableFloatArray, allNullableTypesTwo.aNullableFloatArray); expect( listEquals(allNullableTypesOne.aNullableList, allNullableTypesTwo.aNullableList), true); expect( mapEquals( allNullableTypesOne.aNullableMap, allNullableTypesTwo.aNullableMap), true); expect(allNullableTypesOne.nullableNestedList?.length, allNullableTypesTwo.nullableNestedList?.length); // TODO(stuartmorgan): Enable this once the Dart types are fixed; see // https://github.com/flutter/flutter/issues/116117 //for (int i = 0; i < allNullableTypesOne.nullableNestedList!.length; i++) { // expect(listEquals(allNullableTypesOne.nullableNestedList![i], allNullableTypesTwo.nullableNestedList![i]), // true); //} expect( mapEquals(allNullableTypesOne.nullableMapWithAnnotations, allNullableTypesTwo.nullableMapWithAnnotations), true); expect( mapEquals(allNullableTypesOne.nullableMapWithObject, allNullableTypesTwo.nullableMapWithObject), true); expect(allNullableTypesOne.aNullableObject, allNullableTypesTwo.aNullableObject); expect( allNullableTypesOne.aNullableEnum, allNullableTypesTwo.aNullableEnum); } void compareAllClassesWrapper( AllClassesWrapper? wrapperOne, AllClassesWrapper? wrapperTwo) { expect(wrapperOne == null, wrapperTwo == null); if (wrapperOne == null || wrapperTwo == null) { return; } compareAllNullableTypes( wrapperOne.allNullableTypes, wrapperTwo.allNullableTypes); compareAllTypes(wrapperOne.allTypes, wrapperTwo.allTypes); } final AllTypes genericAllTypes = AllTypes( aBool: true, anInt: _regularInt, anInt64: _biggerThanBigInt, aDouble: _doublePi, aString: 'Hello host!', aByteArray: Uint8List.fromList(<int>[1, 2, 3]), a4ByteArray: Int32List.fromList(<int>[4, 5, 6]), a8ByteArray: Int64List.fromList(<int>[7, 8, 9]), aFloatArray: Float64List.fromList(<double>[2.71828, _doublePi]), aList: <Object?>['Thing 1', 2, true, 3.14, null], aMap: <Object?, Object?>{ 'a': 1, 'b': 2.0, 'c': 'three', 'd': false, 'e': null }, anEnum: AnEnum.fortyTwo, anObject: 1, ); final AllNullableTypes genericAllNullableTypes = AllNullableTypes( aNullableBool: true, aNullableInt: _regularInt, aNullableInt64: _biggerThanBigInt, aNullableDouble: _doublePi, aNullableString: 'Hello host!', aNullableByteArray: Uint8List.fromList(<int>[1, 2, 3]), aNullable4ByteArray: Int32List.fromList(<int>[4, 5, 6]), aNullable8ByteArray: Int64List.fromList(<int>[7, 8, 9]), aNullableFloatArray: Float64List.fromList(<double>[2.71828, _doublePi]), aNullableList: <Object?>['Thing 1', 2, true, 3.14, null], aNullableMap: <Object?, Object?>{ 'a': 1, 'b': 2.0, 'c': 'three', 'd': false, 'e': null }, nullableNestedList: <List<bool>>[ <bool>[true, false], <bool>[false, true] ], nullableMapWithAnnotations: <String?, String?>{}, nullableMapWithObject: <String?, Object?>{}, aNullableEnum: AnEnum.fourHundredTwentyTwo, aNullableObject: 0, ); group('Host sync API tests', () { testWidgets('basic void->void call works', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect(api.noop(), completes); }); testWidgets('all datatypes serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllTypes echoObject = await api.echoAllTypes(genericAllTypes); compareAllTypes(echoObject, genericAllTypes); }); testWidgets('all nullable datatypes serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllNullableTypes? echoObject = await api.echoAllNullableTypes(genericAllNullableTypes); compareAllNullableTypes(echoObject, genericAllNullableTypes); }); testWidgets('all null datatypes serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllNullableTypes allTypesNull = AllNullableTypes(); final AllNullableTypes? echoNullFilledClass = await api.echoAllNullableTypes(allTypesNull); compareAllNullableTypes(allTypesNull, echoNullFilledClass); }); testWidgets('Classes with list of null serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllNullableTypes nullableListTypes = AllNullableTypes(aNullableList: <String?>['String', null]); final AllNullableTypes? echoNullFilledClass = await api.echoAllNullableTypes(nullableListTypes); compareAllNullableTypes(nullableListTypes, echoNullFilledClass); }); testWidgets('Classes with map of null serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllNullableTypes nullableListTypes = AllNullableTypes( aNullableMap: <String?, String?>{'String': 'string', 'null': null}); final AllNullableTypes? echoNullFilledClass = await api.echoAllNullableTypes(nullableListTypes); compareAllNullableTypes(nullableListTypes, echoNullFilledClass); }); testWidgets('errors are returned correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect(() async { await api.throwError(); }, throwsA(isA<PlatformException>())); }); testWidgets('errors are returned from void methods correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect(() async { await api.throwErrorFromVoid(); }, throwsA(isA<PlatformException>())); }); testWidgets('flutter errors are returned correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect( () => api.throwFlutterError(), throwsA((dynamic e) => e is PlatformException && e.code == 'code' && e.message == 'message' && e.details == 'details')); }); testWidgets('nested objects can be sent correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllClassesWrapper sentObject = AllClassesWrapper( allNullableTypes: genericAllNullableTypes, allTypes: genericAllTypes); final String? receivedString = await api.extractNestedNullableString(sentObject); expect(receivedString, sentObject.allNullableTypes.aNullableString); }); testWidgets('nested objects can be received correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentString = 'Some string'; final AllClassesWrapper receivedObject = await api.createNestedNullableString(sentString); expect(receivedObject.allNullableTypes.aNullableString, sentString); }); testWidgets('nested classes can serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllClassesWrapper sentWrapper = AllClassesWrapper( allNullableTypes: AllNullableTypes(), allTypes: genericAllTypes); final AllClassesWrapper receivedClassWrapper = await api.echoClassWrapper(sentWrapper); compareAllClassesWrapper(sentWrapper, receivedClassWrapper); }); testWidgets('nested null classes can serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllClassesWrapper sentWrapper = AllClassesWrapper(allNullableTypes: AllNullableTypes()); final AllClassesWrapper receivedClassWrapper = await api.echoClassWrapper(sentWrapper); compareAllClassesWrapper(sentWrapper, receivedClassWrapper); }); testWidgets( 'Arguments of multiple types serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String aNullableString = 'this is a String'; const bool aNullableBool = false; const int aNullableInt = _regularInt; final AllNullableTypes echoObject = await api.sendMultipleNullableTypes( aNullableBool, aNullableInt, aNullableString); expect(echoObject.aNullableInt, aNullableInt); expect(echoObject.aNullableBool, aNullableBool); expect(echoObject.aNullableString, aNullableString); }); testWidgets( 'Arguments of multiple null types serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllNullableTypes echoNullFilledClass = await api.sendMultipleNullableTypes(null, null, null); expect(echoNullFilledClass.aNullableInt, null); expect(echoNullFilledClass.aNullableBool, null); expect(echoNullFilledClass.aNullableString, null); }); testWidgets('Int serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = _regularInt; final int receivedInt = await api.echoInt(sentInt); expect(receivedInt, sentInt); }); testWidgets('Int64 serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = _biggerThanBigInt; final int receivedInt = await api.echoInt(sentInt); expect(receivedInt, sentInt); }); testWidgets('Doubles serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const double sentDouble = 2.0694; final double receivedDouble = await api.echoDouble(sentDouble); expect(receivedDouble, sentDouble); }); testWidgets('booleans serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); for (final bool sentBool in <bool>[true, false]) { final bool receivedBool = await api.echoBool(sentBool); expect(receivedBool, sentBool); } }); testWidgets('strings serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentString = 'default'; final String receivedString = await api.echoString(sentString); expect(receivedString, sentString); }); testWidgets('Uint8List serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List<int> data = <int>[ 102, 111, 114, 116, 121, 45, 116, 119, 111, 0 ]; final Uint8List sentUint8List = Uint8List.fromList(data); final Uint8List receivedUint8List = await api.echoUint8List(sentUint8List); expect(receivedUint8List, sentUint8List); }); testWidgets('generic Objects serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const Object sentString = "I'm a computer"; final Object receivedString = await api.echoObject(sentString); expect(receivedString, sentString); // Echo a second type as well to ensure the handling is generic. const Object sentInt = _regularInt; final Object receivedInt = await api.echoObject(sentInt); expect(receivedInt, sentInt); }); testWidgets('lists serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const List<Object?> sentObject = <Object>[7, 'Hello Dart!']; final List<Object?> echoObject = await api.echoList(sentObject); expect(listEquals(echoObject, sentObject), true); }); testWidgets('maps serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const Map<String?, Object?> sentObject = <String?, Object?>{ 'a': 1, 'b': 2.3, 'c': 'four', }; final Map<String?, Object?> echoObject = await api.echoMap(sentObject); expect(mapEquals(echoObject, sentObject), true); }); testWidgets('enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.two; final AnEnum receivedEnum = await api.echoEnum(sentEnum); expect(receivedEnum, sentEnum); }); testWidgets('multi word enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fortyTwo; final AnEnum receivedEnum = await api.echoEnum(sentEnum); expect(receivedEnum, sentEnum); }); testWidgets('required named parameter', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); // This number corresponds with the default value of this method. const int sentInt = _regularInt; final int receivedInt = await api.echoRequiredInt(anInt: sentInt); expect(receivedInt, sentInt); }); testWidgets('optional default parameter no arg', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); // This number corresponds with the default value of this method. const double sentDouble = 3.14; final double receivedDouble = await api.echoOptionalDefaultDouble(); expect(receivedDouble, sentDouble); }); testWidgets('optional default parameter with arg', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const double sentDouble = 3.15; final double receivedDouble = await api.echoOptionalDefaultDouble(sentDouble); expect(receivedDouble, sentDouble); }); testWidgets('named default parameter no arg', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); // This string corresponds with the default value of this method. const String sentString = 'default'; final String receivedString = await api.echoNamedDefaultString(); expect(receivedString, sentString); }); testWidgets('named default parameter with arg', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); // This string corresponds with the default value of this method. const String sentString = 'notDefault'; final String receivedString = await api.echoNamedDefaultString(aString: sentString); expect(receivedString, sentString); }); testWidgets('Nullable Int serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = _regularInt; final int? receivedInt = await api.echoNullableInt(sentInt); expect(receivedInt, sentInt); }); testWidgets('Nullable Int64 serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = _biggerThanBigInt; final int? receivedInt = await api.echoNullableInt(sentInt); expect(receivedInt, sentInt); }); testWidgets('Null Ints serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final int? receivedNullInt = await api.echoNullableInt(null); expect(receivedNullInt, null); }); testWidgets('Nullable Doubles serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const double sentDouble = 2.0694; final double? receivedDouble = await api.echoNullableDouble(sentDouble); expect(receivedDouble, sentDouble); }); testWidgets('Null Doubles serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final double? receivedNullDouble = await api.echoNullableDouble(null); expect(receivedNullDouble, null); }); testWidgets('Nullable booleans serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); for (final bool? sentBool in <bool?>[true, false]) { final bool? receivedBool = await api.echoNullableBool(sentBool); expect(receivedBool, sentBool); } }); testWidgets('Null booleans serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const bool? sentBool = null; final bool? receivedBool = await api.echoNullableBool(sentBool); expect(receivedBool, sentBool); }); testWidgets('Nullable strings serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentString = "I'm a computer"; final String? receivedString = await api.echoNullableString(sentString); expect(receivedString, sentString); }); testWidgets('Null strings serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final String? receivedNullString = await api.echoNullableString(null); expect(receivedNullString, null); }); testWidgets('Nullable Uint8List serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List<int> data = <int>[ 102, 111, 114, 116, 121, 45, 116, 119, 111, 0 ]; final Uint8List sentUint8List = Uint8List.fromList(data); final Uint8List? receivedUint8List = await api.echoNullableUint8List(sentUint8List); expect(receivedUint8List, sentUint8List); }); testWidgets('Null Uint8List serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Uint8List? receivedNullUint8List = await api.echoNullableUint8List(null); expect(receivedNullUint8List, null); }); testWidgets('generic nullable Objects serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const Object sentString = "I'm a computer"; final Object? receivedString = await api.echoNullableObject(sentString); expect(receivedString, sentString); // Echo a second type as well to ensure the handling is generic. const Object sentInt = _regularInt; final Object? receivedInt = await api.echoNullableObject(sentInt); expect(receivedInt, sentInt); }); testWidgets('Null generic Objects serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Object? receivedNullObject = await api.echoNullableObject(null); expect(receivedNullObject, null); }); testWidgets('nullable lists serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const List<Object?> sentObject = <Object?>[7, 'Hello Dart!', null]; final List<Object?>? echoObject = await api.echoNullableList(sentObject); expect(listEquals(echoObject, sentObject), true); }); testWidgets('nullable maps serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const Map<String?, Object?> sentObject = <String?, Object?>{ 'a': 1, 'b': 2.3, 'c': 'four', 'd': null, }; final Map<String?, Object?>? echoObject = await api.echoNullableMap(sentObject); expect(mapEquals(echoObject, sentObject), true); }); testWidgets('nullable enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; final AnEnum? echoEnum = await api.echoNullableEnum(sentEnum); expect(echoEnum, sentEnum); }); testWidgets('multi word nullable enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; final AnEnum? echoEnum = await api.echoNullableEnum(sentEnum); expect(echoEnum, sentEnum); }); testWidgets('null lists serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List<Object?>? echoObject = await api.echoNullableList(null); expect(listEquals(echoObject, null), true); }); testWidgets('null maps serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Map<String?, Object?>? echoObject = await api.echoNullableMap(null); expect(mapEquals(echoObject, null), true); }); testWidgets('null enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum? sentEnum = null; final AnEnum? echoEnum = await api.echoNullableEnum(sentEnum); expect(echoEnum, sentEnum); }); testWidgets('optional nullable parameter', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = _regularInt; final int? receivedInt = await api.echoOptionalNullableInt(sentInt); expect(receivedInt, sentInt); }); testWidgets('Null optional nullable parameter', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final int? receivedNullInt = await api.echoOptionalNullableInt(); expect(receivedNullInt, null); }); testWidgets('named nullable parameter', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentString = "I'm a computer"; final String? receivedString = await api.echoNamedNullableString(aNullableString: sentString); expect(receivedString, sentString); }); testWidgets('Null named nullable parameter', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final String? receivedNullString = await api.echoNamedNullableString(); expect(receivedNullString, null); }); }); group('Host async API tests', () { testWidgets('basic void->void call works', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect(api.noopAsync(), completes); }); testWidgets('async errors are returned from non void methods correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect(() async { await api.throwAsyncError(); }, throwsA(isA<PlatformException>())); }); testWidgets('async errors are returned from void methods correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect(() async { await api.throwAsyncErrorFromVoid(); }, throwsA(isA<PlatformException>())); }); testWidgets( 'async flutter errors are returned from non void methods correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect( () => api.throwAsyncFlutterError(), throwsA((dynamic e) => e is PlatformException && e.code == 'code' && e.message == 'message' && e.details == 'details')); }); testWidgets('all datatypes async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllTypes echoObject = await api.echoAsyncAllTypes(genericAllTypes); compareAllTypes(echoObject, genericAllTypes); }); testWidgets( 'all nullable async datatypes serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllNullableTypes? echoObject = await api.echoAsyncNullableAllNullableTypes(genericAllNullableTypes); compareAllNullableTypes(echoObject, genericAllNullableTypes); }); testWidgets('all null datatypes async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllNullableTypes allTypesNull = AllNullableTypes(); final AllNullableTypes? echoNullFilledClass = await api.echoAsyncNullableAllNullableTypes(allTypesNull); compareAllNullableTypes(echoNullFilledClass, allTypesNull); }); testWidgets('Int async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = _regularInt; final int receivedInt = await api.echoAsyncInt(sentInt); expect(receivedInt, sentInt); }); testWidgets('Int64 async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = _biggerThanBigInt; final int receivedInt = await api.echoAsyncInt(sentInt); expect(receivedInt, sentInt); }); testWidgets('Doubles async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const double sentDouble = 2.0694; final double receivedDouble = await api.echoAsyncDouble(sentDouble); expect(receivedDouble, sentDouble); }); testWidgets('booleans async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); for (final bool sentBool in <bool>[true, false]) { final bool receivedBool = await api.echoAsyncBool(sentBool); expect(receivedBool, sentBool); } }); testWidgets('strings async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentObject = 'Hello, asynchronously!'; final String echoObject = await api.echoAsyncString(sentObject); expect(echoObject, sentObject); }); testWidgets('Uint8List async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List<int> data = <int>[ 102, 111, 114, 116, 121, 45, 116, 119, 111, 0 ]; final Uint8List sentUint8List = Uint8List.fromList(data); final Uint8List receivedUint8List = await api.echoAsyncUint8List(sentUint8List); expect(receivedUint8List, sentUint8List); }); testWidgets('generic Objects async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const Object sentString = "I'm a computer"; final Object receivedString = await api.echoAsyncObject(sentString); expect(receivedString, sentString); // Echo a second type as well to ensure the handling is generic. const Object sentInt = _regularInt; final Object receivedInt = await api.echoAsyncObject(sentInt); expect(receivedInt, sentInt); }); testWidgets('lists serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const List<Object?> sentObject = <Object>[7, 'Hello Dart!']; final List<Object?> echoObject = await api.echoAsyncList(sentObject); expect(listEquals(echoObject, sentObject), true); }); testWidgets('maps serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const Map<String?, Object?> sentObject = <String?, Object?>{ 'a': 1, 'b': 2.3, 'c': 'four', }; final Map<String?, Object?> echoObject = await api.echoAsyncMap(sentObject); expect(mapEquals(echoObject, sentObject), true); }); testWidgets('enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; final AnEnum echoEnum = await api.echoAsyncEnum(sentEnum); expect(echoEnum, sentEnum); }); testWidgets('multi word enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; final AnEnum echoEnum = await api.echoAsyncEnum(sentEnum); expect(echoEnum, sentEnum); }); testWidgets('nullable Int async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = _regularInt; final int? receivedInt = await api.echoAsyncNullableInt(sentInt); expect(receivedInt, sentInt); }); testWidgets('nullable Int64 async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentInt = _biggerThanBigInt; final int? receivedInt = await api.echoAsyncNullableInt(sentInt); expect(receivedInt, sentInt); }); testWidgets('nullable Doubles async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const double sentDouble = 2.0694; final double? receivedDouble = await api.echoAsyncNullableDouble(sentDouble); expect(receivedDouble, sentDouble); }); testWidgets('nullable booleans async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); for (final bool sentBool in <bool>[true, false]) { final bool? receivedBool = await api.echoAsyncNullableBool(sentBool); expect(receivedBool, sentBool); } }); testWidgets('nullable strings async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentObject = 'Hello, asynchronously!'; final String? echoObject = await api.echoAsyncNullableString(sentObject); expect(echoObject, sentObject); }); testWidgets('nullable Uint8List async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List<int> data = <int>[ 102, 111, 114, 116, 121, 45, 116, 119, 111, 0 ]; final Uint8List sentUint8List = Uint8List.fromList(data); final Uint8List? receivedUint8List = await api.echoAsyncNullableUint8List(sentUint8List); expect(receivedUint8List, sentUint8List); }); testWidgets( 'nullable generic Objects async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const Object sentString = "I'm a computer"; final Object? receivedString = await api.echoAsyncNullableObject(sentString); expect(receivedString, sentString); // Echo a second type as well to ensure the handling is generic. const Object sentInt = _regularInt; final Object? receivedInt = await api.echoAsyncNullableObject(sentInt); expect(receivedInt, sentInt); }); testWidgets('nullable lists serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const List<Object?> sentObject = <Object>[7, 'Hello Dart!']; final List<Object?>? echoObject = await api.echoAsyncNullableList(sentObject); expect(listEquals(echoObject, sentObject), true); }); testWidgets('nullable maps serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const Map<String?, Object?> sentObject = <String?, Object?>{ 'a': 1, 'b': 2.3, 'c': 'four', }; final Map<String?, Object?>? echoObject = await api.echoAsyncNullableMap(sentObject); expect(mapEquals(echoObject, sentObject), true); }); testWidgets('nullable enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; final AnEnum? echoEnum = await api.echoAsyncNullableEnum(sentEnum); expect(echoEnum, sentEnum); }); testWidgets('nullable enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fortyTwo; final AnEnum? echoEnum = await api.echoAsyncNullableEnum(sentEnum); expect(echoEnum, sentEnum); }); testWidgets('null Ints async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final int? receivedInt = await api.echoAsyncNullableInt(null); expect(receivedInt, null); }); testWidgets('null Doubles async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final double? receivedDouble = await api.echoAsyncNullableDouble(null); expect(receivedDouble, null); }); testWidgets('null booleans async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final bool? receivedBool = await api.echoAsyncNullableBool(null); expect(receivedBool, null); }); testWidgets('null strings async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final String? echoObject = await api.echoAsyncNullableString(null); expect(echoObject, null); }); testWidgets('null Uint8List async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Uint8List? receivedUint8List = await api.echoAsyncNullableUint8List(null); expect(receivedUint8List, null); }); testWidgets( 'null generic Objects async serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Object? receivedString = await api.echoAsyncNullableObject(null); expect(receivedString, null); }); testWidgets('null lists serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List<Object?>? echoObject = await api.echoAsyncNullableList(null); expect(listEquals(echoObject, null), true); }); testWidgets('null maps serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Map<String?, Object?>? echoObject = await api.echoAsyncNullableMap(null); expect(mapEquals(echoObject, null), true); }); testWidgets('null enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum? sentEnum = null; final AnEnum? echoEnum = await api.echoAsyncNullableEnum(null); expect(echoEnum, sentEnum); }); }); // These tests rely on the async Dart->host calls to work correctly, since // the host->Dart call is wrapped in a driving Dart->host call, so any test // added to this group should have coverage of the relevant arguments and // return value in the "Host async API tests" group. group('Flutter API tests', () { setUp(() { FlutterIntegrationCoreApi.setup(_FlutterApiTestImplementation()); }); testWidgets('basic void->void call works', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect(api.callFlutterNoop(), completes); }); testWidgets('errors are returned from non void methods correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect(() async { await api.callFlutterThrowError(); }, throwsA(isA<PlatformException>())); }); testWidgets('errors are returned from void methods correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); expect(() async { await api.callFlutterThrowErrorFromVoid(); }, throwsA(isA<PlatformException>())); }); testWidgets('all datatypes serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllTypes echoObject = await api.callFlutterEchoAllTypes(genericAllTypes); compareAllTypes(echoObject, genericAllTypes); }); testWidgets( 'Arguments of multiple types serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String aNullableString = 'this is a String'; const bool aNullableBool = false; const int aNullableInt = _regularInt; final AllNullableTypes compositeObject = await api.callFlutterSendMultipleNullableTypes( aNullableBool, aNullableInt, aNullableString); expect(compositeObject.aNullableInt, aNullableInt); expect(compositeObject.aNullableBool, aNullableBool); expect(compositeObject.aNullableString, aNullableString); }); testWidgets( 'Arguments of multiple null types serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final AllNullableTypes compositeObject = await api.callFlutterSendMultipleNullableTypes(null, null, null); expect(compositeObject.aNullableInt, null); expect(compositeObject.aNullableBool, null); expect(compositeObject.aNullableString, null); }); testWidgets('booleans serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); for (final bool sentObject in <bool>[true, false]) { final bool echoObject = await api.callFlutterEchoBool(sentObject); expect(echoObject, sentObject); } }); testWidgets('ints serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentObject = _regularInt; final int echoObject = await api.callFlutterEchoInt(sentObject); expect(echoObject, sentObject); }); testWidgets('doubles serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const double sentObject = 2.0694; final double echoObject = await api.callFlutterEchoDouble(sentObject); expect(echoObject, sentObject); }); testWidgets('strings serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentObject = 'Hello Dart!'; final String echoObject = await api.callFlutterEchoString(sentObject); expect(echoObject, sentObject); }); testWidgets('Uint8Lists serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List<int> data = <int>[ 102, 111, 114, 116, 121, 45, 116, 119, 111, 0 ]; final Uint8List sentObject = Uint8List.fromList(data); final Uint8List echoObject = await api.callFlutterEchoUint8List(sentObject); expect(echoObject, sentObject); }); testWidgets('lists serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const List<Object?> sentObject = <Object>[7, 'Hello Dart!']; final List<Object?> echoObject = await api.callFlutterEchoList(sentObject); expect(listEquals(echoObject, sentObject), true); }); testWidgets('maps serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const Map<String?, Object?> sentObject = <String?, Object?>{ 'a': 1, 'b': 2.3, 'c': 'four', }; final Map<String?, Object?> echoObject = await api.callFlutterEchoMap(sentObject); expect(mapEquals(echoObject, sentObject), true); }); testWidgets('enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; final AnEnum echoEnum = await api.callFlutterEchoEnum(sentEnum); expect(echoEnum, sentEnum); }); testWidgets('multi word enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fortyTwo; final AnEnum echoEnum = await api.callFlutterEchoEnum(sentEnum); expect(echoEnum, sentEnum); }); testWidgets('nullable booleans serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); for (final bool? sentObject in <bool?>[true, false]) { final bool? echoObject = await api.callFlutterEchoNullableBool(sentObject); expect(echoObject, sentObject); } }); testWidgets('null booleans serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const bool? sentObject = null; final bool? echoObject = await api.callFlutterEchoNullableBool(sentObject); expect(echoObject, sentObject); }); testWidgets('nullable ints serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentObject = _regularInt; final int? echoObject = await api.callFlutterEchoNullableInt(sentObject); expect(echoObject, sentObject); }); testWidgets('nullable big ints serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const int sentObject = _biggerThanBigInt; final int? echoObject = await api.callFlutterEchoNullableInt(sentObject); expect(echoObject, sentObject); }); testWidgets('null ints serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final int? echoObject = await api.callFlutterEchoNullableInt(null); expect(echoObject, null); }); testWidgets('nullable doubles serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const double sentObject = 2.0694; final double? echoObject = await api.callFlutterEchoNullableDouble(sentObject); expect(echoObject, sentObject); }); testWidgets('null doubles serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final double? echoObject = await api.callFlutterEchoNullableDouble(null); expect(echoObject, null); }); testWidgets('nullable strings serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const String sentObject = "I'm a computer"; final String? echoObject = await api.callFlutterEchoNullableString(sentObject); expect(echoObject, sentObject); }); testWidgets('null strings serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final String? echoObject = await api.callFlutterEchoNullableString(null); expect(echoObject, null); }); testWidgets('nullable Uint8Lists serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List<int> data = <int>[ 102, 111, 114, 116, 121, 45, 116, 119, 111, 0 ]; final Uint8List sentObject = Uint8List.fromList(data); final Uint8List? echoObject = await api.callFlutterEchoNullableUint8List(sentObject); expect(echoObject, sentObject); }); testWidgets('null Uint8Lists serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Uint8List? echoObject = await api.callFlutterEchoNullableUint8List(null); expect(echoObject, null); }); testWidgets('nullable lists serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const List<Object?> sentObject = <Object>[7, 'Hello Dart!']; final List<Object?>? echoObject = await api.callFlutterEchoNullableList(sentObject); expect(listEquals(echoObject, sentObject), true); }); testWidgets('null lists serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final List<Object?>? echoObject = await api.callFlutterEchoNullableList(null); expect(listEquals(echoObject, null), true); }); testWidgets('nullable maps serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const Map<String?, Object?> sentObject = <String?, Object?>{ 'a': 1, 'b': 2.3, 'c': 'four', }; final Map<String?, Object?>? echoObject = await api.callFlutterEchoNullableMap(sentObject); expect(mapEquals(echoObject, sentObject), true); }); testWidgets('null maps serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); final Map<String?, Object?>? echoObject = await api.callFlutterEchoNullableMap(null); expect(mapEquals(echoObject, null), true); }); testWidgets('nullable enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; final AnEnum? echoEnum = await api.callFlutterEchoNullableEnum(sentEnum); expect(echoEnum, sentEnum); }); testWidgets('multi word nullable enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; final AnEnum? echoEnum = await api.callFlutterEchoNullableEnum(sentEnum); expect(echoEnum, sentEnum); }); testWidgets('null enums serialize and deserialize correctly', (WidgetTester _) async { final HostIntegrationCoreApi api = HostIntegrationCoreApi(); const AnEnum? sentEnum = null; final AnEnum? echoEnum = await api.callFlutterEchoNullableEnum(sentEnum); expect(echoEnum, sentEnum); }); }); } class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { @override AllTypes echoAllTypes(AllTypes everything) { return everything; } @override AllNullableTypes? echoAllNullableTypes(AllNullableTypes? everything) { return everything; } @override void noop() {} @override Object? throwError() { throw FlutterError('this is an error'); } @override void throwErrorFromVoid() { throw FlutterError('this is an error'); } @override AllNullableTypes sendMultipleNullableTypes( bool? aNullableBool, int? aNullableInt, String? aNullableString) { return AllNullableTypes( aNullableBool: aNullableBool, aNullableInt: aNullableInt, aNullableString: aNullableString); } @override bool echoBool(bool aBool) => aBool; @override double echoDouble(double aDouble) => aDouble; @override int echoInt(int anInt) => anInt; @override String echoString(String aString) => aString; @override Uint8List echoUint8List(Uint8List aList) => aList; @override List<Object?> echoList(List<Object?> aList) => aList; @override Map<String?, Object?> echoMap(Map<String?, Object?> aMap) => aMap; @override AnEnum echoEnum(AnEnum anEnum) => anEnum; @override bool? echoNullableBool(bool? aBool) => aBool; @override double? echoNullableDouble(double? aDouble) => aDouble; @override int? echoNullableInt(int? anInt) => anInt; @override List<Object?>? echoNullableList(List<Object?>? aList) => aList; @override Map<String?, Object?>? echoNullableMap(Map<String?, Object?>? aMap) => aMap; @override String? echoNullableString(String? aString) => aString; @override Uint8List? echoNullableUint8List(Uint8List? aList) => aList; @override AnEnum? echoNullableEnum(AnEnum? anEnum) => anEnum; @override Future<void> noopAsync() async {} @override Future<String> echoAsyncString(String aString) async { return aString; } }
packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/integration_tests.dart/0
{ "file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/integration_tests.dart", "repo_id": "packages", "token_count": 20750 }
1,255
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:shared_test_plugin_code/src/generated/multiple_arity.gen.dart'; import 'multiple_arity_test.mocks.dart'; @GenerateMocks(<Type>[BinaryMessenger]) void main() { test('multiple arity', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); when(mockMessenger.send( 'dev.flutter.pigeon.pigeon_integration_tests.MultipleArityHostApi.subtract', any)) .thenAnswer((Invocation realInvocation) async { final Object input = MultipleArityHostApi.pigeonChannelCodec .decodeMessage(realInvocation.positionalArguments[1] as ByteData?)!; final List<Object?> args = input as List<Object?>; final int x = (args[0] as int?)!; final int y = (args[1] as int?)!; return MultipleArityHostApi.pigeonChannelCodec .encodeMessage(<Object>[x - y]); }); final MultipleArityHostApi api = MultipleArityHostApi(binaryMessenger: mockMessenger); final int result = await api.subtract(30, 10); expect(result, 20); }); }
packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.dart/0
{ "file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.dart", "repo_id": "packages", "token_count": 519 }
1,256
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.test_plugin"> </manifest>
packages/packages/pigeon/platform_tests/test_plugin/android/src/main/AndroidManifest.xml/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/android/src/main/AndroidManifest.xml", "repo_id": "packages", "token_count": 43 }
1,257
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Flutter import XCTest @testable import test_plugin class MockMultipleArityHostApi: MultipleArityHostApi { func subtract(x: Int64, y: Int64) -> Int64 { return x - y } } class MultipleArityTests: XCTestCase { var codec = FlutterStandardMessageCodec.sharedInstance() func testSimpleHost() throws { let binaryMessenger = MockBinaryMessenger<Int64>(codec: EnumApi2HostCodec.shared) MultipleArityHostApiSetup.setUp( binaryMessenger: binaryMessenger, api: MockMultipleArityHostApi()) let channelName = "dev.flutter.pigeon.pigeon_integration_tests.MultipleArityHostApi.subtract" XCTAssertNotNil(binaryMessenger.handlers[channelName]) let inputX = 10 let inputY = 7 let inputEncoded = binaryMessenger.codec.encode([inputX, inputY]) let expectation = XCTestExpectation(description: "subtraction") binaryMessenger.handlers[channelName]?(inputEncoded) { data in let outputList = binaryMessenger.codec.decode(data) as? [Any] XCTAssertNotNil(outputList) let output = outputList![0] as? Int64 XCTAssertEqual(3, output) XCTAssertTrue(outputList?.count == 1) expectation.fulfill() } wait(for: [expectation], timeout: 1.0) } func testSimpleFlutter() throws { let binaryMessenger = HandlerBinaryMessenger(codec: codec) { args in return (args[0] as! Int) - (args[1] as! Int) } let api = MultipleArityFlutterApi(binaryMessenger: binaryMessenger) let expectation = XCTestExpectation(description: "subtraction") api.subtract(x: 30, y: 10) { result in switch result { case .success(let res): XCTAssertEqual(20, res) expectation.fulfill() case .failure(_): return } } wait(for: [expectation], timeout: 1.0) } }
packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/MultipleArityTests.swift/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/MultipleArityTests.swift", "repo_id": "packages", "token_count": 744 }
1,258
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. # Run `pod lib lint test_plugin.podspec` to validate before publishing. # Pod::Spec.new do |s| s.name = 'test_plugin' s.version = '0.0.1' s.summary = 'Pigeon test plugin' s.description = <<-DESC A plugin to test Pigeon generation for primary languages. DESC s.homepage = 'http://example.com' s.license = { :type => 'BSD', :file => '../../../LICENSE' } s.author = { 'Your Company' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/pigeon' } s.source_files = 'Classes/**/*' s.dependency 'FlutterMacOS' s.platform = :osx, '10.14' s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } s.swift_version = '5.0' end
packages/packages/pigeon/platform_tests/test_plugin/macos/test_plugin.podspec/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/macos/test_plugin.podspec", "repo_id": "packages", "token_count": 402 }
1,259
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "fake_host_messenger.h" #include <flutter/encodable_value.h> #include <flutter/message_codec.h> #include <memory> #include <vector> namespace testing { FakeHostMessenger::FakeHostMessenger( const flutter::MessageCodec<flutter::EncodableValue>* codec) : codec_(codec) {} FakeHostMessenger::~FakeHostMessenger() {} void FakeHostMessenger::SendHostMessage(const std::string& channel, const flutter::EncodableValue& message, HostMessageReply reply_handler) { const auto* codec = codec_; flutter::BinaryReply binary_handler = [reply_handler, codec, channel]( const uint8_t* reply_data, size_t reply_size) { std::unique_ptr<flutter::EncodableValue> reply = codec->DecodeMessage(reply_data, reply_size); reply_handler(*reply); }; std::unique_ptr<std::vector<uint8_t>> data = codec_->EncodeMessage(message); handlers_[channel](data->data(), data->size(), std::move(binary_handler)); } void FakeHostMessenger::Send(const std::string& channel, const uint8_t* message, size_t message_size, flutter::BinaryReply reply) const {} void FakeHostMessenger::SetMessageHandler( const std::string& channel, flutter::BinaryMessageHandler handler) { handlers_[channel] = std::move(handler); } } // namespace testing
packages/packages/pigeon/platform_tests/test_plugin/windows/test/utils/fake_host_messenger.cpp/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/windows/test/utils/fake_host_messenger.cpp", "repo_id": "packages", "token_count": 682 }
1,260
// 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'; import 'package:test/test.dart'; void main() { test('Should be able to import JavaOptions', () async { const JavaOptions javaOptions = JavaOptions(); expect(javaOptions, isNotNull); }); test('Should be able to import ObjcOptions', () async { const ObjcOptions objcOptions = ObjcOptions(); expect(objcOptions, isNotNull); }); test('Should be able to import SwiftOptions', () async { const SwiftOptions swiftOptions = SwiftOptions(); expect(swiftOptions, isNotNull); }); test('Should be able to import KotlinOptions', () async { const KotlinOptions kotlinOptions = KotlinOptions(); expect(kotlinOptions, isNotNull); }); }
packages/packages/pigeon/test/pigeon_test.dart/0
{ "file_path": "packages/packages/pigeon/test/pigeon_test.dart", "repo_id": "packages", "token_count": 267 }
1,261
[![Pub](https://img.shields.io/pub/v/platform.svg)](https://pub.dartlang.org/packages/platform) A generic platform abstraction for Dart. Like `dart:io`, `package:platform` supplies a rich, Dart-idiomatic API for accessing platform-specific information. `package:platform` provides a lightweight wrapper around the static `Platform` properties that exist in `dart:io`. However, it uses instance properties rather than static properties, making it possible to mock out in tests.
packages/packages/platform/README.md/0
{ "file_path": "packages/packages/platform/README.md", "repo_id": "packages", "token_count": 129 }
1,262
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:plaform_example/main.dart'; void main() { testWidgets('smoke test', (WidgetTester tester) async { await tester.pumpWidget(const MyApp()); expect(find.text('Platform Example'), findsOneWidget); expect(find.text('Operating System:'), findsOneWidget); expect(find.text('Number of Processors:'), findsOneWidget); expect(find.text('Path Separator:'), findsOneWidget); }); }
packages/packages/platform/example/test/widget_test.dart/0
{ "file_path": "packages/packages/platform/example/test/widget_test.dart", "repo_id": "packages", "token_count": 200 }
1,263
// 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. // Unreachable code is used in docregion. // ignore_for_file: unreachable_from_main import 'package:mockito/mockito.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'package:test/test.dart'; // #docregion Example abstract class SamplePluginPlatform extends PlatformInterface { SamplePluginPlatform() : super(token: _token); static final Object _token = Object(); // A plugin can have a default implementation, as shown here, or `instance` // can be nullable, and the default instance can be null. static SamplePluginPlatform _instance = SamplePluginDefault(); static SamplePluginPlatform get instance => _instance; /// Platform-specific implementations should set this to their own /// platform-specific class that extends [SamplePluginPlatform] when they /// register themselves. static set instance(SamplePluginPlatform instance) { PlatformInterface.verify(instance, _token); _instance = instance; } // Methods for the plugin's platform interface would go here, often with // implementations that throw UnimplementedError. } class SamplePluginDefault extends SamplePluginPlatform { // A default real implementation of the platform interface would go here. } // #enddocregion Example class ImplementsSamplePluginPlatform extends Mock implements SamplePluginPlatform {} class ImplementsSamplePluginPlatformUsingNoSuchMethod implements SamplePluginPlatform { @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } // #docregion Mock class SamplePluginPlatformMock extends Mock with MockPlatformInterfaceMixin implements SamplePluginPlatform {} // #enddocregion Mock class SamplePluginPlatformFake extends Fake with MockPlatformInterfaceMixin implements SamplePluginPlatform {} class ExtendsSamplePluginPlatform extends SamplePluginPlatform {} class ConstTokenPluginPlatform extends PlatformInterface { ConstTokenPluginPlatform() : super(token: _token); static const Object _token = Object(); // invalid // ignore: avoid_setters_without_getters static set instance(ConstTokenPluginPlatform instance) { PlatformInterface.verify(instance, _token); } } class ExtendsConstTokenPluginPlatform extends ConstTokenPluginPlatform {} class VerifyTokenPluginPlatform extends PlatformInterface { VerifyTokenPluginPlatform() : super(token: _token); static final Object _token = Object(); // ignore: avoid_setters_without_getters static set instance(VerifyTokenPluginPlatform instance) { PlatformInterface.verifyToken(instance, _token); // A real implementation would set a static instance field here. } } class ImplementsVerifyTokenPluginPlatform extends Mock implements VerifyTokenPluginPlatform {} class ImplementsVerifyTokenPluginPlatformUsingMockPlatformInterfaceMixin extends Mock with MockPlatformInterfaceMixin implements VerifyTokenPluginPlatform {} class ExtendsVerifyTokenPluginPlatform extends VerifyTokenPluginPlatform {} class ConstVerifyTokenPluginPlatform extends PlatformInterface { ConstVerifyTokenPluginPlatform() : super(token: _token); static const Object _token = Object(); // invalid // ignore: avoid_setters_without_getters static set instance(ConstVerifyTokenPluginPlatform instance) { PlatformInterface.verifyToken(instance, _token); } } class ImplementsConstVerifyTokenPluginPlatform extends PlatformInterface implements ConstVerifyTokenPluginPlatform { ImplementsConstVerifyTokenPluginPlatform() : super(token: const Object()); } // Ensures that `PlatformInterface` has no instance methods. Adding an // instance method is discouraged and may be a breaking change if it // conflicts with instance methods in subclasses. class StaticMethodsOnlyPlatformInterfaceTest implements PlatformInterface {} class StaticMethodsOnlyMockPlatformInterfaceMixinTest implements MockPlatformInterfaceMixin {} void main() { group('`verify`', () { test('prevents implementation with `implements`', () { expect(() { SamplePluginPlatform.instance = ImplementsSamplePluginPlatform(); }, throwsA(isA<AssertionError>())); }); test('prevents implmentation with `implements` and `noSuchMethod`', () { expect(() { SamplePluginPlatform.instance = ImplementsSamplePluginPlatformUsingNoSuchMethod(); }, throwsA(isA<AssertionError>())); }); test('allows mocking with `implements`', () { final SamplePluginPlatform mock = SamplePluginPlatformMock(); SamplePluginPlatform.instance = mock; }); test('allows faking with `implements`', () { final SamplePluginPlatform fake = SamplePluginPlatformFake(); SamplePluginPlatform.instance = fake; }); test('allows extending', () { SamplePluginPlatform.instance = ExtendsSamplePluginPlatform(); }); test('prevents `const Object()` token', () { expect(() { ConstTokenPluginPlatform.instance = ExtendsConstTokenPluginPlatform(); }, throwsA(isA<AssertionError>())); }); }); // Tests of the earlier, to-be-deprecated `verifyToken` method group('`verifyToken`', () { test('prevents implementation with `implements`', () { expect(() { VerifyTokenPluginPlatform.instance = ImplementsVerifyTokenPluginPlatform(); }, throwsA(isA<AssertionError>())); }); test('allows mocking with `implements`', () { final VerifyTokenPluginPlatform mock = ImplementsVerifyTokenPluginPlatformUsingMockPlatformInterfaceMixin(); VerifyTokenPluginPlatform.instance = mock; }); test('allows extending', () { VerifyTokenPluginPlatform.instance = ExtendsVerifyTokenPluginPlatform(); }); test('does not prevent `const Object()` token', () { ConstVerifyTokenPluginPlatform.instance = ImplementsConstVerifyTokenPluginPlatform(); }); }); }
packages/packages/plugin_platform_interface/test/plugin_platform_interface_test.dart/0
{ "file_path": "packages/packages/plugin_platform_interface/test/plugin_platform_interface_test.dart", "repo_id": "packages", "token_count": 1717 }
1,264
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'package:pointer_interceptor_platform_interface/pointer_interceptor_platform_interface.dart'; /// A [Widget] that prevents clicks from being swallowed by PlatformViews. class PointerInterceptor extends StatelessWidget { /// Create a `PointerInterceptor` wrapping a `child`. // ignore: prefer_const_constructors_in_immutables PointerInterceptor({ required this.child, this.intercepting = true, this.debug = false, super.key, }); /// The `Widget` that is being wrapped by this `PointerInterceptor`. final Widget child; /// Whether or not this `PointerInterceptor` should intercept pointer events. final bool intercepting; /// When true, the widget renders with a semi-transparent red background, for debug purposes. /// /// This is useful when rendering this as a "layout" widget, like the root child /// of a `Drawer`. final bool debug; @override Widget build(BuildContext context) { if (!intercepting) { return child; } return PointerInterceptorPlatform.instance .buildWidget(child: child, debug: debug, key: key); } }
packages/packages/pointer_interceptor/pointer_interceptor/lib/src/pointer_interceptor.dart/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor/lib/src/pointer_interceptor.dart", "repo_id": "packages", "token_count": 386 }
1,265
<?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="21507" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r"> <device id="retina6_12" orientation="portrait" appearance="light"/> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="21505"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--Flutter View Controller--> <scene sceneID="tne-QT-ifu"> <objects> <viewController id="BYZ-38-t0r" customClass="FlutterViewController" sceneMemberID="viewController"> <layoutGuides> <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/> <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/> </layoutGuides> <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC"> <rect key="frame" x="0.0" y="0.0" width="393" height="852"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> </view> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="-17" y="-40"/> </scene> </scenes> </document>
packages/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Runner/Base.lproj/Main.storyboard/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Runner/Base.lproj/Main.storyboard", "repo_id": "packages", "token_count": 822 }
1,266
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:pointer_interceptor_platform_interface/pointer_interceptor_platform_interface.dart'; /// The iOS implementation of the [PointerInterceptorPlatform]. class PointerInterceptorIOS extends PointerInterceptorPlatform { /// Register plugin as iOS version. static void registerWith() { PointerInterceptorPlatform.instance = PointerInterceptorIOS(); } @override Widget buildWidget({required Widget child, bool debug = false, Key? key}) { return Stack(alignment: Alignment.center, children: <Widget>[ Positioned.fill( child: UiKitView( viewType: 'plugins.flutter.dev/pointer_interceptor_ios', creationParams: <String, bool>{ 'debug': debug, }, creationParamsCodec: const StandardMessageCodec(), )), child ]); } }
packages/packages/pointer_interceptor/pointer_interceptor_ios/lib/pointer_interceptor_ios.dart/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor_ios/lib/pointer_interceptor_ios.dart", "repo_id": "packages", "token_count": 353 }
1,267
# pointer\_interceptor\_web The web implementation of [`pointer interceptor`][1]. ## Usage This package is [endorsed][2], which means you can simply use `pointer_interceptor` normally. This package will be automatically included in your app when you do, so you do not need to add it to your `pubspec.yaml`. However, if you `import` this package to use any of its APIs directly, you should add it to your `pubspec.yaml` as usual. [1]: https://pub.dev/packages/pointer_interceptor [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
packages/packages/pointer_interceptor/pointer_interceptor_web/README.md/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor_web/README.md", "repo_id": "packages", "token_count": 175 }
1,268
# Below is a list of people and organizations that have contributed # to the Process project. Names should be added to the list like so: # # Name/Organization <email address> Google Inc.
packages/packages/process/AUTHORS/0
{ "file_path": "packages/packages/process/AUTHORS", "repo_id": "packages", "token_count": 49 }
1,269
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 1.0.7 * Updates minimum required plugin_platform_interface version to 2.1.7. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 1.0.6 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 1.0.5 * Updates iOS quick action documentation in README. ## 1.0.4 * Removes obsolete null checks on non-nullable values. ## 1.0.3 * Updates iOS minimum version in README. * Updates minimum Flutter version to 3.3. * Aligns Dart and Flutter SDK constraints. ## 1.0.2 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 1.0.1 * Updates implementaion package versions to current versions. ## 1.0.0 * Updates version to 1.0 to reflect current status. * Updates minimum Flutter version to 2.10. * Updates README to document that on Android, icons may need to be explicitly marked as used in the Android project for release builds. * Minor fixes for new analysis options. ## 0.6.0+11 * Removes unnecessary imports. * Updates minimum Flutter version to 2.8. * Adds OS version support information to README. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 0.6.0+10 * Moves Android and iOS implementations to federated packages. ## 0.6.0+9 * Updates Android compileSdkVersion to 31. * Updates code for analyzer changes. * Removes dependency on `meta`. ## 0.6.0+8 * Updates example app Android compileSdkVersion to 31. * Moves method call to background thread to fix CI failure. ## 0.6.0+7 * Update minimum Flutter SDK to 2.5 and iOS deployment target to 9.0. ## 0.6.0+6 * Updated Android lint settings. * Fix repository link in pubspec.yaml. ## 0.6.0+5 * Support only calling initialize once. ## 0.6.0+4 * Remove references to the Android V1 embedding. ## 0.6.0+3 * Added a `const` constructor for the `QuickActions` class, so the plugin will behave as documented in the sample code mentioned in the [README.md](https://github.com/flutter/plugins/blob/59e16a556e273c2d69189b2dcdfa92d101ea6408/packages/quick_actions/quick_actions/README.md). ## 0.6.0+2 * Migrate maven repository from jcenter to mavenCentral. ## 0.6.0+1 * Correctly handle iOS Application lifecycle events on cold start of the App. ## 0.6.0 * Migrate to federated architecture. ## 0.5.0+1 * Updated example app implementation. ## 0.5.0 * Migrate to null safety. * Fixes quick actions not working on iOS. ## 0.4.0+12 * Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276)) ## 0.4.0+11 * Update Flutter SDK constraint. ## 0.4.0+10 * Update android compileSdkVersion to 29. ## 0.4.0+9 * Keep handling deprecated Android v1 classes for backward compatibility. ## 0.4.0+8 * Update package:e2e -> package:integration_test ## 0.4.0+7 * Update package:e2e reference to use the local version in the flutter/plugins repository. ## 0.4.0+6 * Post-v2 Android embedding cleanup. ## 0.4.0+5 * Update lower bound of dart dependency to 2.1.0. ## 0.4.0+4 * Bump the minimum Flutter version to 1.12.13+hotfix.5. * Clean up various Android workarounds no longer needed after framework v1.12. * Complete v2 embedding support. * Fix UIApplicationShortcutItem availability warnings. * Fix CocoaPods podspec lint warnings. ## 0.4.0+3 * Replace deprecated `getFlutterEngine` call on Android. ## 0.4.0+2 * Make the pedantic dev_dependency explicit. ## 0.4.0+1 * Remove the deprecated `author:` field from pubspec.yaml * Migrate the plugin to the pubspec platforms manifest. * Require Flutter SDK 1.10.0 or greater. ## 0.4.0 - Added missing documentation. - **Breaking change**. `channel` and `withMethodChannel` are now `@visibleForTesting`. These methods are for plugin unit tests only and may be removed in the future. - **Breaking change**. Removed `runLaunchAction` from public API. This method was not meant to be used by consumers of the plugin. ## 0.3.3+1 * Update and migrate iOS example project by removing flutter_assets, change "English" to "en", remove extraneous xcconfigs, update to Xcode 11 build settings, and remove ARCHS and DEVELOPMENT_TEAM. ## 0.3.3 * Support Android V2 embedding. * Add e2e tests. * Migrate to using the new e2e test binding. ## 0.3.2+4 * Remove AndroidX warnings. ## 0.3.2+3 * Define clang module for iOS. ## 0.3.2+2 * Fix bug that would make the shortcut not open on Android. * Report shortcut used on Android. * Improves example. ## 0.3.2+1 * Update usage example in README. ## 0.3.2 * Fixed the quick actions launch on Android when the app is killed. ## 0.3.1 * Added unit tests. ## 0.3.0+2 * Add missing template type parameter to `invokeMethod` calls. * Bump minimum Flutter version to 1.5.0. * Replace invokeMethod with invokeMapMethod wherever necessary. ## 0.3.0+1 * Log a more detailed warning at build time about the previous AndroidX migration. ## 0.3.0 * **Breaking change**. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to [also migrate](https://developer.android.com/jetpack/androidx/migrate) if they're using the original support library. ## 0.2.2 * Allow to register more than once. ## 0.2.1 * Updated Gradle tooling to match Android Studio 3.1.2. ## 0.2.0 * **Breaking change**. Set SDK constraints to match the Flutter beta release. ## 0.1.1 * Simplified and upgraded Android project template to Android SDK 27. * Updated package description. ## 0.1.0 * **Breaking change**. Upgraded to Gradle 4.1 and Android Studio Gradle plugin 3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in order to use this version of the plugin. Instructions can be found [here](https://github.com/flutter/flutter/wiki/Updating-Flutter-projects-to-Gradle-4.1-and-Android-Studio-Gradle-plugin-3.0.1). ## 0.0.2 * Add FLT prefix to iOS types ## 0.0.1 * Initial release
packages/packages/quick_actions/quick_actions/CHANGELOG.md/0
{ "file_path": "packages/packages/quick_actions/quick_actions/CHANGELOG.md", "repo_id": "packages", "token_count": 1996 }
1,270
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:quick_actions_example/main.dart' as app; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('Can run MyApp', (WidgetTester tester) async { app.main(); await tester.pumpAndSettle(); await tester.pump(const Duration(seconds: 1)); expect(find.byType(Text), findsWidgets); expect(find.byType(app.MyHomePage), findsOneWidget); }); }
packages/packages/quick_actions/quick_actions_android/example/integration_test/quick_actions_test.dart/0
{ "file_path": "packages/packages/quick_actions/quick_actions_android/example/integration_test/quick_actions_test.dart", "repo_id": "packages", "token_count": 238 }
1,271
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Flutter import XCTest @testable import quick_actions_ios class MockFlutterApi: IOSQuickActionsFlutterApiProtocol { /// Method to allow for async testing. var launchActionCallback: ((String) -> Void)? = nil func launchAction( action actionArg: String, completion: @escaping (Result<Void, FlutterError>) -> Void ) { self.launchActionCallback?(actionArg) completion(.success(Void())) } } class QuickActionsPluginTests: XCTestCase { func testHandleMethodCall_setShortcutItems() { let rawItem = ShortcutItemMessage( type: "SearchTheThing", localizedTitle: "Search the thing", icon: "search_the_thing.png" ) let item = UIApplicationShortcutItem( type: "SearchTheThing", localizedTitle: "Search the thing", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"), userInfo: nil) let flutterApi: MockFlutterApi = MockFlutterApi() let mockShortcutItemProvider = MockShortcutItemProvider() let plugin = QuickActionsPlugin( flutterApi: flutterApi, shortcutItemProvider: mockShortcutItemProvider) plugin.setShortcutItems(itemsList: [rawItem]) XCTAssertEqual(mockShortcutItemProvider.shortcutItems, [item], "Must set shortcut items.") } func testHandleMethodCall_clearShortcutItems() { let item = UIApplicationShortcutItem( type: "SearchTheThing", localizedTitle: "Search the thing", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"), userInfo: nil) let flutterApi: MockFlutterApi = MockFlutterApi() let mockShortcutItemProvider = MockShortcutItemProvider() let plugin = QuickActionsPlugin( flutterApi: flutterApi, shortcutItemProvider: mockShortcutItemProvider) mockShortcutItemProvider.shortcutItems = [item] plugin.clearShortcutItems() XCTAssertEqual(mockShortcutItemProvider.shortcutItems, [], "Must clear shortcut items.") } func testApplicationPerformActionForShortcutItem() { let flutterApi: MockFlutterApi = MockFlutterApi() let mockShortcutItemProvider = MockShortcutItemProvider() let plugin = QuickActionsPlugin( flutterApi: flutterApi, shortcutItemProvider: mockShortcutItemProvider) let item = UIApplicationShortcutItem( type: "SearchTheThing", localizedTitle: "Search the thing", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"), userInfo: nil) let invokeMethodExpectation = expectation(description: "invokeMethod must be called.") flutterApi.launchActionCallback = { aString in XCTAssertEqual(aString, item.type) invokeMethodExpectation.fulfill() } let actionResult = plugin.application( UIApplication.shared, performActionFor: item ) { success in // noop } XCTAssert(actionResult, "performActionForShortcutItem must return true.") waitForExpectations(timeout: 1) } func testApplicationDidFinishLaunchingWithOptions_launchWithShortcut() { let flutterApi: MockFlutterApi = MockFlutterApi() let mockShortcutItemProvider = MockShortcutItemProvider() let plugin = QuickActionsPlugin( flutterApi: flutterApi, shortcutItemProvider: mockShortcutItemProvider) let item = UIApplicationShortcutItem( type: "SearchTheThing", localizedTitle: "Search the thing", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"), userInfo: nil) let launchResult = plugin.application( UIApplication.shared, didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.shortcutItem: item]) XCTAssertFalse( launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.") } func testApplicationDidFinishLaunchingWithOptions_launchWithoutShortcut() { let flutterApi: MockFlutterApi = MockFlutterApi() let mockShortcutItemProvider = MockShortcutItemProvider() let plugin = QuickActionsPlugin( flutterApi: flutterApi, shortcutItemProvider: mockShortcutItemProvider) let launchResult = plugin.application(UIApplication.shared, didFinishLaunchingWithOptions: [:]) XCTAssert( launchResult, "didFinishLaunchingWithOptions must return true if not launched from shortcut.") } func testApplicationDidBecomeActive_launchWithoutShortcut() { let flutterApi: MockFlutterApi = MockFlutterApi() let mockShortcutItemProvider = MockShortcutItemProvider() let plugin = QuickActionsPlugin( flutterApi: flutterApi, shortcutItemProvider: mockShortcutItemProvider) let launchResult = plugin.application(UIApplication.shared, didFinishLaunchingWithOptions: [:]) XCTAssert( launchResult, "didFinishLaunchingWithOptions must return true if not launched from shortcut.") plugin.applicationDidBecomeActive(UIApplication.shared) } func testApplicationDidBecomeActive_launchWithShortcut() { let item = UIApplicationShortcutItem( type: "SearchTheThing", localizedTitle: "Search the thing", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"), userInfo: nil) let flutterApi: MockFlutterApi = MockFlutterApi() let mockShortcutItemProvider = MockShortcutItemProvider() let plugin = QuickActionsPlugin( flutterApi: flutterApi, shortcutItemProvider: mockShortcutItemProvider) let invokeMethodExpectation = expectation(description: "invokeMethod must be called.") flutterApi.launchActionCallback = { aString in XCTAssertEqual(aString, item.type) invokeMethodExpectation.fulfill() } let launchResult = plugin.application( UIApplication.shared, didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.shortcutItem: item]) XCTAssertFalse( launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.") plugin.applicationDidBecomeActive(UIApplication.shared) waitForExpectations(timeout: 1) } func testApplicationDidBecomeActive_launchWithShortcut_becomeActiveTwice() { let item = UIApplicationShortcutItem( type: "SearchTheThing", localizedTitle: "Search the thing", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"), userInfo: nil) let flutterApi: MockFlutterApi = MockFlutterApi() let mockShortcutItemProvider = MockShortcutItemProvider() let plugin = QuickActionsPlugin( flutterApi: flutterApi, shortcutItemProvider: mockShortcutItemProvider) let invokeMethodExpectation = expectation(description: "invokeMethod must be called.") var invokeMethodCount = 0 flutterApi.launchActionCallback = { aString in XCTAssertEqual(aString, item.type) invokeMethodCount += 1 invokeMethodExpectation.fulfill() } let launchResult = plugin.application( UIApplication.shared, didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.shortcutItem: item]) XCTAssertFalse( launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.") plugin.applicationDidBecomeActive(UIApplication.shared) waitForExpectations(timeout: 1) XCTAssertEqual(invokeMethodCount, 1, "shortcut should only be handled once per launch.") } }
packages/packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/QuickActionsPluginTests.swift/0
{ "file_path": "packages/packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/QuickActionsPluginTests.swift", "repo_id": "packages", "token_count": 2611 }
1,272
name: quick_actions_ios description: An implementation for the iOS platform of the Flutter `quick_actions` plugin. repository: https://github.com/flutter/packages/tree/main/packages/quick_actions/quick_actions_ios issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+in_app_purchase%22 version: 1.0.10 environment: sdk: ^3.2.3 flutter: ">=3.16.6" flutter: plugin: implements: quick_actions platforms: ios: pluginClass: QuickActionsPlugin dartPluginClass: QuickActionsIos dependencies: flutter: sdk: flutter quick_actions_platform_interface: ^1.0.0 dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter pigeon: ^12.0.1 plugin_platform_interface: ^2.1.7 topics: - quick-actions - os-integration
packages/packages/quick_actions/quick_actions_ios/pubspec.yaml/0
{ "file_path": "packages/packages/quick_actions/quick_actions_ios/pubspec.yaml", "repo_id": "packages", "token_count": 329 }
1,273
#include "Generated.xcconfig"
packages/packages/rfw/example/hello/ios/Flutter/Debug.xcconfig/0
{ "file_path": "packages/packages/rfw/example/hello/ios/Flutter/Debug.xcconfig", "repo_id": "packages", "token_count": 12 }
1,274
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/rfw/example/hello/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/rfw/example/hello/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
1,275
# Example of new custom local widgets for RFW This example shows how one can create custom widgets in an RFW client, for use by remote widgets.
packages/packages/rfw/example/local/README.md/0
{ "file_path": "packages/packages/rfw/example/local/README.md", "repo_id": "packages", "token_count": 35 }
1,276
buildscript { ext.kotlin_version = '1.7.10' repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.4.2' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } allprojects { repositories { // See https://github.com/flutter/flutter/wiki/Plugins-and-Packages-repository-structure#gradle-structure for more info. def artifactRepoKey = 'ARTIFACT_HUB_REPOSITORY' if (System.getenv().containsKey(artifactRepoKey)) { println "Using artifact hub" maven { url System.getenv(artifactRepoKey) } } google() mavenCentral() } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" project.evaluationDependsOn(':app') } tasks.register("clean", Delete) { delete rootProject.buildDir }
packages/packages/rfw/example/local/android/build.gradle/0
{ "file_path": "packages/packages/rfw/example/local/android/build.gradle", "repo_id": "packages", "token_count": 410 }
1,277
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // internals enum Ops { opNone, opAdd }; int _pending = 0; Ops _pendingOp = opNone; int _display = 0; bool _displayLocked = false; void _resolve() { switch (_pendingOp) { case opNone: break; case opAdd: _display += _pending; break; } } // public API extern "C" int value() { return _display; } extern "C" void digit(int n) { if (_displayLocked) { _display = 0; } _display *= 10; _display += n; _displayLocked = false; } extern "C" void add() { _resolve(); _pending = _display; _pendingOp = opAdd; _display = 0; _displayLocked = false; } extern "C" void equals() { int current = _displayLocked ? _pending : _display; _resolve(); _pending = current; _displayLocked = true; }
packages/packages/rfw/example/wasm/logic/calculator.cc/0
{ "file_path": "packages/packages/rfw/example/wasm/logic/calculator.cc", "repo_id": "packages", "token_count": 348 }
1,278
name: rfw_wasm description: Example of using Wasm with RFW publish_to: none # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: sdk: ^3.2.0 flutter: ">=3.16.0" dependencies: flutter: sdk: flutter path: ^1.8.0 path_provider: ^2.0.2 rfw: path: ../../ wasm: ">=0.1.0+1 <=2.0.0" flutter: uses-material-design: true
packages/packages/rfw/example/wasm/pubspec.yaml/0
{ "file_path": "packages/packages/rfw/example/wasm/pubspec.yaml", "repo_id": "packages", "token_count": 170 }
1,279
// 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:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:rfw/formats.dart' show parseLibraryFile; import 'package:rfw/rfw.dart'; import 'utils.dart'; void main() { testWidgets('String example', (WidgetTester tester) async { Duration? duration; Curve? curve; int buildCount = 0; final Widget builder = Builder( builder: (BuildContext context) { buildCount += 1; duration = AnimationDefaults.durationOf(context); curve = AnimationDefaults.curveOf(context); return const SizedBox.shrink(); }, ); await tester.pumpWidget( AnimationDefaults( duration: const Duration(milliseconds: 500), curve: Curves.easeIn, child: builder, ), ); expect(duration, const Duration(milliseconds: 500)); expect(curve, Curves.easeIn); expect(buildCount, 1); await tester.pumpWidget( AnimationDefaults( duration: const Duration(milliseconds: 500), curve: Curves.easeIn, child: builder, ), ); expect(buildCount, 1); await tester.pumpWidget( AnimationDefaults( duration: const Duration(milliseconds: 501), curve: Curves.easeIn, child: builder, ), ); expect(buildCount, 2); }); testWidgets('spot checks', (WidgetTester tester) async { Duration? duration; Curve? curve; int buildCount = 0; final Runtime runtime = Runtime() ..update(const LibraryName(<String>['core']), createCoreWidgets()) ..update(const LibraryName(<String>['builder']), LocalWidgetLibrary(<String, LocalWidgetBuilder>{ 'Test': (BuildContext context, DataSource source) { buildCount += 1; duration = AnimationDefaults.durationOf(context); curve = AnimationDefaults.curveOf(context); return const SizedBox.shrink(); }, })) ..update(const LibraryName(<String>['test']), parseLibraryFile('import core; widget root = SizedBox();')); final DynamicContent data = DynamicContent(); final List<String> eventLog = <String>[]; await tester.pumpWidget( RemoteWidget( runtime: runtime, data: data, widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'), onEvent: (String eventName, DynamicMap eventArguments) { eventLog.add(eventName); expect(eventArguments, const <String, Object?>{ 'argument': true }); }, ), ); expect(find.byType(SizedBox), findsOneWidget); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Align(alignment: { x: 0.25, y: 0.75 }); ''')); await tester.pump(); expect(tester.widget<Align>(find.byType(Align)).alignment, const Alignment(0.25, 0.75)); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Align(alignment: { start: 0.25, y: 0.75 }); ''')); await tester.pump(); expect(tester.widget<Align>(find.byType(Align)).alignment, const Alignment(0.25, 0.75)); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; import builder; widget root = AnimationDefaults(curve: "easeOut", duration: 5000, child: Test()); ''')); await tester.pump(); expect(buildCount, 1); expect(duration, const Duration(seconds: 5)); expect(curve, Curves.easeOut); ArgumentDecoders.curveDecoders['saw3'] = (DataSource source, List<Object> key) => const SawTooth(3); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; import builder; widget root = AnimationDefaults(curve: "saw3", child: Test()); ''')); await tester.pump(); expect(curve, isA<SawTooth>()); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = AspectRatio(aspectRatio: 0.5); ''')); await tester.pump(); expect(tester.widget<AspectRatio>(find.byType(AspectRatio)).aspectRatio, 0.5); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Center(widthFactor: 0.25); ''')); await tester.pump(); expect(tester.widget<Center>(find.byType(Center)).widthFactor, 0.25); expect(tester.widget<Center>(find.byType(Center)).heightFactor, null); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = ColoredBox(color: 0xFF112233); ''')); await tester.pump(); expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xFF112233)); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Column( mainAxisAlignment: "center", children: [ ColoredBox(color: 1), ColoredBox(color: 2) ], ); ''')); await tester.pump(); expect(tester.widget<Column>(find.byType(Column)).mainAxisAlignment, MainAxisAlignment.center); expect(tester.widget<Column>(find.byType(Column)).crossAxisAlignment, CrossAxisAlignment.center); expect(tester.widget<Column>(find.byType(Column)).verticalDirection, VerticalDirection.down); expect(tester.widget<Column>(find.byType(Column)).children, hasLength(2)); expect(tester.widgetList<ColoredBox>(find.byType(ColoredBox)).toList()[0].color, const Color(0x00000001)); expect(tester.widgetList<ColoredBox>(find.byType(ColoredBox)).toList()[1].color, const Color(0x00000002)); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = ColoredBox(color: 0xFF112233); ''')); await tester.pump(); expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xFF112233)); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = DefaultTextStyle( textHeightBehavior: { applyHeightToLastDescent: false }, child: SizedBoxShrink(), ); ''')); await tester.pump(); expect( tester.widget<DefaultTextStyle>(find.byType(DefaultTextStyle)).textHeightBehavior, const TextHeightBehavior(applyHeightToLastDescent: false), ); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Directionality( textDirection: "ltr", child: SizedBoxShrink(), ); ''')); await tester.pump(); expect(tester.widget<Directionality>(find.byType(Directionality)).textDirection, TextDirection.ltr); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = FittedBox( fit: "cover", ); ''')); await tester.pump(); expect(tester.widget<FittedBox>(find.byType(FittedBox)).fit, BoxFit.cover); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = GestureDetector( onTap: event 'tap' { argument: true }, child: ColoredBox(), ); ''')); await tester.pump(); await tester.tap(find.byType(ColoredBox)); expect(eventLog, <String>['tap']); eventLog.clear(); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Directionality( textDirection: "ltr", child: Icon( icon: 0x0001, fontFamily: 'FONT', ), ); ''')); await tester.pump(); expect(tester.widget<Icon>(find.byType(Icon)).icon!.codePoint, 1); expect(tester.widget<Icon>(find.byType(Icon)).icon!.fontFamily, 'FONT'); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = IconTheme( color: 0x12345678, child: SizedBoxShrink(), ); ''')); await tester.pump(); expect(tester.widget<IconTheme>(find.byType(IconTheme)).data.color, const Color(0x12345678)); }); testWidgets('golden checks', (WidgetTester tester) async { final Runtime runtime = Runtime() ..update(const LibraryName(<String>['core']), createCoreWidgets()) ..update(const LibraryName(<String>['test']), parseLibraryFile('import core; widget root = SizedBox();')); final DynamicContent data = DynamicContent(); final List<String> eventLog = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, child: RemoteWidget( runtime: runtime, data: data, widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'), onEvent: (String eventName, DynamicMap eventArguments) { eventLog.add('$eventName $eventArguments'); }, ), ), ); expect(find.byType(RemoteWidget), findsOneWidget); ArgumentDecoders.decorationDecoders['tab'] = (DataSource source, List<Object> key) { return UnderlineTabIndicator( borderSide: ArgumentDecoders.borderSide(source, <Object>[...key, 'side']) ?? const BorderSide(width: 2.0, color: Color(0xFFFFFFFF)), insets: ArgumentDecoders.edgeInsets(source, <Object>['insets']) ?? EdgeInsets.zero, ); }; ArgumentDecoders.gradientDecoders['custom'] = (DataSource source, List<Object> key) { return const RadialGradient( center: Alignment(0.7, -0.6), radius: 0.2, colors: <Color>[ Color(0xFFFFFF00), Color(0xFF0099FF) ], stops: <double>[0.4, 1.0], ); }; ArgumentDecoders.shapeBorderDecoders['custom'] = (DataSource source, List<Object> key) { return StarBorder( side: ArgumentDecoders.borderSide(source, <Object>[...key, 'side']) ?? const BorderSide(width: 2.0, color: Color(0xFFFFFFFF)), points: source.v<double>(<Object>[...key, 'points']) ?? 5.0, ); }; runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Container( margin: [20.0, 10.0, 30.0, 5.0], padding: [10.0], decoration: { type: 'box', borderRadius: [ { x: 120.0 }, { x: 130.0, y: 40.0 } ], image: { // this image doesn't exist so nothing much happens here // we check the results of this parse in a separate expect source: 'asset', color: 0xFF00BBCC, centerSlice: { x: 5.0, y: 8.0, w: 100.0, h: 70.0 }, colorFilter: { type: 'matrix', matrix: [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ], }, }, gradient: { type: 'sweep', }, }, foregroundDecoration: { type: 'box', border: [ { width: 10.0, color: 0xFFFFFF00 }, { width: 3.0, color: 0xFF00FFFF } ], boxShadow: [ { offset: { x: 25.0, y: 25.0 }, color: 0x5F000000, } ], image: { // this image also doesn't exist // we check the results of this parse in a separate expect source: 'x-invalid://', colorFilter: { type: 'mode', color: 0xFF8811FF, blendMode: "xor", }, onError: event 'image-error-event' { }, }, gradient: { type: 'linear', colors: [ 0x1F009900, 0x1F33CC33, 0x7F777700 ], stops: [ 0.0, 0.75, 1.0 ], }, }, alignment: { x: 0.0, y: -0.5, }, transform: [ 0.9, 0.2, 0.1, 0.0, -0.1, 1.1, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 50.0, -20.0, 0.0, 1.0, ], child: Container( constraints: { maxWidth: 400.0, maxHeight: 350.0 }, margin: [5.0, 25.0, 10.0, 20.0], decoration: { type: 'box', color: 0xFF9911CC, gradient: { type: 'custom' }, }, foregroundDecoration: { type: 'flutterLogo', margin: [ 100.0 ], }, child: Container( margin: [5.0], decoration: { type: 'tab', side: { width: 20.0, color: 0xFFFFFFFF }, }, foregroundDecoration: { type: 'shape', shape: [ { type: 'box', border: { width: 10.0, color: 0xFF0000FF } }, { type: 'beveled', borderRadius: [ { x: 60.0 } ], side: { width: 10.0, color: 0xFF0033FF } }, { type: 'circle', side: { width: 10.0, color: 0xFF0066FF } }, { type: 'continuous', borderRadius: [ { x: 60.0 }, { x: 80.0 }, { x: 0.0 }, { x: 20.0, y: 50.0 } ], side: { width: 10.0, color: 0xFFEEFF33 } }, { type: 'rounded', borderRadius: [ { x: 20.0 } ], side: { width: 10.0, color: 0xFF00CCFF } }, { type: 'stadium', side: { width: 10.0, color: 0xFF00FFFF } }, { type: 'custom', side: { width: 5.0, color: 0xFFFFFF00 }, points: 6 }, // star ], gradient: { type: 'radial', }, }, ), ), ); ''')); await tester.pump(); if (!kIsWeb) { expect(eventLog, hasLength(1)); expect(eventLog.first, startsWith('image-error-event {exception: HTTP request failed, statusCode: 400, x-invalid:')); eventLog.clear(); } await expectLater( find.byType(RemoteWidget), matchesGoldenFile('goldens/argument_decoders_test.containers.png'), skip: !runGoldens, ); expect(find.byType(DecoratedBox), findsNWidgets(6)); const String matrix = kIsWeb ? '1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1' : '1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0'; expect( (tester.widgetList<DecoratedBox>(find.byType(DecoratedBox)).toList()[1].decoration as BoxDecoration).image.toString(), 'DecorationImage(AssetImage(bundle: null, name: "asset"), ' // this just seemed like the easiest way to check all this... 'ColorFilter.matrix([$matrix]), ' 'Alignment.center, centerSlice: Rect.fromLTRB(5.0, 8.0, 105.0, 78.0), scale 1.0, opacity 1.0, FilterQuality.low)', ); expect( (tester.widgetList<DecoratedBox>(find.byType(DecoratedBox)).toList()[0].decoration as BoxDecoration).image.toString(), 'DecorationImage(NetworkImage("x-invalid://", scale: 1.0), ' 'ColorFilter.mode(Color(0xff8811ff), BlendMode.xor), Alignment.center, scale 1.0, ' 'opacity 1.0, FilterQuality.low)', ); ArgumentDecoders.colorFilterDecoders['custom'] = (DataSource source, List<Object> key) { return const ColorFilter.mode(Color(0x12345678), BlendMode.xor); }; ArgumentDecoders.maskFilterDecoders['custom'] = (DataSource source, List<Object> key) { return const MaskFilter.blur(BlurStyle.outer, 0.5); }; ArgumentDecoders.shaderDecoders['custom'] = (DataSource source, List<Object> key) { return ui.Gradient.linear(Offset.zero, const Offset(100.0, 100.0), const <Color>[Color(0xFFFFFF00), Color(0xFF00FFFF)]); }; runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Column( children: [ Text( text: [ 'Hello World Hello World Hello World Hello World Hello World Hello World Hello World', 'Hello World Hello World Hello World Hello World Hello World Hello World Hello World', ], locale: "en-US", style: { fontFamilyFallback: [ "a", "b" ], fontSize: 30.0, }, strutStyle: { fontSize: 50.0, }, ), Expanded( flex: 2, child: Text( text: 'Aaaa Aaaaaaa Aaaaa', locale: "en", style: { decoration: [ "underline", "overline" ], decorationColor: 0xFF00FF00, fontFeatures: [ { feature: 'sups' } ], foreground: { blendMode: 'color', color: 0xFFEEDDCC, colorFilter: { type: 'srgbToLinearGamma' }, filterQuality: "high", isAntiAlias: true, maskFilter: { type: 'blur' }, shader: { type: 'linear', rect: { x: 0.0, y: 0.0, w: 300.0, h: 200.0, } } }, background: { colorFilter: { type: 'custom' }, maskFilter: { type: 'custom' }, shader: { type: 'custom' }, }, }, ), ), Expanded( flex: 1, child: Text( text: 'B', locale: "en-latin-GB", ), ), ], ); ''')); await tester.pump(); expect(tester.firstWidget<Text>(find.byType(Text)).style!.fontFamilyFallback, <String>[ 'a', 'b' ]); expect(tester.widgetList<Text>(find.byType(Text)).map<Locale>((Text widget) => widget.locale!), const <Locale>[Locale('en', 'US'), Locale('en'), Locale.fromSubtags(languageCode: 'en', scriptCode: 'latin', countryCode: 'GB')]); await expectLater( find.byType(RemoteWidget), matchesGoldenFile('goldens/argument_decoders_test.text.png'), skip: !runGoldens, ); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = GridView( gridDelegate: { type: 'fixedCrossAxisCount', crossAxisCount: 3 }, children: [ ColoredBox(color: 0xFF118844), ColoredBox(color: 0xFFEE8844), ColoredBox(color: 0xFF882244), ColoredBox(color: 0xFF449999), ColoredBox(color: 0xFF330088), ColoredBox(color: 0xFF8822CC), ColoredBox(color: 0xFF330000), ColoredBox(color: 0xFF992288), ], ); ''')); await tester.pump(); await expectLater( find.byType(RemoteWidget), matchesGoldenFile('goldens/argument_decoders_test.gridview.fixed.png'), skip: !runGoldens, ); runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = GridView( gridDelegate: { type: 'maxCrossAxisExtent', maxCrossAxisExtent: 50.0 }, children: [ ColoredBox(color: 0xFF118844), ColoredBox(color: 0xFFEE8844), ColoredBox(color: 0xFF882244), ColoredBox(color: 0xFF449999), ColoredBox(color: 0xFF330088), ColoredBox(color: 0xFF8822CC), ColoredBox(color: 0xFF330000), ColoredBox(color: 0xFF992288), ], ); ''')); await tester.pump(); await expectLater( find.byType(RemoteWidget), matchesGoldenFile('goldens/argument_decoders_test.gridview.max.png'), skip: !runGoldens, ); int sawGridDelegateDecoder = 0; ArgumentDecoders.gridDelegateDecoders['custom'] = (DataSource source, List<Object> key) { sawGridDelegateDecoder += 1; return null; }; runtime.update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = GridView( gridDelegate: { type: 'custom' }, children: [ ColoredBox(color: 0xFF118844), ColoredBox(color: 0xFFEE8844), ColoredBox(color: 0xFF882244), ColoredBox(color: 0xFF449999), ColoredBox(color: 0xFF330088), ColoredBox(color: 0xFF8822CC), ColoredBox(color: 0xFF330000), ColoredBox(color: 0xFF992288), ], ); ''')); expect(sawGridDelegateDecoder, 0); await tester.pump(); expect(sawGridDelegateDecoder, 1); await expectLater( find.byType(RemoteWidget), matchesGoldenFile('goldens/argument_decoders_test.gridview.custom.png'), skip: !runGoldens, ); expect(eventLog, isEmpty); }, skip: kIsWeb || !isMainChannel); // https://github.com/flutter/flutter/pull/129851 }
packages/packages/rfw/test/argument_decoders_test.dart/0
{ "file_path": "packages/packages/rfw/test/argument_decoders_test.dart", "repo_id": "packages", "token_count": 9415 }
1,280
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "utils.h" #include <flutter_windows.h> #include <io.h> #include <stdio.h> #include <windows.h> #include <iostream> void CreateAndAttachConsole() { if (::AllocConsole()) { FILE* unused; if (freopen_s(&unused, "CONOUT$", "w", stdout)) { _dup2(_fileno(stdout), 1); } if (freopen_s(&unused, "CONOUT$", "w", stderr)) { _dup2(_fileno(stdout), 2); } std::ios::sync_with_stdio(); FlutterDesktopResyncOutputStreams(); } }
packages/packages/shared_preferences/shared_preferences/example/windows/runner/utils.cpp/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences/example/windows/runner/utils.cpp", "repo_id": "packages", "token_count": 257 }
1,281
// 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 android.content.Context; import android.content.SharedPreferences; import android.util.Base64; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.sharedpreferences.Messages.SharedPreferencesApi; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** SharedPreferencesPlugin */ public class SharedPreferencesPlugin implements FlutterPlugin, SharedPreferencesApi { private static final String TAG = "SharedPreferencesPlugin"; private static final String SHARED_PREFERENCES_NAME = "FlutterSharedPreferences"; private static final String LIST_IDENTIFIER = "VGhpcyBpcyB0aGUgcHJlZml4IGZvciBhIGxpc3Qu"; private static final String BIG_INTEGER_PREFIX = "VGhpcyBpcyB0aGUgcHJlZml4IGZvciBCaWdJbnRlZ2Vy"; private static final String DOUBLE_PREFIX = "VGhpcyBpcyB0aGUgcHJlZml4IGZvciBEb3VibGUu"; private SharedPreferences preferences; private SharedPreferencesListEncoder listEncoder; public SharedPreferencesPlugin() { this(new ListEncoder()); } @VisibleForTesting SharedPreferencesPlugin(@NonNull SharedPreferencesListEncoder listEncoder) { this.listEncoder = listEncoder; } @SuppressWarnings("deprecation") public static void registerWith( @NonNull io.flutter.plugin.common.PluginRegistry.Registrar registrar) { final SharedPreferencesPlugin plugin = new SharedPreferencesPlugin(); plugin.setUp(registrar.messenger(), registrar.context()); } private void setUp(@NonNull BinaryMessenger messenger, @NonNull Context context) { preferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); try { SharedPreferencesApi.setup(messenger, this); } catch (Exception ex) { Log.e(TAG, "Received exception while setting up SharedPreferencesPlugin", ex); } } @Override public void onAttachedToEngine(@NonNull FlutterPlugin.FlutterPluginBinding binding) { setUp(binding.getBinaryMessenger(), binding.getApplicationContext()); } @Override public void onDetachedFromEngine(@NonNull FlutterPlugin.FlutterPluginBinding binding) { SharedPreferencesApi.setup(binding.getBinaryMessenger(), null); } @Override public @NonNull Boolean setBool(@NonNull String key, @NonNull Boolean value) { return preferences.edit().putBoolean(key, value).commit(); } @Override public @NonNull Boolean setString(@NonNull String key, @NonNull String value) { // TODO (tarrinneal): Move this string prefix checking logic to dart code and make it an Argument Error. if (value.startsWith(LIST_IDENTIFIER) || value.startsWith(BIG_INTEGER_PREFIX) || value.startsWith(DOUBLE_PREFIX)) { throw new RuntimeException( "StorageError: This string cannot be stored as it clashes with special identifier prefixes"); } return preferences.edit().putString(key, value).commit(); } @Override public @NonNull Boolean setInt(@NonNull String key, @NonNull Long value) { return preferences.edit().putLong(key, value).commit(); } @Override public @NonNull Boolean setDouble(@NonNull String key, @NonNull Double value) { String doubleValueStr = Double.toString(value); return preferences.edit().putString(key, DOUBLE_PREFIX + doubleValueStr).commit(); } @Override public @NonNull Boolean remove(@NonNull String key) { return preferences.edit().remove(key).commit(); } @Override public @NonNull Boolean setStringList(@NonNull String key, @NonNull List<String> value) throws RuntimeException { return preferences.edit().putString(key, LIST_IDENTIFIER + listEncoder.encode(value)).commit(); } @Override public @NonNull Map<String, Object> getAll( @NonNull String prefix, @Nullable List<String> allowList) throws RuntimeException { final Set<String> allowSet = allowList == null ? null : new HashSet<>(allowList); return getAllPrefs(prefix, allowSet); } @Override public @NonNull Boolean clear(@NonNull String prefix, @Nullable List<String> allowList) throws RuntimeException { SharedPreferences.Editor clearEditor = preferences.edit(); Map<String, ?> allPrefs = preferences.getAll(); ArrayList<String> filteredPrefs = new ArrayList<>(); for (String key : allPrefs.keySet()) { if (key.startsWith(prefix) && (allowList == null || allowList.contains(key))) { filteredPrefs.add(key); } } for (String key : filteredPrefs) { clearEditor.remove(key); } return clearEditor.commit(); } // Gets all shared preferences, filtered to only those set with the given prefix. // Optionally filtered also to only those items in the optional [allowList]. @SuppressWarnings("unchecked") private @NonNull Map<String, Object> getAllPrefs( @NonNull String prefix, @Nullable Set<String> allowList) throws RuntimeException { Map<String, ?> allPrefs = preferences.getAll(); Map<String, Object> filteredPrefs = new HashMap<>(); for (String key : allPrefs.keySet()) { if (key.startsWith(prefix) && (allowList == null || allowList.contains(key))) { filteredPrefs.put(key, transformPref(key, allPrefs.get(key))); } } return filteredPrefs; } private Object transformPref(@NonNull String key, @NonNull Object value) { if (value instanceof String) { String stringValue = (String) value; if (stringValue.startsWith(LIST_IDENTIFIER)) { return listEncoder.decode(stringValue.substring(LIST_IDENTIFIER.length())); } else if (stringValue.startsWith(BIG_INTEGER_PREFIX)) { // TODO (tarrinneal): Remove all BigInt code. // https://github.com/flutter/flutter/issues/124420 String encoded = stringValue.substring(BIG_INTEGER_PREFIX.length()); return new BigInteger(encoded, Character.MAX_RADIX); } else if (stringValue.startsWith(DOUBLE_PREFIX)) { String doubleStr = stringValue.substring(DOUBLE_PREFIX.length()); return Double.valueOf(doubleStr); } } else if (value instanceof Set) { // TODO (tarrinneal): Remove Set code. // https://github.com/flutter/flutter/issues/124420 // This only happens for previous usage of setStringSet. The app expects a list. @SuppressWarnings("unchecked") List<String> listValue = new ArrayList<>((Set<String>) value); // Let's migrate the value too while we are at it. preferences .edit() .remove(key) .putString(key, LIST_IDENTIFIER + listEncoder.encode(listValue)) .apply(); return listValue; } return value; } static class ListEncoder implements SharedPreferencesListEncoder { @Override public @NonNull String encode(@NonNull List<String> list) throws RuntimeException { try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ObjectOutputStream stream = new ObjectOutputStream(byteStream); stream.writeObject(list); stream.flush(); return Base64.encodeToString(byteStream.toByteArray(), 0); } catch (IOException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") @Override public @NonNull List<String> decode(@NonNull String listString) throws RuntimeException { try { ObjectInputStream stream = new ObjectInputStream(new ByteArrayInputStream(Base64.decode(listString, 0))); return (List<String>) stream.readObject(); } catch (IOException | ClassNotFoundException e) { throw new RuntimeException(e); } } } }
packages/packages/shared_preferences/shared_preferences_android/android/src/main/java/io/flutter/plugins/sharedpreferences/SharedPreferencesPlugin.java/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_android/android/src/main/java/io/flutter/plugins/sharedpreferences/SharedPreferencesPlugin.java", "repo_id": "packages", "token_count": 2841 }
1,282
name: shared_preferences_linux description: Linux implementation of the shared_preferences plugin repository: https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences_linux issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22 version: 2.3.2 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: shared_preferences platforms: linux: dartPluginClass: SharedPreferencesLinux dependencies: file: ">=6.0.0 <8.0.0" flutter: sdk: flutter path: ^1.8.0 path_provider_linux: ^2.0.0 path_provider_platform_interface: ^2.0.0 shared_preferences_platform_interface: ^2.3.0 dev_dependencies: flutter_test: sdk: flutter topics: - persistence - shared-preferences - storage
packages/packages/shared_preferences/shared_preferences_linux/pubspec.yaml/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_linux/pubspec.yaml", "repo_id": "packages", "token_count": 339 }
1,283
# Platform Implementation Test App This is a test app for manual testing and automated integration testing of this platform implementation. It is not intended to demonstrate actual use of this package, since the intent is that plugin clients use the app-facing package. Unless you are making changes to this implementation package, this example is very unlikely to be relevant. ## Testing This package uses `package:integration_test` to run its tests in a web browser. See [Plugin Tests > Web Tests](https://github.com/flutter/flutter/wiki/Plugin-Tests#web-tests) in the Flutter wiki for instructions to setup and run the tests in this package. Check [flutter.dev > Integration testing](https://flutter.dev/docs/testing/integration-tests) for more info.
packages/packages/shared_preferences/shared_preferences_web/example/README.md/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_web/example/README.md", "repo_id": "packages", "token_count": 186 }
1,284
// 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 RUNNER_FLUTTER_WINDOW_H_ #define RUNNER_FLUTTER_WINDOW_H_ #include <flutter/dart_project.h> #include <flutter/flutter_view_controller.h> #include <memory> #include "run_loop.h" #include "win32_window.h" // A window that does nothing but host a Flutter view. class FlutterWindow : public Win32Window { public: // Creates a new FlutterWindow driven by the |run_loop|, hosting a // Flutter view running |project|. explicit FlutterWindow(RunLoop* run_loop, const flutter::DartProject& project); virtual ~FlutterWindow(); protected: // Win32Window: bool OnCreate() override; void OnDestroy() override; LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept override; private: // The run loop driving events for this window. RunLoop* run_loop_; // The project to run. flutter::DartProject project_; // The Flutter instance hosted by this window. std::unique_ptr<flutter::FlutterViewController> flutter_controller_; }; #endif // RUNNER_FLUTTER_WINDOW_H_
packages/packages/shared_preferences/shared_preferences_windows/example/windows/runner/flutter_window.h/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_windows/example/windows/runner/flutter_window.h", "repo_id": "packages", "token_count": 437 }
1,285
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 0.0.1+4 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 0.0.1+3 * Minor README updates. ## 0.0.1+2 * Fixes lint warnings. ## 0.0.1+1 * Fixes minimum version of `test` dependency. ## 0.0.1 * Initial release of standard message codec extracted from the Flutter SDK.
packages/packages/standard_message_codec/CHANGELOG.md/0
{ "file_path": "packages/packages/standard_message_codec/CHANGELOG.md", "repo_id": "packages", "token_count": 146 }
1,286
name: table_view_example description: 'A sample application that uses TableView' publish_to: 'none' # The following defines the version and build number for your application. version: 1.0.0+1 environment: sdk: '>=3.2.0 <4.0.0' flutter: ">=3.16.0" dependencies: flutter: sdk: flutter two_dimensional_scrollables: path: ../ dev_dependencies: flutter_lints: ^2.0.0 flutter_test: sdk: flutter # The following section is specific to Flutter packages. flutter: uses-material-design: true
packages/packages/two_dimensional_scrollables/example/pubspec.yaml/0
{ "file_path": "packages/packages/two_dimensional_scrollables/example/pubspec.yaml", "repo_id": "packages", "token_count": 191 }
1,287
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:two_dimensional_scrollables/two_dimensional_scrollables.dart'; const TableSpan span = TableSpan(extent: FixedTableSpanExtent(50)); const TableViewCell cell = TableViewCell(child: SizedBox.shrink()); void main() { group('TableCellBuilderDelegate', () { test('exposes addAutomaticKeepAlives from super class', () { final TableCellBuilderDelegate delegate = TableCellBuilderDelegate( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 5, rowCount: 6, addAutomaticKeepAlives: false, ); expect(delegate.addAutomaticKeepAlives, isFalse); }); test('asserts valid counts for rows and columns', () { TableCellBuilderDelegate? delegate; expect( () { delegate = TableCellBuilderDelegate( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 1, rowCount: 1, pinnedColumnCount: -1, // asserts ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('pinnedColumnCount >= 0'), ), ), ); expect( () { delegate = TableCellBuilderDelegate( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 1, rowCount: 1, pinnedRowCount: -1, // asserts ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('pinnedRowCount >= 0'), ), ), ); expect( () { delegate = TableCellBuilderDelegate( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 1, rowCount: -1, // asserts ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('rowCount >= 0'), ), ), ); expect( () { delegate = TableCellBuilderDelegate( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: -1, // asserts rowCount: 1, ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('columnCount >= 0'), ), ), ); expect( () { delegate = TableCellBuilderDelegate( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 1, pinnedColumnCount: 2, // asserts rowCount: 1, ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('pinnedColumnCount <= columnCount'), ), ), ); expect( () { delegate = TableCellBuilderDelegate( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 1, pinnedRowCount: 2, // asserts rowCount: 1, ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('pinnedRowCount <= rowCount'), ), ), ); expect(delegate, isNull); }); test('sets max x and y index of super class', () { final TableCellBuilderDelegate delegate = TableCellBuilderDelegate( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 5, rowCount: 6, ); expect(delegate.maxYIndex, 5); // rows expect(delegate.maxXIndex, 4); // columns }); test('Respects super class default for addRepaintBoundaries', () { final TableCellBuilderDelegate delegate = TableCellBuilderDelegate( cellBuilder: (_, __) => cell, columnBuilder: (_) => span, rowBuilder: (_) => span, columnCount: 1, rowCount: 1, ); expect(delegate.addRepaintBoundaries, isFalse); expect(cell.addRepaintBoundaries, isTrue); }); test('Notifies listeners & rebuilds', () { int notified = 0; TableCellBuilderDelegate oldDelegate; TableSpan spanBuilder(int index) => span; TableViewCell cellBuilder(BuildContext context, TableVicinity vicinity) { return cell; } final TableCellBuilderDelegate delegate = TableCellBuilderDelegate( cellBuilder: cellBuilder, columnBuilder: spanBuilder, rowBuilder: spanBuilder, columnCount: 5, pinnedColumnCount: 1, rowCount: 6, pinnedRowCount: 2, ); delegate.addListener(() { notified++; }); // change column count oldDelegate = delegate; delegate.columnCount = 6; expect(notified, 1); expect(delegate.shouldRebuild(oldDelegate), isTrue); // change pinned column count oldDelegate = delegate; delegate.pinnedColumnCount = 2; expect(notified, 2); expect(delegate.shouldRebuild(oldDelegate), isTrue); // change row count oldDelegate = delegate; delegate.rowCount = 7; expect(notified, 3); expect(delegate.shouldRebuild(oldDelegate), isTrue); // change pinned row count oldDelegate = delegate; delegate.pinnedRowCount = 3; expect(notified, 4); expect(delegate.shouldRebuild(oldDelegate), isTrue); // Builder delegate always returns true. expect(delegate.shouldRebuild(delegate), isTrue); }); }); group('TableCellListDelegate', () { test('exposes addAutomaticKeepAlives from super class', () { final TableCellListDelegate delegate = TableCellListDelegate( cells: <List<TableViewCell>>[<TableViewCell>[]], columnBuilder: (_) => span, rowBuilder: (_) => span, addAutomaticKeepAlives: false, ); expect(delegate.addAutomaticKeepAlives, isFalse); }); test('asserts valid counts for rows and columns', () { TableCellListDelegate? delegate; expect( () { delegate = TableCellListDelegate( cells: <List<TableViewCell>>[<TableViewCell>[]], columnBuilder: (_) => span, rowBuilder: (_) => span, pinnedColumnCount: -1, // asserts ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('pinnedColumnCount >= 0'), ), ), ); expect( () { delegate = TableCellListDelegate( cells: <List<TableViewCell>>[<TableViewCell>[]], columnBuilder: (_) => span, rowBuilder: (_) => span, pinnedRowCount: -1, // asserts ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('pinnedRowCount >= 0'), ), ), ); expect( () { delegate = TableCellListDelegate( cells: <List<TableViewCell>>[ <TableViewCell>[cell, cell], <TableViewCell>[cell, cell], ], columnBuilder: (_) => span, rowBuilder: (_) => span, pinnedRowCount: 3, // asserts ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('rowCount >= pinnedRowCount'), ), ), ); expect( () { delegate = TableCellListDelegate( cells: <List<TableViewCell>>[ <TableViewCell>[cell, cell], <TableViewCell>[cell, cell], ], columnBuilder: (_) => span, rowBuilder: (_) => span, pinnedColumnCount: 3, // asserts ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('columnCount >= pinnedColumnCount'), ), ), ); expect(delegate, isNull); }); test('Asserts child lists lengths match', () { TableCellListDelegate? delegate; expect( () { delegate = TableCellListDelegate( cells: <List<TableViewCell>>[ <TableViewCell>[cell, cell], <TableViewCell>[cell, cell, cell], ], columnBuilder: (_) => span, rowBuilder: (_) => span, ); }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains( 'Each list of Widgets within cells must be of the same length.'), ), ), ); expect(delegate, isNull); }); test('Notifies listeners & rebuilds', () { int notified = 0; TableCellListDelegate oldDelegate; TableSpan spanBuilder(int index) => span; TableCellListDelegate delegate = TableCellListDelegate( cells: <List<TableViewCell>>[ <TableViewCell>[cell, cell], <TableViewCell>[cell, cell], ], columnBuilder: spanBuilder, rowBuilder: spanBuilder, pinnedColumnCount: 1, pinnedRowCount: 1, ); delegate.addListener(() { notified++; }); // change pinned column count oldDelegate = delegate; delegate.pinnedColumnCount = 0; expect(notified, 1); // change pinned row count oldDelegate = delegate; delegate.pinnedRowCount = 0; expect(notified, 2); // shouldRebuild // columnCount oldDelegate = delegate; delegate = TableCellListDelegate( cells: <List<TableViewCell>>[ <TableViewCell>[cell, cell, cell], <TableViewCell>[cell, cell, cell], ], columnBuilder: spanBuilder, rowBuilder: spanBuilder, ); expect(delegate.shouldRebuild(oldDelegate), isTrue); // columnBuilder oldDelegate = delegate; delegate = TableCellListDelegate( cells: <List<TableViewCell>>[ <TableViewCell>[cell, cell, cell], <TableViewCell>[cell, cell, cell], ], columnBuilder: (int index) => const TableSpan( extent: FixedTableSpanExtent(150), ), rowBuilder: spanBuilder, ); expect(delegate.shouldRebuild(oldDelegate), isTrue); // rowCount oldDelegate = delegate; delegate = TableCellListDelegate( cells: <List<TableViewCell>>[ <TableViewCell>[cell, cell, cell], <TableViewCell>[cell, cell, cell], <TableViewCell>[cell, cell, cell], ], columnBuilder: (int index) => const TableSpan( extent: FixedTableSpanExtent(150), ), rowBuilder: spanBuilder, ); expect(delegate.shouldRebuild(oldDelegate), isTrue); // rowBuilder oldDelegate = delegate; delegate = TableCellListDelegate( cells: <List<TableViewCell>>[ <TableViewCell>[cell, cell, cell], <TableViewCell>[cell, cell, cell], <TableViewCell>[cell, cell, cell], ], columnBuilder: (int index) => const TableSpan( extent: FixedTableSpanExtent(150), ), rowBuilder: (int index) => const TableSpan( extent: RemainingTableSpanExtent(), ), ); expect(delegate.shouldRebuild(oldDelegate), isTrue); // pinned row count oldDelegate = delegate; delegate = TableCellListDelegate( cells: <List<TableViewCell>>[ <TableViewCell>[cell, cell, cell], <TableViewCell>[cell, cell, cell], <TableViewCell>[cell, cell, cell], ], columnBuilder: (int index) => const TableSpan( extent: FixedTableSpanExtent(150), ), rowBuilder: (int index) => const TableSpan( extent: RemainingTableSpanExtent(), ), pinnedRowCount: 2, ); expect(delegate.shouldRebuild(oldDelegate), isTrue); // pinned column count oldDelegate = delegate; delegate = TableCellListDelegate( cells: <List<TableViewCell>>[ <TableViewCell>[cell, cell, cell], <TableViewCell>[cell, cell, cell], <TableViewCell>[cell, cell, cell], ], columnBuilder: (int index) => const TableSpan( extent: FixedTableSpanExtent(150), ), rowBuilder: (int index) => const TableSpan( extent: RemainingTableSpanExtent(), ), pinnedColumnCount: 2, pinnedRowCount: 2, ); expect(delegate.shouldRebuild(oldDelegate), isTrue); // Nothing changed expect(delegate.shouldRebuild(delegate), isFalse); }); test('Changing pinned row and column counts asserts valid values', () { final TableCellListDelegate delegate = TableCellListDelegate( cells: <List<TableViewCell>>[ <TableViewCell>[cell, cell, cell], <TableViewCell>[cell, cell, cell], <TableViewCell>[cell, cell, cell], ], columnBuilder: (int index) => const TableSpan( extent: FixedTableSpanExtent(150), ), rowBuilder: (int index) => const TableSpan( extent: RemainingTableSpanExtent(), ), pinnedColumnCount: 2, pinnedRowCount: 2, ); expect( () { delegate.pinnedColumnCount = -1; }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('value >= 0'), ), ), ); expect( () { delegate.pinnedRowCount = -1; }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('value >= 0'), ), ), ); expect( () { delegate.pinnedColumnCount = 4; }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('value <= columnCount'), ), ), ); expect( () { delegate.pinnedRowCount = 4; }, throwsA( isA<AssertionError>().having( (AssertionError error) => error.toString(), 'description', contains('value <= rowCount'), ), ), ); }); }); }
packages/packages/two_dimensional_scrollables/test/table_view/table_delegate_test.dart/0
{ "file_path": "packages/packages/two_dimensional_scrollables/test/table_view/table_delegate_test.dart", "repo_id": "packages", "token_count": 7454 }
1,288
{ "name": "url_launcher example", "short_name": "url_launcher", "start_url": ".", "display": "minimal-ui", "background_color": "#0175C2", "theme_color": "#0175C2", "description": "An example of the url_launcher on the web.", "orientation": "portrait-primary", "prefer_related_applications": false, "icons": [ { "src": "icons/Icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icons/Icon-512.png", "sizes": "512x512", "type": "image/png" } ] }
packages/packages/url_launcher/url_launcher/example/web/manifest.json/0
{ "file_path": "packages/packages/url_launcher/url_launcher/example/web/manifest.json", "repo_id": "packages", "token_count": 316 }
1,289
// 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 RUNNER_UTILS_H_ #define RUNNER_UTILS_H_ // Creates a console for the process, and redirects stdout and stderr to // it for both the runner and the Flutter library. void CreateAndAttachConsole(); #endif // RUNNER_UTILS_H_
packages/packages/url_launcher/url_launcher/example/windows/runner/utils.h/0
{ "file_path": "packages/packages/url_launcher/url_launcher/example/windows/runner/utils.h", "repo_id": "packages", "token_count": 121 }
1,290
// 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_string.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; group('canLaunchUrlString', () { test('handles returning true', () async { const String urlString = 'https://flutter.dev'; mock ..setCanLaunchExpectations(urlString) ..setResponse(true); final bool result = await canLaunchUrlString(urlString); expect(result, isTrue); }); test('handles returning false', () async { const String urlString = 'https://flutter.dev'; mock ..setCanLaunchExpectations(urlString) ..setResponse(false); final bool result = await canLaunchUrlString(urlString); expect(result, isFalse); }); }); group('launchUrlString', () { test('default behavior with web URL', () async { const String urlString = 'https://flutter.dev'; mock ..setLaunchExpectations( url: urlString, launchMode: PreferredLaunchMode.platformDefault, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect(await launchUrlString(urlString), isTrue); }); test('default behavior with non-web URL', () async { const String urlString = 'customscheme:foo'; mock ..setLaunchExpectations( url: urlString, launchMode: PreferredLaunchMode.platformDefault, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect(await launchUrlString(urlString), isTrue); }); test('explicit default launch mode with web URL', () async { const String urlString = 'https://flutter.dev'; mock ..setLaunchExpectations( url: urlString, launchMode: PreferredLaunchMode.platformDefault, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect(await launchUrlString(urlString), isTrue); }); test('explicit default launch mode with non-web URL', () async { const String urlString = 'customscheme:foo'; mock ..setLaunchExpectations( url: urlString, launchMode: PreferredLaunchMode.platformDefault, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect(await launchUrlString(urlString), isTrue); }); test('in-app webview', () async { const String urlString = 'https://flutter.dev'; mock ..setLaunchExpectations( url: urlString, launchMode: PreferredLaunchMode.inAppWebView, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect(await launchUrlString(urlString, mode: LaunchMode.inAppWebView), isTrue); }); test('external browser', () async { const String urlString = 'https://flutter.dev'; mock ..setLaunchExpectations( url: urlString, launchMode: PreferredLaunchMode.externalApplication, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect( await launchUrlString(urlString, mode: LaunchMode.externalApplication), isTrue); }); test('external non-browser only', () async { const String urlString = 'https://flutter.dev'; mock ..setLaunchExpectations( url: urlString, launchMode: PreferredLaunchMode.externalNonBrowserApplication, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: true, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect( await launchUrlString(urlString, mode: LaunchMode.externalNonBrowserApplication), isTrue); }); test('in-app webview without javascript', () async { const String urlString = 'https://flutter.dev'; mock ..setLaunchExpectations( url: urlString, launchMode: PreferredLaunchMode.inAppWebView, enableJavaScript: false, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect( await launchUrlString(urlString, mode: LaunchMode.inAppWebView, webViewConfiguration: const WebViewConfiguration(enableJavaScript: false)), isTrue); }); test('in-app webview without DOM storage', () async { const String urlString = 'https://flutter.dev'; mock ..setLaunchExpectations( url: urlString, launchMode: PreferredLaunchMode.inAppWebView, enableJavaScript: true, enableDomStorage: false, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect( await launchUrlString(urlString, mode: LaunchMode.inAppWebView, webViewConfiguration: const WebViewConfiguration(enableDomStorage: false)), isTrue); }); test('in-app webview with headers', () async { const String urlString = 'https://flutter.dev'; mock ..setLaunchExpectations( url: urlString, launchMode: PreferredLaunchMode.inAppWebView, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{'key': 'value'}, webOnlyWindowName: null, ) ..setResponse(true); expect( await launchUrlString(urlString, 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 => launchUrlString('tel:555-555-5555', mode: LaunchMode.inAppWebView), throwsA(isA<ArgumentError>())); }); test('non-web URL with default options', () async { const String emailLaunchUrlString = 'mailto:[email protected]?subject=Hello'; mock ..setLaunchExpectations( url: emailLaunchUrlString, launchMode: PreferredLaunchMode.platformDefault, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect(await launchUrlString(emailLaunchUrlString), isTrue); }); test('allows non-parsable url', () async { // Not a valid Dart [Uri], but a valid URL on at least some platforms. const String urlString = 'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1'; mock ..setLaunchExpectations( url: urlString, launchMode: PreferredLaunchMode.platformDefault, enableJavaScript: true, enableDomStorage: true, universalLinksOnly: false, headers: <String, String>{}, webOnlyWindowName: null, ) ..setResponse(true); expect(await launchUrlString(urlString), isTrue); }); }); }
packages/packages/url_launcher/url_launcher/test/src/url_launcher_string_test.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher/test/src/url_launcher_string_test.dart", "repo_id": "packages", "token_count": 3710 }
1,291
// 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> { final UrlLauncherPlatform launcher = UrlLauncherPlatform.instance; bool _hasCallSupport = false; bool _hasCustomTabSupport = false; Future<void>? _launched; String _phone = ''; @override void initState() { super.initState(); // Check for phone call support. launcher.canLaunch('tel:123').then((bool result) { setState(() { _hasCallSupport = result; }); }); // Check for Android Custom Tab support. launcher .supportsMode(PreferredLaunchMode.inAppBrowserView) .then((bool result) { setState(() { _hasCustomTabSupport = result; }); }); } Future<void> _launchInBrowser(String url) async { if (!await launcher.launchUrl( url, const LaunchOptions(mode: PreferredLaunchMode.externalApplication), )) { throw Exception('Could not launch $url'); } } Future<void> _launchInCustomTab(String url) async { if (!await launcher.launchUrl( url, const LaunchOptions(mode: PreferredLaunchMode.inAppBrowserView), )) { throw Exception('Could not launch $url'); } } Future<void> _launchInWebView(String url) async { if (!await launcher.launchUrl( url, const LaunchOptions(mode: PreferredLaunchMode.inAppWebView), )) { throw Exception('Could not launch $url'); } } Future<void> _launchInWebViewWithCustomHeaders(String url) async { if (!await launcher.launchUrl( url, const LaunchOptions( mode: PreferredLaunchMode.inAppWebView, webViewConfiguration: InAppWebViewConfiguration( headers: <String, String>{'my_header_key': 'my_header_value'}, )), )) { throw Exception('Could not launch $url'); } } Future<void> _launchInWebViewWithoutJavaScript(String url) async { if (!await launcher.launchUrl( url, const LaunchOptions( mode: PreferredLaunchMode.inAppWebView, webViewConfiguration: InAppWebViewConfiguration( enableJavaScript: false, )), )) { throw Exception('Could not launch $url'); } } Future<void> _launchInWebViewWithoutDomStorage(String url) async { if (!await launcher.launchUrl( url, const LaunchOptions( mode: PreferredLaunchMode.inAppWebView, webViewConfiguration: InAppWebViewConfiguration( enableDomStorage: false, )), )) { throw Exception('Could not launch $url'); } } Widget _launchStatus(BuildContext context, AsyncSnapshot<void> snapshot) { if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { return const Text(''); } } Future<void> _makePhoneCall(String phoneNumber) async { // Use `Uri` to ensure that `phoneNumber` is properly URL-encoded. // Just using 'tel:$phoneNumber' would create invalid URLs in some cases. final Uri launchUri = Uri( scheme: 'tel', path: phoneNumber, ); await launcher.launchUrl(launchUri.toString(), const LaunchOptions()); } @override Widget build(BuildContext context) { // onPressed calls using this URL are not gated on a 'canLaunch' check // because the assumption is that every device can launch a web URL. 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: _hasCallSupport ? () => setState(() { _launched = _makePhoneCall(_phone); }) : null, child: _hasCallSupport ? const Text('Make phone call') : const Text('Calling not supported'), ), const Padding( padding: EdgeInsets.all(16.0), child: Text(toLaunch), ), ElevatedButton( onPressed: _hasCustomTabSupport ? () => setState(() { _launched = _launchInBrowser(toLaunch); }) : null, child: const Text('Launch in browser'), ), const Padding(padding: EdgeInsets.all(16.0)), ElevatedButton( onPressed: () => setState(() { _launched = _launchInCustomTab(toLaunch); }), child: const Text('Launch in Android Custom Tab'), ), const Padding(padding: EdgeInsets.all(16.0)), ElevatedButton( onPressed: () => setState(() { _launched = _launchInWebView(toLaunch); }), child: const Text('Launch in web view'), ), ElevatedButton( onPressed: () => setState(() { _launched = _launchInWebViewWithCustomHeaders(toLaunch); }), child: const Text('Launch in web view (Custom headers)'), ), ElevatedButton( onPressed: () => setState(() { _launched = _launchInWebViewWithoutJavaScript(toLaunch); }), child: const Text('Launch in web view (JavaScript OFF)'), ), ElevatedButton( onPressed: () => setState(() { _launched = _launchInWebViewWithoutDomStorage(toLaunch); }), child: const Text('Launch in web view (DOM storage OFF)'), ), const Padding(padding: EdgeInsets.all(16.0)), ElevatedButton( onPressed: () => setState(() { _launched = _launchInWebView(toLaunch); Timer(const Duration(seconds: 5), () { launcher.closeWebView(); }); }), child: const Text('Launch in web view + close after 5 seconds'), ), const Padding(padding: EdgeInsets.all(16.0)), FutureBuilder<void>(future: _launched, builder: _launchStatus), ], ), ], ), ); } }
packages/packages/url_launcher/url_launcher_android/example/lib/main.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_android/example/lib/main.dart", "repo_id": "packages", "token_count": 3524 }
1,292
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import XCTest class URLLauncherUITests: XCTestCase { var app: XCUIApplication! override func setUp() { continueAfterFailure = false app = XCUIApplication() app.launch() } func testLaunch() { let app = self.app! let buttonNames: [String] = [ "Launch in app", "Launch in app(JavaScript ON)", "Launch in app(DOM storage ON)", "Launch a universal link in a native app, fallback to Safari.(Youtube)", ] for buttonName in buttonNames { let button = app.buttons[buttonName] XCTAssertTrue(button.waitForExistence(timeout: 30.0)) XCTAssertEqual(app.webViews.count, 0) button.tap() let webView = app.webViews.firstMatch XCTAssertTrue(webView.waitForExistence(timeout: 30.0)) XCTAssertTrue(app.buttons["ForwardButton"].waitForExistence(timeout: 30.0)) XCTAssertTrue(app.buttons["Share"].exists) XCTAssertTrue(app.buttons["OpenInSafariButton"].exists) let doneButton = app.buttons["Done"] XCTAssertTrue(doneButton.waitForExistence(timeout: 30.0)) // This should just be doneButton.tap, but for some reason that stopped working in Xcode 15; // tapping via coordinate works, however. doneButton.coordinate(withNormalizedOffset: CGVector()).withOffset(CGVector(dx: 10, dy: 10)) .tap() } } }
packages/packages/url_launcher/url_launcher_ios/example/ios/RunnerUITests/URLLauncherUITests.swift/0
{ "file_path": "packages/packages/url_launcher/url_launcher_ios/example/ios/RunnerUITests/URLLauncherUITests.swift", "repo_id": "packages", "token_count": 558 }
1,293
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:url_launcher_ios/src/messages.g.dart'; import 'package:url_launcher_ios/url_launcher_ios.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import 'url_launcher_ios_test.mocks.dart'; // A web URL to use in tests where the specifics of the URL don't matter. const String _webUrl = 'https://example.com/'; @GenerateMocks(<Type>[UrlLauncherApi]) void main() { late MockUrlLauncherApi api; setUp(() { api = MockUrlLauncherApi(); }); test('registers instance', () { UrlLauncherIOS.registerWith(); expect(UrlLauncherPlatform.instance, isA<UrlLauncherIOS>()); }); group('canLaunch', () { test('handles success', () async { when(api.canLaunchUrl(_webUrl)) .thenAnswer((_) async => LaunchResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect(await launcher.canLaunch(_webUrl), true); }); test('handles failure', () async { when(api.canLaunchUrl(_webUrl)) .thenAnswer((_) async => LaunchResult.failure); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect(await launcher.canLaunch(_webUrl), false); }); test('throws PlatformException for invalid URL', () async { when(api.canLaunchUrl(_webUrl)) .thenAnswer((_) async => LaunchResult.invalidUrl); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); await expectLater( launcher.canLaunch(_webUrl), throwsA(isA<PlatformException>().having( (PlatformException e) => e.code, 'code', 'argument_error'))); }); }); group('legacy launch', () { test('handles success', () async { when(api.launchUrl(_webUrl, any)) .thenAnswer((_) async => LaunchResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( await launcher.launch( _webUrl, useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ), true); verifyNever(api.openUrlInSafariViewController(any)); }); test('handles failure', () async { when(api.launchUrl(_webUrl, any)) .thenAnswer((_) async => LaunchResult.failure); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( await launcher.launch( _webUrl, useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ), false); verifyNever(api.openUrlInSafariViewController(any)); }); test('throws PlatformException for invalid URL', () async { when(api.launchUrl(_webUrl, any)) .thenAnswer((_) async => LaunchResult.invalidUrl); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); await expectLater( launcher.launch( _webUrl, useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ), throwsA(isA<PlatformException>().having( (PlatformException e) => e.code, 'code', 'argument_error'))); }); test('force SafariVC is handled', () async { when(api.openUrlInSafariViewController(_webUrl)) .thenAnswer((_) async => InAppLoadResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( await launcher.launch( _webUrl, useSafariVC: true, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ), true); verifyNever(api.launchUrl(any, any)); }); test('universal links only is handled', () async { when(api.launchUrl(_webUrl, any)) .thenAnswer((_) async => LaunchResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( await launcher.launch( _webUrl, useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: true, headers: const <String, String>{}, ), true); verifyNever(api.openUrlInSafariViewController(any)); }); test('disallowing SafariVC is handled', () async { when(api.launchUrl(_webUrl, any)) .thenAnswer((_) async => LaunchResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( await launcher.launch( _webUrl, useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ), true); verifyNever(api.openUrlInSafariViewController(any)); }); }); test('closeWebView calls through', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); await launcher.closeWebView(); verify(api.closeSafariViewController()).called(1); }); group('launch without webview', () { test('calls through', () async { when(api.launchUrl(_webUrl, any)) .thenAnswer((_) async => LaunchResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); final bool launched = await launcher.launchUrl( _webUrl, const LaunchOptions(mode: PreferredLaunchMode.externalApplication), ); expect(launched, true); verifyNever(api.openUrlInSafariViewController(any)); }); test('throws PlatformException for invalid URL', () async { when(api.launchUrl(_webUrl, any)) .thenAnswer((_) async => LaunchResult.invalidUrl); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); await expectLater( launcher.launchUrl( _webUrl, const LaunchOptions(mode: PreferredLaunchMode.externalApplication), ), throwsA(isA<PlatformException>().having( (PlatformException e) => e.code, 'code', 'argument_error'))); }); }); group('launch with Safari view controller', () { test('calls through with inAppWebView', () async { when(api.openUrlInSafariViewController(_webUrl)) .thenAnswer((_) async => InAppLoadResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); final bool launched = await launcher.launchUrl( _webUrl, const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)); expect(launched, true); verifyNever(api.launchUrl(any, any)); }); test('calls through with inAppBrowserView', () async { when(api.openUrlInSafariViewController(_webUrl)) .thenAnswer((_) async => InAppLoadResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); final bool launched = await launcher.launchUrl(_webUrl, const LaunchOptions(mode: PreferredLaunchMode.inAppBrowserView)); expect(launched, true); verifyNever(api.launchUrl(any, any)); }); test('throws PlatformException for invalid URL', () async { when(api.openUrlInSafariViewController(_webUrl)) .thenAnswer((_) async => InAppLoadResult.invalidUrl); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); await expectLater( launcher.launchUrl(_webUrl, const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)), throwsA(isA<PlatformException>().having( (PlatformException e) => e.code, 'code', 'argument_error'))); }); test('throws PlatformException for load failure', () async { when(api.openUrlInSafariViewController(_webUrl)) .thenAnswer((_) async => InAppLoadResult.failedToLoad); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); await expectLater( launcher.launchUrl(_webUrl, const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)), throwsA(isA<PlatformException>() .having((PlatformException e) => e.code, 'code', 'Error'))); }); }); group('launch with universal links', () { test('calls through', () async { when(api.launchUrl(_webUrl, any)) .thenAnswer((_) async => LaunchResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); final bool launched = await launcher.launchUrl( _webUrl, const LaunchOptions( mode: PreferredLaunchMode.externalNonBrowserApplication), ); expect(launched, true); verifyNever(api.openUrlInSafariViewController(any)); }); test('throws PlatformException for invalid URL', () async { when(api.launchUrl(_webUrl, any)) .thenAnswer((_) async => LaunchResult.invalidUrl); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); await expectLater( launcher.launchUrl( _webUrl, const LaunchOptions( mode: PreferredLaunchMode.externalNonBrowserApplication)), throwsA(isA<PlatformException>().having( (PlatformException e) => e.code, 'code', 'argument_error'))); }); }); group('launch with platform default', () { test('uses Safari view controller for http', () async { const String httpUrl = 'http://example.com/'; when(api.openUrlInSafariViewController(httpUrl)) .thenAnswer((_) async => InAppLoadResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); final bool launched = await launcher.launchUrl(httpUrl, const LaunchOptions()); expect(launched, true); verifyNever(api.launchUrl(any, any)); }); test('uses Safari view controller for https', () async { const String httpsUrl = 'https://example.com/'; when(api.openUrlInSafariViewController(httpsUrl)) .thenAnswer((_) async => InAppLoadResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); final bool launched = await launcher.launchUrl(httpsUrl, const LaunchOptions()); expect(launched, true); verifyNever(api.launchUrl(any, any)); }); test('uses standard external for other schemes', () async { const String nonWebUrl = 'supportedcustomscheme://example.com/'; when(api.launchUrl(nonWebUrl, any)) .thenAnswer((_) async => LaunchResult.success); final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); final bool launched = await launcher.launchUrl(nonWebUrl, const LaunchOptions()); expect(launched, true); verifyNever(api.openUrlInSafariViewController(any)); }); }); group('supportsMode', () { test('returns true for platformDefault', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), true); }); test('returns true for external application', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( await launcher.supportsMode(PreferredLaunchMode.externalApplication), true); }); test('returns true for external non-browser application', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( await launcher .supportsMode(PreferredLaunchMode.externalNonBrowserApplication), true); }); test('returns true for in app web view', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( await launcher.supportsMode(PreferredLaunchMode.inAppWebView), true); }); test('returns true for in app browser view', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), true); }); }); group('supportsCloseForMode', () { test('returns true for in app web view', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( await launcher.supportsCloseForMode(PreferredLaunchMode.inAppWebView), true); }); test('returns true for in app browser view', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( await launcher .supportsCloseForMode(PreferredLaunchMode.inAppBrowserView), true); }); test('returns false for other modes', () async { final UrlLauncherIOS launcher = UrlLauncherIOS(api: api); expect( await launcher .supportsCloseForMode(PreferredLaunchMode.externalApplication), false); expect( await launcher.supportsCloseForMode( PreferredLaunchMode.externalNonBrowserApplication), false); }); }); }
packages/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.dart", "repo_id": "packages", "token_count": 5600 }
1,294
# # Generated file, do not edit. # list(APPEND FLUTTER_PLUGIN_LIST url_launcher_linux ) list(APPEND FLUTTER_FFI_PLUGIN_LIST ) set(PLUGIN_BUNDLED_LIBRARIES) foreach(plugin ${FLUTTER_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) endforeach(plugin) foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) endforeach(ffi_plugin)
packages/packages/url_launcher/url_launcher_linux/example/linux/flutter/generated_plugins.cmake/0
{ "file_path": "packages/packages/url_launcher/url_launcher_linux/example/linux/flutter/generated_plugins.cmake", "repo_id": "packages", "token_count": 320 }
1,295
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_macos: # When depending on this package from a real application you should use: # url_launcher_macos: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ url_launcher_platform_interface: ^2.2.0 dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true
packages/packages/url_launcher/url_launcher_macos/example/pubspec.yaml/0
{ "file_path": "packages/packages/url_launcher/url_launcher_macos/example/pubspec.yaml", "repo_id": "packages", "token_count": 267 }
1,296
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart'; import 'link.dart'; import 'url_launcher_platform_interface.dart'; const MethodChannel _channel = MethodChannel('plugins.flutter.io/url_launcher'); /// An implementation of [UrlLauncherPlatform] that uses method channels. class MethodChannelUrlLauncher extends UrlLauncherPlatform { @override final LinkDelegate? linkDelegate = null; @override Future<bool> canLaunch(String url) { return _channel.invokeMethod<bool>( 'canLaunch', <String, Object>{'url': url}, ).then((bool? value) => value ?? false); } @override Future<void> closeWebView() { return _channel.invokeMethod<void>('closeWebView'); } @override Future<bool> launch( String url, { required bool useSafariVC, required bool useWebView, required bool enableJavaScript, required bool enableDomStorage, required bool universalLinksOnly, required Map<String, String> headers, String? webOnlyWindowName, }) { return _channel.invokeMethod<bool>( 'launch', <String, Object>{ 'url': url, 'useSafariVC': useSafariVC, 'useWebView': useWebView, 'enableJavaScript': enableJavaScript, 'enableDomStorage': enableDomStorage, 'universalLinksOnly': universalLinksOnly, 'headers': headers, }, ).then((bool? value) => value ?? false); } }
packages/packages/url_launcher/url_launcher_platform_interface/lib/method_channel_url_launcher.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_platform_interface/lib/method_channel_url_launcher.dart", "repo_id": "packages", "token_count": 553 }
1,297
// 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:js_interop'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:mockito/mockito.dart' show Mock, any, verify, when; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import 'package:url_launcher_web/url_launcher_web.dart'; import 'package:web/web.dart' as html; abstract class MyWindow { html.Window? open(Object? a, Object? b, Object? c); html.Navigator? get navigator; } @JSExport() class MockWindow extends Mock implements MyWindow {} abstract class MyNavigator { String? get userAgent; } @JSExport() class MockNavigator extends Mock implements MyNavigator {} void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('UrlLauncherPlugin', () { late MockWindow mockWindow; late MockNavigator mockNavigator; late html.Window jsMockWindow; late UrlLauncherPlugin plugin; setUp(() { mockWindow = MockWindow(); mockNavigator = MockNavigator(); jsMockWindow = createJSInteropWrapper(mockWindow) as html.Window; final html.Navigator jsMockNavigator = createJSInteropWrapper(mockNavigator) as html.Navigator; when(mockWindow.navigator).thenReturn(jsMockNavigator); // Simulate that window.open does something. when(mockWindow.open(any, any, any)).thenReturn(jsMockWindow); when(mockNavigator.userAgent).thenReturn( 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'); plugin = UrlLauncherPlugin(debugWindow: jsMockWindow); }); group('canLaunch', () { testWidgets('"http" URLs -> true', (WidgetTester _) async { expect(plugin.canLaunch('http://google.com'), completion(isTrue)); }); testWidgets('"https" URLs -> true', (WidgetTester _) async { expect(plugin.canLaunch('https://google.com'), completion(isTrue)); }); testWidgets('"mailto" URLs -> true', (WidgetTester _) async { expect( plugin.canLaunch('mailto:[email protected]'), completion(isTrue)); }); testWidgets('"tel" URLs -> true', (WidgetTester _) async { expect(plugin.canLaunch('tel:5551234567'), completion(isTrue)); }); testWidgets('"sms" URLs -> true', (WidgetTester _) async { expect(plugin.canLaunch('sms:+19725551212?body=hello%20there'), completion(isTrue)); }); testWidgets('"javascript" URLs -> false', (WidgetTester _) async { expect(plugin.canLaunch('javascript:alert("1")'), completion(isFalse)); }); }); group('launch', () { testWidgets('launching a URL returns true', (WidgetTester _) async { expect( plugin.launch( 'https://www.google.com', ), completion(isTrue)); }); testWidgets('launching a "mailto" returns true', (WidgetTester _) async { expect( plugin.launch( 'mailto:[email protected]', ), completion(isTrue)); }); testWidgets('launching a "tel" returns true', (WidgetTester _) async { expect( plugin.launch( 'tel:5551234567', ), completion(isTrue)); }); testWidgets('launching a "sms" returns true', (WidgetTester _) async { expect( plugin.launch( 'sms:+19725551212?body=hello%20there', ), completion(isTrue)); }); testWidgets('launching a "javascript" returns false', (WidgetTester _) async { expect(plugin.launch('javascript:alert("1")'), completion(isFalse)); }); }); group('openNewWindow', () { testWidgets('http urls should be launched in a new window', (WidgetTester _) async { plugin.openNewWindow('http://www.google.com'); verify(mockWindow.open( 'http://www.google.com', '', 'noopener,noreferrer')); }); testWidgets('https urls should be launched in a new window', (WidgetTester _) async { plugin.openNewWindow('https://www.google.com'); verify(mockWindow.open( 'https://www.google.com', '', 'noopener,noreferrer')); }); testWidgets('mailto urls should be launched on a new window', (WidgetTester _) async { plugin.openNewWindow('mailto:[email protected]'); verify(mockWindow.open( 'mailto:[email protected]', '', 'noopener,noreferrer')); }); testWidgets('tel urls should be launched on a new window', (WidgetTester _) async { plugin.openNewWindow('tel:5551234567'); verify(mockWindow.open('tel:5551234567', '', 'noopener,noreferrer')); }); testWidgets('sms urls should be launched on a new window', (WidgetTester _) async { plugin.openNewWindow('sms:+19725551212?body=hello%20there'); verify(mockWindow.open( 'sms:+19725551212?body=hello%20there', '', 'noopener,noreferrer')); }); testWidgets( 'setting webOnlyLinkTarget as _self opens the url in the same tab', (WidgetTester _) async { plugin.openNewWindow('https://www.google.com', webOnlyWindowName: '_self'); verify(mockWindow.open( 'https://www.google.com', '_self', 'noopener,noreferrer')); }); testWidgets( 'setting webOnlyLinkTarget as _blank opens the url in a new tab', (WidgetTester _) async { plugin.openNewWindow('https://www.google.com', webOnlyWindowName: '_blank'); verify(mockWindow.open( 'https://www.google.com', '_blank', 'noopener,noreferrer')); }); group('Safari', () { setUp(() { when(mockNavigator.userAgent).thenReturn( 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5.1 Safari/605.1.15'); // Recreate the plugin, so it grabs the overrides from this group plugin = UrlLauncherPlugin(debugWindow: jsMockWindow); }); testWidgets('http urls should be launched in a new window', (WidgetTester _) async { plugin.openNewWindow('http://www.google.com'); verify(mockWindow.open( 'http://www.google.com', '', 'noopener,noreferrer')); }); testWidgets('https urls should be launched in a new window', (WidgetTester _) async { plugin.openNewWindow('https://www.google.com'); verify(mockWindow.open( 'https://www.google.com', '', 'noopener,noreferrer')); }); testWidgets('mailto urls should be launched on the same window', (WidgetTester _) async { plugin.openNewWindow('mailto:[email protected]'); verify(mockWindow.open( 'mailto:[email protected]', '_top', 'noopener,noreferrer')); }); testWidgets('tel urls should be launched on the same window', (WidgetTester _) async { plugin.openNewWindow('tel:5551234567'); verify( mockWindow.open('tel:5551234567', '_top', 'noopener,noreferrer')); }); testWidgets('sms urls should be launched on the same window', (WidgetTester _) async { plugin.openNewWindow('sms:+19725551212?body=hello%20there'); verify(mockWindow.open('sms:+19725551212?body=hello%20there', '_top', 'noopener,noreferrer')); }); testWidgets( 'mailto urls should use _blank if webOnlyWindowName is set as _blank', (WidgetTester _) async { plugin.openNewWindow('mailto:[email protected]', webOnlyWindowName: '_blank'); verify(mockWindow.open( 'mailto:[email protected]', '_blank', 'noopener,noreferrer')); }); }); }); group('supportsMode', () { testWidgets('returns true for platformDefault', (WidgetTester _) async { expect(plugin.supportsMode(PreferredLaunchMode.platformDefault), completion(isTrue)); }); testWidgets('returns false for other modes', (WidgetTester _) async { expect(plugin.supportsMode(PreferredLaunchMode.externalApplication), completion(isFalse)); expect( plugin.supportsMode( PreferredLaunchMode.externalNonBrowserApplication), completion(isFalse)); expect(plugin.supportsMode(PreferredLaunchMode.inAppBrowserView), completion(isFalse)); expect(plugin.supportsMode(PreferredLaunchMode.inAppWebView), completion(isFalse)); }); }); testWidgets('supportsCloseForMode returns false', (WidgetTester _) async { expect(plugin.supportsCloseForMode(PreferredLaunchMode.platformDefault), completion(isFalse)); }); }); }
packages/packages/url_launcher/url_launcher_web/example/integration_test/url_launcher_web_test.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_web/example/integration_test/url_launcher_web_test.dart", "repo_id": "packages", "token_count": 3978 }
1,298
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/video_player/video_player/example/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/video_player/video_player/example/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 45 }
1,299